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