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