1 //===-- HexagonInstrInfo.cpp - Hexagon Instruction Information ------------===//
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 // This file contains the Hexagon implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "HexagonHazardRecognizer.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonRegisterInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/DFAPacketizer.h"
21 #include "llvm/CodeGen/LivePhysRegs.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/CodeGen/ScheduleDAG.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cctype>
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "hexagon-instrinfo"
38 
39 #define GET_INSTRINFO_CTOR_DTOR
40 #define GET_INSTRMAP_INFO
41 #include "HexagonGenInstrInfo.inc"
42 #include "HexagonGenDFAPacketizer.inc"
43 
44 cl::opt<bool> ScheduleInlineAsm("hexagon-sched-inline-asm", cl::Hidden,
45   cl::init(false), cl::desc("Do not consider inline-asm a scheduling/"
46                             "packetization boundary."));
47 
48 static cl::opt<bool> EnableBranchPrediction("hexagon-enable-branch-prediction",
49   cl::Hidden, cl::init(true), cl::desc("Enable branch prediction"));
50 
51 static cl::opt<bool> DisableNVSchedule("disable-hexagon-nv-schedule",
52   cl::Hidden, cl::ZeroOrMore, cl::init(false),
53   cl::desc("Disable schedule adjustment for new value stores."));
54 
55 static cl::opt<bool> EnableTimingClassLatency(
56   "enable-timing-class-latency", cl::Hidden, cl::init(false),
57   cl::desc("Enable timing class latency"));
58 
59 static cl::opt<bool> EnableALUForwarding(
60   "enable-alu-forwarding", cl::Hidden, cl::init(true),
61   cl::desc("Enable vec alu forwarding"));
62 
63 static cl::opt<bool> EnableACCForwarding(
64   "enable-acc-forwarding", cl::Hidden, cl::init(true),
65   cl::desc("Enable vec acc forwarding"));
66 
67 static cl::opt<bool> BranchRelaxAsmLarge("branch-relax-asm-large",
68   cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("branch relax asm"));
69 
70 static cl::opt<bool> UseDFAHazardRec("dfa-hazard-rec",
71   cl::init(true), cl::Hidden, cl::ZeroOrMore,
72   cl::desc("Use the DFA based hazard recognizer."));
73 
74 ///
75 /// Constants for Hexagon instructions.
76 ///
77 const int Hexagon_MEMV_OFFSET_MAX_128B = 896;   // #s4: -8*128...7*128
78 const int Hexagon_MEMV_OFFSET_MIN_128B = -1024; // #s4
79 const int Hexagon_MEMV_OFFSET_MAX = 448;  // #s4: -8*64...7*64
80 const int Hexagon_MEMV_OFFSET_MIN = -512; // #s4
81 const int Hexagon_MEMW_OFFSET_MAX = 4095;
82 const int Hexagon_MEMW_OFFSET_MIN = -4096;
83 const int Hexagon_MEMD_OFFSET_MAX = 8191;
84 const int Hexagon_MEMD_OFFSET_MIN = -8192;
85 const int Hexagon_MEMH_OFFSET_MAX = 2047;
86 const int Hexagon_MEMH_OFFSET_MIN = -2048;
87 const int Hexagon_MEMB_OFFSET_MAX = 1023;
88 const int Hexagon_MEMB_OFFSET_MIN = -1024;
89 const int Hexagon_ADDI_OFFSET_MAX = 32767;
90 const int Hexagon_ADDI_OFFSET_MIN = -32768;
91 const int Hexagon_MEMD_AUTOINC_MAX = 56;
92 const int Hexagon_MEMD_AUTOINC_MIN = -64;
93 const int Hexagon_MEMW_AUTOINC_MAX = 28;
94 const int Hexagon_MEMW_AUTOINC_MIN = -32;
95 const int Hexagon_MEMH_AUTOINC_MAX = 14;
96 const int Hexagon_MEMH_AUTOINC_MIN = -16;
97 const int Hexagon_MEMB_AUTOINC_MAX = 7;
98 const int Hexagon_MEMB_AUTOINC_MIN = -8;
99 const int Hexagon_MEMV_AUTOINC_MAX = 192;   // #s3
100 const int Hexagon_MEMV_AUTOINC_MIN = -256;  // #s3
101 const int Hexagon_MEMV_AUTOINC_MAX_128B = 384;  // #s3
102 const int Hexagon_MEMV_AUTOINC_MIN_128B = -512; // #s3
103 
104 // Pin the vtable to this file.
105 void HexagonInstrInfo::anchor() {}
106 
107 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
108     : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
109       RI() {}
110 
111 
112 static bool isIntRegForSubInst(unsigned Reg) {
113   return (Reg >= Hexagon::R0 && Reg <= Hexagon::R7) ||
114          (Reg >= Hexagon::R16 && Reg <= Hexagon::R23);
115 }
116 
117 
118 static bool isDblRegForSubInst(unsigned Reg, const HexagonRegisterInfo &HRI) {
119   return isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::subreg_loreg)) &&
120          isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::subreg_hireg));
121 }
122 
123 
124 /// Calculate number of instructions excluding the debug instructions.
125 static unsigned nonDbgMICount(MachineBasicBlock::const_instr_iterator MIB,
126                               MachineBasicBlock::const_instr_iterator MIE) {
127   unsigned Count = 0;
128   for (; MIB != MIE; ++MIB) {
129     if (!MIB->isDebugValue())
130       ++Count;
131   }
132   return Count;
133 }
134 
135 
136 /// Find the hardware loop instruction used to set-up the specified loop.
137 /// On Hexagon, we have two instructions used to set-up the hardware loop
138 /// (LOOP0, LOOP1) with corresponding endloop (ENDLOOP0, ENDLOOP1) instructions
139 /// to indicate the end of a loop.
140 static MachineInstr *findLoopInstr(MachineBasicBlock *BB, int EndLoopOp,
141       SmallPtrSet<MachineBasicBlock *, 8> &Visited) {
142   int LOOPi;
143   int LOOPr;
144   if (EndLoopOp == Hexagon::ENDLOOP0) {
145     LOOPi = Hexagon::J2_loop0i;
146     LOOPr = Hexagon::J2_loop0r;
147   } else { // EndLoopOp == Hexagon::EndLOOP1
148     LOOPi = Hexagon::J2_loop1i;
149     LOOPr = Hexagon::J2_loop1r;
150   }
151 
152   // The loop set-up instruction will be in a predecessor block
153   for (MachineBasicBlock::pred_iterator PB = BB->pred_begin(),
154          PE = BB->pred_end(); PB != PE; ++PB) {
155     // If this has been visited, already skip it.
156     if (!Visited.insert(*PB).second)
157       continue;
158     if (*PB == BB)
159       continue;
160     for (MachineBasicBlock::reverse_instr_iterator I = (*PB)->instr_rbegin(),
161            E = (*PB)->instr_rend(); I != E; ++I) {
162       int Opc = I->getOpcode();
163       if (Opc == LOOPi || Opc == LOOPr)
164         return &*I;
165       // We've reached a different loop, which means the loop0 has been removed.
166       if (Opc == EndLoopOp)
167         return 0;
168     }
169     // Check the predecessors for the LOOP instruction.
170     MachineInstr *loop = findLoopInstr(*PB, EndLoopOp, Visited);
171     if (loop)
172       return loop;
173   }
174   return 0;
175 }
176 
177 
178 /// Gather register def/uses from MI.
179 /// This treats possible (predicated) defs as actually happening ones
180 /// (conservatively).
181 static inline void parseOperands(const MachineInstr &MI,
182       SmallVector<unsigned, 4> &Defs, SmallVector<unsigned, 8> &Uses) {
183   Defs.clear();
184   Uses.clear();
185 
186   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
187     const MachineOperand &MO = MI.getOperand(i);
188 
189     if (!MO.isReg())
190       continue;
191 
192     unsigned Reg = MO.getReg();
193     if (!Reg)
194       continue;
195 
196     if (MO.isUse())
197       Uses.push_back(MO.getReg());
198 
199     if (MO.isDef())
200       Defs.push_back(MO.getReg());
201   }
202 }
203 
204 
205 // Position dependent, so check twice for swap.
206 static bool isDuplexPairMatch(unsigned Ga, unsigned Gb) {
207   switch (Ga) {
208   case HexagonII::HSIG_None:
209   default:
210     return false;
211   case HexagonII::HSIG_L1:
212     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_A);
213   case HexagonII::HSIG_L2:
214     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
215             Gb == HexagonII::HSIG_A);
216   case HexagonII::HSIG_S1:
217     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
218             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_A);
219   case HexagonII::HSIG_S2:
220     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
221             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_S2 ||
222             Gb == HexagonII::HSIG_A);
223   case HexagonII::HSIG_A:
224     return (Gb == HexagonII::HSIG_A);
225   case HexagonII::HSIG_Compound:
226     return (Gb == HexagonII::HSIG_Compound);
227   }
228   return false;
229 }
230 
231 
232 
233 /// isLoadFromStackSlot - If the specified machine instruction is a direct
234 /// load from a stack slot, return the virtual or physical register number of
235 /// the destination along with the FrameIndex of the loaded stack slot.  If
236 /// not, return 0.  This predicate must return 0 if the instruction has
237 /// any side effects other than loading from the stack slot.
238 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
239                                                int &FrameIndex) const {
240   switch (MI.getOpcode()) {
241   default:
242     break;
243   case Hexagon::L2_loadrb_io:
244   case Hexagon::L2_loadrub_io:
245   case Hexagon::L2_loadrh_io:
246   case Hexagon::L2_loadruh_io:
247   case Hexagon::L2_loadri_io:
248   case Hexagon::L2_loadrd_io:
249   case Hexagon::V6_vL32b_ai:
250   case Hexagon::V6_vL32b_ai_128B:
251   case Hexagon::V6_vL32Ub_ai:
252   case Hexagon::V6_vL32Ub_ai_128B:
253   case Hexagon::LDriw_pred:
254   case Hexagon::LDriw_mod:
255   case Hexagon::PS_vloadrq_ai:
256   case Hexagon::PS_vloadrw_ai:
257   case Hexagon::PS_vloadrq_ai_128B:
258   case Hexagon::PS_vloadrw_ai_128B: {
259     const MachineOperand OpFI = MI.getOperand(1);
260     if (!OpFI.isFI())
261       return 0;
262     const MachineOperand OpOff = MI.getOperand(2);
263     if (!OpOff.isImm() || OpOff.getImm() != 0)
264       return 0;
265     FrameIndex = OpFI.getIndex();
266     return MI.getOperand(0).getReg();
267   }
268 
269   case Hexagon::L2_ploadrbt_io:
270   case Hexagon::L2_ploadrbf_io:
271   case Hexagon::L2_ploadrubt_io:
272   case Hexagon::L2_ploadrubf_io:
273   case Hexagon::L2_ploadrht_io:
274   case Hexagon::L2_ploadrhf_io:
275   case Hexagon::L2_ploadruht_io:
276   case Hexagon::L2_ploadruhf_io:
277   case Hexagon::L2_ploadrit_io:
278   case Hexagon::L2_ploadrif_io:
279   case Hexagon::L2_ploadrdt_io:
280   case Hexagon::L2_ploadrdf_io: {
281     const MachineOperand OpFI = MI.getOperand(2);
282     if (!OpFI.isFI())
283       return 0;
284     const MachineOperand OpOff = MI.getOperand(3);
285     if (!OpOff.isImm() || OpOff.getImm() != 0)
286       return 0;
287     FrameIndex = OpFI.getIndex();
288     return MI.getOperand(0).getReg();
289   }
290   }
291 
292   return 0;
293 }
294 
295 
296 /// isStoreToStackSlot - If the specified machine instruction is a direct
297 /// store to a stack slot, return the virtual or physical register number of
298 /// the source reg along with the FrameIndex of the loaded stack slot.  If
299 /// not, return 0.  This predicate must return 0 if the instruction has
300 /// any side effects other than storing to the stack slot.
301 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
302                                               int &FrameIndex) const {
303   switch (MI.getOpcode()) {
304   default:
305     break;
306   case Hexagon::S2_storerb_io:
307   case Hexagon::S2_storerh_io:
308   case Hexagon::S2_storeri_io:
309   case Hexagon::S2_storerd_io:
310   case Hexagon::V6_vS32b_ai:
311   case Hexagon::V6_vS32b_ai_128B:
312   case Hexagon::V6_vS32Ub_ai:
313   case Hexagon::V6_vS32Ub_ai_128B:
314   case Hexagon::STriw_pred:
315   case Hexagon::STriw_mod:
316   case Hexagon::PS_vstorerq_ai:
317   case Hexagon::PS_vstorerw_ai:
318   case Hexagon::PS_vstorerq_ai_128B:
319   case Hexagon::PS_vstorerw_ai_128B: {
320     const MachineOperand &OpFI = MI.getOperand(0);
321     if (!OpFI.isFI())
322       return 0;
323     const MachineOperand &OpOff = MI.getOperand(1);
324     if (!OpOff.isImm() || OpOff.getImm() != 0)
325       return 0;
326     FrameIndex = OpFI.getIndex();
327     return MI.getOperand(2).getReg();
328   }
329 
330   case Hexagon::S2_pstorerbt_io:
331   case Hexagon::S2_pstorerbf_io:
332   case Hexagon::S2_pstorerht_io:
333   case Hexagon::S2_pstorerhf_io:
334   case Hexagon::S2_pstorerit_io:
335   case Hexagon::S2_pstorerif_io:
336   case Hexagon::S2_pstorerdt_io:
337   case Hexagon::S2_pstorerdf_io: {
338     const MachineOperand &OpFI = MI.getOperand(1);
339     if (!OpFI.isFI())
340       return 0;
341     const MachineOperand &OpOff = MI.getOperand(2);
342     if (!OpOff.isImm() || OpOff.getImm() != 0)
343       return 0;
344     FrameIndex = OpFI.getIndex();
345     return MI.getOperand(3).getReg();
346   }
347   }
348 
349   return 0;
350 }
351 
352 
353 /// This function can analyze one/two way branching only and should (mostly) be
354 /// called by target independent side.
355 /// First entry is always the opcode of the branching instruction, except when
356 /// the Cond vector is supposed to be empty, e.g., when AnalyzeBranch fails, a
357 /// BB with only unconditional jump. Subsequent entries depend upon the opcode,
358 /// e.g. Jump_c p will have
359 /// Cond[0] = Jump_c
360 /// Cond[1] = p
361 /// HW-loop ENDLOOP:
362 /// Cond[0] = ENDLOOP
363 /// Cond[1] = MBB
364 /// New value jump:
365 /// Cond[0] = Hexagon::CMPEQri_f_Jumpnv_t_V4 -- specific opcode
366 /// Cond[1] = R
367 /// Cond[2] = Imm
368 ///
369 bool HexagonInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
370                                      MachineBasicBlock *&TBB,
371                                      MachineBasicBlock *&FBB,
372                                      SmallVectorImpl<MachineOperand> &Cond,
373                                      bool AllowModify) const {
374   TBB = nullptr;
375   FBB = nullptr;
376   Cond.clear();
377 
378   // If the block has no terminators, it just falls into the block after it.
379   MachineBasicBlock::instr_iterator I = MBB.instr_end();
380   if (I == MBB.instr_begin())
381     return false;
382 
383   // A basic block may looks like this:
384   //
385   //  [   insn
386   //     EH_LABEL
387   //      insn
388   //      insn
389   //      insn
390   //     EH_LABEL
391   //      insn     ]
392   //
393   // It has two succs but does not have a terminator
394   // Don't know how to handle it.
395   do {
396     --I;
397     if (I->isEHLabel())
398       // Don't analyze EH branches.
399       return true;
400   } while (I != MBB.instr_begin());
401 
402   I = MBB.instr_end();
403   --I;
404 
405   while (I->isDebugValue()) {
406     if (I == MBB.instr_begin())
407       return false;
408     --I;
409   }
410 
411   bool JumpToBlock = I->getOpcode() == Hexagon::J2_jump &&
412                      I->getOperand(0).isMBB();
413   // Delete the J2_jump if it's equivalent to a fall-through.
414   if (AllowModify && JumpToBlock &&
415       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
416     DEBUG(dbgs()<< "\nErasing the jump to successor block\n";);
417     I->eraseFromParent();
418     I = MBB.instr_end();
419     if (I == MBB.instr_begin())
420       return false;
421     --I;
422   }
423   if (!isUnpredicatedTerminator(*I))
424     return false;
425 
426   // Get the last instruction in the block.
427   MachineInstr *LastInst = &*I;
428   MachineInstr *SecondLastInst = nullptr;
429   // Find one more terminator if present.
430   for (;;) {
431     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
432       if (!SecondLastInst)
433         SecondLastInst = &*I;
434       else
435         // This is a third branch.
436         return true;
437     }
438     if (I == MBB.instr_begin())
439       break;
440     --I;
441   }
442 
443   int LastOpcode = LastInst->getOpcode();
444   int SecLastOpcode = SecondLastInst ? SecondLastInst->getOpcode() : 0;
445   // If the branch target is not a basic block, it could be a tail call.
446   // (It is, if the target is a function.)
447   if (LastOpcode == Hexagon::J2_jump && !LastInst->getOperand(0).isMBB())
448     return true;
449   if (SecLastOpcode == Hexagon::J2_jump &&
450       !SecondLastInst->getOperand(0).isMBB())
451     return true;
452 
453   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
454   bool LastOpcodeHasNVJump = isNewValueJump(*LastInst);
455 
456   if (LastOpcodeHasJMP_c && !LastInst->getOperand(1).isMBB())
457     return true;
458 
459   // If there is only one terminator instruction, process it.
460   if (LastInst && !SecondLastInst) {
461     if (LastOpcode == Hexagon::J2_jump) {
462       TBB = LastInst->getOperand(0).getMBB();
463       return false;
464     }
465     if (isEndLoopN(LastOpcode)) {
466       TBB = LastInst->getOperand(0).getMBB();
467       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
468       Cond.push_back(LastInst->getOperand(0));
469       return false;
470     }
471     if (LastOpcodeHasJMP_c) {
472       TBB = LastInst->getOperand(1).getMBB();
473       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
474       Cond.push_back(LastInst->getOperand(0));
475       return false;
476     }
477     // Only supporting rr/ri versions of new-value jumps.
478     if (LastOpcodeHasNVJump && (LastInst->getNumExplicitOperands() == 3)) {
479       TBB = LastInst->getOperand(2).getMBB();
480       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
481       Cond.push_back(LastInst->getOperand(0));
482       Cond.push_back(LastInst->getOperand(1));
483       return false;
484     }
485     DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
486                  << " with one jump\n";);
487     // Otherwise, don't know what this is.
488     return true;
489   }
490 
491   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
492   bool SecLastOpcodeHasNVJump = isNewValueJump(*SecondLastInst);
493   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
494     if (!SecondLastInst->getOperand(1).isMBB())
495       return true;
496     TBB =  SecondLastInst->getOperand(1).getMBB();
497     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
498     Cond.push_back(SecondLastInst->getOperand(0));
499     FBB = LastInst->getOperand(0).getMBB();
500     return false;
501   }
502 
503   // Only supporting rr/ri versions of new-value jumps.
504   if (SecLastOpcodeHasNVJump &&
505       (SecondLastInst->getNumExplicitOperands() == 3) &&
506       (LastOpcode == Hexagon::J2_jump)) {
507     TBB = SecondLastInst->getOperand(2).getMBB();
508     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
509     Cond.push_back(SecondLastInst->getOperand(0));
510     Cond.push_back(SecondLastInst->getOperand(1));
511     FBB = LastInst->getOperand(0).getMBB();
512     return false;
513   }
514 
515   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
516   // executed, so remove it.
517   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
518     TBB = SecondLastInst->getOperand(0).getMBB();
519     I = LastInst->getIterator();
520     if (AllowModify)
521       I->eraseFromParent();
522     return false;
523   }
524 
525   // If the block ends with an ENDLOOP, and J2_jump, handle it.
526   if (isEndLoopN(SecLastOpcode) && LastOpcode == Hexagon::J2_jump) {
527     TBB = SecondLastInst->getOperand(0).getMBB();
528     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
529     Cond.push_back(SecondLastInst->getOperand(0));
530     FBB = LastInst->getOperand(0).getMBB();
531     return false;
532   }
533   DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
534                << " with two jumps";);
535   // Otherwise, can't handle this.
536   return true;
537 }
538 
539 
540 unsigned HexagonInstrInfo::removeBranch(MachineBasicBlock &MBB,
541                                         int *BytesRemoved) const {
542   assert(!BytesRemoved && "code size not handled");
543 
544   DEBUG(dbgs() << "\nRemoving branches out of BB#" << MBB.getNumber());
545   MachineBasicBlock::iterator I = MBB.end();
546   unsigned Count = 0;
547   while (I != MBB.begin()) {
548     --I;
549     if (I->isDebugValue())
550       continue;
551     // Only removing branches from end of MBB.
552     if (!I->isBranch())
553       return Count;
554     if (Count && (I->getOpcode() == Hexagon::J2_jump))
555       llvm_unreachable("Malformed basic block: unconditional branch not last");
556     MBB.erase(&MBB.back());
557     I = MBB.end();
558     ++Count;
559   }
560   return Count;
561 }
562 
563 unsigned HexagonInstrInfo::insertBranch(MachineBasicBlock &MBB,
564                                         MachineBasicBlock *TBB,
565                                         MachineBasicBlock *FBB,
566                                         ArrayRef<MachineOperand> Cond,
567                                         const DebugLoc &DL,
568                                         int *BytesAdded) const {
569   unsigned BOpc   = Hexagon::J2_jump;
570   unsigned BccOpc = Hexagon::J2_jumpt;
571   assert(validateBranchCond(Cond) && "Invalid branching condition");
572   assert(TBB && "insertBranch must not be told to insert a fallthrough");
573   assert(!BytesAdded && "code size not handled");
574 
575   // Check if reverseBranchCondition has asked to reverse this branch
576   // If we want to reverse the branch an odd number of times, we want
577   // J2_jumpf.
578   if (!Cond.empty() && Cond[0].isImm())
579     BccOpc = Cond[0].getImm();
580 
581   if (!FBB) {
582     if (Cond.empty()) {
583       // Due to a bug in TailMerging/CFG Optimization, we need to add a
584       // special case handling of a predicated jump followed by an
585       // unconditional jump. If not, Tail Merging and CFG Optimization go
586       // into an infinite loop.
587       MachineBasicBlock *NewTBB, *NewFBB;
588       SmallVector<MachineOperand, 4> Cond;
589       auto Term = MBB.getFirstTerminator();
590       if (Term != MBB.end() && isPredicated(*Term) &&
591           !analyzeBranch(MBB, NewTBB, NewFBB, Cond, false) &&
592           MachineFunction::iterator(NewTBB) == ++MBB.getIterator()) {
593         reverseBranchCondition(Cond);
594         removeBranch(MBB);
595         return insertBranch(MBB, TBB, nullptr, Cond, DL);
596       }
597       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
598     } else if (isEndLoopN(Cond[0].getImm())) {
599       int EndLoopOp = Cond[0].getImm();
600       assert(Cond[1].isMBB());
601       // Since we're adding an ENDLOOP, there better be a LOOP instruction.
602       // Check for it, and change the BB target if needed.
603       SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
604       MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, VisitedBBs);
605       assert(Loop != 0 && "Inserting an ENDLOOP without a LOOP");
606       Loop->getOperand(0).setMBB(TBB);
607       // Add the ENDLOOP after the finding the LOOP0.
608       BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
609     } else if (isNewValueJump(Cond[0].getImm())) {
610       assert((Cond.size() == 3) && "Only supporting rr/ri version of nvjump");
611       // New value jump
612       // (ins IntRegs:$src1, IntRegs:$src2, brtarget:$offset)
613       // (ins IntRegs:$src1, u5Imm:$src2, brtarget:$offset)
614       unsigned Flags1 = getUndefRegState(Cond[1].isUndef());
615       DEBUG(dbgs() << "\nInserting NVJump for BB#" << MBB.getNumber(););
616       if (Cond[2].isReg()) {
617         unsigned Flags2 = getUndefRegState(Cond[2].isUndef());
618         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
619           addReg(Cond[2].getReg(), Flags2).addMBB(TBB);
620       } else if(Cond[2].isImm()) {
621         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
622           addImm(Cond[2].getImm()).addMBB(TBB);
623       } else
624         llvm_unreachable("Invalid condition for branching");
625     } else {
626       assert((Cond.size() == 2) && "Malformed cond vector");
627       const MachineOperand &RO = Cond[1];
628       unsigned Flags = getUndefRegState(RO.isUndef());
629       BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
630     }
631     return 1;
632   }
633   assert((!Cond.empty()) &&
634          "Cond. cannot be empty when multiple branchings are required");
635   assert((!isNewValueJump(Cond[0].getImm())) &&
636          "NV-jump cannot be inserted with another branch");
637   // Special case for hardware loops.  The condition is a basic block.
638   if (isEndLoopN(Cond[0].getImm())) {
639     int EndLoopOp = Cond[0].getImm();
640     assert(Cond[1].isMBB());
641     // Since we're adding an ENDLOOP, there better be a LOOP instruction.
642     // Check for it, and change the BB target if needed.
643     SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
644     MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, VisitedBBs);
645     assert(Loop != 0 && "Inserting an ENDLOOP without a LOOP");
646     Loop->getOperand(0).setMBB(TBB);
647     // Add the ENDLOOP after the finding the LOOP0.
648     BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
649   } else {
650     const MachineOperand &RO = Cond[1];
651     unsigned Flags = getUndefRegState(RO.isUndef());
652     BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
653   }
654   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
655 
656   return 2;
657 }
658 
659 /// Analyze the loop code to find the loop induction variable and compare used
660 /// to compute the number of iterations. Currently, we analyze loop that are
661 /// controlled using hardware loops.  In this case, the induction variable
662 /// instruction is null.  For all other cases, this function returns true, which
663 /// means we're unable to analyze it.
664 bool HexagonInstrInfo::analyzeLoop(MachineLoop &L,
665                                    MachineInstr *&IndVarInst,
666                                    MachineInstr *&CmpInst) const {
667 
668   MachineBasicBlock *LoopEnd = L.getBottomBlock();
669   MachineBasicBlock::iterator I = LoopEnd->getFirstTerminator();
670   // We really "analyze" only hardware loops right now.
671   if (I != LoopEnd->end() && isEndLoopN(I->getOpcode())) {
672     IndVarInst = nullptr;
673     CmpInst = &*I;
674     return false;
675   }
676   return true;
677 }
678 
679 /// Generate code to reduce the loop iteration by one and check if the loop is
680 /// finished. Return the value/register of the new loop count. this function
681 /// assumes the nth iteration is peeled first.
682 unsigned HexagonInstrInfo::reduceLoopCount(MachineBasicBlock &MBB,
683       MachineInstr *IndVar, MachineInstr &Cmp,
684       SmallVectorImpl<MachineOperand> &Cond,
685       SmallVectorImpl<MachineInstr *> &PrevInsts,
686       unsigned Iter, unsigned MaxIter) const {
687   // We expect a hardware loop currently. This means that IndVar is set
688   // to null, and the compare is the ENDLOOP instruction.
689   assert((!IndVar) && isEndLoopN(Cmp.getOpcode())
690                    && "Expecting a hardware loop");
691   MachineFunction *MF = MBB.getParent();
692   DebugLoc DL = Cmp.getDebugLoc();
693   SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
694   MachineInstr *Loop = findLoopInstr(&MBB, Cmp.getOpcode(), VisitedBBs);
695   if (!Loop)
696     return 0;
697   // If the loop trip count is a compile-time value, then just change the
698   // value.
699   if (Loop->getOpcode() == Hexagon::J2_loop0i ||
700       Loop->getOpcode() == Hexagon::J2_loop1i) {
701     int64_t Offset = Loop->getOperand(1).getImm();
702     if (Offset <= 1)
703       Loop->eraseFromParent();
704     else
705       Loop->getOperand(1).setImm(Offset - 1);
706     return Offset - 1;
707   }
708   // The loop trip count is a run-time value. We generate code to subtract
709   // one from the trip count, and update the loop instruction.
710   assert(Loop->getOpcode() == Hexagon::J2_loop0r && "Unexpected instruction");
711   unsigned LoopCount = Loop->getOperand(1).getReg();
712   // Check if we're done with the loop.
713   unsigned LoopEnd = createVR(MF, MVT::i1);
714   MachineInstr *NewCmp = BuildMI(&MBB, DL, get(Hexagon::C2_cmpgtui), LoopEnd).
715     addReg(LoopCount).addImm(1);
716   unsigned NewLoopCount = createVR(MF, MVT::i32);
717   MachineInstr *NewAdd = BuildMI(&MBB, DL, get(Hexagon::A2_addi), NewLoopCount).
718     addReg(LoopCount).addImm(-1);
719   // Update the previously generated instructions with the new loop counter.
720   for (SmallVectorImpl<MachineInstr *>::iterator I = PrevInsts.begin(),
721          E = PrevInsts.end(); I != E; ++I)
722     (*I)->substituteRegister(LoopCount, NewLoopCount, 0, getRegisterInfo());
723   PrevInsts.clear();
724   PrevInsts.push_back(NewCmp);
725   PrevInsts.push_back(NewAdd);
726   // Insert the new loop instruction if this is the last time the loop is
727   // decremented.
728   if (Iter == MaxIter)
729     BuildMI(&MBB, DL, get(Hexagon::J2_loop0r)).
730       addMBB(Loop->getOperand(0).getMBB()).addReg(NewLoopCount);
731   // Delete the old loop instruction.
732   if (Iter == 0)
733     Loop->eraseFromParent();
734   Cond.push_back(MachineOperand::CreateImm(Hexagon::J2_jumpf));
735   Cond.push_back(NewCmp->getOperand(0));
736   return NewLoopCount;
737 }
738 
739 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
740       unsigned NumCycles, unsigned ExtraPredCycles,
741       BranchProbability Probability) const {
742   return nonDbgBBSize(&MBB) <= 3;
743 }
744 
745 
746 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
747       unsigned NumTCycles, unsigned ExtraTCycles, MachineBasicBlock &FMBB,
748       unsigned NumFCycles, unsigned ExtraFCycles, BranchProbability Probability)
749       const {
750   return nonDbgBBSize(&TMBB) <= 3 && nonDbgBBSize(&FMBB) <= 3;
751 }
752 
753 
754 bool HexagonInstrInfo::isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
755       unsigned NumInstrs, BranchProbability Probability) const {
756   return NumInstrs <= 4;
757 }
758 
759 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
760                                    MachineBasicBlock::iterator I,
761                                    const DebugLoc &DL, unsigned DestReg,
762                                    unsigned SrcReg, bool KillSrc) const {
763   auto &HRI = getRegisterInfo();
764   unsigned KillFlag = getKillRegState(KillSrc);
765 
766   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
767     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg)
768       .addReg(SrcReg, KillFlag);
769     return;
770   }
771   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
772     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg)
773       .addReg(SrcReg, KillFlag);
774     return;
775   }
776   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
777     // Map Pd = Ps to Pd = or(Ps, Ps).
778     BuildMI(MBB, I, DL, get(Hexagon::C2_or), DestReg)
779       .addReg(SrcReg).addReg(SrcReg, KillFlag);
780     return;
781   }
782   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
783       Hexagon::IntRegsRegClass.contains(SrcReg)) {
784     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
785       .addReg(SrcReg, KillFlag);
786     return;
787   }
788   if (Hexagon::IntRegsRegClass.contains(DestReg) &&
789       Hexagon::CtrRegsRegClass.contains(SrcReg)) {
790     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrcrr), DestReg)
791       .addReg(SrcReg, KillFlag);
792     return;
793   }
794   if (Hexagon::ModRegsRegClass.contains(DestReg) &&
795       Hexagon::IntRegsRegClass.contains(SrcReg)) {
796     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
797       .addReg(SrcReg, KillFlag);
798     return;
799   }
800   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
801       Hexagon::IntRegsRegClass.contains(DestReg)) {
802     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
803       .addReg(SrcReg, KillFlag);
804     return;
805   }
806   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
807       Hexagon::PredRegsRegClass.contains(DestReg)) {
808     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg)
809       .addReg(SrcReg, KillFlag);
810     return;
811   }
812   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
813       Hexagon::IntRegsRegClass.contains(DestReg)) {
814     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
815       .addReg(SrcReg, KillFlag);
816     return;
817   }
818   if (Hexagon::VectorRegsRegClass.contains(SrcReg, DestReg)) {
819     BuildMI(MBB, I, DL, get(Hexagon::V6_vassign), DestReg).
820       addReg(SrcReg, KillFlag);
821     return;
822   }
823   if (Hexagon::VecDblRegsRegClass.contains(SrcReg, DestReg)) {
824     BuildMI(MBB, I, DL, get(Hexagon::V6_vcombine), DestReg)
825       .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_hireg), KillFlag)
826       .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_loreg), KillFlag);
827     return;
828   }
829   if (Hexagon::VecPredRegsRegClass.contains(SrcReg, DestReg)) {
830     BuildMI(MBB, I, DL, get(Hexagon::V6_pred_and), DestReg)
831       .addReg(SrcReg)
832       .addReg(SrcReg, KillFlag);
833     return;
834   }
835   if (Hexagon::VecPredRegsRegClass.contains(SrcReg) &&
836       Hexagon::VectorRegsRegClass.contains(DestReg)) {
837     llvm_unreachable("Unimplemented pred to vec");
838     return;
839   }
840   if (Hexagon::VecPredRegsRegClass.contains(DestReg) &&
841       Hexagon::VectorRegsRegClass.contains(SrcReg)) {
842     llvm_unreachable("Unimplemented vec to pred");
843     return;
844   }
845   if (Hexagon::VecPredRegs128BRegClass.contains(SrcReg, DestReg)) {
846     unsigned DstHi = HRI.getSubReg(DestReg, Hexagon::subreg_hireg);
847     BuildMI(MBB, I, DL, get(Hexagon::V6_pred_and), DstHi)
848       .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_hireg), KillFlag);
849     unsigned DstLo = HRI.getSubReg(DestReg, Hexagon::subreg_loreg);
850     BuildMI(MBB, I, DL, get(Hexagon::V6_pred_and), DstLo)
851       .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_loreg), KillFlag);
852     return;
853   }
854 
855 #ifndef NDEBUG
856   // Show the invalid registers to ease debugging.
857   dbgs() << "Invalid registers for copy in BB#" << MBB.getNumber()
858          << ": " << PrintReg(DestReg, &HRI)
859          << " = " << PrintReg(SrcReg, &HRI) << '\n';
860 #endif
861   llvm_unreachable("Unimplemented");
862 }
863 
864 
865 void HexagonInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
866       MachineBasicBlock::iterator I, unsigned SrcReg, bool isKill, int FI,
867       const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const {
868   DebugLoc DL = MBB.findDebugLoc(I);
869   MachineFunction &MF = *MBB.getParent();
870   MachineFrameInfo &MFI = MF.getFrameInfo();
871   unsigned Align = MFI.getObjectAlignment(FI);
872   unsigned KillFlag = getKillRegState(isKill);
873 
874   MachineMemOperand *MMO = MF.getMachineMemOperand(
875       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
876       MFI.getObjectSize(FI), Align);
877 
878   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
879     BuildMI(MBB, I, DL, get(Hexagon::S2_storeri_io))
880       .addFrameIndex(FI).addImm(0)
881       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
882   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
883     BuildMI(MBB, I, DL, get(Hexagon::S2_storerd_io))
884       .addFrameIndex(FI).addImm(0)
885       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
886   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
887     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
888       .addFrameIndex(FI).addImm(0)
889       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
890   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
891     BuildMI(MBB, I, DL, get(Hexagon::STriw_mod))
892       .addFrameIndex(FI).addImm(0)
893       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
894   } else if (Hexagon::VecPredRegs128BRegClass.hasSubClassEq(RC)) {
895     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerq_ai_128B))
896       .addFrameIndex(FI).addImm(0)
897       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
898   } else if (Hexagon::VecPredRegsRegClass.hasSubClassEq(RC)) {
899     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerq_ai))
900       .addFrameIndex(FI).addImm(0)
901       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
902   } else if (Hexagon::VectorRegs128BRegClass.hasSubClassEq(RC)) {
903     unsigned Opc = Align < 128 ? Hexagon::V6_vS32Ub_ai_128B
904                                : Hexagon::V6_vS32b_ai_128B;
905     BuildMI(MBB, I, DL, get(Opc))
906       .addFrameIndex(FI).addImm(0)
907       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
908   } else if (Hexagon::VectorRegsRegClass.hasSubClassEq(RC)) {
909     unsigned Opc = Align < 64 ? Hexagon::V6_vS32Ub_ai
910                               : Hexagon::V6_vS32b_ai;
911     BuildMI(MBB, I, DL, get(Opc))
912       .addFrameIndex(FI).addImm(0)
913       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
914   } else if (Hexagon::VecDblRegsRegClass.hasSubClassEq(RC)) {
915     unsigned Opc = Align < 64 ? Hexagon::PS_vstorerwu_ai
916                               : Hexagon::PS_vstorerw_ai;
917     BuildMI(MBB, I, DL, get(Opc))
918       .addFrameIndex(FI).addImm(0)
919       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
920   } else if (Hexagon::VecDblRegs128BRegClass.hasSubClassEq(RC)) {
921     unsigned Opc = Align < 128 ? Hexagon::PS_vstorerwu_ai_128B
922                                : Hexagon::PS_vstorerw_ai_128B;
923     BuildMI(MBB, I, DL, get(Opc))
924       .addFrameIndex(FI).addImm(0)
925       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
926   } else {
927     llvm_unreachable("Unimplemented");
928   }
929 }
930 
931 void HexagonInstrInfo::loadRegFromStackSlot(
932     MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg,
933     int FI, const TargetRegisterClass *RC,
934     const TargetRegisterInfo *TRI) const {
935   DebugLoc DL = MBB.findDebugLoc(I);
936   MachineFunction &MF = *MBB.getParent();
937   MachineFrameInfo &MFI = MF.getFrameInfo();
938   unsigned Align = MFI.getObjectAlignment(FI);
939 
940   MachineMemOperand *MMO = MF.getMachineMemOperand(
941       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
942       MFI.getObjectSize(FI), Align);
943 
944   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
945     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
946       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
947   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
948     BuildMI(MBB, I, DL, get(Hexagon::L2_loadrd_io), DestReg)
949       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
950   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
951     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
952       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
953   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
954     BuildMI(MBB, I, DL, get(Hexagon::LDriw_mod), DestReg)
955       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
956   } else if (Hexagon::VecPredRegs128BRegClass.hasSubClassEq(RC)) {
957     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrq_ai_128B), DestReg)
958       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
959   } else if (Hexagon::VecPredRegsRegClass.hasSubClassEq(RC)) {
960     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrq_ai), DestReg)
961       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
962   } else if (Hexagon::VecDblRegs128BRegClass.hasSubClassEq(RC)) {
963     unsigned Opc = Align < 128 ? Hexagon::PS_vloadrwu_ai_128B
964                                : Hexagon::PS_vloadrw_ai_128B;
965     BuildMI(MBB, I, DL, get(Opc), DestReg)
966       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
967   } else if (Hexagon::VectorRegs128BRegClass.hasSubClassEq(RC)) {
968     unsigned Opc = Align < 128 ? Hexagon::V6_vL32Ub_ai_128B
969                                : Hexagon::V6_vL32b_ai_128B;
970     BuildMI(MBB, I, DL, get(Opc), DestReg)
971       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
972   } else if (Hexagon::VectorRegsRegClass.hasSubClassEq(RC)) {
973     unsigned Opc = Align < 64 ? Hexagon::V6_vL32Ub_ai
974                               : Hexagon::V6_vL32b_ai;
975     BuildMI(MBB, I, DL, get(Opc), DestReg)
976       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
977   } else if (Hexagon::VecDblRegsRegClass.hasSubClassEq(RC)) {
978     unsigned Opc = Align < 64 ? Hexagon::PS_vloadrwu_ai
979                               : Hexagon::PS_vloadrw_ai;
980     BuildMI(MBB, I, DL, get(Opc), DestReg)
981       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
982   } else {
983     llvm_unreachable("Can't store this register to stack slot");
984   }
985 }
986 
987 
988 static void getLiveRegsAt(LivePhysRegs &Regs, const MachineInstr &MI) {
989   const MachineBasicBlock &B = *MI.getParent();
990   Regs.addLiveOuts(B);
991   auto E = ++MachineBasicBlock::const_iterator(MI.getIterator()).getReverse();
992   for (auto I = B.rbegin(); I != E; ++I)
993     Regs.stepBackward(*I);
994 }
995 
996 /// expandPostRAPseudo - This function is called for all pseudo instructions
997 /// that remain after register allocation. Many pseudo instructions are
998 /// created to help register allocation. This is the place to convert them
999 /// into real instructions. The target can edit MI in place, or it can insert
1000 /// new instructions and erase MI. The function should return true if
1001 /// anything was changed.
1002 bool HexagonInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1003   const HexagonRegisterInfo &HRI = getRegisterInfo();
1004   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1005   MachineBasicBlock &MBB = *MI.getParent();
1006   DebugLoc DL = MI.getDebugLoc();
1007   unsigned Opc = MI.getOpcode();
1008   const unsigned VecOffset = 1;
1009 
1010   switch (Opc) {
1011     case TargetOpcode::COPY: {
1012       MachineOperand &MD = MI.getOperand(0);
1013       MachineOperand &MS = MI.getOperand(1);
1014       MachineBasicBlock::iterator MBBI = MI.getIterator();
1015       if (MD.getReg() != MS.getReg() && !MS.isUndef()) {
1016         copyPhysReg(MBB, MI, DL, MD.getReg(), MS.getReg(), MS.isKill());
1017         std::prev(MBBI)->copyImplicitOps(*MBB.getParent(), MI);
1018       }
1019       MBB.erase(MBBI);
1020       return true;
1021     }
1022     case Hexagon::PS_aligna:
1023       BuildMI(MBB, MI, DL, get(Hexagon::A2_andir), MI.getOperand(0).getReg())
1024           .addReg(HRI.getFrameRegister())
1025           .addImm(-MI.getOperand(1).getImm());
1026       MBB.erase(MI);
1027       return true;
1028     case Hexagon::V6_vassignp_128B:
1029     case Hexagon::V6_vassignp: {
1030       unsigned SrcReg = MI.getOperand(1).getReg();
1031       unsigned DstReg = MI.getOperand(0).getReg();
1032       unsigned Kill = getKillRegState(MI.getOperand(1).isKill());
1033       BuildMI(MBB, MI, DL, get(Hexagon::V6_vcombine), DstReg)
1034         .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_hireg), Kill)
1035         .addReg(HRI.getSubReg(SrcReg, Hexagon::subreg_loreg), Kill);
1036       MBB.erase(MI);
1037       return true;
1038     }
1039     case Hexagon::V6_lo_128B:
1040     case Hexagon::V6_lo: {
1041       unsigned SrcReg = MI.getOperand(1).getReg();
1042       unsigned DstReg = MI.getOperand(0).getReg();
1043       unsigned SrcSubLo = HRI.getSubReg(SrcReg, Hexagon::subreg_loreg);
1044       copyPhysReg(MBB, MI, DL, DstReg, SrcSubLo, MI.getOperand(1).isKill());
1045       MBB.erase(MI);
1046       MRI.clearKillFlags(SrcSubLo);
1047       return true;
1048     }
1049     case Hexagon::V6_hi_128B:
1050     case Hexagon::V6_hi: {
1051       unsigned SrcReg = MI.getOperand(1).getReg();
1052       unsigned DstReg = MI.getOperand(0).getReg();
1053       unsigned SrcSubHi = HRI.getSubReg(SrcReg, Hexagon::subreg_hireg);
1054       copyPhysReg(MBB, MI, DL, DstReg, SrcSubHi, MI.getOperand(1).isKill());
1055       MBB.erase(MI);
1056       MRI.clearKillFlags(SrcSubHi);
1057       return true;
1058     }
1059     case Hexagon::PS_vstorerw_ai:
1060     case Hexagon::PS_vstorerwu_ai:
1061     case Hexagon::PS_vstorerw_ai_128B:
1062     case Hexagon::PS_vstorerwu_ai_128B: {
1063       bool Is128B = (Opc == Hexagon::PS_vstorerw_ai_128B ||
1064                      Opc == Hexagon::PS_vstorerwu_ai_128B);
1065       bool Aligned = (Opc == Hexagon::PS_vstorerw_ai ||
1066                       Opc == Hexagon::PS_vstorerw_ai_128B);
1067       unsigned SrcReg = MI.getOperand(2).getReg();
1068       unsigned SrcSubHi = HRI.getSubReg(SrcReg, Hexagon::subreg_hireg);
1069       unsigned SrcSubLo = HRI.getSubReg(SrcReg, Hexagon::subreg_loreg);
1070       unsigned NewOpc;
1071       if (Aligned)
1072         NewOpc = Is128B ? Hexagon::V6_vS32b_ai_128B
1073                         : Hexagon::V6_vS32b_ai;
1074       else
1075         NewOpc = Is128B ? Hexagon::V6_vS32Ub_ai_128B
1076                         : Hexagon::V6_vS32Ub_ai;
1077 
1078       unsigned Offset = Is128B ? VecOffset << 7 : VecOffset << 6;
1079       MachineInstr *MI1New =
1080           BuildMI(MBB, MI, DL, get(NewOpc))
1081               .addOperand(MI.getOperand(0))
1082               .addImm(MI.getOperand(1).getImm())
1083               .addReg(SrcSubLo)
1084               .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1085       MI1New->getOperand(0).setIsKill(false);
1086       BuildMI(MBB, MI, DL, get(NewOpc))
1087           .addOperand(MI.getOperand(0))
1088           // The Vectors are indexed in multiples of vector size.
1089           .addImm(MI.getOperand(1).getImm() + Offset)
1090           .addReg(SrcSubHi)
1091           .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1092       MBB.erase(MI);
1093       return true;
1094     }
1095     case Hexagon::PS_vloadrw_ai:
1096     case Hexagon::PS_vloadrwu_ai:
1097     case Hexagon::PS_vloadrw_ai_128B:
1098     case Hexagon::PS_vloadrwu_ai_128B: {
1099       bool Is128B = (Opc == Hexagon::PS_vloadrw_ai_128B ||
1100                      Opc == Hexagon::PS_vloadrwu_ai_128B);
1101       bool Aligned = (Opc == Hexagon::PS_vloadrw_ai ||
1102                       Opc == Hexagon::PS_vloadrw_ai_128B);
1103       unsigned NewOpc;
1104       if (Aligned)
1105         NewOpc = Is128B ? Hexagon::V6_vL32b_ai_128B
1106                         : Hexagon::V6_vL32b_ai;
1107       else
1108         NewOpc = Is128B ? Hexagon::V6_vL32Ub_ai_128B
1109                         : Hexagon::V6_vL32Ub_ai;
1110 
1111       unsigned DstReg = MI.getOperand(0).getReg();
1112       unsigned Offset = Is128B ? VecOffset << 7 : VecOffset << 6;
1113       MachineInstr *MI1New =
1114           BuildMI(MBB, MI, DL, get(NewOpc),
1115                   HRI.getSubReg(DstReg, Hexagon::subreg_loreg))
1116               .addOperand(MI.getOperand(1))
1117               .addImm(MI.getOperand(2).getImm());
1118       MI1New->getOperand(1).setIsKill(false);
1119       BuildMI(MBB, MI, DL, get(NewOpc),
1120               HRI.getSubReg(DstReg, Hexagon::subreg_hireg))
1121           .addOperand(MI.getOperand(1))
1122           // The Vectors are indexed in multiples of vector size.
1123           .addImm(MI.getOperand(2).getImm() + Offset)
1124           .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1125       MBB.erase(MI);
1126       return true;
1127     }
1128     case Hexagon::PS_true: {
1129       unsigned Reg = MI.getOperand(0).getReg();
1130       BuildMI(MBB, MI, DL, get(Hexagon::C2_orn), Reg)
1131         .addReg(Reg, RegState::Undef)
1132         .addReg(Reg, RegState::Undef);
1133       MBB.erase(MI);
1134       return true;
1135     }
1136     case Hexagon::PS_false: {
1137       unsigned Reg = MI.getOperand(0).getReg();
1138       BuildMI(MBB, MI, DL, get(Hexagon::C2_andn), Reg)
1139         .addReg(Reg, RegState::Undef)
1140         .addReg(Reg, RegState::Undef);
1141       MBB.erase(MI);
1142       return true;
1143     }
1144     case Hexagon::PS_vmulw: {
1145       // Expand a 64-bit vector multiply into 2 32-bit scalar multiplies.
1146       unsigned DstReg = MI.getOperand(0).getReg();
1147       unsigned Src1Reg = MI.getOperand(1).getReg();
1148       unsigned Src2Reg = MI.getOperand(2).getReg();
1149       unsigned Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::subreg_hireg);
1150       unsigned Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::subreg_loreg);
1151       unsigned Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::subreg_hireg);
1152       unsigned Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::subreg_loreg);
1153       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1154               HRI.getSubReg(DstReg, Hexagon::subreg_hireg))
1155           .addReg(Src1SubHi)
1156           .addReg(Src2SubHi);
1157       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1158               HRI.getSubReg(DstReg, Hexagon::subreg_loreg))
1159           .addReg(Src1SubLo)
1160           .addReg(Src2SubLo);
1161       MBB.erase(MI);
1162       MRI.clearKillFlags(Src1SubHi);
1163       MRI.clearKillFlags(Src1SubLo);
1164       MRI.clearKillFlags(Src2SubHi);
1165       MRI.clearKillFlags(Src2SubLo);
1166       return true;
1167     }
1168     case Hexagon::PS_vmulw_acc: {
1169       // Expand 64-bit vector multiply with addition into 2 scalar multiplies.
1170       unsigned DstReg = MI.getOperand(0).getReg();
1171       unsigned Src1Reg = MI.getOperand(1).getReg();
1172       unsigned Src2Reg = MI.getOperand(2).getReg();
1173       unsigned Src3Reg = MI.getOperand(3).getReg();
1174       unsigned Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::subreg_hireg);
1175       unsigned Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::subreg_loreg);
1176       unsigned Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::subreg_hireg);
1177       unsigned Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::subreg_loreg);
1178       unsigned Src3SubHi = HRI.getSubReg(Src3Reg, Hexagon::subreg_hireg);
1179       unsigned Src3SubLo = HRI.getSubReg(Src3Reg, Hexagon::subreg_loreg);
1180       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1181               HRI.getSubReg(DstReg, Hexagon::subreg_hireg))
1182           .addReg(Src1SubHi)
1183           .addReg(Src2SubHi)
1184           .addReg(Src3SubHi);
1185       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1186               HRI.getSubReg(DstReg, Hexagon::subreg_loreg))
1187           .addReg(Src1SubLo)
1188           .addReg(Src2SubLo)
1189           .addReg(Src3SubLo);
1190       MBB.erase(MI);
1191       MRI.clearKillFlags(Src1SubHi);
1192       MRI.clearKillFlags(Src1SubLo);
1193       MRI.clearKillFlags(Src2SubHi);
1194       MRI.clearKillFlags(Src2SubLo);
1195       MRI.clearKillFlags(Src3SubHi);
1196       MRI.clearKillFlags(Src3SubLo);
1197       return true;
1198     }
1199     case Hexagon::Insert4: {
1200       unsigned DstReg = MI.getOperand(0).getReg();
1201       unsigned Src1Reg = MI.getOperand(1).getReg();
1202       unsigned Src2Reg = MI.getOperand(2).getReg();
1203       unsigned Src3Reg = MI.getOperand(3).getReg();
1204       unsigned Src4Reg = MI.getOperand(4).getReg();
1205       unsigned Src1RegIsKill = getKillRegState(MI.getOperand(1).isKill());
1206       unsigned Src2RegIsKill = getKillRegState(MI.getOperand(2).isKill());
1207       unsigned Src3RegIsKill = getKillRegState(MI.getOperand(3).isKill());
1208       unsigned Src4RegIsKill = getKillRegState(MI.getOperand(4).isKill());
1209       unsigned DstSubHi = HRI.getSubReg(DstReg, Hexagon::subreg_hireg);
1210       unsigned DstSubLo = HRI.getSubReg(DstReg, Hexagon::subreg_loreg);
1211       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::S2_insert),
1212               HRI.getSubReg(DstReg, Hexagon::subreg_loreg))
1213           .addReg(DstSubLo)
1214           .addReg(Src1Reg, Src1RegIsKill)
1215           .addImm(16)
1216           .addImm(0);
1217       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::S2_insert),
1218               HRI.getSubReg(DstReg, Hexagon::subreg_loreg))
1219           .addReg(DstSubLo)
1220           .addReg(Src2Reg, Src2RegIsKill)
1221           .addImm(16)
1222           .addImm(16);
1223       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::S2_insert),
1224               HRI.getSubReg(DstReg, Hexagon::subreg_hireg))
1225           .addReg(DstSubHi)
1226           .addReg(Src3Reg, Src3RegIsKill)
1227           .addImm(16)
1228           .addImm(0);
1229       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::S2_insert),
1230               HRI.getSubReg(DstReg, Hexagon::subreg_hireg))
1231           .addReg(DstSubHi)
1232           .addReg(Src4Reg, Src4RegIsKill)
1233           .addImm(16)
1234           .addImm(16);
1235       MBB.erase(MI);
1236       MRI.clearKillFlags(DstReg);
1237       MRI.clearKillFlags(DstSubHi);
1238       MRI.clearKillFlags(DstSubLo);
1239       return true;
1240     }
1241     case Hexagon::PS_pselect: {
1242       const MachineOperand &Op0 = MI.getOperand(0);
1243       const MachineOperand &Op1 = MI.getOperand(1);
1244       const MachineOperand &Op2 = MI.getOperand(2);
1245       const MachineOperand &Op3 = MI.getOperand(3);
1246       unsigned Rd = Op0.getReg();
1247       unsigned Pu = Op1.getReg();
1248       unsigned Rs = Op2.getReg();
1249       unsigned Rt = Op3.getReg();
1250       DebugLoc DL = MI.getDebugLoc();
1251       unsigned K1 = getKillRegState(Op1.isKill());
1252       unsigned K2 = getKillRegState(Op2.isKill());
1253       unsigned K3 = getKillRegState(Op3.isKill());
1254       if (Rd != Rs)
1255         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpt), Rd)
1256           .addReg(Pu, (Rd == Rt) ? K1 : 0)
1257           .addReg(Rs, K2);
1258       if (Rd != Rt)
1259         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpf), Rd)
1260           .addReg(Pu, K1)
1261           .addReg(Rt, K3);
1262       MBB.erase(MI);
1263       return true;
1264     }
1265     case Hexagon::PS_vselect:
1266     case Hexagon::PS_vselect_128B: {
1267       const MachineOperand &Op0 = MI.getOperand(0);
1268       const MachineOperand &Op1 = MI.getOperand(1);
1269       const MachineOperand &Op2 = MI.getOperand(2);
1270       const MachineOperand &Op3 = MI.getOperand(3);
1271       LivePhysRegs LiveAtMI(&HRI);
1272       getLiveRegsAt(LiveAtMI, MI);
1273       bool IsDestLive = !LiveAtMI.available(MRI, Op0.getReg());
1274       if (Op0.getReg() != Op2.getReg()) {
1275         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vcmov))
1276                     .addOperand(Op0)
1277                     .addOperand(Op1)
1278                     .addOperand(Op2);
1279         if (IsDestLive)
1280           T.addReg(Op0.getReg(), RegState::Implicit);
1281         IsDestLive = true;
1282       }
1283       if (Op0.getReg() != Op3.getReg()) {
1284         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vncmov))
1285                     .addOperand(Op0)
1286                     .addOperand(Op1)
1287                     .addOperand(Op3);
1288         if (IsDestLive)
1289           T.addReg(Op0.getReg(), RegState::Implicit);
1290       }
1291       MBB.erase(MI);
1292       return true;
1293     }
1294     case Hexagon::PS_wselect:
1295     case Hexagon::PS_wselect_128B: {
1296       MachineOperand &Op0 = MI.getOperand(0);
1297       MachineOperand &Op1 = MI.getOperand(1);
1298       MachineOperand &Op2 = MI.getOperand(2);
1299       MachineOperand &Op3 = MI.getOperand(3);
1300       LivePhysRegs LiveAtMI(&HRI);
1301       getLiveRegsAt(LiveAtMI, MI);
1302       bool IsDestLive = !LiveAtMI.available(MRI, Op0.getReg());
1303 
1304       if (Op0.getReg() != Op2.getReg()) {
1305         unsigned SrcLo = HRI.getSubReg(Op2.getReg(), Hexagon::subreg_loreg);
1306         unsigned SrcHi = HRI.getSubReg(Op2.getReg(), Hexagon::subreg_hireg);
1307         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vccombine))
1308                     .addOperand(Op0)
1309                     .addOperand(Op1)
1310                     .addReg(SrcHi)
1311                     .addReg(SrcLo);
1312         if (IsDestLive)
1313           T.addReg(Op0.getReg(), RegState::Implicit);
1314         IsDestLive = true;
1315       }
1316       if (Op0.getReg() != Op3.getReg()) {
1317         unsigned SrcLo = HRI.getSubReg(Op3.getReg(), Hexagon::subreg_loreg);
1318         unsigned SrcHi = HRI.getSubReg(Op3.getReg(), Hexagon::subreg_hireg);
1319         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vnccombine))
1320                     .addOperand(Op0)
1321                     .addOperand(Op1)
1322                     .addReg(SrcHi)
1323                     .addReg(SrcLo);
1324         if (IsDestLive)
1325           T.addReg(Op0.getReg(), RegState::Implicit);
1326       }
1327       MBB.erase(MI);
1328       return true;
1329     }
1330     case Hexagon::PS_tailcall_i:
1331       MI.setDesc(get(Hexagon::J2_jump));
1332       return true;
1333     case Hexagon::PS_tailcall_r:
1334     case Hexagon::PS_jmpret:
1335       MI.setDesc(get(Hexagon::J2_jumpr));
1336       return true;
1337     case Hexagon::PS_jmprett:
1338       MI.setDesc(get(Hexagon::J2_jumprt));
1339       return true;
1340     case Hexagon::PS_jmpretf:
1341       MI.setDesc(get(Hexagon::J2_jumprf));
1342       return true;
1343     case Hexagon::PS_jmprettnewpt:
1344       MI.setDesc(get(Hexagon::J2_jumprtnewpt));
1345       return true;
1346     case Hexagon::PS_jmpretfnewpt:
1347       MI.setDesc(get(Hexagon::J2_jumprfnewpt));
1348       return true;
1349     case Hexagon::PS_jmprettnew:
1350       MI.setDesc(get(Hexagon::J2_jumprtnew));
1351       return true;
1352     case Hexagon::PS_jmpretfnew:
1353       MI.setDesc(get(Hexagon::J2_jumprfnew));
1354       return true;
1355   }
1356 
1357   return false;
1358 }
1359 
1360 
1361 // We indicate that we want to reverse the branch by
1362 // inserting the reversed branching opcode.
1363 bool HexagonInstrInfo::reverseBranchCondition(
1364       SmallVectorImpl<MachineOperand> &Cond) const {
1365   if (Cond.empty())
1366     return true;
1367   assert(Cond[0].isImm() && "First entry in the cond vector not imm-val");
1368   unsigned opcode = Cond[0].getImm();
1369   //unsigned temp;
1370   assert(get(opcode).isBranch() && "Should be a branching condition.");
1371   if (isEndLoopN(opcode))
1372     return true;
1373   unsigned NewOpcode = getInvertedPredicatedOpcode(opcode);
1374   Cond[0].setImm(NewOpcode);
1375   return false;
1376 }
1377 
1378 
1379 void HexagonInstrInfo::insertNoop(MachineBasicBlock &MBB,
1380       MachineBasicBlock::iterator MI) const {
1381   DebugLoc DL;
1382   BuildMI(MBB, MI, DL, get(Hexagon::A2_nop));
1383 }
1384 
1385 
1386 bool HexagonInstrInfo::isPostIncrement(const MachineInstr &MI) const {
1387   return getAddrMode(MI) == HexagonII::PostInc;
1388 }
1389 
1390 
1391 // Returns true if an instruction is predicated irrespective of the predicate
1392 // sense. For example, all of the following will return true.
1393 // if (p0) R1 = add(R2, R3)
1394 // if (!p0) R1 = add(R2, R3)
1395 // if (p0.new) R1 = add(R2, R3)
1396 // if (!p0.new) R1 = add(R2, R3)
1397 // Note: New-value stores are not included here as in the current
1398 // implementation, we don't need to check their predicate sense.
1399 bool HexagonInstrInfo::isPredicated(const MachineInstr &MI) const {
1400   const uint64_t F = MI.getDesc().TSFlags;
1401   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
1402 }
1403 
1404 
1405 bool HexagonInstrInfo::PredicateInstruction(
1406     MachineInstr &MI, ArrayRef<MachineOperand> Cond) const {
1407   if (Cond.empty() || isNewValueJump(Cond[0].getImm()) ||
1408       isEndLoopN(Cond[0].getImm())) {
1409     DEBUG(dbgs() << "\nCannot predicate:"; MI.dump(););
1410     return false;
1411   }
1412   int Opc = MI.getOpcode();
1413   assert (isPredicable(MI) && "Expected predicable instruction");
1414   bool invertJump = predOpcodeHasNot(Cond);
1415 
1416   // We have to predicate MI "in place", i.e. after this function returns,
1417   // MI will need to be transformed into a predicated form. To avoid com-
1418   // plicated manipulations with the operands (handling tied operands,
1419   // etc.), build a new temporary instruction, then overwrite MI with it.
1420 
1421   MachineBasicBlock &B = *MI.getParent();
1422   DebugLoc DL = MI.getDebugLoc();
1423   unsigned PredOpc = getCondOpcode(Opc, invertJump);
1424   MachineInstrBuilder T = BuildMI(B, MI, DL, get(PredOpc));
1425   unsigned NOp = 0, NumOps = MI.getNumOperands();
1426   while (NOp < NumOps) {
1427     MachineOperand &Op = MI.getOperand(NOp);
1428     if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1429       break;
1430     T.addOperand(Op);
1431     NOp++;
1432   }
1433 
1434   unsigned PredReg, PredRegPos, PredRegFlags;
1435   bool GotPredReg = getPredReg(Cond, PredReg, PredRegPos, PredRegFlags);
1436   (void)GotPredReg;
1437   assert(GotPredReg);
1438   T.addReg(PredReg, PredRegFlags);
1439   while (NOp < NumOps)
1440     T.addOperand(MI.getOperand(NOp++));
1441 
1442   MI.setDesc(get(PredOpc));
1443   while (unsigned n = MI.getNumOperands())
1444     MI.RemoveOperand(n-1);
1445   for (unsigned i = 0, n = T->getNumOperands(); i < n; ++i)
1446     MI.addOperand(T->getOperand(i));
1447 
1448   MachineBasicBlock::instr_iterator TI = T->getIterator();
1449   B.erase(TI);
1450 
1451   MachineRegisterInfo &MRI = B.getParent()->getRegInfo();
1452   MRI.clearKillFlags(PredReg);
1453   return true;
1454 }
1455 
1456 
1457 bool HexagonInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1458       ArrayRef<MachineOperand> Pred2) const {
1459   // TODO: Fix this
1460   return false;
1461 }
1462 
1463 
1464 bool HexagonInstrInfo::DefinesPredicate(
1465     MachineInstr &MI, std::vector<MachineOperand> &Pred) const {
1466   auto &HRI = getRegisterInfo();
1467   for (unsigned oper = 0; oper < MI.getNumOperands(); ++oper) {
1468     MachineOperand MO = MI.getOperand(oper);
1469     if (MO.isReg() && MO.isDef()) {
1470       const TargetRegisterClass* RC = HRI.getMinimalPhysRegClass(MO.getReg());
1471       if (RC == &Hexagon::PredRegsRegClass) {
1472         Pred.push_back(MO);
1473         return true;
1474       }
1475     }
1476   }
1477   return false;
1478 }
1479 
1480 
1481 bool HexagonInstrInfo::isPredicable(MachineInstr &MI) const {
1482   return MI.getDesc().isPredicable();
1483 }
1484 
1485 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1486                                             const MachineBasicBlock *MBB,
1487                                             const MachineFunction &MF) const {
1488   // Debug info is never a scheduling boundary. It's necessary to be explicit
1489   // due to the special treatment of IT instructions below, otherwise a
1490   // dbg_value followed by an IT will result in the IT instruction being
1491   // considered a scheduling hazard, which is wrong. It should be the actual
1492   // instruction preceding the dbg_value instruction(s), just like it is
1493   // when debug info is not present.
1494   if (MI.isDebugValue())
1495     return false;
1496 
1497   // Throwing call is a boundary.
1498   if (MI.isCall()) {
1499     // Don't mess around with no return calls.
1500     if (doesNotReturn(MI))
1501       return true;
1502     // If any of the block's successors is a landing pad, this could be a
1503     // throwing call.
1504     for (auto I : MBB->successors())
1505       if (I->isEHPad())
1506         return true;
1507   }
1508 
1509   // Terminators and labels can't be scheduled around.
1510   if (MI.getDesc().isTerminator() || MI.isPosition())
1511     return true;
1512 
1513   if (MI.isInlineAsm() && !ScheduleInlineAsm)
1514     return true;
1515 
1516   return false;
1517 }
1518 
1519 
1520 /// Measure the specified inline asm to determine an approximation of its
1521 /// length.
1522 /// Comments (which run till the next SeparatorString or newline) do not
1523 /// count as an instruction.
1524 /// Any other non-whitespace text is considered an instruction, with
1525 /// multiple instructions separated by SeparatorString or newlines.
1526 /// Variable-length instructions are not handled here; this function
1527 /// may be overloaded in the target code to do that.
1528 /// Hexagon counts the number of ##'s and adjust for that many
1529 /// constant exenders.
1530 unsigned HexagonInstrInfo::getInlineAsmLength(const char *Str,
1531       const MCAsmInfo &MAI) const {
1532   StringRef AStr(Str);
1533   // Count the number of instructions in the asm.
1534   bool atInsnStart = true;
1535   unsigned Length = 0;
1536   for (; *Str; ++Str) {
1537     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
1538                                 strlen(MAI.getSeparatorString())) == 0)
1539       atInsnStart = true;
1540     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
1541       Length += MAI.getMaxInstLength();
1542       atInsnStart = false;
1543     }
1544     if (atInsnStart && strncmp(Str, MAI.getCommentString().data(),
1545                                MAI.getCommentString().size()) == 0)
1546       atInsnStart = false;
1547   }
1548 
1549   // Add to size number of constant extenders seen * 4.
1550   StringRef Occ("##");
1551   Length += AStr.count(Occ)*4;
1552   return Length;
1553 }
1554 
1555 
1556 ScheduleHazardRecognizer*
1557 HexagonInstrInfo::CreateTargetPostRAHazardRecognizer(
1558       const InstrItineraryData *II, const ScheduleDAG *DAG) const {
1559   if (UseDFAHazardRec) {
1560     auto &HST = DAG->MF.getSubtarget<HexagonSubtarget>();
1561     return new HexagonHazardRecognizer(II, this, HST);
1562   }
1563   return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
1564 }
1565 
1566 
1567 /// \brief For a comparison instruction, return the source registers in
1568 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
1569 /// compares against in CmpValue. Return true if the comparison instruction
1570 /// can be analyzed.
1571 bool HexagonInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1572                                       unsigned &SrcReg2, int &Mask,
1573                                       int &Value) const {
1574   unsigned Opc = MI.getOpcode();
1575 
1576   // Set mask and the first source register.
1577   switch (Opc) {
1578     case Hexagon::C2_cmpeq:
1579     case Hexagon::C2_cmpeqp:
1580     case Hexagon::C2_cmpgt:
1581     case Hexagon::C2_cmpgtp:
1582     case Hexagon::C2_cmpgtu:
1583     case Hexagon::C2_cmpgtup:
1584     case Hexagon::C4_cmpneq:
1585     case Hexagon::C4_cmplte:
1586     case Hexagon::C4_cmplteu:
1587     case Hexagon::C2_cmpeqi:
1588     case Hexagon::C2_cmpgti:
1589     case Hexagon::C2_cmpgtui:
1590     case Hexagon::C4_cmpneqi:
1591     case Hexagon::C4_cmplteui:
1592     case Hexagon::C4_cmpltei:
1593       SrcReg = MI.getOperand(1).getReg();
1594       Mask = ~0;
1595       break;
1596     case Hexagon::A4_cmpbeq:
1597     case Hexagon::A4_cmpbgt:
1598     case Hexagon::A4_cmpbgtu:
1599     case Hexagon::A4_cmpbeqi:
1600     case Hexagon::A4_cmpbgti:
1601     case Hexagon::A4_cmpbgtui:
1602       SrcReg = MI.getOperand(1).getReg();
1603       Mask = 0xFF;
1604       break;
1605     case Hexagon::A4_cmpheq:
1606     case Hexagon::A4_cmphgt:
1607     case Hexagon::A4_cmphgtu:
1608     case Hexagon::A4_cmpheqi:
1609     case Hexagon::A4_cmphgti:
1610     case Hexagon::A4_cmphgtui:
1611       SrcReg = MI.getOperand(1).getReg();
1612       Mask = 0xFFFF;
1613       break;
1614   }
1615 
1616   // Set the value/second source register.
1617   switch (Opc) {
1618     case Hexagon::C2_cmpeq:
1619     case Hexagon::C2_cmpeqp:
1620     case Hexagon::C2_cmpgt:
1621     case Hexagon::C2_cmpgtp:
1622     case Hexagon::C2_cmpgtu:
1623     case Hexagon::C2_cmpgtup:
1624     case Hexagon::A4_cmpbeq:
1625     case Hexagon::A4_cmpbgt:
1626     case Hexagon::A4_cmpbgtu:
1627     case Hexagon::A4_cmpheq:
1628     case Hexagon::A4_cmphgt:
1629     case Hexagon::A4_cmphgtu:
1630     case Hexagon::C4_cmpneq:
1631     case Hexagon::C4_cmplte:
1632     case Hexagon::C4_cmplteu:
1633       SrcReg2 = MI.getOperand(2).getReg();
1634       return true;
1635 
1636     case Hexagon::C2_cmpeqi:
1637     case Hexagon::C2_cmpgtui:
1638     case Hexagon::C2_cmpgti:
1639     case Hexagon::C4_cmpneqi:
1640     case Hexagon::C4_cmplteui:
1641     case Hexagon::C4_cmpltei:
1642     case Hexagon::A4_cmpbeqi:
1643     case Hexagon::A4_cmpbgti:
1644     case Hexagon::A4_cmpbgtui:
1645     case Hexagon::A4_cmpheqi:
1646     case Hexagon::A4_cmphgti:
1647     case Hexagon::A4_cmphgtui:
1648       SrcReg2 = 0;
1649       Value = MI.getOperand(2).getImm();
1650       return true;
1651   }
1652 
1653   return false;
1654 }
1655 
1656 unsigned HexagonInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1657                                            const MachineInstr &MI,
1658                                            unsigned *PredCost) const {
1659   return getInstrTimingClassLatency(ItinData, MI);
1660 }
1661 
1662 
1663 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1664     const TargetSubtargetInfo &STI) const {
1665   const InstrItineraryData *II = STI.getInstrItineraryData();
1666   return static_cast<const HexagonSubtarget&>(STI).createDFAPacketizer(II);
1667 }
1668 
1669 
1670 // Inspired by this pair:
1671 //  %R13<def> = L2_loadri_io %R29, 136; mem:LD4[FixedStack0]
1672 //  S2_storeri_io %R29, 132, %R1<kill>; flags:  mem:ST4[FixedStack1]
1673 // Currently AA considers the addresses in these instructions to be aliasing.
1674 bool HexagonInstrInfo::areMemAccessesTriviallyDisjoint(
1675     MachineInstr &MIa, MachineInstr &MIb, AliasAnalysis *AA) const {
1676   int OffsetA = 0, OffsetB = 0;
1677   unsigned SizeA = 0, SizeB = 0;
1678 
1679   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
1680       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1681     return false;
1682 
1683   // Instructions that are pure loads, not loads and stores like memops are not
1684   // dependent.
1685   if (MIa.mayLoad() && !isMemOp(MIa) && MIb.mayLoad() && !isMemOp(MIb))
1686     return true;
1687 
1688   // Get base, offset, and access size in MIa.
1689   unsigned BaseRegA = getBaseAndOffset(MIa, OffsetA, SizeA);
1690   if (!BaseRegA || !SizeA)
1691     return false;
1692 
1693   // Get base, offset, and access size in MIb.
1694   unsigned BaseRegB = getBaseAndOffset(MIb, OffsetB, SizeB);
1695   if (!BaseRegB || !SizeB)
1696     return false;
1697 
1698   if (BaseRegA != BaseRegB)
1699     return false;
1700 
1701   // This is a mem access with the same base register and known offsets from it.
1702   // Reason about it.
1703   if (OffsetA > OffsetB) {
1704     uint64_t offDiff = (uint64_t)((int64_t)OffsetA - (int64_t)OffsetB);
1705     return (SizeB <= offDiff);
1706   } else if (OffsetA < OffsetB) {
1707     uint64_t offDiff = (uint64_t)((int64_t)OffsetB - (int64_t)OffsetA);
1708     return (SizeA <= offDiff);
1709   }
1710 
1711   return false;
1712 }
1713 
1714 
1715 /// If the instruction is an increment of a constant value, return the amount.
1716 bool HexagonInstrInfo::getIncrementValue(const MachineInstr &MI,
1717       int &Value) const {
1718   if (isPostIncrement(MI)) {
1719     unsigned AccessSize;
1720     return getBaseAndOffset(MI, Value, AccessSize);
1721   }
1722   if (MI.getOpcode() == Hexagon::A2_addi) {
1723     Value = MI.getOperand(2).getImm();
1724     return true;
1725   }
1726 
1727   return false;
1728 }
1729 
1730 
1731 unsigned HexagonInstrInfo::createVR(MachineFunction *MF, MVT VT) const {
1732   MachineRegisterInfo &MRI = MF->getRegInfo();
1733   const TargetRegisterClass *TRC;
1734   if (VT == MVT::i1) {
1735     TRC = &Hexagon::PredRegsRegClass;
1736   } else if (VT == MVT::i32 || VT == MVT::f32) {
1737     TRC = &Hexagon::IntRegsRegClass;
1738   } else if (VT == MVT::i64 || VT == MVT::f64) {
1739     TRC = &Hexagon::DoubleRegsRegClass;
1740   } else {
1741     llvm_unreachable("Cannot handle this register class");
1742   }
1743 
1744   unsigned NewReg = MRI.createVirtualRegister(TRC);
1745   return NewReg;
1746 }
1747 
1748 
1749 bool HexagonInstrInfo::isAbsoluteSet(const MachineInstr &MI) const {
1750   return (getAddrMode(MI) == HexagonII::AbsoluteSet);
1751 }
1752 
1753 
1754 bool HexagonInstrInfo::isAccumulator(const MachineInstr &MI) const {
1755   const uint64_t F = MI.getDesc().TSFlags;
1756   return((F >> HexagonII::AccumulatorPos) & HexagonII::AccumulatorMask);
1757 }
1758 
1759 
1760 bool HexagonInstrInfo::isComplex(const MachineInstr &MI) const {
1761   const MachineFunction *MF = MI.getParent()->getParent();
1762   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1763   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
1764 
1765   if (!(isTC1(MI))
1766       && !(QII->isTC2Early(MI))
1767       && !(MI.getDesc().mayLoad())
1768       && !(MI.getDesc().mayStore())
1769       && (MI.getDesc().getOpcode() != Hexagon::S2_allocframe)
1770       && (MI.getDesc().getOpcode() != Hexagon::L2_deallocframe)
1771       && !(QII->isMemOp(MI))
1772       && !(MI.isBranch())
1773       && !(MI.isReturn())
1774       && !MI.isCall())
1775     return true;
1776 
1777   return false;
1778 }
1779 
1780 
1781 // Return true if the instruction is a compund branch instruction.
1782 bool HexagonInstrInfo::isCompoundBranchInstr(const MachineInstr &MI) const {
1783   return (getType(MI) == HexagonII::TypeCOMPOUND && MI.isBranch());
1784 }
1785 
1786 
1787 bool HexagonInstrInfo::isCondInst(const MachineInstr &MI) const {
1788   return (MI.isBranch() && isPredicated(MI)) ||
1789          isConditionalTransfer(MI) ||
1790          isConditionalALU32(MI)    ||
1791          isConditionalLoad(MI)     ||
1792          // Predicated stores which don't have a .new on any operands.
1793          (MI.mayStore() && isPredicated(MI) && !isNewValueStore(MI) &&
1794           !isPredicatedNew(MI));
1795 }
1796 
1797 
1798 bool HexagonInstrInfo::isConditionalALU32(const MachineInstr &MI) const {
1799   switch (MI.getOpcode()) {
1800     case Hexagon::A2_paddf:
1801     case Hexagon::A2_paddfnew:
1802     case Hexagon::A2_paddif:
1803     case Hexagon::A2_paddifnew:
1804     case Hexagon::A2_paddit:
1805     case Hexagon::A2_padditnew:
1806     case Hexagon::A2_paddt:
1807     case Hexagon::A2_paddtnew:
1808     case Hexagon::A2_pandf:
1809     case Hexagon::A2_pandfnew:
1810     case Hexagon::A2_pandt:
1811     case Hexagon::A2_pandtnew:
1812     case Hexagon::A2_porf:
1813     case Hexagon::A2_porfnew:
1814     case Hexagon::A2_port:
1815     case Hexagon::A2_portnew:
1816     case Hexagon::A2_psubf:
1817     case Hexagon::A2_psubfnew:
1818     case Hexagon::A2_psubt:
1819     case Hexagon::A2_psubtnew:
1820     case Hexagon::A2_pxorf:
1821     case Hexagon::A2_pxorfnew:
1822     case Hexagon::A2_pxort:
1823     case Hexagon::A2_pxortnew:
1824     case Hexagon::A4_paslhf:
1825     case Hexagon::A4_paslhfnew:
1826     case Hexagon::A4_paslht:
1827     case Hexagon::A4_paslhtnew:
1828     case Hexagon::A4_pasrhf:
1829     case Hexagon::A4_pasrhfnew:
1830     case Hexagon::A4_pasrht:
1831     case Hexagon::A4_pasrhtnew:
1832     case Hexagon::A4_psxtbf:
1833     case Hexagon::A4_psxtbfnew:
1834     case Hexagon::A4_psxtbt:
1835     case Hexagon::A4_psxtbtnew:
1836     case Hexagon::A4_psxthf:
1837     case Hexagon::A4_psxthfnew:
1838     case Hexagon::A4_psxtht:
1839     case Hexagon::A4_psxthtnew:
1840     case Hexagon::A4_pzxtbf:
1841     case Hexagon::A4_pzxtbfnew:
1842     case Hexagon::A4_pzxtbt:
1843     case Hexagon::A4_pzxtbtnew:
1844     case Hexagon::A4_pzxthf:
1845     case Hexagon::A4_pzxthfnew:
1846     case Hexagon::A4_pzxtht:
1847     case Hexagon::A4_pzxthtnew:
1848     case Hexagon::C2_ccombinewf:
1849     case Hexagon::C2_ccombinewt:
1850       return true;
1851   }
1852   return false;
1853 }
1854 
1855 
1856 // FIXME - Function name and it's functionality don't match.
1857 // It should be renamed to hasPredNewOpcode()
1858 bool HexagonInstrInfo::isConditionalLoad(const MachineInstr &MI) const {
1859   if (!MI.getDesc().mayLoad() || !isPredicated(MI))
1860     return false;
1861 
1862   int PNewOpcode = Hexagon::getPredNewOpcode(MI.getOpcode());
1863   // Instruction with valid predicated-new opcode can be promoted to .new.
1864   return PNewOpcode >= 0;
1865 }
1866 
1867 
1868 // Returns true if an instruction is a conditional store.
1869 //
1870 // Note: It doesn't include conditional new-value stores as they can't be
1871 // converted to .new predicate.
1872 bool HexagonInstrInfo::isConditionalStore(const MachineInstr &MI) const {
1873   switch (MI.getOpcode()) {
1874     default: return false;
1875     case Hexagon::S4_storeirbt_io:
1876     case Hexagon::S4_storeirbf_io:
1877     case Hexagon::S4_pstorerbt_rr:
1878     case Hexagon::S4_pstorerbf_rr:
1879     case Hexagon::S2_pstorerbt_io:
1880     case Hexagon::S2_pstorerbf_io:
1881     case Hexagon::S2_pstorerbt_pi:
1882     case Hexagon::S2_pstorerbf_pi:
1883     case Hexagon::S2_pstorerdt_io:
1884     case Hexagon::S2_pstorerdf_io:
1885     case Hexagon::S4_pstorerdt_rr:
1886     case Hexagon::S4_pstorerdf_rr:
1887     case Hexagon::S2_pstorerdt_pi:
1888     case Hexagon::S2_pstorerdf_pi:
1889     case Hexagon::S2_pstorerht_io:
1890     case Hexagon::S2_pstorerhf_io:
1891     case Hexagon::S4_storeirht_io:
1892     case Hexagon::S4_storeirhf_io:
1893     case Hexagon::S4_pstorerht_rr:
1894     case Hexagon::S4_pstorerhf_rr:
1895     case Hexagon::S2_pstorerht_pi:
1896     case Hexagon::S2_pstorerhf_pi:
1897     case Hexagon::S2_pstorerit_io:
1898     case Hexagon::S2_pstorerif_io:
1899     case Hexagon::S4_storeirit_io:
1900     case Hexagon::S4_storeirif_io:
1901     case Hexagon::S4_pstorerit_rr:
1902     case Hexagon::S4_pstorerif_rr:
1903     case Hexagon::S2_pstorerit_pi:
1904     case Hexagon::S2_pstorerif_pi:
1905 
1906     // V4 global address store before promoting to dot new.
1907     case Hexagon::S4_pstorerdt_abs:
1908     case Hexagon::S4_pstorerdf_abs:
1909     case Hexagon::S4_pstorerbt_abs:
1910     case Hexagon::S4_pstorerbf_abs:
1911     case Hexagon::S4_pstorerht_abs:
1912     case Hexagon::S4_pstorerhf_abs:
1913     case Hexagon::S4_pstorerit_abs:
1914     case Hexagon::S4_pstorerif_abs:
1915       return true;
1916 
1917     // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
1918     // from the "Conditional Store" list. Because a predicated new value store
1919     // would NOT be promoted to a double dot new store.
1920     // This function returns yes for those stores that are predicated but not
1921     // yet promoted to predicate dot new instructions.
1922   }
1923 }
1924 
1925 
1926 bool HexagonInstrInfo::isConditionalTransfer(const MachineInstr &MI) const {
1927   switch (MI.getOpcode()) {
1928     case Hexagon::A2_tfrt:
1929     case Hexagon::A2_tfrf:
1930     case Hexagon::C2_cmoveit:
1931     case Hexagon::C2_cmoveif:
1932     case Hexagon::A2_tfrtnew:
1933     case Hexagon::A2_tfrfnew:
1934     case Hexagon::C2_cmovenewit:
1935     case Hexagon::C2_cmovenewif:
1936     case Hexagon::A2_tfrpt:
1937     case Hexagon::A2_tfrpf:
1938       return true;
1939 
1940     default:
1941       return false;
1942   }
1943   return false;
1944 }
1945 
1946 
1947 // TODO: In order to have isExtendable for fpimm/f32Ext, we need to handle
1948 // isFPImm and later getFPImm as well.
1949 bool HexagonInstrInfo::isConstExtended(const MachineInstr &MI) const {
1950   const uint64_t F = MI.getDesc().TSFlags;
1951   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
1952   if (isExtended) // Instruction must be extended.
1953     return true;
1954 
1955   unsigned isExtendable =
1956     (F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
1957   if (!isExtendable)
1958     return false;
1959 
1960   if (MI.isCall())
1961     return false;
1962 
1963   short ExtOpNum = getCExtOpNum(MI);
1964   const MachineOperand &MO = MI.getOperand(ExtOpNum);
1965   // Use MO operand flags to determine if MO
1966   // has the HMOTF_ConstExtended flag set.
1967   if (MO.getTargetFlags() && HexagonII::HMOTF_ConstExtended)
1968     return true;
1969   // If this is a Machine BB address we are talking about, and it is
1970   // not marked as extended, say so.
1971   if (MO.isMBB())
1972     return false;
1973 
1974   // We could be using an instruction with an extendable immediate and shoehorn
1975   // a global address into it. If it is a global address it will be constant
1976   // extended. We do this for COMBINE.
1977   // We currently only handle isGlobal() because it is the only kind of
1978   // object we are going to end up with here for now.
1979   // In the future we probably should add isSymbol(), etc.
1980   if (MO.isGlobal() || MO.isSymbol() || MO.isBlockAddress() ||
1981       MO.isJTI() || MO.isCPI() || MO.isFPImm())
1982     return true;
1983 
1984   // If the extendable operand is not 'Immediate' type, the instruction should
1985   // have 'isExtended' flag set.
1986   assert(MO.isImm() && "Extendable operand must be Immediate type");
1987 
1988   int MinValue = getMinValue(MI);
1989   int MaxValue = getMaxValue(MI);
1990   int ImmValue = MO.getImm();
1991 
1992   return (ImmValue < MinValue || ImmValue > MaxValue);
1993 }
1994 
1995 
1996 bool HexagonInstrInfo::isDeallocRet(const MachineInstr &MI) const {
1997   switch (MI.getOpcode()) {
1998   case Hexagon::L4_return :
1999   case Hexagon::L4_return_t :
2000   case Hexagon::L4_return_f :
2001   case Hexagon::L4_return_tnew_pnt :
2002   case Hexagon::L4_return_fnew_pnt :
2003   case Hexagon::L4_return_tnew_pt :
2004   case Hexagon::L4_return_fnew_pt :
2005    return true;
2006   }
2007   return false;
2008 }
2009 
2010 
2011 // Return true when ConsMI uses a register defined by ProdMI.
2012 bool HexagonInstrInfo::isDependent(const MachineInstr &ProdMI,
2013       const MachineInstr &ConsMI) const {
2014   if (!ProdMI.getDesc().getNumDefs())
2015     return false;
2016 
2017   auto &HRI = getRegisterInfo();
2018 
2019   SmallVector<unsigned, 4> DefsA;
2020   SmallVector<unsigned, 4> DefsB;
2021   SmallVector<unsigned, 8> UsesA;
2022   SmallVector<unsigned, 8> UsesB;
2023 
2024   parseOperands(ProdMI, DefsA, UsesA);
2025   parseOperands(ConsMI, DefsB, UsesB);
2026 
2027   for (auto &RegA : DefsA)
2028     for (auto &RegB : UsesB) {
2029       // True data dependency.
2030       if (RegA == RegB)
2031         return true;
2032 
2033       if (Hexagon::DoubleRegsRegClass.contains(RegA))
2034         for (MCSubRegIterator SubRegs(RegA, &HRI); SubRegs.isValid(); ++SubRegs)
2035           if (RegB == *SubRegs)
2036             return true;
2037 
2038       if (Hexagon::DoubleRegsRegClass.contains(RegB))
2039         for (MCSubRegIterator SubRegs(RegB, &HRI); SubRegs.isValid(); ++SubRegs)
2040           if (RegA == *SubRegs)
2041             return true;
2042     }
2043 
2044   return false;
2045 }
2046 
2047 
2048 // Returns true if the instruction is alread a .cur.
2049 bool HexagonInstrInfo::isDotCurInst(const MachineInstr &MI) const {
2050   switch (MI.getOpcode()) {
2051   case Hexagon::V6_vL32b_cur_pi:
2052   case Hexagon::V6_vL32b_cur_ai:
2053   case Hexagon::V6_vL32b_cur_pi_128B:
2054   case Hexagon::V6_vL32b_cur_ai_128B:
2055     return true;
2056   }
2057   return false;
2058 }
2059 
2060 
2061 // Returns true, if any one of the operands is a dot new
2062 // insn, whether it is predicated dot new or register dot new.
2063 bool HexagonInstrInfo::isDotNewInst(const MachineInstr &MI) const {
2064   if (isNewValueInst(MI) || (isPredicated(MI) && isPredicatedNew(MI)))
2065     return true;
2066 
2067   return false;
2068 }
2069 
2070 
2071 /// Symmetrical. See if these two instructions are fit for duplex pair.
2072 bool HexagonInstrInfo::isDuplexPair(const MachineInstr &MIa,
2073       const MachineInstr &MIb) const {
2074   HexagonII::SubInstructionGroup MIaG = getDuplexCandidateGroup(MIa);
2075   HexagonII::SubInstructionGroup MIbG = getDuplexCandidateGroup(MIb);
2076   return (isDuplexPairMatch(MIaG, MIbG) || isDuplexPairMatch(MIbG, MIaG));
2077 }
2078 
2079 
2080 bool HexagonInstrInfo::isEarlySourceInstr(const MachineInstr &MI) const {
2081   if (MI.mayLoad() || MI.mayStore() || MI.isCompare())
2082     return true;
2083 
2084   // Multiply
2085   unsigned SchedClass = MI.getDesc().getSchedClass();
2086   if (SchedClass == Hexagon::Sched::M_tc_3or4x_SLOT23)
2087     return true;
2088   return false;
2089 }
2090 
2091 
2092 bool HexagonInstrInfo::isEndLoopN(unsigned Opcode) const {
2093   return (Opcode == Hexagon::ENDLOOP0 ||
2094           Opcode == Hexagon::ENDLOOP1);
2095 }
2096 
2097 
2098 bool HexagonInstrInfo::isExpr(unsigned OpType) const {
2099   switch(OpType) {
2100   case MachineOperand::MO_MachineBasicBlock:
2101   case MachineOperand::MO_GlobalAddress:
2102   case MachineOperand::MO_ExternalSymbol:
2103   case MachineOperand::MO_JumpTableIndex:
2104   case MachineOperand::MO_ConstantPoolIndex:
2105   case MachineOperand::MO_BlockAddress:
2106     return true;
2107   default:
2108     return false;
2109   }
2110 }
2111 
2112 
2113 bool HexagonInstrInfo::isExtendable(const MachineInstr &MI) const {
2114   const MCInstrDesc &MID = MI.getDesc();
2115   const uint64_t F = MID.TSFlags;
2116   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
2117     return true;
2118 
2119   // TODO: This is largely obsolete now. Will need to be removed
2120   // in consecutive patches.
2121   switch (MI.getOpcode()) {
2122     // PS_fi and PS_fia remain special cases.
2123     case Hexagon::PS_fi:
2124     case Hexagon::PS_fia:
2125       return true;
2126     default:
2127       return false;
2128   }
2129   return  false;
2130 }
2131 
2132 
2133 // This returns true in two cases:
2134 // - The OP code itself indicates that this is an extended instruction.
2135 // - One of MOs has been marked with HMOTF_ConstExtended flag.
2136 bool HexagonInstrInfo::isExtended(const MachineInstr &MI) const {
2137   // First check if this is permanently extended op code.
2138   const uint64_t F = MI.getDesc().TSFlags;
2139   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
2140     return true;
2141   // Use MO operand flags to determine if one of MI's operands
2142   // has HMOTF_ConstExtended flag set.
2143   for (MachineInstr::const_mop_iterator I = MI.operands_begin(),
2144        E = MI.operands_end(); I != E; ++I) {
2145     if (I->getTargetFlags() && HexagonII::HMOTF_ConstExtended)
2146       return true;
2147   }
2148   return  false;
2149 }
2150 
2151 
2152 bool HexagonInstrInfo::isFloat(const MachineInstr &MI) const {
2153   unsigned Opcode = MI.getOpcode();
2154   const uint64_t F = get(Opcode).TSFlags;
2155   return (F >> HexagonII::FPPos) & HexagonII::FPMask;
2156 }
2157 
2158 
2159 // No V60 HVX VMEM with A_INDIRECT.
2160 bool HexagonInstrInfo::isHVXMemWithAIndirect(const MachineInstr &I,
2161       const MachineInstr &J) const {
2162   if (!isV60VectorInstruction(I))
2163     return false;
2164   if (!I.mayLoad() && !I.mayStore())
2165     return false;
2166   return J.isIndirectBranch() || isIndirectCall(J) || isIndirectL4Return(J);
2167 }
2168 
2169 
2170 bool HexagonInstrInfo::isIndirectCall(const MachineInstr &MI) const {
2171   switch (MI.getOpcode()) {
2172   case Hexagon::J2_callr :
2173   case Hexagon::J2_callrf :
2174   case Hexagon::J2_callrt :
2175   case Hexagon::PS_call_nr :
2176     return true;
2177   }
2178   return false;
2179 }
2180 
2181 
2182 bool HexagonInstrInfo::isIndirectL4Return(const MachineInstr &MI) const {
2183   switch (MI.getOpcode()) {
2184   case Hexagon::L4_return :
2185   case Hexagon::L4_return_t :
2186   case Hexagon::L4_return_f :
2187   case Hexagon::L4_return_fnew_pnt :
2188   case Hexagon::L4_return_fnew_pt :
2189   case Hexagon::L4_return_tnew_pnt :
2190   case Hexagon::L4_return_tnew_pt :
2191     return true;
2192   }
2193   return false;
2194 }
2195 
2196 
2197 bool HexagonInstrInfo::isJumpR(const MachineInstr &MI) const {
2198   switch (MI.getOpcode()) {
2199   case Hexagon::J2_jumpr :
2200   case Hexagon::J2_jumprt :
2201   case Hexagon::J2_jumprf :
2202   case Hexagon::J2_jumprtnewpt :
2203   case Hexagon::J2_jumprfnewpt  :
2204   case Hexagon::J2_jumprtnew :
2205   case Hexagon::J2_jumprfnew :
2206     return true;
2207   }
2208   return false;
2209 }
2210 
2211 
2212 // Return true if a given MI can accomodate given offset.
2213 // Use abs estimate as oppose to the exact number.
2214 // TODO: This will need to be changed to use MC level
2215 // definition of instruction extendable field size.
2216 bool HexagonInstrInfo::isJumpWithinBranchRange(const MachineInstr &MI,
2217       unsigned offset) const {
2218   // This selection of jump instructions matches to that what
2219   // AnalyzeBranch can parse, plus NVJ.
2220   if (isNewValueJump(MI)) // r9:2
2221     return isInt<11>(offset);
2222 
2223   switch (MI.getOpcode()) {
2224   // Still missing Jump to address condition on register value.
2225   default:
2226     return false;
2227   case Hexagon::J2_jump: // bits<24> dst; // r22:2
2228   case Hexagon::J2_call:
2229   case Hexagon::PS_call_nr:
2230     return isInt<24>(offset);
2231   case Hexagon::J2_jumpt: //bits<17> dst; // r15:2
2232   case Hexagon::J2_jumpf:
2233   case Hexagon::J2_jumptnew:
2234   case Hexagon::J2_jumptnewpt:
2235   case Hexagon::J2_jumpfnew:
2236   case Hexagon::J2_jumpfnewpt:
2237   case Hexagon::J2_callt:
2238   case Hexagon::J2_callf:
2239     return isInt<17>(offset);
2240   case Hexagon::J2_loop0i:
2241   case Hexagon::J2_loop0iext:
2242   case Hexagon::J2_loop0r:
2243   case Hexagon::J2_loop0rext:
2244   case Hexagon::J2_loop1i:
2245   case Hexagon::J2_loop1iext:
2246   case Hexagon::J2_loop1r:
2247   case Hexagon::J2_loop1rext:
2248     return isInt<9>(offset);
2249   // TODO: Add all the compound branches here. Can we do this in Relation model?
2250   case Hexagon::J4_cmpeqi_tp0_jump_nt:
2251   case Hexagon::J4_cmpeqi_tp1_jump_nt:
2252     return isInt<11>(offset);
2253   }
2254 }
2255 
2256 
2257 bool HexagonInstrInfo::isLateInstrFeedsEarlyInstr(const MachineInstr &LRMI,
2258       const MachineInstr &ESMI) const {
2259   bool isLate = isLateResultInstr(LRMI);
2260   bool isEarly = isEarlySourceInstr(ESMI);
2261 
2262   DEBUG(dbgs() << "V60" <<  (isLate ? "-LR  " : " --  "));
2263   DEBUG(LRMI.dump());
2264   DEBUG(dbgs() << "V60" <<  (isEarly ? "-ES  " : " --  "));
2265   DEBUG(ESMI.dump());
2266 
2267   if (isLate && isEarly) {
2268     DEBUG(dbgs() << "++Is Late Result feeding Early Source\n");
2269     return true;
2270   }
2271 
2272   return false;
2273 }
2274 
2275 
2276 bool HexagonInstrInfo::isLateResultInstr(const MachineInstr &MI) const {
2277   switch (MI.getOpcode()) {
2278   case TargetOpcode::EXTRACT_SUBREG:
2279   case TargetOpcode::INSERT_SUBREG:
2280   case TargetOpcode::SUBREG_TO_REG:
2281   case TargetOpcode::REG_SEQUENCE:
2282   case TargetOpcode::IMPLICIT_DEF:
2283   case TargetOpcode::COPY:
2284   case TargetOpcode::INLINEASM:
2285   case TargetOpcode::PHI:
2286     return false;
2287   default:
2288     break;
2289   }
2290 
2291   unsigned SchedClass = MI.getDesc().getSchedClass();
2292 
2293   switch (SchedClass) {
2294   case Hexagon::Sched::ALU32_2op_tc_1_SLOT0123:
2295   case Hexagon::Sched::ALU32_3op_tc_1_SLOT0123:
2296   case Hexagon::Sched::ALU32_ADDI_tc_1_SLOT0123:
2297   case Hexagon::Sched::ALU64_tc_1_SLOT23:
2298   case Hexagon::Sched::EXTENDER_tc_1_SLOT0123:
2299   case Hexagon::Sched::S_2op_tc_1_SLOT23:
2300   case Hexagon::Sched::S_3op_tc_1_SLOT23:
2301   case Hexagon::Sched::V2LDST_tc_ld_SLOT01:
2302   case Hexagon::Sched::V2LDST_tc_st_SLOT0:
2303   case Hexagon::Sched::V2LDST_tc_st_SLOT01:
2304   case Hexagon::Sched::V4LDST_tc_ld_SLOT01:
2305   case Hexagon::Sched::V4LDST_tc_st_SLOT0:
2306   case Hexagon::Sched::V4LDST_tc_st_SLOT01:
2307     return false;
2308   }
2309   return true;
2310 }
2311 
2312 
2313 bool HexagonInstrInfo::isLateSourceInstr(const MachineInstr &MI) const {
2314   // Instructions with iclass A_CVI_VX and attribute A_CVI_LATE uses a multiply
2315   // resource, but all operands can be received late like an ALU instruction.
2316   return MI.getDesc().getSchedClass() == Hexagon::Sched::CVI_VX_LATE;
2317 }
2318 
2319 
2320 bool HexagonInstrInfo::isLoopN(const MachineInstr &MI) const {
2321   unsigned Opcode = MI.getOpcode();
2322   return Opcode == Hexagon::J2_loop0i    ||
2323          Opcode == Hexagon::J2_loop0r    ||
2324          Opcode == Hexagon::J2_loop0iext ||
2325          Opcode == Hexagon::J2_loop0rext ||
2326          Opcode == Hexagon::J2_loop1i    ||
2327          Opcode == Hexagon::J2_loop1r    ||
2328          Opcode == Hexagon::J2_loop1iext ||
2329          Opcode == Hexagon::J2_loop1rext;
2330 }
2331 
2332 
2333 bool HexagonInstrInfo::isMemOp(const MachineInstr &MI) const {
2334   switch (MI.getOpcode()) {
2335     default: return false;
2336     case Hexagon::L4_iadd_memopw_io :
2337     case Hexagon::L4_isub_memopw_io :
2338     case Hexagon::L4_add_memopw_io :
2339     case Hexagon::L4_sub_memopw_io :
2340     case Hexagon::L4_and_memopw_io :
2341     case Hexagon::L4_or_memopw_io :
2342     case Hexagon::L4_iadd_memoph_io :
2343     case Hexagon::L4_isub_memoph_io :
2344     case Hexagon::L4_add_memoph_io :
2345     case Hexagon::L4_sub_memoph_io :
2346     case Hexagon::L4_and_memoph_io :
2347     case Hexagon::L4_or_memoph_io :
2348     case Hexagon::L4_iadd_memopb_io :
2349     case Hexagon::L4_isub_memopb_io :
2350     case Hexagon::L4_add_memopb_io :
2351     case Hexagon::L4_sub_memopb_io :
2352     case Hexagon::L4_and_memopb_io :
2353     case Hexagon::L4_or_memopb_io :
2354     case Hexagon::L4_ior_memopb_io:
2355     case Hexagon::L4_ior_memoph_io:
2356     case Hexagon::L4_ior_memopw_io:
2357     case Hexagon::L4_iand_memopb_io:
2358     case Hexagon::L4_iand_memoph_io:
2359     case Hexagon::L4_iand_memopw_io:
2360     return true;
2361   }
2362   return false;
2363 }
2364 
2365 
2366 bool HexagonInstrInfo::isNewValue(const MachineInstr &MI) const {
2367   const uint64_t F = MI.getDesc().TSFlags;
2368   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2369 }
2370 
2371 
2372 bool HexagonInstrInfo::isNewValue(unsigned Opcode) const {
2373   const uint64_t F = get(Opcode).TSFlags;
2374   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2375 }
2376 
2377 
2378 bool HexagonInstrInfo::isNewValueInst(const MachineInstr &MI) const {
2379   return isNewValueJump(MI) || isNewValueStore(MI);
2380 }
2381 
2382 
2383 bool HexagonInstrInfo::isNewValueJump(const MachineInstr &MI) const {
2384   return isNewValue(MI) && MI.isBranch();
2385 }
2386 
2387 
2388 bool HexagonInstrInfo::isNewValueJump(unsigned Opcode) const {
2389   return isNewValue(Opcode) && get(Opcode).isBranch() && isPredicated(Opcode);
2390 }
2391 
2392 
2393 bool HexagonInstrInfo::isNewValueStore(const MachineInstr &MI) const {
2394   const uint64_t F = MI.getDesc().TSFlags;
2395   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2396 }
2397 
2398 
2399 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
2400   const uint64_t F = get(Opcode).TSFlags;
2401   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2402 }
2403 
2404 
2405 // Returns true if a particular operand is extendable for an instruction.
2406 bool HexagonInstrInfo::isOperandExtended(const MachineInstr &MI,
2407     unsigned OperandNum) const {
2408   const uint64_t F = MI.getDesc().TSFlags;
2409   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
2410           == OperandNum;
2411 }
2412 
2413 
2414 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr &MI) const {
2415   const uint64_t F = MI.getDesc().TSFlags;
2416   assert(isPredicated(MI));
2417   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2418 }
2419 
2420 
2421 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
2422   const uint64_t F = get(Opcode).TSFlags;
2423   assert(isPredicated(Opcode));
2424   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2425 }
2426 
2427 
2428 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr &MI) const {
2429   const uint64_t F = MI.getDesc().TSFlags;
2430   return !((F >> HexagonII::PredicatedFalsePos) &
2431            HexagonII::PredicatedFalseMask);
2432 }
2433 
2434 
2435 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
2436   const uint64_t F = get(Opcode).TSFlags;
2437   // Make sure that the instruction is predicated.
2438   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
2439   return !((F >> HexagonII::PredicatedFalsePos) &
2440            HexagonII::PredicatedFalseMask);
2441 }
2442 
2443 
2444 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
2445   const uint64_t F = get(Opcode).TSFlags;
2446   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
2447 }
2448 
2449 
2450 bool HexagonInstrInfo::isPredicateLate(unsigned Opcode) const {
2451   const uint64_t F = get(Opcode).TSFlags;
2452   return ~(F >> HexagonII::PredicateLatePos) & HexagonII::PredicateLateMask;
2453 }
2454 
2455 
2456 bool HexagonInstrInfo::isPredictedTaken(unsigned Opcode) const {
2457   const uint64_t F = get(Opcode).TSFlags;
2458   assert(get(Opcode).isBranch() &&
2459          (isPredicatedNew(Opcode) || isNewValue(Opcode)));
2460   return (F >> HexagonII::TakenPos) & HexagonII::TakenMask;
2461 }
2462 
2463 
2464 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr &MI) const {
2465   return MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4 ||
2466          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT ||
2467          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_PIC ||
2468          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC;
2469 }
2470 
2471 bool HexagonInstrInfo::isSignExtendingLoad(const MachineInstr &MI) const {
2472   switch (MI.getOpcode()) {
2473   // Byte
2474   case Hexagon::L2_loadrb_io:
2475   case Hexagon::L4_loadrb_ur:
2476   case Hexagon::L4_loadrb_ap:
2477   case Hexagon::L2_loadrb_pr:
2478   case Hexagon::L2_loadrb_pbr:
2479   case Hexagon::L2_loadrb_pi:
2480   case Hexagon::L2_loadrb_pci:
2481   case Hexagon::L2_loadrb_pcr:
2482   case Hexagon::L2_loadbsw2_io:
2483   case Hexagon::L4_loadbsw2_ur:
2484   case Hexagon::L4_loadbsw2_ap:
2485   case Hexagon::L2_loadbsw2_pr:
2486   case Hexagon::L2_loadbsw2_pbr:
2487   case Hexagon::L2_loadbsw2_pi:
2488   case Hexagon::L2_loadbsw2_pci:
2489   case Hexagon::L2_loadbsw2_pcr:
2490   case Hexagon::L2_loadbsw4_io:
2491   case Hexagon::L4_loadbsw4_ur:
2492   case Hexagon::L4_loadbsw4_ap:
2493   case Hexagon::L2_loadbsw4_pr:
2494   case Hexagon::L2_loadbsw4_pbr:
2495   case Hexagon::L2_loadbsw4_pi:
2496   case Hexagon::L2_loadbsw4_pci:
2497   case Hexagon::L2_loadbsw4_pcr:
2498   case Hexagon::L4_loadrb_rr:
2499   case Hexagon::L2_ploadrbt_io:
2500   case Hexagon::L2_ploadrbt_pi:
2501   case Hexagon::L2_ploadrbf_io:
2502   case Hexagon::L2_ploadrbf_pi:
2503   case Hexagon::L2_ploadrbtnew_io:
2504   case Hexagon::L2_ploadrbfnew_io:
2505   case Hexagon::L4_ploadrbt_rr:
2506   case Hexagon::L4_ploadrbf_rr:
2507   case Hexagon::L4_ploadrbtnew_rr:
2508   case Hexagon::L4_ploadrbfnew_rr:
2509   case Hexagon::L2_ploadrbtnew_pi:
2510   case Hexagon::L2_ploadrbfnew_pi:
2511   case Hexagon::L4_ploadrbt_abs:
2512   case Hexagon::L4_ploadrbf_abs:
2513   case Hexagon::L4_ploadrbtnew_abs:
2514   case Hexagon::L4_ploadrbfnew_abs:
2515   case Hexagon::L2_loadrbgp:
2516   // Half
2517   case Hexagon::L2_loadrh_io:
2518   case Hexagon::L4_loadrh_ur:
2519   case Hexagon::L4_loadrh_ap:
2520   case Hexagon::L2_loadrh_pr:
2521   case Hexagon::L2_loadrh_pbr:
2522   case Hexagon::L2_loadrh_pi:
2523   case Hexagon::L2_loadrh_pci:
2524   case Hexagon::L2_loadrh_pcr:
2525   case Hexagon::L4_loadrh_rr:
2526   case Hexagon::L2_ploadrht_io:
2527   case Hexagon::L2_ploadrht_pi:
2528   case Hexagon::L2_ploadrhf_io:
2529   case Hexagon::L2_ploadrhf_pi:
2530   case Hexagon::L2_ploadrhtnew_io:
2531   case Hexagon::L2_ploadrhfnew_io:
2532   case Hexagon::L4_ploadrht_rr:
2533   case Hexagon::L4_ploadrhf_rr:
2534   case Hexagon::L4_ploadrhtnew_rr:
2535   case Hexagon::L4_ploadrhfnew_rr:
2536   case Hexagon::L2_ploadrhtnew_pi:
2537   case Hexagon::L2_ploadrhfnew_pi:
2538   case Hexagon::L4_ploadrht_abs:
2539   case Hexagon::L4_ploadrhf_abs:
2540   case Hexagon::L4_ploadrhtnew_abs:
2541   case Hexagon::L4_ploadrhfnew_abs:
2542   case Hexagon::L2_loadrhgp:
2543     return true;
2544   default:
2545     return false;
2546   }
2547 }
2548 
2549 
2550 bool HexagonInstrInfo::isSolo(const MachineInstr &MI) const {
2551   const uint64_t F = MI.getDesc().TSFlags;
2552   return (F >> HexagonII::SoloPos) & HexagonII::SoloMask;
2553 }
2554 
2555 
2556 bool HexagonInstrInfo::isSpillPredRegOp(const MachineInstr &MI) const {
2557   switch (MI.getOpcode()) {
2558   case Hexagon::STriw_pred :
2559   case Hexagon::LDriw_pred :
2560     return true;
2561   default:
2562     return false;
2563   }
2564 }
2565 
2566 
2567 bool HexagonInstrInfo::isTailCall(const MachineInstr &MI) const {
2568   if (!MI.isBranch())
2569     return false;
2570 
2571   for (auto &Op : MI.operands())
2572     if (Op.isGlobal() || Op.isSymbol())
2573       return true;
2574   return false;
2575 }
2576 
2577 
2578 // Returns true when SU has a timing class TC1.
2579 bool HexagonInstrInfo::isTC1(const MachineInstr &MI) const {
2580   unsigned SchedClass = MI.getDesc().getSchedClass();
2581   switch (SchedClass) {
2582   case Hexagon::Sched::ALU32_2op_tc_1_SLOT0123:
2583   case Hexagon::Sched::ALU32_3op_tc_1_SLOT0123:
2584   case Hexagon::Sched::ALU32_ADDI_tc_1_SLOT0123:
2585   case Hexagon::Sched::ALU64_tc_1_SLOT23:
2586   case Hexagon::Sched::EXTENDER_tc_1_SLOT0123:
2587   //case Hexagon::Sched::M_tc_1_SLOT23:
2588   case Hexagon::Sched::S_2op_tc_1_SLOT23:
2589   case Hexagon::Sched::S_3op_tc_1_SLOT23:
2590     return true;
2591 
2592   default:
2593     return false;
2594   }
2595 }
2596 
2597 
2598 bool HexagonInstrInfo::isTC2(const MachineInstr &MI) const {
2599   unsigned SchedClass = MI.getDesc().getSchedClass();
2600   switch (SchedClass) {
2601   case Hexagon::Sched::ALU32_3op_tc_2_SLOT0123:
2602   case Hexagon::Sched::ALU64_tc_2_SLOT23:
2603   case Hexagon::Sched::CR_tc_2_SLOT3:
2604   case Hexagon::Sched::M_tc_2_SLOT23:
2605   case Hexagon::Sched::S_2op_tc_2_SLOT23:
2606   case Hexagon::Sched::S_3op_tc_2_SLOT23:
2607     return true;
2608 
2609   default:
2610     return false;
2611   }
2612 }
2613 
2614 
2615 bool HexagonInstrInfo::isTC2Early(const MachineInstr &MI) const {
2616   unsigned SchedClass = MI.getDesc().getSchedClass();
2617   switch (SchedClass) {
2618   case Hexagon::Sched::ALU32_2op_tc_2early_SLOT0123:
2619   case Hexagon::Sched::ALU32_3op_tc_2early_SLOT0123:
2620   case Hexagon::Sched::ALU64_tc_2early_SLOT23:
2621   case Hexagon::Sched::CR_tc_2early_SLOT23:
2622   case Hexagon::Sched::CR_tc_2early_SLOT3:
2623   case Hexagon::Sched::J_tc_2early_SLOT0123:
2624   case Hexagon::Sched::J_tc_2early_SLOT2:
2625   case Hexagon::Sched::J_tc_2early_SLOT23:
2626   case Hexagon::Sched::S_2op_tc_2early_SLOT23:
2627   case Hexagon::Sched::S_3op_tc_2early_SLOT23:
2628     return true;
2629 
2630   default:
2631     return false;
2632   }
2633 }
2634 
2635 
2636 bool HexagonInstrInfo::isTC4x(const MachineInstr &MI) const {
2637   unsigned SchedClass = MI.getDesc().getSchedClass();
2638   return SchedClass == Hexagon::Sched::M_tc_3or4x_SLOT23;
2639 }
2640 
2641 
2642 // Schedule this ASAP.
2643 bool HexagonInstrInfo::isToBeScheduledASAP(const MachineInstr &MI1,
2644       const MachineInstr &MI2) const {
2645   if (mayBeCurLoad(MI1)) {
2646     // if (result of SU is used in Next) return true;
2647     unsigned DstReg = MI1.getOperand(0).getReg();
2648     int N = MI2.getNumOperands();
2649     for (int I = 0; I < N; I++)
2650       if (MI2.getOperand(I).isReg() && DstReg == MI2.getOperand(I).getReg())
2651         return true;
2652   }
2653   if (mayBeNewStore(MI2))
2654     if (MI2.getOpcode() == Hexagon::V6_vS32b_pi)
2655       if (MI1.getOperand(0).isReg() && MI2.getOperand(3).isReg() &&
2656           MI1.getOperand(0).getReg() == MI2.getOperand(3).getReg())
2657         return true;
2658   return false;
2659 }
2660 
2661 
2662 bool HexagonInstrInfo::isV60VectorInstruction(const MachineInstr &MI) const {
2663   const uint64_t V = getType(MI);
2664   return HexagonII::TypeCVI_FIRST <= V && V <= HexagonII::TypeCVI_LAST;
2665 }
2666 
2667 
2668 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
2669 //
2670 bool HexagonInstrInfo::isValidAutoIncImm(const EVT VT, const int Offset) const {
2671   if (VT == MVT::v16i32 || VT == MVT::v8i64 ||
2672       VT == MVT::v32i16 || VT == MVT::v64i8) {
2673       return (Offset >= Hexagon_MEMV_AUTOINC_MIN &&
2674               Offset <= Hexagon_MEMV_AUTOINC_MAX &&
2675               (Offset & 0x3f) == 0);
2676   }
2677   // 128B
2678   if (VT == MVT::v32i32 || VT == MVT::v16i64 ||
2679       VT == MVT::v64i16 || VT == MVT::v128i8) {
2680       return (Offset >= Hexagon_MEMV_AUTOINC_MIN_128B &&
2681               Offset <= Hexagon_MEMV_AUTOINC_MAX_128B &&
2682               (Offset & 0x7f) == 0);
2683   }
2684   if (VT == MVT::i64) {
2685       return (Offset >= Hexagon_MEMD_AUTOINC_MIN &&
2686               Offset <= Hexagon_MEMD_AUTOINC_MAX &&
2687               (Offset & 0x7) == 0);
2688   }
2689   if (VT == MVT::i32) {
2690       return (Offset >= Hexagon_MEMW_AUTOINC_MIN &&
2691               Offset <= Hexagon_MEMW_AUTOINC_MAX &&
2692               (Offset & 0x3) == 0);
2693   }
2694   if (VT == MVT::i16) {
2695       return (Offset >= Hexagon_MEMH_AUTOINC_MIN &&
2696               Offset <= Hexagon_MEMH_AUTOINC_MAX &&
2697               (Offset & 0x1) == 0);
2698   }
2699   if (VT == MVT::i8) {
2700       return (Offset >= Hexagon_MEMB_AUTOINC_MIN &&
2701               Offset <= Hexagon_MEMB_AUTOINC_MAX);
2702   }
2703   llvm_unreachable("Not an auto-inc opc!");
2704 }
2705 
2706 
2707 bool HexagonInstrInfo::isValidOffset(unsigned Opcode, int Offset,
2708       bool Extend) const {
2709   // This function is to check whether the "Offset" is in the correct range of
2710   // the given "Opcode". If "Offset" is not in the correct range, "A2_addi" is
2711   // inserted to calculate the final address. Due to this reason, the function
2712   // assumes that the "Offset" has correct alignment.
2713   // We used to assert if the offset was not properly aligned, however,
2714   // there are cases where a misaligned pointer recast can cause this
2715   // problem, and we need to allow for it. The front end warns of such
2716   // misaligns with respect to load size.
2717 
2718   switch (Opcode) {
2719   case Hexagon::PS_vstorerq_ai:
2720   case Hexagon::PS_vstorerw_ai:
2721   case Hexagon::PS_vloadrq_ai:
2722   case Hexagon::PS_vloadrw_ai:
2723   case Hexagon::V6_vL32b_ai:
2724   case Hexagon::V6_vS32b_ai:
2725   case Hexagon::V6_vL32Ub_ai:
2726   case Hexagon::V6_vS32Ub_ai:
2727     return (Offset >= Hexagon_MEMV_OFFSET_MIN) &&
2728       (Offset <= Hexagon_MEMV_OFFSET_MAX);
2729 
2730   case Hexagon::PS_vstorerq_ai_128B:
2731   case Hexagon::PS_vstorerw_ai_128B:
2732   case Hexagon::PS_vloadrq_ai_128B:
2733   case Hexagon::PS_vloadrw_ai_128B:
2734   case Hexagon::V6_vL32b_ai_128B:
2735   case Hexagon::V6_vS32b_ai_128B:
2736   case Hexagon::V6_vL32Ub_ai_128B:
2737   case Hexagon::V6_vS32Ub_ai_128B:
2738     return (Offset >= Hexagon_MEMV_OFFSET_MIN_128B) &&
2739       (Offset <= Hexagon_MEMV_OFFSET_MAX_128B);
2740 
2741   case Hexagon::J2_loop0i:
2742   case Hexagon::J2_loop1i:
2743     return isUInt<10>(Offset);
2744 
2745   case Hexagon::S4_storeirb_io:
2746   case Hexagon::S4_storeirbt_io:
2747   case Hexagon::S4_storeirbf_io:
2748     return isUInt<6>(Offset);
2749 
2750   case Hexagon::S4_storeirh_io:
2751   case Hexagon::S4_storeirht_io:
2752   case Hexagon::S4_storeirhf_io:
2753     return isShiftedUInt<6,1>(Offset);
2754 
2755   case Hexagon::S4_storeiri_io:
2756   case Hexagon::S4_storeirit_io:
2757   case Hexagon::S4_storeirif_io:
2758     return isShiftedUInt<6,2>(Offset);
2759   }
2760 
2761   if (Extend)
2762     return true;
2763 
2764   switch (Opcode) {
2765   case Hexagon::L2_loadri_io:
2766   case Hexagon::S2_storeri_io:
2767     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
2768       (Offset <= Hexagon_MEMW_OFFSET_MAX);
2769 
2770   case Hexagon::L2_loadrd_io:
2771   case Hexagon::S2_storerd_io:
2772     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
2773       (Offset <= Hexagon_MEMD_OFFSET_MAX);
2774 
2775   case Hexagon::L2_loadrh_io:
2776   case Hexagon::L2_loadruh_io:
2777   case Hexagon::S2_storerh_io:
2778     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
2779       (Offset <= Hexagon_MEMH_OFFSET_MAX);
2780 
2781   case Hexagon::L2_loadrb_io:
2782   case Hexagon::L2_loadrub_io:
2783   case Hexagon::S2_storerb_io:
2784     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
2785       (Offset <= Hexagon_MEMB_OFFSET_MAX);
2786 
2787   case Hexagon::A2_addi:
2788     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
2789       (Offset <= Hexagon_ADDI_OFFSET_MAX);
2790 
2791   case Hexagon::L4_iadd_memopw_io :
2792   case Hexagon::L4_isub_memopw_io :
2793   case Hexagon::L4_add_memopw_io :
2794   case Hexagon::L4_sub_memopw_io :
2795   case Hexagon::L4_and_memopw_io :
2796   case Hexagon::L4_or_memopw_io :
2797     return (0 <= Offset && Offset <= 255);
2798 
2799   case Hexagon::L4_iadd_memoph_io :
2800   case Hexagon::L4_isub_memoph_io :
2801   case Hexagon::L4_add_memoph_io :
2802   case Hexagon::L4_sub_memoph_io :
2803   case Hexagon::L4_and_memoph_io :
2804   case Hexagon::L4_or_memoph_io :
2805     return (0 <= Offset && Offset <= 127);
2806 
2807   case Hexagon::L4_iadd_memopb_io :
2808   case Hexagon::L4_isub_memopb_io :
2809   case Hexagon::L4_add_memopb_io :
2810   case Hexagon::L4_sub_memopb_io :
2811   case Hexagon::L4_and_memopb_io :
2812   case Hexagon::L4_or_memopb_io :
2813     return (0 <= Offset && Offset <= 63);
2814 
2815   // LDriw_xxx and STriw_xxx are pseudo operations, so it has to take offset of
2816   // any size. Later pass knows how to handle it.
2817   case Hexagon::STriw_pred:
2818   case Hexagon::LDriw_pred:
2819   case Hexagon::STriw_mod:
2820   case Hexagon::LDriw_mod:
2821     return true;
2822 
2823   case Hexagon::PS_fi:
2824   case Hexagon::PS_fia:
2825   case Hexagon::INLINEASM:
2826     return true;
2827 
2828   case Hexagon::L2_ploadrbt_io:
2829   case Hexagon::L2_ploadrbf_io:
2830   case Hexagon::L2_ploadrubt_io:
2831   case Hexagon::L2_ploadrubf_io:
2832   case Hexagon::S2_pstorerbt_io:
2833   case Hexagon::S2_pstorerbf_io:
2834     return isUInt<6>(Offset);
2835 
2836   case Hexagon::L2_ploadrht_io:
2837   case Hexagon::L2_ploadrhf_io:
2838   case Hexagon::L2_ploadruht_io:
2839   case Hexagon::L2_ploadruhf_io:
2840   case Hexagon::S2_pstorerht_io:
2841   case Hexagon::S2_pstorerhf_io:
2842     return isShiftedUInt<6,1>(Offset);
2843 
2844   case Hexagon::L2_ploadrit_io:
2845   case Hexagon::L2_ploadrif_io:
2846   case Hexagon::S2_pstorerit_io:
2847   case Hexagon::S2_pstorerif_io:
2848     return isShiftedUInt<6,2>(Offset);
2849 
2850   case Hexagon::L2_ploadrdt_io:
2851   case Hexagon::L2_ploadrdf_io:
2852   case Hexagon::S2_pstorerdt_io:
2853   case Hexagon::S2_pstorerdf_io:
2854     return isShiftedUInt<6,3>(Offset);
2855   } // switch
2856 
2857   llvm_unreachable("No offset range is defined for this opcode. "
2858                    "Please define it in the above switch statement!");
2859 }
2860 
2861 
2862 bool HexagonInstrInfo::isVecAcc(const MachineInstr &MI) const {
2863   return isV60VectorInstruction(MI) && isAccumulator(MI);
2864 }
2865 
2866 
2867 bool HexagonInstrInfo::isVecALU(const MachineInstr &MI) const {
2868   const uint64_t F = get(MI.getOpcode()).TSFlags;
2869   const uint64_t V = ((F >> HexagonII::TypePos) & HexagonII::TypeMask);
2870   return
2871     V == HexagonII::TypeCVI_VA         ||
2872     V == HexagonII::TypeCVI_VA_DV;
2873 }
2874 
2875 
2876 bool HexagonInstrInfo::isVecUsableNextPacket(const MachineInstr &ProdMI,
2877       const MachineInstr &ConsMI) const {
2878   if (EnableACCForwarding && isVecAcc(ProdMI) && isVecAcc(ConsMI))
2879     return true;
2880 
2881   if (EnableALUForwarding && (isVecALU(ConsMI) || isLateSourceInstr(ConsMI)))
2882     return true;
2883 
2884   if (mayBeNewStore(ConsMI))
2885     return true;
2886 
2887   return false;
2888 }
2889 
2890 bool HexagonInstrInfo::isZeroExtendingLoad(const MachineInstr &MI) const {
2891   switch (MI.getOpcode()) {
2892   // Byte
2893   case Hexagon::L2_loadrub_io:
2894   case Hexagon::L4_loadrub_ur:
2895   case Hexagon::L4_loadrub_ap:
2896   case Hexagon::L2_loadrub_pr:
2897   case Hexagon::L2_loadrub_pbr:
2898   case Hexagon::L2_loadrub_pi:
2899   case Hexagon::L2_loadrub_pci:
2900   case Hexagon::L2_loadrub_pcr:
2901   case Hexagon::L2_loadbzw2_io:
2902   case Hexagon::L4_loadbzw2_ur:
2903   case Hexagon::L4_loadbzw2_ap:
2904   case Hexagon::L2_loadbzw2_pr:
2905   case Hexagon::L2_loadbzw2_pbr:
2906   case Hexagon::L2_loadbzw2_pi:
2907   case Hexagon::L2_loadbzw2_pci:
2908   case Hexagon::L2_loadbzw2_pcr:
2909   case Hexagon::L2_loadbzw4_io:
2910   case Hexagon::L4_loadbzw4_ur:
2911   case Hexagon::L4_loadbzw4_ap:
2912   case Hexagon::L2_loadbzw4_pr:
2913   case Hexagon::L2_loadbzw4_pbr:
2914   case Hexagon::L2_loadbzw4_pi:
2915   case Hexagon::L2_loadbzw4_pci:
2916   case Hexagon::L2_loadbzw4_pcr:
2917   case Hexagon::L4_loadrub_rr:
2918   case Hexagon::L2_ploadrubt_io:
2919   case Hexagon::L2_ploadrubt_pi:
2920   case Hexagon::L2_ploadrubf_io:
2921   case Hexagon::L2_ploadrubf_pi:
2922   case Hexagon::L2_ploadrubtnew_io:
2923   case Hexagon::L2_ploadrubfnew_io:
2924   case Hexagon::L4_ploadrubt_rr:
2925   case Hexagon::L4_ploadrubf_rr:
2926   case Hexagon::L4_ploadrubtnew_rr:
2927   case Hexagon::L4_ploadrubfnew_rr:
2928   case Hexagon::L2_ploadrubtnew_pi:
2929   case Hexagon::L2_ploadrubfnew_pi:
2930   case Hexagon::L4_ploadrubt_abs:
2931   case Hexagon::L4_ploadrubf_abs:
2932   case Hexagon::L4_ploadrubtnew_abs:
2933   case Hexagon::L4_ploadrubfnew_abs:
2934   case Hexagon::L2_loadrubgp:
2935   // Half
2936   case Hexagon::L2_loadruh_io:
2937   case Hexagon::L4_loadruh_ur:
2938   case Hexagon::L4_loadruh_ap:
2939   case Hexagon::L2_loadruh_pr:
2940   case Hexagon::L2_loadruh_pbr:
2941   case Hexagon::L2_loadruh_pi:
2942   case Hexagon::L2_loadruh_pci:
2943   case Hexagon::L2_loadruh_pcr:
2944   case Hexagon::L4_loadruh_rr:
2945   case Hexagon::L2_ploadruht_io:
2946   case Hexagon::L2_ploadruht_pi:
2947   case Hexagon::L2_ploadruhf_io:
2948   case Hexagon::L2_ploadruhf_pi:
2949   case Hexagon::L2_ploadruhtnew_io:
2950   case Hexagon::L2_ploadruhfnew_io:
2951   case Hexagon::L4_ploadruht_rr:
2952   case Hexagon::L4_ploadruhf_rr:
2953   case Hexagon::L4_ploadruhtnew_rr:
2954   case Hexagon::L4_ploadruhfnew_rr:
2955   case Hexagon::L2_ploadruhtnew_pi:
2956   case Hexagon::L2_ploadruhfnew_pi:
2957   case Hexagon::L4_ploadruht_abs:
2958   case Hexagon::L4_ploadruhf_abs:
2959   case Hexagon::L4_ploadruhtnew_abs:
2960   case Hexagon::L4_ploadruhfnew_abs:
2961   case Hexagon::L2_loadruhgp:
2962     return true;
2963   default:
2964     return false;
2965   }
2966 }
2967 
2968 
2969 // Add latency to instruction.
2970 bool HexagonInstrInfo::addLatencyToSchedule(const MachineInstr &MI1,
2971       const MachineInstr &MI2) const {
2972   if (isV60VectorInstruction(MI1) && isV60VectorInstruction(MI2))
2973     if (!isVecUsableNextPacket(MI1, MI2))
2974       return true;
2975   return false;
2976 }
2977 
2978 
2979 /// \brief Get the base register and byte offset of a load/store instr.
2980 bool HexagonInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt,
2981       unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI)
2982       const {
2983   unsigned AccessSize = 0;
2984   int OffsetVal = 0;
2985   BaseReg = getBaseAndOffset(LdSt, OffsetVal, AccessSize);
2986   Offset = OffsetVal;
2987   return BaseReg != 0;
2988 }
2989 
2990 
2991 /// \brief Can these instructions execute at the same time in a bundle.
2992 bool HexagonInstrInfo::canExecuteInBundle(const MachineInstr &First,
2993       const MachineInstr &Second) const {
2994   if (DisableNVSchedule)
2995     return false;
2996   if (mayBeNewStore(Second)) {
2997     // Make sure the definition of the first instruction is the value being
2998     // stored.
2999     const MachineOperand &Stored =
3000       Second.getOperand(Second.getNumOperands() - 1);
3001     if (!Stored.isReg())
3002       return false;
3003     for (unsigned i = 0, e = First.getNumOperands(); i < e; ++i) {
3004       const MachineOperand &Op = First.getOperand(i);
3005       if (Op.isReg() && Op.isDef() && Op.getReg() == Stored.getReg())
3006         return true;
3007     }
3008   }
3009   return false;
3010 }
3011 
3012 
3013 bool HexagonInstrInfo::doesNotReturn(const MachineInstr &CallMI) const {
3014   unsigned Opc = CallMI.getOpcode();
3015   return Opc == Hexagon::PS_call_nr || Opc == Hexagon::PS_callr_nr;
3016 }
3017 
3018 
3019 bool HexagonInstrInfo::hasEHLabel(const MachineBasicBlock *B) const {
3020   for (auto &I : *B)
3021     if (I.isEHLabel())
3022       return true;
3023   return false;
3024 }
3025 
3026 
3027 // Returns true if an instruction can be converted into a non-extended
3028 // equivalent instruction.
3029 bool HexagonInstrInfo::hasNonExtEquivalent(const MachineInstr &MI) const {
3030   short NonExtOpcode;
3031   // Check if the instruction has a register form that uses register in place
3032   // of the extended operand, if so return that as the non-extended form.
3033   if (Hexagon::getRegForm(MI.getOpcode()) >= 0)
3034     return true;
3035 
3036   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
3037     // Check addressing mode and retrieve non-ext equivalent instruction.
3038 
3039     switch (getAddrMode(MI)) {
3040     case HexagonII::Absolute :
3041       // Load/store with absolute addressing mode can be converted into
3042       // base+offset mode.
3043       NonExtOpcode = Hexagon::getBaseWithImmOffset(MI.getOpcode());
3044       break;
3045     case HexagonII::BaseImmOffset :
3046       // Load/store with base+offset addressing mode can be converted into
3047       // base+register offset addressing mode. However left shift operand should
3048       // be set to 0.
3049       NonExtOpcode = Hexagon::getBaseWithRegOffset(MI.getOpcode());
3050       break;
3051     case HexagonII::BaseLongOffset:
3052       NonExtOpcode = Hexagon::getRegShlForm(MI.getOpcode());
3053       break;
3054     default:
3055       return false;
3056     }
3057     if (NonExtOpcode < 0)
3058       return false;
3059     return true;
3060   }
3061   return false;
3062 }
3063 
3064 
3065 bool HexagonInstrInfo::hasPseudoInstrPair(const MachineInstr &MI) const {
3066   return Hexagon::getRealHWInstr(MI.getOpcode(),
3067                                  Hexagon::InstrType_Pseudo) >= 0;
3068 }
3069 
3070 
3071 bool HexagonInstrInfo::hasUncondBranch(const MachineBasicBlock *B)
3072       const {
3073   MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
3074   while (I != E) {
3075     if (I->isBarrier())
3076       return true;
3077     ++I;
3078   }
3079   return false;
3080 }
3081 
3082 
3083 // Returns true, if a LD insn can be promoted to a cur load.
3084 bool HexagonInstrInfo::mayBeCurLoad(const MachineInstr &MI) const {
3085   auto &HST = MI.getParent()->getParent()->getSubtarget<HexagonSubtarget>();
3086   const uint64_t F = MI.getDesc().TSFlags;
3087   return ((F >> HexagonII::mayCVLoadPos) & HexagonII::mayCVLoadMask) &&
3088          HST.hasV60TOps();
3089 }
3090 
3091 
3092 // Returns true, if a ST insn can be promoted to a new-value store.
3093 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr &MI) const {
3094   const uint64_t F = MI.getDesc().TSFlags;
3095   return (F >> HexagonII::mayNVStorePos) & HexagonII::mayNVStoreMask;
3096 }
3097 
3098 
3099 bool HexagonInstrInfo::producesStall(const MachineInstr &ProdMI,
3100       const MachineInstr &ConsMI) const {
3101   // There is no stall when ProdMI is not a V60 vector.
3102   if (!isV60VectorInstruction(ProdMI))
3103     return false;
3104 
3105   // There is no stall when ProdMI and ConsMI are not dependent.
3106   if (!isDependent(ProdMI, ConsMI))
3107     return false;
3108 
3109   // When Forward Scheduling is enabled, there is no stall if ProdMI and ConsMI
3110   // are scheduled in consecutive packets.
3111   if (isVecUsableNextPacket(ProdMI, ConsMI))
3112     return false;
3113 
3114   return true;
3115 }
3116 
3117 
3118 bool HexagonInstrInfo::producesStall(const MachineInstr &MI,
3119       MachineBasicBlock::const_instr_iterator BII) const {
3120   // There is no stall when I is not a V60 vector.
3121   if (!isV60VectorInstruction(MI))
3122     return false;
3123 
3124   MachineBasicBlock::const_instr_iterator MII = BII;
3125   MachineBasicBlock::const_instr_iterator MIE = MII->getParent()->instr_end();
3126 
3127   if (!MII->isBundle()) {
3128     const MachineInstr &J = *MII;
3129     if (!isV60VectorInstruction(J))
3130       return false;
3131     else if (isVecUsableNextPacket(J, MI))
3132       return false;
3133     return true;
3134   }
3135 
3136   for (++MII; MII != MIE && MII->isInsideBundle(); ++MII) {
3137     const MachineInstr &J = *MII;
3138     if (producesStall(J, MI))
3139       return true;
3140   }
3141   return false;
3142 }
3143 
3144 
3145 bool HexagonInstrInfo::predCanBeUsedAsDotNew(const MachineInstr &MI,
3146       unsigned PredReg) const {
3147   for (unsigned opNum = 0; opNum < MI.getNumOperands(); opNum++) {
3148     const MachineOperand &MO = MI.getOperand(opNum);
3149     if (MO.isReg() && MO.isDef() && MO.isImplicit() && (MO.getReg() == PredReg))
3150       return false; // Predicate register must be explicitly defined.
3151   }
3152 
3153   // Hexagon Programmer's Reference says that decbin, memw_locked, and
3154   // memd_locked cannot be used as .new as well,
3155   // but we don't seem to have these instructions defined.
3156   return MI.getOpcode() != Hexagon::A4_tlbmatch;
3157 }
3158 
3159 
3160 bool HexagonInstrInfo::PredOpcodeHasJMP_c(unsigned Opcode) const {
3161   return (Opcode == Hexagon::J2_jumpt)      ||
3162          (Opcode == Hexagon::J2_jumpf)      ||
3163          (Opcode == Hexagon::J2_jumptnew)   ||
3164          (Opcode == Hexagon::J2_jumpfnew)   ||
3165          (Opcode == Hexagon::J2_jumptnewpt) ||
3166          (Opcode == Hexagon::J2_jumpfnewpt);
3167 }
3168 
3169 
3170 bool HexagonInstrInfo::predOpcodeHasNot(ArrayRef<MachineOperand> Cond) const {
3171   if (Cond.empty() || !isPredicated(Cond[0].getImm()))
3172     return false;
3173   return !isPredicatedTrue(Cond[0].getImm());
3174 }
3175 
3176 
3177 short HexagonInstrInfo::getAbsoluteForm(const MachineInstr &MI) const {
3178   return Hexagon::getAbsoluteForm(MI.getOpcode());
3179 }
3180 
3181 
3182 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr &MI) const {
3183   const uint64_t F = MI.getDesc().TSFlags;
3184   return (F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask;
3185 }
3186 
3187 
3188 // Returns the base register in a memory access (load/store). The offset is
3189 // returned in Offset and the access size is returned in AccessSize.
3190 unsigned HexagonInstrInfo::getBaseAndOffset(const MachineInstr &MI,
3191       int &Offset, unsigned &AccessSize) const {
3192   // Return if it is not a base+offset type instruction or a MemOp.
3193   if (getAddrMode(MI) != HexagonII::BaseImmOffset &&
3194       getAddrMode(MI) != HexagonII::BaseLongOffset &&
3195       !isMemOp(MI) && !isPostIncrement(MI))
3196     return 0;
3197 
3198   // Since it is a memory access instruction, getMemAccessSize() should never
3199   // return 0.
3200   assert (getMemAccessSize(MI) &&
3201           "BaseImmOffset or BaseLongOffset or MemOp without accessSize");
3202 
3203   // Return Values of getMemAccessSize() are
3204   // 0 - Checked in the assert above.
3205   // 1, 2, 3, 4 & 7, 8 - The statement below is correct for all these.
3206   // MemAccessSize is represented as 1+log2(N) where N is size in bits.
3207   AccessSize = (1U << (getMemAccessSize(MI) - 1));
3208 
3209   unsigned basePos = 0, offsetPos = 0;
3210   if (!getBaseAndOffsetPosition(MI, basePos, offsetPos))
3211     return 0;
3212 
3213   // Post increment updates its EA after the mem access,
3214   // so we need to treat its offset as zero.
3215   if (isPostIncrement(MI))
3216     Offset = 0;
3217   else {
3218     Offset = MI.getOperand(offsetPos).getImm();
3219   }
3220 
3221   return MI.getOperand(basePos).getReg();
3222 }
3223 
3224 
3225 /// Return the position of the base and offset operands for this instruction.
3226 bool HexagonInstrInfo::getBaseAndOffsetPosition(const MachineInstr &MI,
3227       unsigned &BasePos, unsigned &OffsetPos) const {
3228   // Deal with memops first.
3229   if (isMemOp(MI)) {
3230     BasePos = 0;
3231     OffsetPos = 1;
3232   } else if (MI.mayStore()) {
3233     BasePos = 0;
3234     OffsetPos = 1;
3235   } else if (MI.mayLoad()) {
3236     BasePos = 1;
3237     OffsetPos = 2;
3238   } else
3239     return false;
3240 
3241   if (isPredicated(MI)) {
3242     BasePos++;
3243     OffsetPos++;
3244   }
3245   if (isPostIncrement(MI)) {
3246     BasePos++;
3247     OffsetPos++;
3248   }
3249 
3250   if (!MI.getOperand(BasePos).isReg() || !MI.getOperand(OffsetPos).isImm())
3251     return false;
3252 
3253   return true;
3254 }
3255 
3256 
3257 // Inserts branching instructions in reverse order of their occurence.
3258 // e.g. jump_t t1 (i1)
3259 // jump t2        (i2)
3260 // Jumpers = {i2, i1}
3261 SmallVector<MachineInstr*, 2> HexagonInstrInfo::getBranchingInstrs(
3262       MachineBasicBlock& MBB) const {
3263   SmallVector<MachineInstr*, 2> Jumpers;
3264   // If the block has no terminators, it just falls into the block after it.
3265   MachineBasicBlock::instr_iterator I = MBB.instr_end();
3266   if (I == MBB.instr_begin())
3267     return Jumpers;
3268 
3269   // A basic block may looks like this:
3270   //
3271   //  [   insn
3272   //     EH_LABEL
3273   //      insn
3274   //      insn
3275   //      insn
3276   //     EH_LABEL
3277   //      insn     ]
3278   //
3279   // It has two succs but does not have a terminator
3280   // Don't know how to handle it.
3281   do {
3282     --I;
3283     if (I->isEHLabel())
3284       return Jumpers;
3285   } while (I != MBB.instr_begin());
3286 
3287   I = MBB.instr_end();
3288   --I;
3289 
3290   while (I->isDebugValue()) {
3291     if (I == MBB.instr_begin())
3292       return Jumpers;
3293     --I;
3294   }
3295   if (!isUnpredicatedTerminator(*I))
3296     return Jumpers;
3297 
3298   // Get the last instruction in the block.
3299   MachineInstr *LastInst = &*I;
3300   Jumpers.push_back(LastInst);
3301   MachineInstr *SecondLastInst = nullptr;
3302   // Find one more terminator if present.
3303   do {
3304     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
3305       if (!SecondLastInst) {
3306         SecondLastInst = &*I;
3307         Jumpers.push_back(SecondLastInst);
3308       } else // This is a third branch.
3309         return Jumpers;
3310     }
3311     if (I == MBB.instr_begin())
3312       break;
3313     --I;
3314   } while (true);
3315   return Jumpers;
3316 }
3317 
3318 
3319 short HexagonInstrInfo::getBaseWithLongOffset(short Opcode) const {
3320   if (Opcode < 0)
3321     return -1;
3322   return Hexagon::getBaseWithLongOffset(Opcode);
3323 }
3324 
3325 
3326 short HexagonInstrInfo::getBaseWithLongOffset(const MachineInstr &MI) const {
3327   return Hexagon::getBaseWithLongOffset(MI.getOpcode());
3328 }
3329 
3330 
3331 short HexagonInstrInfo::getBaseWithRegOffset(const MachineInstr &MI) const {
3332   return Hexagon::getBaseWithRegOffset(MI.getOpcode());
3333 }
3334 
3335 
3336 // Returns Operand Index for the constant extended instruction.
3337 unsigned HexagonInstrInfo::getCExtOpNum(const MachineInstr &MI) const {
3338   const uint64_t F = MI.getDesc().TSFlags;
3339   return (F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask;
3340 }
3341 
3342 // See if instruction could potentially be a duplex candidate.
3343 // If so, return its group. Zero otherwise.
3344 HexagonII::CompoundGroup HexagonInstrInfo::getCompoundCandidateGroup(
3345       const MachineInstr &MI) const {
3346   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
3347 
3348   switch (MI.getOpcode()) {
3349   default:
3350     return HexagonII::HCG_None;
3351   //
3352   // Compound pairs.
3353   // "p0=cmp.eq(Rs16,Rt16); if (p0.new) jump:nt #r9:2"
3354   // "Rd16=#U6 ; jump #r9:2"
3355   // "Rd16=Rs16 ; jump #r9:2"
3356   //
3357   case Hexagon::C2_cmpeq:
3358   case Hexagon::C2_cmpgt:
3359   case Hexagon::C2_cmpgtu:
3360     DstReg = MI.getOperand(0).getReg();
3361     Src1Reg = MI.getOperand(1).getReg();
3362     Src2Reg = MI.getOperand(2).getReg();
3363     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3364         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3365         isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg))
3366       return HexagonII::HCG_A;
3367     break;
3368   case Hexagon::C2_cmpeqi:
3369   case Hexagon::C2_cmpgti:
3370   case Hexagon::C2_cmpgtui:
3371     // P0 = cmp.eq(Rs,#u2)
3372     DstReg = MI.getOperand(0).getReg();
3373     SrcReg = MI.getOperand(1).getReg();
3374     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3375         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3376         isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
3377         ((isUInt<5>(MI.getOperand(2).getImm())) ||
3378          (MI.getOperand(2).getImm() == -1)))
3379       return HexagonII::HCG_A;
3380     break;
3381   case Hexagon::A2_tfr:
3382     // Rd = Rs
3383     DstReg = MI.getOperand(0).getReg();
3384     SrcReg = MI.getOperand(1).getReg();
3385     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3386       return HexagonII::HCG_A;
3387     break;
3388   case Hexagon::A2_tfrsi:
3389     // Rd = #u6
3390     // Do not test for #u6 size since the const is getting extended
3391     // regardless and compound could be formed.
3392     DstReg = MI.getOperand(0).getReg();
3393     if (isIntRegForSubInst(DstReg))
3394       return HexagonII::HCG_A;
3395     break;
3396   case Hexagon::S2_tstbit_i:
3397     DstReg = MI.getOperand(0).getReg();
3398     Src1Reg = MI.getOperand(1).getReg();
3399     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3400         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3401         MI.getOperand(2).isImm() &&
3402         isIntRegForSubInst(Src1Reg) && (MI.getOperand(2).getImm() == 0))
3403       return HexagonII::HCG_A;
3404     break;
3405   // The fact that .new form is used pretty much guarantees
3406   // that predicate register will match. Nevertheless,
3407   // there could be some false positives without additional
3408   // checking.
3409   case Hexagon::J2_jumptnew:
3410   case Hexagon::J2_jumpfnew:
3411   case Hexagon::J2_jumptnewpt:
3412   case Hexagon::J2_jumpfnewpt:
3413     Src1Reg = MI.getOperand(0).getReg();
3414     if (Hexagon::PredRegsRegClass.contains(Src1Reg) &&
3415         (Hexagon::P0 == Src1Reg || Hexagon::P1 == Src1Reg))
3416       return HexagonII::HCG_B;
3417     break;
3418   // Transfer and jump:
3419   // Rd=#U6 ; jump #r9:2
3420   // Rd=Rs ; jump #r9:2
3421   // Do not test for jump range here.
3422   case Hexagon::J2_jump:
3423   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3424   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3425     return HexagonII::HCG_C;
3426     break;
3427   }
3428 
3429   return HexagonII::HCG_None;
3430 }
3431 
3432 
3433 // Returns -1 when there is no opcode found.
3434 unsigned HexagonInstrInfo::getCompoundOpcode(const MachineInstr &GA,
3435       const MachineInstr &GB) const {
3436   assert(getCompoundCandidateGroup(GA) == HexagonII::HCG_A);
3437   assert(getCompoundCandidateGroup(GB) == HexagonII::HCG_B);
3438   if ((GA.getOpcode() != Hexagon::C2_cmpeqi) ||
3439       (GB.getOpcode() != Hexagon::J2_jumptnew))
3440     return -1;
3441   unsigned DestReg = GA.getOperand(0).getReg();
3442   if (!GB.readsRegister(DestReg))
3443     return -1;
3444   if (DestReg == Hexagon::P0)
3445     return Hexagon::J4_cmpeqi_tp0_jump_nt;
3446   if (DestReg == Hexagon::P1)
3447     return Hexagon::J4_cmpeqi_tp1_jump_nt;
3448   return -1;
3449 }
3450 
3451 
3452 int HexagonInstrInfo::getCondOpcode(int Opc, bool invertPredicate) const {
3453   enum Hexagon::PredSense inPredSense;
3454   inPredSense = invertPredicate ? Hexagon::PredSense_false :
3455                                   Hexagon::PredSense_true;
3456   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
3457   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
3458     return CondOpcode;
3459 
3460   llvm_unreachable("Unexpected predicable instruction");
3461 }
3462 
3463 
3464 // Return the cur value instruction for a given store.
3465 int HexagonInstrInfo::getDotCurOp(const MachineInstr &MI) const {
3466   switch (MI.getOpcode()) {
3467   default: llvm_unreachable("Unknown .cur type");
3468   case Hexagon::V6_vL32b_pi:
3469     return Hexagon::V6_vL32b_cur_pi;
3470   case Hexagon::V6_vL32b_ai:
3471     return Hexagon::V6_vL32b_cur_ai;
3472   //128B
3473   case Hexagon::V6_vL32b_pi_128B:
3474     return Hexagon::V6_vL32b_cur_pi_128B;
3475   case Hexagon::V6_vL32b_ai_128B:
3476     return Hexagon::V6_vL32b_cur_ai_128B;
3477   }
3478   return 0;
3479 }
3480 
3481 
3482 
3483 // The diagram below shows the steps involved in the conversion of a predicated
3484 // store instruction to its .new predicated new-value form.
3485 //
3486 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
3487 //                ^           ^
3488 //               /             \ (not OK. it will cause new-value store to be
3489 //              /               X conditional on p0.new while R2 producer is
3490 //             /                 \ on p0)
3491 //            /                   \.
3492 //     p.new store                 p.old NV store
3493 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
3494 //            ^                  ^
3495 //             \                /
3496 //              \              /
3497 //               \            /
3498 //                 p.old store
3499 //             [if (p0)memw(R0+#0)=R2]
3500 //
3501 //
3502 // The following set of instructions further explains the scenario where
3503 // conditional new-value store becomes invalid when promoted to .new predicate
3504 // form.
3505 //
3506 // { 1) if (p0) r0 = add(r1, r2)
3507 //   2) p0 = cmp.eq(r3, #0) }
3508 //
3509 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
3510 // the first two instructions because in instr 1, r0 is conditional on old value
3511 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
3512 // is not valid for new-value stores.
3513 // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
3514 // from the "Conditional Store" list. Because a predicated new value store
3515 // would NOT be promoted to a double dot new store. See diagram below:
3516 // This function returns yes for those stores that are predicated but not
3517 // yet promoted to predicate dot new instructions.
3518 //
3519 //                          +---------------------+
3520 //                    /-----| if (p0) memw(..)=r0 |---------\~
3521 //                   ||     +---------------------+         ||
3522 //          promote  ||       /\       /\                   ||  promote
3523 //                   ||      /||\     /||\                  ||
3524 //                  \||/    demote     ||                  \||/
3525 //                   \/       ||       ||                   \/
3526 //       +-------------------------+   ||   +-------------------------+
3527 //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
3528 //       +-------------------------+   ||   +-------------------------+
3529 //                        ||           ||         ||
3530 //                        ||         demote      \||/
3531 //                      promote        ||         \/ NOT possible
3532 //                        ||           ||         /\~
3533 //                       \||/          ||        /||\~
3534 //                        \/           ||         ||
3535 //                      +-----------------------------+
3536 //                      | if (p0.new) memw(..)=r0.new |
3537 //                      +-----------------------------+
3538 //                           Double Dot New Store
3539 //
3540 // Returns the most basic instruction for the .new predicated instructions and
3541 // new-value stores.
3542 // For example, all of the following instructions will be converted back to the
3543 // same instruction:
3544 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
3545 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
3546 // 3) if (p0.new) memw(R0+#0) = R1      --->
3547 //
3548 // To understand the translation of instruction 1 to its original form, consider
3549 // a packet with 3 instructions.
3550 // { p0 = cmp.eq(R0,R1)
3551 //   if (p0.new) R2 = add(R3, R4)
3552 //   R5 = add (R3, R1)
3553 // }
3554 // if (p0) memw(R5+#0) = R2 <--- trying to include it in the previous packet
3555 //
3556 // This instruction can be part of the previous packet only if both p0 and R2
3557 // are promoted to .new values. This promotion happens in steps, first
3558 // predicate register is promoted to .new and in the next iteration R2 is
3559 // promoted. Therefore, in case of dependence check failure (due to R5) during
3560 // next iteration, it should be converted back to its most basic form.
3561 
3562 
3563 // Return the new value instruction for a given store.
3564 int HexagonInstrInfo::getDotNewOp(const MachineInstr &MI) const {
3565   int NVOpcode = Hexagon::getNewValueOpcode(MI.getOpcode());
3566   if (NVOpcode >= 0) // Valid new-value store instruction.
3567     return NVOpcode;
3568 
3569   switch (MI.getOpcode()) {
3570   default: llvm_unreachable("Unknown .new type");
3571   case Hexagon::S4_storerb_ur:
3572     return Hexagon::S4_storerbnew_ur;
3573 
3574   case Hexagon::S2_storerb_pci:
3575     return Hexagon::S2_storerb_pci;
3576 
3577   case Hexagon::S2_storeri_pci:
3578     return Hexagon::S2_storeri_pci;
3579 
3580   case Hexagon::S2_storerh_pci:
3581     return Hexagon::S2_storerh_pci;
3582 
3583   case Hexagon::S2_storerd_pci:
3584     return Hexagon::S2_storerd_pci;
3585 
3586   case Hexagon::S2_storerf_pci:
3587     return Hexagon::S2_storerf_pci;
3588 
3589   case Hexagon::V6_vS32b_ai:
3590     return Hexagon::V6_vS32b_new_ai;
3591 
3592   case Hexagon::V6_vS32b_pi:
3593     return Hexagon::V6_vS32b_new_pi;
3594 
3595   // 128B
3596   case Hexagon::V6_vS32b_ai_128B:
3597     return Hexagon::V6_vS32b_new_ai_128B;
3598 
3599   case Hexagon::V6_vS32b_pi_128B:
3600     return Hexagon::V6_vS32b_new_pi_128B;
3601   }
3602   return 0;
3603 }
3604 
3605 
3606 // Returns the opcode to use when converting MI, which is a conditional jump,
3607 // into a conditional instruction which uses the .new value of the predicate.
3608 // We also use branch probabilities to add a hint to the jump.
3609 int HexagonInstrInfo::getDotNewPredJumpOp(const MachineInstr &MI,
3610       const MachineBranchProbabilityInfo *MBPI) const {
3611   // We assume that block can have at most two successors.
3612   bool taken = false;
3613   const MachineBasicBlock *Src = MI.getParent();
3614   const MachineOperand &BrTarget = MI.getOperand(1);
3615   const MachineBasicBlock *Dst = BrTarget.getMBB();
3616 
3617   const BranchProbability Prediction = MBPI->getEdgeProbability(Src, Dst);
3618   if (Prediction >= BranchProbability(1,2))
3619     taken = true;
3620 
3621   switch (MI.getOpcode()) {
3622   case Hexagon::J2_jumpt:
3623     return taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
3624   case Hexagon::J2_jumpf:
3625     return taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
3626 
3627   default:
3628     llvm_unreachable("Unexpected jump instruction.");
3629   }
3630 }
3631 
3632 
3633 // Return .new predicate version for an instruction.
3634 int HexagonInstrInfo::getDotNewPredOp(const MachineInstr &MI,
3635       const MachineBranchProbabilityInfo *MBPI) const {
3636   int NewOpcode = Hexagon::getPredNewOpcode(MI.getOpcode());
3637   if (NewOpcode >= 0) // Valid predicate new instruction
3638     return NewOpcode;
3639 
3640   switch (MI.getOpcode()) {
3641   // Condtional Jumps
3642   case Hexagon::J2_jumpt:
3643   case Hexagon::J2_jumpf:
3644     return getDotNewPredJumpOp(MI, MBPI);
3645 
3646   default:
3647     assert(0 && "Unknown .new type");
3648   }
3649   return 0;
3650 }
3651 
3652 
3653 int HexagonInstrInfo::getDotOldOp(const int opc) const {
3654   int NewOp = opc;
3655   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
3656     NewOp = Hexagon::getPredOldOpcode(NewOp);
3657     assert(NewOp >= 0 &&
3658            "Couldn't change predicate new instruction to its old form.");
3659   }
3660 
3661   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
3662     NewOp = Hexagon::getNonNVStore(NewOp);
3663     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
3664   }
3665   return NewOp;
3666 }
3667 
3668 
3669 // See if instruction could potentially be a duplex candidate.
3670 // If so, return its group. Zero otherwise.
3671 HexagonII::SubInstructionGroup HexagonInstrInfo::getDuplexCandidateGroup(
3672       const MachineInstr &MI) const {
3673   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
3674   auto &HRI = getRegisterInfo();
3675 
3676   switch (MI.getOpcode()) {
3677   default:
3678     return HexagonII::HSIG_None;
3679   //
3680   // Group L1:
3681   //
3682   // Rd = memw(Rs+#u4:2)
3683   // Rd = memub(Rs+#u4:0)
3684   case Hexagon::L2_loadri_io:
3685     DstReg = MI.getOperand(0).getReg();
3686     SrcReg = MI.getOperand(1).getReg();
3687     // Special case this one from Group L2.
3688     // Rd = memw(r29+#u5:2)
3689     if (isIntRegForSubInst(DstReg)) {
3690       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
3691           HRI.getStackRegister() == SrcReg &&
3692           MI.getOperand(2).isImm() &&
3693           isShiftedUInt<5,2>(MI.getOperand(2).getImm()))
3694         return HexagonII::HSIG_L2;
3695       // Rd = memw(Rs+#u4:2)
3696       if (isIntRegForSubInst(SrcReg) &&
3697           (MI.getOperand(2).isImm() &&
3698           isShiftedUInt<4,2>(MI.getOperand(2).getImm())))
3699         return HexagonII::HSIG_L1;
3700     }
3701     break;
3702   case Hexagon::L2_loadrub_io:
3703     // Rd = memub(Rs+#u4:0)
3704     DstReg = MI.getOperand(0).getReg();
3705     SrcReg = MI.getOperand(1).getReg();
3706     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3707         MI.getOperand(2).isImm() && isUInt<4>(MI.getOperand(2).getImm()))
3708       return HexagonII::HSIG_L1;
3709     break;
3710   //
3711   // Group L2:
3712   //
3713   // Rd = memh/memuh(Rs+#u3:1)
3714   // Rd = memb(Rs+#u3:0)
3715   // Rd = memw(r29+#u5:2) - Handled above.
3716   // Rdd = memd(r29+#u5:3)
3717   // deallocframe
3718   // [if ([!]p0[.new])] dealloc_return
3719   // [if ([!]p0[.new])] jumpr r31
3720   case Hexagon::L2_loadrh_io:
3721   case Hexagon::L2_loadruh_io:
3722     // Rd = memh/memuh(Rs+#u3:1)
3723     DstReg = MI.getOperand(0).getReg();
3724     SrcReg = MI.getOperand(1).getReg();
3725     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3726         MI.getOperand(2).isImm() &&
3727         isShiftedUInt<3,1>(MI.getOperand(2).getImm()))
3728       return HexagonII::HSIG_L2;
3729     break;
3730   case Hexagon::L2_loadrb_io:
3731     // Rd = memb(Rs+#u3:0)
3732     DstReg = MI.getOperand(0).getReg();
3733     SrcReg = MI.getOperand(1).getReg();
3734     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3735         MI.getOperand(2).isImm() &&
3736         isUInt<3>(MI.getOperand(2).getImm()))
3737       return HexagonII::HSIG_L2;
3738     break;
3739   case Hexagon::L2_loadrd_io:
3740     // Rdd = memd(r29+#u5:3)
3741     DstReg = MI.getOperand(0).getReg();
3742     SrcReg = MI.getOperand(1).getReg();
3743     if (isDblRegForSubInst(DstReg, HRI) &&
3744         Hexagon::IntRegsRegClass.contains(SrcReg) &&
3745         HRI.getStackRegister() == SrcReg &&
3746         MI.getOperand(2).isImm() &&
3747         isShiftedUInt<5,3>(MI.getOperand(2).getImm()))
3748       return HexagonII::HSIG_L2;
3749     break;
3750   // dealloc_return is not documented in Hexagon Manual, but marked
3751   // with A_SUBINSN attribute in iset_v4classic.py.
3752   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3753   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3754   case Hexagon::L4_return:
3755   case Hexagon::L2_deallocframe:
3756     return HexagonII::HSIG_L2;
3757   case Hexagon::EH_RETURN_JMPR:
3758   case Hexagon::PS_jmpret:
3759     // jumpr r31
3760     // Actual form JMPR %PC<imp-def>, %R31<imp-use>, %R0<imp-use,internal>.
3761     DstReg = MI.getOperand(0).getReg();
3762     if (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg))
3763       return HexagonII::HSIG_L2;
3764     break;
3765   case Hexagon::PS_jmprett:
3766   case Hexagon::PS_jmpretf:
3767   case Hexagon::PS_jmprettnewpt:
3768   case Hexagon::PS_jmpretfnewpt:
3769   case Hexagon::PS_jmprettnew:
3770   case Hexagon::PS_jmpretfnew:
3771     DstReg = MI.getOperand(1).getReg();
3772     SrcReg = MI.getOperand(0).getReg();
3773     // [if ([!]p0[.new])] jumpr r31
3774     if ((Hexagon::PredRegsRegClass.contains(SrcReg) &&
3775         (Hexagon::P0 == SrcReg)) &&
3776         (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg)))
3777       return HexagonII::HSIG_L2;
3778     break;
3779   case Hexagon::L4_return_t :
3780   case Hexagon::L4_return_f :
3781   case Hexagon::L4_return_tnew_pnt :
3782   case Hexagon::L4_return_fnew_pnt :
3783   case Hexagon::L4_return_tnew_pt :
3784   case Hexagon::L4_return_fnew_pt :
3785     // [if ([!]p0[.new])] dealloc_return
3786     SrcReg = MI.getOperand(0).getReg();
3787     if (Hexagon::PredRegsRegClass.contains(SrcReg) && (Hexagon::P0 == SrcReg))
3788       return HexagonII::HSIG_L2;
3789     break;
3790   //
3791   // Group S1:
3792   //
3793   // memw(Rs+#u4:2) = Rt
3794   // memb(Rs+#u4:0) = Rt
3795   case Hexagon::S2_storeri_io:
3796     // Special case this one from Group S2.
3797     // memw(r29+#u5:2) = Rt
3798     Src1Reg = MI.getOperand(0).getReg();
3799     Src2Reg = MI.getOperand(2).getReg();
3800     if (Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3801         isIntRegForSubInst(Src2Reg) &&
3802         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3803         isShiftedUInt<5,2>(MI.getOperand(1).getImm()))
3804       return HexagonII::HSIG_S2;
3805     // memw(Rs+#u4:2) = Rt
3806     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3807         MI.getOperand(1).isImm() &&
3808         isShiftedUInt<4,2>(MI.getOperand(1).getImm()))
3809       return HexagonII::HSIG_S1;
3810     break;
3811   case Hexagon::S2_storerb_io:
3812     // memb(Rs+#u4:0) = Rt
3813     Src1Reg = MI.getOperand(0).getReg();
3814     Src2Reg = MI.getOperand(2).getReg();
3815     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3816         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()))
3817       return HexagonII::HSIG_S1;
3818     break;
3819   //
3820   // Group S2:
3821   //
3822   // memh(Rs+#u3:1) = Rt
3823   // memw(r29+#u5:2) = Rt
3824   // memd(r29+#s6:3) = Rtt
3825   // memw(Rs+#u4:2) = #U1
3826   // memb(Rs+#u4) = #U1
3827   // allocframe(#u5:3)
3828   case Hexagon::S2_storerh_io:
3829     // memh(Rs+#u3:1) = Rt
3830     Src1Reg = MI.getOperand(0).getReg();
3831     Src2Reg = MI.getOperand(2).getReg();
3832     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3833         MI.getOperand(1).isImm() &&
3834         isShiftedUInt<3,1>(MI.getOperand(1).getImm()))
3835       return HexagonII::HSIG_S1;
3836     break;
3837   case Hexagon::S2_storerd_io:
3838     // memd(r29+#s6:3) = Rtt
3839     Src1Reg = MI.getOperand(0).getReg();
3840     Src2Reg = MI.getOperand(2).getReg();
3841     if (isDblRegForSubInst(Src2Reg, HRI) &&
3842         Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3843         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3844         isShiftedInt<6,3>(MI.getOperand(1).getImm()))
3845       return HexagonII::HSIG_S2;
3846     break;
3847   case Hexagon::S4_storeiri_io:
3848     // memw(Rs+#u4:2) = #U1
3849     Src1Reg = MI.getOperand(0).getReg();
3850     if (isIntRegForSubInst(Src1Reg) && MI.getOperand(1).isImm() &&
3851         isShiftedUInt<4,2>(MI.getOperand(1).getImm()) &&
3852         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
3853       return HexagonII::HSIG_S2;
3854     break;
3855   case Hexagon::S4_storeirb_io:
3856     // memb(Rs+#u4) = #U1
3857     Src1Reg = MI.getOperand(0).getReg();
3858     if (isIntRegForSubInst(Src1Reg) &&
3859         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()) &&
3860         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
3861       return HexagonII::HSIG_S2;
3862     break;
3863   case Hexagon::S2_allocframe:
3864     if (MI.getOperand(0).isImm() &&
3865         isShiftedUInt<5,3>(MI.getOperand(0).getImm()))
3866       return HexagonII::HSIG_S1;
3867     break;
3868   //
3869   // Group A:
3870   //
3871   // Rx = add(Rx,#s7)
3872   // Rd = Rs
3873   // Rd = #u6
3874   // Rd = #-1
3875   // if ([!]P0[.new]) Rd = #0
3876   // Rd = add(r29,#u6:2)
3877   // Rx = add(Rx,Rs)
3878   // P0 = cmp.eq(Rs,#u2)
3879   // Rdd = combine(#0,Rs)
3880   // Rdd = combine(Rs,#0)
3881   // Rdd = combine(#u2,#U2)
3882   // Rd = add(Rs,#1)
3883   // Rd = add(Rs,#-1)
3884   // Rd = sxth/sxtb/zxtb/zxth(Rs)
3885   // Rd = and(Rs,#1)
3886   case Hexagon::A2_addi:
3887     DstReg = MI.getOperand(0).getReg();
3888     SrcReg = MI.getOperand(1).getReg();
3889     if (isIntRegForSubInst(DstReg)) {
3890       // Rd = add(r29,#u6:2)
3891       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
3892         HRI.getStackRegister() == SrcReg && MI.getOperand(2).isImm() &&
3893         isShiftedUInt<6,2>(MI.getOperand(2).getImm()))
3894         return HexagonII::HSIG_A;
3895       // Rx = add(Rx,#s7)
3896       if ((DstReg == SrcReg) && MI.getOperand(2).isImm() &&
3897           isInt<7>(MI.getOperand(2).getImm()))
3898         return HexagonII::HSIG_A;
3899       // Rd = add(Rs,#1)
3900       // Rd = add(Rs,#-1)
3901       if (isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
3902           ((MI.getOperand(2).getImm() == 1) ||
3903           (MI.getOperand(2).getImm() == -1)))
3904         return HexagonII::HSIG_A;
3905     }
3906     break;
3907   case Hexagon::A2_add:
3908     // Rx = add(Rx,Rs)
3909     DstReg = MI.getOperand(0).getReg();
3910     Src1Reg = MI.getOperand(1).getReg();
3911     Src2Reg = MI.getOperand(2).getReg();
3912     if (isIntRegForSubInst(DstReg) && (DstReg == Src1Reg) &&
3913         isIntRegForSubInst(Src2Reg))
3914       return HexagonII::HSIG_A;
3915     break;
3916   case Hexagon::A2_andir:
3917     // Same as zxtb.
3918     // Rd16=and(Rs16,#255)
3919     // Rd16=and(Rs16,#1)
3920     DstReg = MI.getOperand(0).getReg();
3921     SrcReg = MI.getOperand(1).getReg();
3922     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3923         MI.getOperand(2).isImm() &&
3924         ((MI.getOperand(2).getImm() == 1) ||
3925         (MI.getOperand(2).getImm() == 255)))
3926       return HexagonII::HSIG_A;
3927     break;
3928   case Hexagon::A2_tfr:
3929     // Rd = Rs
3930     DstReg = MI.getOperand(0).getReg();
3931     SrcReg = MI.getOperand(1).getReg();
3932     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3933       return HexagonII::HSIG_A;
3934     break;
3935   case Hexagon::A2_tfrsi:
3936     // Rd = #u6
3937     // Do not test for #u6 size since the const is getting extended
3938     // regardless and compound could be formed.
3939     // Rd = #-1
3940     DstReg = MI.getOperand(0).getReg();
3941     if (isIntRegForSubInst(DstReg))
3942       return HexagonII::HSIG_A;
3943     break;
3944   case Hexagon::C2_cmoveit:
3945   case Hexagon::C2_cmovenewit:
3946   case Hexagon::C2_cmoveif:
3947   case Hexagon::C2_cmovenewif:
3948     // if ([!]P0[.new]) Rd = #0
3949     // Actual form:
3950     // %R16<def> = C2_cmovenewit %P0<internal>, 0, %R16<imp-use,undef>;
3951     DstReg = MI.getOperand(0).getReg();
3952     SrcReg = MI.getOperand(1).getReg();
3953     if (isIntRegForSubInst(DstReg) &&
3954         Hexagon::PredRegsRegClass.contains(SrcReg) && Hexagon::P0 == SrcReg &&
3955         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0)
3956       return HexagonII::HSIG_A;
3957     break;
3958   case Hexagon::C2_cmpeqi:
3959     // P0 = cmp.eq(Rs,#u2)
3960     DstReg = MI.getOperand(0).getReg();
3961     SrcReg = MI.getOperand(1).getReg();
3962     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3963         Hexagon::P0 == DstReg && isIntRegForSubInst(SrcReg) &&
3964         MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm()))
3965       return HexagonII::HSIG_A;
3966     break;
3967   case Hexagon::A2_combineii:
3968   case Hexagon::A4_combineii:
3969     // Rdd = combine(#u2,#U2)
3970     DstReg = MI.getOperand(0).getReg();
3971     if (isDblRegForSubInst(DstReg, HRI) &&
3972         ((MI.getOperand(1).isImm() && isUInt<2>(MI.getOperand(1).getImm())) ||
3973         (MI.getOperand(1).isGlobal() &&
3974         isUInt<2>(MI.getOperand(1).getOffset()))) &&
3975         ((MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm())) ||
3976         (MI.getOperand(2).isGlobal() &&
3977         isUInt<2>(MI.getOperand(2).getOffset()))))
3978       return HexagonII::HSIG_A;
3979     break;
3980   case Hexagon::A4_combineri:
3981     // Rdd = combine(Rs,#0)
3982     DstReg = MI.getOperand(0).getReg();
3983     SrcReg = MI.getOperand(1).getReg();
3984     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
3985         ((MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) ||
3986         (MI.getOperand(2).isGlobal() && MI.getOperand(2).getOffset() == 0)))
3987       return HexagonII::HSIG_A;
3988     break;
3989   case Hexagon::A4_combineir:
3990     // Rdd = combine(#0,Rs)
3991     DstReg = MI.getOperand(0).getReg();
3992     SrcReg = MI.getOperand(2).getReg();
3993     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
3994         ((MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) ||
3995         (MI.getOperand(1).isGlobal() && MI.getOperand(1).getOffset() == 0)))
3996       return HexagonII::HSIG_A;
3997     break;
3998   case Hexagon::A2_sxtb:
3999   case Hexagon::A2_sxth:
4000   case Hexagon::A2_zxtb:
4001   case Hexagon::A2_zxth:
4002     // Rd = sxth/sxtb/zxtb/zxth(Rs)
4003     DstReg = MI.getOperand(0).getReg();
4004     SrcReg = MI.getOperand(1).getReg();
4005     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
4006       return HexagonII::HSIG_A;
4007     break;
4008   }
4009 
4010   return HexagonII::HSIG_None;
4011 }
4012 
4013 
4014 short HexagonInstrInfo::getEquivalentHWInstr(const MachineInstr &MI) const {
4015   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Real);
4016 }
4017 
4018 
4019 // Return first non-debug instruction in the basic block.
4020 MachineInstr *HexagonInstrInfo::getFirstNonDbgInst(MachineBasicBlock *BB)
4021       const {
4022   for (auto MII = BB->instr_begin(), End = BB->instr_end(); MII != End; MII++) {
4023     MachineInstr &MI = *MII;
4024     if (MI.isDebugValue())
4025       continue;
4026     return &MI;
4027   }
4028   return nullptr;
4029 }
4030 
4031 
4032 unsigned HexagonInstrInfo::getInstrTimingClassLatency(
4033       const InstrItineraryData *ItinData, const MachineInstr &MI) const {
4034   // Default to one cycle for no itinerary. However, an "empty" itinerary may
4035   // still have a MinLatency property, which getStageLatency checks.
4036   if (!ItinData)
4037     return getInstrLatency(ItinData, MI);
4038 
4039   // Get the latency embedded in the itinerary. If we're not using timing class
4040   // latencies or if we using BSB scheduling, then restrict the maximum latency
4041   // to 1 (that is, either 0 or 1).
4042   if (MI.isTransient())
4043     return 0;
4044   unsigned Latency = ItinData->getStageLatency(MI.getDesc().getSchedClass());
4045   if (!EnableTimingClassLatency ||
4046       MI.getParent()->getParent()->getSubtarget<HexagonSubtarget>().
4047       useBSBScheduling())
4048     if (Latency > 1)
4049       Latency = 1;
4050   return Latency;
4051 }
4052 
4053 
4054 // inverts the predication logic.
4055 // p -> NotP
4056 // NotP -> P
4057 bool HexagonInstrInfo::getInvertedPredSense(
4058       SmallVectorImpl<MachineOperand> &Cond) const {
4059   if (Cond.empty())
4060     return false;
4061   unsigned Opc = getInvertedPredicatedOpcode(Cond[0].getImm());
4062   Cond[0].setImm(Opc);
4063   return true;
4064 }
4065 
4066 
4067 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
4068   int InvPredOpcode;
4069   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
4070                                         : Hexagon::getTruePredOpcode(Opc);
4071   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
4072     return InvPredOpcode;
4073 
4074   llvm_unreachable("Unexpected predicated instruction");
4075 }
4076 
4077 
4078 // Returns the max value that doesn't need to be extended.
4079 int HexagonInstrInfo::getMaxValue(const MachineInstr &MI) const {
4080   const uint64_t F = MI.getDesc().TSFlags;
4081   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
4082                     & HexagonII::ExtentSignedMask;
4083   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
4084                     & HexagonII::ExtentBitsMask;
4085 
4086   if (isSigned) // if value is signed
4087     return ~(-1U << (bits - 1));
4088   else
4089     return ~(-1U << bits);
4090 }
4091 
4092 
4093 unsigned HexagonInstrInfo::getMemAccessSize(const MachineInstr &MI) const {
4094   const uint64_t F = MI.getDesc().TSFlags;
4095   return (F >> HexagonII::MemAccessSizePos) & HexagonII::MemAccesSizeMask;
4096 }
4097 
4098 
4099 // Returns the min value that doesn't need to be extended.
4100 int HexagonInstrInfo::getMinValue(const MachineInstr &MI) const {
4101   const uint64_t F = MI.getDesc().TSFlags;
4102   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
4103                     & HexagonII::ExtentSignedMask;
4104   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
4105                     & HexagonII::ExtentBitsMask;
4106 
4107   if (isSigned) // if value is signed
4108     return -1U << (bits - 1);
4109   else
4110     return 0;
4111 }
4112 
4113 
4114 // Returns opcode of the non-extended equivalent instruction.
4115 short HexagonInstrInfo::getNonExtOpcode(const MachineInstr &MI) const {
4116   // Check if the instruction has a register form that uses register in place
4117   // of the extended operand, if so return that as the non-extended form.
4118   short NonExtOpcode = Hexagon::getRegForm(MI.getOpcode());
4119     if (NonExtOpcode >= 0)
4120       return NonExtOpcode;
4121 
4122   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
4123     // Check addressing mode and retrieve non-ext equivalent instruction.
4124     switch (getAddrMode(MI)) {
4125     case HexagonII::Absolute :
4126       return Hexagon::getBaseWithImmOffset(MI.getOpcode());
4127     case HexagonII::BaseImmOffset :
4128       return Hexagon::getBaseWithRegOffset(MI.getOpcode());
4129     case HexagonII::BaseLongOffset:
4130       return Hexagon::getRegShlForm(MI.getOpcode());
4131 
4132     default:
4133       return -1;
4134     }
4135   }
4136   return -1;
4137 }
4138 
4139 
4140 bool HexagonInstrInfo::getPredReg(ArrayRef<MachineOperand> Cond,
4141       unsigned &PredReg, unsigned &PredRegPos, unsigned &PredRegFlags) const {
4142   if (Cond.empty())
4143     return false;
4144   assert(Cond.size() == 2);
4145   if (isNewValueJump(Cond[0].getImm()) || Cond[1].isMBB()) {
4146     DEBUG(dbgs() << "No predregs for new-value jumps/endloop");
4147     return false;
4148   }
4149   PredReg = Cond[1].getReg();
4150   PredRegPos = 1;
4151   // See IfConversion.cpp why we add RegState::Implicit | RegState::Undef
4152   PredRegFlags = 0;
4153   if (Cond[1].isImplicit())
4154     PredRegFlags = RegState::Implicit;
4155   if (Cond[1].isUndef())
4156     PredRegFlags |= RegState::Undef;
4157   return true;
4158 }
4159 
4160 
4161 short HexagonInstrInfo::getPseudoInstrPair(const MachineInstr &MI) const {
4162   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Pseudo);
4163 }
4164 
4165 
4166 short HexagonInstrInfo::getRegForm(const MachineInstr &MI) const {
4167   return Hexagon::getRegForm(MI.getOpcode());
4168 }
4169 
4170 
4171 // Return the number of bytes required to encode the instruction.
4172 // Hexagon instructions are fixed length, 4 bytes, unless they
4173 // use a constant extender, which requires another 4 bytes.
4174 // For debug instructions and prolog labels, return 0.
4175 unsigned HexagonInstrInfo::getSize(const MachineInstr &MI) const {
4176   if (MI.isDebugValue() || MI.isPosition())
4177     return 0;
4178 
4179   unsigned Size = MI.getDesc().getSize();
4180   if (!Size)
4181     // Assume the default insn size in case it cannot be determined
4182     // for whatever reason.
4183     Size = HEXAGON_INSTR_SIZE;
4184 
4185   if (isConstExtended(MI) || isExtended(MI))
4186     Size += HEXAGON_INSTR_SIZE;
4187 
4188   // Try and compute number of instructions in asm.
4189   if (BranchRelaxAsmLarge && MI.getOpcode() == Hexagon::INLINEASM) {
4190     const MachineBasicBlock &MBB = *MI.getParent();
4191     const MachineFunction *MF = MBB.getParent();
4192     const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
4193 
4194     // Count the number of register definitions to find the asm string.
4195     unsigned NumDefs = 0;
4196     for (; MI.getOperand(NumDefs).isReg() && MI.getOperand(NumDefs).isDef();
4197          ++NumDefs)
4198       assert(NumDefs != MI.getNumOperands()-2 && "No asm string?");
4199 
4200     assert(MI.getOperand(NumDefs).isSymbol() && "No asm string?");
4201     // Disassemble the AsmStr and approximate number of instructions.
4202     const char *AsmStr = MI.getOperand(NumDefs).getSymbolName();
4203     Size = getInlineAsmLength(AsmStr, *MAI);
4204   }
4205 
4206   return Size;
4207 }
4208 
4209 
4210 uint64_t HexagonInstrInfo::getType(const MachineInstr &MI) const {
4211   const uint64_t F = MI.getDesc().TSFlags;
4212   return (F >> HexagonII::TypePos) & HexagonII::TypeMask;
4213 }
4214 
4215 
4216 unsigned HexagonInstrInfo::getUnits(const MachineInstr &MI) const {
4217   const TargetSubtargetInfo &ST = MI.getParent()->getParent()->getSubtarget();
4218   const InstrItineraryData &II = *ST.getInstrItineraryData();
4219   const InstrStage &IS = *II.beginStage(MI.getDesc().getSchedClass());
4220 
4221   return IS.getUnits();
4222 }
4223 
4224 
4225 unsigned HexagonInstrInfo::getValidSubTargets(const unsigned Opcode) const {
4226   const uint64_t F = get(Opcode).TSFlags;
4227   return (F >> HexagonII::validSubTargetPos) & HexagonII::validSubTargetMask;
4228 }
4229 
4230 
4231 // Calculate size of the basic block without debug instructions.
4232 unsigned HexagonInstrInfo::nonDbgBBSize(const MachineBasicBlock *BB) const {
4233   return nonDbgMICount(BB->instr_begin(), BB->instr_end());
4234 }
4235 
4236 
4237 unsigned HexagonInstrInfo::nonDbgBundleSize(
4238       MachineBasicBlock::const_iterator BundleHead) const {
4239   assert(BundleHead->isBundle() && "Not a bundle header");
4240   auto MII = BundleHead.getInstrIterator();
4241   // Skip the bundle header.
4242   return nonDbgMICount(++MII, getBundleEnd(*BundleHead));
4243 }
4244 
4245 
4246 /// immediateExtend - Changes the instruction in place to one using an immediate
4247 /// extender.
4248 void HexagonInstrInfo::immediateExtend(MachineInstr &MI) const {
4249   assert((isExtendable(MI)||isConstExtended(MI)) &&
4250                                "Instruction must be extendable");
4251   // Find which operand is extendable.
4252   short ExtOpNum = getCExtOpNum(MI);
4253   MachineOperand &MO = MI.getOperand(ExtOpNum);
4254   // This needs to be something we understand.
4255   assert((MO.isMBB() || MO.isImm()) &&
4256          "Branch with unknown extendable field type");
4257   // Mark given operand as extended.
4258   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
4259 }
4260 
4261 
4262 bool HexagonInstrInfo::invertAndChangeJumpTarget(
4263       MachineInstr &MI, MachineBasicBlock *NewTarget) const {
4264   DEBUG(dbgs() << "\n[invertAndChangeJumpTarget] to BB#"
4265                << NewTarget->getNumber(); MI.dump(););
4266   assert(MI.isBranch());
4267   unsigned NewOpcode = getInvertedPredicatedOpcode(MI.getOpcode());
4268   int TargetPos = MI.getNumOperands() - 1;
4269   // In general branch target is the last operand,
4270   // but some implicit defs added at the end might change it.
4271   while ((TargetPos > -1) && !MI.getOperand(TargetPos).isMBB())
4272     --TargetPos;
4273   assert((TargetPos >= 0) && MI.getOperand(TargetPos).isMBB());
4274   MI.getOperand(TargetPos).setMBB(NewTarget);
4275   if (EnableBranchPrediction && isPredicatedNew(MI)) {
4276     NewOpcode = reversePrediction(NewOpcode);
4277   }
4278   MI.setDesc(get(NewOpcode));
4279   return true;
4280 }
4281 
4282 
4283 void HexagonInstrInfo::genAllInsnTimingClasses(MachineFunction &MF) const {
4284   /* +++ The code below is used to generate complete set of Hexagon Insn +++ */
4285   MachineFunction::iterator A = MF.begin();
4286   MachineBasicBlock &B = *A;
4287   MachineBasicBlock::iterator I = B.begin();
4288   DebugLoc DL = I->getDebugLoc();
4289   MachineInstr *NewMI;
4290 
4291   for (unsigned insn = TargetOpcode::GENERIC_OP_END+1;
4292        insn < Hexagon::INSTRUCTION_LIST_END; ++insn) {
4293     NewMI = BuildMI(B, I, DL, get(insn));
4294     DEBUG(dbgs() << "\n" << getName(NewMI->getOpcode()) <<
4295           "  Class: " << NewMI->getDesc().getSchedClass());
4296     NewMI->eraseFromParent();
4297   }
4298   /* --- The code above is used to generate complete set of Hexagon Insn --- */
4299 }
4300 
4301 
4302 // inverts the predication logic.
4303 // p -> NotP
4304 // NotP -> P
4305 bool HexagonInstrInfo::reversePredSense(MachineInstr &MI) const {
4306   DEBUG(dbgs() << "\nTrying to reverse pred. sense of:"; MI.dump());
4307   MI.setDesc(get(getInvertedPredicatedOpcode(MI.getOpcode())));
4308   return true;
4309 }
4310 
4311 
4312 // Reverse the branch prediction.
4313 unsigned HexagonInstrInfo::reversePrediction(unsigned Opcode) const {
4314   int PredRevOpcode = -1;
4315   if (isPredictedTaken(Opcode))
4316     PredRevOpcode = Hexagon::notTakenBranchPrediction(Opcode);
4317   else
4318     PredRevOpcode = Hexagon::takenBranchPrediction(Opcode);
4319   assert(PredRevOpcode > 0);
4320   return PredRevOpcode;
4321 }
4322 
4323 
4324 // TODO: Add more rigorous validation.
4325 bool HexagonInstrInfo::validateBranchCond(const ArrayRef<MachineOperand> &Cond)
4326       const {
4327   return Cond.empty() || (Cond[0].isImm() && (Cond.size() != 1));
4328 }
4329 
4330 
4331 short HexagonInstrInfo::xformRegToImmOffset(const MachineInstr &MI) const {
4332   return Hexagon::xformRegToImmOffset(MI.getOpcode());
4333 }
4334