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