blob: c4a0a62e04328a3914f92d47f952870660c3efe4 [file] [log] [blame]
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00001//===--- HexagonConstPropagation.cpp --------------------------------------===//
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#define DEBUG_TYPE "hcp"
11
12#include "HexagonInstrInfo.h"
13#include "HexagonRegisterInfo.h"
14#include "HexagonSubtarget.h"
15
16#include "llvm/ADT/PostOrderIterator.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Target/TargetInstrInfo.h"
27
28#include <map>
29#include <queue>
30#include <set>
31
32using namespace llvm;
33
34namespace {
35 class LatticeCell;
36
37 // Properties of a value that are tracked by the propagation.
38 // A property that is marked as present (i.e. bit is set) dentes that the
39 // value is known (proven) to have this property. Not all combinations
40 // of bits make sense, for example Zero and NonZero are mutually exclusive,
41 // but on the other hand, Zero implies Finite. In this case, whenever
42 // the Zero property is present, Finite should also be present.
43 class ConstantProperties {
44 public:
45 enum {
46 Unknown = 0x0000,
47 Zero = 0x0001,
48 NonZero = 0x0002,
49 Finite = 0x0004,
50 Infinity = 0x0008,
51 NaN = 0x0010,
52 SignedZero = 0x0020,
53 NumericProperties = (Zero|NonZero|Finite|Infinity|NaN|SignedZero),
54 PosOrZero = 0x0100,
55 NegOrZero = 0x0200,
56 SignProperties = (PosOrZero|NegOrZero),
57 Everything = (NumericProperties|SignProperties)
58 };
59
60 // For a given constant, deduce the set of trackable properties that this
61 // constant has.
62 static uint32_t deduce(const Constant *C);
63 };
64
65
66 // A representation of a register as it can appear in a MachineOperand,
67 // i.e. a pair register:subregister.
68 struct Register {
69 unsigned Reg, SubReg;
70 explicit Register(unsigned R, unsigned SR = 0) : Reg(R), SubReg(SR) {}
71 explicit Register(const MachineOperand &MO)
72 : Reg(MO.getReg()), SubReg(MO.getSubReg()) {}
73 void print(const TargetRegisterInfo *TRI = 0) const {
74 dbgs() << PrintReg(Reg, TRI, SubReg);
75 }
76 bool operator== (const Register &R) const {
77 return (Reg == R.Reg) && (SubReg == R.SubReg);
78 }
79 };
80
81
82 // Lattice cell, based on that was described in the W-Z paper on constant
83 // propagation.
84 // Latice cell will be allowed to hold multiple constant values. While
85 // multiple values would normally indicate "bottom", we can still derive
86 // some useful information from them. For example, comparison X > 0
87 // could be folded if all the values in the cell associated with X are
88 // positive.
89 class LatticeCell {
90 private:
91 enum { Normal, Top, Bottom };
92 static const unsigned MaxCellSize = 4;
93 unsigned Kind:2;
94 unsigned Size:3;
95 unsigned IsSpecial:1;
96 unsigned :0;
97
98 public:
99 union {
100 uint32_t Properties;
101 const Constant *Value;
102 const Constant *Values[MaxCellSize];
103 };
104
105 LatticeCell() : Kind(Top), Size(0), IsSpecial(false) {
106 for (unsigned i = 0; i < MaxCellSize; ++i)
107 Values[i] = 0;
108 }
109
110 bool meet(const LatticeCell &L);
111 bool add(const Constant *C);
112 bool add(uint32_t Property);
113 uint32_t properties() const;
114 unsigned size() const { return Size; }
115
116 LatticeCell &operator= (const LatticeCell &L) {
117 if (this != &L) {
118 // This memcpy also copies Properties (when L.Size == 0).
119 uint32_t N = L.IsSpecial ? sizeof L.Properties
120 : L.Size*sizeof(const Constant*);
121 memcpy(Values, L.Values, N);
122 Kind = L.Kind;
123 Size = L.Size;
124 IsSpecial = L.IsSpecial;
125 }
126 return *this;
127 }
128
129 bool isSingle() const { return size() == 1; }
130 bool isProperty() const { return IsSpecial; }
131 bool isTop() const { return Kind == Top; }
132 bool isBottom() const { return Kind == Bottom; }
133 bool setBottom() {
134 bool Changed = (Kind != Bottom);
135 Kind = Bottom;
136 Size = 0;
137 IsSpecial = false;
138 return Changed;
139 }
140 void print(raw_ostream &os) const;
141
142 private:
143 void setProperty() {
144 IsSpecial = true;
145 Size = 0;
146 Kind = Normal;
147 }
148 bool convertToProperty();
149 };
150
151 raw_ostream &operator<< (raw_ostream &os, const LatticeCell &L) {
152 L.print(os);
153 return os;
154 }
155
156 class MachineConstEvaluator;
157
158 class MachineConstPropagator {
159 public:
160 MachineConstPropagator(MachineConstEvaluator &E) : MCE(E) {
161 Bottom.setBottom();
162 }
163
164 // Mapping: vreg -> cell
165 // The keys are registers _without_ subregisters. This won't allow
166 // definitions in the form of "vreg:subreg<def> = ...". Such definitions
167 // would be questionable from the point of view of SSA, since the "vreg"
168 // could not be initialized in its entirety (specifically, an instruction
169 // defining the "other part" of "vreg" would also count as a definition
170 // of "vreg", which would violate the SSA).
171 // If a value of a pair vreg:subreg needs to be obtained, the cell for
172 // "vreg" needs to be looked up, and then the value of subregister "subreg"
173 // needs to be evaluated.
174 class CellMap {
175 public:
176 CellMap() {
177 assert(Top.isTop());
178 Bottom.setBottom();
179 }
180 void clear() { Map.clear(); }
181 bool has(unsigned R) const {
182 // All non-virtual registers are considered "bottom".
183 if (!TargetRegisterInfo::isVirtualRegister(R))
184 return true;
185 MapType::const_iterator F = Map.find(R);
186 return F != Map.end();
187 }
188 const LatticeCell &get(unsigned R) const {
189 if (!TargetRegisterInfo::isVirtualRegister(R))
190 return Bottom;
191 MapType::const_iterator F = Map.find(R);
192 if (F != Map.end())
193 return F->second;
194 return Top;
195 }
196 // Invalidates any const references.
197 void update(unsigned R, const LatticeCell &L) {
198 Map[R] = L;
199 }
200 void print(raw_ostream &os, const TargetRegisterInfo &TRI) const;
201 private:
202 typedef std::map<unsigned,LatticeCell> MapType;
203 MapType Map;
204 // To avoid creating "top" entries, return a const reference to
205 // this cell in "get". Also, have a "Bottom" cell to return from
206 // get when a value of a physical register is requested.
207 LatticeCell Top, Bottom;
208 public:
209 typedef MapType::const_iterator const_iterator;
210 const_iterator begin() const { return Map.begin(); }
211 const_iterator end() const { return Map.end(); }
212 };
213
214 bool run(MachineFunction &MF);
215
216 private:
217 void visitPHI(const MachineInstr &PN);
218 void visitNonBranch(const MachineInstr &MI);
219 void visitBranchesFrom(const MachineInstr &BrI);
220 void visitUsesOf(unsigned R);
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +0000221 bool computeBlockSuccessors(const MachineBasicBlock *MB,
222 SetVector<const MachineBasicBlock*> &Targets);
223 void removeCFGEdge(MachineBasicBlock *From, MachineBasicBlock *To);
224
225 void propagate(MachineFunction &MF);
226 bool rewrite(MachineFunction &MF);
227
228 MachineRegisterInfo *MRI;
229 MachineConstEvaluator &MCE;
230
231 typedef std::pair<unsigned,unsigned> CFGEdge;
232 typedef std::set<CFGEdge> SetOfCFGEdge;
233 typedef std::set<const MachineInstr*> SetOfInstr;
234 typedef std::queue<CFGEdge> QueueOfCFGEdge;
235
236 LatticeCell Bottom;
237 CellMap Cells;
238 SetOfCFGEdge EdgeExec;
239 SetOfInstr InstrExec;
240 QueueOfCFGEdge FlowQ;
241 };
242
243
244 // The "evaluator/rewriter" of machine instructions. This is an abstract
245 // base class that provides the interface that the propagator will use,
246 // as well as some helper functions that are target-independent.
247 class MachineConstEvaluator {
248 public:
249 MachineConstEvaluator(MachineFunction &Fn)
250 : TRI(*Fn.getSubtarget().getRegisterInfo()),
251 MF(Fn), CX(Fn.getFunction()->getContext()) {}
252 virtual ~MachineConstEvaluator() {}
253
254 // The required interface:
255 // - A set of three "evaluate" functions. Each returns "true" if the
256 // computation succeeded, "false" otherwise.
257 // (1) Given an instruction MI, and the map with input values "Inputs",
258 // compute the set of output values "Outputs". An example of when
259 // the computation can "fail" is if MI is not an instruction that
260 // is recognized by the evaluator.
261 // (2) Given a register R (as reg:subreg), compute the cell that
262 // corresponds to the "subreg" part of the given register.
263 // (3) Given a branch instruction BrI, compute the set of target blocks.
264 // If the branch can fall-through, add null (0) to the list of
265 // possible targets.
266 // - A function "rewrite", that given the cell map after propagation,
267 // could rewrite instruction MI in a more beneficial form. Return
268 // "true" if a change has been made, "false" otherwise.
269 typedef MachineConstPropagator::CellMap CellMap;
270 virtual bool evaluate(const MachineInstr &MI, const CellMap &Inputs,
271 CellMap &Outputs) = 0;
272 virtual bool evaluate(const Register &R, const LatticeCell &SrcC,
273 LatticeCell &Result) = 0;
274 virtual bool evaluate(const MachineInstr &BrI, const CellMap &Inputs,
275 SetVector<const MachineBasicBlock*> &Targets,
276 bool &CanFallThru) = 0;
277 virtual bool rewrite(MachineInstr &MI, const CellMap &Inputs) = 0;
278
279 const TargetRegisterInfo &TRI;
280
281 protected:
282 MachineFunction &MF;
283 LLVMContext &CX;
284
285 struct Comparison {
286 enum {
287 Unk = 0x00,
288 EQ = 0x01,
289 NE = 0x02,
290 L = 0x04, // Less-than property.
291 G = 0x08, // Greater-than property.
292 U = 0x40, // Unsigned property.
293 LTs = L,
294 LEs = L | EQ,
295 GTs = G,
296 GEs = G | EQ,
297 LTu = L | U,
298 LEu = L | EQ | U,
299 GTu = G | U,
300 GEu = G | EQ | U
301 };
302 static uint32_t negate(uint32_t Cmp) {
303 if (Cmp == EQ)
304 return NE;
305 if (Cmp == NE)
306 return EQ;
307 assert((Cmp & (L|G)) != (L|G));
308 return Cmp ^ (L|G);
309 }
310 };
311
312 // Helper functions.
313
314 bool getCell(const Register &R, const CellMap &Inputs, LatticeCell &RC);
315 bool constToInt(const Constant *C, APInt &Val) const;
316 bool constToFloat(const Constant *C, APFloat &Val) const;
317 const ConstantInt *intToConst(const APInt &Val) const;
318
319 // Compares.
320 bool evaluateCMPrr(uint32_t Cmp, const Register &R1, const Register &R2,
321 const CellMap &Inputs, bool &Result);
322 bool evaluateCMPri(uint32_t Cmp, const Register &R1, const APInt &A2,
323 const CellMap &Inputs, bool &Result);
324 bool evaluateCMPrp(uint32_t Cmp, const Register &R1, uint64_t Props2,
325 const CellMap &Inputs, bool &Result);
326 bool evaluateCMPii(uint32_t Cmp, const APInt &A1, const APInt &A2,
327 bool &Result);
328 bool evaluateCMPpi(uint32_t Cmp, uint32_t Props, const APInt &A2,
329 bool &Result);
330 bool evaluateCMPpp(uint32_t Cmp, uint32_t Props1, uint32_t Props2,
331 bool &Result);
332
333 bool evaluateCOPY(const Register &R1, const CellMap &Inputs,
334 LatticeCell &Result);
335
336 // Logical operations.
337 bool evaluateANDrr(const Register &R1, const Register &R2,
338 const CellMap &Inputs, LatticeCell &Result);
339 bool evaluateANDri(const Register &R1, const APInt &A2,
340 const CellMap &Inputs, LatticeCell &Result);
341 bool evaluateANDii(const APInt &A1, const APInt &A2, APInt &Result);
342 bool evaluateORrr(const Register &R1, const Register &R2,
343 const CellMap &Inputs, LatticeCell &Result);
344 bool evaluateORri(const Register &R1, const APInt &A2,
345 const CellMap &Inputs, LatticeCell &Result);
346 bool evaluateORii(const APInt &A1, const APInt &A2, APInt &Result);
347 bool evaluateXORrr(const Register &R1, const Register &R2,
348 const CellMap &Inputs, LatticeCell &Result);
349 bool evaluateXORri(const Register &R1, const APInt &A2,
350 const CellMap &Inputs, LatticeCell &Result);
351 bool evaluateXORii(const APInt &A1, const APInt &A2, APInt &Result);
352
353 // Extensions.
354 bool evaluateZEXTr(const Register &R1, unsigned Width, unsigned Bits,
355 const CellMap &Inputs, LatticeCell &Result);
356 bool evaluateZEXTi(const APInt &A1, unsigned Width, unsigned Bits,
357 APInt &Result);
358 bool evaluateSEXTr(const Register &R1, unsigned Width, unsigned Bits,
359 const CellMap &Inputs, LatticeCell &Result);
360 bool evaluateSEXTi(const APInt &A1, unsigned Width, unsigned Bits,
361 APInt &Result);
362
363 // Leading/trailing bits.
364 bool evaluateCLBr(const Register &R1, bool Zeros, bool Ones,
365 const CellMap &Inputs, LatticeCell &Result);
366 bool evaluateCLBi(const APInt &A1, bool Zeros, bool Ones, APInt &Result);
367 bool evaluateCTBr(const Register &R1, bool Zeros, bool Ones,
368 const CellMap &Inputs, LatticeCell &Result);
369 bool evaluateCTBi(const APInt &A1, bool Zeros, bool Ones, APInt &Result);
370
371 // Bitfield extract.
372 bool evaluateEXTRACTr(const Register &R1, unsigned Width, unsigned Bits,
373 unsigned Offset, bool Signed, const CellMap &Inputs,
374 LatticeCell &Result);
375 bool evaluateEXTRACTi(const APInt &A1, unsigned Bits, unsigned Offset,
376 bool Signed, APInt &Result);
377 // Vector operations.
378 bool evaluateSplatr(const Register &R1, unsigned Bits, unsigned Count,
379 const CellMap &Inputs, LatticeCell &Result);
380 bool evaluateSplati(const APInt &A1, unsigned Bits, unsigned Count,
381 APInt &Result);
382 };
383
384}
385
386uint32_t ConstantProperties::deduce(const Constant *C) {
387 if (isa<ConstantInt>(C)) {
388 const ConstantInt *CI = cast<ConstantInt>(C);
389 if (CI->isZero())
390 return Zero | PosOrZero | NegOrZero | Finite;
391 uint32_t Props = (NonZero | Finite);
392 if (CI->isNegative())
393 return Props | NegOrZero;
394 return Props | PosOrZero;
395 }
396
397 if (isa<ConstantFP>(C)) {
398 const ConstantFP *CF = cast<ConstantFP>(C);
399 uint32_t Props = CF->isNegative() ? (NegOrZero|NonZero)
400 : PosOrZero;
401 if (CF->isZero())
402 return (Props & ~NumericProperties) | (Zero|Finite);
403 Props = (Props & ~NumericProperties) | NonZero;
404 if (CF->isNaN())
405 return (Props & ~NumericProperties) | NaN;
406 const APFloat &Val = CF->getValueAPF();
407 if (Val.isInfinity())
408 return (Props & ~NumericProperties) | Infinity;
409 Props |= Finite;
410 return Props;
411 }
412
413 return Unknown;
414}
415
416
417// Convert a cell from a set of specific values to a cell that tracks
418// properties.
419bool LatticeCell::convertToProperty() {
420 if (isProperty())
421 return false;
422 // Corner case: converting a fresh (top) cell to "special".
423 // This can happen, when adding a property to a top cell.
424 uint32_t Everything = ConstantProperties::Everything;
425 uint32_t Ps = !isTop() ? properties()
426 : Everything;
427 if (Ps != ConstantProperties::Unknown) {
428 Properties = Ps;
429 setProperty();
430 } else {
431 setBottom();
432 }
433 return true;
434}
435
436
437void LatticeCell::print(raw_ostream &os) const {
438 if (isProperty()) {
439 os << "{ ";
440 uint32_t Ps = properties();
441 if (Ps & ConstantProperties::Zero)
442 os << "zero ";
443 if (Ps & ConstantProperties::NonZero)
444 os << "nonzero ";
445 if (Ps & ConstantProperties::Finite)
446 os << "finite ";
447 if (Ps & ConstantProperties::Infinity)
448 os << "infinity ";
449 if (Ps & ConstantProperties::NaN)
450 os << "nan ";
451 if (Ps & ConstantProperties::PosOrZero)
452 os << "poz ";
453 if (Ps & ConstantProperties::NegOrZero)
454 os << "nez ";
455 os << '}';
456 return;
457 }
458
459 os << "{ ";
460 if (isBottom()) {
461 os << "bottom";
462 } else if (isTop()) {
463 os << "top";
464 } else {
465 for (unsigned i = 0; i < size(); ++i) {
466 const Constant *C = Values[i];
467 if (i != 0)
468 os << ", ";
469 C->print(os);
470 }
471 }
472 os << " }";
473}
474
475
476// "Meet" operation on two cells. This is the key of the propagation
477// algorithm.
478bool LatticeCell::meet(const LatticeCell &L) {
479 bool Changed = false;
480 if (L.isBottom())
481 Changed = setBottom();
482 if (isBottom() || L.isTop())
483 return Changed;
484 if (isTop()) {
485 *this = L;
486 // L can be neither Top nor Bottom, so *this must have changed.
487 return true;
488 }
489
490 // Top/bottom cases covered. Need to integrate L's set into ours.
491 if (L.isProperty())
492 return add(L.properties());
493 for (unsigned i = 0; i < L.size(); ++i) {
494 const Constant *LC = L.Values[i];
495 Changed |= add(LC);
496 }
497 return Changed;
498}
499
500
501// Add a new constant to the cell. This is actually where the cell update
502// happens. If a cell has room for more constants, the new constant is added.
503// Otherwise, the cell is converted to a "property" cell (i.e. a cell that
504// will track properties of the associated values, and not the values
505// themselves. Care is taken to handle special cases, like "bottom", etc.
506bool LatticeCell::add(const Constant *LC) {
507 assert(LC);
508 if (isBottom())
509 return false;
510
511 if (!isProperty()) {
512 // Cell is not special. Try to add the constant here first,
513 // if there is room.
514 unsigned Index = 0;
515 while (Index < Size) {
516 const Constant *C = Values[Index];
517 // If the constant is already here, no change is needed.
518 if (C == LC)
519 return false;
520 Index++;
521 }
522 if (Index < MaxCellSize) {
523 Values[Index] = LC;
524 Kind = Normal;
525 Size++;
526 return true;
527 }
528 }
529
530 bool Changed = false;
531
532 // This cell is special, or is not special, but is full. After this
533 // it will be special.
534 Changed = convertToProperty();
535 uint32_t Ps = properties();
536 uint32_t NewPs = Ps & ConstantProperties::deduce(LC);
537 if (NewPs == ConstantProperties::Unknown) {
538 setBottom();
539 return true;
540 }
541 if (Ps != NewPs) {
542 Properties = NewPs;
543 Changed = true;
544 }
545 return Changed;
546}
547
548
549// Add a property to the cell. This will force the cell to become a property-
550// tracking cell.
551bool LatticeCell::add(uint32_t Property) {
552 bool Changed = convertToProperty();
553 uint32_t Ps = properties();
554 if (Ps == (Ps & Property))
555 return Changed;
556 Properties = Property & Ps;
557 return true;
558}
559
560
561// Return the properties of the values in the cell. This is valid for any
562// cell, and does not alter the cell itself.
563uint32_t LatticeCell::properties() const {
564 if (isProperty())
565 return Properties;
566 assert(!isTop() && "Should not call this for a top cell");
567 if (isBottom())
568 return ConstantProperties::Unknown;
569
570 assert(size() > 0 && "Empty cell");
571 uint32_t Ps = ConstantProperties::deduce(Values[0]);
572 for (unsigned i = 1; i < size(); ++i) {
573 if (Ps == ConstantProperties::Unknown)
574 break;
575 Ps &= ConstantProperties::deduce(Values[i]);
576 }
577 return Ps;
578}
579
580
581void MachineConstPropagator::CellMap::print(raw_ostream &os,
582 const TargetRegisterInfo &TRI) const {
583 for (auto &I : Map)
584 dbgs() << " " << PrintReg(I.first, &TRI) << " -> " << I.second << '\n';
585}
586
587
588void MachineConstPropagator::visitPHI(const MachineInstr &PN) {
589 const MachineBasicBlock *MB = PN.getParent();
590 unsigned MBN = MB->getNumber();
591 DEBUG(dbgs() << "Visiting FI(BB#" << MBN << "): " << PN);
592
593 const MachineOperand &MD = PN.getOperand(0);
594 Register DefR(MD);
595 assert(TargetRegisterInfo::isVirtualRegister(DefR.Reg));
596
597 bool Changed = false;
598
599 // If the def has a sub-register, set the corresponding cell to "bottom".
600 if (DefR.SubReg) {
601Bottomize:
602 const LatticeCell &T = Cells.get(DefR.Reg);
603 Changed = !T.isBottom();
604 Cells.update(DefR.Reg, Bottom);
605 if (Changed)
606 visitUsesOf(DefR.Reg);
607 return;
608 }
609
610 LatticeCell DefC = Cells.get(DefR.Reg);
611
612 for (unsigned i = 1, n = PN.getNumOperands(); i < n; i += 2) {
613 const MachineBasicBlock *PB = PN.getOperand(i+1).getMBB();
614 unsigned PBN = PB->getNumber();
615 if (!EdgeExec.count(CFGEdge(PBN, MBN))) {
616 DEBUG(dbgs() << " edge BB#" << PBN << "->BB#" << MBN
617 << " not executable\n");
618 continue;
619 }
620 const MachineOperand &SO = PN.getOperand(i);
621 Register UseR(SO);
622 // If the input is not a virtual register, we don't really know what
623 // value it holds.
624 if (!TargetRegisterInfo::isVirtualRegister(UseR.Reg))
625 goto Bottomize;
626 // If there is no cell for an input register, it means top.
627 if (!Cells.has(UseR.Reg))
628 continue;
629
630 LatticeCell SrcC;
631 bool Eval = MCE.evaluate(UseR, Cells.get(UseR.Reg), SrcC);
632 DEBUG(dbgs() << " edge from BB#" << PBN << ": "
633 << PrintReg(UseR.Reg, &MCE.TRI, UseR.SubReg)
634 << SrcC << '\n');
635 Changed |= Eval ? DefC.meet(SrcC)
636 : DefC.setBottom();
637 Cells.update(DefR.Reg, DefC);
638 if (DefC.isBottom())
639 break;
640 }
641 if (Changed)
642 visitUsesOf(DefR.Reg);
643}
644
645
646void MachineConstPropagator::visitNonBranch(const MachineInstr &MI) {
647 DEBUG(dbgs() << "Visiting MI(BB#" << MI.getParent()->getNumber()
648 << "): " << MI);
649 CellMap Outputs;
650 bool Eval = MCE.evaluate(MI, Cells, Outputs);
651 DEBUG({
652 if (Eval) {
653 dbgs() << " outputs:";
654 for (auto &I : Outputs)
655 dbgs() << ' ' << I.second;
656 dbgs() << '\n';
657 }
658 });
659
660 // Update outputs. If the value was not computed, set all the
661 // def cells to bottom.
662 for (const MachineOperand &MO : MI.operands()) {
663 if (!MO.isReg() || !MO.isDef())
664 continue;
665 Register DefR(MO);
666 // Only track virtual registers.
667 if (!TargetRegisterInfo::isVirtualRegister(DefR.Reg))
668 continue;
669 bool Changed = false;
670 // If the evaluation failed, set cells for all output registers to bottom.
671 if (!Eval) {
672 const LatticeCell &T = Cells.get(DefR.Reg);
673 Changed = !T.isBottom();
674 Cells.update(DefR.Reg, Bottom);
675 } else {
676 // Find the corresponding cell in the computed outputs.
677 // If it's not there, go on to the next def.
678 if (!Outputs.has(DefR.Reg))
679 continue;
680 LatticeCell RC = Cells.get(DefR.Reg);
681 Changed = RC.meet(Outputs.get(DefR.Reg));
682 Cells.update(DefR.Reg, RC);
683 }
684 if (Changed)
685 visitUsesOf(DefR.Reg);
686 }
687}
688
689
690// \brief Starting at a given branch, visit remaining branches in the block.
691// Traverse over the subsequent branches for as long as the preceding one
692// can fall through. Add all the possible targets to the flow work queue,
693// including the potential fall-through to the layout-successor block.
694void MachineConstPropagator::visitBranchesFrom(const MachineInstr &BrI) {
695 const MachineBasicBlock &B = *BrI.getParent();
696 unsigned MBN = B.getNumber();
697 MachineBasicBlock::const_iterator It = BrI.getIterator();
698 MachineBasicBlock::const_iterator End = B.end();
699
700 SetVector<const MachineBasicBlock*> Targets;
701 bool EvalOk = true, FallsThru = true;
702 while (It != End) {
703 const MachineInstr &MI = *It;
704 InstrExec.insert(&MI);
705 DEBUG(dbgs() << "Visiting " << (EvalOk ? "BR" : "br") << "(BB#"
706 << MBN << "): " << MI);
707 // Do not evaluate subsequent branches if the evaluation of any of the
708 // previous branches failed. Keep iterating over the branches only
709 // to mark them as executable.
710 EvalOk = EvalOk && MCE.evaluate(MI, Cells, Targets, FallsThru);
711 if (!EvalOk)
712 FallsThru = true;
713 if (!FallsThru)
714 break;
715 ++It;
716 }
717
718 if (EvalOk) {
719 // Need to add all CFG successors that lead to EH landing pads.
720 // There won't be explicit branches to these blocks, but they must
721 // be processed.
722 for (const MachineBasicBlock *SB : B.successors()) {
723 if (SB->isEHPad())
724 Targets.insert(SB);
725 }
726 if (FallsThru) {
727 const MachineFunction &MF = *B.getParent();
728 MachineFunction::const_iterator BI = B.getIterator();
729 MachineFunction::const_iterator Next = std::next(BI);
730 if (Next != MF.end())
731 Targets.insert(&*Next);
732 }
733 } else {
734 // If the evaluation of the branches failed, make "Targets" to be the
735 // set of all successors of the block from the CFG.
736 // If the evaluation succeeded for all visited branches, then if the
737 // last one set "FallsThru", then add an edge to the layout successor
738 // to the targets.
739 Targets.clear();
740 DEBUG(dbgs() << " failed to evaluate a branch...adding all CFG "
741 "successors\n");
742 for (const MachineBasicBlock *SB : B.successors())
743 Targets.insert(SB);
744 }
745
746 for (const MachineBasicBlock *TB : Targets) {
747 unsigned TBN = TB->getNumber();
748 DEBUG(dbgs() << " pushing edge BB#" << MBN << " -> BB#" << TBN << "\n");
749 FlowQ.push(CFGEdge(MBN, TBN));
750 }
751}
752
753
754void MachineConstPropagator::visitUsesOf(unsigned Reg) {
755 DEBUG(dbgs() << "Visiting uses of " << PrintReg(Reg, &MCE.TRI)
756 << Cells.get(Reg) << '\n');
757 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
758 // Do not process non-executable instructions. They can become exceutable
759 // later (via a flow-edge in the work queue). In such case, the instruc-
760 // tion will be visited at that time.
761 if (!InstrExec.count(&MI))
762 continue;
763 if (MI.isPHI())
764 visitPHI(MI);
765 else if (!MI.isBranch())
766 visitNonBranch(MI);
767 else
768 visitBranchesFrom(MI);
769 }
770}
771
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +0000772bool MachineConstPropagator::computeBlockSuccessors(const MachineBasicBlock *MB,
773 SetVector<const MachineBasicBlock*> &Targets) {
774 MachineBasicBlock::const_iterator FirstBr = MB->end();
775 for (const MachineInstr &MI : *MB) {
776 if (MI.isDebugValue())
777 continue;
778 if (MI.isBranch()) {
779 FirstBr = MI.getIterator();
780 break;
781 }
782 }
783
784 Targets.clear();
785 MachineBasicBlock::const_iterator End = MB->end();
786
787 bool DoNext = true;
788 for (MachineBasicBlock::const_iterator I = FirstBr; I != End; ++I) {
789 const MachineInstr &MI = *I;
790 // Can there be debug instructions between branches?
791 if (MI.isDebugValue())
792 continue;
793 if (!InstrExec.count(&MI))
794 continue;
795 bool Eval = MCE.evaluate(MI, Cells, Targets, DoNext);
796 if (!Eval)
797 return false;
798 if (!DoNext)
799 break;
800 }
801 // If the last branch could fall-through, add block's layout successor.
802 if (DoNext) {
803 MachineFunction::const_iterator BI = MB->getIterator();
804 MachineFunction::const_iterator NextI = std::next(BI);
805 if (NextI != MB->getParent()->end())
806 Targets.insert(&*NextI);
807 }
808
809 // Add all the EH landing pads.
810 for (const MachineBasicBlock *SB : MB->successors())
811 if (SB->isEHPad())
812 Targets.insert(SB);
813
814 return true;
815}
816
817
818void MachineConstPropagator::removeCFGEdge(MachineBasicBlock *From,
819 MachineBasicBlock *To) {
820 // First, remove the CFG successor/predecessor information.
821 From->removeSuccessor(To);
822 // Remove all corresponding PHI operands in the To block.
823 for (auto I = To->begin(), E = To->getFirstNonPHI(); I != E; ++I) {
824 MachineInstr *PN = &*I;
825 // reg0 = PHI reg1, bb2, reg3, bb4, ...
826 int N = PN->getNumOperands()-2;
827 while (N > 0) {
828 if (PN->getOperand(N+1).getMBB() == From) {
829 PN->RemoveOperand(N+1);
830 PN->RemoveOperand(N);
831 }
832 N -= 2;
833 }
834 }
835}
836
837
838void MachineConstPropagator::propagate(MachineFunction &MF) {
839 MachineBasicBlock *Entry = GraphTraits<MachineFunction*>::getEntryNode(&MF);
840 unsigned EntryNum = Entry->getNumber();
841
842 // Start with a fake edge, just to process the entry node.
843 FlowQ.push(CFGEdge(EntryNum, EntryNum));
844
845 while (!FlowQ.empty()) {
846 CFGEdge Edge = FlowQ.front();
847 FlowQ.pop();
848
849 DEBUG(dbgs() << "Picked edge BB#" << Edge.first << "->BB#"
850 << Edge.second << '\n');
851 if (Edge.first != EntryNum)
852 if (EdgeExec.count(Edge))
853 continue;
854 EdgeExec.insert(Edge);
855 MachineBasicBlock *SB = MF.getBlockNumbered(Edge.second);
856
857 // Process the block in three stages:
858 // - visit all PHI nodes,
859 // - visit all non-branch instructions,
860 // - visit block branches.
861 MachineBasicBlock::const_iterator It = SB->begin(), End = SB->end();
862
863 // Visit PHI nodes in the successor block.
864 while (It != End && It->isPHI()) {
865 InstrExec.insert(&*It);
866 visitPHI(*It);
867 ++It;
868 }
869
870 // If the successor block just became executable, visit all instructions.
871 // To see if this is the first time we're visiting it, check the first
872 // non-debug instruction to see if it is executable.
873 while (It != End && It->isDebugValue())
874 ++It;
875 assert(It == End || !It->isPHI());
876 // If this block has been visited, go on to the next one.
877 if (It != End && InstrExec.count(&*It))
878 continue;
879 // For now, scan all non-branch instructions. Branches require different
880 // processing.
881 while (It != End && !It->isBranch()) {
882 if (!It->isDebugValue()) {
883 InstrExec.insert(&*It);
884 visitNonBranch(*It);
885 }
886 ++It;
887 }
888
889 // Time to process the end of the block. This is different from
890 // processing regular (non-branch) instructions, because there can
891 // be multiple branches in a block, and they can cause the block to
892 // terminate early.
893 if (It != End) {
894 visitBranchesFrom(*It);
895 } else {
896 // If the block didn't have a branch, add all successor edges to the
897 // work queue. (There should really be only one successor in such case.)
898 unsigned SBN = SB->getNumber();
899 for (const MachineBasicBlock *SSB : SB->successors())
900 FlowQ.push(CFGEdge(SBN, SSB->getNumber()));
901 }
902 } // while (FlowQ)
903
904 DEBUG({
905 dbgs() << "Cells after propagation:\n";
906 Cells.print(dbgs(), MCE.TRI);
907 dbgs() << "Dead CFG edges:\n";
908 for (const MachineBasicBlock &B : MF) {
909 unsigned BN = B.getNumber();
910 for (const MachineBasicBlock *SB : B.successors()) {
911 unsigned SN = SB->getNumber();
912 if (!EdgeExec.count(CFGEdge(BN, SN)))
913 dbgs() << " BB#" << BN << " -> BB#" << SN << '\n';
914 }
915 }
916 });
917}
918
919
920bool MachineConstPropagator::rewrite(MachineFunction &MF) {
921 bool Changed = false;
922 // Rewrite all instructions based on the collected cell information.
923 //
924 // Traverse the instructions in a post-order, so that rewriting an
925 // instruction can make changes "downstream" in terms of control-flow
926 // without affecting the rewriting process. (We should not change
927 // instructions that have not yet been visited by the rewriter.)
928 // The reason for this is that the rewriter can introduce new vregs,
929 // and replace uses of old vregs (which had corresponding cells
930 // computed during propagation) with these new vregs (which at this
931 // point would not have any cells, and would appear to be "top").
932 // If an attempt was made to evaluate an instruction with a fresh
933 // "top" vreg, it would cause an error (abend) in the evaluator.
934
935 // Collect the post-order-traversal block ordering. The subsequent
936 // traversal/rewrite will update block successors, so it's safer
937 // if the visiting order it computed ahead of time.
938 std::vector<MachineBasicBlock*> POT;
939 for (MachineBasicBlock *B : post_order(&MF))
940 if (!B->empty())
941 POT.push_back(B);
942
943 for (MachineBasicBlock *B : POT) {
944 // Walk the block backwards (which usually begin with the branches).
945 // If any branch is rewritten, we may need to update the successor
946 // information for this block. Unless the block's successors can be
947 // precisely determined (which may not be the case for indirect
948 // branches), we cannot modify any branch.
949
950 // Compute the successor information.
951 SetVector<const MachineBasicBlock*> Targets;
952 bool HaveTargets = computeBlockSuccessors(B, Targets);
953 // Rewrite the executable instructions. Skip branches if we don't
954 // have block successor information.
955 for (auto I = B->rbegin(), E = B->rend(); I != E; ++I) {
956 MachineInstr &MI = *I;
957 if (InstrExec.count(&MI)) {
958 if (MI.isBranch() && !HaveTargets)
959 continue;
960 Changed |= MCE.rewrite(MI, Cells);
961 }
962 }
963 // The rewriting could rewrite PHI nodes to non-PHI nodes, causing
964 // regular instructions to appear in between PHI nodes. Bring all
965 // the PHI nodes to the beginning of the block.
966 for (auto I = B->begin(), E = B->end(); I != E; ++I) {
967 if (I->isPHI())
968 continue;
969 // I is not PHI. Find the next PHI node P.
970 auto P = I;
971 while (++P != E)
972 if (P->isPHI())
973 break;
974 // Not found.
975 if (P == E)
976 break;
977 // Splice P right before I.
978 B->splice(I, B, P);
979 // Reset I to point at the just spliced PHI node.
980 --I;
981 }
982 // Update the block successor information: remove unnecessary successors.
983 if (HaveTargets) {
984 SmallVector<MachineBasicBlock*,2> ToRemove;
985 for (MachineBasicBlock *SB : B->successors()) {
986 if (!Targets.count(SB))
987 ToRemove.push_back(const_cast<MachineBasicBlock*>(SB));
988 Targets.remove(SB);
989 }
990 for (unsigned i = 0, n = ToRemove.size(); i < n; ++i)
991 removeCFGEdge(B, ToRemove[i]);
992 // If there are any blocks left in the computed targets, it means that
993 // we think that the block could go somewhere, but the CFG does not.
994 // This could legitimately happen in blocks that have non-returning
995 // calls---we would think that the execution can continue, but the
996 // CFG will not have a successor edge.
997 }
998 }
999 // Need to do some final post-processing.
1000 // If a branch was not executable, it will not get rewritten, but should
1001 // be removed (or replaced with something equivalent to a A2_nop). We can't
1002 // erase instructions during rewriting, so this needs to be delayed until
1003 // now.
1004 for (MachineBasicBlock &B : MF) {
1005 MachineBasicBlock::iterator I = B.begin(), E = B.end();
1006 while (I != E) {
1007 auto Next = std::next(I);
1008 if (I->isBranch() && !InstrExec.count(&*I))
1009 B.erase(I);
1010 I = Next;
1011 }
1012 }
1013 return Changed;
1014}
1015
1016
1017// This is the constant propagation algorithm as described by Wegman-Zadeck.
1018// Most of the terminology comes from there.
1019bool MachineConstPropagator::run(MachineFunction &MF) {
1020 DEBUG(MF.print(dbgs() << "Starting MachineConstPropagator\n", 0));
1021
1022 MRI = &MF.getRegInfo();
1023
1024 Cells.clear();
1025 EdgeExec.clear();
1026 InstrExec.clear();
1027 assert(FlowQ.empty());
1028
1029 propagate(MF);
1030 bool Changed = rewrite(MF);
1031
1032 DEBUG({
1033 dbgs() << "End of MachineConstPropagator (Changed=" << Changed << ")\n";
1034 if (Changed)
1035 MF.print(dbgs(), 0);
1036 });
1037 return Changed;
1038}
1039
1040
1041// --------------------------------------------------------------------
1042// Machine const evaluator.
1043
1044bool MachineConstEvaluator::getCell(const Register &R, const CellMap &Inputs,
1045 LatticeCell &RC) {
1046 if (!TargetRegisterInfo::isVirtualRegister(R.Reg))
1047 return false;
1048 const LatticeCell &L = Inputs.get(R.Reg);
1049 if (!R.SubReg) {
1050 RC = L;
1051 return !RC.isBottom();
1052 }
1053 bool Eval = evaluate(R, L, RC);
1054 return Eval && !RC.isBottom();
1055}
1056
1057
1058bool MachineConstEvaluator::constToInt(const Constant *C,
1059 APInt &Val) const {
1060 const ConstantInt *CI = dyn_cast<ConstantInt>(C);
1061 if (!CI)
1062 return false;
1063 Val = CI->getValue();
1064 return true;
1065}
1066
1067
1068const ConstantInt *MachineConstEvaluator::intToConst(const APInt &Val) const {
1069 return ConstantInt::get(CX, Val);
1070}
1071
1072
1073bool MachineConstEvaluator::evaluateCMPrr(uint32_t Cmp, const Register &R1,
1074 const Register &R2, const CellMap &Inputs, bool &Result) {
1075 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
1076 LatticeCell LS1, LS2;
1077 if (!getCell(R1, Inputs, LS1) || !getCell(R2, Inputs, LS2))
1078 return false;
1079
1080 bool IsProp1 = LS1.isProperty();
1081 bool IsProp2 = LS2.isProperty();
1082 if (IsProp1) {
1083 uint32_t Prop1 = LS1.properties();
1084 if (IsProp2)
1085 return evaluateCMPpp(Cmp, Prop1, LS2.properties(), Result);
1086 uint32_t NegCmp = Comparison::negate(Cmp);
1087 return evaluateCMPrp(NegCmp, R2, Prop1, Inputs, Result);
1088 }
1089 if (IsProp2) {
1090 uint32_t Prop2 = LS2.properties();
1091 return evaluateCMPrp(Cmp, R1, Prop2, Inputs, Result);
1092 }
1093
1094 APInt A;
1095 bool IsTrue = true, IsFalse = true;
1096 for (unsigned i = 0; i < LS2.size(); ++i) {
1097 bool Res;
1098 bool Computed = constToInt(LS2.Values[i], A) &&
1099 evaluateCMPri(Cmp, R1, A, Inputs, Res);
1100 if (!Computed)
1101 return false;
1102 IsTrue &= Res;
1103 IsFalse &= !Res;
1104 }
1105 assert(!IsTrue || !IsFalse);
1106 // The actual logical value of the comparison is same as IsTrue.
1107 Result = IsTrue;
1108 // Return true if the result was proven to be true or proven to be false.
1109 return IsTrue || IsFalse;
1110}
1111
1112
1113bool MachineConstEvaluator::evaluateCMPri(uint32_t Cmp, const Register &R1,
1114 const APInt &A2, const CellMap &Inputs, bool &Result) {
1115 assert(Inputs.has(R1.Reg));
1116 LatticeCell LS;
1117 if (!getCell(R1, Inputs, LS))
1118 return false;
1119 if (LS.isProperty())
1120 return evaluateCMPpi(Cmp, LS.properties(), A2, Result);
1121
1122 APInt A;
1123 bool IsTrue = true, IsFalse = true;
1124 for (unsigned i = 0; i < LS.size(); ++i) {
1125 bool Res;
1126 bool Computed = constToInt(LS.Values[i], A) &&
1127 evaluateCMPii(Cmp, A, A2, Res);
1128 if (!Computed)
1129 return false;
1130 IsTrue &= Res;
1131 IsFalse &= !Res;
1132 }
1133 assert(!IsTrue || !IsFalse);
1134 // The actual logical value of the comparison is same as IsTrue.
1135 Result = IsTrue;
1136 // Return true if the result was proven to be true or proven to be false.
1137 return IsTrue || IsFalse;
1138}
1139
1140
1141bool MachineConstEvaluator::evaluateCMPrp(uint32_t Cmp, const Register &R1,
1142 uint64_t Props2, const CellMap &Inputs, bool &Result) {
1143 assert(Inputs.has(R1.Reg));
1144 LatticeCell LS;
1145 if (!getCell(R1, Inputs, LS))
1146 return false;
1147 if (LS.isProperty())
1148 return evaluateCMPpp(Cmp, LS.properties(), Props2, Result);
1149
1150 APInt A;
1151 uint32_t NegCmp = Comparison::negate(Cmp);
1152 bool IsTrue = true, IsFalse = true;
1153 for (unsigned i = 0; i < LS.size(); ++i) {
1154 bool Res;
1155 bool Computed = constToInt(LS.Values[i], A) &&
1156 evaluateCMPpi(NegCmp, Props2, A, Res);
1157 if (!Computed)
1158 return false;
1159 IsTrue &= Res;
1160 IsFalse &= !Res;
1161 }
1162 assert(!IsTrue || !IsFalse);
1163 Result = IsTrue;
1164 return IsTrue || IsFalse;
1165}
1166
1167
1168bool MachineConstEvaluator::evaluateCMPii(uint32_t Cmp, const APInt &A1,
1169 const APInt &A2, bool &Result) {
1170 // NE is a special kind of comparison (not composed of smaller properties).
1171 if (Cmp == Comparison::NE) {
1172 Result = !APInt::isSameValue(A1, A2);
1173 return true;
1174 }
1175 if (Cmp == Comparison::EQ) {
1176 Result = APInt::isSameValue(A1, A2);
1177 return true;
1178 }
1179 if (Cmp & Comparison::EQ) {
1180 if (APInt::isSameValue(A1, A2))
1181 return (Result = true);
1182 }
1183 assert((Cmp & (Comparison::L | Comparison::G)) && "Malformed comparison");
1184 Result = false;
1185
1186 unsigned W1 = A1.getBitWidth();
1187 unsigned W2 = A2.getBitWidth();
1188 unsigned MaxW = (W1 >= W2) ? W1 : W2;
1189 if (Cmp & Comparison::U) {
1190 const APInt Zx1 = A1.zextOrSelf(MaxW);
1191 const APInt Zx2 = A2.zextOrSelf(MaxW);
1192 if (Cmp & Comparison::L)
1193 Result = Zx1.ult(Zx2);
1194 else if (Cmp & Comparison::G)
1195 Result = Zx2.ult(Zx1);
1196 return true;
1197 }
1198
1199 // Signed comparison.
1200 const APInt Sx1 = A1.sextOrSelf(MaxW);
1201 const APInt Sx2 = A2.sextOrSelf(MaxW);
1202 if (Cmp & Comparison::L)
1203 Result = Sx1.slt(Sx2);
1204 else if (Cmp & Comparison::G)
1205 Result = Sx2.slt(Sx1);
1206 return true;
1207}
1208
1209
1210bool MachineConstEvaluator::evaluateCMPpi(uint32_t Cmp, uint32_t Props,
1211 const APInt &A2, bool &Result) {
1212 if (Props == ConstantProperties::Unknown)
1213 return false;
1214
1215 // Should never see NaN here, but check for it for completeness.
1216 if (Props & ConstantProperties::NaN)
1217 return false;
1218 // Infinity could theoretically be compared to a number, but the
1219 // presence of infinity here would be very suspicious. If we don't
1220 // know for sure that the number is finite, bail out.
1221 if (!(Props & ConstantProperties::Finite))
1222 return false;
1223
1224 // Let X be a number that has properties Props.
1225
1226 if (Cmp & Comparison::U) {
1227 // In case of unsigned comparisons, we can only compare against 0.
1228 if (A2 == 0) {
1229 // Any x!=0 will be considered >0 in an unsigned comparison.
1230 if (Props & ConstantProperties::Zero)
1231 Result = (Cmp & Comparison::EQ);
1232 else if (Props & ConstantProperties::NonZero)
1233 Result = (Cmp & Comparison::G) || (Cmp == Comparison::NE);
1234 else
1235 return false;
1236 return true;
1237 }
1238 // A2 is not zero. The only handled case is if X = 0.
1239 if (Props & ConstantProperties::Zero) {
1240 Result = (Cmp & Comparison::L) || (Cmp == Comparison::NE);
1241 return true;
1242 }
1243 return false;
1244 }
1245
1246 // Signed comparisons are different.
1247 if (Props & ConstantProperties::Zero) {
1248 if (A2 == 0)
1249 Result = (Cmp & Comparison::EQ);
1250 else
1251 Result = (Cmp == Comparison::NE) ||
1252 ((Cmp & Comparison::L) && !A2.isNegative()) ||
1253 ((Cmp & Comparison::G) && A2.isNegative());
1254 return true;
1255 }
1256 if (Props & ConstantProperties::PosOrZero) {
1257 // X >= 0 and !(A2 < 0) => cannot compare
1258 if (!A2.isNegative())
1259 return false;
1260 // X >= 0 and A2 < 0
1261 Result = (Cmp & Comparison::G) || (Cmp == Comparison::NE);
1262 return true;
1263 }
1264 if (Props & ConstantProperties::NegOrZero) {
1265 // X <= 0 and Src1 < 0 => cannot compare
1266 if (A2 == 0 || A2.isNegative())
1267 return false;
1268 // X <= 0 and A2 > 0
1269 Result = (Cmp & Comparison::L) || (Cmp == Comparison::NE);
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
1276
1277bool MachineConstEvaluator::evaluateCMPpp(uint32_t Cmp, uint32_t Props1,
1278 uint32_t Props2, bool &Result) {
1279 typedef ConstantProperties P;
1280 if ((Props1 & P::NaN) && (Props2 & P::NaN))
1281 return false;
1282 if (!(Props1 & P::Finite) || !(Props2 & P::Finite))
1283 return false;
1284
1285 bool Zero1 = (Props1 & P::Zero), Zero2 = (Props2 & P::Zero);
1286 bool NonZero1 = (Props1 & P::NonZero), NonZero2 = (Props2 & P::NonZero);
1287 if (Zero1 && Zero2) {
1288 Result = (Cmp & Comparison::EQ);
1289 return true;
1290 }
1291 if (Cmp == Comparison::NE) {
1292 if ((Zero1 && NonZero2) || (NonZero1 && Zero2))
1293 return (Result = true);
1294 return false;
1295 }
1296
1297 if (Cmp & Comparison::U) {
1298 // In unsigned comparisons, we can only compare against a known zero,
1299 // or a known non-zero.
1300 if (Zero1 && NonZero2) {
1301 Result = (Cmp & Comparison::L);
1302 return true;
1303 }
1304 if (NonZero1 && Zero2) {
1305 Result = (Cmp & Comparison::G);
1306 return true;
1307 }
1308 return false;
1309 }
1310
1311 // Signed comparison. The comparison is not NE.
1312 bool Poz1 = (Props1 & P::PosOrZero), Poz2 = (Props2 & P::PosOrZero);
1313 bool Nez1 = (Props1 & P::NegOrZero), Nez2 = (Props2 & P::NegOrZero);
1314 if (Nez1 && Poz2) {
1315 if (NonZero1 || NonZero2) {
1316 Result = (Cmp & Comparison::L);
1317 return true;
1318 }
1319 // Either (or both) could be zero. Can only say that X <= Y.
1320 if ((Cmp & Comparison::EQ) && (Cmp & Comparison::L))
1321 return (Result = true);
1322 }
1323 if (Poz1 && Nez2) {
1324 if (NonZero1 || NonZero2) {
1325 Result = (Cmp & Comparison::G);
1326 return true;
1327 }
1328 // Either (or both) could be zero. Can only say that X >= Y.
1329 if ((Cmp & Comparison::EQ) && (Cmp & Comparison::G))
1330 return (Result = true);
1331 }
1332
1333 return false;
1334}
1335
1336
1337bool MachineConstEvaluator::evaluateCOPY(const Register &R1,
1338 const CellMap &Inputs, LatticeCell &Result) {
1339 return getCell(R1, Inputs, Result);
1340}
1341
1342
1343bool MachineConstEvaluator::evaluateANDrr(const Register &R1,
1344 const Register &R2, const CellMap &Inputs, LatticeCell &Result) {
1345 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
1346 const LatticeCell &L1 = Inputs.get(R2.Reg);
1347 const LatticeCell &L2 = Inputs.get(R2.Reg);
1348 // If both sources are bottom, exit. Otherwise try to evaluate ANDri
1349 // with the non-bottom argument passed as the immediate. This is to
1350 // catch cases of ANDing with 0.
1351 if (L2.isBottom()) {
1352 if (L1.isBottom())
1353 return false;
1354 return evaluateANDrr(R2, R1, Inputs, Result);
1355 }
1356 LatticeCell LS2;
1357 if (!evaluate(R2, L2, LS2))
1358 return false;
1359 if (LS2.isBottom() || LS2.isProperty())
1360 return false;
1361
1362 APInt A;
1363 for (unsigned i = 0; i < LS2.size(); ++i) {
1364 LatticeCell RC;
1365 bool Eval = constToInt(LS2.Values[i], A) &&
1366 evaluateANDri(R1, A, Inputs, RC);
1367 if (!Eval)
1368 return false;
1369 Result.meet(RC);
1370 }
1371 return !Result.isBottom();
1372}
1373
1374
1375bool MachineConstEvaluator::evaluateANDri(const Register &R1,
1376 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) {
1377 assert(Inputs.has(R1.Reg));
1378 if (A2 == -1)
1379 return getCell(R1, Inputs, Result);
1380 if (A2 == 0) {
1381 LatticeCell RC;
1382 RC.add(intToConst(A2));
1383 // Overwrite Result.
1384 Result = RC;
1385 return true;
1386 }
1387 LatticeCell LS1;
1388 if (!getCell(R1, Inputs, LS1))
1389 return false;
1390 if (LS1.isBottom() || LS1.isProperty())
1391 return false;
1392
1393 APInt A, ResA;
1394 for (unsigned i = 0; i < LS1.size(); ++i) {
1395 bool Eval = constToInt(LS1.Values[i], A) &&
1396 evaluateANDii(A, A2, ResA);
1397 if (!Eval)
1398 return false;
1399 const Constant *C = intToConst(ResA);
1400 Result.add(C);
1401 }
1402 return !Result.isBottom();
1403}
1404
1405
1406bool MachineConstEvaluator::evaluateANDii(const APInt &A1,
1407 const APInt &A2, APInt &Result) {
1408 Result = A1 & A2;
1409 return true;
1410}
1411
1412
1413bool MachineConstEvaluator::evaluateORrr(const Register &R1,
1414 const Register &R2, const CellMap &Inputs, LatticeCell &Result) {
1415 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
1416 const LatticeCell &L1 = Inputs.get(R2.Reg);
1417 const LatticeCell &L2 = Inputs.get(R2.Reg);
1418 // If both sources are bottom, exit. Otherwise try to evaluate ORri
1419 // with the non-bottom argument passed as the immediate. This is to
1420 // catch cases of ORing with -1.
1421 if (L2.isBottom()) {
1422 if (L1.isBottom())
1423 return false;
1424 return evaluateORrr(R2, R1, Inputs, Result);
1425 }
1426 LatticeCell LS2;
1427 if (!evaluate(R2, L2, LS2))
1428 return false;
1429 if (LS2.isBottom() || LS2.isProperty())
1430 return false;
1431
1432 APInt A;
1433 for (unsigned i = 0; i < LS2.size(); ++i) {
1434 LatticeCell RC;
1435 bool Eval = constToInt(LS2.Values[i], A) &&
1436 evaluateORri(R1, A, Inputs, RC);
1437 if (!Eval)
1438 return false;
1439 Result.meet(RC);
1440 }
1441 return !Result.isBottom();
1442}
1443
1444
1445bool MachineConstEvaluator::evaluateORri(const Register &R1,
1446 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) {
1447 assert(Inputs.has(R1.Reg));
1448 if (A2 == 0)
1449 return getCell(R1, Inputs, Result);
1450 if (A2 == -1) {
1451 LatticeCell RC;
1452 RC.add(intToConst(A2));
1453 // Overwrite Result.
1454 Result = RC;
1455 return true;
1456 }
1457 LatticeCell LS1;
1458 if (!getCell(R1, Inputs, LS1))
1459 return false;
1460 if (LS1.isBottom() || LS1.isProperty())
1461 return false;
1462
1463 APInt A, ResA;
1464 for (unsigned i = 0; i < LS1.size(); ++i) {
1465 bool Eval = constToInt(LS1.Values[i], A) &&
1466 evaluateORii(A, A2, ResA);
1467 if (!Eval)
1468 return false;
1469 const Constant *C = intToConst(ResA);
1470 Result.add(C);
1471 }
1472 return !Result.isBottom();
1473}
1474
1475
1476bool MachineConstEvaluator::evaluateORii(const APInt &A1,
1477 const APInt &A2, APInt &Result) {
1478 Result = A1 | A2;
1479 return true;
1480}
1481
1482
1483bool MachineConstEvaluator::evaluateXORrr(const Register &R1,
1484 const Register &R2, const CellMap &Inputs, LatticeCell &Result) {
1485 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
1486 LatticeCell LS1, LS2;
1487 if (!getCell(R1, Inputs, LS1) || !getCell(R2, Inputs, LS2))
1488 return false;
1489 if (LS1.isProperty()) {
1490 if (LS1.properties() & ConstantProperties::Zero)
1491 return !(Result = LS2).isBottom();
1492 return false;
1493 }
1494 if (LS2.isProperty()) {
1495 if (LS2.properties() & ConstantProperties::Zero)
1496 return !(Result = LS1).isBottom();
1497 return false;
1498 }
1499
1500 APInt A;
1501 for (unsigned i = 0; i < LS2.size(); ++i) {
1502 LatticeCell RC;
1503 bool Eval = constToInt(LS2.Values[i], A) &&
1504 evaluateXORri(R1, A, Inputs, RC);
1505 if (!Eval)
1506 return false;
1507 Result.meet(RC);
1508 }
1509 return !Result.isBottom();
1510}
1511
1512
1513bool MachineConstEvaluator::evaluateXORri(const Register &R1,
1514 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) {
1515 assert(Inputs.has(R1.Reg));
1516 LatticeCell LS1;
1517 if (!getCell(R1, Inputs, LS1))
1518 return false;
1519 if (LS1.isProperty()) {
1520 if (LS1.properties() & ConstantProperties::Zero) {
1521 const Constant *C = intToConst(A2);
1522 Result.add(C);
1523 return !Result.isBottom();
1524 }
1525 return false;
1526 }
1527
1528 APInt A, XA;
1529 for (unsigned i = 0; i < LS1.size(); ++i) {
1530 bool Eval = constToInt(LS1.Values[i], A) &&
1531 evaluateXORii(A, A2, XA);
1532 if (!Eval)
1533 return false;
1534 const Constant *C = intToConst(XA);
1535 Result.add(C);
1536 }
1537 return !Result.isBottom();
1538}
1539
1540
1541bool MachineConstEvaluator::evaluateXORii(const APInt &A1,
1542 const APInt &A2, APInt &Result) {
1543 Result = A1 ^ A2;
1544 return true;
1545}
1546
1547
1548bool MachineConstEvaluator::evaluateZEXTr(const Register &R1, unsigned Width,
1549 unsigned Bits, const CellMap &Inputs, LatticeCell &Result) {
1550 assert(Inputs.has(R1.Reg));
1551 LatticeCell LS1;
1552 if (!getCell(R1, Inputs, LS1))
1553 return false;
1554 if (LS1.isProperty())
1555 return false;
1556
1557 APInt A, XA;
1558 for (unsigned i = 0; i < LS1.size(); ++i) {
1559 bool Eval = constToInt(LS1.Values[i], A) &&
1560 evaluateZEXTi(A, Width, Bits, XA);
1561 if (!Eval)
1562 return false;
1563 const Constant *C = intToConst(XA);
1564 Result.add(C);
1565 }
1566 return true;
1567}
1568
1569
1570bool MachineConstEvaluator::evaluateZEXTi(const APInt &A1, unsigned Width,
1571 unsigned Bits, APInt &Result) {
1572 unsigned BW = A1.getBitWidth();
Krzysztof Parzyszek6400dec2016-07-28 20:25:21 +00001573 (void)BW;
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00001574 assert(Width >= Bits && BW >= Bits);
1575 APInt Mask = APInt::getLowBitsSet(Width, Bits);
1576 Result = A1.zextOrTrunc(Width) & Mask;
1577 return true;
1578}
1579
1580
1581bool MachineConstEvaluator::evaluateSEXTr(const Register &R1, unsigned Width,
1582 unsigned Bits, const CellMap &Inputs, LatticeCell &Result) {
1583 assert(Inputs.has(R1.Reg));
1584 LatticeCell LS1;
1585 if (!getCell(R1, Inputs, LS1))
1586 return false;
1587 if (LS1.isBottom() || LS1.isProperty())
1588 return false;
1589
1590 APInt A, XA;
1591 for (unsigned i = 0; i < LS1.size(); ++i) {
1592 bool Eval = constToInt(LS1.Values[i], A) &&
1593 evaluateSEXTi(A, Width, Bits, XA);
1594 if (!Eval)
1595 return false;
1596 const Constant *C = intToConst(XA);
1597 Result.add(C);
1598 }
1599 return true;
1600}
1601
1602
1603bool MachineConstEvaluator::evaluateSEXTi(const APInt &A1, unsigned Width,
1604 unsigned Bits, APInt &Result) {
1605 unsigned BW = A1.getBitWidth();
1606 assert(Width >= Bits && BW >= Bits);
1607 // Special case to make things faster for smaller source widths.
1608 // Sign extension of 0 bits generates 0 as a result. This is consistent
1609 // with what the HW does.
1610 if (Bits == 0) {
1611 Result = APInt(Width, 0);
1612 return true;
1613 }
1614 // In C, shifts by 64 invoke undefined behavior: handle that case in APInt.
1615 if (BW <= 64 && Bits != 0) {
1616 int64_t V = A1.getSExtValue();
1617 switch (Bits) {
1618 case 8:
1619 V = static_cast<int8_t>(V);
1620 break;
1621 case 16:
1622 V = static_cast<int16_t>(V);
1623 break;
1624 case 32:
1625 V = static_cast<int32_t>(V);
1626 break;
1627 default:
1628 // Shift left to lose all bits except lower "Bits" bits, then shift
1629 // the value back, replicating what was a sign bit after the first
1630 // shift.
1631 V = (V << (64-Bits)) >> (64-Bits);
1632 break;
1633 }
1634 // V is a 64-bit sign-extended value. Convert it to APInt of desired
1635 // width.
1636 Result = APInt(Width, V, true);
1637 return true;
1638 }
1639 // Slow case: the value doesn't fit in int64_t.
1640 if (Bits < BW)
1641 Result = A1.trunc(Bits).sext(Width);
1642 else // Bits == BW
1643 Result = A1.sext(Width);
1644 return true;
1645}
1646
1647
1648bool MachineConstEvaluator::evaluateCLBr(const Register &R1, bool Zeros,
1649 bool Ones, const CellMap &Inputs, LatticeCell &Result) {
1650 assert(Inputs.has(R1.Reg));
1651 LatticeCell LS1;
1652 if (!getCell(R1, Inputs, LS1))
1653 return false;
1654 if (LS1.isBottom() || LS1.isProperty())
1655 return false;
1656
1657 APInt A, CA;
1658 for (unsigned i = 0; i < LS1.size(); ++i) {
1659 bool Eval = constToInt(LS1.Values[i], A) &&
1660 evaluateCLBi(A, Zeros, Ones, CA);
1661 if (!Eval)
1662 return false;
1663 const Constant *C = intToConst(CA);
1664 Result.add(C);
1665 }
1666 return true;
1667}
1668
1669
1670bool MachineConstEvaluator::evaluateCLBi(const APInt &A1, bool Zeros,
1671 bool Ones, APInt &Result) {
1672 unsigned BW = A1.getBitWidth();
1673 if (!Zeros && !Ones)
1674 return false;
1675 unsigned Count = 0;
1676 if (Zeros && (Count == 0))
1677 Count = A1.countLeadingZeros();
1678 if (Ones && (Count == 0))
1679 Count = A1.countLeadingOnes();
1680 Result = APInt(BW, static_cast<uint64_t>(Count), false);
1681 return true;
1682}
1683
1684
1685bool MachineConstEvaluator::evaluateCTBr(const Register &R1, bool Zeros,
1686 bool Ones, const CellMap &Inputs, LatticeCell &Result) {
1687 assert(Inputs.has(R1.Reg));
1688 LatticeCell LS1;
1689 if (!getCell(R1, Inputs, LS1))
1690 return false;
1691 if (LS1.isBottom() || LS1.isProperty())
1692 return false;
1693
1694 APInt A, CA;
1695 for (unsigned i = 0; i < LS1.size(); ++i) {
1696 bool Eval = constToInt(LS1.Values[i], A) &&
1697 evaluateCTBi(A, Zeros, Ones, CA);
1698 if (!Eval)
1699 return false;
1700 const Constant *C = intToConst(CA);
1701 Result.add(C);
1702 }
1703 return true;
1704}
1705
1706
1707bool MachineConstEvaluator::evaluateCTBi(const APInt &A1, bool Zeros,
1708 bool Ones, APInt &Result) {
1709 unsigned BW = A1.getBitWidth();
1710 if (!Zeros && !Ones)
1711 return false;
1712 unsigned Count = 0;
1713 if (Zeros && (Count == 0))
1714 Count = A1.countTrailingZeros();
1715 if (Ones && (Count == 0))
1716 Count = A1.countTrailingOnes();
1717 Result = APInt(BW, static_cast<uint64_t>(Count), false);
1718 return true;
1719}
1720
1721
1722bool MachineConstEvaluator::evaluateEXTRACTr(const Register &R1,
1723 unsigned Width, unsigned Bits, unsigned Offset, bool Signed,
1724 const CellMap &Inputs, LatticeCell &Result) {
1725 assert(Inputs.has(R1.Reg));
1726 assert(Bits+Offset <= Width);
1727 LatticeCell LS1;
1728 if (!getCell(R1, Inputs, LS1))
1729 return false;
1730 if (LS1.isBottom())
1731 return false;
1732 if (LS1.isProperty()) {
1733 uint32_t Ps = LS1.properties();
1734 if (Ps & ConstantProperties::Zero) {
1735 const Constant *C = intToConst(APInt(Width, 0, false));
1736 Result.add(C);
1737 return true;
1738 }
1739 return false;
1740 }
1741
1742 APInt A, CA;
1743 for (unsigned i = 0; i < LS1.size(); ++i) {
1744 bool Eval = constToInt(LS1.Values[i], A) &&
1745 evaluateEXTRACTi(A, Bits, Offset, Signed, CA);
1746 if (!Eval)
1747 return false;
1748 const Constant *C = intToConst(CA);
1749 Result.add(C);
1750 }
1751 return true;
1752}
1753
1754
1755bool MachineConstEvaluator::evaluateEXTRACTi(const APInt &A1, unsigned Bits,
1756 unsigned Offset, bool Signed, APInt &Result) {
1757 unsigned BW = A1.getBitWidth();
1758 assert(Bits+Offset <= BW);
1759 // Extracting 0 bits generates 0 as a result (as indicated by the HW people).
1760 if (Bits == 0) {
1761 Result = APInt(BW, 0);
1762 return true;
1763 }
1764 if (BW <= 64) {
1765 int64_t V = A1.getZExtValue();
1766 V <<= (64-Bits-Offset);
1767 if (Signed)
1768 V >>= (64-Bits);
1769 else
1770 V = static_cast<uint64_t>(V) >> (64-Bits);
1771 Result = APInt(BW, V, Signed);
1772 return true;
1773 }
1774 if (Signed)
1775 Result = A1.shl(BW-Bits-Offset).ashr(BW-Bits);
1776 else
1777 Result = A1.shl(BW-Bits-Offset).lshr(BW-Bits);
1778 return true;
1779}
1780
1781
1782bool MachineConstEvaluator::evaluateSplatr(const Register &R1,
1783 unsigned Bits, unsigned Count, const CellMap &Inputs,
1784 LatticeCell &Result) {
1785 assert(Inputs.has(R1.Reg));
1786 LatticeCell LS1;
1787 if (!getCell(R1, Inputs, LS1))
1788 return false;
1789 if (LS1.isBottom() || LS1.isProperty())
1790 return false;
1791
1792 APInt A, SA;
1793 for (unsigned i = 0; i < LS1.size(); ++i) {
1794 bool Eval = constToInt(LS1.Values[i], A) &&
1795 evaluateSplati(A, Bits, Count, SA);
1796 if (!Eval)
1797 return false;
1798 const Constant *C = intToConst(SA);
1799 Result.add(C);
1800 }
1801 return true;
1802}
1803
1804
1805bool MachineConstEvaluator::evaluateSplati(const APInt &A1, unsigned Bits,
1806 unsigned Count, APInt &Result) {
1807 assert(Count > 0);
1808 unsigned BW = A1.getBitWidth(), SW = Count*Bits;
1809 APInt LoBits = (Bits < BW) ? A1.trunc(Bits) : A1.zextOrSelf(Bits);
1810 if (Count > 1)
1811 LoBits = LoBits.zext(SW);
1812
1813 APInt Res(SW, 0, false);
1814 for (unsigned i = 0; i < Count; ++i) {
1815 Res <<= Bits;
1816 Res |= LoBits;
1817 }
1818 Result = Res;
1819 return true;
1820}
1821
1822
1823// ----------------------------------------------------------------------
1824// Hexagon-specific code.
1825
1826namespace llvm {
1827 FunctionPass *createHexagonConstPropagationPass();
1828 void initializeHexagonConstPropagationPass(PassRegistry &Registry);
1829}
1830
1831namespace {
1832 class HexagonConstEvaluator : public MachineConstEvaluator {
1833 public:
1834 HexagonConstEvaluator(MachineFunction &Fn);
1835
1836 bool evaluate(const MachineInstr &MI, const CellMap &Inputs,
1837 CellMap &Outputs) override;
1838 bool evaluate(const Register &R, const LatticeCell &SrcC,
1839 LatticeCell &Result) override;
1840 bool evaluate(const MachineInstr &BrI, const CellMap &Inputs,
1841 SetVector<const MachineBasicBlock*> &Targets, bool &FallsThru)
1842 override;
1843 bool rewrite(MachineInstr &MI, const CellMap &Inputs) override;
1844
1845
1846 private:
1847 unsigned getRegBitWidth(unsigned Reg) const;
1848
1849 static uint32_t getCmp(unsigned Opc);
1850 static APInt getCmpImm(unsigned Opc, unsigned OpX,
1851 const MachineOperand &MO);
1852 void replaceWithNop(MachineInstr &MI);
1853
1854 bool evaluateHexRSEQ32(Register RL, Register RH, const CellMap &Inputs,
1855 LatticeCell &Result);
1856 bool evaluateHexCompare(const MachineInstr &MI, const CellMap &Inputs,
1857 CellMap &Outputs);
1858 // This is suitable to be called for compare-and-jump instructions.
1859 bool evaluateHexCompare2(uint32_t Cmp, const MachineOperand &Src1,
1860 const MachineOperand &Src2, const CellMap &Inputs, bool &Result);
1861 bool evaluateHexLogical(const MachineInstr &MI, const CellMap &Inputs,
1862 CellMap &Outputs);
1863 bool evaluateHexCondMove(const MachineInstr &MI, const CellMap &Inputs,
1864 CellMap &Outputs);
1865 bool evaluateHexExt(const MachineInstr &MI, const CellMap &Inputs,
1866 CellMap &Outputs);
1867 bool evaluateHexVector1(const MachineInstr &MI, const CellMap &Inputs,
1868 CellMap &Outputs);
1869 bool evaluateHexVector2(const MachineInstr &MI, const CellMap &Inputs,
1870 CellMap &Outputs);
1871
1872 void replaceAllRegUsesWith(unsigned FromReg, unsigned ToReg);
1873 bool rewriteHexBranch(MachineInstr &BrI, const CellMap &Inputs);
1874 bool rewriteHexConstDefs(MachineInstr &MI, const CellMap &Inputs,
1875 bool &AllDefs);
1876 bool rewriteHexConstUses(MachineInstr &MI, const CellMap &Inputs);
1877
1878 MachineRegisterInfo *MRI;
1879 const HexagonInstrInfo &HII;
1880 const HexagonRegisterInfo &HRI;
1881 };
1882
1883
1884 class HexagonConstPropagation : public MachineFunctionPass {
1885 public:
1886 static char ID;
1887 HexagonConstPropagation() : MachineFunctionPass(ID) {
1888 PassRegistry &Registry = *PassRegistry::getPassRegistry();
1889 initializeHexagonConstPropagationPass(Registry);
1890 }
1891 const char *getPassName() const override {
1892 return "Hexagon Constant Propagation";
1893 }
1894 bool runOnMachineFunction(MachineFunction &MF) override {
1895 const Function *F = MF.getFunction();
1896 if (!F)
1897 return false;
1898 if (skipFunction(*F))
1899 return false;
1900
1901 HexagonConstEvaluator HCE(MF);
1902 return MachineConstPropagator(HCE).run(MF);
1903 }
1904 };
1905
1906 char HexagonConstPropagation::ID = 0;
1907}
1908
1909INITIALIZE_PASS(HexagonConstPropagation, "hcp", "Hexagon Constant Propagation",
1910 false, false)
1911
1912
1913HexagonConstEvaluator::HexagonConstEvaluator(MachineFunction &Fn)
1914 : MachineConstEvaluator(Fn),
1915 HII(*Fn.getSubtarget<HexagonSubtarget>().getInstrInfo()),
1916 HRI(*Fn.getSubtarget<HexagonSubtarget>().getRegisterInfo()) {
1917 MRI = &Fn.getRegInfo();
1918}
1919
1920
1921bool HexagonConstEvaluator::evaluate(const MachineInstr &MI,
1922 const CellMap &Inputs, CellMap &Outputs) {
1923 if (MI.isCall())
1924 return false;
1925 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg())
1926 return false;
1927 const MachineOperand &MD = MI.getOperand(0);
1928 if (!MD.isDef())
1929 return false;
1930
1931 unsigned Opc = MI.getOpcode();
1932 Register DefR(MD);
1933 assert(!DefR.SubReg);
1934 if (!TargetRegisterInfo::isVirtualRegister(DefR.Reg))
1935 return false;
1936
1937 if (MI.isCopy()) {
1938 LatticeCell RC;
1939 Register SrcR(MI.getOperand(1));
1940 bool Eval = evaluateCOPY(SrcR, Inputs, RC);
1941 if (!Eval)
1942 return false;
1943 Outputs.update(DefR.Reg, RC);
1944 return true;
1945 }
1946 if (MI.isRegSequence()) {
1947 unsigned Sub1 = MI.getOperand(2).getImm();
1948 unsigned Sub2 = MI.getOperand(4).getImm();
1949 if (Sub1 != Hexagon::subreg_loreg && Sub1 != Hexagon::subreg_hireg)
1950 return false;
1951 if (Sub2 != Hexagon::subreg_loreg && Sub2 != Hexagon::subreg_hireg)
1952 return false;
1953 assert(Sub1 != Sub2);
1954 bool LoIs1 = (Sub1 == Hexagon::subreg_loreg);
1955 const MachineOperand &OpLo = LoIs1 ? MI.getOperand(1) : MI.getOperand(3);
1956 const MachineOperand &OpHi = LoIs1 ? MI.getOperand(3) : MI.getOperand(1);
1957 LatticeCell RC;
1958 Register SrcRL(OpLo), SrcRH(OpHi);
1959 bool Eval = evaluateHexRSEQ32(SrcRL, SrcRH, Inputs, RC);
1960 if (!Eval)
1961 return false;
1962 Outputs.update(DefR.Reg, RC);
1963 return true;
1964 }
1965 if (MI.isCompare()) {
1966 bool Eval = evaluateHexCompare(MI, Inputs, Outputs);
1967 return Eval;
1968 }
1969
1970 switch (Opc) {
1971 default:
1972 return false;
1973 case Hexagon::A2_tfrsi:
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00001974 case Hexagon::A2_tfrpi:
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +00001975 case Hexagon::CONST32:
1976 case Hexagon::CONST64:
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00001977 {
1978 const MachineOperand &VO = MI.getOperand(1);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +00001979 // The operand of CONST32 can be a blockaddress, e.g.
1980 // %vreg0<def> = CONST32 <blockaddress(@eat, %L)>
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00001981 // Do this check for all instructions for safety.
1982 if (!VO.isImm())
1983 return false;
1984 int64_t V = MI.getOperand(1).getImm();
1985 unsigned W = getRegBitWidth(DefR.Reg);
1986 if (W != 32 && W != 64)
1987 return false;
1988 IntegerType *Ty = (W == 32) ? Type::getInt32Ty(CX)
1989 : Type::getInt64Ty(CX);
1990 const ConstantInt *CI = ConstantInt::get(Ty, V, true);
1991 LatticeCell RC = Outputs.get(DefR.Reg);
1992 RC.add(CI);
1993 Outputs.update(DefR.Reg, RC);
1994 break;
1995 }
1996
1997 case Hexagon::TFR_PdTrue:
1998 case Hexagon::TFR_PdFalse:
1999 {
2000 LatticeCell RC = Outputs.get(DefR.Reg);
2001 bool NonZero = (Opc == Hexagon::TFR_PdTrue);
2002 uint32_t P = NonZero ? ConstantProperties::NonZero
2003 : ConstantProperties::Zero;
2004 RC.add(P);
2005 Outputs.update(DefR.Reg, RC);
2006 break;
2007 }
2008
2009 case Hexagon::A2_and:
2010 case Hexagon::A2_andir:
2011 case Hexagon::A2_andp:
2012 case Hexagon::A2_or:
2013 case Hexagon::A2_orir:
2014 case Hexagon::A2_orp:
2015 case Hexagon::A2_xor:
2016 case Hexagon::A2_xorp:
2017 {
2018 bool Eval = evaluateHexLogical(MI, Inputs, Outputs);
2019 if (!Eval)
2020 return false;
2021 break;
2022 }
2023
2024 case Hexagon::A2_combineii: // combine(#s8Ext, #s8)
2025 case Hexagon::A4_combineii: // combine(#s8, #u6Ext)
2026 {
Benjamin Kramerafff73c2016-07-30 13:25:37 +00002027 uint64_t Hi = MI.getOperand(1).getImm();
2028 uint64_t Lo = MI.getOperand(2).getImm();
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00002029 uint64_t Res = (Hi << 32) | (Lo & 0xFFFFFFFF);
2030 IntegerType *Ty = Type::getInt64Ty(CX);
2031 const ConstantInt *CI = ConstantInt::get(Ty, Res, false);
2032 LatticeCell RC = Outputs.get(DefR.Reg);
2033 RC.add(CI);
2034 Outputs.update(DefR.Reg, RC);
2035 break;
2036 }
2037
2038 case Hexagon::S2_setbit_i:
2039 {
2040 int64_t B = MI.getOperand(2).getImm();
2041 assert(B >=0 && B < 32);
Simon Pilgrim0aaf6ba2016-07-29 10:03:39 +00002042 APInt A(32, (1ull << B), false);
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00002043 Register R(MI.getOperand(1));
2044 LatticeCell RC = Outputs.get(DefR.Reg);
2045 bool Eval = evaluateORri(R, A, Inputs, RC);
2046 if (!Eval)
2047 return false;
2048 Outputs.update(DefR.Reg, RC);
2049 break;
2050 }
2051
2052 case Hexagon::C2_mux:
2053 case Hexagon::C2_muxir:
2054 case Hexagon::C2_muxri:
2055 case Hexagon::C2_muxii:
2056 {
2057 bool Eval = evaluateHexCondMove(MI, Inputs, Outputs);
2058 if (!Eval)
2059 return false;
2060 break;
2061 }
2062
2063 case Hexagon::A2_sxtb:
2064 case Hexagon::A2_sxth:
2065 case Hexagon::A2_sxtw:
2066 case Hexagon::A2_zxtb:
2067 case Hexagon::A2_zxth:
2068 {
2069 bool Eval = evaluateHexExt(MI, Inputs, Outputs);
2070 if (!Eval)
2071 return false;
2072 break;
2073 }
2074
2075 case Hexagon::S2_ct0:
2076 case Hexagon::S2_ct0p:
2077 case Hexagon::S2_ct1:
2078 case Hexagon::S2_ct1p:
2079 {
2080 using namespace Hexagon;
2081 bool Ones = (Opc == S2_ct1) || (Opc == S2_ct1p);
2082 Register R1(MI.getOperand(1));
2083 assert(Inputs.has(R1.Reg));
2084 LatticeCell T;
2085 bool Eval = evaluateCTBr(R1, !Ones, Ones, Inputs, T);
2086 if (!Eval)
2087 return false;
2088 // All of these instructions return a 32-bit value. The evaluate
2089 // will generate the same type as the operand, so truncate the
2090 // result if necessary.
2091 APInt C;
2092 LatticeCell RC = Outputs.get(DefR.Reg);
2093 for (unsigned i = 0; i < T.size(); ++i) {
2094 const Constant *CI = T.Values[i];
2095 if (constToInt(CI, C) && C.getBitWidth() > 32)
2096 CI = intToConst(C.trunc(32));
2097 RC.add(CI);
2098 }
2099 Outputs.update(DefR.Reg, RC);
2100 break;
2101 }
2102
2103 case Hexagon::S2_cl0:
2104 case Hexagon::S2_cl0p:
2105 case Hexagon::S2_cl1:
2106 case Hexagon::S2_cl1p:
2107 case Hexagon::S2_clb:
2108 case Hexagon::S2_clbp:
2109 {
2110 using namespace Hexagon;
2111 bool OnlyZeros = (Opc == S2_cl0) || (Opc == S2_cl0p);
2112 bool OnlyOnes = (Opc == S2_cl1) || (Opc == S2_cl1p);
2113 Register R1(MI.getOperand(1));
2114 assert(Inputs.has(R1.Reg));
2115 LatticeCell T;
2116 bool Eval = evaluateCLBr(R1, !OnlyOnes, !OnlyZeros, Inputs, T);
2117 if (!Eval)
2118 return false;
2119 // All of these instructions return a 32-bit value. The evaluate
2120 // will generate the same type as the operand, so truncate the
2121 // result if necessary.
2122 APInt C;
2123 LatticeCell RC = Outputs.get(DefR.Reg);
2124 for (unsigned i = 0; i < T.size(); ++i) {
2125 const Constant *CI = T.Values[i];
2126 if (constToInt(CI, C) && C.getBitWidth() > 32)
2127 CI = intToConst(C.trunc(32));
2128 RC.add(CI);
2129 }
2130 Outputs.update(DefR.Reg, RC);
2131 break;
2132 }
2133
2134 case Hexagon::S4_extract:
2135 case Hexagon::S4_extractp:
2136 case Hexagon::S2_extractu:
2137 case Hexagon::S2_extractup:
2138 {
2139 bool Signed = (Opc == Hexagon::S4_extract) ||
2140 (Opc == Hexagon::S4_extractp);
2141 Register R1(MI.getOperand(1));
2142 unsigned BW = getRegBitWidth(R1.Reg);
2143 unsigned Bits = MI.getOperand(2).getImm();
2144 unsigned Offset = MI.getOperand(3).getImm();
2145 LatticeCell RC = Outputs.get(DefR.Reg);
2146 if (Offset >= BW) {
2147 APInt Zero(BW, 0, false);
2148 RC.add(intToConst(Zero));
2149 break;
2150 }
2151 if (Offset+Bits > BW) {
2152 // If the requested bitfield extends beyond the most significant bit,
2153 // the extra bits are treated as 0s. To emulate this behavior, reduce
2154 // the number of requested bits, and make the extract unsigned.
2155 Bits = BW-Offset;
2156 Signed = false;
2157 }
2158 bool Eval = evaluateEXTRACTr(R1, BW, Bits, Offset, Signed, Inputs, RC);
2159 if (!Eval)
2160 return false;
2161 Outputs.update(DefR.Reg, RC);
2162 break;
2163 }
2164
2165 case Hexagon::S2_vsplatrb:
2166 case Hexagon::S2_vsplatrh:
2167 // vabsh, vabsh:sat
2168 // vabsw, vabsw:sat
2169 // vconj:sat
2170 // vrndwh, vrndwh:sat
2171 // vsathb, vsathub, vsatwuh
2172 // vsxtbh, vsxthw
2173 // vtrunehb, vtrunohb
2174 // vzxtbh, vzxthw
2175 {
2176 bool Eval = evaluateHexVector1(MI, Inputs, Outputs);
2177 if (!Eval)
2178 return false;
2179 break;
2180 }
2181
2182 // TODO:
2183 // A2_vaddh
2184 // A2_vaddhs
2185 // A2_vaddw
2186 // A2_vaddws
2187 }
2188
2189 return true;
2190}
2191
2192
2193bool HexagonConstEvaluator::evaluate(const Register &R,
2194 const LatticeCell &Input, LatticeCell &Result) {
2195 if (!R.SubReg) {
2196 Result = Input;
2197 return true;
2198 }
2199 // Predicate registers do not have subregisters.
2200 const TargetRegisterClass *RC = MRI->getRegClass(R.Reg);
2201 if (RC == &Hexagon::PredRegsRegClass)
2202 return false;
2203 if (R.SubReg != Hexagon::subreg_loreg && R.SubReg != Hexagon::subreg_hireg)
2204 return false;
2205
2206 assert(!Input.isTop());
2207 if (Input.isBottom())
2208 return false;
2209
2210 typedef ConstantProperties P;
2211 if (Input.isProperty()) {
2212 uint32_t Ps = Input.properties();
2213 if (Ps & (P::Zero|P::NaN)) {
2214 uint32_t Ns = (Ps & (P::Zero|P::NaN|P::SignProperties));
2215 Result.add(Ns);
2216 return true;
2217 }
2218 if (R.SubReg == Hexagon::subreg_hireg) {
2219 uint32_t Ns = (Ps & P::SignProperties);
2220 Result.add(Ns);
2221 return true;
2222 }
2223 return false;
2224 }
2225
2226 // The Input cell contains some known values. Pick the word corresponding
2227 // to the subregister.
2228 APInt A;
2229 for (unsigned i = 0; i < Input.size(); ++i) {
2230 const Constant *C = Input.Values[i];
2231 if (!constToInt(C, A))
2232 return false;
2233 if (!A.isIntN(64))
2234 return false;
2235 uint64_t U = A.getZExtValue();
2236 if (R.SubReg == Hexagon::subreg_hireg)
2237 U >>= 32;
2238 U &= 0xFFFFFFFFULL;
2239 uint32_t U32 = Lo_32(U);
2240 int32_t V32;
2241 memcpy(&V32, &U32, sizeof V32);
2242 IntegerType *Ty = Type::getInt32Ty(CX);
2243 const ConstantInt *C32 = ConstantInt::get(Ty, static_cast<int64_t>(V32));
2244 Result.add(C32);
2245 }
2246 return true;
2247}
2248
2249
2250bool HexagonConstEvaluator::evaluate(const MachineInstr &BrI,
2251 const CellMap &Inputs, SetVector<const MachineBasicBlock*> &Targets,
2252 bool &FallsThru) {
2253 // We need to evaluate one branch at a time. TII::analyzeBranch checks
2254 // all the branches in a basic block at once, so we cannot use it.
2255 unsigned Opc = BrI.getOpcode();
2256 bool SimpleBranch = false;
2257 bool Negated = false;
2258 switch (Opc) {
2259 case Hexagon::J2_jumpf:
2260 case Hexagon::J2_jumpfnew:
2261 case Hexagon::J2_jumpfnewpt:
2262 Negated = true;
2263 case Hexagon::J2_jumpt:
2264 case Hexagon::J2_jumptnew:
2265 case Hexagon::J2_jumptnewpt:
2266 // Simple branch: if([!]Pn) jump ...
2267 // i.e. Op0 = predicate, Op1 = branch target.
2268 SimpleBranch = true;
2269 break;
2270 case Hexagon::J2_jump:
2271 Targets.insert(BrI.getOperand(0).getMBB());
2272 FallsThru = false;
2273 return true;
2274 default:
2275Undetermined:
2276 // If the branch is of unknown type, assume that all successors are
2277 // executable.
2278 FallsThru = !BrI.isUnconditionalBranch();
2279 return false;
2280 }
2281
2282 if (SimpleBranch) {
2283 const MachineOperand &MD = BrI.getOperand(0);
2284 Register PR(MD);
2285 // If the condition operand has a subregister, this is not something
2286 // we currently recognize.
2287 if (PR.SubReg)
2288 goto Undetermined;
2289 assert(Inputs.has(PR.Reg));
2290 const LatticeCell &PredC = Inputs.get(PR.Reg);
2291 if (PredC.isBottom())
2292 goto Undetermined;
2293
2294 uint32_t Props = PredC.properties();
2295 bool CTrue = false, CFalse = false;;
2296 if (Props & ConstantProperties::Zero)
2297 CFalse = true;
2298 else if (Props & ConstantProperties::NonZero)
2299 CTrue = true;
2300 // If the condition is not known to be either, bail out.
2301 if (!CTrue && !CFalse)
2302 goto Undetermined;
2303
2304 const MachineBasicBlock *BranchTarget = BrI.getOperand(1).getMBB();
2305
2306 FallsThru = false;
2307 if ((!Negated && CTrue) || (Negated && CFalse))
2308 Targets.insert(BranchTarget);
2309 else if ((!Negated && CFalse) || (Negated && CTrue))
2310 FallsThru = true;
2311 else
2312 goto Undetermined;
2313 }
2314
2315 return true;
2316}
2317
2318
2319bool HexagonConstEvaluator::rewrite(MachineInstr &MI, const CellMap &Inputs) {
2320 if (MI.isBranch())
2321 return rewriteHexBranch(MI, Inputs);
2322
2323 unsigned Opc = MI.getOpcode();
2324 switch (Opc) {
2325 default:
2326 break;
2327 case Hexagon::A2_tfrsi:
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00002328 case Hexagon::A2_tfrpi:
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +00002329 case Hexagon::CONST32:
2330 case Hexagon::CONST64:
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00002331 case Hexagon::TFR_PdTrue:
2332 case Hexagon::TFR_PdFalse:
2333 return false;
2334 }
2335
2336 unsigned NumOp = MI.getNumOperands();
2337 if (NumOp == 0)
2338 return false;
2339
2340 bool AllDefs, Changed;
2341 Changed = rewriteHexConstDefs(MI, Inputs, AllDefs);
2342 // If not all defs have been rewritten (i.e. the instruction defines
2343 // a register that is not compile-time constant), then try to rewrite
2344 // register operands that are known to be constant with immediates.
2345 if (!AllDefs)
2346 Changed |= rewriteHexConstUses(MI, Inputs);
2347
2348 return Changed;
2349}
2350
2351
2352unsigned HexagonConstEvaluator::getRegBitWidth(unsigned Reg) const {
2353 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
2354 if (Hexagon::IntRegsRegClass.hasSubClassEq(RC))
2355 return 32;
2356 if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC))
2357 return 64;
2358 if (Hexagon::PredRegsRegClass.hasSubClassEq(RC))
2359 return 8;
2360 llvm_unreachable("Invalid register");
2361 return 0;
2362}
2363
2364
2365uint32_t HexagonConstEvaluator::getCmp(unsigned Opc) {
2366 switch (Opc) {
2367 case Hexagon::C2_cmpeq:
2368 case Hexagon::C2_cmpeqp:
2369 case Hexagon::A4_cmpbeq:
2370 case Hexagon::A4_cmpheq:
2371 case Hexagon::A4_cmpbeqi:
2372 case Hexagon::A4_cmpheqi:
2373 case Hexagon::C2_cmpeqi:
2374 case Hexagon::J4_cmpeqn1_t_jumpnv_nt:
2375 case Hexagon::J4_cmpeqn1_t_jumpnv_t:
2376 case Hexagon::J4_cmpeqi_t_jumpnv_nt:
2377 case Hexagon::J4_cmpeqi_t_jumpnv_t:
2378 case Hexagon::J4_cmpeq_t_jumpnv_nt:
2379 case Hexagon::J4_cmpeq_t_jumpnv_t:
2380 return Comparison::EQ;
2381
2382 case Hexagon::C4_cmpneq:
2383 case Hexagon::C4_cmpneqi:
2384 case Hexagon::J4_cmpeqn1_f_jumpnv_nt:
2385 case Hexagon::J4_cmpeqn1_f_jumpnv_t:
2386 case Hexagon::J4_cmpeqi_f_jumpnv_nt:
2387 case Hexagon::J4_cmpeqi_f_jumpnv_t:
2388 case Hexagon::J4_cmpeq_f_jumpnv_nt:
2389 case Hexagon::J4_cmpeq_f_jumpnv_t:
2390 return Comparison::NE;
2391
2392 case Hexagon::C2_cmpgt:
2393 case Hexagon::C2_cmpgtp:
2394 case Hexagon::A4_cmpbgt:
2395 case Hexagon::A4_cmphgt:
2396 case Hexagon::A4_cmpbgti:
2397 case Hexagon::A4_cmphgti:
2398 case Hexagon::C2_cmpgti:
2399 case Hexagon::J4_cmpgtn1_t_jumpnv_nt:
2400 case Hexagon::J4_cmpgtn1_t_jumpnv_t:
2401 case Hexagon::J4_cmpgti_t_jumpnv_nt:
2402 case Hexagon::J4_cmpgti_t_jumpnv_t:
2403 case Hexagon::J4_cmpgt_t_jumpnv_nt:
2404 case Hexagon::J4_cmpgt_t_jumpnv_t:
2405 return Comparison::GTs;
2406
2407 case Hexagon::C4_cmplte:
2408 case Hexagon::C4_cmpltei:
2409 case Hexagon::J4_cmpgtn1_f_jumpnv_nt:
2410 case Hexagon::J4_cmpgtn1_f_jumpnv_t:
2411 case Hexagon::J4_cmpgti_f_jumpnv_nt:
2412 case Hexagon::J4_cmpgti_f_jumpnv_t:
2413 case Hexagon::J4_cmpgt_f_jumpnv_nt:
2414 case Hexagon::J4_cmpgt_f_jumpnv_t:
2415 return Comparison::LEs;
2416
2417 case Hexagon::C2_cmpgtu:
2418 case Hexagon::C2_cmpgtup:
2419 case Hexagon::A4_cmpbgtu:
2420 case Hexagon::A4_cmpbgtui:
2421 case Hexagon::A4_cmphgtu:
2422 case Hexagon::A4_cmphgtui:
2423 case Hexagon::C2_cmpgtui:
2424 case Hexagon::J4_cmpgtui_t_jumpnv_nt:
2425 case Hexagon::J4_cmpgtui_t_jumpnv_t:
2426 case Hexagon::J4_cmpgtu_t_jumpnv_nt:
2427 case Hexagon::J4_cmpgtu_t_jumpnv_t:
2428 return Comparison::GTu;
2429
2430 case Hexagon::J4_cmpltu_f_jumpnv_nt:
2431 case Hexagon::J4_cmpltu_f_jumpnv_t:
2432 return Comparison::GEu;
2433
2434 case Hexagon::J4_cmpltu_t_jumpnv_nt:
2435 case Hexagon::J4_cmpltu_t_jumpnv_t:
2436 return Comparison::LTu;
2437
2438 case Hexagon::J4_cmplt_f_jumpnv_nt:
2439 case Hexagon::J4_cmplt_f_jumpnv_t:
2440 return Comparison::GEs;
2441
2442 case Hexagon::C4_cmplteu:
2443 case Hexagon::C4_cmplteui:
2444 case Hexagon::J4_cmpgtui_f_jumpnv_nt:
2445 case Hexagon::J4_cmpgtui_f_jumpnv_t:
2446 case Hexagon::J4_cmpgtu_f_jumpnv_nt:
2447 case Hexagon::J4_cmpgtu_f_jumpnv_t:
2448 return Comparison::LEu;
2449
2450 case Hexagon::J4_cmplt_t_jumpnv_nt:
2451 case Hexagon::J4_cmplt_t_jumpnv_t:
2452 return Comparison::LTs;
2453
2454 default:
2455 break;
2456 }
2457 return Comparison::Unk;
2458}
2459
2460
2461APInt HexagonConstEvaluator::getCmpImm(unsigned Opc, unsigned OpX,
2462 const MachineOperand &MO) {
2463 bool Signed = false;
2464 switch (Opc) {
2465 case Hexagon::A4_cmpbgtui: // u7
2466 case Hexagon::A4_cmphgtui: // u7
2467 break;
2468 case Hexagon::A4_cmpheqi: // s8
2469 case Hexagon::C4_cmpneqi: // s8
2470 Signed = true;
2471 case Hexagon::A4_cmpbeqi: // u8
2472 break;
2473 case Hexagon::C2_cmpgtui: // u9
2474 case Hexagon::C4_cmplteui: // u9
2475 break;
2476 case Hexagon::C2_cmpeqi: // s10
2477 case Hexagon::C2_cmpgti: // s10
2478 case Hexagon::C4_cmpltei: // s10
2479 Signed = true;
2480 break;
2481 case Hexagon::J4_cmpeqi_f_jumpnv_nt: // u5
2482 case Hexagon::J4_cmpeqi_f_jumpnv_t: // u5
2483 case Hexagon::J4_cmpeqi_t_jumpnv_nt: // u5
2484 case Hexagon::J4_cmpeqi_t_jumpnv_t: // u5
2485 case Hexagon::J4_cmpgti_f_jumpnv_nt: // u5
2486 case Hexagon::J4_cmpgti_f_jumpnv_t: // u5
2487 case Hexagon::J4_cmpgti_t_jumpnv_nt: // u5
2488 case Hexagon::J4_cmpgti_t_jumpnv_t: // u5
2489 case Hexagon::J4_cmpgtui_f_jumpnv_nt: // u5
2490 case Hexagon::J4_cmpgtui_f_jumpnv_t: // u5
2491 case Hexagon::J4_cmpgtui_t_jumpnv_nt: // u5
2492 case Hexagon::J4_cmpgtui_t_jumpnv_t: // u5
2493 break;
2494 default:
2495 llvm_unreachable("Unhandled instruction");
2496 break;
2497 }
2498
2499 uint64_t Val = MO.getImm();
2500 return APInt(32, Val, Signed);
2501}
2502
2503
2504void HexagonConstEvaluator::replaceWithNop(MachineInstr &MI) {
2505 MI.setDesc(HII.get(Hexagon::A2_nop));
2506 while (MI.getNumOperands() > 0)
2507 MI.RemoveOperand(0);
2508}
2509
2510
2511bool HexagonConstEvaluator::evaluateHexRSEQ32(Register RL, Register RH,
2512 const CellMap &Inputs, LatticeCell &Result) {
2513 assert(Inputs.has(RL.Reg) && Inputs.has(RH.Reg));
2514 LatticeCell LSL, LSH;
2515 if (!getCell(RL, Inputs, LSL) || !getCell(RH, Inputs, LSH))
2516 return false;
2517 if (LSL.isProperty() || LSH.isProperty())
2518 return false;
2519
2520 unsigned LN = LSL.size(), HN = LSH.size();
2521 SmallVector<APInt,4> LoVs(LN), HiVs(HN);
2522 for (unsigned i = 0; i < LN; ++i) {
2523 bool Eval = constToInt(LSL.Values[i], LoVs[i]);
2524 if (!Eval)
2525 return false;
2526 assert(LoVs[i].getBitWidth() == 32);
2527 }
2528 for (unsigned i = 0; i < HN; ++i) {
2529 bool Eval = constToInt(LSH.Values[i], HiVs[i]);
2530 if (!Eval)
2531 return false;
2532 assert(HiVs[i].getBitWidth() == 32);
2533 }
2534
2535 for (unsigned i = 0; i < HiVs.size(); ++i) {
2536 APInt HV = HiVs[i].zextOrSelf(64) << 32;
2537 for (unsigned j = 0; j < LoVs.size(); ++j) {
2538 APInt LV = LoVs[j].zextOrSelf(64);
2539 const Constant *C = intToConst(HV | LV);
2540 Result.add(C);
2541 if (Result.isBottom())
2542 return false;
2543 }
2544 }
2545 return !Result.isBottom();
2546}
2547
2548
2549bool HexagonConstEvaluator::evaluateHexCompare(const MachineInstr &MI,
2550 const CellMap &Inputs, CellMap &Outputs) {
2551 unsigned Opc = MI.getOpcode();
2552 bool Classic = false;
2553 switch (Opc) {
2554 case Hexagon::C2_cmpeq:
2555 case Hexagon::C2_cmpeqp:
2556 case Hexagon::C2_cmpgt:
2557 case Hexagon::C2_cmpgtp:
2558 case Hexagon::C2_cmpgtu:
2559 case Hexagon::C2_cmpgtup:
2560 case Hexagon::C2_cmpeqi:
2561 case Hexagon::C2_cmpgti:
2562 case Hexagon::C2_cmpgtui:
2563 // Classic compare: Dst0 = CMP Src1, Src2
2564 Classic = true;
2565 break;
2566 default:
2567 // Not handling other compare instructions now.
2568 return false;
2569 }
2570
2571 if (Classic) {
2572 const MachineOperand &Src1 = MI.getOperand(1);
2573 const MachineOperand &Src2 = MI.getOperand(2);
2574
2575 bool Result;
2576 unsigned Opc = MI.getOpcode();
2577 bool Computed = evaluateHexCompare2(Opc, Src1, Src2, Inputs, Result);
2578 if (Computed) {
2579 // Only create a zero/non-zero cell. At this time there isn't really
2580 // much need for specific values.
2581 Register DefR(MI.getOperand(0));
2582 LatticeCell L = Outputs.get(DefR.Reg);
2583 uint32_t P = Result ? ConstantProperties::NonZero
2584 : ConstantProperties::Zero;
2585 L.add(P);
2586 Outputs.update(DefR.Reg, L);
2587 return true;
2588 }
2589 }
2590
2591 return false;
2592}
2593
2594
2595bool HexagonConstEvaluator::evaluateHexCompare2(unsigned Opc,
2596 const MachineOperand &Src1, const MachineOperand &Src2,
2597 const CellMap &Inputs, bool &Result) {
2598 uint32_t Cmp = getCmp(Opc);
2599 bool Reg1 = Src1.isReg(), Reg2 = Src2.isReg();
2600 bool Imm1 = Src1.isImm(), Imm2 = Src2.isImm();
2601 if (Reg1) {
2602 Register R1(Src1);
2603 if (Reg2) {
2604 Register R2(Src2);
2605 return evaluateCMPrr(Cmp, R1, R2, Inputs, Result);
2606 } else if (Imm2) {
2607 APInt A2 = getCmpImm(Opc, 2, Src2);
2608 return evaluateCMPri(Cmp, R1, A2, Inputs, Result);
2609 }
2610 } else if (Imm1) {
2611 APInt A1 = getCmpImm(Opc, 1, Src1);
2612 if (Reg2) {
2613 Register R2(Src2);
2614 uint32_t NegCmp = Comparison::negate(Cmp);
2615 return evaluateCMPri(NegCmp, R2, A1, Inputs, Result);
2616 } else if (Imm2) {
2617 APInt A2 = getCmpImm(Opc, 2, Src2);
2618 return evaluateCMPii(Cmp, A1, A2, Result);
2619 }
2620 }
2621 // Unknown kind of comparison.
2622 return false;
2623}
2624
2625
2626bool HexagonConstEvaluator::evaluateHexLogical(const MachineInstr &MI,
2627 const CellMap &Inputs, CellMap &Outputs) {
2628 unsigned Opc = MI.getOpcode();
2629 if (MI.getNumOperands() != 3)
2630 return false;
2631 const MachineOperand &Src1 = MI.getOperand(1);
2632 const MachineOperand &Src2 = MI.getOperand(2);
2633 Register R1(Src1);
2634 bool Eval = false;
2635 LatticeCell RC;
2636 switch (Opc) {
2637 default:
2638 return false;
2639 case Hexagon::A2_and:
2640 case Hexagon::A2_andp:
2641 Eval = evaluateANDrr(R1, Register(Src2), Inputs, RC);
2642 break;
2643 case Hexagon::A2_andir: {
2644 APInt A(32, Src2.getImm(), true);
2645 Eval = evaluateANDri(R1, A, Inputs, RC);
2646 break;
2647 }
2648 case Hexagon::A2_or:
2649 case Hexagon::A2_orp:
2650 Eval = evaluateORrr(R1, Register(Src2), Inputs, RC);
2651 break;
2652 case Hexagon::A2_orir: {
2653 APInt A(32, Src2.getImm(), true);
2654 Eval = evaluateORri(R1, A, Inputs, RC);
2655 break;
2656 }
2657 case Hexagon::A2_xor:
2658 case Hexagon::A2_xorp:
2659 Eval = evaluateXORrr(R1, Register(Src2), Inputs, RC);
2660 break;
2661 }
2662 if (Eval) {
2663 Register DefR(MI.getOperand(0));
2664 Outputs.update(DefR.Reg, RC);
2665 }
2666 return Eval;
2667}
2668
2669
2670bool HexagonConstEvaluator::evaluateHexCondMove(const MachineInstr &MI,
2671 const CellMap &Inputs, CellMap &Outputs) {
2672 // Dst0 = Cond1 ? Src2 : Src3
2673 Register CR(MI.getOperand(1));
2674 assert(Inputs.has(CR.Reg));
2675 LatticeCell LS;
2676 if (!getCell(CR, Inputs, LS))
2677 return false;
2678 uint32_t Ps = LS.properties();
2679 unsigned TakeOp;
2680 if (Ps & ConstantProperties::Zero)
2681 TakeOp = 3;
2682 else if (Ps & ConstantProperties::NonZero)
2683 TakeOp = 2;
2684 else
2685 return false;
2686
2687 const MachineOperand &ValOp = MI.getOperand(TakeOp);
2688 Register DefR(MI.getOperand(0));
2689 LatticeCell RC = Outputs.get(DefR.Reg);
2690
2691 if (ValOp.isImm()) {
2692 int64_t V = ValOp.getImm();
2693 unsigned W = getRegBitWidth(DefR.Reg);
2694 APInt A(W, V, true);
2695 const Constant *C = intToConst(A);
2696 RC.add(C);
2697 Outputs.update(DefR.Reg, RC);
2698 return true;
2699 }
2700 if (ValOp.isReg()) {
2701 Register R(ValOp);
2702 const LatticeCell &LR = Inputs.get(R.Reg);
2703 LatticeCell LSR;
2704 if (!evaluate(R, LR, LSR))
2705 return false;
2706 RC.meet(LSR);
2707 Outputs.update(DefR.Reg, RC);
2708 return true;
2709 }
2710 return false;
2711}
2712
2713
2714bool HexagonConstEvaluator::evaluateHexExt(const MachineInstr &MI,
2715 const CellMap &Inputs, CellMap &Outputs) {
2716 // Dst0 = ext R1
2717 Register R1(MI.getOperand(1));
2718 assert(Inputs.has(R1.Reg));
2719
2720 unsigned Opc = MI.getOpcode();
2721 unsigned Bits;
2722 switch (Opc) {
2723 case Hexagon::A2_sxtb:
2724 case Hexagon::A2_zxtb:
2725 Bits = 8;
2726 break;
2727 case Hexagon::A2_sxth:
2728 case Hexagon::A2_zxth:
2729 Bits = 16;
2730 break;
2731 case Hexagon::A2_sxtw:
2732 Bits = 32;
2733 break;
2734 }
2735
2736 bool Signed = false;
2737 switch (Opc) {
2738 case Hexagon::A2_sxtb:
2739 case Hexagon::A2_sxth:
2740 case Hexagon::A2_sxtw:
2741 Signed = true;
2742 break;
2743 }
2744
2745 Register DefR(MI.getOperand(0));
2746 unsigned BW = getRegBitWidth(DefR.Reg);
2747 LatticeCell RC = Outputs.get(DefR.Reg);
2748 bool Eval = Signed ? evaluateSEXTr(R1, BW, Bits, Inputs, RC)
2749 : evaluateZEXTr(R1, BW, Bits, Inputs, RC);
2750 if (!Eval)
2751 return false;
2752 Outputs.update(DefR.Reg, RC);
2753 return true;
2754}
2755
2756
2757bool HexagonConstEvaluator::evaluateHexVector1(const MachineInstr &MI,
2758 const CellMap &Inputs, CellMap &Outputs) {
2759 // DefR = op R1
2760 Register DefR(MI.getOperand(0));
2761 Register R1(MI.getOperand(1));
2762 assert(Inputs.has(R1.Reg));
2763 LatticeCell RC = Outputs.get(DefR.Reg);
2764 bool Eval;
2765
2766 unsigned Opc = MI.getOpcode();
2767 switch (Opc) {
2768 case Hexagon::S2_vsplatrb:
2769 // Rd = 4 times Rs:0..7
2770 Eval = evaluateSplatr(R1, 8, 4, Inputs, RC);
2771 break;
2772 case Hexagon::S2_vsplatrh:
2773 // Rdd = 4 times Rs:0..15
2774 Eval = evaluateSplatr(R1, 16, 4, Inputs, RC);
2775 break;
2776 default:
2777 return false;
2778 }
2779
2780 if (!Eval)
2781 return false;
2782 Outputs.update(DefR.Reg, RC);
2783 return true;
2784}
2785
2786
2787bool HexagonConstEvaluator::rewriteHexConstDefs(MachineInstr &MI,
2788 const CellMap &Inputs, bool &AllDefs) {
2789 AllDefs = false;
2790
2791 // Some diagnostics.
2792 // DEBUG({...}) gets confused with all this code as an argument.
2793#ifndef NDEBUG
2794 bool Debugging = llvm::DebugFlag &&
2795 llvm::isCurrentDebugType(DEBUG_TYPE);
2796 if (Debugging) {
2797 bool Const = true, HasUse = false;
2798 for (const MachineOperand &MO : MI.operands()) {
2799 if (!MO.isReg() || !MO.isUse() || MO.isImplicit())
2800 continue;
2801 Register R(MO);
2802 if (!TargetRegisterInfo::isVirtualRegister(R.Reg))
2803 continue;
2804 HasUse = true;
2805 // PHIs can legitimately have "top" cells after propagation.
2806 if (!MI.isPHI() && !Inputs.has(R.Reg)) {
2807 dbgs() << "Top " << PrintReg(R.Reg, &HRI, R.SubReg)
2808 << " in MI: " << MI;
2809 continue;
2810 }
2811 const LatticeCell &L = Inputs.get(R.Reg);
2812 Const &= L.isSingle();
2813 if (!Const)
2814 break;
2815 }
2816 if (HasUse && Const) {
2817 if (!MI.isCopy()) {
2818 dbgs() << "CONST: " << MI;
2819 for (const MachineOperand &MO : MI.operands()) {
2820 if (!MO.isReg() || !MO.isUse() || MO.isImplicit())
2821 continue;
2822 unsigned R = MO.getReg();
2823 dbgs() << PrintReg(R, &TRI) << ": " << Inputs.get(R) << "\n";
2824 }
2825 }
2826 }
2827 }
2828#endif
2829
2830 // Avoid generating TFRIs for register transfers---this will keep the
2831 // coalescing opportunities.
2832 if (MI.isCopy())
2833 return false;
2834
2835 // Collect all virtual register-def operands.
2836 SmallVector<unsigned,2> DefRegs;
2837 for (const MachineOperand &MO : MI.operands()) {
2838 if (!MO.isReg() || !MO.isDef())
2839 continue;
2840 unsigned R = MO.getReg();
2841 if (!TargetRegisterInfo::isVirtualRegister(R))
2842 continue;
2843 assert(!MO.getSubReg());
2844 assert(Inputs.has(R));
2845 DefRegs.push_back(R);
2846 }
2847
2848 MachineBasicBlock &B = *MI.getParent();
2849 const DebugLoc &DL = MI.getDebugLoc();
2850 unsigned ChangedNum = 0;
2851#ifndef NDEBUG
2852 SmallVector<const MachineInstr*,4> NewInstrs;
2853#endif
2854
2855 // For each defined register, if it is a constant, create an instruction
2856 // NewR = const
2857 // and replace all uses of the defined register with NewR.
2858 for (unsigned i = 0, n = DefRegs.size(); i < n; ++i) {
2859 unsigned R = DefRegs[i];
2860 const LatticeCell &L = Inputs.get(R);
2861 if (L.isBottom())
2862 continue;
2863 const TargetRegisterClass *RC = MRI->getRegClass(R);
2864 MachineBasicBlock::iterator At = MI.getIterator();
2865
2866 if (!L.isSingle()) {
2867 // If this a zero/non-zero cell, we can fold a definition
2868 // of a predicate register.
2869 typedef ConstantProperties P;
2870 uint64_t Ps = L.properties();
2871 if (!(Ps & (P::Zero|P::NonZero)))
2872 continue;
2873 const TargetRegisterClass *PredRC = &Hexagon::PredRegsRegClass;
2874 if (RC != PredRC)
2875 continue;
2876 const MCInstrDesc *NewD = (Ps & P::Zero) ?
2877 &HII.get(Hexagon::TFR_PdFalse) :
2878 &HII.get(Hexagon::TFR_PdTrue);
2879 unsigned NewR = MRI->createVirtualRegister(PredRC);
2880 const MachineInstrBuilder &MIB = BuildMI(B, At, DL, *NewD, NewR);
2881 (void)MIB;
2882#ifndef NDEBUG
2883 NewInstrs.push_back(&*MIB);
2884#endif
2885 replaceAllRegUsesWith(R, NewR);
2886 } else {
2887 // This cell has a single value.
2888 APInt A;
2889 if (!constToInt(L.Value, A) || !A.isSignedIntN(64))
2890 continue;
2891 const TargetRegisterClass *NewRC;
2892 const MCInstrDesc *NewD;
2893
2894 unsigned W = getRegBitWidth(R);
2895 int64_t V = A.getSExtValue();
2896 assert(W == 32 || W == 64);
2897 if (W == 32)
2898 NewRC = &Hexagon::IntRegsRegClass;
2899 else
2900 NewRC = &Hexagon::DoubleRegsRegClass;
2901 unsigned NewR = MRI->createVirtualRegister(NewRC);
2902 const MachineInstr *NewMI;
2903
2904 if (W == 32) {
2905 NewD = &HII.get(Hexagon::A2_tfrsi);
2906 NewMI = BuildMI(B, At, DL, *NewD, NewR)
2907 .addImm(V);
2908 } else {
2909 if (A.isSignedIntN(8)) {
2910 NewD = &HII.get(Hexagon::A2_tfrpi);
2911 NewMI = BuildMI(B, At, DL, *NewD, NewR)
2912 .addImm(V);
2913 } else {
2914 int32_t Hi = V >> 32;
2915 int32_t Lo = V & 0xFFFFFFFFLL;
2916 if (isInt<8>(Hi) && isInt<8>(Lo)) {
2917 NewD = &HII.get(Hexagon::A2_combineii);
2918 NewMI = BuildMI(B, At, DL, *NewD, NewR)
2919 .addImm(Hi)
2920 .addImm(Lo);
2921 } else {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +00002922 NewD = &HII.get(Hexagon::CONST64);
Krzysztof Parzyszek167d9182016-07-28 20:01:59 +00002923 NewMI = BuildMI(B, At, DL, *NewD, NewR)
2924 .addImm(V);
2925 }
2926 }
2927 }
2928 (void)NewMI;
2929#ifndef NDEBUG
2930 NewInstrs.push_back(NewMI);
2931#endif
2932 replaceAllRegUsesWith(R, NewR);
2933 }
2934 ChangedNum++;
2935 }
2936
2937 DEBUG({
2938 if (!NewInstrs.empty()) {
2939 MachineFunction &MF = *MI.getParent()->getParent();
2940 dbgs() << "In function: " << MF.getFunction()->getName() << "\n";
2941 dbgs() << "Rewrite: for " << MI << " created " << *NewInstrs[0];
2942 for (unsigned i = 1; i < NewInstrs.size(); ++i)
2943 dbgs() << " " << *NewInstrs[i];
2944 }
2945 });
2946
2947 AllDefs = (ChangedNum == DefRegs.size());
2948 return ChangedNum > 0;
2949}
2950
2951
2952bool HexagonConstEvaluator::rewriteHexConstUses(MachineInstr &MI,
2953 const CellMap &Inputs) {
2954 bool Changed = false;
2955 unsigned Opc = MI.getOpcode();
2956 MachineBasicBlock &B = *MI.getParent();
2957 const DebugLoc &DL = MI.getDebugLoc();
2958 MachineBasicBlock::iterator At = MI.getIterator();
2959 MachineInstr *NewMI = NULL;
2960
2961 switch (Opc) {
2962 case Hexagon::M2_maci:
2963 // Convert DefR += mpyi(R2, R3)
2964 // to DefR += mpyi(R, #imm),
2965 // or DefR -= mpyi(R, #imm).
2966 {
2967 Register DefR(MI.getOperand(0));
2968 assert(!DefR.SubReg);
2969 Register R2(MI.getOperand(2));
2970 Register R3(MI.getOperand(3));
2971 assert(Inputs.has(R2.Reg) && Inputs.has(R3.Reg));
2972 LatticeCell LS2, LS3;
2973 // It is enough to get one of the input cells, since we will only try
2974 // to replace one argument---whichever happens to be a single constant.
2975 bool HasC2 = getCell(R2, Inputs, LS2), HasC3 = getCell(R3, Inputs, LS3);
2976 if (!HasC2 && !HasC3)
2977 return false;
2978 bool Zero = ((HasC2 && (LS2.properties() & ConstantProperties::Zero)) ||
2979 (HasC3 && (LS3.properties() & ConstantProperties::Zero)));
2980 // If one of the operands is zero, eliminate the multiplication.
2981 if (Zero) {
2982 // DefR == R1 (tied operands).
2983 MachineOperand &Acc = MI.getOperand(1);
2984 Register R1(Acc);
2985 unsigned NewR = R1.Reg;
2986 if (R1.SubReg) {
2987 // Generate COPY. FIXME: Replace with the register:subregister.
2988 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg);
2989 NewR = MRI->createVirtualRegister(RC);
2990 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
2991 .addReg(R1.Reg, getRegState(Acc), R1.SubReg);
2992 }
2993 replaceAllRegUsesWith(DefR.Reg, NewR);
2994 MRI->clearKillFlags(NewR);
2995 Changed = true;
2996 break;
2997 }
2998
2999 bool Swap = false;
3000 if (!LS3.isSingle()) {
3001 if (!LS2.isSingle())
3002 return false;
3003 Swap = true;
3004 }
3005 const LatticeCell &LI = Swap ? LS2 : LS3;
3006 const MachineOperand &OpR2 = Swap ? MI.getOperand(3)
3007 : MI.getOperand(2);
3008 // LI is single here.
3009 APInt A;
3010 if (!constToInt(LI.Value, A) || !A.isSignedIntN(8))
3011 return false;
3012 int64_t V = A.getSExtValue();
3013 const MCInstrDesc &D = (V >= 0) ? HII.get(Hexagon::M2_macsip)
3014 : HII.get(Hexagon::M2_macsin);
3015 if (V < 0)
3016 V = -V;
3017 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg);
3018 unsigned NewR = MRI->createVirtualRegister(RC);
3019 const MachineOperand &Src1 = MI.getOperand(1);
3020 NewMI = BuildMI(B, At, DL, D, NewR)
3021 .addReg(Src1.getReg(), getRegState(Src1), Src1.getSubReg())
3022 .addReg(OpR2.getReg(), getRegState(OpR2), OpR2.getSubReg())
3023 .addImm(V);
3024 replaceAllRegUsesWith(DefR.Reg, NewR);
3025 Changed = true;
3026 break;
3027 }
3028
3029 case Hexagon::A2_and:
3030 {
3031 Register R1(MI.getOperand(1));
3032 Register R2(MI.getOperand(2));
3033 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
3034 LatticeCell LS1, LS2;
3035 unsigned CopyOf = 0;
3036 // Check if any of the operands is -1 (i.e. all bits set).
3037 if (getCell(R1, Inputs, LS1) && LS1.isSingle()) {
3038 APInt M1;
3039 if (constToInt(LS1.Value, M1) && !~M1)
3040 CopyOf = 2;
3041 }
3042 else if (getCell(R2, Inputs, LS2) && LS2.isSingle()) {
3043 APInt M1;
3044 if (constToInt(LS2.Value, M1) && !~M1)
3045 CopyOf = 1;
3046 }
3047 if (!CopyOf)
3048 return false;
3049 MachineOperand &SO = MI.getOperand(CopyOf);
3050 Register SR(SO);
3051 Register DefR(MI.getOperand(0));
3052 unsigned NewR = SR.Reg;
3053 if (SR.SubReg) {
3054 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg);
3055 NewR = MRI->createVirtualRegister(RC);
3056 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
3057 .addReg(SR.Reg, getRegState(SO), SR.SubReg);
3058 }
3059 replaceAllRegUsesWith(DefR.Reg, NewR);
3060 MRI->clearKillFlags(NewR);
3061 Changed = true;
3062 }
3063 break;
3064
3065 case Hexagon::A2_or:
3066 {
3067 Register R1(MI.getOperand(1));
3068 Register R2(MI.getOperand(2));
3069 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg));
3070 LatticeCell LS1, LS2;
3071 unsigned CopyOf = 0;
3072 typedef ConstantProperties P;
3073 if (getCell(R1, Inputs, LS1) && (LS1.properties() & P::Zero))
3074 CopyOf = 2;
3075 else if (getCell(R2, Inputs, LS2) && (LS2.properties() & P::Zero))
3076 CopyOf = 1;
3077 if (!CopyOf)
3078 return false;
3079 MachineOperand &SO = MI.getOperand(CopyOf);
3080 Register SR(SO);
3081 Register DefR(MI.getOperand(0));
3082 unsigned NewR = SR.Reg;
3083 if (SR.SubReg) {
3084 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg);
3085 NewR = MRI->createVirtualRegister(RC);
3086 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR)
3087 .addReg(SR.Reg, getRegState(SO), SR.SubReg);
3088 }
3089 replaceAllRegUsesWith(DefR.Reg, NewR);
3090 MRI->clearKillFlags(NewR);
3091 Changed = true;
3092 }
3093 break;
3094 }
3095
3096 if (NewMI) {
3097 // clear all the kill flags of this new instruction.
3098 for (MachineOperand &MO : NewMI->operands())
3099 if (MO.isReg() && MO.isUse())
3100 MO.setIsKill(false);
3101 }
3102
3103 DEBUG({
3104 if (NewMI) {
3105 dbgs() << "Rewrite: for " << MI;
3106 if (NewMI != &MI)
3107 dbgs() << " created " << *NewMI;
3108 else
3109 dbgs() << " modified the instruction itself and created:" << *NewMI;
3110 }
3111 });
3112
3113 return Changed;
3114}
3115
3116
3117void HexagonConstEvaluator::replaceAllRegUsesWith(unsigned FromReg,
3118 unsigned ToReg) {
3119 assert(TargetRegisterInfo::isVirtualRegister(FromReg));
3120 assert(TargetRegisterInfo::isVirtualRegister(ToReg));
3121 for (auto I = MRI->use_begin(FromReg), E = MRI->use_end(); I != E;) {
3122 MachineOperand &O = *I;
3123 ++I;
3124 O.setReg(ToReg);
3125 }
3126}
3127
3128
3129bool HexagonConstEvaluator::rewriteHexBranch(MachineInstr &BrI,
3130 const CellMap &Inputs) {
3131 MachineBasicBlock &B = *BrI.getParent();
3132 unsigned NumOp = BrI.getNumOperands();
3133 if (!NumOp)
3134 return false;
3135
3136 bool FallsThru;
3137 SetVector<const MachineBasicBlock*> Targets;
3138 bool Eval = evaluate(BrI, Inputs, Targets, FallsThru);
3139 unsigned NumTargets = Targets.size();
3140 if (!Eval || NumTargets > 1 || (NumTargets == 1 && FallsThru))
3141 return false;
3142 if (BrI.getOpcode() == Hexagon::J2_jump)
3143 return false;
3144
3145 DEBUG(dbgs() << "Rewrite(BB#" << B.getNumber() << "):" << BrI);
3146 bool Rewritten = false;
3147 if (NumTargets > 0) {
3148 assert(!FallsThru && "This should have been checked before");
3149 // MIB.addMBB needs non-const pointer.
3150 MachineBasicBlock *TargetB = const_cast<MachineBasicBlock*>(Targets[0]);
3151 bool Moot = B.isLayoutSuccessor(TargetB);
3152 if (!Moot) {
3153 // If we build a branch here, we must make sure that it won't be
3154 // erased as "non-executable". We can't mark any new instructions
3155 // as executable here, so we need to overwrite the BrI, which we
3156 // know is executable.
3157 const MCInstrDesc &JD = HII.get(Hexagon::J2_jump);
3158 auto NI = BuildMI(B, BrI.getIterator(), BrI.getDebugLoc(), JD)
3159 .addMBB(TargetB);
3160 BrI.setDesc(JD);
3161 while (BrI.getNumOperands() > 0)
3162 BrI.RemoveOperand(0);
3163 // This ensures that all implicit operands (e.g. %R31<imp-def>, etc)
3164 // are present in the rewritten branch.
3165 for (auto &Op : NI->operands())
3166 BrI.addOperand(Op);
3167 NI->eraseFromParent();
3168 Rewritten = true;
3169 }
3170 }
3171
3172 // Do not erase instructions. A newly created instruction could get
3173 // the same address as an instruction marked as executable during the
3174 // propagation.
3175 if (!Rewritten)
3176 replaceWithNop(BrI);
3177 return true;
3178}
3179
3180
3181// --------------------------------------------------------------------
3182FunctionPass *llvm::createHexagonConstPropagationPass() {
3183 return new HexagonConstPropagation();
3184}
3185