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