Pass BranchProbability/BlockMass by value instead of const& as they are small. NFC.
[oota-llvm.git] / lib / Target / Hexagon / HexagonInstrInfo.cpp
1 //===-- HexagonInstrInfo.cpp - Hexagon Instruction Information ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the Hexagon implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "HexagonInstrInfo.h"
15 #include "Hexagon.h"
16 #include "HexagonRegisterInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/DFAPacketizer.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "hexagon-instrinfo"
33
34 #define GET_INSTRINFO_CTOR_DTOR
35 #define GET_INSTRMAP_INFO
36 #include "HexagonGenInstrInfo.inc"
37 #include "HexagonGenDFAPacketizer.inc"
38
39 ///
40 /// Constants for Hexagon instructions.
41 ///
42 const int Hexagon_MEMW_OFFSET_MAX = 4095;
43 const int Hexagon_MEMW_OFFSET_MIN = -4096;
44 const int Hexagon_MEMD_OFFSET_MAX = 8191;
45 const int Hexagon_MEMD_OFFSET_MIN = -8192;
46 const int Hexagon_MEMH_OFFSET_MAX = 2047;
47 const int Hexagon_MEMH_OFFSET_MIN = -2048;
48 const int Hexagon_MEMB_OFFSET_MAX = 1023;
49 const int Hexagon_MEMB_OFFSET_MIN = -1024;
50 const int Hexagon_ADDI_OFFSET_MAX = 32767;
51 const int Hexagon_ADDI_OFFSET_MIN = -32768;
52 const int Hexagon_MEMD_AUTOINC_MAX = 56;
53 const int Hexagon_MEMD_AUTOINC_MIN = -64;
54 const int Hexagon_MEMW_AUTOINC_MAX = 28;
55 const int Hexagon_MEMW_AUTOINC_MIN = -32;
56 const int Hexagon_MEMH_AUTOINC_MAX = 14;
57 const int Hexagon_MEMH_AUTOINC_MIN = -16;
58 const int Hexagon_MEMB_AUTOINC_MAX = 7;
59 const int Hexagon_MEMB_AUTOINC_MIN = -8;
60
61 // Pin the vtable to this file.
62 void HexagonInstrInfo::anchor() {}
63
64 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
65     : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
66       RI(), Subtarget(ST) {}
67
68 /// isLoadFromStackSlot - If the specified machine instruction is a direct
69 /// load from a stack slot, return the virtual or physical register number of
70 /// the destination along with the FrameIndex of the loaded stack slot.  If
71 /// not, return 0.  This predicate must return 0 if the instruction has
72 /// any side effects other than loading from the stack slot.
73 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
74                                              int &FrameIndex) const {
75
76
77   switch (MI->getOpcode()) {
78   default: break;
79   case Hexagon::L2_loadri_io:
80   case Hexagon::L2_loadrd_io:
81   case Hexagon::L2_loadrh_io:
82   case Hexagon::L2_loadrb_io:
83   case Hexagon::L2_loadrub_io:
84     if (MI->getOperand(2).isFI() &&
85         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
86       FrameIndex = MI->getOperand(2).getIndex();
87       return MI->getOperand(0).getReg();
88     }
89     break;
90   }
91   return 0;
92 }
93
94
95 /// isStoreToStackSlot - If the specified machine instruction is a direct
96 /// store to a stack slot, return the virtual or physical register number of
97 /// the source reg along with the FrameIndex of the loaded stack slot.  If
98 /// not, return 0.  This predicate must return 0 if the instruction has
99 /// any side effects other than storing to the stack slot.
100 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
101                                             int &FrameIndex) const {
102   switch (MI->getOpcode()) {
103   default: break;
104   case Hexagon::S2_storeri_io:
105   case Hexagon::S2_storerd_io:
106   case Hexagon::S2_storerh_io:
107   case Hexagon::S2_storerb_io:
108     if (MI->getOperand(2).isFI() &&
109         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
110       FrameIndex = MI->getOperand(0).getIndex();
111       return MI->getOperand(2).getReg();
112     }
113     break;
114   }
115   return 0;
116 }
117
118 // Find the hardware loop instruction used to set-up the specified loop.
119 // On Hexagon, we have two instructions used to set-up the hardware loop
120 // (LOOP0, LOOP1) with corresponding endloop (ENDLOOP0, ENDLOOP1) instructions
121 // to indicate the end of a loop.
122 static MachineInstr *
123 findLoopInstr(MachineBasicBlock *BB, int EndLoopOp,
124               SmallPtrSet<MachineBasicBlock *, 8> &Visited) {
125   int LOOPi;
126   int LOOPr;
127   if (EndLoopOp == Hexagon::ENDLOOP0) {
128     LOOPi = Hexagon::J2_loop0i;
129     LOOPr = Hexagon::J2_loop0r;
130   } else { // EndLoopOp == Hexagon::EndLOOP1
131     LOOPi = Hexagon::J2_loop1i;
132     LOOPr = Hexagon::J2_loop1r;
133   }
134
135   // The loop set-up instruction will be in a predecessor block
136   for (MachineBasicBlock::pred_iterator PB = BB->pred_begin(),
137          PE = BB->pred_end(); PB != PE; ++PB) {
138     // If this has been visited, already skip it.
139     if (!Visited.insert(*PB).second)
140       continue;
141     if (*PB == BB)
142       continue;
143     for (MachineBasicBlock::reverse_instr_iterator I = (*PB)->instr_rbegin(),
144            E = (*PB)->instr_rend(); I != E; ++I) {
145       int Opc = I->getOpcode();
146       if (Opc == LOOPi || Opc == LOOPr)
147         return &*I;
148       // We've reached a different loop, which means the loop0 has been removed.
149       if (Opc == EndLoopOp)
150         return 0;
151     }
152     // Check the predecessors for the LOOP instruction.
153     MachineInstr *loop = findLoopInstr(*PB, EndLoopOp, Visited);
154     if (loop)
155       return loop;
156   }
157   return 0;
158 }
159
160 unsigned HexagonInstrInfo::InsertBranch(
161     MachineBasicBlock &MBB,MachineBasicBlock *TBB, MachineBasicBlock *FBB,
162     ArrayRef<MachineOperand> Cond, DebugLoc DL) const {
163
164   Opcode_t BOpc   = Hexagon::J2_jump;
165   Opcode_t BccOpc = Hexagon::J2_jumpt;
166
167   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
168
169   // Check if ReverseBranchCondition has asked to reverse this branch
170   // If we want to reverse the branch an odd number of times, we want
171   // J2_jumpf.
172   if (!Cond.empty() && Cond[0].isImm())
173     BccOpc = Cond[0].getImm();
174
175   if (!FBB) {
176     if (Cond.empty()) {
177       // Due to a bug in TailMerging/CFG Optimization, we need to add a
178       // special case handling of a predicated jump followed by an
179       // unconditional jump. If not, Tail Merging and CFG Optimization go
180       // into an infinite loop.
181       MachineBasicBlock *NewTBB, *NewFBB;
182       SmallVector<MachineOperand, 4> Cond;
183       MachineInstr *Term = MBB.getFirstTerminator();
184       if (Term != MBB.end() && isPredicated(Term) &&
185           !AnalyzeBranch(MBB, NewTBB, NewFBB, Cond, false)) {
186         MachineBasicBlock *NextBB =
187           std::next(MachineFunction::iterator(&MBB));
188         if (NewTBB == NextBB) {
189           ReverseBranchCondition(Cond);
190           RemoveBranch(MBB);
191           return InsertBranch(MBB, TBB, nullptr, Cond, DL);
192         }
193       }
194       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
195     } else if (isEndLoopN(Cond[0].getImm())) {
196       int EndLoopOp = Cond[0].getImm();
197       assert(Cond[1].isMBB());
198       // Since we're adding an ENDLOOP, there better be a LOOP instruction.
199       // Check for it, and change the BB target if needed.
200       SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
201       MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, VisitedBBs);
202       assert(Loop != 0 && "Inserting an ENDLOOP without a LOOP");
203       Loop->getOperand(0).setMBB(TBB);
204       // Add the ENDLOOP after the finding the LOOP0.
205       BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
206     } else if (isNewValueJump(Cond[0].getImm())) {
207       assert((Cond.size() == 3) && "Only supporting rr/ri version of nvjump");
208       // New value jump
209       // (ins IntRegs:$src1, IntRegs:$src2, brtarget:$offset)
210       // (ins IntRegs:$src1, u5Imm:$src2, brtarget:$offset)
211       unsigned Flags1 = getUndefRegState(Cond[1].isUndef());
212       DEBUG(dbgs() << "\nInserting NVJump for BB#" << MBB.getNumber(););
213       if (Cond[2].isReg()) {
214         unsigned Flags2 = getUndefRegState(Cond[2].isUndef());
215         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
216           addReg(Cond[2].getReg(), Flags2).addMBB(TBB);
217       } else if(Cond[2].isImm()) {
218         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
219           addImm(Cond[2].getImm()).addMBB(TBB);
220       } else
221         llvm_unreachable("Invalid condition for branching");
222     } else {
223       assert((Cond.size() == 2) && "Malformed cond vector");
224       const MachineOperand &RO = Cond[1];
225       unsigned Flags = getUndefRegState(RO.isUndef());
226       BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
227     }
228     return 1;
229   }
230   assert((!Cond.empty()) &&
231          "Cond. cannot be empty when multiple branchings are required");
232   assert((!isNewValueJump(Cond[0].getImm())) &&
233          "NV-jump cannot be inserted with another branch");
234   // Special case for hardware loops.  The condition is a basic block.
235   if (isEndLoopN(Cond[0].getImm())) {
236     int EndLoopOp = Cond[0].getImm();
237     assert(Cond[1].isMBB());
238     // Since we're adding an ENDLOOP, there better be a LOOP instruction.
239     // Check for it, and change the BB target if needed.
240     SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
241     MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, VisitedBBs);
242     assert(Loop != 0 && "Inserting an ENDLOOP without a LOOP");
243     Loop->getOperand(0).setMBB(TBB);
244     // Add the ENDLOOP after the finding the LOOP0.
245     BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
246   } else {
247     const MachineOperand &RO = Cond[1];
248     unsigned Flags = getUndefRegState(RO.isUndef());
249     BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
250   }
251   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
252
253   return 2;
254 }
255
256
257 /// This function can analyze one/two way branching only and should (mostly) be
258 /// called by target independent side.
259 /// First entry is always the opcode of the branching instruction, except when
260 /// the Cond vector is supposed to be empty, e.g., when AnalyzeBranch fails, a
261 /// BB with only unconditional jump. Subsequent entries depend upon the opcode,
262 /// e.g. Jump_c p will have
263 /// Cond[0] = Jump_c
264 /// Cond[1] = p
265 /// HW-loop ENDLOOP:
266 /// Cond[0] = ENDLOOP
267 /// Cond[1] = MBB
268 /// New value jump:
269 /// Cond[0] = Hexagon::CMPEQri_f_Jumpnv_t_V4 -- specific opcode
270 /// Cond[1] = R
271 /// Cond[2] = Imm
272 /// @note Related function is \fn findInstrPredicate which fills in
273 /// Cond. vector when a predicated instruction is passed to it.
274 /// We follow same protocol in that case too.
275 ///
276 bool HexagonInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
277                                      MachineBasicBlock *&TBB,
278                                      MachineBasicBlock *&FBB,
279                                      SmallVectorImpl<MachineOperand> &Cond,
280                                      bool AllowModify) const {
281   TBB = nullptr;
282   FBB = nullptr;
283   Cond.clear();
284
285   // If the block has no terminators, it just falls into the block after it.
286   MachineBasicBlock::instr_iterator I = MBB.instr_end();
287   if (I == MBB.instr_begin())
288     return false;
289
290   // A basic block may looks like this:
291   //
292   //  [   insn
293   //     EH_LABEL
294   //      insn
295   //      insn
296   //      insn
297   //     EH_LABEL
298   //      insn     ]
299   //
300   // It has two succs but does not have a terminator
301   // Don't know how to handle it.
302   do {
303     --I;
304     if (I->isEHLabel())
305       // Don't analyze EH branches.
306       return true;
307   } while (I != MBB.instr_begin());
308
309   I = MBB.instr_end();
310   --I;
311
312   while (I->isDebugValue()) {
313     if (I == MBB.instr_begin())
314       return false;
315     --I;
316   }
317   
318   bool JumpToBlock = I->getOpcode() == Hexagon::J2_jump &&
319                      I->getOperand(0).isMBB();
320   // Delete the J2_jump if it's equivalent to a fall-through.
321   if (AllowModify && JumpToBlock &&
322       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
323     DEBUG(dbgs()<< "\nErasing the jump to successor block\n";);
324     I->eraseFromParent();
325     I = MBB.instr_end();
326     if (I == MBB.instr_begin())
327       return false;
328     --I;
329   }
330   if (!isUnpredicatedTerminator(I))
331     return false;
332
333   // Get the last instruction in the block.
334   MachineInstr *LastInst = I;
335   MachineInstr *SecondLastInst = nullptr;
336   // Find one more terminator if present.
337   do {
338     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(I)) {
339       if (!SecondLastInst)
340         SecondLastInst = I;
341       else
342         // This is a third branch.
343         return true;
344     }
345     if (I == MBB.instr_begin())
346       break;
347     --I;
348   } while(I);
349
350   int LastOpcode = LastInst->getOpcode();
351   int SecLastOpcode = SecondLastInst ? SecondLastInst->getOpcode() : 0;
352   // If the branch target is not a basic block, it could be a tail call.
353   // (It is, if the target is a function.)
354   if (LastOpcode == Hexagon::J2_jump && !LastInst->getOperand(0).isMBB())
355     return true;
356   if (SecLastOpcode == Hexagon::J2_jump &&
357       !SecondLastInst->getOperand(0).isMBB())
358     return true;
359
360   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
361   bool LastOpcodeHasNVJump = isNewValueJump(LastInst);
362
363   // If there is only one terminator instruction, process it.
364   if (LastInst && !SecondLastInst) {
365     if (LastOpcode == Hexagon::J2_jump) {
366       TBB = LastInst->getOperand(0).getMBB();
367       return false;
368     }
369     if (isEndLoopN(LastOpcode)) {
370       TBB = LastInst->getOperand(0).getMBB();
371       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
372       Cond.push_back(LastInst->getOperand(0));
373       return false;
374     }
375     if (LastOpcodeHasJMP_c) {
376       TBB = LastInst->getOperand(1).getMBB();
377       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
378       Cond.push_back(LastInst->getOperand(0));
379       return false;
380     }
381     // Only supporting rr/ri versions of new-value jumps.
382     if (LastOpcodeHasNVJump && (LastInst->getNumExplicitOperands() == 3)) {
383       TBB = LastInst->getOperand(2).getMBB();
384       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
385       Cond.push_back(LastInst->getOperand(0));
386       Cond.push_back(LastInst->getOperand(1));
387       return false;
388     }
389     DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
390                  << " with one jump\n";);
391     // Otherwise, don't know what this is.
392     return true;
393   }
394
395   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
396   bool SecLastOpcodeHasNVJump = isNewValueJump(SecondLastInst);
397   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
398     TBB =  SecondLastInst->getOperand(1).getMBB();
399     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
400     Cond.push_back(SecondLastInst->getOperand(0));
401     FBB = LastInst->getOperand(0).getMBB();
402     return false;
403   }
404
405   // Only supporting rr/ri versions of new-value jumps.
406   if (SecLastOpcodeHasNVJump &&
407       (SecondLastInst->getNumExplicitOperands() == 3) &&
408       (LastOpcode == Hexagon::J2_jump)) {
409     TBB = SecondLastInst->getOperand(2).getMBB();
410     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
411     Cond.push_back(SecondLastInst->getOperand(0));
412     Cond.push_back(SecondLastInst->getOperand(1));
413     FBB = LastInst->getOperand(0).getMBB();
414     return false;
415   }
416
417   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
418   // executed, so remove it.
419   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
420     TBB = SecondLastInst->getOperand(0).getMBB();
421     I = LastInst;
422     if (AllowModify)
423       I->eraseFromParent();
424     return false;
425   }
426
427   // If the block ends with an ENDLOOP, and J2_jump, handle it.
428   if (isEndLoopN(SecLastOpcode) && LastOpcode == Hexagon::J2_jump) {
429     TBB = SecondLastInst->getOperand(0).getMBB();
430     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
431     Cond.push_back(SecondLastInst->getOperand(0));
432     FBB = LastInst->getOperand(0).getMBB();
433     return false;
434   }
435   DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
436                << " with two jumps";);
437   // Otherwise, can't handle this.
438   return true;
439 }
440
441 unsigned HexagonInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
442   DEBUG(dbgs() << "\nRemoving branches out of BB#" << MBB.getNumber());
443   MachineBasicBlock::iterator I = MBB.end();
444   unsigned Count = 0;
445   while (I != MBB.begin()) {
446     --I;
447     if (I->isDebugValue())
448       continue;
449     // Only removing branches from end of MBB.
450     if (!I->isBranch())
451       return Count;
452     if (Count && (I->getOpcode() == Hexagon::J2_jump))
453       llvm_unreachable("Malformed basic block: unconditional branch not last");
454     MBB.erase(&MBB.back());
455     I = MBB.end();
456     ++Count;
457   }
458   return Count;
459 }
460
461 /// \brief For a comparison instruction, return the source registers in
462 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
463 /// compares against in CmpValue. Return true if the comparison instruction
464 /// can be analyzed.
465 bool HexagonInstrInfo::analyzeCompare(const MachineInstr *MI,
466                                       unsigned &SrcReg, unsigned &SrcReg2,
467                                       int &Mask, int &Value) const {
468   unsigned Opc = MI->getOpcode();
469
470   // Set mask and the first source register.
471   switch (Opc) {
472     case Hexagon::C2_cmpeq:
473     case Hexagon::C2_cmpeqp:
474     case Hexagon::C2_cmpgt:
475     case Hexagon::C2_cmpgtp:
476     case Hexagon::C2_cmpgtu:
477     case Hexagon::C2_cmpgtup:
478     case Hexagon::C4_cmpneq:
479     case Hexagon::C4_cmplte:
480     case Hexagon::C4_cmplteu:
481     case Hexagon::C2_cmpeqi:
482     case Hexagon::C2_cmpgti:
483     case Hexagon::C2_cmpgtui:
484     case Hexagon::C4_cmpneqi:
485     case Hexagon::C4_cmplteui:
486     case Hexagon::C4_cmpltei:
487       SrcReg = MI->getOperand(1).getReg();
488       Mask = ~0;
489       break;
490     case Hexagon::A4_cmpbeq:
491     case Hexagon::A4_cmpbgt:
492     case Hexagon::A4_cmpbgtu:
493     case Hexagon::A4_cmpbeqi:
494     case Hexagon::A4_cmpbgti:
495     case Hexagon::A4_cmpbgtui:
496       SrcReg = MI->getOperand(1).getReg();
497       Mask = 0xFF;
498       break;
499     case Hexagon::A4_cmpheq:
500     case Hexagon::A4_cmphgt:
501     case Hexagon::A4_cmphgtu:
502     case Hexagon::A4_cmpheqi:
503     case Hexagon::A4_cmphgti:
504     case Hexagon::A4_cmphgtui:
505       SrcReg = MI->getOperand(1).getReg();
506       Mask = 0xFFFF;
507       break;
508   }
509
510   // Set the value/second source register.
511   switch (Opc) {
512     case Hexagon::C2_cmpeq:
513     case Hexagon::C2_cmpeqp:
514     case Hexagon::C2_cmpgt:
515     case Hexagon::C2_cmpgtp:
516     case Hexagon::C2_cmpgtu:
517     case Hexagon::C2_cmpgtup:
518     case Hexagon::A4_cmpbeq:
519     case Hexagon::A4_cmpbgt:
520     case Hexagon::A4_cmpbgtu:
521     case Hexagon::A4_cmpheq:
522     case Hexagon::A4_cmphgt:
523     case Hexagon::A4_cmphgtu:
524     case Hexagon::C4_cmpneq:
525     case Hexagon::C4_cmplte:
526     case Hexagon::C4_cmplteu:
527       SrcReg2 = MI->getOperand(2).getReg();
528       return true;
529
530     case Hexagon::C2_cmpeqi:
531     case Hexagon::C2_cmpgtui:
532     case Hexagon::C2_cmpgti:
533     case Hexagon::C4_cmpneqi:
534     case Hexagon::C4_cmplteui:
535     case Hexagon::C4_cmpltei:
536     case Hexagon::A4_cmpbeqi:
537     case Hexagon::A4_cmpbgti:
538     case Hexagon::A4_cmpbgtui:
539     case Hexagon::A4_cmpheqi:
540     case Hexagon::A4_cmphgti:
541     case Hexagon::A4_cmphgtui:
542       SrcReg2 = 0;
543       Value = MI->getOperand(2).getImm();
544       return true;
545   }
546
547   return false;
548 }
549
550
551 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
552                                  MachineBasicBlock::iterator I, DebugLoc DL,
553                                  unsigned DestReg, unsigned SrcReg,
554                                  bool KillSrc) const {
555   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
556     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg).addReg(SrcReg);
557     return;
558   }
559   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
560     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg).addReg(SrcReg);
561     return;
562   }
563   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
564     // Map Pd = Ps to Pd = or(Ps, Ps).
565     BuildMI(MBB, I, DL, get(Hexagon::C2_or),
566             DestReg).addReg(SrcReg).addReg(SrcReg);
567     return;
568   }
569   if (Hexagon::DoubleRegsRegClass.contains(DestReg) &&
570       Hexagon::IntRegsRegClass.contains(SrcReg)) {
571     // We can have an overlap between single and double reg: r1:0 = r0.
572     if(SrcReg == RI.getSubReg(DestReg, Hexagon::subreg_loreg)) {
573         // r1:0 = r0
574         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
575                 Hexagon::subreg_hireg))).addImm(0);
576     } else {
577         // r1:0 = r1 or no overlap.
578         BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), (RI.getSubReg(DestReg,
579                 Hexagon::subreg_loreg))).addReg(SrcReg);
580         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
581                 Hexagon::subreg_hireg))).addImm(0);
582     }
583     return;
584   }
585   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
586       Hexagon::IntRegsRegClass.contains(SrcReg)) {
587     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg).addReg(SrcReg);
588     return;
589   }
590   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
591       Hexagon::IntRegsRegClass.contains(DestReg)) {
592     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg).
593       addReg(SrcReg, getKillRegState(KillSrc));
594     return;
595   }
596   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
597       Hexagon::PredRegsRegClass.contains(DestReg)) {
598     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg).
599       addReg(SrcReg, getKillRegState(KillSrc));
600     return;
601   }
602
603   llvm_unreachable("Unimplemented");
604 }
605
606
607 void HexagonInstrInfo::
608 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
609                     unsigned SrcReg, bool isKill, int FI,
610                     const TargetRegisterClass *RC,
611                     const TargetRegisterInfo *TRI) const {
612
613   DebugLoc DL = MBB.findDebugLoc(I);
614   MachineFunction &MF = *MBB.getParent();
615   MachineFrameInfo &MFI = *MF.getFrameInfo();
616   unsigned Align = MFI.getObjectAlignment(FI);
617
618   MachineMemOperand *MMO = MF.getMachineMemOperand(
619       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
620       MFI.getObjectSize(FI), Align);
621
622   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
623     BuildMI(MBB, I, DL, get(Hexagon::S2_storeri_io))
624           .addFrameIndex(FI).addImm(0)
625           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
626   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
627     BuildMI(MBB, I, DL, get(Hexagon::S2_storerd_io))
628           .addFrameIndex(FI).addImm(0)
629           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
630   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
631     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
632           .addFrameIndex(FI).addImm(0)
633           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
634   } else {
635     llvm_unreachable("Unimplemented");
636   }
637 }
638
639
640 void HexagonInstrInfo::storeRegToAddr(
641                                  MachineFunction &MF, unsigned SrcReg,
642                                  bool isKill,
643                                  SmallVectorImpl<MachineOperand> &Addr,
644                                  const TargetRegisterClass *RC,
645                                  SmallVectorImpl<MachineInstr*> &NewMIs) const
646 {
647   llvm_unreachable("Unimplemented");
648 }
649
650
651 void HexagonInstrInfo::
652 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
653                      unsigned DestReg, int FI,
654                      const TargetRegisterClass *RC,
655                      const TargetRegisterInfo *TRI) const {
656   DebugLoc DL = MBB.findDebugLoc(I);
657   MachineFunction &MF = *MBB.getParent();
658   MachineFrameInfo &MFI = *MF.getFrameInfo();
659   unsigned Align = MFI.getObjectAlignment(FI);
660
661   MachineMemOperand *MMO = MF.getMachineMemOperand(
662       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
663       MFI.getObjectSize(FI), Align);
664   if (RC == &Hexagon::IntRegsRegClass) {
665     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
666           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
667   } else if (RC == &Hexagon::DoubleRegsRegClass) {
668     BuildMI(MBB, I, DL, get(Hexagon::L2_loadrd_io), DestReg)
669           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
670   } else if (RC == &Hexagon::PredRegsRegClass) {
671     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
672           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
673   } else {
674     llvm_unreachable("Can't store this register to stack slot");
675   }
676 }
677
678
679 void HexagonInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
680                                         SmallVectorImpl<MachineOperand> &Addr,
681                                         const TargetRegisterClass *RC,
682                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
683   llvm_unreachable("Unimplemented");
684 }
685 bool
686 HexagonInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
687   const HexagonRegisterInfo &TRI = getRegisterInfo();
688   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
689   MachineBasicBlock &MBB = *MI->getParent();
690   DebugLoc DL = MI->getDebugLoc();
691   unsigned Opc = MI->getOpcode();
692
693   switch (Opc) {
694     case Hexagon::ALIGNA:
695       BuildMI(MBB, MI, DL, get(Hexagon::A2_andir), MI->getOperand(0).getReg())
696           .addReg(TRI.getFrameRegister())
697           .addImm(-MI->getOperand(1).getImm());
698       MBB.erase(MI);
699       return true;
700     case Hexagon::TFR_PdTrue: {
701       unsigned Reg = MI->getOperand(0).getReg();
702       BuildMI(MBB, MI, DL, get(Hexagon::C2_orn), Reg)
703         .addReg(Reg, RegState::Undef)
704         .addReg(Reg, RegState::Undef);
705       MBB.erase(MI);
706       return true;
707     }
708     case Hexagon::TFR_PdFalse: {
709       unsigned Reg = MI->getOperand(0).getReg();
710       BuildMI(MBB, MI, DL, get(Hexagon::C2_andn), Reg)
711         .addReg(Reg, RegState::Undef)
712         .addReg(Reg, RegState::Undef);
713       MBB.erase(MI);
714       return true;
715     }
716     case Hexagon::VMULW: {
717       // Expand a 64-bit vector multiply into 2 32-bit scalar multiplies.
718       unsigned DstReg = MI->getOperand(0).getReg();
719       unsigned Src1Reg = MI->getOperand(1).getReg();
720       unsigned Src2Reg = MI->getOperand(2).getReg();
721       unsigned Src1SubHi = TRI.getSubReg(Src1Reg, Hexagon::subreg_hireg);
722       unsigned Src1SubLo = TRI.getSubReg(Src1Reg, Hexagon::subreg_loreg);
723       unsigned Src2SubHi = TRI.getSubReg(Src2Reg, Hexagon::subreg_hireg);
724       unsigned Src2SubLo = TRI.getSubReg(Src2Reg, Hexagon::subreg_loreg);
725       BuildMI(MBB, MI, MI->getDebugLoc(), get(Hexagon::M2_mpyi),
726               TRI.getSubReg(DstReg, Hexagon::subreg_hireg)).addReg(Src1SubHi)
727           .addReg(Src2SubHi);
728       BuildMI(MBB, MI, MI->getDebugLoc(), get(Hexagon::M2_mpyi),
729               TRI.getSubReg(DstReg, Hexagon::subreg_loreg)).addReg(Src1SubLo)
730           .addReg(Src2SubLo);
731       MBB.erase(MI);
732       MRI.clearKillFlags(Src1SubHi);
733       MRI.clearKillFlags(Src1SubLo);
734       MRI.clearKillFlags(Src2SubHi);
735       MRI.clearKillFlags(Src2SubLo);
736       return true;
737     }
738     case Hexagon::VMULW_ACC: {
739       // Expand 64-bit vector multiply with addition into 2 scalar multiplies.
740       unsigned DstReg = MI->getOperand(0).getReg();
741       unsigned Src1Reg = MI->getOperand(1).getReg();
742       unsigned Src2Reg = MI->getOperand(2).getReg();
743       unsigned Src3Reg = MI->getOperand(3).getReg();
744       unsigned Src1SubHi = TRI.getSubReg(Src1Reg, Hexagon::subreg_hireg);
745       unsigned Src1SubLo = TRI.getSubReg(Src1Reg, Hexagon::subreg_loreg);
746       unsigned Src2SubHi = TRI.getSubReg(Src2Reg, Hexagon::subreg_hireg);
747       unsigned Src2SubLo = TRI.getSubReg(Src2Reg, Hexagon::subreg_loreg);
748       unsigned Src3SubHi = TRI.getSubReg(Src3Reg, Hexagon::subreg_hireg);
749       unsigned Src3SubLo = TRI.getSubReg(Src3Reg, Hexagon::subreg_loreg);
750       BuildMI(MBB, MI, MI->getDebugLoc(), get(Hexagon::M2_maci),
751               TRI.getSubReg(DstReg, Hexagon::subreg_hireg)).addReg(Src1SubHi)
752           .addReg(Src2SubHi).addReg(Src3SubHi);
753       BuildMI(MBB, MI, MI->getDebugLoc(), get(Hexagon::M2_maci),
754               TRI.getSubReg(DstReg, Hexagon::subreg_loreg)).addReg(Src1SubLo)
755           .addReg(Src2SubLo).addReg(Src3SubLo);
756       MBB.erase(MI);
757       MRI.clearKillFlags(Src1SubHi);
758       MRI.clearKillFlags(Src1SubLo);
759       MRI.clearKillFlags(Src2SubHi);
760       MRI.clearKillFlags(Src2SubLo);
761       MRI.clearKillFlags(Src3SubHi);
762       MRI.clearKillFlags(Src3SubLo);
763       return true;
764     }
765     case Hexagon::TCRETURNi:
766       MI->setDesc(get(Hexagon::J2_jump));
767       return true;
768     case Hexagon::TCRETURNr:
769       MI->setDesc(get(Hexagon::J2_jumpr));
770       return true;
771   }
772
773   return false;
774 }
775
776 MachineInstr *HexagonInstrInfo::foldMemoryOperandImpl(
777     MachineFunction &MF, MachineInstr *MI, ArrayRef<unsigned> Ops,
778     MachineBasicBlock::iterator InsertPt, int FI) const {
779   // Hexagon_TODO: Implement.
780   return nullptr;
781 }
782
783 unsigned HexagonInstrInfo::createVR(MachineFunction* MF, MVT VT) const {
784
785   MachineRegisterInfo &RegInfo = MF->getRegInfo();
786   const TargetRegisterClass *TRC;
787   if (VT == MVT::i1) {
788     TRC = &Hexagon::PredRegsRegClass;
789   } else if (VT == MVT::i32 || VT == MVT::f32) {
790     TRC = &Hexagon::IntRegsRegClass;
791   } else if (VT == MVT::i64 || VT == MVT::f64) {
792     TRC = &Hexagon::DoubleRegsRegClass;
793   } else {
794     llvm_unreachable("Cannot handle this register class");
795   }
796
797   unsigned NewReg = RegInfo.createVirtualRegister(TRC);
798   return NewReg;
799 }
800
801 bool HexagonInstrInfo::isExtendable(const MachineInstr *MI) const {
802   const MCInstrDesc &MID = MI->getDesc();
803   const uint64_t F = MID.TSFlags;
804   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
805     return true;
806
807   // TODO: This is largely obsolete now. Will need to be removed
808   // in consecutive patches.
809   switch(MI->getOpcode()) {
810     // TFR_FI Remains a special case.
811     case Hexagon::TFR_FI:
812       return true;
813     default:
814       return false;
815   }
816   return  false;
817 }
818
819 // This returns true in two cases:
820 // - The OP code itself indicates that this is an extended instruction.
821 // - One of MOs has been marked with HMOTF_ConstExtended flag.
822 bool HexagonInstrInfo::isExtended(const MachineInstr *MI) const {
823   // First check if this is permanently extended op code.
824   const uint64_t F = MI->getDesc().TSFlags;
825   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
826     return true;
827   // Use MO operand flags to determine if one of MI's operands
828   // has HMOTF_ConstExtended flag set.
829   for (MachineInstr::const_mop_iterator I = MI->operands_begin(),
830        E = MI->operands_end(); I != E; ++I) {
831     if (I->getTargetFlags() && HexagonII::HMOTF_ConstExtended)
832       return true;
833   }
834   return  false;
835 }
836
837 bool HexagonInstrInfo::isBranch (const MachineInstr *MI) const {
838   return MI->getDesc().isBranch();
839 }
840
841 bool HexagonInstrInfo::isNewValueInst(const MachineInstr *MI) const {
842   if (isNewValueJump(MI))
843     return true;
844
845   if (isNewValueStore(MI))
846     return true;
847
848   return false;
849 }
850
851 bool HexagonInstrInfo::isNewValue(const MachineInstr* MI) const {
852   const uint64_t F = MI->getDesc().TSFlags;
853   return ((F >> HexagonII::NewValuePos) & HexagonII::NewValueMask);
854 }
855
856 bool HexagonInstrInfo::isNewValue(Opcode_t Opcode) const {
857   const uint64_t F = get(Opcode).TSFlags;
858   return ((F >> HexagonII::NewValuePos) & HexagonII::NewValueMask);
859 }
860
861 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr *MI) const {
862   return MI->getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4;
863 }
864
865 bool HexagonInstrInfo::isPredicable(MachineInstr *MI) const {
866   bool isPred = MI->getDesc().isPredicable();
867
868   if (!isPred)
869     return false;
870
871   const int Opc = MI->getOpcode();
872
873   switch(Opc) {
874   case Hexagon::A2_tfrsi:
875     return (isOperandExtended(MI, 1) && isConstExtended(MI)) || isInt<12>(MI->getOperand(1).getImm());
876
877   case Hexagon::S2_storerd_io:
878     return isShiftedUInt<6,3>(MI->getOperand(1).getImm());
879
880   case Hexagon::S2_storeri_io:
881   case Hexagon::S2_storerinew_io:
882     return isShiftedUInt<6,2>(MI->getOperand(1).getImm());
883
884   case Hexagon::S2_storerh_io:
885   case Hexagon::S2_storerhnew_io:
886     return isShiftedUInt<6,1>(MI->getOperand(1).getImm());
887
888   case Hexagon::S2_storerb_io:
889   case Hexagon::S2_storerbnew_io:
890     return isUInt<6>(MI->getOperand(1).getImm());
891
892   case Hexagon::L2_loadrd_io:
893     return isShiftedUInt<6,3>(MI->getOperand(2).getImm());
894
895   case Hexagon::L2_loadri_io:
896     return isShiftedUInt<6,2>(MI->getOperand(2).getImm());
897
898   case Hexagon::L2_loadrh_io:
899   case Hexagon::L2_loadruh_io:
900     return isShiftedUInt<6,1>(MI->getOperand(2).getImm());
901
902   case Hexagon::L2_loadrb_io:
903   case Hexagon::L2_loadrub_io:
904     return isUInt<6>(MI->getOperand(2).getImm());
905
906   case Hexagon::L2_loadrd_pi:
907     return isShiftedInt<4,3>(MI->getOperand(3).getImm());
908
909   case Hexagon::L2_loadri_pi:
910     return isShiftedInt<4,2>(MI->getOperand(3).getImm());
911
912   case Hexagon::L2_loadrh_pi:
913   case Hexagon::L2_loadruh_pi:
914     return isShiftedInt<4,1>(MI->getOperand(3).getImm());
915
916   case Hexagon::L2_loadrb_pi:
917   case Hexagon::L2_loadrub_pi:
918     return isInt<4>(MI->getOperand(3).getImm());
919
920   case Hexagon::S4_storeirb_io:
921   case Hexagon::S4_storeirh_io:
922   case Hexagon::S4_storeiri_io:
923     return (isUInt<6>(MI->getOperand(1).getImm()) &&
924             isInt<6>(MI->getOperand(2).getImm()));
925
926   case Hexagon::A2_addi:
927     return isInt<8>(MI->getOperand(2).getImm());
928
929   case Hexagon::A2_aslh:
930   case Hexagon::A2_asrh:
931   case Hexagon::A2_sxtb:
932   case Hexagon::A2_sxth:
933   case Hexagon::A2_zxtb:
934   case Hexagon::A2_zxth:
935     return true;
936   }
937
938   return true;
939 }
940
941 // This function performs the following inversiones:
942 //
943 //  cPt    ---> cNotPt
944 //  cNotPt ---> cPt
945 //
946 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
947   int InvPredOpcode;
948   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
949                                         : Hexagon::getTruePredOpcode(Opc);
950   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
951     return InvPredOpcode;
952
953   switch(Opc) {
954     default: llvm_unreachable("Unexpected predicated instruction");
955     case Hexagon::C2_ccombinewt:
956       return Hexagon::C2_ccombinewf;
957     case Hexagon::C2_ccombinewf:
958       return Hexagon::C2_ccombinewt;
959
960       // Dealloc_return.
961     case Hexagon::L4_return_t:
962       return Hexagon::L4_return_f;
963     case Hexagon::L4_return_f:
964       return Hexagon::L4_return_t;
965   }
966 }
967
968 // New Value Store instructions.
969 bool HexagonInstrInfo::isNewValueStore(const MachineInstr *MI) const {
970   const uint64_t F = MI->getDesc().TSFlags;
971
972   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
973 }
974
975 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
976   const uint64_t F = get(Opcode).TSFlags;
977
978   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
979 }
980
981 int HexagonInstrInfo::getCondOpcode(int Opc, bool invertPredicate) const {
982   enum Hexagon::PredSense inPredSense;
983   inPredSense = invertPredicate ? Hexagon::PredSense_false :
984                                   Hexagon::PredSense_true;
985   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
986   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
987     return CondOpcode;
988
989   // This switch case will be removed once all the instructions have been
990   // modified to use relation maps.
991   switch(Opc) {
992   case Hexagon::TFRI_f:
993     return !invertPredicate ? Hexagon::TFRI_cPt_f :
994                               Hexagon::TFRI_cNotPt_f;
995   case Hexagon::A2_combinew:
996     return !invertPredicate ? Hexagon::C2_ccombinewt :
997                               Hexagon::C2_ccombinewf;
998
999   // DEALLOC_RETURN.
1000   case Hexagon::L4_return:
1001     return !invertPredicate ? Hexagon::L4_return_t:
1002                               Hexagon::L4_return_f;
1003   }
1004   llvm_unreachable("Unexpected predicable instruction");
1005 }
1006
1007
1008 bool HexagonInstrInfo::
1009 PredicateInstruction(MachineInstr *MI,
1010                      ArrayRef<MachineOperand> Cond) const {
1011   if (Cond.empty() || isEndLoopN(Cond[0].getImm())) {
1012     DEBUG(dbgs() << "\nCannot predicate:"; MI->dump(););
1013     return false;
1014   }
1015   int Opc = MI->getOpcode();
1016   assert (isPredicable(MI) && "Expected predicable instruction");
1017   bool invertJump = predOpcodeHasNot(Cond);
1018
1019   // We have to predicate MI "in place", i.e. after this function returns,
1020   // MI will need to be transformed into a predicated form. To avoid com-
1021   // plicated manipulations with the operands (handling tied operands,
1022   // etc.), build a new temporary instruction, then overwrite MI with it.
1023
1024   MachineBasicBlock &B = *MI->getParent();
1025   DebugLoc DL = MI->getDebugLoc();
1026   unsigned PredOpc = getCondOpcode(Opc, invertJump);
1027   MachineInstrBuilder T = BuildMI(B, MI, DL, get(PredOpc));
1028   unsigned NOp = 0, NumOps = MI->getNumOperands();
1029   while (NOp < NumOps) {
1030     MachineOperand &Op = MI->getOperand(NOp);
1031     if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1032       break;
1033     T.addOperand(Op);
1034     NOp++;
1035   }
1036
1037   unsigned PredReg, PredRegPos, PredRegFlags;
1038   bool GotPredReg = getPredReg(Cond, PredReg, PredRegPos, PredRegFlags);
1039   (void)GotPredReg;
1040   assert(GotPredReg);
1041   T.addReg(PredReg, PredRegFlags);
1042   while (NOp < NumOps)
1043     T.addOperand(MI->getOperand(NOp++));
1044
1045   MI->setDesc(get(PredOpc));
1046   while (unsigned n = MI->getNumOperands())
1047     MI->RemoveOperand(n-1);
1048   for (unsigned i = 0, n = T->getNumOperands(); i < n; ++i)
1049     MI->addOperand(T->getOperand(i));
1050
1051   MachineBasicBlock::instr_iterator TI = &*T;
1052   B.erase(TI);
1053
1054   MachineRegisterInfo &MRI = B.getParent()->getRegInfo();
1055   MRI.clearKillFlags(PredReg);
1056
1057   return true;
1058 }
1059
1060
1061 bool
1062 HexagonInstrInfo::
1063 isProfitableToIfCvt(MachineBasicBlock &MBB,
1064                     unsigned NumCycles,
1065                     unsigned ExtraPredCycles,
1066                     BranchProbability Probability) const {
1067   return true;
1068 }
1069
1070
1071 bool
1072 HexagonInstrInfo::
1073 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1074                     unsigned NumTCycles,
1075                     unsigned ExtraTCycles,
1076                     MachineBasicBlock &FMBB,
1077                     unsigned NumFCycles,
1078                     unsigned ExtraFCycles,
1079                     BranchProbability Probability) const {
1080   return true;
1081 }
1082
1083 // Returns true if an instruction is predicated irrespective of the predicate
1084 // sense. For example, all of the following will return true.
1085 // if (p0) R1 = add(R2, R3)
1086 // if (!p0) R1 = add(R2, R3)
1087 // if (p0.new) R1 = add(R2, R3)
1088 // if (!p0.new) R1 = add(R2, R3)
1089 bool HexagonInstrInfo::isPredicated(const MachineInstr *MI) const {
1090   const uint64_t F = MI->getDesc().TSFlags;
1091
1092   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
1093 }
1094
1095 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
1096   const uint64_t F = get(Opcode).TSFlags;
1097
1098   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
1099 }
1100
1101 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr *MI) const {
1102   const uint64_t F = MI->getDesc().TSFlags;
1103
1104   assert(isPredicated(MI));
1105   return (!((F >> HexagonII::PredicatedFalsePos) &
1106             HexagonII::PredicatedFalseMask));
1107 }
1108
1109 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
1110   const uint64_t F = get(Opcode).TSFlags;
1111
1112   // Make sure that the instruction is predicated.
1113   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
1114   return (!((F >> HexagonII::PredicatedFalsePos) &
1115             HexagonII::PredicatedFalseMask));
1116 }
1117
1118 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr *MI) const {
1119   const uint64_t F = MI->getDesc().TSFlags;
1120
1121   assert(isPredicated(MI));
1122   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1123 }
1124
1125 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
1126   const uint64_t F = get(Opcode).TSFlags;
1127
1128   assert(isPredicated(Opcode));
1129   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1130 }
1131
1132 // Returns true, if a ST insn can be promoted to a new-value store.
1133 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr *MI) const {
1134   const uint64_t F = MI->getDesc().TSFlags;
1135
1136   return ((F >> HexagonII::mayNVStorePos) &
1137            HexagonII::mayNVStoreMask);
1138 }
1139
1140 bool
1141 HexagonInstrInfo::DefinesPredicate(MachineInstr *MI,
1142                                    std::vector<MachineOperand> &Pred) const {
1143   for (unsigned oper = 0; oper < MI->getNumOperands(); ++oper) {
1144     MachineOperand MO = MI->getOperand(oper);
1145     if (MO.isReg() && MO.isDef()) {
1146       const TargetRegisterClass* RC = RI.getMinimalPhysRegClass(MO.getReg());
1147       if (RC == &Hexagon::PredRegsRegClass) {
1148         Pred.push_back(MO);
1149         return true;
1150       }
1151     }
1152   }
1153   return false;
1154 }
1155
1156
1157 bool
1158 HexagonInstrInfo::
1159 SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1160                   ArrayRef<MachineOperand> Pred2) const {
1161   // TODO: Fix this
1162   return false;
1163 }
1164
1165
1166 //
1167 // We indicate that we want to reverse the branch by
1168 // inserting the reversed branching opcode.
1169 //
1170 bool HexagonInstrInfo::ReverseBranchCondition(
1171     SmallVectorImpl<MachineOperand> &Cond) const {
1172   if (Cond.empty())
1173     return true;
1174   assert(Cond[0].isImm() && "First entry in the cond vector not imm-val");
1175   Opcode_t opcode = Cond[0].getImm();
1176   //unsigned temp;
1177   assert(get(opcode).isBranch() && "Should be a branching condition.");
1178   if (isEndLoopN(opcode))
1179     return true;
1180   Opcode_t NewOpcode = getInvertedPredicatedOpcode(opcode);
1181   Cond[0].setImm(NewOpcode);
1182   return false;
1183 }
1184
1185
1186 bool HexagonInstrInfo::
1187 isProfitableToDupForIfCvt(MachineBasicBlock &MBB,unsigned NumInstrs,
1188                           BranchProbability Probability) const {
1189   return (NumInstrs <= 4);
1190 }
1191
1192 bool HexagonInstrInfo::isDeallocRet(const MachineInstr *MI) const {
1193   switch (MI->getOpcode()) {
1194   default: return false;
1195   case Hexagon::L4_return:
1196   case Hexagon::L4_return_t:
1197   case Hexagon::L4_return_f:
1198   case Hexagon::L4_return_tnew_pnt:
1199   case Hexagon::L4_return_fnew_pnt:
1200   case Hexagon::L4_return_tnew_pt:
1201   case Hexagon::L4_return_fnew_pt:
1202    return true;
1203   }
1204 }
1205
1206
1207 bool HexagonInstrInfo::isValidOffset(unsigned Opcode, int Offset,
1208       bool Extend) const {
1209   // This function is to check whether the "Offset" is in the correct range of
1210   // the given "Opcode". If "Offset" is not in the correct range, "A2_addi" is
1211   // inserted to calculate the final address. Due to this reason, the function
1212   // assumes that the "Offset" has correct alignment.
1213   // We used to assert if the offset was not properly aligned, however,
1214   // there are cases where a misaligned pointer recast can cause this
1215   // problem, and we need to allow for it. The front end warns of such
1216   // misaligns with respect to load size.
1217
1218   switch (Opcode) {
1219   case Hexagon::J2_loop0i:
1220   case Hexagon::J2_loop1i:
1221     return isUInt<10>(Offset);
1222   }
1223
1224   if (Extend)
1225     return true;
1226
1227   switch (Opcode) {
1228   case Hexagon::L2_loadri_io:
1229   case Hexagon::S2_storeri_io:
1230     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
1231       (Offset <= Hexagon_MEMW_OFFSET_MAX);
1232
1233   case Hexagon::L2_loadrd_io:
1234   case Hexagon::S2_storerd_io:
1235     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
1236       (Offset <= Hexagon_MEMD_OFFSET_MAX);
1237
1238   case Hexagon::L2_loadrh_io:
1239   case Hexagon::L2_loadruh_io:
1240   case Hexagon::S2_storerh_io:
1241     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
1242       (Offset <= Hexagon_MEMH_OFFSET_MAX);
1243
1244   case Hexagon::L2_loadrb_io:
1245   case Hexagon::S2_storerb_io:
1246   case Hexagon::L2_loadrub_io:
1247     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
1248       (Offset <= Hexagon_MEMB_OFFSET_MAX);
1249
1250   case Hexagon::A2_addi:
1251     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
1252       (Offset <= Hexagon_ADDI_OFFSET_MAX);
1253
1254   case Hexagon::L4_iadd_memopw_io:
1255   case Hexagon::L4_isub_memopw_io:
1256   case Hexagon::L4_add_memopw_io:
1257   case Hexagon::L4_sub_memopw_io:
1258   case Hexagon::L4_and_memopw_io:
1259   case Hexagon::L4_or_memopw_io:
1260     return (0 <= Offset && Offset <= 255);
1261
1262   case Hexagon::L4_iadd_memoph_io:
1263   case Hexagon::L4_isub_memoph_io:
1264   case Hexagon::L4_add_memoph_io:
1265   case Hexagon::L4_sub_memoph_io:
1266   case Hexagon::L4_and_memoph_io:
1267   case Hexagon::L4_or_memoph_io:
1268     return (0 <= Offset && Offset <= 127);
1269
1270   case Hexagon::L4_iadd_memopb_io:
1271   case Hexagon::L4_isub_memopb_io:
1272   case Hexagon::L4_add_memopb_io:
1273   case Hexagon::L4_sub_memopb_io:
1274   case Hexagon::L4_and_memopb_io:
1275   case Hexagon::L4_or_memopb_io:
1276     return (0 <= Offset && Offset <= 63);
1277
1278   // LDri_pred and STriw_pred are pseudo operations, so it has to take offset of
1279   // any size. Later pass knows how to handle it.
1280   case Hexagon::STriw_pred:
1281   case Hexagon::LDriw_pred:
1282     return true;
1283
1284   case Hexagon::TFR_FI:
1285   case Hexagon::TFR_FIA:
1286   case Hexagon::INLINEASM:
1287     return true;
1288   }
1289
1290   llvm_unreachable("No offset range is defined for this opcode. "
1291                    "Please define it in the above switch statement!");
1292 }
1293
1294
1295 //
1296 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
1297 //
1298 bool HexagonInstrInfo::
1299 isValidAutoIncImm(const EVT VT, const int Offset) const {
1300
1301   if (VT == MVT::i64) {
1302       return (Offset >= Hexagon_MEMD_AUTOINC_MIN &&
1303               Offset <= Hexagon_MEMD_AUTOINC_MAX &&
1304               (Offset & 0x7) == 0);
1305   }
1306   if (VT == MVT::i32) {
1307       return (Offset >= Hexagon_MEMW_AUTOINC_MIN &&
1308               Offset <= Hexagon_MEMW_AUTOINC_MAX &&
1309               (Offset & 0x3) == 0);
1310   }
1311   if (VT == MVT::i16) {
1312       return (Offset >= Hexagon_MEMH_AUTOINC_MIN &&
1313               Offset <= Hexagon_MEMH_AUTOINC_MAX &&
1314               (Offset & 0x1) == 0);
1315   }
1316   if (VT == MVT::i8) {
1317       return (Offset >= Hexagon_MEMB_AUTOINC_MIN &&
1318               Offset <= Hexagon_MEMB_AUTOINC_MAX);
1319   }
1320   llvm_unreachable("Not an auto-inc opc!");
1321 }
1322
1323
1324 bool HexagonInstrInfo::
1325 isMemOp(const MachineInstr *MI) const {
1326 //  return MI->getDesc().mayLoad() && MI->getDesc().mayStore();
1327
1328   switch (MI->getOpcode())
1329   {
1330   default: return false;
1331   case Hexagon::L4_iadd_memopw_io:
1332   case Hexagon::L4_isub_memopw_io:
1333   case Hexagon::L4_add_memopw_io:
1334   case Hexagon::L4_sub_memopw_io:
1335   case Hexagon::L4_and_memopw_io:
1336   case Hexagon::L4_or_memopw_io:
1337   case Hexagon::L4_iadd_memoph_io:
1338   case Hexagon::L4_isub_memoph_io:
1339   case Hexagon::L4_add_memoph_io:
1340   case Hexagon::L4_sub_memoph_io:
1341   case Hexagon::L4_and_memoph_io:
1342   case Hexagon::L4_or_memoph_io:
1343   case Hexagon::L4_iadd_memopb_io:
1344   case Hexagon::L4_isub_memopb_io:
1345   case Hexagon::L4_add_memopb_io:
1346   case Hexagon::L4_sub_memopb_io:
1347   case Hexagon::L4_and_memopb_io:
1348   case Hexagon::L4_or_memopb_io:
1349   case Hexagon::L4_ior_memopb_io:
1350   case Hexagon::L4_ior_memoph_io:
1351   case Hexagon::L4_ior_memopw_io:
1352   case Hexagon::L4_iand_memopb_io:
1353   case Hexagon::L4_iand_memoph_io:
1354   case Hexagon::L4_iand_memopw_io:
1355     return true;
1356   }
1357   return false;
1358 }
1359
1360
1361 bool HexagonInstrInfo::
1362 isSpillPredRegOp(const MachineInstr *MI) const {
1363   switch (MI->getOpcode()) {
1364     default: return false;
1365     case Hexagon::STriw_pred :
1366     case Hexagon::LDriw_pred :
1367       return true;
1368   }
1369 }
1370
1371 bool HexagonInstrInfo::isNewValueJumpCandidate(const MachineInstr *MI) const {
1372   switch (MI->getOpcode()) {
1373     default: return false;
1374     case Hexagon::C2_cmpeq:
1375     case Hexagon::C2_cmpeqi:
1376     case Hexagon::C2_cmpgt:
1377     case Hexagon::C2_cmpgti:
1378     case Hexagon::C2_cmpgtu:
1379     case Hexagon::C2_cmpgtui:
1380       return true;
1381   }
1382 }
1383
1384 bool HexagonInstrInfo::
1385 isConditionalTransfer (const MachineInstr *MI) const {
1386   switch (MI->getOpcode()) {
1387     default: return false;
1388     case Hexagon::A2_tfrt:
1389     case Hexagon::A2_tfrf:
1390     case Hexagon::C2_cmoveit:
1391     case Hexagon::C2_cmoveif:
1392     case Hexagon::A2_tfrtnew:
1393     case Hexagon::A2_tfrfnew:
1394     case Hexagon::C2_cmovenewit:
1395     case Hexagon::C2_cmovenewif:
1396       return true;
1397   }
1398 }
1399
1400 bool HexagonInstrInfo::isConditionalALU32 (const MachineInstr* MI) const {
1401   switch (MI->getOpcode())
1402   {
1403     default: return false;
1404     case Hexagon::A2_paddf:
1405     case Hexagon::A2_paddfnew:
1406     case Hexagon::A2_paddt:
1407     case Hexagon::A2_paddtnew:
1408     case Hexagon::A2_pandf:
1409     case Hexagon::A2_pandfnew:
1410     case Hexagon::A2_pandt:
1411     case Hexagon::A2_pandtnew:
1412     case Hexagon::A4_paslhf:
1413     case Hexagon::A4_paslhfnew:
1414     case Hexagon::A4_paslht:
1415     case Hexagon::A4_paslhtnew:
1416     case Hexagon::A4_pasrhf:
1417     case Hexagon::A4_pasrhfnew:
1418     case Hexagon::A4_pasrht:
1419     case Hexagon::A4_pasrhtnew:
1420     case Hexagon::A2_porf:
1421     case Hexagon::A2_porfnew:
1422     case Hexagon::A2_port:
1423     case Hexagon::A2_portnew:
1424     case Hexagon::A2_psubf:
1425     case Hexagon::A2_psubfnew:
1426     case Hexagon::A2_psubt:
1427     case Hexagon::A2_psubtnew:
1428     case Hexagon::A2_pxorf:
1429     case Hexagon::A2_pxorfnew:
1430     case Hexagon::A2_pxort:
1431     case Hexagon::A2_pxortnew:
1432     case Hexagon::A4_psxthf:
1433     case Hexagon::A4_psxthfnew:
1434     case Hexagon::A4_psxtht:
1435     case Hexagon::A4_psxthtnew:
1436     case Hexagon::A4_psxtbf:
1437     case Hexagon::A4_psxtbfnew:
1438     case Hexagon::A4_psxtbt:
1439     case Hexagon::A4_psxtbtnew:
1440     case Hexagon::A4_pzxtbf:
1441     case Hexagon::A4_pzxtbfnew:
1442     case Hexagon::A4_pzxtbt:
1443     case Hexagon::A4_pzxtbtnew:
1444     case Hexagon::A4_pzxthf:
1445     case Hexagon::A4_pzxthfnew:
1446     case Hexagon::A4_pzxtht:
1447     case Hexagon::A4_pzxthtnew:
1448     case Hexagon::A2_paddit:
1449     case Hexagon::A2_paddif:
1450     case Hexagon::C2_ccombinewt:
1451     case Hexagon::C2_ccombinewf:
1452       return true;
1453   }
1454 }
1455
1456 bool HexagonInstrInfo::
1457 isConditionalLoad (const MachineInstr* MI) const {
1458   switch (MI->getOpcode())
1459   {
1460     default: return false;
1461     case Hexagon::L2_ploadrdt_io :
1462     case Hexagon::L2_ploadrdf_io:
1463     case Hexagon::L2_ploadrit_io:
1464     case Hexagon::L2_ploadrif_io:
1465     case Hexagon::L2_ploadrht_io:
1466     case Hexagon::L2_ploadrhf_io:
1467     case Hexagon::L2_ploadrbt_io:
1468     case Hexagon::L2_ploadrbf_io:
1469     case Hexagon::L2_ploadruht_io:
1470     case Hexagon::L2_ploadruhf_io:
1471     case Hexagon::L2_ploadrubt_io:
1472     case Hexagon::L2_ploadrubf_io:
1473     case Hexagon::L2_ploadrdt_pi:
1474     case Hexagon::L2_ploadrdf_pi:
1475     case Hexagon::L2_ploadrit_pi:
1476     case Hexagon::L2_ploadrif_pi:
1477     case Hexagon::L2_ploadrht_pi:
1478     case Hexagon::L2_ploadrhf_pi:
1479     case Hexagon::L2_ploadrbt_pi:
1480     case Hexagon::L2_ploadrbf_pi:
1481     case Hexagon::L2_ploadruht_pi:
1482     case Hexagon::L2_ploadruhf_pi:
1483     case Hexagon::L2_ploadrubt_pi:
1484     case Hexagon::L2_ploadrubf_pi:
1485     case Hexagon::L4_ploadrdt_rr:
1486     case Hexagon::L4_ploadrdf_rr:
1487     case Hexagon::L4_ploadrbt_rr:
1488     case Hexagon::L4_ploadrbf_rr:
1489     case Hexagon::L4_ploadrubt_rr:
1490     case Hexagon::L4_ploadrubf_rr:
1491     case Hexagon::L4_ploadrht_rr:
1492     case Hexagon::L4_ploadrhf_rr:
1493     case Hexagon::L4_ploadruht_rr:
1494     case Hexagon::L4_ploadruhf_rr:
1495     case Hexagon::L4_ploadrit_rr:
1496     case Hexagon::L4_ploadrif_rr:
1497       return true;
1498   }
1499 }
1500
1501 // Returns true if an instruction is a conditional store.
1502 //
1503 // Note: It doesn't include conditional new-value stores as they can't be
1504 // converted to .new predicate.
1505 //
1506 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
1507 //                ^           ^
1508 //               /             \ (not OK. it will cause new-value store to be
1509 //              /               X conditional on p0.new while R2 producer is
1510 //             /                 \ on p0)
1511 //            /                   \.
1512 //     p.new store                 p.old NV store
1513 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
1514 //            ^                  ^
1515 //             \                /
1516 //              \              /
1517 //               \            /
1518 //                 p.old store
1519 //             [if (p0)memw(R0+#0)=R2]
1520 //
1521 // The above diagram shows the steps involoved in the conversion of a predicated
1522 // store instruction to its .new predicated new-value form.
1523 //
1524 // The following set of instructions further explains the scenario where
1525 // conditional new-value store becomes invalid when promoted to .new predicate
1526 // form.
1527 //
1528 // { 1) if (p0) r0 = add(r1, r2)
1529 //   2) p0 = cmp.eq(r3, #0) }
1530 //
1531 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
1532 // the first two instructions because in instr 1, r0 is conditional on old value
1533 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
1534 // is not valid for new-value stores.
1535 bool HexagonInstrInfo::
1536 isConditionalStore (const MachineInstr* MI) const {
1537   switch (MI->getOpcode())
1538   {
1539     default: return false;
1540     case Hexagon::S4_storeirbt_io:
1541     case Hexagon::S4_storeirbf_io:
1542     case Hexagon::S4_pstorerbt_rr:
1543     case Hexagon::S4_pstorerbf_rr:
1544     case Hexagon::S2_pstorerbt_io:
1545     case Hexagon::S2_pstorerbf_io:
1546     case Hexagon::S2_pstorerbt_pi:
1547     case Hexagon::S2_pstorerbf_pi:
1548     case Hexagon::S2_pstorerdt_io:
1549     case Hexagon::S2_pstorerdf_io:
1550     case Hexagon::S4_pstorerdt_rr:
1551     case Hexagon::S4_pstorerdf_rr:
1552     case Hexagon::S2_pstorerdt_pi:
1553     case Hexagon::S2_pstorerdf_pi:
1554     case Hexagon::S2_pstorerht_io:
1555     case Hexagon::S2_pstorerhf_io:
1556     case Hexagon::S4_storeirht_io:
1557     case Hexagon::S4_storeirhf_io:
1558     case Hexagon::S4_pstorerht_rr:
1559     case Hexagon::S4_pstorerhf_rr:
1560     case Hexagon::S2_pstorerht_pi:
1561     case Hexagon::S2_pstorerhf_pi:
1562     case Hexagon::S2_pstorerit_io:
1563     case Hexagon::S2_pstorerif_io:
1564     case Hexagon::S4_storeirit_io:
1565     case Hexagon::S4_storeirif_io:
1566     case Hexagon::S4_pstorerit_rr:
1567     case Hexagon::S4_pstorerif_rr:
1568     case Hexagon::S2_pstorerit_pi:
1569     case Hexagon::S2_pstorerif_pi:
1570
1571     // V4 global address store before promoting to dot new.
1572     case Hexagon::S4_pstorerdt_abs:
1573     case Hexagon::S4_pstorerdf_abs:
1574     case Hexagon::S4_pstorerbt_abs:
1575     case Hexagon::S4_pstorerbf_abs:
1576     case Hexagon::S4_pstorerht_abs:
1577     case Hexagon::S4_pstorerhf_abs:
1578     case Hexagon::S4_pstorerit_abs:
1579     case Hexagon::S4_pstorerif_abs:
1580       return true;
1581
1582     // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
1583     // from the "Conditional Store" list. Because a predicated new value store
1584     // would NOT be promoted to a double dot new store. See diagram below:
1585     // This function returns yes for those stores that are predicated but not
1586     // yet promoted to predicate dot new instructions.
1587     //
1588     //                          +---------------------+
1589     //                    /-----| if (p0) memw(..)=r0 |---------\~
1590     //                   ||     +---------------------+         ||
1591     //          promote  ||       /\       /\                   ||  promote
1592     //                   ||      /||\     /||\                  ||
1593     //                  \||/    demote     ||                  \||/
1594     //                   \/       ||       ||                   \/
1595     //       +-------------------------+   ||   +-------------------------+
1596     //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
1597     //       +-------------------------+   ||   +-------------------------+
1598     //                        ||           ||         ||
1599     //                        ||         demote      \||/
1600     //                      promote        ||         \/ NOT possible
1601     //                        ||           ||         /\~
1602     //                       \||/          ||        /||\~
1603     //                        \/           ||         ||
1604     //                      +-----------------------------+
1605     //                      | if (p0.new) memw(..)=r0.new |
1606     //                      +-----------------------------+
1607     //                           Double Dot New Store
1608     //
1609   }
1610 }
1611
1612
1613 bool HexagonInstrInfo::isNewValueJump(const MachineInstr *MI) const {
1614   if (isNewValue(MI) && isBranch(MI))
1615     return true;
1616   return false;
1617 }
1618
1619 bool HexagonInstrInfo::isNewValueJump(Opcode_t Opcode) const {
1620   return isNewValue(Opcode) && get(Opcode).isBranch() && isPredicated(Opcode);
1621 }
1622
1623 bool HexagonInstrInfo::isPostIncrement (const MachineInstr* MI) const {
1624   return (getAddrMode(MI) == HexagonII::PostInc);
1625 }
1626
1627 // Returns true, if any one of the operands is a dot new
1628 // insn, whether it is predicated dot new or register dot new.
1629 bool HexagonInstrInfo::isDotNewInst (const MachineInstr* MI) const {
1630   return (isNewValueInst(MI) ||
1631      (isPredicated(MI) && isPredicatedNew(MI)));
1632 }
1633
1634 // Returns the most basic instruction for the .new predicated instructions and
1635 // new-value stores.
1636 // For example, all of the following instructions will be converted back to the
1637 // same instruction:
1638 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
1639 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
1640 // 3) if (p0.new) memw(R0+#0) = R1      --->
1641 //
1642
1643 int HexagonInstrInfo::GetDotOldOp(const int opc) const {
1644   int NewOp = opc;
1645   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
1646     NewOp = Hexagon::getPredOldOpcode(NewOp);
1647     assert(NewOp >= 0 &&
1648            "Couldn't change predicate new instruction to its old form.");
1649   }
1650
1651   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
1652     NewOp = Hexagon::getNonNVStore(NewOp);
1653     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
1654   }
1655   return NewOp;
1656 }
1657
1658 // Return the new value instruction for a given store.
1659 int HexagonInstrInfo::GetDotNewOp(const MachineInstr* MI) const {
1660   int NVOpcode = Hexagon::getNewValueOpcode(MI->getOpcode());
1661   if (NVOpcode >= 0) // Valid new-value store instruction.
1662     return NVOpcode;
1663
1664   switch (MI->getOpcode()) {
1665   default: llvm_unreachable("Unknown .new type");
1666   case Hexagon::S4_storerb_ur:
1667     return Hexagon::S4_storerbnew_ur;
1668
1669   case Hexagon::S4_storerh_ur:
1670     return Hexagon::S4_storerhnew_ur;
1671
1672   case Hexagon::S4_storeri_ur:
1673     return Hexagon::S4_storerinew_ur;
1674
1675   case Hexagon::S2_storerb_pci:
1676     return Hexagon::S2_storerb_pci;
1677
1678   case Hexagon::S2_storeri_pci:
1679     return Hexagon::S2_storeri_pci;
1680
1681   case Hexagon::S2_storerh_pci:
1682     return Hexagon::S2_storerh_pci;
1683
1684   case Hexagon::S2_storerd_pci:
1685     return Hexagon::S2_storerd_pci;
1686
1687   case Hexagon::S2_storerf_pci:
1688     return Hexagon::S2_storerf_pci;
1689   }
1690   return 0;
1691 }
1692
1693 // Return .new predicate version for an instruction.
1694 int HexagonInstrInfo::GetDotNewPredOp(MachineInstr *MI,
1695                                       const MachineBranchProbabilityInfo
1696                                       *MBPI) const {
1697
1698   int NewOpcode = Hexagon::getPredNewOpcode(MI->getOpcode());
1699   if (NewOpcode >= 0) // Valid predicate new instruction
1700     return NewOpcode;
1701
1702   switch (MI->getOpcode()) {
1703   default: llvm_unreachable("Unknown .new type");
1704   // Condtional Jumps
1705   case Hexagon::J2_jumpt:
1706   case Hexagon::J2_jumpf:
1707     return getDotNewPredJumpOp(MI, MBPI);
1708
1709   case Hexagon::J2_jumprt:
1710     return Hexagon::J2_jumptnewpt;
1711
1712   case Hexagon::J2_jumprf:
1713     return Hexagon::J2_jumprfnewpt;
1714
1715   case Hexagon::JMPrett:
1716     return Hexagon::J2_jumprtnewpt;
1717
1718   case Hexagon::JMPretf:
1719     return Hexagon::J2_jumprfnewpt;
1720
1721
1722   // Conditional combine
1723   case Hexagon::C2_ccombinewt:
1724     return Hexagon::C2_ccombinewnewt;
1725   case Hexagon::C2_ccombinewf:
1726     return Hexagon::C2_ccombinewnewf;
1727   }
1728 }
1729
1730
1731 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr* MI) const {
1732   const uint64_t F = MI->getDesc().TSFlags;
1733
1734   return((F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask);
1735 }
1736
1737 /// immediateExtend - Changes the instruction in place to one using an immediate
1738 /// extender.
1739 void HexagonInstrInfo::immediateExtend(MachineInstr *MI) const {
1740   assert((isExtendable(MI)||isConstExtended(MI)) &&
1741                                "Instruction must be extendable");
1742   // Find which operand is extendable.
1743   short ExtOpNum = getCExtOpNum(MI);
1744   MachineOperand &MO = MI->getOperand(ExtOpNum);
1745   // This needs to be something we understand.
1746   assert((MO.isMBB() || MO.isImm()) &&
1747          "Branch with unknown extendable field type");
1748   // Mark given operand as extended.
1749   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
1750 }
1751
1752 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1753     const TargetSubtargetInfo &STI) const {
1754   const InstrItineraryData *II = STI.getInstrItineraryData();
1755   return static_cast<const HexagonSubtarget &>(STI).createDFAPacketizer(II);
1756 }
1757
1758 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1759                                             const MachineBasicBlock *MBB,
1760                                             const MachineFunction &MF) const {
1761   // Debug info is never a scheduling boundary. It's necessary to be explicit
1762   // due to the special treatment of IT instructions below, otherwise a
1763   // dbg_value followed by an IT will result in the IT instruction being
1764   // considered a scheduling hazard, which is wrong. It should be the actual
1765   // instruction preceding the dbg_value instruction(s), just like it is
1766   // when debug info is not present.
1767   if (MI->isDebugValue())
1768     return false;
1769
1770   // Terminators and labels can't be scheduled around.
1771   if (MI->getDesc().isTerminator() || MI->isPosition() || MI->isInlineAsm())
1772     return true;
1773
1774   return false;
1775 }
1776
1777 bool HexagonInstrInfo::isConstExtended(const MachineInstr *MI) const {
1778   const uint64_t F = MI->getDesc().TSFlags;
1779   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
1780   if (isExtended) // Instruction must be extended.
1781     return true;
1782
1783   unsigned isExtendable =
1784     (F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
1785   if (!isExtendable)
1786     return false;
1787
1788   short ExtOpNum = getCExtOpNum(MI);
1789   const MachineOperand &MO = MI->getOperand(ExtOpNum);
1790   // Use MO operand flags to determine if MO
1791   // has the HMOTF_ConstExtended flag set.
1792   if (MO.getTargetFlags() && HexagonII::HMOTF_ConstExtended)
1793     return true;
1794   // If this is a Machine BB address we are talking about, and it is
1795   // not marked as extended, say so.
1796   if (MO.isMBB())
1797     return false;
1798
1799   // We could be using an instruction with an extendable immediate and shoehorn
1800   // a global address into it. If it is a global address it will be constant
1801   // extended. We do this for COMBINE.
1802   // We currently only handle isGlobal() because it is the only kind of
1803   // object we are going to end up with here for now.
1804   // In the future we probably should add isSymbol(), etc.
1805   if (MO.isGlobal() || MO.isSymbol() || MO.isBlockAddress() ||
1806       MO.isJTI() || MO.isCPI())
1807     return true;
1808
1809   // If the extendable operand is not 'Immediate' type, the instruction should
1810   // have 'isExtended' flag set.
1811   assert(MO.isImm() && "Extendable operand must be Immediate type");
1812
1813   int MinValue = getMinValue(MI);
1814   int MaxValue = getMaxValue(MI);
1815   int ImmValue = MO.getImm();
1816
1817   return (ImmValue < MinValue || ImmValue > MaxValue);
1818 }
1819
1820 // Return the number of bytes required to encode the instruction.
1821 // Hexagon instructions are fixed length, 4 bytes, unless they
1822 // use a constant extender, which requires another 4 bytes.
1823 // For debug instructions and prolog labels, return 0.
1824 unsigned HexagonInstrInfo::getSize(const MachineInstr *MI) const {
1825
1826   if (MI->isDebugValue() || MI->isPosition())
1827     return 0;
1828
1829   unsigned Size = MI->getDesc().getSize();
1830   if (!Size)
1831     // Assume the default insn size in case it cannot be determined
1832     // for whatever reason.
1833     Size = HEXAGON_INSTR_SIZE;
1834
1835   if (isConstExtended(MI) || isExtended(MI))
1836     Size += HEXAGON_INSTR_SIZE;
1837
1838   return Size;
1839 }
1840
1841 // Returns the opcode to use when converting MI, which is a conditional jump,
1842 // into a conditional instruction which uses the .new value of the predicate.
1843 // We also use branch probabilities to add a hint to the jump.
1844 int
1845 HexagonInstrInfo::getDotNewPredJumpOp(MachineInstr *MI,
1846                                   const
1847                                   MachineBranchProbabilityInfo *MBPI) const {
1848
1849   // We assume that block can have at most two successors.
1850   bool taken = false;
1851   MachineBasicBlock *Src = MI->getParent();
1852   MachineOperand *BrTarget = &MI->getOperand(1);
1853   MachineBasicBlock *Dst = BrTarget->getMBB();
1854
1855   const BranchProbability Prediction = MBPI->getEdgeProbability(Src, Dst);
1856   if (Prediction >= BranchProbability(1,2))
1857     taken = true;
1858
1859   switch (MI->getOpcode()) {
1860   case Hexagon::J2_jumpt:
1861     return taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
1862   case Hexagon::J2_jumpf:
1863     return taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
1864
1865   default:
1866     llvm_unreachable("Unexpected jump instruction.");
1867   }
1868 }
1869 // Returns true if a particular operand is extendable for an instruction.
1870 bool HexagonInstrInfo::isOperandExtended(const MachineInstr *MI,
1871                                          unsigned short OperandNum) const {
1872   const uint64_t F = MI->getDesc().TSFlags;
1873
1874   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
1875           == OperandNum;
1876 }
1877
1878 // Returns Operand Index for the constant extended instruction.
1879 unsigned short HexagonInstrInfo::getCExtOpNum(const MachineInstr *MI) const {
1880   const uint64_t F = MI->getDesc().TSFlags;
1881   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask);
1882 }
1883
1884 // Returns the min value that doesn't need to be extended.
1885 int HexagonInstrInfo::getMinValue(const MachineInstr *MI) const {
1886   const uint64_t F = MI->getDesc().TSFlags;
1887   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1888                     & HexagonII::ExtentSignedMask;
1889   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1890                     & HexagonII::ExtentBitsMask;
1891
1892   if (isSigned) // if value is signed
1893     return -1U << (bits - 1);
1894   else
1895     return 0;
1896 }
1897
1898 // Returns the max value that doesn't need to be extended.
1899 int HexagonInstrInfo::getMaxValue(const MachineInstr *MI) const {
1900   const uint64_t F = MI->getDesc().TSFlags;
1901   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1902                     & HexagonII::ExtentSignedMask;
1903   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1904                     & HexagonII::ExtentBitsMask;
1905
1906   if (isSigned) // if value is signed
1907     return ~(-1U << (bits - 1));
1908   else
1909     return ~(-1U << bits);
1910 }
1911
1912 // Returns true if an instruction can be converted into a non-extended
1913 // equivalent instruction.
1914 bool HexagonInstrInfo::NonExtEquivalentExists (const MachineInstr *MI) const {
1915
1916   short NonExtOpcode;
1917   // Check if the instruction has a register form that uses register in place
1918   // of the extended operand, if so return that as the non-extended form.
1919   if (Hexagon::getRegForm(MI->getOpcode()) >= 0)
1920     return true;
1921
1922   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1923     // Check addressing mode and retrieve non-ext equivalent instruction.
1924
1925     switch (getAddrMode(MI)) {
1926     case HexagonII::Absolute :
1927       // Load/store with absolute addressing mode can be converted into
1928       // base+offset mode.
1929       NonExtOpcode = Hexagon::getBasedWithImmOffset(MI->getOpcode());
1930       break;
1931     case HexagonII::BaseImmOffset :
1932       // Load/store with base+offset addressing mode can be converted into
1933       // base+register offset addressing mode. However left shift operand should
1934       // be set to 0.
1935       NonExtOpcode = Hexagon::getBaseWithRegOffset(MI->getOpcode());
1936       break;
1937     default:
1938       return false;
1939     }
1940     if (NonExtOpcode < 0)
1941       return false;
1942     return true;
1943   }
1944   return false;
1945 }
1946
1947 // Returns opcode of the non-extended equivalent instruction.
1948 short HexagonInstrInfo::getNonExtOpcode (const MachineInstr *MI) const {
1949
1950   // Check if the instruction has a register form that uses register in place
1951   // of the extended operand, if so return that as the non-extended form.
1952   short NonExtOpcode = Hexagon::getRegForm(MI->getOpcode());
1953     if (NonExtOpcode >= 0)
1954       return NonExtOpcode;
1955
1956   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1957     // Check addressing mode and retrieve non-ext equivalent instruction.
1958     switch (getAddrMode(MI)) {
1959     case HexagonII::Absolute :
1960       return Hexagon::getBasedWithImmOffset(MI->getOpcode());
1961     case HexagonII::BaseImmOffset :
1962       return Hexagon::getBaseWithRegOffset(MI->getOpcode());
1963     default:
1964       return -1;
1965     }
1966   }
1967   return -1;
1968 }
1969
1970 bool HexagonInstrInfo::PredOpcodeHasJMP_c(Opcode_t Opcode) const {
1971   return (Opcode == Hexagon::J2_jumpt) ||
1972          (Opcode == Hexagon::J2_jumpf) ||
1973          (Opcode == Hexagon::J2_jumptnewpt) ||
1974          (Opcode == Hexagon::J2_jumpfnewpt) ||
1975          (Opcode == Hexagon::J2_jumpt) ||
1976          (Opcode == Hexagon::J2_jumpf);
1977 }
1978
1979 bool HexagonInstrInfo::predOpcodeHasNot(ArrayRef<MachineOperand> Cond) const {
1980   if (Cond.empty() || !isPredicated(Cond[0].getImm()))
1981     return false;
1982   return !isPredicatedTrue(Cond[0].getImm());
1983 }
1984
1985 bool HexagonInstrInfo::isEndLoopN(Opcode_t Opcode) const {
1986   return (Opcode == Hexagon::ENDLOOP0 ||
1987           Opcode == Hexagon::ENDLOOP1);
1988 }
1989
1990 bool HexagonInstrInfo::getPredReg(ArrayRef<MachineOperand> Cond,
1991                                   unsigned &PredReg, unsigned &PredRegPos,
1992                                   unsigned &PredRegFlags) const {
1993   if (Cond.empty())
1994     return false;
1995   assert(Cond.size() == 2);
1996   if (isNewValueJump(Cond[0].getImm()) || Cond[1].isMBB()) {
1997      DEBUG(dbgs() << "No predregs for new-value jumps/endloop");
1998      return false;
1999   }
2000   PredReg = Cond[1].getReg();
2001   PredRegPos = 1;
2002   // See IfConversion.cpp why we add RegState::Implicit | RegState::Undef
2003   PredRegFlags = 0;
2004   if (Cond[1].isImplicit())
2005     PredRegFlags = RegState::Implicit;
2006   if (Cond[1].isUndef())
2007     PredRegFlags |= RegState::Undef;
2008   return true;
2009 }
2010