Replace uint16_t with the MCPhysReg typedef in many places. A lot of physical registe...
[oota-llvm.git] / lib / Target / Hexagon / MCTargetDesc / HexagonMCChecker.cpp
1 //===----- HexagonMCChecker.cpp - Instruction bundle checking -------------===//
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 implements the checking of insns inside a bundle according to the
11 // packet constraint rules of the Hexagon ISA.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "HexagonMCChecker.h"
16
17 #include "HexagonBaseInfo.h"
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/MC/MCInstrDesc.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 static cl::opt<bool> RelaxNVChecks("relax-nv-checks", cl::init(false),
29   cl::ZeroOrMore, cl::Hidden, cl::desc("Relax checks of new-value validity"));
30
31 const HexagonMCChecker::PredSense
32   HexagonMCChecker::Unconditional(Hexagon::NoRegister, false);
33
34 void HexagonMCChecker::init() {
35   // Initialize read-only registers set.
36   ReadOnly.insert(Hexagon::PC);
37
38   // Figure out the loop-registers definitions.
39   if (HexagonMCInstrInfo::isInnerLoop(MCB)) {
40     Defs[Hexagon::SA0].insert(Unconditional); // FIXME: define or change SA0?
41     Defs[Hexagon::LC0].insert(Unconditional);
42   }
43   if (HexagonMCInstrInfo::isOuterLoop(MCB)) {
44     Defs[Hexagon::SA1].insert(Unconditional); // FIXME: define or change SA0?
45     Defs[Hexagon::LC1].insert(Unconditional);
46   }
47
48   if (HexagonMCInstrInfo::isBundle(MCB))
49     // Unfurl a bundle.
50     for (auto const&I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
51       init(*I.getInst());
52     }
53   else
54     init(MCB);
55 }
56
57 void HexagonMCChecker::init(MCInst const& MCI) {
58   const MCInstrDesc& MCID = HexagonMCInstrInfo::getDesc(MCII, MCI);
59   unsigned PredReg = Hexagon::NoRegister;
60   bool isTrue = false;
61
62   // Get used registers.
63   for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
64     if (MCI.getOperand(i).isReg()) {
65       unsigned R = MCI.getOperand(i).getReg();
66
67       if (HexagonMCInstrInfo::isPredicated(MCII, MCI) && isPredicateRegister(R)) {
68         // Note an used predicate register.
69         PredReg = R;
70         isTrue = HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI);
71
72         // Note use of new predicate register.
73         if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
74           NewPreds.insert(PredReg);
75       }
76       else
77         // Note register use.  Super-registers are not tracked directly,
78         // but their components.
79         for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
80            SRI.isValid();
81            ++SRI)
82          if (!MCSubRegIterator(*SRI, &RI).isValid())
83            // Skip super-registers used indirectly.
84            Uses.insert(*SRI);
85     }
86
87   // Get implicit register definitions.
88   const MCPhysReg *ImpDefs = MCID.getImplicitDefs();
89   for (unsigned i = 0; i < MCID.getNumImplicitDefs(); ++i) {
90     unsigned R = ImpDefs[i];
91
92     if (Hexagon::R31 != R && MCID.isCall())
93       // Any register other than the LR and the PC are actually volatile ones
94       // as defined by the ABI, not modified implicitly by the call insn.
95       continue;
96     if (Hexagon::PC == R)
97       // Branches are the only insns that can change the PC,
98       // otherwise a read-only register.
99       continue;
100
101     if (Hexagon::USR_OVF == R)
102       // Many insns change the USR implicitly, but only one or another flag.
103       // The instruction table models the USR.OVF flag, which can be implicitly
104       // modified more than once, but cannot be modified in the same packet
105       // with an instruction that modifies is explicitly. Deal with such situ-
106       // ations individually.
107       SoftDefs.insert(R);
108     else if (isPredicateRegister(R) && HexagonMCInstrInfo::isPredicateLate(MCII, MCI))
109       // Include implicit late predicates.
110       LatePreds.insert(R);
111     else
112       Defs[R].insert(PredSense(PredReg, isTrue));
113   }
114
115   // Figure out explicit register definitions.
116   for (unsigned i = 0; i < MCID.getNumDefs(); ++i) {
117     unsigned R = MCI.getOperand(i).getReg(),
118              S = Hexagon::NoRegister;
119
120     // Note register definitions, direct ones as well as indirect side-effects.
121     // Super-registers are not tracked directly, but their components.
122     for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
123         SRI.isValid();
124         ++SRI) {
125       if (MCSubRegIterator(*SRI, &RI).isValid())
126         // Skip super-registers defined indirectly.
127         continue;
128
129       if (R == *SRI) {
130         if (S == R)
131           // Avoid scoring the defined register multiple times.
132           continue;
133         else
134           // Note that the defined register has already been scored.
135           S = R;
136       }
137
138       if (Hexagon::P3_0 != R && Hexagon::P3_0 == *SRI)
139         // P3:0 is a special case, since multiple predicate register definitions
140         // in a packet is allowed as the equivalent of their logical "and".
141         // Only an explicit definition of P3:0 is noted as such; if a
142         // side-effect, then note as a soft definition.
143         SoftDefs.insert(*SRI);
144       else if (HexagonMCInstrInfo::isPredicateLate(MCII, MCI) && isPredicateRegister(*SRI))
145         // Some insns produce predicates too late to be used in the same packet.
146         LatePreds.insert(*SRI);
147       else if (i == 0 && llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeCVI_VM_CUR_LD)
148         // Current loads should be used in the same packet.
149         // TODO: relies on the impossibility of a current and a temporary loads
150         // in the same packet.
151         CurDefs.insert(*SRI), Defs[*SRI].insert(PredSense(PredReg, isTrue));
152       else if (i == 0 && llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeCVI_VM_TMP_LD)
153         // Temporary loads should be used in the same packet, but don't commit
154         // results, so it should be disregarded if another insn changes the same
155         // register.
156         // TODO: relies on the impossibility of a current and a temporary loads
157         // in the same packet.
158         TmpDefs.insert(*SRI);
159       else if (i <= 1 && llvm::HexagonMCInstrInfo::hasNewValue2(MCII, MCI) )
160         // vshuff(Vx, Vy, Rx) <- Vx(0) and Vy(1) are both source and
161         // destination registers with this instruction. same for vdeal(Vx,Vy,Rx)
162         Uses.insert(*SRI);
163       else
164         Defs[*SRI].insert(PredSense(PredReg, isTrue));
165     }
166   }
167
168   // Figure out register definitions that produce new values.
169   if (HexagonMCInstrInfo::hasNewValue(MCII, MCI)) {
170     unsigned R = HexagonMCInstrInfo::getNewValueOperand(MCII, MCI).getReg();
171
172     if (HexagonMCInstrInfo::isCompound(MCII, MCI))
173       compoundRegisterMap(R); // Compound insns have a limited register range.
174
175     for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
176         SRI.isValid();
177         ++SRI)
178       if (!MCSubRegIterator(*SRI, &RI).isValid())
179         // No super-registers defined indirectly.
180         NewDefs[*SRI].push_back(NewSense::Def(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI),
181                                               HexagonMCInstrInfo::isFloat(MCII, MCI)));
182
183     // For fairly unique 2-dot-new producers, example:
184     // vdeal(V1, V9, R0) V1.new and V9.new can be used by consumers.
185     if (HexagonMCInstrInfo::hasNewValue2(MCII, MCI)) {
186       unsigned R2 = HexagonMCInstrInfo::getNewValueOperand2(MCII, MCI).getReg();
187
188       for(MCRegAliasIterator SRI(R2, &RI, !MCSubRegIterator(R2, &RI).isValid());
189           SRI.isValid();
190           ++SRI)
191         if (!MCSubRegIterator(*SRI, &RI).isValid())
192           NewDefs[*SRI].push_back(NewSense::Def(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI),
193                                                 HexagonMCInstrInfo::isFloat(MCII, MCI)));
194     }
195   }
196
197   // Figure out definitions of new predicate registers.
198   if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
199     for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
200       if (MCI.getOperand(i).isReg()) {
201         unsigned P = MCI.getOperand(i).getReg();
202
203         if (isPredicateRegister(P))
204           NewPreds.insert(P);
205       }
206
207   // Figure out uses of new values.
208   if (HexagonMCInstrInfo::isNewValue(MCII, MCI)) {
209     unsigned N = HexagonMCInstrInfo::getNewValueOperand(MCII, MCI).getReg();
210
211     if (!MCSubRegIterator(N, &RI).isValid()) {
212       // Super-registers cannot use new values.
213       if (MCID.isBranch())
214         NewUses[N] = NewSense::Jmp(llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeNV);
215       else
216         NewUses[N] = NewSense::Use(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI));
217     }
218   }
219 }
220
221 HexagonMCChecker::HexagonMCChecker(MCInstrInfo const &MCII, MCSubtargetInfo const &STI, MCInst &mcb, MCInst &mcbdx,
222                                    MCRegisterInfo const &ri)
223     : MCB(mcb), MCBDX(mcbdx), RI(ri), MCII(MCII), STI(STI),
224       bLoadErrInfo(false) {
225   init();
226 }
227
228 bool HexagonMCChecker::check() {
229   bool chkB = checkBranches();
230   bool chkP = checkPredicates();
231   bool chkNV = checkNewValues();
232   bool chkR = checkRegisters();
233   bool chkS = checkSolo();
234   bool chkSh = checkShuffle();
235   bool chkSl = checkSlots();
236   bool chk = chkB && chkP && chkNV && chkR && chkS && chkSh && chkSl;
237
238   return chk;
239 }
240
241 bool HexagonMCChecker::checkSlots()
242
243 {
244   unsigned slotsUsed = 0;
245   for (auto HMI: HexagonMCInstrInfo::bundleInstructions(MCBDX)) {
246     MCInst const& MCI = *HMI.getInst();
247     if (HexagonMCInstrInfo::isImmext(MCI))
248       continue;
249     if (HexagonMCInstrInfo::isDuplex(MCII, MCI))
250       slotsUsed += 2;
251     else
252       ++slotsUsed;
253   }
254
255   if (slotsUsed > HEXAGON_PACKET_SIZE) {
256     HexagonMCErrInfo errInfo;
257     errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NOSLOTS);
258     addErrInfo(errInfo);
259     return false;
260   }
261   return true;
262 }
263
264 // Check legal use of branches.
265 bool HexagonMCChecker::checkBranches() {
266   HexagonMCErrInfo errInfo;
267   if (HexagonMCInstrInfo::isBundle(MCB)) {
268     bool hasConditional = false;
269     unsigned Branches = 0, Returns = 0, NewIndirectBranches = 0,
270              NewValueBranches = 0, Conditional = HEXAGON_PRESHUFFLE_PACKET_SIZE,
271              Unconditional = HEXAGON_PRESHUFFLE_PACKET_SIZE;
272
273     for (unsigned i = HexagonMCInstrInfo::bundleInstructionsOffset;
274          i < MCB.size(); ++i) {
275       MCInst const &MCI = *MCB.begin()[i].getInst();
276
277       if (HexagonMCInstrInfo::isImmext(MCI))
278         continue;
279       if (HexagonMCInstrInfo::getDesc(MCII, MCI).isBranch() ||
280           HexagonMCInstrInfo::getDesc(MCII, MCI).isCall()) {
281         ++Branches;
282         if (HexagonMCInstrInfo::getDesc(MCII, MCI).isIndirectBranch() &&
283             HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
284           ++NewIndirectBranches;
285         if (HexagonMCInstrInfo::isNewValue(MCII, MCI))
286           ++NewValueBranches;
287
288         if (HexagonMCInstrInfo::isPredicated(MCII, MCI) ||
289             HexagonMCInstrInfo::isPredicatedNew(MCII, MCI)) {
290           hasConditional = true;
291           Conditional = i; // Record the position of the conditional branch.
292         } else {
293           Unconditional = i; // Record the position of the unconditional branch.
294         }
295       }
296       if (HexagonMCInstrInfo::getDesc(MCII, MCI).isReturn() &&
297           HexagonMCInstrInfo::getDesc(MCII, MCI).mayLoad())
298         ++Returns;
299     }
300
301     if (Branches) // FIXME: should "Defs.count(Hexagon::PC)" be here too?
302       if (HexagonMCInstrInfo::isInnerLoop(MCB) ||
303           HexagonMCInstrInfo::isOuterLoop(MCB)) {
304         // Error out if there's any branch in a loop-end packet.
305         errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_ENDLOOP, Hexagon::PC);
306         addErrInfo(errInfo);
307         return false;
308       }
309     if (Branches > 1)
310       if (!hasConditional || Conditional > Unconditional) {
311         // Error out if more than one unconditional branch or
312         // the conditional branch appears after the unconditional one.
313         errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_BRANCHES);
314         addErrInfo(errInfo);
315         return false;
316       }
317   }
318
319   return true;
320 }
321
322 // Check legal use of predicate registers.
323 bool HexagonMCChecker::checkPredicates() {
324   HexagonMCErrInfo errInfo;
325   // Check for proper use of new predicate registers.
326   for (const auto& I : NewPreds) {
327     unsigned P = I;
328
329     if (!Defs.count(P) || LatePreds.count(P)) {
330       // Error out if the new predicate register is not defined,
331       // or defined "late"
332       // (e.g., "{ if (p3.new)... ; p3 = sp1loop0(#r7:2, Rs) }").
333       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NEWP, P);
334       addErrInfo(errInfo);
335       return false;
336     }
337   }
338
339   // Check for proper use of auto-anded of predicate registers.
340   for (const auto& I : LatePreds) {
341     unsigned P = I;
342
343     if (LatePreds.count(P) > 1 || Defs.count(P)) {
344       // Error out if predicate register defined "late" multiple times or
345       // defined late and regularly defined
346       // (e.g., "{ p3 = sp1loop0(...); p3 = cmp.eq(...) }".
347       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, P);
348       addErrInfo(errInfo);
349       return false;
350     }
351   }
352
353   return true;
354 }
355
356 // Check legal use of new values.
357 bool HexagonMCChecker::checkNewValues() {
358   HexagonMCErrInfo errInfo;
359   memset(&errInfo, 0, sizeof(errInfo));
360   for (auto& I : NewUses) {
361     unsigned R = I.first;
362     NewSense &US = I.second;
363
364     if (!hasValidNewValueDef(US, NewDefs[R])) {
365       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NEWV, R);
366       addErrInfo(errInfo);
367       return false;
368     }
369   }
370
371   return true;
372 }
373
374 // Check for legal register uses and definitions.
375 bool HexagonMCChecker::checkRegisters() {
376   HexagonMCErrInfo errInfo;
377   // Check for proper register definitions.
378   for (const auto& I : Defs) {
379     unsigned R = I.first;
380
381     if (ReadOnly.count(R)) {
382       // Error out for definitions of read-only registers.
383       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_READONLY, R);
384       addErrInfo(errInfo);
385       return false;
386     }
387     if (isLoopRegister(R) && Defs.count(R) > 1 &&
388         (HexagonMCInstrInfo::isInnerLoop(MCB) ||
389          HexagonMCInstrInfo::isOuterLoop(MCB))) {
390       // Error out for definitions of loop registers at the end of a loop.
391       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_LOOP, R);
392       addErrInfo(errInfo);
393       return false;
394     }
395     if (SoftDefs.count(R)) {
396       // Error out for explicit changes to registers also weakly defined
397       // (e.g., "{ usr = r0; r0 = sfadd(...) }").
398       unsigned UsrR = Hexagon::USR; // Silence warning about mixed types in ?:.
399       unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
400       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, BadR);
401       addErrInfo(errInfo);
402       return false;
403     }
404     if (!isPredicateRegister(R) && Defs[R].size() > 1) {
405       // Check for multiple register definitions.
406       PredSet &PM = Defs[R];
407
408       // Check for multiple unconditional register definitions.
409       if (PM.count(Unconditional)) {
410         // Error out on an unconditional change when there are any other
411         // changes, conditional or not.
412         unsigned UsrR = Hexagon::USR;
413         unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
414         errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, BadR);
415         addErrInfo(errInfo);
416         return false;
417       }
418       // Check for multiple conditional register definitions.
419       for (const auto& J : PM) {
420         PredSense P = J;
421
422         // Check for multiple uses of the same condition.
423         if (PM.count(P) > 1) {
424           // Error out on conditional changes based on the same predicate
425           // (e.g., "{ if (!p0) r0 =...; if (!p0) r0 =... }").
426           errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, R);
427           addErrInfo(errInfo);
428           return false;
429         }
430         // Check for the use of the complementary condition.
431         P.second = !P.second;
432         if (PM.count(P) && PM.size() > 2) {
433           // Error out on conditional changes based on the same predicate
434           // multiple times
435           // (e.g., "{ if (p0) r0 =...; if (!p0) r0 =... }; if (!p0) r0 =... }").
436           errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, R);
437           addErrInfo(errInfo);
438           return false;
439         }
440       }
441     }
442   }
443
444   // Check for use of current definitions.
445   for (const auto& I : CurDefs) {
446     unsigned R = I;
447
448     if (!Uses.count(R)) {
449       // Warn on an unused current definition.
450       errInfo.setWarning(HexagonMCErrInfo::CHECK_WARN_CURRENT, R);
451       addErrInfo(errInfo);
452       return true;
453     }
454   }
455
456   // Check for use of temporary definitions.
457   for (const auto& I : TmpDefs) {
458     unsigned R = I;
459
460     if (!Uses.count(R)) {
461       // special case for vhist
462       bool vHistFound = false;
463       for (auto const&HMI : HexagonMCInstrInfo::bundleInstructions(MCB)) {
464         if(llvm::HexagonMCInstrInfo::getType(MCII, *HMI.getInst()) == HexagonII::TypeCVI_HIST) {
465           vHistFound = true;  // vhist() implicitly uses ALL REGxx.tmp
466           break;
467         }
468       }
469       // Warn on an unused temporary definition.
470       if (vHistFound == false) {
471         errInfo.setWarning(HexagonMCErrInfo::CHECK_WARN_TEMPORARY, R);
472         addErrInfo(errInfo);
473         return true;
474       }
475     }
476   }
477
478   return true;
479 }
480
481 // Check for legal use of solo insns.
482 bool HexagonMCChecker::checkSolo() {
483   HexagonMCErrInfo errInfo;
484   if (HexagonMCInstrInfo::isBundle(MCB) &&
485       HexagonMCInstrInfo::bundleSize(MCB) > 1) {
486     for (auto const&I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
487       if (llvm::HexagonMCInstrInfo::isSolo(MCII, *I.getInst())) {
488         errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SOLO);
489         addErrInfo(errInfo);
490         return false;
491       }
492     }
493   }
494
495   return true;
496 }
497
498 bool HexagonMCChecker::checkShuffle() {
499   HexagonMCErrInfo errInfo;
500   // Branch info is lost when duplexing. The unduplexed insns must be
501   // checked and only branch errors matter for this case.
502   HexagonMCShuffler MCS(MCII, STI, MCB);
503   if (!MCS.check()) {
504     if (MCS.getError() == HexagonShuffler::SHUFFLE_ERROR_BRANCHES) {
505       errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SHUFFLE);
506       errInfo.setShuffleError(MCS.getError());
507       addErrInfo(errInfo);
508       return false;
509     }
510   }
511   HexagonMCShuffler MCSDX(MCII, STI, MCBDX);
512   if (!MCSDX.check()) {
513     errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SHUFFLE);
514     errInfo.setShuffleError(MCSDX.getError());
515     addErrInfo(errInfo);
516     return false;
517   }
518   return true;
519 }
520
521 void HexagonMCChecker::compoundRegisterMap(unsigned& Register) {
522   switch (Register) {
523   default:
524     break;
525   case Hexagon::R15:
526     Register = Hexagon::R23;
527     break;
528   case Hexagon::R14:
529     Register = Hexagon::R22;
530     break;
531   case Hexagon::R13:
532     Register = Hexagon::R21;
533     break;
534   case Hexagon::R12:
535     Register = Hexagon::R20;
536     break;
537   case Hexagon::R11:
538     Register = Hexagon::R19;
539     break;
540   case Hexagon::R10:
541     Register = Hexagon::R18;
542     break;
543   case Hexagon::R9:
544     Register = Hexagon::R17;
545     break;
546   case Hexagon::R8:
547     Register = Hexagon::R16;
548     break;
549   }
550 }
551
552 bool HexagonMCChecker::hasValidNewValueDef(const NewSense &Use,
553       const NewSenseList &Defs) const {
554   bool Strict = !RelaxNVChecks;
555
556   for (unsigned i = 0, n = Defs.size(); i < n; ++i) {
557     const NewSense &Def = Defs[i];
558     // NVJ cannot use a new FP value [7.6.1]
559     if (Use.IsNVJ && (Def.IsFloat || Def.PredReg != 0))
560       continue;
561     // If the definition was not predicated, then it does not matter if
562     // the use is.
563     if (Def.PredReg == 0)
564       return true;
565     // With the strict checks, both the definition and the use must be
566     // predicated on the same register and condition.
567     if (Strict) {
568       if (Def.PredReg == Use.PredReg && Def.Cond == Use.Cond)
569         return true;
570     } else {
571       // With the relaxed checks, if the definition was predicated, the only
572       // detectable violation is if the use is predicated on the opposing
573       // condition, otherwise, it's ok.
574       if (Def.PredReg != Use.PredReg || Def.Cond == Use.Cond)
575         return true;
576     }
577   }
578   return false;
579 }
580