Remove most of the TargetMachine::getSubtarget/getSubtargetImpl
[oota-llvm.git] / lib / Target / Mips / MipsSEISelDAGToDAG.cpp
1 //===-- MipsSEISelDAGToDAG.cpp - A Dag to Dag Inst Selector for MipsSE ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Subclass of MipsDAGToDAGISel specialized for mips32/64.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MipsSEISelDAGToDAG.h"
15 #include "MCTargetDesc/MipsBaseInfo.h"
16 #include "Mips.h"
17 #include "MipsAnalyzeImmediate.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsRegisterInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAGNodes.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace llvm;
36
37 #define DEBUG_TYPE "mips-isel"
38
39 bool MipsSEDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
40   Subtarget = &static_cast<const MipsSubtarget &>(MF.getSubtarget());
41   if (Subtarget->inMips16Mode())
42     return false;
43   return MipsDAGToDAGISel::runOnMachineFunction(MF);
44 }
45
46 void MipsSEDAGToDAGISel::addDSPCtrlRegOperands(bool IsDef, MachineInstr &MI,
47                                                MachineFunction &MF) {
48   MachineInstrBuilder MIB(MF, &MI);
49   unsigned Mask = MI.getOperand(1).getImm();
50   unsigned Flag = IsDef ? RegState::ImplicitDefine : RegState::Implicit;
51
52   if (Mask & 1)
53     MIB.addReg(Mips::DSPPos, Flag);
54
55   if (Mask & 2)
56     MIB.addReg(Mips::DSPSCount, Flag);
57
58   if (Mask & 4)
59     MIB.addReg(Mips::DSPCarry, Flag);
60
61   if (Mask & 8)
62     MIB.addReg(Mips::DSPOutFlag, Flag);
63
64   if (Mask & 16)
65     MIB.addReg(Mips::DSPCCond, Flag);
66
67   if (Mask & 32)
68     MIB.addReg(Mips::DSPEFI, Flag);
69 }
70
71 unsigned MipsSEDAGToDAGISel::getMSACtrlReg(const SDValue RegIdx) const {
72   switch (cast<ConstantSDNode>(RegIdx)->getZExtValue()) {
73   default:
74     llvm_unreachable("Could not map int to register");
75   case 0: return Mips::MSAIR;
76   case 1: return Mips::MSACSR;
77   case 2: return Mips::MSAAccess;
78   case 3: return Mips::MSASave;
79   case 4: return Mips::MSAModify;
80   case 5: return Mips::MSARequest;
81   case 6: return Mips::MSAMap;
82   case 7: return Mips::MSAUnmap;
83   }
84 }
85
86 bool MipsSEDAGToDAGISel::replaceUsesWithZeroReg(MachineRegisterInfo *MRI,
87                                                 const MachineInstr& MI) {
88   unsigned DstReg = 0, ZeroReg = 0;
89
90   // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
91   if ((MI.getOpcode() == Mips::ADDiu) &&
92       (MI.getOperand(1).getReg() == Mips::ZERO) &&
93       (MI.getOperand(2).getImm() == 0)) {
94     DstReg = MI.getOperand(0).getReg();
95     ZeroReg = Mips::ZERO;
96   } else if ((MI.getOpcode() == Mips::DADDiu) &&
97              (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
98              (MI.getOperand(2).getImm() == 0)) {
99     DstReg = MI.getOperand(0).getReg();
100     ZeroReg = Mips::ZERO_64;
101   }
102
103   if (!DstReg)
104     return false;
105
106   // Replace uses with ZeroReg.
107   for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
108        E = MRI->use_end(); U != E;) {
109     MachineOperand &MO = *U;
110     unsigned OpNo = U.getOperandNo();
111     MachineInstr *MI = MO.getParent();
112     ++U;
113
114     // Do not replace if it is a phi's operand or is tied to def operand.
115     if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
116       continue;
117
118     MO.setReg(ZeroReg);
119   }
120
121   return true;
122 }
123
124 void MipsSEDAGToDAGISel::initGlobalBaseReg(MachineFunction &MF) {
125   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
126
127   if (!MipsFI->globalBaseRegSet())
128     return;
129
130   MachineBasicBlock &MBB = MF.front();
131   MachineBasicBlock::iterator I = MBB.begin();
132   MachineRegisterInfo &RegInfo = MF.getRegInfo();
133   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
134   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
135   unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
136   const TargetRegisterClass *RC;
137
138   RC = (Subtarget->isABI_N64()) ? &Mips::GPR64RegClass : &Mips::GPR32RegClass;
139
140   V0 = RegInfo.createVirtualRegister(RC);
141   V1 = RegInfo.createVirtualRegister(RC);
142
143   if (Subtarget->isABI_N64()) {
144     MF.getRegInfo().addLiveIn(Mips::T9_64);
145     MBB.addLiveIn(Mips::T9_64);
146
147     // lui $v0, %hi(%neg(%gp_rel(fname)))
148     // daddu $v1, $v0, $t9
149     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
150     const GlobalValue *FName = MF.getFunction();
151     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
152       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
153     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
154       .addReg(Mips::T9_64);
155     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
156       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
157     return;
158   }
159
160   if (MF.getTarget().getRelocationModel() == Reloc::Static) {
161     // Set global register to __gnu_local_gp.
162     //
163     // lui   $v0, %hi(__gnu_local_gp)
164     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
165     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
166       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
167     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
168       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
169     return;
170   }
171
172   MF.getRegInfo().addLiveIn(Mips::T9);
173   MBB.addLiveIn(Mips::T9);
174
175   if (Subtarget->isABI_N32()) {
176     // lui $v0, %hi(%neg(%gp_rel(fname)))
177     // addu $v1, $v0, $t9
178     // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
179     const GlobalValue *FName = MF.getFunction();
180     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
181       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
182     BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
183     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
184       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
185     return;
186   }
187
188   assert(Subtarget->isABI_O32());
189
190   // For O32 ABI, the following instruction sequence is emitted to initialize
191   // the global base register:
192   //
193   //  0. lui   $2, %hi(_gp_disp)
194   //  1. addiu $2, $2, %lo(_gp_disp)
195   //  2. addu  $globalbasereg, $2, $t9
196   //
197   // We emit only the last instruction here.
198   //
199   // GNU linker requires that the first two instructions appear at the beginning
200   // of a function and no instructions be inserted before or between them.
201   // The two instructions are emitted during lowering to MC layer in order to
202   // avoid any reordering.
203   //
204   // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
205   // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
206   // reads it.
207   MF.getRegInfo().addLiveIn(Mips::V0);
208   MBB.addLiveIn(Mips::V0);
209   BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
210     .addReg(Mips::V0).addReg(Mips::T9);
211 }
212
213 void MipsSEDAGToDAGISel::processFunctionAfterISel(MachineFunction &MF) {
214   initGlobalBaseReg(MF);
215
216   MachineRegisterInfo *MRI = &MF.getRegInfo();
217
218   for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
219        ++MFI)
220     for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I) {
221       if (I->getOpcode() == Mips::RDDSP)
222         addDSPCtrlRegOperands(false, *I, MF);
223       else if (I->getOpcode() == Mips::WRDSP)
224         addDSPCtrlRegOperands(true, *I, MF);
225       else
226         replaceUsesWithZeroReg(MRI, *I);
227     }
228 }
229
230 SDNode *MipsSEDAGToDAGISel::selectAddESubE(unsigned MOp, SDValue InFlag,
231                                            SDValue CmpLHS, SDLoc DL,
232                                            SDNode *Node) const {
233   unsigned Opc = InFlag.getOpcode(); (void)Opc;
234
235   assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
236           (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
237          "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
238
239   unsigned SLTuOp = Mips::SLTu, ADDuOp = Mips::ADDu;
240   if (Subtarget->isGP64bit()) {
241     SLTuOp = Mips::SLTu64;
242     ADDuOp = Mips::DADDu;
243   }
244
245   SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
246   SDValue LHS = Node->getOperand(0), RHS = Node->getOperand(1);
247   EVT VT = LHS.getValueType();
248
249   SDNode *Carry = CurDAG->getMachineNode(SLTuOp, DL, VT, Ops);
250
251   if (Subtarget->isGP64bit()) {
252     // On 64-bit targets, sltu produces an i64 but our backend currently says
253     // that SLTu64 produces an i32. We need to fix this in the long run but for
254     // now, just make the DAG type-correct by asserting the upper bits are zero.
255     Carry = CurDAG->getMachineNode(Mips::SUBREG_TO_REG, DL, VT,
256                                    CurDAG->getTargetConstant(0, VT),
257                                    SDValue(Carry, 0),
258                                    CurDAG->getTargetConstant(Mips::sub_32, VT));
259   }
260
261   SDNode *AddCarry = CurDAG->getMachineNode(ADDuOp, DL, VT,
262                                             SDValue(Carry, 0), RHS);
263
264   return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS,
265                               SDValue(AddCarry, 0));
266 }
267
268 /// Match frameindex
269 bool MipsSEDAGToDAGISel::selectAddrFrameIndex(SDValue Addr, SDValue &Base,
270                                               SDValue &Offset) const {
271   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
272     EVT ValTy = Addr.getValueType();
273
274     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
275     Offset = CurDAG->getTargetConstant(0, ValTy);
276     return true;
277   }
278   return false;
279 }
280
281 /// Match frameindex+offset and frameindex|offset
282 bool MipsSEDAGToDAGISel::selectAddrFrameIndexOffset(SDValue Addr, SDValue &Base,
283                                                     SDValue &Offset,
284                                                     unsigned OffsetBits) const {
285   if (CurDAG->isBaseWithConstantOffset(Addr)) {
286     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
287     if (isIntN(OffsetBits, CN->getSExtValue())) {
288       EVT ValTy = Addr.getValueType();
289
290       // If the first operand is a FI, get the TargetFI Node
291       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
292                                   (Addr.getOperand(0)))
293         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
294       else
295         Base = Addr.getOperand(0);
296
297       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
298       return true;
299     }
300   }
301   return false;
302 }
303
304 /// ComplexPattern used on MipsInstrInfo
305 /// Used on Mips Load/Store instructions
306 bool MipsSEDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
307                                           SDValue &Offset) const {
308   // if Address is FI, get the TargetFrameIndex.
309   if (selectAddrFrameIndex(Addr, Base, Offset))
310     return true;
311
312   // on PIC code Load GA
313   if (Addr.getOpcode() == MipsISD::Wrapper) {
314     Base   = Addr.getOperand(0);
315     Offset = Addr.getOperand(1);
316     return true;
317   }
318
319   if (TM.getRelocationModel() != Reloc::PIC_) {
320     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
321         Addr.getOpcode() == ISD::TargetGlobalAddress))
322       return false;
323   }
324
325   // Addresses of the form FI+const or FI|const
326   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 16))
327     return true;
328
329   // Operand is a result from an ADD.
330   if (Addr.getOpcode() == ISD::ADD) {
331     // When loading from constant pools, load the lower address part in
332     // the instruction itself. Example, instead of:
333     //  lui $2, %hi($CPI1_0)
334     //  addiu $2, $2, %lo($CPI1_0)
335     //  lwc1 $f0, 0($2)
336     // Generate:
337     //  lui $2, %hi($CPI1_0)
338     //  lwc1 $f0, %lo($CPI1_0)($2)
339     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
340         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
341       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
342       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
343           isa<JumpTableSDNode>(Opnd0)) {
344         Base = Addr.getOperand(0);
345         Offset = Opnd0;
346         return true;
347       }
348     }
349   }
350
351   return false;
352 }
353
354 /// ComplexPattern used on MipsInstrInfo
355 /// Used on Mips Load/Store instructions
356 bool MipsSEDAGToDAGISel::selectAddrRegReg(SDValue Addr, SDValue &Base,
357                                           SDValue &Offset) const {
358   // Operand is a result from an ADD.
359   if (Addr.getOpcode() == ISD::ADD) {
360     Base = Addr.getOperand(0);
361     Offset = Addr.getOperand(1);
362     return true;
363   }
364
365   return false;
366 }
367
368 bool MipsSEDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
369                                            SDValue &Offset) const {
370   Base = Addr;
371   Offset = CurDAG->getTargetConstant(0, Addr.getValueType());
372   return true;
373 }
374
375 bool MipsSEDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
376                                        SDValue &Offset) const {
377   return selectAddrRegImm(Addr, Base, Offset) ||
378     selectAddrDefault(Addr, Base, Offset);
379 }
380
381 bool MipsSEDAGToDAGISel::selectAddrRegImm10(SDValue Addr, SDValue &Base,
382                                             SDValue &Offset) const {
383   if (selectAddrFrameIndex(Addr, Base, Offset))
384     return true;
385
386   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 10))
387     return true;
388
389   return false;
390 }
391
392 /// Used on microMIPS Load/Store unaligned instructions (12-bit offset)
393 bool MipsSEDAGToDAGISel::selectAddrRegImm12(SDValue Addr, SDValue &Base,
394                                             SDValue &Offset) const {
395   if (selectAddrFrameIndex(Addr, Base, Offset))
396     return true;
397
398   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 12))
399     return true;
400
401   return false;
402 }
403
404 bool MipsSEDAGToDAGISel::selectIntAddrMM(SDValue Addr, SDValue &Base,
405                                          SDValue &Offset) const {
406   return selectAddrRegImm12(Addr, Base, Offset) ||
407     selectAddrDefault(Addr, Base, Offset);
408 }
409
410 bool MipsSEDAGToDAGISel::selectIntAddrMSA(SDValue Addr, SDValue &Base,
411                                           SDValue &Offset) const {
412   if (selectAddrRegImm10(Addr, Base, Offset))
413     return true;
414
415   if (selectAddrDefault(Addr, Base, Offset))
416     return true;
417
418   return false;
419 }
420
421 // Select constant vector splats.
422 //
423 // Returns true and sets Imm if:
424 // * MSA is enabled
425 // * N is a ISD::BUILD_VECTOR representing a constant splat
426 bool MipsSEDAGToDAGISel::selectVSplat(SDNode *N, APInt &Imm) const {
427   if (!Subtarget->hasMSA())
428     return false;
429
430   BuildVectorSDNode *Node = dyn_cast<BuildVectorSDNode>(N);
431
432   if (!Node)
433     return false;
434
435   APInt SplatValue, SplatUndef;
436   unsigned SplatBitSize;
437   bool HasAnyUndefs;
438
439   if (!Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
440                              HasAnyUndefs, 8,
441                              !Subtarget->isLittle()))
442     return false;
443
444   Imm = SplatValue;
445
446   return true;
447 }
448
449 // Select constant vector splats.
450 //
451 // In addition to the requirements of selectVSplat(), this function returns
452 // true and sets Imm if:
453 // * The splat value is the same width as the elements of the vector
454 // * The splat value fits in an integer with the specified signed-ness and
455 //   width.
456 //
457 // This function looks through ISD::BITCAST nodes.
458 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
459 //       sometimes a shuffle in big-endian mode.
460 //
461 // It's worth noting that this function is not used as part of the selection
462 // of ldi.[bhwd] since it does not permit using the wrong-typed ldi.[bhwd]
463 // instruction to achieve the desired bit pattern. ldi.[bhwd] is selected in
464 // MipsSEDAGToDAGISel::selectNode.
465 bool MipsSEDAGToDAGISel::
466 selectVSplatCommon(SDValue N, SDValue &Imm, bool Signed,
467                    unsigned ImmBitSize) const {
468   APInt ImmValue;
469   EVT EltTy = N->getValueType(0).getVectorElementType();
470
471   if (N->getOpcode() == ISD::BITCAST)
472     N = N->getOperand(0);
473
474   if (selectVSplat (N.getNode(), ImmValue) &&
475       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
476     if (( Signed && ImmValue.isSignedIntN(ImmBitSize)) ||
477         (!Signed && ImmValue.isIntN(ImmBitSize))) {
478       Imm = CurDAG->getTargetConstant(ImmValue, EltTy);
479       return true;
480     }
481   }
482
483   return false;
484 }
485
486 // Select constant vector splats.
487 bool MipsSEDAGToDAGISel::
488 selectVSplatUimm1(SDValue N, SDValue &Imm) const {
489   return selectVSplatCommon(N, Imm, false, 1);
490 }
491
492 bool MipsSEDAGToDAGISel::
493 selectVSplatUimm2(SDValue N, SDValue &Imm) const {
494   return selectVSplatCommon(N, Imm, false, 2);
495 }
496
497 bool MipsSEDAGToDAGISel::
498 selectVSplatUimm3(SDValue N, SDValue &Imm) const {
499   return selectVSplatCommon(N, Imm, false, 3);
500 }
501
502 // Select constant vector splats.
503 bool MipsSEDAGToDAGISel::
504 selectVSplatUimm4(SDValue N, SDValue &Imm) const {
505   return selectVSplatCommon(N, Imm, false, 4);
506 }
507
508 // Select constant vector splats.
509 bool MipsSEDAGToDAGISel::
510 selectVSplatUimm5(SDValue N, SDValue &Imm) const {
511   return selectVSplatCommon(N, Imm, false, 5);
512 }
513
514 // Select constant vector splats.
515 bool MipsSEDAGToDAGISel::
516 selectVSplatUimm6(SDValue N, SDValue &Imm) const {
517   return selectVSplatCommon(N, Imm, false, 6);
518 }
519
520 // Select constant vector splats.
521 bool MipsSEDAGToDAGISel::
522 selectVSplatUimm8(SDValue N, SDValue &Imm) const {
523   return selectVSplatCommon(N, Imm, false, 8);
524 }
525
526 // Select constant vector splats.
527 bool MipsSEDAGToDAGISel::
528 selectVSplatSimm5(SDValue N, SDValue &Imm) const {
529   return selectVSplatCommon(N, Imm, true, 5);
530 }
531
532 // Select constant vector splats whose value is a power of 2.
533 //
534 // In addition to the requirements of selectVSplat(), this function returns
535 // true and sets Imm if:
536 // * The splat value is the same width as the elements of the vector
537 // * The splat value is a power of two.
538 //
539 // This function looks through ISD::BITCAST nodes.
540 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
541 //       sometimes a shuffle in big-endian mode.
542 bool MipsSEDAGToDAGISel::selectVSplatUimmPow2(SDValue N, SDValue &Imm) const {
543   APInt ImmValue;
544   EVT EltTy = N->getValueType(0).getVectorElementType();
545
546   if (N->getOpcode() == ISD::BITCAST)
547     N = N->getOperand(0);
548
549   if (selectVSplat (N.getNode(), ImmValue) &&
550       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
551     int32_t Log2 = ImmValue.exactLogBase2();
552
553     if (Log2 != -1) {
554       Imm = CurDAG->getTargetConstant(Log2, EltTy);
555       return true;
556     }
557   }
558
559   return false;
560 }
561
562 // Select constant vector splats whose value only has a consecutive sequence
563 // of left-most bits set (e.g. 0b11...1100...00).
564 //
565 // In addition to the requirements of selectVSplat(), this function returns
566 // true and sets Imm if:
567 // * The splat value is the same width as the elements of the vector
568 // * The splat value is a consecutive sequence of left-most bits.
569 //
570 // This function looks through ISD::BITCAST nodes.
571 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
572 //       sometimes a shuffle in big-endian mode.
573 bool MipsSEDAGToDAGISel::selectVSplatMaskL(SDValue N, SDValue &Imm) const {
574   APInt ImmValue;
575   EVT EltTy = N->getValueType(0).getVectorElementType();
576
577   if (N->getOpcode() == ISD::BITCAST)
578     N = N->getOperand(0);
579
580   if (selectVSplat(N.getNode(), ImmValue) &&
581       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
582     // Extract the run of set bits starting with bit zero from the bitwise
583     // inverse of ImmValue, and test that the inverse of this is the same
584     // as the original value.
585     if (ImmValue == ~(~ImmValue & ~(~ImmValue + 1))) {
586
587       Imm = CurDAG->getTargetConstant(ImmValue.countPopulation(), EltTy);
588       return true;
589     }
590   }
591
592   return false;
593 }
594
595 // Select constant vector splats whose value only has a consecutive sequence
596 // of right-most bits set (e.g. 0b00...0011...11).
597 //
598 // In addition to the requirements of selectVSplat(), this function returns
599 // true and sets Imm if:
600 // * The splat value is the same width as the elements of the vector
601 // * The splat value is a consecutive sequence of right-most bits.
602 //
603 // This function looks through ISD::BITCAST nodes.
604 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
605 //       sometimes a shuffle in big-endian mode.
606 bool MipsSEDAGToDAGISel::selectVSplatMaskR(SDValue N, SDValue &Imm) const {
607   APInt ImmValue;
608   EVT EltTy = N->getValueType(0).getVectorElementType();
609
610   if (N->getOpcode() == ISD::BITCAST)
611     N = N->getOperand(0);
612
613   if (selectVSplat(N.getNode(), ImmValue) &&
614       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
615     // Extract the run of set bits starting with bit zero, and test that the
616     // result is the same as the original value
617     if (ImmValue == (ImmValue & ~(ImmValue + 1))) {
618       Imm = CurDAG->getTargetConstant(ImmValue.countPopulation(), EltTy);
619       return true;
620     }
621   }
622
623   return false;
624 }
625
626 bool MipsSEDAGToDAGISel::selectVSplatUimmInvPow2(SDValue N,
627                                                  SDValue &Imm) const {
628   APInt ImmValue;
629   EVT EltTy = N->getValueType(0).getVectorElementType();
630
631   if (N->getOpcode() == ISD::BITCAST)
632     N = N->getOperand(0);
633
634   if (selectVSplat(N.getNode(), ImmValue) &&
635       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
636     int32_t Log2 = (~ImmValue).exactLogBase2();
637
638     if (Log2 != -1) {
639       Imm = CurDAG->getTargetConstant(Log2, EltTy);
640       return true;
641     }
642   }
643
644   return false;
645 }
646
647 std::pair<bool, SDNode*> MipsSEDAGToDAGISel::selectNode(SDNode *Node) {
648   unsigned Opcode = Node->getOpcode();
649   SDLoc DL(Node);
650
651   ///
652   // Instruction Selection not handled by the auto-generated
653   // tablegen selection should be handled here.
654   ///
655   SDNode *Result;
656
657   switch(Opcode) {
658   default: break;
659
660   case ISD::SUBE: {
661     SDValue InFlag = Node->getOperand(2);
662     unsigned Opc = Subtarget->isGP64bit() ? Mips::DSUBu : Mips::SUBu;
663     Result = selectAddESubE(Opc, InFlag, InFlag.getOperand(0), DL, Node);
664     return std::make_pair(true, Result);
665   }
666
667   case ISD::ADDE: {
668     if (Subtarget->hasDSP()) // Select DSP instructions, ADDSC and ADDWC.
669       break;
670     SDValue InFlag = Node->getOperand(2);
671     unsigned Opc = Subtarget->isGP64bit() ? Mips::DADDu : Mips::ADDu;
672     Result = selectAddESubE(Opc, InFlag, InFlag.getValue(0), DL, Node);
673     return std::make_pair(true, Result);
674   }
675
676   case ISD::ConstantFP: {
677     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
678     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
679       if (Subtarget->isGP64bit()) {
680         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
681                                               Mips::ZERO_64, MVT::i64);
682         Result = CurDAG->getMachineNode(Mips::DMTC1, DL, MVT::f64, Zero);
683       } else if (Subtarget->isFP64bit()) {
684         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
685                                               Mips::ZERO, MVT::i32);
686         Result = CurDAG->getMachineNode(Mips::BuildPairF64_64, DL, MVT::f64,
687                                         Zero, Zero);
688       } else {
689         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
690                                               Mips::ZERO, MVT::i32);
691         Result = CurDAG->getMachineNode(Mips::BuildPairF64, DL, MVT::f64, Zero,
692                                         Zero);
693       }
694
695       return std::make_pair(true, Result);
696     }
697     break;
698   }
699
700   case ISD::Constant: {
701     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
702     unsigned Size = CN->getValueSizeInBits(0);
703
704     if (Size == 32)
705       break;
706
707     MipsAnalyzeImmediate AnalyzeImm;
708     int64_t Imm = CN->getSExtValue();
709
710     const MipsAnalyzeImmediate::InstSeq &Seq =
711       AnalyzeImm.Analyze(Imm, Size, false);
712
713     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
714     SDLoc DL(CN);
715     SDNode *RegOpnd;
716     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
717                                                 MVT::i64);
718
719     // The first instruction can be a LUi which is different from other
720     // instructions (ADDiu, ORI and SLL) in that it does not have a register
721     // operand.
722     if (Inst->Opc == Mips::LUi64)
723       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
724     else
725       RegOpnd =
726         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
727                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
728                                ImmOpnd);
729
730     // The remaining instructions in the sequence are handled here.
731     for (++Inst; Inst != Seq.end(); ++Inst) {
732       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
733                                           MVT::i64);
734       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
735                                        SDValue(RegOpnd, 0), ImmOpnd);
736     }
737
738     return std::make_pair(true, RegOpnd);
739   }
740
741   case ISD::INTRINSIC_W_CHAIN: {
742     switch (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
743     default:
744       break;
745
746     case Intrinsic::mips_cfcmsa: {
747       SDValue ChainIn = Node->getOperand(0);
748       SDValue RegIdx = Node->getOperand(2);
749       SDValue Reg = CurDAG->getCopyFromReg(ChainIn, DL,
750                                            getMSACtrlReg(RegIdx), MVT::i32);
751       return std::make_pair(true, Reg.getNode());
752     }
753     }
754     break;
755   }
756
757   case ISD::INTRINSIC_WO_CHAIN: {
758     switch (cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue()) {
759     default:
760       break;
761
762     case Intrinsic::mips_move_v:
763       // Like an assignment but will always produce a move.v even if
764       // unnecessary.
765       return std::make_pair(true,
766                             CurDAG->getMachineNode(Mips::MOVE_V, DL,
767                                                    Node->getValueType(0),
768                                                    Node->getOperand(1)));
769     }
770     break;
771   }
772
773   case ISD::INTRINSIC_VOID: {
774     switch (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
775     default:
776       break;
777
778     case Intrinsic::mips_ctcmsa: {
779       SDValue ChainIn = Node->getOperand(0);
780       SDValue RegIdx  = Node->getOperand(2);
781       SDValue Value   = Node->getOperand(3);
782       SDValue ChainOut = CurDAG->getCopyToReg(ChainIn, DL,
783                                               getMSACtrlReg(RegIdx), Value);
784       return std::make_pair(true, ChainOut.getNode());
785     }
786     }
787     break;
788   }
789
790   case MipsISD::ThreadPointer: {
791     EVT PtrVT = getTargetLowering()->getPointerTy();
792     unsigned RdhwrOpc, DestReg;
793
794     if (PtrVT == MVT::i32) {
795       RdhwrOpc = Mips::RDHWR;
796       DestReg = Mips::V1;
797     } else {
798       RdhwrOpc = Mips::RDHWR64;
799       DestReg = Mips::V1_64;
800     }
801
802     SDNode *Rdhwr =
803       CurDAG->getMachineNode(RdhwrOpc, SDLoc(Node),
804                              Node->getValueType(0),
805                              CurDAG->getRegister(Mips::HWR29, MVT::i32));
806     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, DestReg,
807                                          SDValue(Rdhwr, 0));
808     SDValue ResNode = CurDAG->getCopyFromReg(Chain, DL, DestReg, PtrVT);
809     ReplaceUses(SDValue(Node, 0), ResNode);
810     return std::make_pair(true, ResNode.getNode());
811   }
812
813   case ISD::BUILD_VECTOR: {
814     // Select appropriate ldi.[bhwd] instructions for constant splats of
815     // 128-bit when MSA is enabled. Fixup any register class mismatches that
816     // occur as a result.
817     //
818     // This allows the compiler to use a wider range of immediates than would
819     // otherwise be allowed. If, for example, v4i32 could only use ldi.h then
820     // it would not be possible to load { 0x01010101, 0x01010101, 0x01010101,
821     // 0x01010101 } without using a constant pool. This would be sub-optimal
822     // when // 'ldi.b wd, 1' is capable of producing that bit-pattern in the
823     // same set/ of registers. Similarly, ldi.h isn't capable of producing {
824     // 0x00000000, 0x00000001, 0x00000000, 0x00000001 } but 'ldi.d wd, 1' can.
825
826     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Node);
827     APInt SplatValue, SplatUndef;
828     unsigned SplatBitSize;
829     bool HasAnyUndefs;
830     unsigned LdiOp;
831     EVT ResVecTy = BVN->getValueType(0);
832     EVT ViaVecTy;
833
834     if (!Subtarget->hasMSA() || !BVN->getValueType(0).is128BitVector())
835       return std::make_pair(false, nullptr);
836
837     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
838                               HasAnyUndefs, 8,
839                               !Subtarget->isLittle()))
840       return std::make_pair(false, nullptr);
841
842     switch (SplatBitSize) {
843     default:
844       return std::make_pair(false, nullptr);
845     case 8:
846       LdiOp = Mips::LDI_B;
847       ViaVecTy = MVT::v16i8;
848       break;
849     case 16:
850       LdiOp = Mips::LDI_H;
851       ViaVecTy = MVT::v8i16;
852       break;
853     case 32:
854       LdiOp = Mips::LDI_W;
855       ViaVecTy = MVT::v4i32;
856       break;
857     case 64:
858       LdiOp = Mips::LDI_D;
859       ViaVecTy = MVT::v2i64;
860       break;
861     }
862
863     if (!SplatValue.isSignedIntN(10))
864       return std::make_pair(false, nullptr);
865
866     SDValue Imm = CurDAG->getTargetConstant(SplatValue,
867                                             ViaVecTy.getVectorElementType());
868
869     SDNode *Res = CurDAG->getMachineNode(LdiOp, SDLoc(Node), ViaVecTy, Imm);
870
871     if (ResVecTy != ViaVecTy) {
872       // If LdiOp is writing to a different register class to ResVecTy, then
873       // fix it up here. This COPY_TO_REGCLASS should never cause a move.v
874       // since the source and destination register sets contain the same
875       // registers.
876       const TargetLowering *TLI = getTargetLowering();
877       MVT ResVecTySimple = ResVecTy.getSimpleVT();
878       const TargetRegisterClass *RC = TLI->getRegClassFor(ResVecTySimple);
879       Res = CurDAG->getMachineNode(Mips::COPY_TO_REGCLASS, SDLoc(Node),
880                                    ResVecTy, SDValue(Res, 0),
881                                    CurDAG->getTargetConstant(RC->getID(),
882                                                              MVT::i32));
883     }
884
885     return std::make_pair(true, Res);
886   }
887
888   }
889
890   return std::make_pair(false, nullptr);
891 }
892
893 FunctionPass *llvm::createMipsSEISelDag(MipsTargetMachine &TM) {
894   return new MipsSEDAGToDAGISel(TM);
895 }