LLVM 24.0.0git
HexagonConstExtenders.cpp
Go to the documentation of this file.
1//===- HexagonConstExtenders.cpp ------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "HexagonInstrInfo.h"
10#include "HexagonRegisterInfo.h"
11#include "HexagonSubtarget.h"
12#include "llvm/ADT/SetVector.h"
20#include "llvm/Pass.h"
22#include <map>
23#include <set>
24#include <utility>
25#include <vector>
26
27#define DEBUG_TYPE "hexagon-cext-opt"
28
29using namespace llvm;
30
31static int32_t adjustUp(int32_t V, uint8_t A, uint8_t O) {
33 int32_t U = (V & -A) + O;
34 return U >= V ? U : U+A;
35}
36
37static int32_t adjustDown(int32_t V, uint8_t A, uint8_t O) {
39 int32_t U = (V & -A) + O;
40 return U <= V ? U : U-A;
41}
42
43namespace {
44 struct OffsetRange {
45 // The range of values between Min and Max that are of form Align*N+Offset,
46 // for some integer N. Min and Max are required to be of that form as well,
47 // except in the case of an empty range.
48 int32_t Min = INT_MIN, Max = INT_MAX;
49 uint8_t Align = 1;
50 uint8_t Offset = 0;
51
52 OffsetRange() = default;
53 OffsetRange(int32_t L, int32_t H, uint8_t A, uint8_t O = 0)
54 : Min(L), Max(H), Align(A), Offset(O) {}
55 OffsetRange &intersect(OffsetRange A) {
56 if (Align < A.Align)
57 std::swap(*this, A);
58
59 // Align >= A.Align.
60 if (Offset >= A.Offset && (Offset - A.Offset) % A.Align == 0) {
61 Min = adjustUp(std::max(Min, A.Min), Align, Offset);
62 Max = adjustDown(std::min(Max, A.Max), Align, Offset);
63 } else {
64 // Make an empty range.
65 Min = 0;
66 Max = -1;
67 }
68 // Canonicalize empty ranges.
69 if (Min > Max)
70 std::tie(Min, Max, Align) = std::make_tuple(0, -1, 1);
71 return *this;
72 }
73 OffsetRange &shift(int32_t S) {
74 Min += S;
75 Max += S;
76 Offset = (Offset+S) % Align;
77 return *this;
78 }
79 OffsetRange &extendBy(int32_t D) {
80 // If D < 0, extend Min, otherwise extend Max.
81 assert(D % Align == 0);
82 if (D < 0)
83 Min = (INT_MIN-D < Min) ? Min+D : INT_MIN;
84 else
85 Max = (INT_MAX-D > Max) ? Max+D : INT_MAX;
86 return *this;
87 }
88 bool empty() const {
89 return Min > Max;
90 }
91 bool contains(int32_t V) const {
92 return Min <= V && V <= Max && (V-Offset) % Align == 0;
93 }
94 bool operator==(const OffsetRange &R) const {
95 return Min == R.Min && Max == R.Max && Align == R.Align;
96 }
97 bool operator!=(const OffsetRange &R) const {
98 return !operator==(R);
99 }
100 bool operator<(const OffsetRange &R) const {
101 return std::tie(Min, Max, Align) < std::tie(R.Min, R.Max, R.Align);
102 }
103 static OffsetRange zero() { return {0, 0, 1}; }
104 };
105
106 struct RangeTree {
107 struct Node {
108 Node(const OffsetRange &R) : MaxEnd(R.Max), Range(R) {}
109 unsigned Height = 1;
110 unsigned Count = 1;
111 int32_t MaxEnd;
112 const OffsetRange &Range;
113 Node *Left = nullptr, *Right = nullptr;
114 };
115
116 Node *Root = nullptr;
117
118 void add(const OffsetRange &R) {
119 Root = add(Root, R);
120 }
121 void erase(const Node *N) {
122 Root = remove(Root, N);
123 delete N;
124 }
125 void order(SmallVectorImpl<Node*> &Seq) const {
126 order(Root, Seq);
127 }
128 SmallVector<Node*,8> nodesWith(int32_t P, bool CheckAlign = true) {
130 nodesWith(Root, P, CheckAlign, Nodes);
131 return Nodes;
132 }
133 void dump() const;
134 ~RangeTree() {
136 order(Nodes);
137 for (Node *N : Nodes)
138 delete N;
139 }
140
141 private:
142 void dump(const Node *N) const;
143 void order(Node *N, SmallVectorImpl<Node*> &Seq) const;
144 void nodesWith(Node *N, int32_t P, bool CheckA,
145 SmallVectorImpl<Node*> &Seq) const;
146
147 Node *add(Node *N, const OffsetRange &R);
148 Node *remove(Node *N, const Node *D);
149 Node *rotateLeft(Node *Lower, Node *Higher);
150 Node *rotateRight(Node *Lower, Node *Higher);
151 unsigned height(Node *N) {
152 return N != nullptr ? N->Height : 0;
153 }
154 Node *update(Node *N) {
155 assert(N != nullptr);
156 N->Height = 1 + std::max(height(N->Left), height(N->Right));
157 if (N->Left)
158 N->MaxEnd = std::max(N->MaxEnd, N->Left->MaxEnd);
159 if (N->Right)
160 N->MaxEnd = std::max(N->MaxEnd, N->Right->MaxEnd);
161 return N;
162 }
163 Node *rebalance(Node *N) {
164 assert(N != nullptr);
165 int32_t Balance = height(N->Right) - height(N->Left);
166 if (Balance < -1)
167 return rotateRight(N->Left, N);
168 if (Balance > 1)
169 return rotateLeft(N->Right, N);
170 return N;
171 }
172 };
173
174 struct Loc {
175 MachineBasicBlock *Block = nullptr;
177
178 Loc(MachineBasicBlock *B, MachineBasicBlock::iterator It)
179 : Block(B), At(It) {
180 if (B->end() == It) {
181 Pos = -1;
182 } else {
183 assert(It->getParent() == B);
184 Pos = std::distance(B->begin(), It);
185 }
186 }
187 bool operator<(Loc A) const {
188 if (Block != A.Block)
189 return Block->getNumber() < A.Block->getNumber();
190 if (A.Pos == -1)
191 return Pos != A.Pos;
192 return Pos != -1 && Pos < A.Pos;
193 }
194 private:
195 int Pos = 0;
196 };
197
198 struct HexagonConstExtenders : public MachineFunctionPass {
199 static char ID;
200 HexagonConstExtenders() : MachineFunctionPass(ID) {}
201
202 void getAnalysisUsage(AnalysisUsage &AU) const override {
203 AU.addRequired<MachineDominatorTreeWrapperPass>();
204 AU.addPreserved<MachineDominatorTreeWrapperPass>();
206 }
207
208 StringRef getPassName() const override {
209 return "Hexagon constant-extender optimization";
210 }
211 bool runOnMachineFunction(MachineFunction &MF) override;
212
213 private:
214 struct Register {
215 Register() = default;
216 Register(llvm::Register R, unsigned S) : Reg(R), Sub(S) {}
217 Register(const MachineOperand &Op)
218 : Reg(Op.getReg()), Sub(Op.getSubReg()) {}
219 Register &operator=(const MachineOperand &Op) {
220 if (Op.isReg()) {
221 Reg = Op.getReg();
222 Sub = Op.getSubReg();
223 } else if (Op.isFI()) {
224 Reg = llvm::Register::index2StackSlot(Op.getIndex());
225 }
226 return *this;
227 }
228 bool isVReg() const {
229 return Reg != 0 && !Reg.isStack() && Reg.isVirtual();
230 }
231 bool isSlot() const { return Reg != 0 && Reg.isStack(); }
232 operator MachineOperand() const {
233 if (isVReg())
234 return MachineOperand::CreateReg(Reg, /*Def*/false, /*Imp*/false,
235 /*Kill*/false, /*Dead*/false, /*Undef*/false,
236 /*EarlyClobber*/false, Sub);
237 if (Reg.isStack()) {
238 int FI = Reg.stackSlotIndex();
239 return MachineOperand::CreateFI(FI);
240 }
241 llvm_unreachable("Cannot create MachineOperand");
242 }
243 bool operator==(Register R) const { return Reg == R.Reg && Sub == R.Sub; }
244 bool operator!=(Register R) const { return !operator==(R); }
245 bool operator<(Register R) const {
246 // For std::map.
247 return std::tie(Reg, Sub) < std::tie(R.Reg, R.Sub);
248 }
249 llvm::Register Reg;
250 unsigned Sub = 0;
251 };
252
253 struct ExtExpr {
254 // A subexpression in which the extender is used. In general, this
255 // represents an expression where adding D to the extender will be
256 // equivalent to adding D to the expression as a whole. In other
257 // words, expr(add(##V,D) = add(expr(##V),D).
258
259 // The original motivation for this are the io/ur addressing modes,
260 // where the offset is extended. Consider the io example:
261 // In memw(Rs+##V), the ##V could be replaced by a register Rt to
262 // form the rr mode: memw(Rt+Rs<<0). In such case, however, the
263 // register Rt must have exactly the value of ##V. If there was
264 // another instruction memw(Rs+##V+4), it would need a different Rt.
265 // Now, if Rt was initialized as "##V+Rs<<0", both of these
266 // instructions could use the same Rt, just with different offsets.
267 // Here it's clear that "initializer+4" should be the same as if
268 // the offset 4 was added to the ##V in the initializer.
269
270 // The only kinds of expressions that support the requirement of
271 // commuting with addition are addition and subtraction from ##V.
272 // Include shifting the Rs to account for the ur addressing mode:
273 // ##Val + Rs << S
274 // ##Val - Rs
275 Register Rs;
276 unsigned S = 0;
277 bool Neg = false;
278
279 ExtExpr() = default;
280 ExtExpr(Register RS, bool NG, unsigned SH) : Rs(RS), S(SH), Neg(NG) {}
281 // Expression is trivial if it does not modify the extender.
282 bool trivial() const {
283 return Rs.Reg == 0;
284 }
285 bool operator==(const ExtExpr &Ex) const {
286 return Rs == Ex.Rs && S == Ex.S && Neg == Ex.Neg;
287 }
288 bool operator!=(const ExtExpr &Ex) const {
289 return !operator==(Ex);
290 }
291 bool operator<(const ExtExpr &Ex) const {
292 return std::tie(Rs, S, Neg) < std::tie(Ex.Rs, Ex.S, Ex.Neg);
293 }
294 };
295
296 struct ExtDesc {
297 MachineInstr *UseMI = nullptr;
298 unsigned OpNum = -1u;
299 // The subexpression in which the extender is used (e.g. address
300 // computation).
301 ExtExpr Expr;
302 // Optional register that is assigned the value of Expr.
303 Register Rd;
304 // Def means that the output of the instruction may differ from the
305 // original by a constant c, and that the difference can be corrected
306 // by adding/subtracting c in all users of the defined register.
307 bool IsDef = false;
308
309 MachineOperand &getOp() {
310 return UseMI->getOperand(OpNum);
311 }
312 const MachineOperand &getOp() const {
313 return UseMI->getOperand(OpNum);
314 }
315 };
316
317 struct ExtRoot {
318 union {
319 const ConstantFP *CFP; // MO_FPImmediate
320 const char *SymbolName; // MO_ExternalSymbol
321 const GlobalValue *GV; // MO_GlobalAddress
322 const BlockAddress *BA; // MO_BlockAddress
323 int64_t ImmVal; // MO_Immediate, MO_TargetIndex,
324 // and MO_ConstantPoolIndex
325 } V;
326 unsigned Kind; // Same as in MachineOperand.
327 unsigned char TF; // TargetFlags.
328
329 ExtRoot(const MachineOperand &Op);
330 bool operator==(const ExtRoot &ER) const {
331 return Kind == ER.Kind && V.ImmVal == ER.V.ImmVal;
332 }
333 bool operator!=(const ExtRoot &ER) const {
334 return !operator==(ER);
335 }
336 bool operator<(const ExtRoot &ER) const;
337 };
338
339 struct ExtValue : public ExtRoot {
340 int32_t Offset;
341
342 ExtValue(const MachineOperand &Op);
343 ExtValue(const ExtDesc &ED) : ExtValue(ED.getOp()) {}
344 ExtValue(const ExtRoot &ER, int32_t Off) : ExtRoot(ER), Offset(Off) {}
345 bool operator<(const ExtValue &EV) const;
346 bool operator==(const ExtValue &EV) const {
347 return ExtRoot(*this) == ExtRoot(EV) && Offset == EV.Offset;
348 }
349 bool operator!=(const ExtValue &EV) const {
350 return !operator==(EV);
351 }
352 explicit operator MachineOperand() const;
353 };
354
355 using IndexList = SetVector<unsigned>;
356 using ExtenderInit = std::pair<ExtValue, ExtExpr>;
357 using AssignmentMap = std::map<ExtenderInit, IndexList>;
358 using LocDefList = std::vector<std::pair<Loc, IndexList>>;
359
360 const HexagonSubtarget *HST = nullptr;
361 const HexagonInstrInfo *HII = nullptr;
362 const HexagonRegisterInfo *HRI = nullptr;
363 MachineDominatorTree *MDT = nullptr;
364 MachineRegisterInfo *MRI = nullptr;
365 std::vector<ExtDesc> Extenders;
366 std::vector<unsigned> NewRegs;
367
368 bool isStoreImmediate(unsigned Opc) const;
369 bool isRegOffOpcode(unsigned ExtOpc) const ;
370 unsigned getRegOffOpcode(unsigned ExtOpc) const;
371 unsigned getDirectRegReplacement(unsigned ExtOpc) const;
372 OffsetRange getOffsetRange(Register R, const MachineInstr &MI) const;
373 OffsetRange getOffsetRange(const ExtDesc &ED) const;
374 OffsetRange getOffsetRange(Register Rd) const;
375
376 void recordExtender(MachineInstr &MI, unsigned OpNum);
377 void collectInstr(MachineInstr &MI);
378 void collect(MachineFunction &MF);
379 void assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
380 AssignmentMap &IMap);
381 void calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
382 LocDefList &Defs);
383 Register insertInitializer(Loc DefL, const ExtenderInit &ExtI);
384 bool replaceInstrExact(const ExtDesc &ED, Register ExtR);
385 bool replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
386 Register ExtR, int32_t &Diff);
387 bool replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI);
388 bool replaceExtenders(const AssignmentMap &IMap);
389
390 unsigned getOperandIndex(const MachineInstr &MI,
391 const MachineOperand &Op) const;
392 const MachineOperand &getPredicateOp(const MachineInstr &MI) const;
393 const MachineOperand &getLoadResultOp(const MachineInstr &MI) const;
394 const MachineOperand &getStoredValueOp(const MachineInstr &MI) const;
395
396 friend struct PrintRegister;
397 friend struct PrintExpr;
398 friend struct PrintInit;
399 friend struct PrintIMap;
400 friend raw_ostream &operator<< (raw_ostream &OS,
401 const struct PrintRegister &P);
402 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintExpr &P);
403 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintInit &P);
404 friend raw_ostream &operator<< (raw_ostream &OS, const ExtDesc &ED);
405 friend raw_ostream &operator<< (raw_ostream &OS, const ExtRoot &ER);
406 friend raw_ostream &operator<< (raw_ostream &OS, const ExtValue &EV);
407 friend raw_ostream &operator<< (raw_ostream &OS, const OffsetRange &OR);
408 friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintIMap &P);
409 };
410
411 using HCE = HexagonConstExtenders;
412
413 [[maybe_unused]]
414 raw_ostream &operator<<(raw_ostream &OS, const OffsetRange &OR) {
415 if (OR.Min > OR.Max)
416 OS << '!';
417 OS << '[' << OR.Min << ',' << OR.Max << "]a" << unsigned(OR.Align)
418 << '+' << unsigned(OR.Offset);
419 return OS;
420 }
421
422 struct PrintRegister {
423 PrintRegister(HCE::Register R, const HexagonRegisterInfo &I)
424 : Rs(R), HRI(I) {}
425 HCE::Register Rs;
426 const HexagonRegisterInfo &HRI;
427 };
428
429 [[maybe_unused]]
430 raw_ostream &operator<<(raw_ostream &OS, const PrintRegister &P) {
431 if (P.Rs.Reg != 0)
432 OS << printReg(P.Rs.Reg, &P.HRI, P.Rs.Sub);
433 else
434 OS << "noreg";
435 return OS;
436 }
437
438 struct PrintExpr {
439 PrintExpr(const HCE::ExtExpr &E, const HexagonRegisterInfo &I)
440 : Ex(E), HRI(I) {}
441 const HCE::ExtExpr &Ex;
442 const HexagonRegisterInfo &HRI;
443 };
444
445 [[maybe_unused]]
446 raw_ostream &operator<<(raw_ostream &OS, const PrintExpr &P) {
447 OS << "## " << (P.Ex.Neg ? "- " : "+ ");
448 if (P.Ex.Rs.Reg != 0)
449 OS << printReg(P.Ex.Rs.Reg, &P.HRI, P.Ex.Rs.Sub);
450 else
451 OS << "__";
452 OS << " << " << P.Ex.S;
453 return OS;
454 }
455
456 struct PrintInit {
457 PrintInit(const HCE::ExtenderInit &EI, const HexagonRegisterInfo &I)
458 : ExtI(EI), HRI(I) {}
459 const HCE::ExtenderInit &ExtI;
460 const HexagonRegisterInfo &HRI;
461 };
462
463 [[maybe_unused]]
464 raw_ostream &operator<<(raw_ostream &OS, const PrintInit &P) {
465 OS << '[' << P.ExtI.first << ", "
466 << PrintExpr(P.ExtI.second, P.HRI) << ']';
467 return OS;
468 }
469
470 [[maybe_unused]]
471 raw_ostream &operator<<(raw_ostream &OS, const HCE::ExtDesc &ED) {
472 assert(ED.OpNum != -1u);
473 const MachineBasicBlock &MBB = *ED.getOp().getParent()->getParent();
474 const MachineFunction &MF = *MBB.getParent();
475 const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
476 OS << "bb#" << MBB.getNumber() << ": ";
477 if (ED.Rd.Reg != 0)
478 OS << printReg(ED.Rd.Reg, &HRI, ED.Rd.Sub);
479 else
480 OS << "__";
481 OS << " = " << PrintExpr(ED.Expr, HRI);
482 if (ED.IsDef)
483 OS << ", def";
484 return OS;
485 }
486
487 [[maybe_unused]]
488 raw_ostream &operator<<(raw_ostream &OS, const HCE::ExtRoot &ER) {
489 switch (ER.Kind) {
491 OS << "imm:" << ER.V.ImmVal;
492 break;
494 OS << "fpi:" << *ER.V.CFP;
495 break;
497 OS << "sym:" << *ER.V.SymbolName;
498 break;
500 OS << "gad:" << ER.V.GV->getName();
501 break;
503 OS << "blk:" << *ER.V.BA;
504 break;
506 OS << "tgi:" << ER.V.ImmVal;
507 break;
509 OS << "cpi:" << ER.V.ImmVal;
510 break;
512 OS << "jti:" << ER.V.ImmVal;
513 break;
514 default:
515 OS << "???:" << ER.V.ImmVal;
516 break;
517 }
518 return OS;
519 }
520
521 [[maybe_unused]]
522 raw_ostream &operator<<(raw_ostream &OS, const HCE::ExtValue &EV) {
523 OS << HCE::ExtRoot(EV) << " off:" << EV.Offset;
524 return OS;
525 }
526
527 struct PrintIMap {
528 PrintIMap(const HCE::AssignmentMap &M, const HexagonRegisterInfo &I)
529 : IMap(M), HRI(I) {}
530 const HCE::AssignmentMap &IMap;
531 const HexagonRegisterInfo &HRI;
532 };
533
534 [[maybe_unused]]
535 raw_ostream &operator<<(raw_ostream &OS, const PrintIMap &P) {
536 OS << "{\n";
537 for (const std::pair<const HCE::ExtenderInit, HCE::IndexList> &Q : P.IMap) {
538 OS << " " << PrintInit(Q.first, P.HRI) << " -> {";
539 for (unsigned I : Q.second)
540 OS << ' ' << I;
541 OS << " }\n";
542 }
543 OS << "}\n";
544 return OS;
545 }
546}
547
548INITIALIZE_PASS_BEGIN(HexagonConstExtenders, "hexagon-cext-opt",
549 "Hexagon constant-extender optimization", false, false)
551INITIALIZE_PASS_END(HexagonConstExtenders, "hexagon-cext-opt",
552 "Hexagon constant-extender optimization", false, false)
553
554static unsigned ReplaceCounter = 0;
555
556char HCE::ID = 0;
557
558#ifndef NDEBUG
559LLVM_DUMP_METHOD void RangeTree::dump() const {
560 dbgs() << "Root: " << Root << '\n';
561 if (Root)
562 dump(Root);
563}
564
565LLVM_DUMP_METHOD void RangeTree::dump(const Node *N) const {
566 dbgs() << "Node: " << N << '\n';
567 dbgs() << " Height: " << N->Height << '\n';
568 dbgs() << " Count: " << N->Count << '\n';
569 dbgs() << " MaxEnd: " << N->MaxEnd << '\n';
570 dbgs() << " Range: " << N->Range << '\n';
571 dbgs() << " Left: " << N->Left << '\n';
572 dbgs() << " Right: " << N->Right << "\n\n";
573
574 if (N->Left)
575 dump(N->Left);
576 if (N->Right)
577 dump(N->Right);
578}
579#endif
580
581void RangeTree::order(Node *N, SmallVectorImpl<Node*> &Seq) const {
582 if (N == nullptr)
583 return;
584 order(N->Left, Seq);
585 Seq.push_back(N);
586 order(N->Right, Seq);
587}
588
589void RangeTree::nodesWith(Node *N, int32_t P, bool CheckA,
590 SmallVectorImpl<Node*> &Seq) const {
591 if (N == nullptr || N->MaxEnd < P)
592 return;
593 nodesWith(N->Left, P, CheckA, Seq);
594 if (N->Range.Min <= P) {
595 if ((CheckA && N->Range.contains(P)) || (!CheckA && P <= N->Range.Max))
596 Seq.push_back(N);
597 nodesWith(N->Right, P, CheckA, Seq);
598 }
599}
600
601RangeTree::Node *RangeTree::add(Node *N, const OffsetRange &R) {
602 if (N == nullptr)
603 return new Node(R);
604
605 if (N->Range == R) {
606 N->Count++;
607 return N;
608 }
609
610 if (R < N->Range)
611 N->Left = add(N->Left, R);
612 else
613 N->Right = add(N->Right, R);
614 return rebalance(update(N));
615}
616
617RangeTree::Node *RangeTree::remove(Node *N, const Node *D) {
618 assert(N != nullptr);
619
620 if (N != D) {
621 assert(N->Range != D->Range && "N and D should not be equal");
622 if (D->Range < N->Range)
623 N->Left = remove(N->Left, D);
624 else
625 N->Right = remove(N->Right, D);
626 return rebalance(update(N));
627 }
628
629 // We got to the node we need to remove. If any of its children are
630 // missing, simply replace it with the other child.
631 if (N->Left == nullptr || N->Right == nullptr)
632 return (N->Left == nullptr) ? N->Right : N->Left;
633
634 // Find the rightmost child of N->Left, remove it and plug it in place
635 // of N.
636 Node *M = N->Left;
637 while (M->Right)
638 M = M->Right;
639 M->Left = remove(N->Left, M);
640 M->Right = N->Right;
641 return rebalance(update(M));
642}
643
644RangeTree::Node *RangeTree::rotateLeft(Node *Lower, Node *Higher) {
645 assert(Higher->Right == Lower);
646 // The Lower node is on the right from Higher. Make sure that Lower's
647 // balance is greater to the right. Otherwise the rotation will create
648 // an unbalanced tree again.
649 if (height(Lower->Left) > height(Lower->Right))
650 Lower = rotateRight(Lower->Left, Lower);
651 assert(height(Lower->Left) <= height(Lower->Right));
652 Higher->Right = Lower->Left;
653 update(Higher);
654 Lower->Left = Higher;
655 update(Lower);
656 return Lower;
657}
658
659RangeTree::Node *RangeTree::rotateRight(Node *Lower, Node *Higher) {
660 assert(Higher->Left == Lower);
661 // The Lower node is on the left from Higher. Make sure that Lower's
662 // balance is greater to the left. Otherwise the rotation will create
663 // an unbalanced tree again.
664 if (height(Lower->Left) < height(Lower->Right))
665 Lower = rotateLeft(Lower->Right, Lower);
666 assert(height(Lower->Left) >= height(Lower->Right));
667 Higher->Left = Lower->Right;
668 update(Higher);
669 Lower->Right = Higher;
670 update(Lower);
671 return Lower;
672}
673
674
675HCE::ExtRoot::ExtRoot(const MachineOperand &Op) {
676 // Always store ImmVal, since it's the field used for comparisons.
677 V.ImmVal = 0;
678 if (Op.isImm())
679 ; // Keep 0. Do not use Op.getImm() for value here (treat 0 as the root).
680 else if (Op.isFPImm())
681 V.CFP = Op.getFPImm();
682 else if (Op.isSymbol())
683 V.SymbolName = Op.getSymbolName();
684 else if (Op.isGlobal())
685 V.GV = Op.getGlobal();
686 else if (Op.isBlockAddress())
687 V.BA = Op.getBlockAddress();
688 else if (Op.isCPI() || Op.isTargetIndex() || Op.isJTI())
689 V.ImmVal = Op.getIndex();
690 else
691 llvm_unreachable("Unexpected operand type");
692
693 Kind = Op.getType();
694 TF = Op.getTargetFlags();
695}
696
697bool HCE::ExtRoot::operator< (const HCE::ExtRoot &ER) const {
698 if (Kind != ER.Kind)
699 return Kind < ER.Kind;
700 switch (Kind) {
705 return V.ImmVal < ER.V.ImmVal;
707 const APFloat &ThisF = V.CFP->getValueAPF();
708 const APFloat &OtherF = ER.V.CFP->getValueAPF();
709 return ThisF.bitcastToAPInt().ult(OtherF.bitcastToAPInt());
710 }
712 return StringRef(V.SymbolName) < StringRef(ER.V.SymbolName);
714 // Do not use GUIDs, since they depend on the source path. Moving the
715 // source file to a different directory could cause different GUID
716 // values for a pair of given symbols. These symbols could then compare
717 // "less" in one directory, but "greater" in another.
718 assert(!V.GV->getName().empty() && !ER.V.GV->getName().empty());
719 return V.GV->getName() < ER.V.GV->getName();
721 const BasicBlock *ThisB = V.BA->getBasicBlock();
722 const BasicBlock *OtherB = ER.V.BA->getBasicBlock();
723 assert(ThisB->getParent() == OtherB->getParent());
724 const Function &F = *ThisB->getParent();
725 return std::distance(F.begin(), ThisB->getIterator()) <
726 std::distance(F.begin(), OtherB->getIterator());
727 }
728 }
729 return V.ImmVal < ER.V.ImmVal;
730}
731
732HCE::ExtValue::ExtValue(const MachineOperand &Op) : ExtRoot(Op) {
733 if (Op.isImm())
734 Offset = Op.getImm();
735 else if (Op.isFPImm() || Op.isJTI())
736 Offset = 0;
737 else if (Op.isSymbol() || Op.isGlobal() || Op.isBlockAddress() ||
738 Op.isCPI() || Op.isTargetIndex())
739 Offset = Op.getOffset();
740 else
741 llvm_unreachable("Unexpected operand type");
742}
743
744bool HCE::ExtValue::operator< (const HCE::ExtValue &EV) const {
745 const ExtRoot &ER = *this;
746 if (!(ER == ExtRoot(EV)))
747 return ER < EV;
748 return Offset < EV.Offset;
749}
750
751HCE::ExtValue::operator MachineOperand() const {
752 switch (Kind) {
754 return MachineOperand::CreateImm(V.ImmVal + Offset);
756 assert(Offset == 0);
757 return MachineOperand::CreateFPImm(V.CFP);
759 assert(Offset == 0);
760 return MachineOperand::CreateES(V.SymbolName, TF);
762 return MachineOperand::CreateGA(V.GV, Offset, TF);
764 return MachineOperand::CreateBA(V.BA, Offset, TF);
766 return MachineOperand::CreateTargetIndex(V.ImmVal, Offset, TF);
768 return MachineOperand::CreateCPI(V.ImmVal, Offset, TF);
770 assert(Offset == 0);
771 return MachineOperand::CreateJTI(V.ImmVal, TF);
772 default:
773 llvm_unreachable("Unhandled kind");
774 }
775}
776
777bool HCE::isStoreImmediate(unsigned Opc) const {
778 switch (Opc) {
779 case Hexagon::S4_storeirbt_io:
780 case Hexagon::S4_storeirbf_io:
781 case Hexagon::S4_storeirht_io:
782 case Hexagon::S4_storeirhf_io:
783 case Hexagon::S4_storeirit_io:
784 case Hexagon::S4_storeirif_io:
785 case Hexagon::S4_storeirb_io:
786 case Hexagon::S4_storeirh_io:
787 case Hexagon::S4_storeiri_io:
788 return true;
789 default:
790 break;
791 }
792 return false;
793}
794
795bool HCE::isRegOffOpcode(unsigned Opc) const {
796 switch (Opc) {
797 case Hexagon::L2_loadrub_io:
798 case Hexagon::L2_loadrb_io:
799 case Hexagon::L2_loadruh_io:
800 case Hexagon::L2_loadrh_io:
801 case Hexagon::L2_loadri_io:
802 case Hexagon::L2_loadrd_io:
803 case Hexagon::L2_loadbzw2_io:
804 case Hexagon::L2_loadbzw4_io:
805 case Hexagon::L2_loadbsw2_io:
806 case Hexagon::L2_loadbsw4_io:
807 case Hexagon::L2_loadalignh_io:
808 case Hexagon::L2_loadalignb_io:
809 case Hexagon::L2_ploadrubt_io:
810 case Hexagon::L2_ploadrubf_io:
811 case Hexagon::L2_ploadrbt_io:
812 case Hexagon::L2_ploadrbf_io:
813 case Hexagon::L2_ploadruht_io:
814 case Hexagon::L2_ploadruhf_io:
815 case Hexagon::L2_ploadrht_io:
816 case Hexagon::L2_ploadrhf_io:
817 case Hexagon::L2_ploadrit_io:
818 case Hexagon::L2_ploadrif_io:
819 case Hexagon::L2_ploadrdt_io:
820 case Hexagon::L2_ploadrdf_io:
821 case Hexagon::S2_storerb_io:
822 case Hexagon::S2_storerh_io:
823 case Hexagon::S2_storerf_io:
824 case Hexagon::S2_storeri_io:
825 case Hexagon::S2_storerd_io:
826 case Hexagon::S2_pstorerbt_io:
827 case Hexagon::S2_pstorerbf_io:
828 case Hexagon::S2_pstorerht_io:
829 case Hexagon::S2_pstorerhf_io:
830 case Hexagon::S2_pstorerft_io:
831 case Hexagon::S2_pstorerff_io:
832 case Hexagon::S2_pstorerit_io:
833 case Hexagon::S2_pstorerif_io:
834 case Hexagon::S2_pstorerdt_io:
835 case Hexagon::S2_pstorerdf_io:
836 case Hexagon::A2_addi:
837 return true;
838 default:
839 break;
840 }
841 return false;
842}
843
844unsigned HCE::getRegOffOpcode(unsigned ExtOpc) const {
845 // If there exists an instruction that takes a register and offset,
846 // that corresponds to the ExtOpc, return it, otherwise return 0.
847 using namespace Hexagon;
848 switch (ExtOpc) {
849 case A2_tfrsi: return A2_addi;
850 default:
851 break;
852 }
853 const MCInstrDesc &D = HII->get(ExtOpc);
854 if (D.mayLoad() || D.mayStore()) {
855 uint64_t F = D.TSFlags;
857 switch (AM) {
861 switch (ExtOpc) {
862 case PS_loadrubabs:
863 case L4_loadrub_ap:
864 case L4_loadrub_ur: return L2_loadrub_io;
865 case PS_loadrbabs:
866 case L4_loadrb_ap:
867 case L4_loadrb_ur: return L2_loadrb_io;
868 case PS_loadruhabs:
869 case L4_loadruh_ap:
870 case L4_loadruh_ur: return L2_loadruh_io;
871 case PS_loadrhabs:
872 case L4_loadrh_ap:
873 case L4_loadrh_ur: return L2_loadrh_io;
874 case PS_loadriabs:
875 case L4_loadri_ap:
876 case L4_loadri_ur: return L2_loadri_io;
877 case PS_loadrdabs:
878 case L4_loadrd_ap:
879 case L4_loadrd_ur: return L2_loadrd_io;
880 case L4_loadbzw2_ap:
881 case L4_loadbzw2_ur: return L2_loadbzw2_io;
882 case L4_loadbzw4_ap:
883 case L4_loadbzw4_ur: return L2_loadbzw4_io;
884 case L4_loadbsw2_ap:
885 case L4_loadbsw2_ur: return L2_loadbsw2_io;
886 case L4_loadbsw4_ap:
887 case L4_loadbsw4_ur: return L2_loadbsw4_io;
888 case L4_loadalignh_ap:
889 case L4_loadalignh_ur: return L2_loadalignh_io;
890 case L4_loadalignb_ap:
891 case L4_loadalignb_ur: return L2_loadalignb_io;
892 case L4_ploadrubt_abs: return L2_ploadrubt_io;
893 case L4_ploadrubf_abs: return L2_ploadrubf_io;
894 case L4_ploadrbt_abs: return L2_ploadrbt_io;
895 case L4_ploadrbf_abs: return L2_ploadrbf_io;
896 case L4_ploadruht_abs: return L2_ploadruht_io;
897 case L4_ploadruhf_abs: return L2_ploadruhf_io;
898 case L4_ploadrht_abs: return L2_ploadrht_io;
899 case L4_ploadrhf_abs: return L2_ploadrhf_io;
900 case L4_ploadrit_abs: return L2_ploadrit_io;
901 case L4_ploadrif_abs: return L2_ploadrif_io;
902 case L4_ploadrdt_abs: return L2_ploadrdt_io;
903 case L4_ploadrdf_abs: return L2_ploadrdf_io;
904 case PS_storerbabs:
905 case S4_storerb_ap:
906 case S4_storerb_ur: return S2_storerb_io;
907 case PS_storerhabs:
908 case S4_storerh_ap:
909 case S4_storerh_ur: return S2_storerh_io;
910 case PS_storerfabs:
911 case S4_storerf_ap:
912 case S4_storerf_ur: return S2_storerf_io;
913 case PS_storeriabs:
914 case S4_storeri_ap:
915 case S4_storeri_ur: return S2_storeri_io;
916 case PS_storerdabs:
917 case S4_storerd_ap:
918 case S4_storerd_ur: return S2_storerd_io;
919 case S4_pstorerbt_abs: return S2_pstorerbt_io;
920 case S4_pstorerbf_abs: return S2_pstorerbf_io;
921 case S4_pstorerht_abs: return S2_pstorerht_io;
922 case S4_pstorerhf_abs: return S2_pstorerhf_io;
923 case S4_pstorerft_abs: return S2_pstorerft_io;
924 case S4_pstorerff_abs: return S2_pstorerff_io;
925 case S4_pstorerit_abs: return S2_pstorerit_io;
926 case S4_pstorerif_abs: return S2_pstorerif_io;
927 case S4_pstorerdt_abs: return S2_pstorerdt_io;
928 case S4_pstorerdf_abs: return S2_pstorerdf_io;
929 default:
930 break;
931 }
932 break;
934 if (!isStoreImmediate(ExtOpc))
935 return ExtOpc;
936 break;
937 default:
938 break;
939 }
940 }
941 return 0;
942}
943
944unsigned HCE::getDirectRegReplacement(unsigned ExtOpc) const {
945 switch (ExtOpc) {
946 case Hexagon::A2_addi: return Hexagon::A2_add;
947 case Hexagon::A2_andir: return Hexagon::A2_and;
948 case Hexagon::A2_combineii: return Hexagon::A4_combineri;
949 case Hexagon::A2_orir: return Hexagon::A2_or;
950 case Hexagon::A2_paddif: return Hexagon::A2_paddf;
951 case Hexagon::A2_paddit: return Hexagon::A2_paddt;
952 case Hexagon::A2_subri: return Hexagon::A2_sub;
953 case Hexagon::A2_tfrsi: return TargetOpcode::COPY;
954 case Hexagon::A4_cmpbeqi: return Hexagon::A4_cmpbeq;
955 case Hexagon::A4_cmpbgti: return Hexagon::A4_cmpbgt;
956 case Hexagon::A4_cmpbgtui: return Hexagon::A4_cmpbgtu;
957 case Hexagon::A4_cmpheqi: return Hexagon::A4_cmpheq;
958 case Hexagon::A4_cmphgti: return Hexagon::A4_cmphgt;
959 case Hexagon::A4_cmphgtui: return Hexagon::A4_cmphgtu;
960 case Hexagon::A4_combineii: return Hexagon::A4_combineir;
961 case Hexagon::A4_combineir: return TargetOpcode::REG_SEQUENCE;
962 case Hexagon::A4_combineri: return TargetOpcode::REG_SEQUENCE;
963 case Hexagon::A4_rcmpeqi: return Hexagon::A4_rcmpeq;
964 case Hexagon::A4_rcmpneqi: return Hexagon::A4_rcmpneq;
965 case Hexagon::C2_cmoveif:
966 return Hexagon::A2_tfrf;
967 case Hexagon::C2_cmoveit:
968 return Hexagon::A2_tfrt;
969 case Hexagon::C2_cmpeqi: return Hexagon::C2_cmpeq;
970 case Hexagon::C2_cmpgti: return Hexagon::C2_cmpgt;
971 case Hexagon::C2_cmpgtui: return Hexagon::C2_cmpgtu;
972 case Hexagon::C2_muxii: return Hexagon::C2_muxir;
973 case Hexagon::C2_muxir: return Hexagon::C2_mux;
974 case Hexagon::C2_muxri: return Hexagon::C2_mux;
975 case Hexagon::C4_cmpltei: return Hexagon::C4_cmplte;
976 case Hexagon::C4_cmplteui: return Hexagon::C4_cmplteu;
977 case Hexagon::C4_cmpneqi: return Hexagon::C4_cmpneq;
978 case Hexagon::M2_accii: return Hexagon::M2_acci; // T -> T
979 /* No M2_macsin */
980 case Hexagon::M2_macsip: return Hexagon::M2_maci; // T -> T
981 case Hexagon::M2_mpysin: return Hexagon::M2_mpyi;
982 case Hexagon::M2_mpysip: return Hexagon::M2_mpyi;
983 case Hexagon::M2_mpysmi: return Hexagon::M2_mpyi;
984 case Hexagon::M2_naccii: return Hexagon::M2_nacci; // T -> T
985 case Hexagon::M4_mpyri_addi: return Hexagon::M4_mpyri_addr;
986 case Hexagon::M4_mpyri_addr: return Hexagon::M4_mpyrr_addr; // _ -> T
987 case Hexagon::M4_mpyrr_addi: return Hexagon::M4_mpyrr_addr; // _ -> T
988 case Hexagon::S4_addaddi: return Hexagon::M2_acci; // _ -> T
989 case Hexagon::S4_addi_asl_ri: return Hexagon::S2_asl_i_r_acc; // T -> T
990 case Hexagon::S4_addi_lsr_ri: return Hexagon::S2_lsr_i_r_acc; // T -> T
991 case Hexagon::S4_andi_asl_ri: return Hexagon::S2_asl_i_r_and; // T -> T
992 case Hexagon::S4_andi_lsr_ri: return Hexagon::S2_lsr_i_r_and; // T -> T
993 case Hexagon::S4_ori_asl_ri: return Hexagon::S2_asl_i_r_or; // T -> T
994 case Hexagon::S4_ori_lsr_ri: return Hexagon::S2_lsr_i_r_or; // T -> T
995 case Hexagon::S4_subaddi: return Hexagon::M2_subacc; // _ -> T
996 case Hexagon::S4_subi_asl_ri: return Hexagon::S2_asl_i_r_nac; // T -> T
997 case Hexagon::S4_subi_lsr_ri: return Hexagon::S2_lsr_i_r_nac; // T -> T
998
999 // Store-immediates:
1000 case Hexagon::S4_storeirbf_io: return Hexagon::S2_pstorerbf_io;
1001 case Hexagon::S4_storeirb_io: return Hexagon::S2_storerb_io;
1002 case Hexagon::S4_storeirbt_io: return Hexagon::S2_pstorerbt_io;
1003 case Hexagon::S4_storeirhf_io: return Hexagon::S2_pstorerhf_io;
1004 case Hexagon::S4_storeirh_io: return Hexagon::S2_storerh_io;
1005 case Hexagon::S4_storeirht_io: return Hexagon::S2_pstorerht_io;
1006 case Hexagon::S4_storeirif_io: return Hexagon::S2_pstorerif_io;
1007 case Hexagon::S4_storeiri_io: return Hexagon::S2_storeri_io;
1008 case Hexagon::S4_storeirit_io: return Hexagon::S2_pstorerit_io;
1009
1010 default:
1011 break;
1012 }
1013 return 0;
1014}
1015
1016// Return the allowable deviation from the current value of Rb (i.e. the
1017// range of values that can be added to the current value) which the
1018// instruction MI can accommodate.
1019// The instruction MI is a user of register Rb, which is defined via an
1020// extender. It may be possible for MI to be tweaked to work for a register
1021// defined with a slightly different value. For example
1022// ... = L2_loadrub_io Rb, 1
1023// can be modified to be
1024// ... = L2_loadrub_io Rb', 0
1025// if Rb' = Rb+1.
1026// The range for Rb would be [Min+1, Max+1], where [Min, Max] is a range
1027// for L2_loadrub with offset 0. That means that Rb could be replaced with
1028// Rc, where Rc-Rb belongs to [Min+1, Max+1].
1029OffsetRange HCE::getOffsetRange(Register Rb, const MachineInstr &MI) const {
1030 unsigned Opc = MI.getOpcode();
1031 // Instructions that are constant-extended may be replaced with something
1032 // else that no longer offers the same range as the original.
1033 if (!isRegOffOpcode(Opc) || HII->isConstExtended(MI))
1034 return OffsetRange::zero();
1035
1036 if (Opc == Hexagon::A2_addi) {
1037 const MachineOperand &Op1 = MI.getOperand(1), &Op2 = MI.getOperand(2);
1038 if (Rb != Register(Op1) || !Op2.isImm())
1039 return OffsetRange::zero();
1040 OffsetRange R = { -(1<<15)+1, (1<<15)-1, 1 };
1041 return R.shift(Op2.getImm());
1042 }
1043
1044 // HII::getBaseAndOffsetPosition returns the increment position as "offset".
1045 if (HII->isPostIncrement(MI))
1046 return OffsetRange::zero();
1047
1048 const MCInstrDesc &D = HII->get(Opc);
1049 assert(D.mayLoad() || D.mayStore());
1050
1051 unsigned BaseP, OffP;
1052 if (!HII->getBaseAndOffsetPosition(MI, BaseP, OffP) ||
1053 Rb != Register(MI.getOperand(BaseP)) ||
1054 !MI.getOperand(OffP).isImm())
1055 return OffsetRange::zero();
1056
1057 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1060 unsigned L = Log2_32(A);
1061 unsigned S = 10+L; // sint11_L
1062 int32_t Min = -alignDown((1<<S)-1, A);
1063
1064 // The range will be shifted by Off. To prefer non-negative offsets,
1065 // adjust Max accordingly.
1066 int32_t Off = MI.getOperand(OffP).getImm();
1067 int32_t Max = Off >= 0 ? 0 : -Off;
1068
1069 OffsetRange R = { Min, Max, A };
1070 return R.shift(Off);
1071}
1072
1073// Return the allowable deviation from the current value of the extender ED,
1074// for which the instruction corresponding to ED can be modified without
1075// using an extender.
1076// The instruction uses the extender directly. It will be replaced with
1077// another instruction, say MJ, where the extender will be replaced with a
1078// register. MJ can allow some variability with respect to the value of
1079// that register, as is the case with indexed memory instructions.
1080OffsetRange HCE::getOffsetRange(const ExtDesc &ED) const {
1081 // The only way that there can be a non-zero range available is if
1082 // the instruction using ED will be converted to an indexed memory
1083 // instruction.
1084 unsigned IdxOpc = getRegOffOpcode(ED.UseMI->getOpcode());
1085 switch (IdxOpc) {
1086 case 0:
1087 return OffsetRange::zero();
1088 case Hexagon::A2_addi: // s16
1089 return { -32767, 32767, 1 };
1090 case Hexagon::A2_subri: // s10
1091 return { -511, 511, 1 };
1092 }
1093
1094 if (!ED.UseMI->mayLoad() && !ED.UseMI->mayStore())
1095 return OffsetRange::zero();
1096 const MCInstrDesc &D = HII->get(IdxOpc);
1097 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1100 unsigned L = Log2_32(A);
1101 unsigned S = 10+L; // sint11_L
1102 int32_t Min = -alignDown((1<<S)-1, A);
1103 int32_t Max = 0; // Force non-negative offsets.
1104 return { Min, Max, A };
1105}
1106
1107// Get the allowable deviation from the current value of Rd by checking
1108// all uses of Rd.
1109OffsetRange HCE::getOffsetRange(Register Rd) const {
1110 OffsetRange Range;
1111 for (const MachineOperand &Op : MRI->use_nodbg_operands(Rd.Reg)) {
1112 // Make sure that the register being used by this operand is identical
1113 // to the register that was defined: using a different subregister
1114 // precludes any non-trivial range.
1115 if (Rd != Register(Op))
1116 return OffsetRange::zero();
1117 Range.intersect(getOffsetRange(Rd, *Op.getParent()));
1118 }
1119 return Range;
1120}
1121
1122void HCE::recordExtender(MachineInstr &MI, unsigned OpNum) {
1123 unsigned Opc = MI.getOpcode();
1124 ExtDesc ED;
1125 ED.OpNum = OpNum;
1126
1127 bool IsLoad = MI.mayLoad();
1128 bool IsStore = MI.mayStore();
1129
1130 // Fixed stack slots have negative indexes, and they cannot be used
1131 // with Register::stackSlotIndex and Register::index2StackSlot. This is
1132 // somewhat unfortunate, but should not be a frequent thing.
1133 for (MachineOperand &Op : MI.operands())
1134 if (Op.isFI() && Op.getIndex() < 0)
1135 return;
1136
1137 if (IsLoad || IsStore) {
1138 unsigned AM = HII->getAddrMode(MI);
1139 switch (AM) {
1140 // (Re: ##Off + Rb<<S) = Rd: ##Val
1141 case HexagonII::Absolute: // (__: ## + __<<_)
1142 break;
1143 case HexagonII::AbsoluteSet: // (Rd: ## + __<<_)
1144 ED.Rd = MI.getOperand(OpNum-1);
1145 ED.IsDef = true;
1146 break;
1147 case HexagonII::BaseImmOffset: // (__: ## + Rs<<0)
1148 // Store-immediates are treated as non-memory operations, since
1149 // it's the value being stored that is extended (as opposed to
1150 // a part of the address).
1151 if (!isStoreImmediate(Opc))
1152 ED.Expr.Rs = MI.getOperand(OpNum-1);
1153 break;
1154 case HexagonII::BaseLongOffset: // (__: ## + Rs<<S)
1155 ED.Expr.Rs = MI.getOperand(OpNum-2);
1156 ED.Expr.S = MI.getOperand(OpNum-1).getImm();
1157 break;
1158 default:
1159 llvm_unreachable("Unhandled memory instruction");
1160 }
1161 } else {
1162 switch (Opc) {
1163 case Hexagon::A2_tfrsi: // (Rd: ## + __<<_)
1164 ED.Rd = MI.getOperand(0);
1165 ED.IsDef = true;
1166 break;
1167 case Hexagon::A2_combineii: // (Rd: ## + __<<_)
1168 case Hexagon::A4_combineir:
1169 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_hi };
1170 ED.IsDef = true;
1171 break;
1172 case Hexagon::A4_combineri: // (Rd: ## + __<<_)
1173 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_lo };
1174 ED.IsDef = true;
1175 break;
1176 case Hexagon::A2_addi: // (Rd: ## + Rs<<0)
1177 ED.Rd = MI.getOperand(0);
1178 ED.Expr.Rs = MI.getOperand(OpNum-1);
1179 break;
1180 case Hexagon::M2_accii: // (__: ## + Rs<<0)
1181 case Hexagon::M2_naccii:
1182 case Hexagon::S4_addaddi:
1183 ED.Expr.Rs = MI.getOperand(OpNum-1);
1184 break;
1185 case Hexagon::A2_subri: // (Rd: ## - Rs<<0)
1186 ED.Rd = MI.getOperand(0);
1187 ED.Expr.Rs = MI.getOperand(OpNum+1);
1188 ED.Expr.Neg = true;
1189 break;
1190 case Hexagon::S4_subaddi: // (__: ## - Rs<<0)
1191 ED.Expr.Rs = MI.getOperand(OpNum+1);
1192 ED.Expr.Neg = true;
1193 break;
1194 default: // (__: ## + __<<_)
1195 break;
1196 }
1197 }
1198
1199 ED.UseMI = &MI;
1200
1201 // Ignore unnamed globals.
1202 ExtRoot ER(ED.getOp());
1203 if (ER.Kind == MachineOperand::MO_GlobalAddress)
1204 if (ER.V.GV->getName().empty())
1205 return;
1206 // Ignore block address that points to block in another function
1207 if (ER.Kind == MachineOperand::MO_BlockAddress)
1208 if (ER.V.BA->getFunction() != &(MI.getMF()->getFunction()))
1209 return;
1210 Extenders.push_back(ED);
1211}
1212
1213void HCE::collectInstr(MachineInstr &MI) {
1214 if (!HII->isConstExtended(MI))
1215 return;
1216
1217 // Skip some non-convertible instructions.
1218 unsigned Opc = MI.getOpcode();
1219 switch (Opc) {
1220 case Hexagon::M2_macsin: // There is no Rx -= mpyi(Rs,Rt).
1221 case Hexagon::C4_addipc:
1222 case Hexagon::S4_or_andi:
1223 case Hexagon::S4_or_andix:
1224 case Hexagon::S4_or_ori:
1225 return;
1226 }
1227 recordExtender(MI, HII->getCExtOpNum(MI));
1228}
1229
1230void HCE::collect(MachineFunction &MF) {
1231 Extenders.clear();
1232 for (MachineBasicBlock &MBB : MF) {
1233 // Skip unreachable blocks.
1234 if (MBB.getNumber() == -1)
1235 continue;
1236 for (MachineInstr &MI : MBB)
1237 collectInstr(MI);
1238 }
1239}
1240
1241void HCE::assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
1242 AssignmentMap &IMap) {
1243 // Basic correctness: make sure that all extenders in the range [Begin..End)
1244 // share the same root ER.
1245 for (unsigned I = Begin; I != End; ++I)
1246 assert(ER == ExtRoot(Extenders[I].getOp()));
1247
1248 // Construct the list of ranges, such that for each P in Ranges[I],
1249 // a register Reg = ER+P can be used in place of Extender[I]. If the
1250 // instruction allows, uses in the form of Reg+Off are considered
1251 // (here, Off = required_value - P).
1252 std::vector<OffsetRange> Ranges(End-Begin);
1253
1254 // For each extender that is a def, visit all uses of the defined register,
1255 // and produce an offset range that works for all uses. The def doesn't
1256 // have to be checked, because it can become dead if all uses can be updated
1257 // to use a different reg/offset.
1258 for (unsigned I = Begin; I != End; ++I) {
1259 const ExtDesc &ED = Extenders[I];
1260 if (!ED.IsDef)
1261 continue;
1262 ExtValue EV(ED);
1263 LLVM_DEBUG(dbgs() << " =" << I << ". " << EV << " " << ED << '\n');
1264 assert(ED.Rd.Reg != 0);
1265 Ranges[I-Begin] = getOffsetRange(ED.Rd).shift(EV.Offset);
1266 // A2_tfrsi is a special case: it will be replaced with A2_addi, which
1267 // has a 16-bit signed offset. This means that A2_tfrsi not only has a
1268 // range coming from its uses, but also from the fact that its replacement
1269 // has a range as well.
1270 if (ED.UseMI->getOpcode() == Hexagon::A2_tfrsi) {
1271 int32_t D = alignDown(32767, Ranges[I-Begin].Align); // XXX hardcoded
1272 Ranges[I-Begin].extendBy(-D).extendBy(D);
1273 }
1274 }
1275
1276 // Visit all non-def extenders. For each one, determine the offset range
1277 // available for it.
1278 for (unsigned I = Begin; I != End; ++I) {
1279 const ExtDesc &ED = Extenders[I];
1280 if (ED.IsDef)
1281 continue;
1282 ExtValue EV(ED);
1283 LLVM_DEBUG(dbgs() << " " << I << ". " << EV << " " << ED << '\n');
1284 OffsetRange Dev = getOffsetRange(ED);
1285 Ranges[I-Begin].intersect(Dev.shift(EV.Offset));
1286 }
1287
1288 // Here for each I there is a corresponding Range[I]. Construct the
1289 // inverse map, that to each range will assign the set of indexes in
1290 // [Begin..End) that this range corresponds to.
1291 std::map<OffsetRange, IndexList> RangeMap;
1292 for (unsigned I = Begin; I != End; ++I)
1293 RangeMap[Ranges[I-Begin]].insert(I);
1294
1295 LLVM_DEBUG({
1296 dbgs() << "Ranges\n";
1297 for (unsigned I = Begin; I != End; ++I)
1298 dbgs() << " " << I << ". " << Ranges[I-Begin] << '\n';
1299 dbgs() << "RangeMap\n";
1300 for (auto &P : RangeMap) {
1301 dbgs() << " " << P.first << " ->";
1302 for (unsigned I : P.second)
1303 dbgs() << ' ' << I;
1304 dbgs() << '\n';
1305 }
1306 });
1307
1308 // Select the definition points, and generate the assignment between
1309 // these points and the uses.
1310
1311 RangeTree Tree;
1312 for (const OffsetRange &R : Ranges)
1313 Tree.add(R);
1315 Tree.order(Nodes);
1316
1317 auto MaxAlign = [](const SmallVectorImpl<RangeTree::Node*> &Nodes,
1319 for (RangeTree::Node *N : Nodes) {
1320 if (N->Range.Align <= Align || N->Range.Offset < Offset)
1321 continue;
1322 if ((N->Range.Offset - Offset) % Align != 0)
1323 continue;
1324 Align = N->Range.Align;
1325 Offset = N->Range.Offset;
1326 }
1327 return std::make_pair(Align, Offset);
1328 };
1329
1330 // Construct the set of all potential definition points from the endpoints
1331 // of the ranges. If a given endpoint also belongs to a different range,
1332 // but with a higher alignment, also consider the more-highly-aligned
1333 // value of this endpoint.
1334 std::set<int32_t> CandSet;
1335 for (RangeTree::Node *N : Nodes) {
1336 const OffsetRange &R = N->Range;
1337 auto P0 = MaxAlign(Tree.nodesWith(R.Min, false), R.Align, R.Offset);
1338 CandSet.insert(R.Min);
1339 if (R.Align < P0.first)
1340 CandSet.insert(adjustUp(R.Min, P0.first, P0.second));
1341 auto P1 = MaxAlign(Tree.nodesWith(R.Max, false), R.Align, R.Offset);
1342 CandSet.insert(R.Max);
1343 if (R.Align < P1.first)
1344 CandSet.insert(adjustDown(R.Max, P1.first, P1.second));
1345 }
1346
1347 // Build the assignment map: candidate C -> { list of extender indexes }.
1348 // This has to be done iteratively:
1349 // - pick the candidate that covers the maximum number of extenders,
1350 // - add the candidate to the map,
1351 // - remove the extenders from the pool.
1352 while (true) {
1353 using CMap = std::map<int32_t,unsigned>;
1354 CMap Counts;
1355 for (auto It = CandSet.begin(), Et = CandSet.end(); It != Et; ) {
1356 auto &&V = Tree.nodesWith(*It);
1357 unsigned N = std::accumulate(V.begin(), V.end(), 0u,
1358 [](unsigned Acc, const RangeTree::Node *N) {
1359 return Acc + N->Count;
1360 });
1361 if (N != 0)
1362 Counts.insert({*It, N});
1363 It = (N != 0) ? std::next(It) : CandSet.erase(It);
1364 }
1365 if (Counts.empty())
1366 break;
1367
1368 // Find the best candidate with respect to the number of extenders covered.
1369 auto BestIt = llvm::max_element(
1370 Counts, [](const CMap::value_type &A, const CMap::value_type &B) {
1371 return A.second < B.second || (A.second == B.second && A < B);
1372 });
1373 int32_t Best = BestIt->first;
1374 ExtValue BestV(ER, Best);
1375 for (RangeTree::Node *N : Tree.nodesWith(Best)) {
1376 for (unsigned I : RangeMap[N->Range])
1377 IMap[{BestV,Extenders[I].Expr}].insert(I);
1378 Tree.erase(N);
1379 }
1380 }
1381
1382 LLVM_DEBUG(dbgs() << "IMap (before fixup) = " << PrintIMap(IMap, *HRI));
1383
1384 // There is some ambiguity in what initializer should be used, if the
1385 // descriptor's subexpression is non-trivial: it can be the entire
1386 // subexpression (which is what has been done so far), or it can be
1387 // the extender's value itself, if all corresponding extenders have the
1388 // exact value of the initializer (i.e. require offset of 0).
1389
1390 // To reduce the number of initializers, merge such special cases.
1391 for (std::pair<const ExtenderInit,IndexList> &P : IMap) {
1392 // Skip trivial initializers.
1393 if (P.first.second.trivial())
1394 continue;
1395 // If the corresponding trivial initializer does not exist, skip this
1396 // entry.
1397 const ExtValue &EV = P.first.first;
1398 AssignmentMap::iterator F = IMap.find({EV, ExtExpr()});
1399 if (F == IMap.end())
1400 continue;
1401
1402 // Finally, check if all extenders have the same value as the initializer.
1403 // Make sure that extenders that are a part of a stack address are not
1404 // merged with those that aren't. Stack addresses need an offset field
1405 // (to be used by frame index elimination), while non-stack expressions
1406 // can be replaced with forms (such as rr) that do not have such a field.
1407 // Example:
1408 //
1409 // Collected 3 extenders
1410 // =2. imm:0 off:32968 bb#2: %7 = ## + __ << 0, def
1411 // 0. imm:0 off:267 bb#0: __ = ## + SS#1 << 0
1412 // 1. imm:0 off:267 bb#1: __ = ## + SS#1 << 0
1413 // Ranges
1414 // 0. [-756,267]a1+0
1415 // 1. [-756,267]a1+0
1416 // 2. [201,65735]a1+0
1417 // RangeMap
1418 // [-756,267]a1+0 -> 0 1
1419 // [201,65735]a1+0 -> 2
1420 // IMap (before fixup) = {
1421 // [imm:0 off:267, ## + __ << 0] -> { 2 }
1422 // [imm:0 off:267, ## + SS#1 << 0] -> { 0 1 }
1423 // }
1424 // IMap (after fixup) = {
1425 // [imm:0 off:267, ## + __ << 0] -> { 2 0 1 }
1426 // [imm:0 off:267, ## + SS#1 << 0] -> { }
1427 // }
1428 // Inserted def in bb#0 for initializer: [imm:0 off:267, ## + __ << 0]
1429 // %12:intregs = A2_tfrsi 267
1430 //
1431 // The result was
1432 // %12:intregs = A2_tfrsi 267
1433 // S4_pstorerbt_rr %3, %12, %stack.1, 0, killed %4
1434 // Which became
1435 // r0 = #267
1436 // if (p0.new) memb(r0+r29<<#4) = r2
1437
1438 bool IsStack = any_of(F->second, [this](unsigned I) {
1439 return Extenders[I].Expr.Rs.isSlot();
1440 });
1441 auto SameValue = [&EV,this,IsStack](unsigned I) {
1442 const ExtDesc &ED = Extenders[I];
1443 return ED.Expr.Rs.isSlot() == IsStack &&
1444 ExtValue(ED).Offset == EV.Offset;
1445 };
1446 if (all_of(P.second, SameValue)) {
1447 F->second.insert_range(P.second);
1448 P.second.clear();
1449 }
1450 }
1451
1452 LLVM_DEBUG(dbgs() << "IMap (after fixup) = " << PrintIMap(IMap, *HRI));
1453}
1454
1455void HCE::calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
1456 LocDefList &Defs) {
1457 if (Refs.empty())
1458 return;
1459
1460 // The placement calculation is somewhat simple right now: it finds a
1461 // single location for the def that dominates all refs. Since this may
1462 // place the def far from the uses, producing several locations for
1463 // defs that collectively dominate all refs could be better.
1464 // For now only do the single one.
1467 const ExtDesc &ED0 = Extenders[Refs[0]];
1468 MachineBasicBlock *DomB = ED0.UseMI->getParent();
1469 RefMIs.insert(ED0.UseMI);
1470 Blocks.insert(DomB);
1471 for (unsigned i = 1, e = Refs.size(); i != e; ++i) {
1472 const ExtDesc &ED = Extenders[Refs[i]];
1473 MachineBasicBlock *MBB = ED.UseMI->getParent();
1474 RefMIs.insert(ED.UseMI);
1475 DomB = MDT->findNearestCommonDominator(DomB, MBB);
1476 Blocks.insert(MBB);
1477 }
1478
1479#ifndef NDEBUG
1480 // The block DomB should be dominated by the def of each register used
1481 // in the initializer.
1482 Register Rs = ExtI.second.Rs; // Only one reg allowed now.
1483 const MachineInstr *DefI = Rs.isVReg() ? MRI->getVRegDef(Rs.Reg) : nullptr;
1484
1485 // This should be guaranteed given that the entire expression is used
1486 // at each instruction in Refs. Add an assertion just in case.
1487 assert(!DefI || MDT->dominates(DefI->getParent(), DomB));
1488#endif
1489
1491 if (Blocks.count(DomB)) {
1492 // Try to find the latest possible location for the def.
1494 for (It = DomB->begin(); It != End; ++It)
1495 if (RefMIs.count(&*It))
1496 break;
1497 assert(It != End && "Should have found a ref in DomB");
1498 } else {
1499 // DomB does not contain any refs.
1500 It = DomB->getFirstTerminator();
1501 }
1502 Loc DefLoc(DomB, It);
1503 Defs.emplace_back(DefLoc, Refs);
1504}
1505
1506HCE::Register HCE::insertInitializer(Loc DefL, const ExtenderInit &ExtI) {
1507 llvm::Register DefR = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1508 MachineBasicBlock &MBB = *DefL.Block;
1509 MachineBasicBlock::iterator At = DefL.At;
1510 DebugLoc dl = DefL.Block->findDebugLoc(DefL.At);
1511 const ExtValue &EV = ExtI.first;
1512 MachineOperand ExtOp(EV);
1513
1514 const ExtExpr &Ex = ExtI.second;
1515 const MachineInstr *InitI = nullptr;
1516
1517 if (Ex.Rs.isSlot()) {
1518 assert(Ex.S == 0 && "Cannot have a shift of a stack slot");
1519 assert(!Ex.Neg && "Cannot subtract a stack slot");
1520 // DefR = PS_fi Rb,##EV
1521 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::PS_fi), DefR)
1522 .add(MachineOperand(Ex.Rs))
1523 .add(ExtOp);
1524 } else {
1525 assert((Ex.Rs.Reg == 0 || Ex.Rs.isVReg()) && "Expecting virtual register");
1526 if (Ex.trivial()) {
1527 // DefR = ##EV
1528 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_tfrsi), DefR)
1529 .add(ExtOp);
1530 } else if (Ex.S == 0) {
1531 if (Ex.Neg) {
1532 // DefR = sub(##EV,Rb)
1533 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_subri), DefR)
1534 .add(ExtOp)
1535 .add(MachineOperand(Ex.Rs));
1536 } else {
1537 // DefR = add(Rb,##EV)
1538 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_addi), DefR)
1539 .add(MachineOperand(Ex.Rs))
1540 .add(ExtOp);
1541 }
1542 } else {
1543 if (HST->useCompound()) {
1544 unsigned NewOpc = Ex.Neg ? Hexagon::S4_subi_asl_ri
1545 : Hexagon::S4_addi_asl_ri;
1546 // DefR = add(##EV,asl(Rb,S))
1547 InitI = BuildMI(MBB, At, dl, HII->get(NewOpc), DefR)
1548 .add(ExtOp)
1549 .add(MachineOperand(Ex.Rs))
1550 .addImm(Ex.S);
1551 } else {
1552 // No compounds are available. It is not clear whether we should
1553 // even process such extenders where the initializer cannot be
1554 // a single instruction, but do it for now.
1555 llvm::Register TmpR = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1556 BuildMI(MBB, At, dl, HII->get(Hexagon::S2_asl_i_r), TmpR)
1557 .add(MachineOperand(Ex.Rs))
1558 .addImm(Ex.S);
1559 if (Ex.Neg)
1560 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_subri), DefR)
1561 .add(ExtOp)
1562 .add(MachineOperand(Register(TmpR, 0)));
1563 else
1564 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_addi), DefR)
1565 .add(MachineOperand(Register(TmpR, 0)))
1566 .add(ExtOp);
1567 }
1568 }
1569 }
1570
1571 assert(InitI);
1572 (void)InitI;
1573 LLVM_DEBUG(dbgs() << "Inserted def in bb#" << MBB.getNumber()
1574 << " for initializer: " << PrintInit(ExtI, *HRI) << "\n "
1575 << *InitI);
1576 return { DefR, 0 };
1577}
1578
1579// Replace the extender at index Idx with the register ExtR.
1580bool HCE::replaceInstrExact(const ExtDesc &ED, Register ExtR) {
1581 MachineInstr &MI = *ED.UseMI;
1582 MachineBasicBlock &MBB = *MI.getParent();
1583 MachineBasicBlock::iterator At = MI.getIterator();
1584 DebugLoc dl = MI.getDebugLoc();
1585 unsigned ExtOpc = MI.getOpcode();
1586
1587 // With a few exceptions, direct replacement amounts to creating an
1588 // instruction with a corresponding register opcode, with all operands
1589 // the same, except for the register used in place of the extender.
1590 unsigned RegOpc = getDirectRegReplacement(ExtOpc);
1591
1592 if (RegOpc == TargetOpcode::REG_SEQUENCE) {
1593 if (ExtOpc == Hexagon::A4_combineri)
1594 BuildMI(MBB, At, dl, HII->get(RegOpc))
1595 .add(MI.getOperand(0))
1596 .add(MI.getOperand(1))
1597 .addImm(Hexagon::isub_hi)
1598 .add(MachineOperand(ExtR))
1599 .addImm(Hexagon::isub_lo);
1600 else if (ExtOpc == Hexagon::A4_combineir)
1601 BuildMI(MBB, At, dl, HII->get(RegOpc))
1602 .add(MI.getOperand(0))
1603 .add(MachineOperand(ExtR))
1604 .addImm(Hexagon::isub_hi)
1605 .add(MI.getOperand(2))
1606 .addImm(Hexagon::isub_lo);
1607 else
1608 llvm_unreachable("Unexpected opcode became REG_SEQUENCE");
1609 MBB.erase(MI);
1610 return true;
1611 }
1612 if (ExtOpc == Hexagon::C2_cmpgei || ExtOpc == Hexagon::C2_cmpgeui) {
1613 unsigned NewOpc = ExtOpc == Hexagon::C2_cmpgei ? Hexagon::C2_cmplt
1614 : Hexagon::C2_cmpltu;
1615 BuildMI(MBB, At, dl, HII->get(NewOpc))
1616 .add(MI.getOperand(0))
1617 .add(MachineOperand(ExtR))
1618 .add(MI.getOperand(1));
1619 MBB.erase(MI);
1620 return true;
1621 }
1622
1623 if (RegOpc != 0) {
1624 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1625 unsigned RegN = ED.OpNum;
1626 // Copy all operands except the one that has the extender.
1627 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1628 if (i != RegN)
1629 MIB.add(MI.getOperand(i));
1630 else
1631 MIB.add(MachineOperand(ExtR));
1632 }
1633 MIB.cloneMemRefs(MI);
1634 MBB.erase(MI);
1635 return true;
1636 }
1637
1638 if (MI.mayLoadOrStore() && !isStoreImmediate(ExtOpc)) {
1639 // For memory instructions, there is an asymmetry in the addressing
1640 // modes. Addressing modes allowing extenders can be replaced with
1641 // addressing modes that use registers, but the order of operands
1642 // (or even their number) may be different.
1643 // Replacements:
1644 // BaseImmOffset (io) -> BaseRegOffset (rr)
1645 // BaseLongOffset (ur) -> BaseRegOffset (rr)
1646 unsigned RegOpc, Shift;
1647 unsigned AM = HII->getAddrMode(MI);
1648 if (AM == HexagonII::BaseImmOffset) {
1649 RegOpc = HII->changeAddrMode_io_rr(ExtOpc);
1650 Shift = 0;
1651 } else if (AM == HexagonII::BaseLongOffset) {
1652 // Loads: Rd = L4_loadri_ur Rs, S, ##
1653 // Stores: S4_storeri_ur Rs, S, ##, Rt
1654 RegOpc = HII->changeAddrMode_ur_rr(ExtOpc);
1655 Shift = MI.getOperand(MI.mayLoad() ? 2 : 1).getImm();
1656 } else {
1657 llvm_unreachable("Unexpected addressing mode");
1658 }
1659#ifndef NDEBUG
1660 if (RegOpc == -1u) {
1661 dbgs() << "\nExtOpc: " << HII->getName(ExtOpc) << " has no rr version\n";
1662 llvm_unreachable("No corresponding rr instruction");
1663 }
1664#endif
1665
1666 unsigned BaseP, OffP;
1667 HII->getBaseAndOffsetPosition(MI, BaseP, OffP);
1668
1669 // Build an rr instruction: (RegOff + RegBase<<0)
1670 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1671 // First, add the def for loads.
1672 if (MI.mayLoad())
1673 MIB.add(getLoadResultOp(MI));
1674 // Handle possible predication.
1675 if (HII->isPredicated(MI))
1676 MIB.add(getPredicateOp(MI));
1677 // Build the address.
1678 MIB.add(MachineOperand(ExtR)); // RegOff
1679 MIB.add(MI.getOperand(BaseP)); // RegBase
1680 MIB.addImm(Shift); // << Shift
1681 // Add the stored value for stores.
1682 if (MI.mayStore())
1683 MIB.add(getStoredValueOp(MI));
1684 MIB.cloneMemRefs(MI);
1685 MBB.erase(MI);
1686 return true;
1687 }
1688
1689#ifndef NDEBUG
1690 dbgs() << '\n' << MI;
1691#endif
1692 llvm_unreachable("Unhandled exact replacement");
1693 return false;
1694}
1695
1696// Replace the extender ED with a form corresponding to the initializer ExtI.
1697bool HCE::replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
1698 Register ExtR, int32_t &Diff) {
1699 MachineInstr &MI = *ED.UseMI;
1700 MachineBasicBlock &MBB = *MI.getParent();
1701 MachineBasicBlock::iterator At = MI.getIterator();
1702 DebugLoc dl = MI.getDebugLoc();
1703 unsigned ExtOpc = MI.getOpcode();
1704
1705 if (ExtOpc == Hexagon::A2_tfrsi) {
1706 // A2_tfrsi is a special case: it's replaced with A2_addi, which introduces
1707 // another range. One range is the one that's common to all tfrsi's uses,
1708 // this one is the range of immediates in A2_addi. When calculating ranges,
1709 // the addi's 16-bit argument was included, so now we need to make it such
1710 // that the produced value is in the range for the uses alone.
1711 // Most of the time, simply adding Diff will make the addi produce exact
1712 // result, but if Diff is outside of the 16-bit range, some adjustment
1713 // will be needed.
1714 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1715 assert(IdxOpc == Hexagon::A2_addi);
1716
1717 // Clamp Diff to the 16 bit range.
1718 int32_t D = isInt<16>(Diff) ? Diff : (Diff > 0 ? 32767 : -32768);
1719 if (Diff > 32767) {
1720 // Split Diff into two values: one that is close to min/max int16,
1721 // and the other being the rest, and such that both have the same
1722 // "alignment" as Diff.
1723 uint32_t UD = Diff;
1724 OffsetRange R = getOffsetRange(MI.getOperand(0));
1725 uint32_t A = std::min<uint32_t>(R.Align, 1u << llvm::countr_zero(UD));
1726 D &= ~(A-1);
1727 }
1728 BuildMI(MBB, At, dl, HII->get(IdxOpc))
1729 .add(MI.getOperand(0))
1730 .add(MachineOperand(ExtR))
1731 .addImm(D);
1732 Diff -= D;
1733#ifndef NDEBUG
1734 // Make sure the output is within allowable range for uses.
1735 // "Diff" is a difference in the "opposite direction", i.e. Ext - DefV,
1736 // not DefV - Ext, as the getOffsetRange would calculate.
1737 OffsetRange Uses = getOffsetRange(MI.getOperand(0));
1738 if (!Uses.contains(-Diff))
1739 dbgs() << "Diff: " << -Diff << " out of range " << Uses
1740 << " for " << MI;
1741 assert(Uses.contains(-Diff));
1742#endif
1743 MBB.erase(MI);
1744 return true;
1745 }
1746
1747 const ExtValue &EV = ExtI.first; (void)EV;
1748 const ExtExpr &Ex = ExtI.second; (void)Ex;
1749
1750 if (ExtOpc == Hexagon::A2_addi || ExtOpc == Hexagon::A2_subri) {
1751 // If addi/subri are replaced with the exactly matching initializer,
1752 // they amount to COPY.
1753 // Check that the initializer is an exact match (for simplicity).
1754#ifndef NDEBUG
1755 bool IsAddi = ExtOpc == Hexagon::A2_addi;
1756 const MachineOperand &RegOp = MI.getOperand(IsAddi ? 1 : 2);
1757 const MachineOperand &ImmOp = MI.getOperand(IsAddi ? 2 : 1);
1758 assert(Ex.Rs == RegOp && EV == ImmOp && Ex.Neg != IsAddi &&
1759 "Initializer mismatch");
1760#endif
1761 BuildMI(MBB, At, dl, HII->get(TargetOpcode::COPY))
1762 .add(MI.getOperand(0))
1763 .add(MachineOperand(ExtR));
1764 Diff = 0;
1765 MBB.erase(MI);
1766 return true;
1767 }
1768 if (ExtOpc == Hexagon::M2_accii || ExtOpc == Hexagon::M2_naccii ||
1769 ExtOpc == Hexagon::S4_addaddi || ExtOpc == Hexagon::S4_subaddi) {
1770 // M2_accii: add(Rt,add(Rs,V)) (tied)
1771 // M2_naccii: sub(Rt,add(Rs,V))
1772 // S4_addaddi: add(Rt,add(Rs,V))
1773 // S4_subaddi: add(Rt,sub(V,Rs))
1774 // Check that Rs and V match the initializer expression. The Rs+V is the
1775 // combination that is considered "subexpression" for V, although Rx+V
1776 // would also be valid.
1777#ifndef NDEBUG
1778 bool IsSub = ExtOpc == Hexagon::S4_subaddi;
1779 Register Rs = MI.getOperand(IsSub ? 3 : 2);
1780 ExtValue V = MI.getOperand(IsSub ? 2 : 3);
1781 assert(EV == V && Rs == Ex.Rs && IsSub == Ex.Neg && "Initializer mismatch");
1782#endif
1783 unsigned NewOpc = ExtOpc == Hexagon::M2_naccii ? Hexagon::A2_sub
1784 : Hexagon::A2_add;
1785 BuildMI(MBB, At, dl, HII->get(NewOpc))
1786 .add(MI.getOperand(0))
1787 .add(MI.getOperand(1))
1788 .add(MachineOperand(ExtR));
1789 MBB.erase(MI);
1790 return true;
1791 }
1792
1793 if (MI.mayLoadOrStore()) {
1794 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1795 assert(IdxOpc && "Expecting indexed opcode");
1796 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(IdxOpc));
1797 // Construct the new indexed instruction.
1798 // First, add the def for loads.
1799 if (MI.mayLoad())
1800 MIB.add(getLoadResultOp(MI));
1801 // Handle possible predication.
1802 if (HII->isPredicated(MI))
1803 MIB.add(getPredicateOp(MI));
1804 // Build the address.
1805 MIB.add(MachineOperand(ExtR));
1806 MIB.addImm(Diff);
1807 // Add the stored value for stores.
1808 if (MI.mayStore())
1809 MIB.add(getStoredValueOp(MI));
1810 MIB.cloneMemRefs(MI);
1811 MBB.erase(MI);
1812 return true;
1813 }
1814
1815#ifndef NDEBUG
1816 dbgs() << '\n' << PrintInit(ExtI, *HRI) << " " << MI;
1817#endif
1818 llvm_unreachable("Unhandled expr replacement");
1819 return false;
1820}
1821
1822bool HCE::replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI) {
1823 if (HST->getCLOpts().cext_limit) {
1824 if (*HST->getCLOpts().cext_limit <= ReplaceCounter)
1825 return false;
1827 }
1828 const ExtDesc &ED = Extenders[Idx];
1829 assert((!ED.IsDef || ED.Rd.Reg != 0) && "Missing Rd for def");
1830 const ExtValue &DefV = ExtI.first;
1831 assert(ExtRoot(ExtValue(ED)) == ExtRoot(DefV) && "Extender root mismatch");
1832 const ExtExpr &DefEx = ExtI.second;
1833
1834 ExtValue EV(ED);
1835 int32_t Diff = EV.Offset - DefV.Offset;
1836 const MachineInstr &MI = *ED.UseMI;
1837 LLVM_DEBUG(dbgs() << __func__ << " Idx:" << Idx << " ExtR:"
1838 << PrintRegister(ExtR, *HRI) << " Diff:" << Diff << '\n');
1839
1840 // These two addressing modes must be converted into indexed forms
1841 // regardless of what the initializer looks like.
1842 bool IsAbs = false, IsAbsSet = false;
1843 if (MI.mayLoadOrStore()) {
1844 unsigned AM = HII->getAddrMode(MI);
1845 IsAbs = AM == HexagonII::Absolute;
1846 IsAbsSet = AM == HexagonII::AbsoluteSet;
1847 }
1848
1849 // If it's a def, remember all operands that need to be updated.
1850 // If ED is a def, and Diff is not 0, then all uses of the register Rd
1851 // defined by ED must be in the form (Rd, imm), i.e. the immediate offset
1852 // must follow the Rd in the operand list.
1853 std::vector<std::pair<MachineInstr*,unsigned>> RegOps;
1854 if (ED.IsDef && Diff != 0) {
1855 for (MachineOperand &Op : MRI->use_nodbg_operands(ED.Rd.Reg)) {
1856 MachineInstr &UI = *Op.getParent();
1857 RegOps.push_back({&UI, getOperandIndex(UI, Op)});
1858 }
1859 }
1860
1861 // Replace the instruction.
1862 bool Replaced = false;
1863 if (Diff == 0 && DefEx.trivial() && !IsAbs && !IsAbsSet)
1864 Replaced = replaceInstrExact(ED, ExtR);
1865 else
1866 Replaced = replaceInstrExpr(ED, ExtI, ExtR, Diff);
1867
1868 if (Diff != 0 && Replaced && ED.IsDef) {
1869 // Update offsets of the def's uses.
1870 for (std::pair<MachineInstr*,unsigned> P : RegOps) {
1871 unsigned J = P.second;
1872 assert(P.first->getNumOperands() > J+1 &&
1873 P.first->getOperand(J+1).isImm());
1874 MachineOperand &ImmOp = P.first->getOperand(J+1);
1875 ImmOp.setImm(ImmOp.getImm() + Diff);
1876 }
1877 // If it was an absolute-set instruction, the "set" part has been removed.
1878 // ExtR will now be the register with the extended value, and since all
1879 // users of Rd have been updated, all that needs to be done is to replace
1880 // Rd with ExtR.
1881 if (IsAbsSet) {
1882 assert(ED.Rd.Sub == 0 && ExtR.Sub == 0);
1883 MRI->replaceRegWith(ED.Rd.Reg, ExtR.Reg);
1884 }
1885 }
1886
1887 return Replaced;
1888}
1889
1890bool HCE::replaceExtenders(const AssignmentMap &IMap) {
1891 LocDefList Defs;
1892 bool Changed = false;
1893
1894 for (const std::pair<const ExtenderInit, IndexList> &P : IMap) {
1895 const IndexList &Idxs = P.second;
1896 if (Idxs.size() < HST->getCLOpts().cext_threshold)
1897 continue;
1898
1899 Defs.clear();
1900 calculatePlacement(P.first, Idxs, Defs);
1901 for (const std::pair<Loc,IndexList> &Q : Defs) {
1902 Register DefR = insertInitializer(Q.first, P.first);
1903 NewRegs.push_back(DefR.Reg);
1904 for (unsigned I : Q.second)
1905 Changed |= replaceInstr(I, DefR, P.first);
1906 }
1907 }
1908 return Changed;
1909}
1910
1911unsigned HCE::getOperandIndex(const MachineInstr &MI,
1912 const MachineOperand &Op) const {
1913 for (unsigned i = 0, n = MI.getNumOperands(); i != n; ++i)
1914 if (&MI.getOperand(i) == &Op)
1915 return i;
1916 llvm_unreachable("Not an operand of MI");
1917}
1918
1919const MachineOperand &HCE::getPredicateOp(const MachineInstr &MI) const {
1920 assert(HII->isPredicated(MI));
1921 for (const MachineOperand &Op : MI.operands()) {
1922 if (!Op.isReg() || !Op.isUse() ||
1923 MRI->getRegClass(Op.getReg()) != &Hexagon::PredRegsRegClass)
1924 continue;
1925 assert(Op.getSubReg() == 0 && "Predicate register with a subregister");
1926 return Op;
1927 }
1928 llvm_unreachable("Predicate operand not found");
1929}
1930
1931const MachineOperand &HCE::getLoadResultOp(const MachineInstr &MI) const {
1932 assert(MI.mayLoad());
1933 return MI.getOperand(0);
1934}
1935
1936const MachineOperand &HCE::getStoredValueOp(const MachineInstr &MI) const {
1937 assert(MI.mayStore());
1938 return MI.getOperand(MI.getNumExplicitOperands()-1);
1939}
1940
1941bool HCE::runOnMachineFunction(MachineFunction &MF) {
1942 if (skipFunction(MF.getFunction()))
1943 return false;
1944 if (MF.getFunction().hasPersonalityFn()) {
1945 LLVM_DEBUG(dbgs() << getPassName() << ": skipping " << MF.getName()
1946 << " due to exception handling\n");
1947 return false;
1948 }
1949 LLVM_DEBUG(MF.print(dbgs() << "Before " << getPassName() << '\n', nullptr));
1950
1951 HST = &MF.getSubtarget<HexagonSubtarget>();
1952 HII = HST->getInstrInfo();
1953 HRI = HST->getRegisterInfo();
1954 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1955 MRI = &MF.getRegInfo();
1956 AssignmentMap IMap;
1957
1958 collect(MF);
1959 llvm::sort(Extenders, [this](const ExtDesc &A, const ExtDesc &B) {
1960 ExtValue VA(A), VB(B);
1961 if (VA != VB)
1962 return VA < VB;
1963 const MachineInstr *MA = A.UseMI;
1964 const MachineInstr *MB = B.UseMI;
1965 if (MA == MB) {
1966 // If it's the same instruction, compare operand numbers.
1967 return A.OpNum < B.OpNum;
1968 }
1969
1970 const MachineBasicBlock *BA = MA->getParent();
1971 const MachineBasicBlock *BB = MB->getParent();
1972 assert(BA->getNumber() != -1 && BB->getNumber() != -1);
1973 if (BA != BB)
1974 return BA->getNumber() < BB->getNumber();
1975 return MDT->dominates(MA, MB);
1976 });
1977
1978 bool Changed = false;
1979 LLVM_DEBUG(dbgs() << "Collected " << Extenders.size() << " extenders\n");
1980 for (unsigned I = 0, E = Extenders.size(); I != E; ) {
1981 unsigned B = I;
1982 const ExtRoot &T = Extenders[B].getOp();
1983 while (I != E && ExtRoot(Extenders[I].getOp()) == T)
1984 ++I;
1985
1986 IMap.clear();
1987 assignInits(T, B, I, IMap);
1988 Changed |= replaceExtenders(IMap);
1989 }
1990
1991 LLVM_DEBUG({
1992 if (Changed)
1993 MF.print(dbgs() << "After " << getPassName() << '\n', nullptr);
1994 else
1995 dbgs() << "No changes\n";
1996 });
1997 return Changed;
1998}
1999
2001 return new HexagonConstExtenders();
2002}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
bpf unwind BPF Unwind Lower
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
static void zero(T &Obj)
hexagon cext Hexagon constant extender static false unsigned ReplaceCounter
static int32_t adjustUp(int32_t V, uint8_t A, uint8_t O)
static int32_t adjustDown(int32_t V, uint8_t A, uint8_t O)
IRTranslator LLVM IR MI
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
static Interval intersect(const Interval &I1, const Interval &I2)
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
APInt bitcastToAPInt() const
Definition APFloat.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
const HexagonRegisterInfo & getRegisterInfo() const
const HexagonInstrInfo * getInstrInfo() const override
Describe properties that are true of each instruction in the target description file.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
static MachineOperand CreateFPImm(const ConstantFP *CFP)
void setImm(int64_t immVal)
int64_t getImm() const
static MachineOperand CreateImm(int64_t Val)
static MachineOperand CreateJTI(unsigned Idx, unsigned TargetFlags=0)
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_FPImmediate
Floating-point immediate operand.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateFI(int Idx)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2StackSlot(int FI)
Convert a frame index to a stack slot register value.
Definition Register.h:51
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
static unsigned getMemAccessSizeInBytes(MemAccessSize S)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool empty() const
Definition BasicBlock.h:101
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
FunctionPass * createHexagonConstExtenders()
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
@ Off
Use window algorithm after SMS algorithm fails.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39