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