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