blob: 8b024fad4f86295407fd1765bddb29dbe769c0d4 [file] [log] [blame]
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001//===- HexagonConstExtenders.cpp ------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "HexagonInstrInfo.h"
11#include "HexagonRegisterInfo.h"
12#include "HexagonSubtarget.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/CodeGen/MachineDominators.h"
15#include "llvm/CodeGen/MachineFunctionPass.h"
16#include "llvm/CodeGen/MachineInstrBuilder.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/Pass.h"
21#include <map>
22#include <set>
23#include <utility>
24#include <vector>
25
26#define DEBUG_TYPE "hexagon-cext-opt"
27
28using namespace llvm;
29
30static cl::opt<unsigned> CountThreshold("hexagon-cext-threshold",
31 cl::init(3), cl::Hidden, cl::ZeroOrMore,
32 cl::desc("Minimum number of extenders to trigger replacement"));
33
34static cl::opt<unsigned> ReplaceLimit("hexagon-cext-limit", cl::init(0),
35 cl::Hidden, cl::ZeroOrMore, cl::desc("Maximum number of replacements"));
36
37namespace llvm {
38 void initializeHexagonConstExtendersPass(PassRegistry&);
39 FunctionPass *createHexagonConstExtenders();
40}
41
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000042static int32_t adjustUp(int32_t V, uint8_t A, uint8_t O) {
43 assert(isPowerOf2_32(A));
44 int32_t U = (V & -A) + O;
45 return U >= V ? U : U+A;
46}
47
48static int32_t adjustDown(int32_t V, uint8_t A, uint8_t O) {
49 assert(isPowerOf2_32(A));
50 int32_t U = (V & -A) + O;
51 return U <= V ? U : U-A;
52}
53
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000054namespace {
55 struct OffsetRange {
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000056 // The range of values between Min and Max that are of form Align*N+Offset,
57 // for some integer N. Min and Max are required to be of that form as well,
58 // except in the case of an empty range.
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000059 int32_t Min = INT_MIN, Max = INT_MAX;
60 uint8_t Align = 1;
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000061 uint8_t Offset = 0;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000062
63 OffsetRange() = default;
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000064 OffsetRange(int32_t L, int32_t H, uint8_t A, uint8_t O = 0)
65 : Min(L), Max(H), Align(A), Offset(O) {}
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000066 OffsetRange &intersect(OffsetRange A) {
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000067 if (Align < A.Align)
68 std::swap(*this, A);
69
70 // Align >= A.Align.
71 if (Offset >= A.Offset && (Offset - A.Offset) % A.Align == 0) {
72 Min = adjustUp(std::max(Min, A.Min), Align, Offset);
73 Max = adjustDown(std::min(Max, A.Max), Align, Offset);
74 } else {
75 // Make an empty range.
76 Min = 0;
77 Max = -1;
78 }
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000079 // Canonicalize empty ranges.
80 if (Min > Max)
81 std::tie(Min, Max, Align) = std::make_tuple(0, -1, 1);
82 return *this;
83 }
84 OffsetRange &shift(int32_t S) {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000085 Min += S;
86 Max += S;
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000087 Offset = (Offset+S) % Align;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000088 return *this;
89 }
90 OffsetRange &extendBy(int32_t D) {
91 // If D < 0, extend Min, otherwise extend Max.
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +000092 assert(D % Align == 0);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +000093 if (D < 0)
94 Min = (INT_MIN-D < Min) ? Min+D : INT_MIN;
95 else
96 Max = (INT_MAX-D > Max) ? Max+D : INT_MAX;
97 return *this;
98 }
99 bool empty() const {
100 return Min > Max;
101 }
102 bool contains(int32_t V) const {
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +0000103 return Min <= V && V <= Max && (V-Offset) % Align == 0;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000104 }
105 bool operator==(const OffsetRange &R) const {
106 return Min == R.Min && Max == R.Max && Align == R.Align;
107 }
108 bool operator!=(const OffsetRange &R) const {
109 return !operator==(R);
110 }
111 bool operator<(const OffsetRange &R) const {
112 if (Min != R.Min)
113 return Min < R.Min;
114 if (Max != R.Max)
115 return Max < R.Max;
116 return Align < R.Align;
117 }
118 static OffsetRange zero() { return {0, 0, 1}; }
119 };
120
121 struct RangeTree {
122 struct Node {
123 Node(const OffsetRange &R) : MaxEnd(R.Max), Range(R) {}
124 unsigned Height = 1;
125 unsigned Count = 1;
126 int32_t MaxEnd;
127 const OffsetRange &Range;
128 Node *Left = nullptr, *Right = nullptr;
129 };
130
131 Node *Root = nullptr;
132
133 void add(const OffsetRange &R) {
134 Root = add(Root, R);
135 }
136 void erase(const Node *N) {
137 Root = remove(Root, N);
138 delete N;
139 }
140 void order(SmallVectorImpl<Node*> &Seq) const {
141 order(Root, Seq);
142 }
143 SmallVector<Node*,8> nodesWith(int32_t P, bool CheckAlign = true) {
144 SmallVector<Node*,8> Nodes;
145 nodesWith(Root, P, CheckAlign, Nodes);
146 return Nodes;
147 }
148 void dump() const;
149 ~RangeTree() {
150 SmallVector<Node*,8> Nodes;
151 order(Nodes);
152 for (Node *N : Nodes)
153 delete N;
154 }
155
156 private:
157 void dump(const Node *N) const;
158 void order(Node *N, SmallVectorImpl<Node*> &Seq) const;
159 void nodesWith(Node *N, int32_t P, bool CheckA,
160 SmallVectorImpl<Node*> &Seq) const;
161
162 Node *add(Node *N, const OffsetRange &R);
163 Node *remove(Node *N, const Node *D);
164 Node *rotateLeft(Node *Lower, Node *Higher);
165 Node *rotateRight(Node *Lower, Node *Higher);
166 unsigned height(Node *N) {
167 return N != nullptr ? N->Height : 0;
168 }
169 Node *update(Node *N) {
170 assert(N != nullptr);
171 N->Height = 1 + std::max(height(N->Left), height(N->Right));
172 if (N->Left)
173 N->MaxEnd = std::max(N->MaxEnd, N->Left->MaxEnd);
174 if (N->Right)
175 N->MaxEnd = std::max(N->MaxEnd, N->Right->MaxEnd);
176 return N;
177 }
178 Node *rebalance(Node *N) {
179 assert(N != nullptr);
180 int32_t Balance = height(N->Right) - height(N->Left);
181 if (Balance < -1)
182 return rotateRight(N->Left, N);
183 if (Balance > 1)
184 return rotateLeft(N->Right, N);
185 return N;
186 }
187 };
188
189 struct Loc {
190 MachineBasicBlock *Block = nullptr;
191 MachineBasicBlock::iterator At;
192
193 Loc(MachineBasicBlock *B, MachineBasicBlock::iterator It)
194 : Block(B), At(It) {
195 if (B->end() == It) {
196 Pos = -1;
197 } else {
198 assert(It->getParent() == B);
199 Pos = std::distance(B->begin(), It);
200 }
201 }
202 bool operator<(Loc A) const {
203 if (Block != A.Block)
204 return Block->getNumber() < A.Block->getNumber();
205 if (A.Pos == -1)
206 return Pos != A.Pos;
207 return Pos != -1 && Pos < A.Pos;
208 }
209 private:
210 int Pos = 0;
211 };
212
213 struct HexagonConstExtenders : public MachineFunctionPass {
214 static char ID;
215 HexagonConstExtenders() : MachineFunctionPass(ID) {}
216
217 void getAnalysisUsage(AnalysisUsage &AU) const override {
218 AU.addRequired<MachineDominatorTree>();
219 AU.addPreserved<MachineDominatorTree>();
220 MachineFunctionPass::getAnalysisUsage(AU);
221 }
222
223 StringRef getPassName() const override {
224 return "Hexagon constant-extender optimization";
225 }
226 bool runOnMachineFunction(MachineFunction &MF) override;
227
228 private:
229 struct Register {
230 Register() = default;
231 Register(unsigned R, unsigned S) : Reg(R), Sub(S) {}
232 Register(const MachineOperand &Op)
233 : Reg(Op.getReg()), Sub(Op.getSubReg()) {}
234 Register &operator=(const MachineOperand &Op) {
235 if (Op.isReg()) {
236 Reg = Op.getReg();
237 Sub = Op.getSubReg();
238 } else if (Op.isFI()) {
239 Reg = TargetRegisterInfo::index2StackSlot(Op.getIndex());
240 }
241 return *this;
242 }
243 bool isVReg() const {
244 return Reg != 0 && !TargetRegisterInfo::isStackSlot(Reg) &&
245 TargetRegisterInfo::isVirtualRegister(Reg);
246 }
247 bool isSlot() const {
248 return Reg != 0 && TargetRegisterInfo::isStackSlot(Reg);
249 }
250 operator MachineOperand() const {
251 if (isVReg())
252 return MachineOperand::CreateReg(Reg, /*Def*/false, /*Imp*/false,
253 /*Kill*/false, /*Dead*/false, /*Undef*/false,
254 /*EarlyClobber*/false, Sub);
255 if (TargetRegisterInfo::isStackSlot(Reg)) {
256 int FI = TargetRegisterInfo::stackSlot2Index(Reg);
257 return MachineOperand::CreateFI(FI);
258 }
259 llvm_unreachable("Cannot create MachineOperand");
260 }
261 bool operator==(Register R) const { return Reg == R.Reg && Sub == R.Sub; }
262 bool operator!=(Register R) const { return !operator==(R); }
263 bool operator<(Register R) const {
264 // For std::map.
265 return Reg < R.Reg || (Reg == R.Reg && Sub < R.Sub);
266 }
267 unsigned Reg = 0, Sub = 0;
268 };
269
270 struct ExtExpr {
271 // A subexpression in which the extender is used. In general, this
272 // represents an expression where adding D to the extender will be
273 // equivalent to adding D to the expression as a whole. In other
274 // words, expr(add(##V,D) = add(expr(##V),D).
275
276 // The original motivation for this are the io/ur addressing modes,
277 // where the offset is extended. Consider the io example:
278 // In memw(Rs+##V), the ##V could be replaced by a register Rt to
279 // form the rr mode: memw(Rt+Rs<<0). In such case, however, the
280 // register Rt must have exactly the value of ##V. If there was
281 // another instruction memw(Rs+##V+4), it would need a different Rt.
282 // Now, if Rt was initialized as "##V+Rs<<0", both of these
283 // instructions could use the same Rt, just with different offsets.
284 // Here it's clear that "initializer+4" should be the same as if
285 // the offset 4 was added to the ##V in the initializer.
286
287 // The only kinds of expressions that support the requirement of
288 // commuting with addition are addition and subtraction from ##V.
289 // Include shifting the Rs to account for the ur addressing mode:
290 // ##Val + Rs << S
291 // ##Val - Rs
292 Register Rs;
293 unsigned S = 0;
294 bool Neg = false;
295
296 ExtExpr() = default;
297 ExtExpr(Register RS, bool NG, unsigned SH) : Rs(RS), S(SH), Neg(NG) {}
298 // Expression is trivial if it does not modify the extender.
299 bool trivial() const {
300 return Rs.Reg == 0;
301 }
302 bool operator==(const ExtExpr &Ex) const {
303 return Rs == Ex.Rs && S == Ex.S && Neg == Ex.Neg;
304 }
305 bool operator!=(const ExtExpr &Ex) const {
306 return !operator==(Ex);
307 }
308 bool operator<(const ExtExpr &Ex) const {
309 if (Rs != Ex.Rs)
310 return Rs < Ex.Rs;
311 if (S != Ex.S)
312 return S < Ex.S;
313 return !Neg && Ex.Neg;
314 }
315 };
316
317 struct ExtDesc {
318 MachineInstr *UseMI = nullptr;
319 unsigned OpNum = -1u;
320 // The subexpression in which the extender is used (e.g. address
321 // computation).
322 ExtExpr Expr;
323 // Optional register that is assigned the value of Expr.
324 Register Rd;
325 // Def means that the output of the instruction may differ from the
326 // original by a constant c, and that the difference can be corrected
327 // by adding/subtracting c in all users of the defined register.
328 bool IsDef = false;
329
330 MachineOperand &getOp() {
331 return UseMI->getOperand(OpNum);
332 }
333 const MachineOperand &getOp() const {
334 return UseMI->getOperand(OpNum);
335 }
336 };
337
338 struct ExtRoot {
339 union {
340 const ConstantFP *CFP; // MO_FPImmediate
341 const char *SymbolName; // MO_ExternalSymbol
342 const GlobalValue *GV; // MO_GlobalAddress
343 const BlockAddress *BA; // MO_BlockAddress
344 int64_t ImmVal; // MO_Immediate, MO_TargetIndex,
345 // and MO_ConstantPoolIndex
346 } V;
347 unsigned Kind; // Same as in MachineOperand.
348 unsigned char TF; // TargetFlags.
349
350 ExtRoot(const MachineOperand &Op);
351 bool operator==(const ExtRoot &ER) const {
352 return Kind == ER.Kind && V.ImmVal == ER.V.ImmVal;
353 }
354 bool operator!=(const ExtRoot &ER) const {
355 return !operator==(ER);
356 }
357 bool operator<(const ExtRoot &ER) const;
358 };
359
360 struct ExtValue : public ExtRoot {
361 int32_t Offset;
362
363 ExtValue(const MachineOperand &Op);
364 ExtValue(const ExtDesc &ED) : ExtValue(ED.getOp()) {}
365 ExtValue(const ExtRoot &ER, int32_t Off) : ExtRoot(ER), Offset(Off) {}
366 bool operator<(const ExtValue &EV) const;
367 bool operator==(const ExtValue &EV) const {
368 return ExtRoot(*this) == ExtRoot(EV) && Offset == EV.Offset;
369 }
370 bool operator!=(const ExtValue &EV) const {
371 return !operator==(EV);
372 }
373 explicit operator MachineOperand() const;
374 };
375
376 using IndexList = SetVector<unsigned>;
377 using ExtenderInit = std::pair<ExtValue, ExtExpr>;
378 using AssignmentMap = std::map<ExtenderInit, IndexList>;
379 using LocDefMap = std::map<Loc, IndexList>;
380
381 const HexagonInstrInfo *HII = nullptr;
382 const HexagonRegisterInfo *HRI = nullptr;
383 MachineDominatorTree *MDT = nullptr;
384 MachineRegisterInfo *MRI = nullptr;
385 std::vector<ExtDesc> Extenders;
386 std::vector<unsigned> NewRegs;
387
388 bool isStoreImmediate(unsigned Opc) const;
389 bool isRegOffOpcode(unsigned ExtOpc) const ;
390 unsigned getRegOffOpcode(unsigned ExtOpc) const;
391 unsigned getDirectRegReplacement(unsigned ExtOpc) const;
392 OffsetRange getOffsetRange(Register R, const MachineInstr &MI) const;
393 OffsetRange getOffsetRange(const ExtDesc &ED) const;
394 OffsetRange getOffsetRange(Register Rd) const;
395
396 void recordExtender(MachineInstr &MI, unsigned OpNum);
397 void collectInstr(MachineInstr &MI);
398 void collect(MachineFunction &MF);
399 void assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
400 AssignmentMap &IMap);
401 void calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
402 LocDefMap &Defs);
403 Register insertInitializer(Loc DefL, const ExtenderInit &ExtI);
404 bool replaceInstrExact(const ExtDesc &ED, Register ExtR);
405 bool replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
406 Register ExtR, int32_t &Diff);
407 bool replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI);
408 bool replaceExtenders(const AssignmentMap &IMap);
409
410 unsigned getOperandIndex(const MachineInstr &MI,
411 const MachineOperand &Op) const;
412 const MachineOperand &getPredicateOp(const MachineInstr &MI) const;
413 const MachineOperand &getLoadResultOp(const MachineInstr &MI) const;
414 const MachineOperand &getStoredValueOp(const MachineInstr &MI) const;
415
416 friend struct PrintRegister;
417 friend struct PrintExpr;
418 friend struct PrintInit;
419 friend struct PrintIMap;
420 friend raw_ostream &operator<< (raw_ostream &OS,
421 const struct PrintRegister &P);
422 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintExpr &P);
423 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintInit &P);
424 friend raw_ostream &operator<< (raw_ostream &OS, const ExtDesc &ED);
425 friend raw_ostream &operator<< (raw_ostream &OS, const ExtRoot &ER);
426 friend raw_ostream &operator<< (raw_ostream &OS, const ExtValue &EV);
427 friend raw_ostream &operator<< (raw_ostream &OS, const OffsetRange &OR);
428 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintIMap &P);
429 };
430
431 using HCE = HexagonConstExtenders;
432
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000433 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000434 raw_ostream &operator<< (raw_ostream &OS, const OffsetRange &OR) {
435 if (OR.Min > OR.Max)
436 OS << '!';
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +0000437 OS << '[' << OR.Min << ',' << OR.Max << "]a" << unsigned(OR.Align)
438 << '+' << unsigned(OR.Offset);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000439 return OS;
440 }
441
442 struct PrintRegister {
443 PrintRegister(HCE::Register R, const HexagonRegisterInfo &I)
444 : Rs(R), HRI(I) {}
445 HCE::Register Rs;
446 const HexagonRegisterInfo &HRI;
447 };
448
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000449 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000450 raw_ostream &operator<< (raw_ostream &OS, const PrintRegister &P) {
451 if (P.Rs.Reg != 0)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000452 OS << printReg(P.Rs.Reg, &P.HRI, P.Rs.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000453 else
454 OS << "noreg";
455 return OS;
456 }
457
458 struct PrintExpr {
459 PrintExpr(const HCE::ExtExpr &E, const HexagonRegisterInfo &I)
460 : Ex(E), HRI(I) {}
461 const HCE::ExtExpr &Ex;
462 const HexagonRegisterInfo &HRI;
463 };
464
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000465 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000466 raw_ostream &operator<< (raw_ostream &OS, const PrintExpr &P) {
467 OS << "## " << (P.Ex.Neg ? "- " : "+ ");
468 if (P.Ex.Rs.Reg != 0)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000469 OS << printReg(P.Ex.Rs.Reg, &P.HRI, P.Ex.Rs.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000470 else
471 OS << "__";
472 OS << " << " << P.Ex.S;
473 return OS;
474 }
475
476 struct PrintInit {
477 PrintInit(const HCE::ExtenderInit &EI, const HexagonRegisterInfo &I)
478 : ExtI(EI), HRI(I) {}
479 const HCE::ExtenderInit &ExtI;
480 const HexagonRegisterInfo &HRI;
481 };
482
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000483 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000484 raw_ostream &operator<< (raw_ostream &OS, const PrintInit &P) {
485 OS << '[' << P.ExtI.first << ", "
486 << PrintExpr(P.ExtI.second, P.HRI) << ']';
487 return OS;
488 }
489
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000490 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000491 raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtDesc &ED) {
492 assert(ED.OpNum != -1u);
493 const MachineBasicBlock &MBB = *ED.getOp().getParent()->getParent();
494 const MachineFunction &MF = *MBB.getParent();
495 const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
496 OS << "bb#" << MBB.getNumber() << ": ";
497 if (ED.Rd.Reg != 0)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000498 OS << printReg(ED.Rd.Reg, &HRI, ED.Rd.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000499 else
500 OS << "__";
501 OS << " = " << PrintExpr(ED.Expr, HRI);
502 if (ED.IsDef)
503 OS << ", def";
504 return OS;
505 }
506
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000507 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000508 raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtRoot &ER) {
509 switch (ER.Kind) {
510 case MachineOperand::MO_Immediate:
511 OS << "imm:" << ER.V.ImmVal;
512 break;
513 case MachineOperand::MO_FPImmediate:
514 OS << "fpi:" << *ER.V.CFP;
515 break;
516 case MachineOperand::MO_ExternalSymbol:
517 OS << "sym:" << *ER.V.SymbolName;
518 break;
519 case MachineOperand::MO_GlobalAddress:
520 OS << "gad:" << ER.V.GV->getName();
521 break;
522 case MachineOperand::MO_BlockAddress:
523 OS << "blk:" << *ER.V.BA;
524 break;
525 case MachineOperand::MO_TargetIndex:
526 OS << "tgi:" << ER.V.ImmVal;
527 break;
528 case MachineOperand::MO_ConstantPoolIndex:
529 OS << "cpi:" << ER.V.ImmVal;
530 break;
531 case MachineOperand::MO_JumpTableIndex:
532 OS << "jti:" << ER.V.ImmVal;
533 break;
534 default:
535 OS << "???:" << ER.V.ImmVal;
536 break;
537 }
538 return OS;
539 }
540
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000541 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000542 raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtValue &EV) {
543 OS << HCE::ExtRoot(EV) << " off:" << EV.Offset;
544 return OS;
545 }
546
547 struct PrintIMap {
548 PrintIMap(const HCE::AssignmentMap &M, const HexagonRegisterInfo &I)
549 : IMap(M), HRI(I) {}
550 const HCE::AssignmentMap &IMap;
551 const HexagonRegisterInfo &HRI;
552 };
553
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000554 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000555 raw_ostream &operator<< (raw_ostream &OS, const PrintIMap &P) {
556 OS << "{\n";
557 for (const std::pair<HCE::ExtenderInit,HCE::IndexList> &Q : P.IMap) {
558 OS << " " << PrintInit(Q.first, P.HRI) << " -> {";
559 for (unsigned I : Q.second)
560 OS << ' ' << I;
561 OS << " }\n";
562 }
563 OS << "}\n";
564 return OS;
565 }
566}
567
568INITIALIZE_PASS_BEGIN(HexagonConstExtenders, "hexagon-cext-opt",
569 "Hexagon constant-extender optimization", false, false)
570INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
571INITIALIZE_PASS_END(HexagonConstExtenders, "hexagon-cext-opt",
572 "Hexagon constant-extender optimization", false, false)
573
574static unsigned ReplaceCounter = 0;
575
576char HCE::ID = 0;
577
Eric Christopher3148a1b2017-11-16 03:18:15 +0000578#ifndef NDEBUG
Davide Italiano76067582017-10-14 23:46:01 +0000579LLVM_DUMP_METHOD void RangeTree::dump() const {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000580 dbgs() << "Root: " << Root << '\n';
581 if (Root)
582 dump(Root);
583}
584
Eric Christopher3148a1b2017-11-16 03:18:15 +0000585LLVM_DUMP_METHOD void RangeTree::dump(const Node *N) const {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000586 dbgs() << "Node: " << N << '\n';
587 dbgs() << " Height: " << N->Height << '\n';
588 dbgs() << " Count: " << N->Count << '\n';
589 dbgs() << " MaxEnd: " << N->MaxEnd << '\n';
590 dbgs() << " Range: " << N->Range << '\n';
591 dbgs() << " Left: " << N->Left << '\n';
592 dbgs() << " Right: " << N->Right << "\n\n";
593
594 if (N->Left)
595 dump(N->Left);
596 if (N->Right)
597 dump(N->Right);
598}
Eric Christopher3148a1b2017-11-16 03:18:15 +0000599#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000600
601void RangeTree::order(Node *N, SmallVectorImpl<Node*> &Seq) const {
602 if (N == nullptr)
603 return;
604 order(N->Left, Seq);
605 Seq.push_back(N);
606 order(N->Right, Seq);
607}
608
609void RangeTree::nodesWith(Node *N, int32_t P, bool CheckA,
610 SmallVectorImpl<Node*> &Seq) const {
611 if (N == nullptr || N->MaxEnd < P)
612 return;
613 nodesWith(N->Left, P, CheckA, Seq);
614 if (N->Range.Min <= P) {
615 if ((CheckA && N->Range.contains(P)) || (!CheckA && P <= N->Range.Max))
616 Seq.push_back(N);
617 nodesWith(N->Right, P, CheckA, Seq);
618 }
619}
620
621RangeTree::Node *RangeTree::add(Node *N, const OffsetRange &R) {
622 if (N == nullptr)
623 return new Node(R);
624
625 if (N->Range == R) {
626 N->Count++;
627 return N;
628 }
629
630 if (R < N->Range)
631 N->Left = add(N->Left, R);
632 else
633 N->Right = add(N->Right, R);
634 return rebalance(update(N));
635}
636
637RangeTree::Node *RangeTree::remove(Node *N, const Node *D) {
638 assert(N != nullptr);
639
640 if (N != D) {
641 assert(N->Range != D->Range && "N and D should not be equal");
642 if (D->Range < N->Range)
643 N->Left = remove(N->Left, D);
644 else
645 N->Right = remove(N->Right, D);
646 return rebalance(update(N));
647 }
648
649 // We got to the node we need to remove. If any of its children are
650 // missing, simply replace it with the other child.
651 if (N->Left == nullptr || N->Right == nullptr)
652 return (N->Left == nullptr) ? N->Right : N->Left;
653
654 // Find the rightmost child of N->Left, remove it and plug it in place
655 // of N.
656 Node *M = N->Left;
657 while (M->Right)
658 M = M->Right;
659 M->Left = remove(N->Left, M);
660 M->Right = N->Right;
661 return rebalance(update(M));
662}
663
664RangeTree::Node *RangeTree::rotateLeft(Node *Lower, Node *Higher) {
665 assert(Higher->Right == Lower);
666 // The Lower node is on the right from Higher. Make sure that Lower's
667 // balance is greater to the right. Otherwise the rotation will create
668 // an unbalanced tree again.
669 if (height(Lower->Left) > height(Lower->Right))
670 Lower = rotateRight(Lower->Left, Lower);
671 assert(height(Lower->Left) <= height(Lower->Right));
672 Higher->Right = Lower->Left;
673 update(Higher);
674 Lower->Left = Higher;
675 update(Lower);
676 return Lower;
677}
678
679RangeTree::Node *RangeTree::rotateRight(Node *Lower, Node *Higher) {
680 assert(Higher->Left == Lower);
681 // The Lower node is on the left from Higher. Make sure that Lower's
682 // balance is greater to the left. Otherwise the rotation will create
683 // an unbalanced tree again.
684 if (height(Lower->Left) < height(Lower->Right))
685 Lower = rotateLeft(Lower->Right, Lower);
686 assert(height(Lower->Left) >= height(Lower->Right));
687 Higher->Left = Lower->Right;
688 update(Higher);
689 Lower->Right = Higher;
690 update(Lower);
691 return Lower;
692}
693
694
695HCE::ExtRoot::ExtRoot(const MachineOperand &Op) {
696 // Always store ImmVal, since it's the field used for comparisons.
697 V.ImmVal = 0;
698 if (Op.isImm())
699 ; // Keep 0. Do not use Op.getImm() for value here (treat 0 as the root).
700 else if (Op.isFPImm())
701 V.CFP = Op.getFPImm();
702 else if (Op.isSymbol())
703 V.SymbolName = Op.getSymbolName();
704 else if (Op.isGlobal())
705 V.GV = Op.getGlobal();
706 else if (Op.isBlockAddress())
707 V.BA = Op.getBlockAddress();
708 else if (Op.isCPI() || Op.isTargetIndex() || Op.isJTI())
709 V.ImmVal = Op.getIndex();
710 else
711 llvm_unreachable("Unexpected operand type");
712
713 Kind = Op.getType();
714 TF = Op.getTargetFlags();
715}
716
717bool HCE::ExtRoot::operator< (const HCE::ExtRoot &ER) const {
718 if (Kind != ER.Kind)
719 return Kind < ER.Kind;
720 switch (Kind) {
721 case MachineOperand::MO_Immediate:
722 case MachineOperand::MO_TargetIndex:
723 case MachineOperand::MO_ConstantPoolIndex:
724 case MachineOperand::MO_JumpTableIndex:
725 return V.ImmVal < ER.V.ImmVal;
726 case MachineOperand::MO_FPImmediate: {
727 const APFloat &ThisF = V.CFP->getValueAPF();
728 const APFloat &OtherF = ER.V.CFP->getValueAPF();
729 return ThisF.bitcastToAPInt().ult(OtherF.bitcastToAPInt());
730 }
731 case MachineOperand::MO_ExternalSymbol:
732 return StringRef(V.SymbolName) < StringRef(ER.V.SymbolName);
733 case MachineOperand::MO_GlobalAddress:
734 assert(V.GV->hasName() && ER.V.GV->hasName());
735 return V.GV->getName() < ER.V.GV->getName();
736 case MachineOperand::MO_BlockAddress: {
737 const BasicBlock *ThisB = V.BA->getBasicBlock();
738 const BasicBlock *OtherB = ER.V.BA->getBasicBlock();
739 assert(ThisB->getParent() == OtherB->getParent());
740 const Function &F = *ThisB->getParent();
741 return std::distance(F.begin(), ThisB->getIterator()) <
742 std::distance(F.begin(), OtherB->getIterator());
743 }
744 }
745 return V.ImmVal < ER.V.ImmVal;
746}
747
748HCE::ExtValue::ExtValue(const MachineOperand &Op) : ExtRoot(Op) {
749 if (Op.isImm())
750 Offset = Op.getImm();
751 else if (Op.isFPImm() || Op.isJTI())
752 Offset = 0;
753 else if (Op.isSymbol() || Op.isGlobal() || Op.isBlockAddress() ||
754 Op.isCPI() || Op.isTargetIndex())
755 Offset = Op.getOffset();
756 else
757 llvm_unreachable("Unexpected operand type");
758}
759
760bool HCE::ExtValue::operator< (const HCE::ExtValue &EV) const {
761 const ExtRoot &ER = *this;
762 if (!(ER == ExtRoot(EV)))
763 return ER < EV;
764 return Offset < EV.Offset;
765}
766
767HCE::ExtValue::operator MachineOperand() const {
768 switch (Kind) {
769 case MachineOperand::MO_Immediate:
770 return MachineOperand::CreateImm(V.ImmVal + Offset);
771 case MachineOperand::MO_FPImmediate:
772 assert(Offset == 0);
773 return MachineOperand::CreateFPImm(V.CFP);
774 case MachineOperand::MO_ExternalSymbol:
775 assert(Offset == 0);
776 return MachineOperand::CreateES(V.SymbolName, TF);
777 case MachineOperand::MO_GlobalAddress:
778 return MachineOperand::CreateGA(V.GV, Offset, TF);
779 case MachineOperand::MO_BlockAddress:
780 return MachineOperand::CreateBA(V.BA, Offset, TF);
781 case MachineOperand::MO_TargetIndex:
782 return MachineOperand::CreateTargetIndex(V.ImmVal, Offset, TF);
783 case MachineOperand::MO_ConstantPoolIndex:
784 return MachineOperand::CreateCPI(V.ImmVal, Offset, TF);
785 case MachineOperand::MO_JumpTableIndex:
786 assert(Offset == 0);
787 default:
788 llvm_unreachable("Unhandled kind");
789 }
790}
791
792bool HCE::isStoreImmediate(unsigned Opc) const {
793 switch (Opc) {
794 case Hexagon::S4_storeirbt_io:
795 case Hexagon::S4_storeirbf_io:
796 case Hexagon::S4_storeirht_io:
797 case Hexagon::S4_storeirhf_io:
798 case Hexagon::S4_storeirit_io:
799 case Hexagon::S4_storeirif_io:
800 case Hexagon::S4_storeirb_io:
801 case Hexagon::S4_storeirh_io:
802 case Hexagon::S4_storeiri_io:
803 return true;
804 default:
805 break;
806 }
807 return false;
808}
809
810bool HCE::isRegOffOpcode(unsigned Opc) const {
811 switch (Opc) {
812 case Hexagon::L2_loadrub_io:
813 case Hexagon::L2_loadrb_io:
814 case Hexagon::L2_loadruh_io:
815 case Hexagon::L2_loadrh_io:
816 case Hexagon::L2_loadri_io:
817 case Hexagon::L2_loadrd_io:
818 case Hexagon::L2_loadbzw2_io:
819 case Hexagon::L2_loadbzw4_io:
820 case Hexagon::L2_loadbsw2_io:
821 case Hexagon::L2_loadbsw4_io:
822 case Hexagon::L2_loadalignh_io:
823 case Hexagon::L2_loadalignb_io:
824 case Hexagon::L2_ploadrubt_io:
825 case Hexagon::L2_ploadrubf_io:
826 case Hexagon::L2_ploadrbt_io:
827 case Hexagon::L2_ploadrbf_io:
828 case Hexagon::L2_ploadruht_io:
829 case Hexagon::L2_ploadruhf_io:
830 case Hexagon::L2_ploadrht_io:
831 case Hexagon::L2_ploadrhf_io:
832 case Hexagon::L2_ploadrit_io:
833 case Hexagon::L2_ploadrif_io:
834 case Hexagon::L2_ploadrdt_io:
835 case Hexagon::L2_ploadrdf_io:
836 case Hexagon::S2_storerb_io:
837 case Hexagon::S2_storerh_io:
838 case Hexagon::S2_storerf_io:
839 case Hexagon::S2_storeri_io:
840 case Hexagon::S2_storerd_io:
841 case Hexagon::S2_pstorerbt_io:
842 case Hexagon::S2_pstorerbf_io:
843 case Hexagon::S2_pstorerht_io:
844 case Hexagon::S2_pstorerhf_io:
845 case Hexagon::S2_pstorerft_io:
846 case Hexagon::S2_pstorerff_io:
847 case Hexagon::S2_pstorerit_io:
848 case Hexagon::S2_pstorerif_io:
849 case Hexagon::S2_pstorerdt_io:
850 case Hexagon::S2_pstorerdf_io:
851 case Hexagon::A2_addi:
852 return true;
853 default:
854 break;
855 }
856 return false;
857}
858
859unsigned HCE::getRegOffOpcode(unsigned ExtOpc) const {
860 // If there exists an instruction that takes a register and offset,
861 // that corresponds to the ExtOpc, return it, otherwise return 0.
862 using namespace Hexagon;
863 switch (ExtOpc) {
864 case A2_tfrsi: return A2_addi;
865 default:
866 break;
867 }
868 const MCInstrDesc &D = HII->get(ExtOpc);
869 if (D.mayLoad() || D.mayStore()) {
870 uint64_t F = D.TSFlags;
871 unsigned AM = (F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask;
872 switch (AM) {
873 case HexagonII::Absolute:
874 case HexagonII::AbsoluteSet:
875 case HexagonII::BaseLongOffset:
876 switch (ExtOpc) {
877 case PS_loadrubabs:
878 case L4_loadrub_ap:
879 case L4_loadrub_ur: return L2_loadrub_io;
880 case PS_loadrbabs:
881 case L4_loadrb_ap:
882 case L4_loadrb_ur: return L2_loadrb_io;
883 case PS_loadruhabs:
884 case L4_loadruh_ap:
885 case L4_loadruh_ur: return L2_loadruh_io;
886 case PS_loadrhabs:
887 case L4_loadrh_ap:
888 case L4_loadrh_ur: return L2_loadrh_io;
889 case PS_loadriabs:
890 case L4_loadri_ap:
891 case L4_loadri_ur: return L2_loadri_io;
892 case PS_loadrdabs:
893 case L4_loadrd_ap:
894 case L4_loadrd_ur: return L2_loadrd_io;
895 case L4_loadbzw2_ap:
896 case L4_loadbzw2_ur: return L2_loadbzw2_io;
897 case L4_loadbzw4_ap:
898 case L4_loadbzw4_ur: return L2_loadbzw4_io;
899 case L4_loadbsw2_ap:
900 case L4_loadbsw2_ur: return L2_loadbsw2_io;
901 case L4_loadbsw4_ap:
902 case L4_loadbsw4_ur: return L2_loadbsw4_io;
903 case L4_loadalignh_ap:
904 case L4_loadalignh_ur: return L2_loadalignh_io;
905 case L4_loadalignb_ap:
906 case L4_loadalignb_ur: return L2_loadalignb_io;
907 case L4_ploadrubt_abs: return L2_ploadrubt_io;
908 case L4_ploadrubf_abs: return L2_ploadrubf_io;
909 case L4_ploadrbt_abs: return L2_ploadrbt_io;
910 case L4_ploadrbf_abs: return L2_ploadrbf_io;
911 case L4_ploadruht_abs: return L2_ploadruht_io;
912 case L4_ploadruhf_abs: return L2_ploadruhf_io;
913 case L4_ploadrht_abs: return L2_ploadrht_io;
914 case L4_ploadrhf_abs: return L2_ploadrhf_io;
915 case L4_ploadrit_abs: return L2_ploadrit_io;
916 case L4_ploadrif_abs: return L2_ploadrif_io;
917 case L4_ploadrdt_abs: return L2_ploadrdt_io;
918 case L4_ploadrdf_abs: return L2_ploadrdf_io;
919 case PS_storerbabs:
920 case S4_storerb_ap:
921 case S4_storerb_ur: return S2_storerb_io;
922 case PS_storerhabs:
923 case S4_storerh_ap:
924 case S4_storerh_ur: return S2_storerh_io;
925 case PS_storerfabs:
926 case S4_storerf_ap:
927 case S4_storerf_ur: return S2_storerf_io;
928 case PS_storeriabs:
929 case S4_storeri_ap:
930 case S4_storeri_ur: return S2_storeri_io;
931 case PS_storerdabs:
932 case S4_storerd_ap:
933 case S4_storerd_ur: return S2_storerd_io;
934 case S4_pstorerbt_abs: return S2_pstorerbt_io;
935 case S4_pstorerbf_abs: return S2_pstorerbf_io;
936 case S4_pstorerht_abs: return S2_pstorerht_io;
937 case S4_pstorerhf_abs: return S2_pstorerhf_io;
938 case S4_pstorerft_abs: return S2_pstorerft_io;
939 case S4_pstorerff_abs: return S2_pstorerff_io;
940 case S4_pstorerit_abs: return S2_pstorerit_io;
941 case S4_pstorerif_abs: return S2_pstorerif_io;
942 case S4_pstorerdt_abs: return S2_pstorerdt_io;
943 case S4_pstorerdf_abs: return S2_pstorerdf_io;
944 default:
945 break;
946 }
947 break;
948 case HexagonII::BaseImmOffset:
949 if (!isStoreImmediate(ExtOpc))
950 return ExtOpc;
951 break;
952 default:
953 break;
954 }
955 }
956 return 0;
957}
958
959unsigned HCE::getDirectRegReplacement(unsigned ExtOpc) const {
960 switch (ExtOpc) {
961 case Hexagon::A2_addi: return Hexagon::A2_add;
962 case Hexagon::A2_andir: return Hexagon::A2_and;
963 case Hexagon::A2_combineii: return Hexagon::A4_combineri;
964 case Hexagon::A2_orir: return Hexagon::A2_or;
965 case Hexagon::A2_paddif: return Hexagon::A2_paddf;
966 case Hexagon::A2_paddit: return Hexagon::A2_paddt;
967 case Hexagon::A2_subri: return Hexagon::A2_sub;
968 case Hexagon::A2_tfrsi: return TargetOpcode::COPY;
969 case Hexagon::A4_cmpbeqi: return Hexagon::A4_cmpbeq;
970 case Hexagon::A4_cmpbgti: return Hexagon::A4_cmpbgt;
971 case Hexagon::A4_cmpbgtui: return Hexagon::A4_cmpbgtu;
972 case Hexagon::A4_cmpheqi: return Hexagon::A4_cmpheq;
973 case Hexagon::A4_cmphgti: return Hexagon::A4_cmphgt;
974 case Hexagon::A4_cmphgtui: return Hexagon::A4_cmphgtu;
975 case Hexagon::A4_combineii: return Hexagon::A4_combineir;
976 case Hexagon::A4_combineir: return TargetOpcode::REG_SEQUENCE;
977 case Hexagon::A4_combineri: return TargetOpcode::REG_SEQUENCE;
978 case Hexagon::A4_rcmpeqi: return Hexagon::A4_rcmpeq;
979 case Hexagon::A4_rcmpneqi: return Hexagon::A4_rcmpneq;
980 case Hexagon::C2_cmoveif: return Hexagon::A2_tfrpf;
981 case Hexagon::C2_cmoveit: return Hexagon::A2_tfrpt;
982 case Hexagon::C2_cmpeqi: return Hexagon::C2_cmpeq;
983 case Hexagon::C2_cmpgti: return Hexagon::C2_cmpgt;
984 case Hexagon::C2_cmpgtui: return Hexagon::C2_cmpgtu;
985 case Hexagon::C2_muxii: return Hexagon::C2_muxir;
986 case Hexagon::C2_muxir: return Hexagon::C2_mux;
987 case Hexagon::C2_muxri: return Hexagon::C2_mux;
988 case Hexagon::C4_cmpltei: return Hexagon::C4_cmplte;
989 case Hexagon::C4_cmplteui: return Hexagon::C4_cmplteu;
990 case Hexagon::C4_cmpneqi: return Hexagon::C4_cmpneq;
991 case Hexagon::M2_accii: return Hexagon::M2_acci; // T -> T
992 /* No M2_macsin */
993 case Hexagon::M2_macsip: return Hexagon::M2_maci; // T -> T
994 case Hexagon::M2_mpysin: return Hexagon::M2_mpyi;
995 case Hexagon::M2_mpysip: return Hexagon::M2_mpyi;
996 case Hexagon::M2_mpysmi: return Hexagon::M2_mpyi;
997 case Hexagon::M2_naccii: return Hexagon::M2_nacci; // T -> T
998 case Hexagon::M4_mpyri_addi: return Hexagon::M4_mpyri_addr;
999 case Hexagon::M4_mpyri_addr: return Hexagon::M4_mpyrr_addr; // _ -> T
1000 case Hexagon::M4_mpyrr_addi: return Hexagon::M4_mpyrr_addr; // _ -> T
1001 case Hexagon::S4_addaddi: return Hexagon::M2_acci; // _ -> T
1002 case Hexagon::S4_addi_asl_ri: return Hexagon::S2_asl_i_r_acc; // T -> T
1003 case Hexagon::S4_addi_lsr_ri: return Hexagon::S2_lsr_i_r_acc; // T -> T
1004 case Hexagon::S4_andi_asl_ri: return Hexagon::S2_asl_i_r_and; // T -> T
1005 case Hexagon::S4_andi_lsr_ri: return Hexagon::S2_lsr_i_r_and; // T -> T
1006 case Hexagon::S4_ori_asl_ri: return Hexagon::S2_asl_i_r_or; // T -> T
1007 case Hexagon::S4_ori_lsr_ri: return Hexagon::S2_lsr_i_r_or; // T -> T
1008 case Hexagon::S4_subaddi: return Hexagon::M2_subacc; // _ -> T
1009 case Hexagon::S4_subi_asl_ri: return Hexagon::S2_asl_i_r_nac; // T -> T
1010 case Hexagon::S4_subi_lsr_ri: return Hexagon::S2_lsr_i_r_nac; // T -> T
1011
1012 // Store-immediates:
1013 case Hexagon::S4_storeirbf_io: return Hexagon::S2_pstorerbf_io;
1014 case Hexagon::S4_storeirb_io: return Hexagon::S2_storerb_io;
1015 case Hexagon::S4_storeirbt_io: return Hexagon::S2_pstorerbt_io;
1016 case Hexagon::S4_storeirhf_io: return Hexagon::S2_pstorerhf_io;
1017 case Hexagon::S4_storeirh_io: return Hexagon::S2_storerh_io;
1018 case Hexagon::S4_storeirht_io: return Hexagon::S2_pstorerht_io;
1019 case Hexagon::S4_storeirif_io: return Hexagon::S2_pstorerif_io;
1020 case Hexagon::S4_storeiri_io: return Hexagon::S2_storeri_io;
1021 case Hexagon::S4_storeirit_io: return Hexagon::S2_pstorerit_io;
1022
1023 default:
1024 break;
1025 }
1026 return 0;
1027}
1028
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001029// Return the allowable deviation from the current value of Rb (i.e. the
1030// range of values that can be added to the current value) which the
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001031// instruction MI can accommodate.
1032// The instruction MI is a user of register Rb, which is defined via an
1033// extender. It may be possible for MI to be tweaked to work for a register
1034// defined with a slightly different value. For example
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001035// ... = L2_loadrub_io Rb, 1
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001036// can be modifed to be
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001037// ... = L2_loadrub_io Rb', 0
1038// if Rb' = Rb+1.
1039// The range for Rb would be [Min+1, Max+1], where [Min, Max] is a range
1040// for L2_loadrub with offset 0. That means that Rb could be replaced with
1041// Rc, where Rc-Rb belongs to [Min+1, Max+1].
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001042OffsetRange HCE::getOffsetRange(Register Rb, const MachineInstr &MI) const {
1043 unsigned Opc = MI.getOpcode();
1044 // Instructions that are constant-extended may be replaced with something
1045 // else that no longer offers the same range as the original.
1046 if (!isRegOffOpcode(Opc) || HII->isConstExtended(MI))
1047 return OffsetRange::zero();
1048
1049 if (Opc == Hexagon::A2_addi) {
1050 const MachineOperand &Op1 = MI.getOperand(1), &Op2 = MI.getOperand(2);
1051 if (Rb != Register(Op1) || !Op2.isImm())
1052 return OffsetRange::zero();
1053 OffsetRange R = { -(1<<15)+1, (1<<15)-1, 1 };
1054 return R.shift(Op2.getImm());
1055 }
1056
1057 // HII::getBaseAndOffsetPosition returns the increment position as "offset".
1058 if (HII->isPostIncrement(MI))
1059 return OffsetRange::zero();
1060
1061 const MCInstrDesc &D = HII->get(Opc);
1062 assert(D.mayLoad() || D.mayStore());
1063
1064 unsigned BaseP, OffP;
1065 if (!HII->getBaseAndOffsetPosition(MI, BaseP, OffP) ||
1066 Rb != Register(MI.getOperand(BaseP)) ||
1067 !MI.getOperand(OffP).isImm())
1068 return OffsetRange::zero();
1069
1070 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1071 HexagonII::MemAccesSizeMask;
1072 uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1073 unsigned L = Log2_32(A);
1074 unsigned S = 10+L; // sint11_L
1075 int32_t Min = -alignDown((1<<S)-1, A);
Krzysztof Parzyszek27056da2017-10-25 18:46:40 +00001076
1077 // The range will be shifted by Off. To prefer non-negative offsets,
1078 // adjust Max accordingly.
1079 int32_t Off = MI.getOperand(OffP).getImm();
1080 int32_t Max = Off >= 0 ? 0 : -Off;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001081
1082 OffsetRange R = { Min, Max, A };
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001083 return R.shift(Off);
1084}
1085
1086// Return the allowable deviation from the current value of the extender ED,
1087// for which the instruction corresponding to ED can be modified without
1088// using an extender.
1089// The instruction uses the extender directly. It will be replaced with
1090// another instruction, say MJ, where the extender will be replaced with a
1091// register. MJ can allow some variability with respect to the value of
1092// that register, as is the case with indexed memory instructions.
1093OffsetRange HCE::getOffsetRange(const ExtDesc &ED) const {
1094 // The only way that there can be a non-zero range available is if
1095 // the instruction using ED will be converted to an indexed memory
1096 // instruction.
1097 unsigned IdxOpc = getRegOffOpcode(ED.UseMI->getOpcode());
1098 switch (IdxOpc) {
1099 case 0:
1100 return OffsetRange::zero();
1101 case Hexagon::A2_addi: // s16
1102 return { -32767, 32767, 1 };
1103 case Hexagon::A2_subri: // s10
1104 return { -511, 511, 1 };
1105 }
1106
1107 if (!ED.UseMI->mayLoad() && !ED.UseMI->mayStore())
1108 return OffsetRange::zero();
1109 const MCInstrDesc &D = HII->get(IdxOpc);
1110 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1111 HexagonII::MemAccesSizeMask;
1112 uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1113 unsigned L = Log2_32(A);
1114 unsigned S = 10+L; // sint11_L
1115 int32_t Min = -alignDown((1<<S)-1, A);
1116 int32_t Max = 0; // Force non-negative offsets.
1117 return { Min, Max, A };
1118}
1119
1120// Get the allowable deviation from the current value of Rd by checking
1121// all uses of Rd.
1122OffsetRange HCE::getOffsetRange(Register Rd) const {
1123 OffsetRange Range;
1124 for (const MachineOperand &Op : MRI->use_operands(Rd.Reg)) {
1125 // Make sure that the register being used by this operand is identical
1126 // to the register that was defined: using a different subregister
1127 // precludes any non-trivial range.
1128 if (Rd != Register(Op))
1129 return OffsetRange::zero();
1130 Range.intersect(getOffsetRange(Rd, *Op.getParent()));
1131 }
1132 return Range;
1133}
1134
1135void HCE::recordExtender(MachineInstr &MI, unsigned OpNum) {
1136 unsigned Opc = MI.getOpcode();
1137 ExtDesc ED;
1138 ED.OpNum = OpNum;
1139
1140 bool IsLoad = MI.mayLoad();
1141 bool IsStore = MI.mayStore();
1142
Krzysztof Parzyszek64212012018-04-20 19:06:46 +00001143 // Fixed stack slots have negative indexes, and they cannot be used
1144 // with TRI::stackSlot2Index and TRI::index2StackSlot. This is somewhat
1145 // unfortunate, but should not be a frequent thing.
1146 for (MachineOperand &Op : MI.operands())
1147 if (Op.isFI() && Op.getIndex() < 0)
1148 return;
1149
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001150 if (IsLoad || IsStore) {
1151 unsigned AM = HII->getAddrMode(MI);
1152 switch (AM) {
1153 // (Re: ##Off + Rb<<S) = Rd: ##Val
1154 case HexagonII::Absolute: // (__: ## + __<<_)
1155 break;
1156 case HexagonII::AbsoluteSet: // (Rd: ## + __<<_)
1157 ED.Rd = MI.getOperand(OpNum-1);
1158 ED.IsDef = true;
1159 break;
1160 case HexagonII::BaseImmOffset: // (__: ## + Rs<<0)
1161 // Store-immediates are treated as non-memory operations, since
1162 // it's the value being stored that is extended (as opposed to
1163 // a part of the address).
1164 if (!isStoreImmediate(Opc))
1165 ED.Expr.Rs = MI.getOperand(OpNum-1);
1166 break;
1167 case HexagonII::BaseLongOffset: // (__: ## + Rs<<S)
1168 ED.Expr.Rs = MI.getOperand(OpNum-2);
1169 ED.Expr.S = MI.getOperand(OpNum-1).getImm();
1170 break;
1171 default:
1172 llvm_unreachable("Unhandled memory instruction");
1173 }
1174 } else {
1175 switch (Opc) {
1176 case Hexagon::A2_tfrsi: // (Rd: ## + __<<_)
1177 ED.Rd = MI.getOperand(0);
1178 ED.IsDef = true;
1179 break;
1180 case Hexagon::A2_combineii: // (Rd: ## + __<<_)
1181 case Hexagon::A4_combineir:
1182 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_hi };
1183 ED.IsDef = true;
1184 break;
1185 case Hexagon::A4_combineri: // (Rd: ## + __<<_)
1186 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_lo };
1187 ED.IsDef = true;
1188 break;
1189 case Hexagon::A2_addi: // (Rd: ## + Rs<<0)
1190 ED.Rd = MI.getOperand(0);
1191 ED.Expr.Rs = MI.getOperand(OpNum-1);
1192 break;
1193 case Hexagon::M2_accii: // (__: ## + Rs<<0)
1194 case Hexagon::M2_naccii:
1195 case Hexagon::S4_addaddi:
1196 ED.Expr.Rs = MI.getOperand(OpNum-1);
1197 break;
1198 case Hexagon::A2_subri: // (Rd: ## - Rs<<0)
1199 ED.Rd = MI.getOperand(0);
1200 ED.Expr.Rs = MI.getOperand(OpNum+1);
1201 ED.Expr.Neg = true;
1202 break;
1203 case Hexagon::S4_subaddi: // (__: ## - Rs<<0)
1204 ED.Expr.Rs = MI.getOperand(OpNum+1);
1205 ED.Expr.Neg = true;
1206 default: // (__: ## + __<<_)
1207 break;
1208 }
1209 }
1210
1211 ED.UseMI = &MI;
1212 Extenders.push_back(ED);
1213}
1214
1215void HCE::collectInstr(MachineInstr &MI) {
1216 if (!HII->isConstExtended(MI))
1217 return;
1218
1219 // Skip some non-convertible instructions.
1220 unsigned Opc = MI.getOpcode();
1221 switch (Opc) {
1222 case Hexagon::M2_macsin: // There is no Rx -= mpyi(Rs,Rt).
1223 case Hexagon::C4_addipc:
1224 case Hexagon::S4_or_andi:
1225 case Hexagon::S4_or_andix:
1226 case Hexagon::S4_or_ori:
1227 return;
1228 }
1229 recordExtender(MI, HII->getCExtOpNum(MI));
1230}
1231
1232void HCE::collect(MachineFunction &MF) {
1233 Extenders.clear();
1234 for (MachineBasicBlock &MBB : MF)
1235 for (MachineInstr &MI : MBB)
1236 collectInstr(MI);
1237}
1238
1239void HCE::assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
1240 AssignmentMap &IMap) {
1241 // Sanity check: make sure that all extenders in the range [Begin..End)
1242 // share the same root ER.
1243 for (unsigned I = Begin; I != End; ++I)
1244 assert(ER == ExtRoot(Extenders[I].getOp()));
1245
1246 // Construct the list of ranges, such that for each P in Ranges[I],
1247 // a register Reg = ER+P can be used in place of Extender[I]. If the
1248 // instruction allows, uses in the form of Reg+Off are considered
1249 // (here, Off = required_value - P).
1250 std::vector<OffsetRange> Ranges(End-Begin);
1251
1252 // For each extender that is a def, visit all uses of the defined register,
1253 // and produce an offset range that works for all uses. The def doesn't
1254 // have to be checked, because it can become dead if all uses can be updated
1255 // to use a different reg/offset.
1256 for (unsigned I = Begin; I != End; ++I) {
1257 const ExtDesc &ED = Extenders[I];
1258 if (!ED.IsDef)
1259 continue;
1260 ExtValue EV(ED);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001261 LLVM_DEBUG(dbgs() << " =" << I << ". " << EV << " " << ED << '\n');
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001262 assert(ED.Rd.Reg != 0);
1263 Ranges[I-Begin] = getOffsetRange(ED.Rd).shift(EV.Offset);
1264 // A2_tfrsi is a special case: it will be replaced with A2_addi, which
1265 // has a 16-bit signed offset. This means that A2_tfrsi not only has a
1266 // range coming from its uses, but also from the fact that its replacement
1267 // has a range as well.
1268 if (ED.UseMI->getOpcode() == Hexagon::A2_tfrsi) {
1269 int32_t D = alignDown(32767, Ranges[I-Begin].Align); // XXX hardcoded
1270 Ranges[I-Begin].extendBy(-D).extendBy(D);
1271 }
1272 }
1273
1274 // Visit all non-def extenders. For each one, determine the offset range
1275 // available for it.
1276 for (unsigned I = Begin; I != End; ++I) {
1277 const ExtDesc &ED = Extenders[I];
1278 if (ED.IsDef)
1279 continue;
1280 ExtValue EV(ED);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001281 LLVM_DEBUG(dbgs() << " " << I << ". " << EV << " " << ED << '\n');
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001282 OffsetRange Dev = getOffsetRange(ED);
1283 Ranges[I-Begin].intersect(Dev.shift(EV.Offset));
1284 }
1285
1286 // Here for each I there is a corresponding Range[I]. Construct the
1287 // inverse map, that to each range will assign the set of indexes in
1288 // [Begin..End) that this range corresponds to.
1289 std::map<OffsetRange, IndexList> RangeMap;
1290 for (unsigned I = Begin; I != End; ++I)
1291 RangeMap[Ranges[I-Begin]].insert(I);
1292
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001293 LLVM_DEBUG({
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001294 dbgs() << "Ranges\n";
1295 for (unsigned I = Begin; I != End; ++I)
1296 dbgs() << " " << I << ". " << Ranges[I-Begin] << '\n';
1297 dbgs() << "RangeMap\n";
1298 for (auto &P : RangeMap) {
1299 dbgs() << " " << P.first << " ->";
1300 for (unsigned I : P.second)
1301 dbgs() << ' ' << I;
1302 dbgs() << '\n';
1303 }
1304 });
1305
1306 // Select the definition points, and generate the assignment between
1307 // these points and the uses.
1308
1309 // For each candidate offset, keep a pair CandData consisting of
1310 // the total number of ranges containing that candidate, and the
1311 // vector of corresponding RangeTree nodes.
1312 using CandData = std::pair<unsigned, SmallVector<RangeTree::Node*,8>>;
1313 std::map<int32_t, CandData> CandMap;
1314
1315 RangeTree Tree;
1316 for (const OffsetRange &R : Ranges)
1317 Tree.add(R);
1318 SmallVector<RangeTree::Node*,8> Nodes;
1319 Tree.order(Nodes);
1320
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +00001321 auto MaxAlign = [](const SmallVectorImpl<RangeTree::Node*> &Nodes,
1322 uint8_t Align, uint8_t Offset) {
1323 for (RangeTree::Node *N : Nodes) {
1324 if (N->Range.Align <= Align || N->Range.Offset < Offset)
1325 continue;
1326 if ((N->Range.Offset - Offset) % Align != 0)
1327 continue;
1328 Align = N->Range.Align;
1329 Offset = N->Range.Offset;
1330 }
1331 return std::make_pair(Align, Offset);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001332 };
1333
1334 // Construct the set of all potential definition points from the endpoints
1335 // of the ranges. If a given endpoint also belongs to a different range,
1336 // but with a higher alignment, also consider the more-highly-aligned
1337 // value of this endpoint.
1338 std::set<int32_t> CandSet;
1339 for (RangeTree::Node *N : Nodes) {
1340 const OffsetRange &R = N->Range;
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +00001341 auto P0 = MaxAlign(Tree.nodesWith(R.Min, false), R.Align, R.Offset);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001342 CandSet.insert(R.Min);
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +00001343 if (R.Align < P0.first)
1344 CandSet.insert(adjustUp(R.Min, P0.first, P0.second));
1345 auto P1 = MaxAlign(Tree.nodesWith(R.Max, false), R.Align, R.Offset);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001346 CandSet.insert(R.Max);
Krzysztof Parzyszek39a98422018-01-30 18:12:37 +00001347 if (R.Align < P1.first)
1348 CandSet.insert(adjustDown(R.Max, P1.first, P1.second));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001349 }
1350
1351 // Build the assignment map: candidate C -> { list of extender indexes }.
1352 // This has to be done iteratively:
1353 // - pick the candidate that covers the maximum number of extenders,
1354 // - add the candidate to the map,
1355 // - remove the extenders from the pool.
1356 while (true) {
1357 using CMap = std::map<int32_t,unsigned>;
1358 CMap Counts;
1359 for (auto It = CandSet.begin(), Et = CandSet.end(); It != Et; ) {
1360 auto &&V = Tree.nodesWith(*It);
1361 unsigned N = std::accumulate(V.begin(), V.end(), 0u,
1362 [](unsigned Acc, const RangeTree::Node *N) {
1363 return Acc + N->Count;
1364 });
1365 if (N != 0)
1366 Counts.insert({*It, N});
1367 It = (N != 0) ? std::next(It) : CandSet.erase(It);
1368 }
1369 if (Counts.empty())
1370 break;
1371
1372 // Find the best candidate with respect to the number of extenders covered.
1373 auto BestIt = std::max_element(Counts.begin(), Counts.end(),
1374 [](const CMap::value_type &A, const CMap::value_type &B) {
1375 return A.second < B.second ||
1376 (A.second == B.second && A < B);
1377 });
1378 int32_t Best = BestIt->first;
1379 ExtValue BestV(ER, Best);
1380 for (RangeTree::Node *N : Tree.nodesWith(Best)) {
1381 for (unsigned I : RangeMap[N->Range])
1382 IMap[{BestV,Extenders[I].Expr}].insert(I);
1383 Tree.erase(N);
1384 }
1385 }
1386
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001387 LLVM_DEBUG(dbgs() << "IMap (before fixup) = " << PrintIMap(IMap, *HRI));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001388
1389 // There is some ambiguity in what initializer should be used, if the
1390 // descriptor's subexpression is non-trivial: it can be the entire
1391 // subexpression (which is what has been done so far), or it can be
1392 // the extender's value itself, if all corresponding extenders have the
1393 // exact value of the initializer (i.e. require offset of 0).
1394
1395 // To reduce the number of initializers, merge such special cases.
1396 for (std::pair<const ExtenderInit,IndexList> &P : IMap) {
1397 // Skip trivial initializers.
1398 if (P.first.second.trivial())
1399 continue;
1400 // If the corresponding trivial initializer does not exist, skip this
1401 // entry.
1402 const ExtValue &EV = P.first.first;
1403 AssignmentMap::iterator F = IMap.find({EV, ExtExpr()});
1404 if (F == IMap.end())
1405 continue;
Krzysztof Parzyszekcc712912018-04-17 15:23:09 +00001406
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001407 // Finally, check if all extenders have the same value as the initializer.
Krzysztof Parzyszekcc712912018-04-17 15:23:09 +00001408 // Make sure that extenders that are a part of a stack address are not
1409 // merged with those that aren't. Stack addresses need an offset field
1410 // (to be used by frame index elimination), while non-stack expressions
1411 // can be replaced with forms (such as rr) that do not have such a field.
1412 // Example:
1413 //
1414 // Collected 3 extenders
1415 // =2. imm:0 off:32968 bb#2: %7 = ## + __ << 0, def
1416 // 0. imm:0 off:267 bb#0: __ = ## + SS#1 << 0
1417 // 1. imm:0 off:267 bb#1: __ = ## + SS#1 << 0
1418 // Ranges
1419 // 0. [-756,267]a1+0
1420 // 1. [-756,267]a1+0
1421 // 2. [201,65735]a1+0
1422 // RangeMap
1423 // [-756,267]a1+0 -> 0 1
1424 // [201,65735]a1+0 -> 2
1425 // IMap (before fixup) = {
1426 // [imm:0 off:267, ## + __ << 0] -> { 2 }
1427 // [imm:0 off:267, ## + SS#1 << 0] -> { 0 1 }
1428 // }
1429 // IMap (after fixup) = {
1430 // [imm:0 off:267, ## + __ << 0] -> { 2 0 1 }
1431 // [imm:0 off:267, ## + SS#1 << 0] -> { }
1432 // }
1433 // Inserted def in bb#0 for initializer: [imm:0 off:267, ## + __ << 0]
1434 // %12:intregs = A2_tfrsi 267
1435 //
1436 // The result was
1437 // %12:intregs = A2_tfrsi 267
1438 // S4_pstorerbt_rr %3, %12, %stack.1, 0, killed %4
1439 // Which became
1440 // r0 = #267
1441 // if (p0.new) memb(r0+r29<<#4) = r2
1442
1443 bool IsStack = any_of(F->second, [this](unsigned I) {
1444 return Extenders[I].Expr.Rs.isSlot();
1445 });
1446 auto SameValue = [&EV,this,IsStack](unsigned I) {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001447 const ExtDesc &ED = Extenders[I];
Krzysztof Parzyszekcc712912018-04-17 15:23:09 +00001448 return ED.Expr.Rs.isSlot() == IsStack &&
1449 ExtValue(ED).Offset == EV.Offset;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001450 };
1451 if (all_of(P.second, SameValue)) {
1452 F->second.insert(P.second.begin(), P.second.end());
1453 P.second.clear();
1454 }
1455 }
1456
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001457 LLVM_DEBUG(dbgs() << "IMap (after fixup) = " << PrintIMap(IMap, *HRI));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001458}
1459
1460void HCE::calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
1461 LocDefMap &Defs) {
1462 if (Refs.empty())
1463 return;
1464
1465 // The placement calculation is somewhat simple right now: it finds a
1466 // single location for the def that dominates all refs. Since this may
1467 // place the def far from the uses, producing several locations for
1468 // defs that collectively dominate all refs could be better.
1469 // For now only do the single one.
1470 DenseSet<MachineBasicBlock*> Blocks;
1471 DenseSet<MachineInstr*> RefMIs;
1472 const ExtDesc &ED0 = Extenders[Refs[0]];
1473 MachineBasicBlock *DomB = ED0.UseMI->getParent();
1474 RefMIs.insert(ED0.UseMI);
1475 Blocks.insert(DomB);
1476 for (unsigned i = 1, e = Refs.size(); i != e; ++i) {
1477 const ExtDesc &ED = Extenders[Refs[i]];
1478 MachineBasicBlock *MBB = ED.UseMI->getParent();
1479 RefMIs.insert(ED.UseMI);
1480 DomB = MDT->findNearestCommonDominator(DomB, MBB);
1481 Blocks.insert(MBB);
1482 }
1483
1484#ifndef NDEBUG
1485 // The block DomB should be dominated by the def of each register used
1486 // in the initializer.
1487 Register Rs = ExtI.second.Rs; // Only one reg allowed now.
1488 const MachineInstr *DefI = Rs.isVReg() ? MRI->getVRegDef(Rs.Reg) : nullptr;
1489
1490 // This should be guaranteed given that the entire expression is used
1491 // at each instruction in Refs. Add an assertion just in case.
1492 assert(!DefI || MDT->dominates(DefI->getParent(), DomB));
1493#endif
1494
1495 MachineBasicBlock::iterator It;
1496 if (Blocks.count(DomB)) {
1497 // Try to find the latest possible location for the def.
1498 MachineBasicBlock::iterator End = DomB->end();
1499 for (It = DomB->begin(); It != End; ++It)
1500 if (RefMIs.count(&*It))
1501 break;
1502 assert(It != End && "Should have found a ref in DomB");
1503 } else {
1504 // DomB does not contain any refs.
1505 It = DomB->getFirstTerminator();
1506 }
1507 Loc DefLoc(DomB, It);
1508 Defs.emplace(DefLoc, Refs);
1509}
1510
1511HCE::Register HCE::insertInitializer(Loc DefL, const ExtenderInit &ExtI) {
1512 unsigned DefR = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1513 MachineBasicBlock &MBB = *DefL.Block;
1514 MachineBasicBlock::iterator At = DefL.At;
1515 DebugLoc dl = DefL.Block->findDebugLoc(DefL.At);
1516 const ExtValue &EV = ExtI.first;
1517 MachineOperand ExtOp(EV);
1518
1519 const ExtExpr &Ex = ExtI.second;
1520 const MachineInstr *InitI = nullptr;
1521
1522 if (Ex.Rs.isSlot()) {
1523 assert(Ex.S == 0 && "Cannot have a shift of a stack slot");
1524 assert(!Ex.Neg && "Cannot subtract a stack slot");
1525 // DefR = PS_fi Rb,##EV
1526 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::PS_fi), DefR)
1527 .add(MachineOperand(Ex.Rs))
1528 .add(ExtOp);
1529 } else {
1530 assert((Ex.Rs.Reg == 0 || Ex.Rs.isVReg()) && "Expecting virtual register");
1531 if (Ex.trivial()) {
1532 // DefR = ##EV
1533 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_tfrsi), DefR)
1534 .add(ExtOp);
1535 } else if (Ex.S == 0) {
1536 if (Ex.Neg) {
1537 // DefR = sub(##EV,Rb)
1538 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_subri), DefR)
1539 .add(ExtOp)
1540 .add(MachineOperand(Ex.Rs));
1541 } else {
1542 // DefR = add(Rb,##EV)
1543 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_addi), DefR)
1544 .add(MachineOperand(Ex.Rs))
1545 .add(ExtOp);
1546 }
1547 } else {
1548 unsigned NewOpc = Ex.Neg ? Hexagon::S4_subi_asl_ri
1549 : Hexagon::S4_addi_asl_ri;
1550 // DefR = add(##EV,asl(Rb,S))
1551 InitI = BuildMI(MBB, At, dl, HII->get(NewOpc), DefR)
1552 .add(ExtOp)
1553 .add(MachineOperand(Ex.Rs))
1554 .addImm(Ex.S);
1555 }
1556 }
1557
1558 assert(InitI);
1559 (void)InitI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001560 LLVM_DEBUG(dbgs() << "Inserted def in bb#" << MBB.getNumber()
1561 << " for initializer: " << PrintInit(ExtI, *HRI) << "\n "
1562 << *InitI);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001563 return { DefR, 0 };
1564}
1565
1566// Replace the extender at index Idx with the register ExtR.
1567bool HCE::replaceInstrExact(const ExtDesc &ED, Register ExtR) {
1568 MachineInstr &MI = *ED.UseMI;
1569 MachineBasicBlock &MBB = *MI.getParent();
1570 MachineBasicBlock::iterator At = MI.getIterator();
1571 DebugLoc dl = MI.getDebugLoc();
1572 unsigned ExtOpc = MI.getOpcode();
1573
1574 // With a few exceptions, direct replacement amounts to creating an
1575 // instruction with a corresponding register opcode, with all operands
1576 // the same, except for the register used in place of the extender.
1577 unsigned RegOpc = getDirectRegReplacement(ExtOpc);
1578
1579 if (RegOpc == TargetOpcode::REG_SEQUENCE) {
1580 if (ExtOpc == Hexagon::A4_combineri)
1581 BuildMI(MBB, At, dl, HII->get(RegOpc))
1582 .add(MI.getOperand(0))
1583 .add(MI.getOperand(1))
1584 .addImm(Hexagon::isub_hi)
1585 .add(MachineOperand(ExtR))
1586 .addImm(Hexagon::isub_lo);
1587 else if (ExtOpc == Hexagon::A4_combineir)
1588 BuildMI(MBB, At, dl, HII->get(RegOpc))
1589 .add(MI.getOperand(0))
1590 .add(MachineOperand(ExtR))
1591 .addImm(Hexagon::isub_hi)
1592 .add(MI.getOperand(2))
1593 .addImm(Hexagon::isub_lo);
1594 else
1595 llvm_unreachable("Unexpected opcode became REG_SEQUENCE");
1596 MBB.erase(MI);
1597 return true;
1598 }
1599 if (ExtOpc == Hexagon::C2_cmpgei || ExtOpc == Hexagon::C2_cmpgeui) {
1600 unsigned NewOpc = ExtOpc == Hexagon::C2_cmpgei ? Hexagon::C2_cmplt
1601 : Hexagon::C2_cmpltu;
1602 BuildMI(MBB, At, dl, HII->get(NewOpc))
1603 .add(MI.getOperand(0))
1604 .add(MachineOperand(ExtR))
1605 .add(MI.getOperand(1));
1606 MBB.erase(MI);
1607 return true;
1608 }
1609
1610 if (RegOpc != 0) {
1611 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1612 unsigned RegN = ED.OpNum;
1613 // Copy all operands except the one that has the extender.
1614 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1615 if (i != RegN)
1616 MIB.add(MI.getOperand(i));
1617 else
1618 MIB.add(MachineOperand(ExtR));
1619 }
1620 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1621 MBB.erase(MI);
1622 return true;
1623 }
1624
1625 if ((MI.mayLoad() || MI.mayStore()) && !isStoreImmediate(ExtOpc)) {
1626 // For memory instructions, there is an asymmetry in the addressing
1627 // modes. Addressing modes allowing extenders can be replaced with
1628 // addressing modes that use registers, but the order of operands
1629 // (or even their number) may be different.
1630 // Replacements:
1631 // BaseImmOffset (io) -> BaseRegOffset (rr)
1632 // BaseLongOffset (ur) -> BaseRegOffset (rr)
1633 unsigned RegOpc, Shift;
1634 unsigned AM = HII->getAddrMode(MI);
1635 if (AM == HexagonII::BaseImmOffset) {
1636 RegOpc = HII->changeAddrMode_io_rr(ExtOpc);
1637 Shift = 0;
1638 } else if (AM == HexagonII::BaseLongOffset) {
1639 // Loads: Rd = L4_loadri_ur Rs, S, ##
1640 // Stores: S4_storeri_ur Rs, S, ##, Rt
1641 RegOpc = HII->changeAddrMode_ur_rr(ExtOpc);
1642 Shift = MI.getOperand(MI.mayLoad() ? 2 : 1).getImm();
1643 } else {
1644 llvm_unreachable("Unexpected addressing mode");
1645 }
1646#ifndef NDEBUG
1647 if (RegOpc == -1u) {
1648 dbgs() << "\nExtOpc: " << HII->getName(ExtOpc) << " has no rr version\n";
1649 llvm_unreachable("No corresponding rr instruction");
1650 }
1651#endif
1652
1653 unsigned BaseP, OffP;
1654 HII->getBaseAndOffsetPosition(MI, BaseP, OffP);
1655
1656 // Build an rr instruction: (RegOff + RegBase<<0)
1657 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1658 // First, add the def for loads.
1659 if (MI.mayLoad())
1660 MIB.add(getLoadResultOp(MI));
1661 // Handle possible predication.
1662 if (HII->isPredicated(MI))
1663 MIB.add(getPredicateOp(MI));
1664 // Build the address.
1665 MIB.add(MachineOperand(ExtR)); // RegOff
1666 MIB.add(MI.getOperand(BaseP)); // RegBase
1667 MIB.addImm(Shift); // << Shift
1668 // Add the stored value for stores.
1669 if (MI.mayStore())
1670 MIB.add(getStoredValueOp(MI));
1671 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1672 MBB.erase(MI);
1673 return true;
1674 }
1675
1676#ifndef NDEBUG
1677 dbgs() << '\n' << MI;
1678#endif
1679 llvm_unreachable("Unhandled exact replacement");
1680 return false;
1681}
1682
1683// Replace the extender ED with a form corresponding to the initializer ExtI.
1684bool HCE::replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
1685 Register ExtR, int32_t &Diff) {
1686 MachineInstr &MI = *ED.UseMI;
1687 MachineBasicBlock &MBB = *MI.getParent();
1688 MachineBasicBlock::iterator At = MI.getIterator();
1689 DebugLoc dl = MI.getDebugLoc();
1690 unsigned ExtOpc = MI.getOpcode();
1691
1692 if (ExtOpc == Hexagon::A2_tfrsi) {
1693 // A2_tfrsi is a special case: it's replaced with A2_addi, which introduces
1694 // another range. One range is the one that's common to all tfrsi's uses,
1695 // this one is the range of immediates in A2_addi. When calculating ranges,
1696 // the addi's 16-bit argument was included, so now we need to make it such
1697 // that the produced value is in the range for the uses alone.
1698 // Most of the time, simply adding Diff will make the addi produce exact
1699 // result, but if Diff is outside of the 16-bit range, some adjustment
1700 // will be needed.
1701 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1702 assert(IdxOpc == Hexagon::A2_addi);
1703
1704 // Clamp Diff to the 16 bit range.
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001705 int32_t D = isInt<16>(Diff) ? Diff : (Diff > 0 ? 32767 : -32768);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001706 BuildMI(MBB, At, dl, HII->get(IdxOpc))
1707 .add(MI.getOperand(0))
1708 .add(MachineOperand(ExtR))
1709 .addImm(D);
1710 Diff -= D;
1711#ifndef NDEBUG
1712 // Make sure the output is within allowable range for uses.
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001713 // "Diff" is a difference in the "opposite direction", i.e. Ext - DefV,
1714 // not DefV - Ext, as the getOffsetRange would calculate.
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001715 OffsetRange Uses = getOffsetRange(MI.getOperand(0));
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001716 if (!Uses.contains(-Diff))
1717 dbgs() << "Diff: " << -Diff << " out of range " << Uses
Krzysztof Parzyszek27056da2017-10-25 18:46:40 +00001718 << " for " << MI;
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001719 assert(Uses.contains(-Diff));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001720#endif
1721 MBB.erase(MI);
1722 return true;
1723 }
1724
1725 const ExtValue &EV = ExtI.first; (void)EV;
1726 const ExtExpr &Ex = ExtI.second; (void)Ex;
1727
1728 if (ExtOpc == Hexagon::A2_addi || ExtOpc == Hexagon::A2_subri) {
1729 // If addi/subri are replaced with the exactly matching initializer,
1730 // they amount to COPY.
1731 // Check that the initializer is an exact match (for simplicity).
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001732#ifndef NDEBUG
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001733 bool IsAddi = ExtOpc == Hexagon::A2_addi;
1734 const MachineOperand &RegOp = MI.getOperand(IsAddi ? 1 : 2);
1735 const MachineOperand &ImmOp = MI.getOperand(IsAddi ? 2 : 1);
1736 assert(Ex.Rs == RegOp && EV == ImmOp && Ex.Neg != IsAddi &&
1737 "Initializer mismatch");
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001738#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001739 BuildMI(MBB, At, dl, HII->get(TargetOpcode::COPY))
1740 .add(MI.getOperand(0))
1741 .add(MachineOperand(ExtR));
1742 Diff = 0;
1743 MBB.erase(MI);
1744 return true;
1745 }
1746 if (ExtOpc == Hexagon::M2_accii || ExtOpc == Hexagon::M2_naccii ||
1747 ExtOpc == Hexagon::S4_addaddi || ExtOpc == Hexagon::S4_subaddi) {
1748 // M2_accii: add(Rt,add(Rs,V)) (tied)
1749 // M2_naccii: sub(Rt,add(Rs,V))
1750 // S4_addaddi: add(Rt,add(Rs,V))
1751 // S4_subaddi: add(Rt,sub(V,Rs))
1752 // Check that Rs and V match the initializer expression. The Rs+V is the
1753 // combination that is considered "subexpression" for V, although Rx+V
1754 // would also be valid.
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001755#ifndef NDEBUG
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001756 bool IsSub = ExtOpc == Hexagon::S4_subaddi;
1757 Register Rs = MI.getOperand(IsSub ? 3 : 2);
1758 ExtValue V = MI.getOperand(IsSub ? 2 : 3);
1759 assert(EV == V && Rs == Ex.Rs && IsSub == Ex.Neg && "Initializer mismatch");
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001760#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001761 unsigned NewOpc = ExtOpc == Hexagon::M2_naccii ? Hexagon::A2_sub
1762 : Hexagon::A2_add;
1763 BuildMI(MBB, At, dl, HII->get(NewOpc))
1764 .add(MI.getOperand(0))
1765 .add(MI.getOperand(1))
1766 .add(MachineOperand(ExtR));
1767 MBB.erase(MI);
1768 return true;
1769 }
1770
1771 if (MI.mayLoad() || MI.mayStore()) {
1772 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1773 assert(IdxOpc && "Expecting indexed opcode");
1774 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(IdxOpc));
1775 // Construct the new indexed instruction.
1776 // First, add the def for loads.
1777 if (MI.mayLoad())
1778 MIB.add(getLoadResultOp(MI));
1779 // Handle possible predication.
1780 if (HII->isPredicated(MI))
1781 MIB.add(getPredicateOp(MI));
1782 // Build the address.
1783 MIB.add(MachineOperand(ExtR));
1784 MIB.addImm(Diff);
1785 // Add the stored value for stores.
1786 if (MI.mayStore())
1787 MIB.add(getStoredValueOp(MI));
1788 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1789 MBB.erase(MI);
1790 return true;
1791 }
1792
1793#ifndef NDEBUG
1794 dbgs() << '\n' << PrintInit(ExtI, *HRI) << " " << MI;
1795#endif
1796 llvm_unreachable("Unhandled expr replacement");
1797 return false;
1798}
1799
1800bool HCE::replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI) {
1801 if (ReplaceLimit.getNumOccurrences()) {
1802 if (ReplaceLimit <= ReplaceCounter)
1803 return false;
1804 ++ReplaceCounter;
1805 }
1806 const ExtDesc &ED = Extenders[Idx];
1807 assert((!ED.IsDef || ED.Rd.Reg != 0) && "Missing Rd for def");
1808 const ExtValue &DefV = ExtI.first;
1809 assert(ExtRoot(ExtValue(ED)) == ExtRoot(DefV) && "Extender root mismatch");
1810 const ExtExpr &DefEx = ExtI.second;
1811
1812 ExtValue EV(ED);
1813 int32_t Diff = EV.Offset - DefV.Offset;
1814 const MachineInstr &MI = *ED.UseMI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001815 LLVM_DEBUG(dbgs() << __func__ << " Idx:" << Idx << " ExtR:"
1816 << PrintRegister(ExtR, *HRI) << " Diff:" << Diff << '\n');
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001817
1818 // These two addressing modes must be converted into indexed forms
1819 // regardless of what the initializer looks like.
1820 bool IsAbs = false, IsAbsSet = false;
1821 if (MI.mayLoad() || MI.mayStore()) {
1822 unsigned AM = HII->getAddrMode(MI);
1823 IsAbs = AM == HexagonII::Absolute;
1824 IsAbsSet = AM == HexagonII::AbsoluteSet;
1825 }
1826
1827 // If it's a def, remember all operands that need to be updated.
1828 // If ED is a def, and Diff is not 0, then all uses of the register Rd
1829 // defined by ED must be in the form (Rd, imm), i.e. the immediate offset
1830 // must follow the Rd in the operand list.
1831 std::vector<std::pair<MachineInstr*,unsigned>> RegOps;
1832 if (ED.IsDef && Diff != 0) {
1833 for (MachineOperand &Op : MRI->use_operands(ED.Rd.Reg)) {
1834 MachineInstr &UI = *Op.getParent();
1835 RegOps.push_back({&UI, getOperandIndex(UI, Op)});
1836 }
1837 }
1838
1839 // Replace the instruction.
1840 bool Replaced = false;
1841 if (Diff == 0 && DefEx.trivial() && !IsAbs && !IsAbsSet)
1842 Replaced = replaceInstrExact(ED, ExtR);
1843 else
1844 Replaced = replaceInstrExpr(ED, ExtI, ExtR, Diff);
1845
1846 if (Diff != 0 && Replaced && ED.IsDef) {
1847 // Update offsets of the def's uses.
1848 for (std::pair<MachineInstr*,unsigned> P : RegOps) {
1849 unsigned J = P.second;
Krzysztof Parzyszek92a26352017-10-27 18:52:28 +00001850 assert(P.first->getNumOperands() > J+1 &&
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001851 P.first->getOperand(J+1).isImm());
1852 MachineOperand &ImmOp = P.first->getOperand(J+1);
1853 ImmOp.setImm(ImmOp.getImm() + Diff);
1854 }
1855 // If it was an absolute-set instruction, the "set" part has been removed.
1856 // ExtR will now be the register with the extended value, and since all
1857 // users of Rd have been updated, all that needs to be done is to replace
1858 // Rd with ExtR.
1859 if (IsAbsSet) {
1860 assert(ED.Rd.Sub == 0 && ExtR.Sub == 0);
1861 MRI->replaceRegWith(ED.Rd.Reg, ExtR.Reg);
1862 }
1863 }
1864
1865 return Replaced;
1866}
1867
1868bool HCE::replaceExtenders(const AssignmentMap &IMap) {
1869 LocDefMap Defs;
1870 bool Changed = false;
1871
1872 for (const std::pair<ExtenderInit,IndexList> &P : IMap) {
1873 const IndexList &Idxs = P.second;
1874 if (Idxs.size() < CountThreshold)
1875 continue;
1876
1877 Defs.clear();
1878 calculatePlacement(P.first, Idxs, Defs);
1879 for (const std::pair<Loc,IndexList> &Q : Defs) {
1880 Register DefR = insertInitializer(Q.first, P.first);
1881 NewRegs.push_back(DefR.Reg);
1882 for (unsigned I : Q.second)
1883 Changed |= replaceInstr(I, DefR, P.first);
1884 }
1885 }
1886 return Changed;
1887}
1888
1889unsigned HCE::getOperandIndex(const MachineInstr &MI,
1890 const MachineOperand &Op) const {
1891 for (unsigned i = 0, n = MI.getNumOperands(); i != n; ++i)
1892 if (&MI.getOperand(i) == &Op)
1893 return i;
1894 llvm_unreachable("Not an operand of MI");
1895}
1896
1897const MachineOperand &HCE::getPredicateOp(const MachineInstr &MI) const {
1898 assert(HII->isPredicated(MI));
1899 for (const MachineOperand &Op : MI.operands()) {
1900 if (!Op.isReg() || !Op.isUse() ||
1901 MRI->getRegClass(Op.getReg()) != &Hexagon::PredRegsRegClass)
1902 continue;
1903 assert(Op.getSubReg() == 0 && "Predicate register with a subregister");
1904 return Op;
1905 }
1906 llvm_unreachable("Predicate operand not found");
1907}
1908
1909const MachineOperand &HCE::getLoadResultOp(const MachineInstr &MI) const {
1910 assert(MI.mayLoad());
1911 return MI.getOperand(0);
1912}
1913
1914const MachineOperand &HCE::getStoredValueOp(const MachineInstr &MI) const {
1915 assert(MI.mayStore());
1916 return MI.getOperand(MI.getNumExplicitOperands()-1);
1917}
1918
1919bool HCE::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001920 if (skipFunction(MF.getFunction()))
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001921 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001922 LLVM_DEBUG(MF.print(dbgs() << "Before " << getPassName() << '\n', nullptr));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001923
1924 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
1925 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1926 MDT = &getAnalysis<MachineDominatorTree>();
1927 MRI = &MF.getRegInfo();
1928 AssignmentMap IMap;
1929
1930 collect(MF);
Mandeep Singh Grangdb00e2e2018-03-24 17:34:37 +00001931 llvm::sort(Extenders.begin(), Extenders.end(),
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001932 [](const ExtDesc &A, const ExtDesc &B) {
1933 return ExtValue(A) < ExtValue(B);
1934 });
1935
1936 bool Changed = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001937 LLVM_DEBUG(dbgs() << "Collected " << Extenders.size() << " extenders\n");
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001938 for (unsigned I = 0, E = Extenders.size(); I != E; ) {
1939 unsigned B = I;
1940 const ExtRoot &T = Extenders[B].getOp();
1941 while (I != E && ExtRoot(Extenders[I].getOp()) == T)
1942 ++I;
1943
1944 IMap.clear();
1945 assignInits(T, B, I, IMap);
1946 Changed |= replaceExtenders(IMap);
1947 }
1948
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001949 LLVM_DEBUG({
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001950 if (Changed)
1951 MF.print(dbgs() << "After " << getPassName() << '\n', nullptr);
1952 else
1953 dbgs() << "No changes\n";
1954 });
1955 return Changed;
1956}
1957
1958FunctionPass *llvm::createHexagonConstExtenders() {
1959 return new HexagonConstExtenders();
1960}