xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonConstExtenders.cpp (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
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/SmallVector.h"
13 #include "llvm/CodeGen/MachineDominators.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/CodeGen/Register.h"
18 #include "llvm/InitializePasses.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <map>
23 #include <set>
24 #include <utility>
25 #include <vector>
26 
27 #define DEBUG_TYPE "hexagon-cext-opt"
28 
29 using namespace llvm;
30 
31 static cl::opt<unsigned> CountThreshold("hexagon-cext-threshold",
32   cl::init(3), cl::Hidden, cl::ZeroOrMore,
33   cl::desc("Minimum number of extenders to trigger replacement"));
34 
35 static cl::opt<unsigned> ReplaceLimit("hexagon-cext-limit", cl::init(0),
36   cl::Hidden, cl::ZeroOrMore, cl::desc("Maximum number of replacements"));
37 
38 namespace llvm {
39   void initializeHexagonConstExtendersPass(PassRegistry&);
40   FunctionPass *createHexagonConstExtenders();
41 }
42 
43 static int32_t adjustUp(int32_t V, uint8_t A, uint8_t O) {
44   assert(isPowerOf2_32(A));
45   int32_t U = (V & -A) + O;
46   return U >= V ? U : U+A;
47 }
48 
49 static int32_t adjustDown(int32_t V, uint8_t A, uint8_t O) {
50   assert(isPowerOf2_32(A));
51   int32_t U = (V & -A) + O;
52   return U <= V ? U : U-A;
53 }
54 
55 namespace {
56   struct OffsetRange {
57     // The range of values between Min and Max that are of form Align*N+Offset,
58     // for some integer N. Min and Max are required to be of that form as well,
59     // except in the case of an empty range.
60     int32_t Min = INT_MIN, Max = INT_MAX;
61     uint8_t Align = 1;
62     uint8_t Offset = 0;
63 
64     OffsetRange() = default;
65     OffsetRange(int32_t L, int32_t H, uint8_t A, uint8_t O = 0)
66       : Min(L), Max(H), Align(A), Offset(O) {}
67     OffsetRange &intersect(OffsetRange A) {
68       if (Align < A.Align)
69         std::swap(*this, A);
70 
71       // Align >= A.Align.
72       if (Offset >= A.Offset && (Offset - A.Offset) % A.Align == 0) {
73         Min = adjustUp(std::max(Min, A.Min), Align, Offset);
74         Max = adjustDown(std::min(Max, A.Max), Align, Offset);
75       } else {
76         // Make an empty range.
77         Min = 0;
78         Max = -1;
79       }
80       // Canonicalize empty ranges.
81       if (Min > Max)
82         std::tie(Min, Max, Align) = std::make_tuple(0, -1, 1);
83       return *this;
84     }
85     OffsetRange &shift(int32_t S) {
86       Min += S;
87       Max += S;
88       Offset = (Offset+S) % Align;
89       return *this;
90     }
91     OffsetRange &extendBy(int32_t D) {
92       // If D < 0, extend Min, otherwise extend Max.
93       assert(D % Align == 0);
94       if (D < 0)
95         Min = (INT_MIN-D < Min) ? Min+D : INT_MIN;
96       else
97         Max = (INT_MAX-D > Max) ? Max+D : INT_MAX;
98       return *this;
99     }
100     bool empty() const {
101       return Min > Max;
102     }
103     bool contains(int32_t V) const {
104       return Min <= V && V <= Max && (V-Offset) % Align == 0;
105     }
106     bool operator==(const OffsetRange &R) const {
107       return Min == R.Min && Max == R.Max && Align == R.Align;
108     }
109     bool operator!=(const OffsetRange &R) const {
110       return !operator==(R);
111     }
112     bool operator<(const OffsetRange &R) const {
113       if (Min != R.Min)
114         return Min < R.Min;
115       if (Max != R.Max)
116         return Max < R.Max;
117       return Align < R.Align;
118     }
119     static OffsetRange zero() { return {0, 0, 1}; }
120   };
121 
122   struct RangeTree {
123     struct Node {
124       Node(const OffsetRange &R) : MaxEnd(R.Max), Range(R) {}
125       unsigned Height = 1;
126       unsigned Count = 1;
127       int32_t MaxEnd;
128       const OffsetRange &Range;
129       Node *Left = nullptr, *Right = nullptr;
130     };
131 
132     Node *Root = nullptr;
133 
134     void add(const OffsetRange &R) {
135       Root = add(Root, R);
136     }
137     void erase(const Node *N) {
138       Root = remove(Root, N);
139       delete N;
140     }
141     void order(SmallVectorImpl<Node*> &Seq) const {
142       order(Root, Seq);
143     }
144     SmallVector<Node*,8> nodesWith(int32_t P, bool CheckAlign = true) {
145       SmallVector<Node*,8> Nodes;
146       nodesWith(Root, P, CheckAlign, Nodes);
147       return Nodes;
148     }
149     void dump() const;
150     ~RangeTree() {
151       SmallVector<Node*,8> Nodes;
152       order(Nodes);
153       for (Node *N : Nodes)
154         delete N;
155     }
156 
157   private:
158     void dump(const Node *N) const;
159     void order(Node *N, SmallVectorImpl<Node*> &Seq) const;
160     void nodesWith(Node *N, int32_t P, bool CheckA,
161                    SmallVectorImpl<Node*> &Seq) const;
162 
163     Node *add(Node *N, const OffsetRange &R);
164     Node *remove(Node *N, const Node *D);
165     Node *rotateLeft(Node *Lower, Node *Higher);
166     Node *rotateRight(Node *Lower, Node *Higher);
167     unsigned height(Node *N) {
168       return N != nullptr ? N->Height : 0;
169     }
170     Node *update(Node *N) {
171       assert(N != nullptr);
172       N->Height = 1 + std::max(height(N->Left), height(N->Right));
173       if (N->Left)
174         N->MaxEnd = std::max(N->MaxEnd, N->Left->MaxEnd);
175       if (N->Right)
176         N->MaxEnd = std::max(N->MaxEnd, N->Right->MaxEnd);
177       return N;
178     }
179     Node *rebalance(Node *N) {
180       assert(N != nullptr);
181       int32_t Balance = height(N->Right) - height(N->Left);
182       if (Balance < -1)
183         return rotateRight(N->Left, N);
184       if (Balance > 1)
185         return rotateLeft(N->Right, N);
186       return N;
187     }
188   };
189 
190   struct Loc {
191     MachineBasicBlock *Block = nullptr;
192     MachineBasicBlock::iterator At;
193 
194     Loc(MachineBasicBlock *B, MachineBasicBlock::iterator It)
195       : Block(B), At(It) {
196       if (B->end() == It) {
197         Pos = -1;
198       } else {
199         assert(It->getParent() == B);
200         Pos = std::distance(B->begin(), It);
201       }
202     }
203     bool operator<(Loc A) const {
204       if (Block != A.Block)
205         return Block->getNumber() < A.Block->getNumber();
206       if (A.Pos == -1)
207         return Pos != A.Pos;
208       return Pos != -1 && Pos < A.Pos;
209     }
210   private:
211     int Pos = 0;
212   };
213 
214   struct HexagonConstExtenders : public MachineFunctionPass {
215     static char ID;
216     HexagonConstExtenders() : MachineFunctionPass(ID) {}
217 
218     void getAnalysisUsage(AnalysisUsage &AU) const override {
219       AU.addRequired<MachineDominatorTree>();
220       AU.addPreserved<MachineDominatorTree>();
221       MachineFunctionPass::getAnalysisUsage(AU);
222     }
223 
224     StringRef getPassName() const override {
225       return "Hexagon constant-extender optimization";
226     }
227     bool runOnMachineFunction(MachineFunction &MF) override;
228 
229   private:
230     struct Register {
231       Register() = default;
232       Register(unsigned R, unsigned S) : Reg(R), Sub(S) {}
233       Register(const MachineOperand &Op)
234         : Reg(Op.getReg()), Sub(Op.getSubReg()) {}
235       Register &operator=(const MachineOperand &Op) {
236         if (Op.isReg()) {
237           Reg = Op.getReg();
238           Sub = Op.getSubReg();
239         } else if (Op.isFI()) {
240           Reg = llvm::Register::index2StackSlot(Op.getIndex());
241         }
242         return *this;
243       }
244       bool isVReg() const {
245         return Reg != 0 && !llvm::Register::isStackSlot(Reg) &&
246                llvm::Register::isVirtualRegister(Reg);
247       }
248       bool isSlot() const {
249         return Reg != 0 && llvm::Register::isStackSlot(Reg);
250       }
251       operator MachineOperand() const {
252         if (isVReg())
253           return MachineOperand::CreateReg(Reg, /*Def*/false, /*Imp*/false,
254                           /*Kill*/false, /*Dead*/false, /*Undef*/false,
255                           /*EarlyClobber*/false, Sub);
256         if (llvm::Register::isStackSlot(Reg)) {
257           int FI = llvm::Register::stackSlot2Index(Reg);
258           return MachineOperand::CreateFI(FI);
259         }
260         llvm_unreachable("Cannot create MachineOperand");
261       }
262       bool operator==(Register R) const { return Reg == R.Reg && Sub == R.Sub; }
263       bool operator!=(Register R) const { return !operator==(R); }
264       bool operator<(Register R) const {
265         // For std::map.
266         return Reg < R.Reg || (Reg == R.Reg && Sub < R.Sub);
267       }
268       unsigned Reg = 0, Sub = 0;
269     };
270 
271     struct ExtExpr {
272       // A subexpression in which the extender is used. In general, this
273       // represents an expression where adding D to the extender will be
274       // equivalent to adding D to the expression as a whole. In other
275       // words, expr(add(##V,D) = add(expr(##V),D).
276 
277       // The original motivation for this are the io/ur addressing modes,
278       // where the offset is extended. Consider the io example:
279       // In memw(Rs+##V), the ##V could be replaced by a register Rt to
280       // form the rr mode: memw(Rt+Rs<<0). In such case, however, the
281       // register Rt must have exactly the value of ##V. If there was
282       // another instruction memw(Rs+##V+4), it would need a different Rt.
283       // Now, if Rt was initialized as "##V+Rs<<0", both of these
284       // instructions could use the same Rt, just with different offsets.
285       // Here it's clear that "initializer+4" should be the same as if
286       // the offset 4 was added to the ##V in the initializer.
287 
288       // The only kinds of expressions that support the requirement of
289       // commuting with addition are addition and subtraction from ##V.
290       // Include shifting the Rs to account for the ur addressing mode:
291       //   ##Val + Rs << S
292       //   ##Val - Rs
293       Register Rs;
294       unsigned S = 0;
295       bool Neg = false;
296 
297       ExtExpr() = default;
298       ExtExpr(Register RS, bool NG, unsigned SH) : Rs(RS), S(SH), Neg(NG) {}
299       // Expression is trivial if it does not modify the extender.
300       bool trivial() const {
301         return Rs.Reg == 0;
302       }
303       bool operator==(const ExtExpr &Ex) const {
304         return Rs == Ex.Rs && S == Ex.S && Neg == Ex.Neg;
305       }
306       bool operator!=(const ExtExpr &Ex) const {
307         return !operator==(Ex);
308       }
309       bool operator<(const ExtExpr &Ex) const {
310         if (Rs != Ex.Rs)
311           return Rs < Ex.Rs;
312         if (S != Ex.S)
313           return S < Ex.S;
314         return !Neg && Ex.Neg;
315       }
316     };
317 
318     struct ExtDesc {
319       MachineInstr *UseMI = nullptr;
320       unsigned OpNum = -1u;
321       // The subexpression in which the extender is used (e.g. address
322       // computation).
323       ExtExpr Expr;
324       // Optional register that is assigned the value of Expr.
325       Register Rd;
326       // Def means that the output of the instruction may differ from the
327       // original by a constant c, and that the difference can be corrected
328       // by adding/subtracting c in all users of the defined register.
329       bool IsDef = false;
330 
331       MachineOperand &getOp() {
332         return UseMI->getOperand(OpNum);
333       }
334       const MachineOperand &getOp() const {
335         return UseMI->getOperand(OpNum);
336       }
337     };
338 
339     struct ExtRoot {
340       union {
341         const ConstantFP *CFP;  // MO_FPImmediate
342         const char *SymbolName; // MO_ExternalSymbol
343         const GlobalValue *GV;  // MO_GlobalAddress
344         const BlockAddress *BA; // MO_BlockAddress
345         int64_t ImmVal;         // MO_Immediate, MO_TargetIndex,
346                                 // and MO_ConstantPoolIndex
347       } V;
348       unsigned Kind;            // Same as in MachineOperand.
349       unsigned char TF;         // TargetFlags.
350 
351       ExtRoot(const MachineOperand &Op);
352       bool operator==(const ExtRoot &ER) const {
353         return Kind == ER.Kind && V.ImmVal == ER.V.ImmVal;
354       }
355       bool operator!=(const ExtRoot &ER) const {
356         return !operator==(ER);
357       }
358       bool operator<(const ExtRoot &ER) const;
359     };
360 
361     struct ExtValue : public ExtRoot {
362       int32_t Offset;
363 
364       ExtValue(const MachineOperand &Op);
365       ExtValue(const ExtDesc &ED) : ExtValue(ED.getOp()) {}
366       ExtValue(const ExtRoot &ER, int32_t Off) : ExtRoot(ER), Offset(Off) {}
367       bool operator<(const ExtValue &EV) const;
368       bool operator==(const ExtValue &EV) const {
369         return ExtRoot(*this) == ExtRoot(EV) && Offset == EV.Offset;
370       }
371       bool operator!=(const ExtValue &EV) const {
372         return !operator==(EV);
373       }
374       explicit operator MachineOperand() const;
375     };
376 
377     using IndexList = SetVector<unsigned>;
378     using ExtenderInit = std::pair<ExtValue, ExtExpr>;
379     using AssignmentMap = std::map<ExtenderInit, IndexList>;
380     using LocDefList = std::vector<std::pair<Loc, IndexList>>;
381 
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   // Sanity check: 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       unsigned NewOpc = Ex.Neg ? Hexagon::S4_subi_asl_ri
1566                                : Hexagon::S4_addi_asl_ri;
1567       // DefR = add(##EV,asl(Rb,S))
1568       InitI = BuildMI(MBB, At, dl, HII->get(NewOpc), DefR)
1569                 .add(ExtOp)
1570                 .add(MachineOperand(Ex.Rs))
1571                 .addImm(Ex.S);
1572     }
1573   }
1574 
1575   assert(InitI);
1576   (void)InitI;
1577   LLVM_DEBUG(dbgs() << "Inserted def in bb#" << MBB.getNumber()
1578                     << " for initializer: " << PrintInit(ExtI, *HRI) << "\n  "
1579                     << *InitI);
1580   return { DefR, 0 };
1581 }
1582 
1583 // Replace the extender at index Idx with the register ExtR.
1584 bool HCE::replaceInstrExact(const ExtDesc &ED, Register ExtR) {
1585   MachineInstr &MI = *ED.UseMI;
1586   MachineBasicBlock &MBB = *MI.getParent();
1587   MachineBasicBlock::iterator At = MI.getIterator();
1588   DebugLoc dl = MI.getDebugLoc();
1589   unsigned ExtOpc = MI.getOpcode();
1590 
1591   // With a few exceptions, direct replacement amounts to creating an
1592   // instruction with a corresponding register opcode, with all operands
1593   // the same, except for the register used in place of the extender.
1594   unsigned RegOpc = getDirectRegReplacement(ExtOpc);
1595 
1596   if (RegOpc == TargetOpcode::REG_SEQUENCE) {
1597     if (ExtOpc == Hexagon::A4_combineri)
1598       BuildMI(MBB, At, dl, HII->get(RegOpc))
1599         .add(MI.getOperand(0))
1600         .add(MI.getOperand(1))
1601         .addImm(Hexagon::isub_hi)
1602         .add(MachineOperand(ExtR))
1603         .addImm(Hexagon::isub_lo);
1604     else if (ExtOpc == Hexagon::A4_combineir)
1605       BuildMI(MBB, At, dl, HII->get(RegOpc))
1606         .add(MI.getOperand(0))
1607         .add(MachineOperand(ExtR))
1608         .addImm(Hexagon::isub_hi)
1609         .add(MI.getOperand(2))
1610         .addImm(Hexagon::isub_lo);
1611     else
1612       llvm_unreachable("Unexpected opcode became REG_SEQUENCE");
1613     MBB.erase(MI);
1614     return true;
1615   }
1616   if (ExtOpc == Hexagon::C2_cmpgei || ExtOpc == Hexagon::C2_cmpgeui) {
1617     unsigned NewOpc = ExtOpc == Hexagon::C2_cmpgei ? Hexagon::C2_cmplt
1618                                                    : Hexagon::C2_cmpltu;
1619     BuildMI(MBB, At, dl, HII->get(NewOpc))
1620       .add(MI.getOperand(0))
1621       .add(MachineOperand(ExtR))
1622       .add(MI.getOperand(1));
1623     MBB.erase(MI);
1624     return true;
1625   }
1626 
1627   if (RegOpc != 0) {
1628     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1629     unsigned RegN = ED.OpNum;
1630     // Copy all operands except the one that has the extender.
1631     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1632       if (i != RegN)
1633         MIB.add(MI.getOperand(i));
1634       else
1635         MIB.add(MachineOperand(ExtR));
1636     }
1637     MIB.cloneMemRefs(MI);
1638     MBB.erase(MI);
1639     return true;
1640   }
1641 
1642   if (MI.mayLoadOrStore() && !isStoreImmediate(ExtOpc)) {
1643     // For memory instructions, there is an asymmetry in the addressing
1644     // modes. Addressing modes allowing extenders can be replaced with
1645     // addressing modes that use registers, but the order of operands
1646     // (or even their number) may be different.
1647     // Replacements:
1648     //   BaseImmOffset (io)  -> BaseRegOffset (rr)
1649     //   BaseLongOffset (ur) -> BaseRegOffset (rr)
1650     unsigned RegOpc, Shift;
1651     unsigned AM = HII->getAddrMode(MI);
1652     if (AM == HexagonII::BaseImmOffset) {
1653       RegOpc = HII->changeAddrMode_io_rr(ExtOpc);
1654       Shift = 0;
1655     } else if (AM == HexagonII::BaseLongOffset) {
1656       // Loads:  Rd = L4_loadri_ur Rs, S, ##
1657       // Stores: S4_storeri_ur Rs, S, ##, Rt
1658       RegOpc = HII->changeAddrMode_ur_rr(ExtOpc);
1659       Shift = MI.getOperand(MI.mayLoad() ? 2 : 1).getImm();
1660     } else {
1661       llvm_unreachable("Unexpected addressing mode");
1662     }
1663 #ifndef NDEBUG
1664     if (RegOpc == -1u) {
1665       dbgs() << "\nExtOpc: " << HII->getName(ExtOpc) << " has no rr version\n";
1666       llvm_unreachable("No corresponding rr instruction");
1667     }
1668 #endif
1669 
1670     unsigned BaseP, OffP;
1671     HII->getBaseAndOffsetPosition(MI, BaseP, OffP);
1672 
1673     // Build an rr instruction: (RegOff + RegBase<<0)
1674     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1675     // First, add the def for loads.
1676     if (MI.mayLoad())
1677       MIB.add(getLoadResultOp(MI));
1678     // Handle possible predication.
1679     if (HII->isPredicated(MI))
1680       MIB.add(getPredicateOp(MI));
1681     // Build the address.
1682     MIB.add(MachineOperand(ExtR));      // RegOff
1683     MIB.add(MI.getOperand(BaseP));      // RegBase
1684     MIB.addImm(Shift);                  // << Shift
1685     // Add the stored value for stores.
1686     if (MI.mayStore())
1687       MIB.add(getStoredValueOp(MI));
1688     MIB.cloneMemRefs(MI);
1689     MBB.erase(MI);
1690     return true;
1691   }
1692 
1693 #ifndef NDEBUG
1694   dbgs() << '\n' << MI;
1695 #endif
1696   llvm_unreachable("Unhandled exact replacement");
1697   return false;
1698 }
1699 
1700 // Replace the extender ED with a form corresponding to the initializer ExtI.
1701 bool HCE::replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
1702       Register ExtR, int32_t &Diff) {
1703   MachineInstr &MI = *ED.UseMI;
1704   MachineBasicBlock &MBB = *MI.getParent();
1705   MachineBasicBlock::iterator At = MI.getIterator();
1706   DebugLoc dl = MI.getDebugLoc();
1707   unsigned ExtOpc = MI.getOpcode();
1708 
1709   if (ExtOpc == Hexagon::A2_tfrsi) {
1710     // A2_tfrsi is a special case: it's replaced with A2_addi, which introduces
1711     // another range. One range is the one that's common to all tfrsi's uses,
1712     // this one is the range of immediates in A2_addi. When calculating ranges,
1713     // the addi's 16-bit argument was included, so now we need to make it such
1714     // that the produced value is in the range for the uses alone.
1715     // Most of the time, simply adding Diff will make the addi produce exact
1716     // result, but if Diff is outside of the 16-bit range, some adjustment
1717     // will be needed.
1718     unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1719     assert(IdxOpc == Hexagon::A2_addi);
1720 
1721     // Clamp Diff to the 16 bit range.
1722     int32_t D = isInt<16>(Diff) ? Diff : (Diff > 0 ? 32767 : -32768);
1723     if (Diff > 32767) {
1724       // Split Diff into two values: one that is close to min/max int16,
1725       // and the other being the rest, and such that both have the same
1726       // "alignment" as Diff.
1727       uint32_t UD = Diff;
1728       OffsetRange R = getOffsetRange(MI.getOperand(0));
1729       uint32_t A = std::min<uint32_t>(R.Align, 1u << countTrailingZeros(UD));
1730       D &= ~(A-1);
1731     }
1732     BuildMI(MBB, At, dl, HII->get(IdxOpc))
1733       .add(MI.getOperand(0))
1734       .add(MachineOperand(ExtR))
1735       .addImm(D);
1736     Diff -= D;
1737 #ifndef NDEBUG
1738     // Make sure the output is within allowable range for uses.
1739     // "Diff" is a difference in the "opposite direction", i.e. Ext - DefV,
1740     // not DefV - Ext, as the getOffsetRange would calculate.
1741     OffsetRange Uses = getOffsetRange(MI.getOperand(0));
1742     if (!Uses.contains(-Diff))
1743       dbgs() << "Diff: " << -Diff << " out of range " << Uses
1744              << " for " << MI;
1745     assert(Uses.contains(-Diff));
1746 #endif
1747     MBB.erase(MI);
1748     return true;
1749   }
1750 
1751   const ExtValue &EV = ExtI.first; (void)EV;
1752   const ExtExpr &Ex = ExtI.second; (void)Ex;
1753 
1754   if (ExtOpc == Hexagon::A2_addi || ExtOpc == Hexagon::A2_subri) {
1755     // If addi/subri are replaced with the exactly matching initializer,
1756     // they amount to COPY.
1757     // Check that the initializer is an exact match (for simplicity).
1758 #ifndef NDEBUG
1759     bool IsAddi = ExtOpc == Hexagon::A2_addi;
1760     const MachineOperand &RegOp = MI.getOperand(IsAddi ? 1 : 2);
1761     const MachineOperand &ImmOp = MI.getOperand(IsAddi ? 2 : 1);
1762     assert(Ex.Rs == RegOp && EV == ImmOp && Ex.Neg != IsAddi &&
1763            "Initializer mismatch");
1764 #endif
1765     BuildMI(MBB, At, dl, HII->get(TargetOpcode::COPY))
1766       .add(MI.getOperand(0))
1767       .add(MachineOperand(ExtR));
1768     Diff = 0;
1769     MBB.erase(MI);
1770     return true;
1771   }
1772   if (ExtOpc == Hexagon::M2_accii || ExtOpc == Hexagon::M2_naccii ||
1773       ExtOpc == Hexagon::S4_addaddi || ExtOpc == Hexagon::S4_subaddi) {
1774     // M2_accii:    add(Rt,add(Rs,V)) (tied)
1775     // M2_naccii:   sub(Rt,add(Rs,V))
1776     // S4_addaddi:  add(Rt,add(Rs,V))
1777     // S4_subaddi:  add(Rt,sub(V,Rs))
1778     // Check that Rs and V match the initializer expression. The Rs+V is the
1779     // combination that is considered "subexpression" for V, although Rx+V
1780     // would also be valid.
1781 #ifndef NDEBUG
1782     bool IsSub = ExtOpc == Hexagon::S4_subaddi;
1783     Register Rs = MI.getOperand(IsSub ? 3 : 2);
1784     ExtValue V = MI.getOperand(IsSub ? 2 : 3);
1785     assert(EV == V && Rs == Ex.Rs && IsSub == Ex.Neg && "Initializer mismatch");
1786 #endif
1787     unsigned NewOpc = ExtOpc == Hexagon::M2_naccii ? Hexagon::A2_sub
1788                                                    : Hexagon::A2_add;
1789     BuildMI(MBB, At, dl, HII->get(NewOpc))
1790       .add(MI.getOperand(0))
1791       .add(MI.getOperand(1))
1792       .add(MachineOperand(ExtR));
1793     MBB.erase(MI);
1794     return true;
1795   }
1796 
1797   if (MI.mayLoadOrStore()) {
1798     unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1799     assert(IdxOpc && "Expecting indexed opcode");
1800     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(IdxOpc));
1801     // Construct the new indexed instruction.
1802     // First, add the def for loads.
1803     if (MI.mayLoad())
1804       MIB.add(getLoadResultOp(MI));
1805     // Handle possible predication.
1806     if (HII->isPredicated(MI))
1807       MIB.add(getPredicateOp(MI));
1808     // Build the address.
1809     MIB.add(MachineOperand(ExtR));
1810     MIB.addImm(Diff);
1811     // Add the stored value for stores.
1812     if (MI.mayStore())
1813       MIB.add(getStoredValueOp(MI));
1814     MIB.cloneMemRefs(MI);
1815     MBB.erase(MI);
1816     return true;
1817   }
1818 
1819 #ifndef NDEBUG
1820   dbgs() << '\n' << PrintInit(ExtI, *HRI) << "  " << MI;
1821 #endif
1822   llvm_unreachable("Unhandled expr replacement");
1823   return false;
1824 }
1825 
1826 bool HCE::replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI) {
1827   if (ReplaceLimit.getNumOccurrences()) {
1828     if (ReplaceLimit <= ReplaceCounter)
1829       return false;
1830     ++ReplaceCounter;
1831   }
1832   const ExtDesc &ED = Extenders[Idx];
1833   assert((!ED.IsDef || ED.Rd.Reg != 0) && "Missing Rd for def");
1834   const ExtValue &DefV = ExtI.first;
1835   assert(ExtRoot(ExtValue(ED)) == ExtRoot(DefV) && "Extender root mismatch");
1836   const ExtExpr &DefEx = ExtI.second;
1837 
1838   ExtValue EV(ED);
1839   int32_t Diff = EV.Offset - DefV.Offset;
1840   const MachineInstr &MI = *ED.UseMI;
1841   LLVM_DEBUG(dbgs() << __func__ << " Idx:" << Idx << " ExtR:"
1842                     << PrintRegister(ExtR, *HRI) << " Diff:" << Diff << '\n');
1843 
1844   // These two addressing modes must be converted into indexed forms
1845   // regardless of what the initializer looks like.
1846   bool IsAbs = false, IsAbsSet = false;
1847   if (MI.mayLoadOrStore()) {
1848     unsigned AM = HII->getAddrMode(MI);
1849     IsAbs = AM == HexagonII::Absolute;
1850     IsAbsSet = AM == HexagonII::AbsoluteSet;
1851   }
1852 
1853   // If it's a def, remember all operands that need to be updated.
1854   // If ED is a def, and Diff is not 0, then all uses of the register Rd
1855   // defined by ED must be in the form (Rd, imm), i.e. the immediate offset
1856   // must follow the Rd in the operand list.
1857   std::vector<std::pair<MachineInstr*,unsigned>> RegOps;
1858   if (ED.IsDef && Diff != 0) {
1859     for (MachineOperand &Op : MRI->use_operands(ED.Rd.Reg)) {
1860       MachineInstr &UI = *Op.getParent();
1861       RegOps.push_back({&UI, getOperandIndex(UI, Op)});
1862     }
1863   }
1864 
1865   // Replace the instruction.
1866   bool Replaced = false;
1867   if (Diff == 0 && DefEx.trivial() && !IsAbs && !IsAbsSet)
1868     Replaced = replaceInstrExact(ED, ExtR);
1869   else
1870     Replaced = replaceInstrExpr(ED, ExtI, ExtR, Diff);
1871 
1872   if (Diff != 0 && Replaced && ED.IsDef) {
1873     // Update offsets of the def's uses.
1874     for (std::pair<MachineInstr*,unsigned> P : RegOps) {
1875       unsigned J = P.second;
1876       assert(P.first->getNumOperands() > J+1 &&
1877              P.first->getOperand(J+1).isImm());
1878       MachineOperand &ImmOp = P.first->getOperand(J+1);
1879       ImmOp.setImm(ImmOp.getImm() + Diff);
1880     }
1881     // If it was an absolute-set instruction, the "set" part has been removed.
1882     // ExtR will now be the register with the extended value, and since all
1883     // users of Rd have been updated, all that needs to be done is to replace
1884     // Rd with ExtR.
1885     if (IsAbsSet) {
1886       assert(ED.Rd.Sub == 0 && ExtR.Sub == 0);
1887       MRI->replaceRegWith(ED.Rd.Reg, ExtR.Reg);
1888     }
1889   }
1890 
1891   return Replaced;
1892 }
1893 
1894 bool HCE::replaceExtenders(const AssignmentMap &IMap) {
1895   LocDefList Defs;
1896   bool Changed = false;
1897 
1898   for (const std::pair<const ExtenderInit, IndexList> &P : IMap) {
1899     const IndexList &Idxs = P.second;
1900     if (Idxs.size() < CountThreshold)
1901       continue;
1902 
1903     Defs.clear();
1904     calculatePlacement(P.first, Idxs, Defs);
1905     for (const std::pair<Loc,IndexList> &Q : Defs) {
1906       Register DefR = insertInitializer(Q.first, P.first);
1907       NewRegs.push_back(DefR.Reg);
1908       for (unsigned I : Q.second)
1909         Changed |= replaceInstr(I, DefR, P.first);
1910     }
1911   }
1912   return Changed;
1913 }
1914 
1915 unsigned HCE::getOperandIndex(const MachineInstr &MI,
1916       const MachineOperand &Op) const {
1917   for (unsigned i = 0, n = MI.getNumOperands(); i != n; ++i)
1918     if (&MI.getOperand(i) == &Op)
1919       return i;
1920   llvm_unreachable("Not an operand of MI");
1921 }
1922 
1923 const MachineOperand &HCE::getPredicateOp(const MachineInstr &MI) const {
1924   assert(HII->isPredicated(MI));
1925   for (const MachineOperand &Op : MI.operands()) {
1926     if (!Op.isReg() || !Op.isUse() ||
1927         MRI->getRegClass(Op.getReg()) != &Hexagon::PredRegsRegClass)
1928       continue;
1929     assert(Op.getSubReg() == 0 && "Predicate register with a subregister");
1930     return Op;
1931   }
1932   llvm_unreachable("Predicate operand not found");
1933 }
1934 
1935 const MachineOperand &HCE::getLoadResultOp(const MachineInstr &MI) const {
1936   assert(MI.mayLoad());
1937   return MI.getOperand(0);
1938 }
1939 
1940 const MachineOperand &HCE::getStoredValueOp(const MachineInstr &MI) const {
1941   assert(MI.mayStore());
1942   return MI.getOperand(MI.getNumExplicitOperands()-1);
1943 }
1944 
1945 bool HCE::runOnMachineFunction(MachineFunction &MF) {
1946   if (skipFunction(MF.getFunction()))
1947     return false;
1948   if (MF.getFunction().hasPersonalityFn()) {
1949     LLVM_DEBUG(dbgs() << getPassName() << ": skipping " << MF.getName()
1950                       << " due to exception handling\n");
1951     return false;
1952   }
1953   LLVM_DEBUG(MF.print(dbgs() << "Before " << getPassName() << '\n', nullptr));
1954 
1955   HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
1956   HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1957   MDT = &getAnalysis<MachineDominatorTree>();
1958   MRI = &MF.getRegInfo();
1959   AssignmentMap IMap;
1960 
1961   collect(MF);
1962   llvm::sort(Extenders, [this](const ExtDesc &A, const ExtDesc &B) {
1963     ExtValue VA(A), VB(B);
1964     if (VA != VB)
1965       return VA < VB;
1966     const MachineInstr *MA = A.UseMI;
1967     const MachineInstr *MB = B.UseMI;
1968     if (MA == MB) {
1969       // If it's the same instruction, compare operand numbers.
1970       return A.OpNum < B.OpNum;
1971     }
1972 
1973     const MachineBasicBlock *BA = MA->getParent();
1974     const MachineBasicBlock *BB = MB->getParent();
1975     assert(BA->getNumber() != -1 && BB->getNumber() != -1);
1976     if (BA != BB)
1977       return BA->getNumber() < BB->getNumber();
1978     return MDT->dominates(MA, MB);
1979   });
1980 
1981   bool Changed = false;
1982   LLVM_DEBUG(dbgs() << "Collected " << Extenders.size() << " extenders\n");
1983   for (unsigned I = 0, E = Extenders.size(); I != E; ) {
1984     unsigned B = I;
1985     const ExtRoot &T = Extenders[B].getOp();
1986     while (I != E && ExtRoot(Extenders[I].getOp()) == T)
1987       ++I;
1988 
1989     IMap.clear();
1990     assignInits(T, B, I, IMap);
1991     Changed |= replaceExtenders(IMap);
1992   }
1993 
1994   LLVM_DEBUG({
1995     if (Changed)
1996       MF.print(dbgs() << "After " << getPassName() << '\n', nullptr);
1997     else
1998       dbgs() << "No changes\n";
1999   });
2000   return Changed;
2001 }
2002 
2003 FunctionPass *llvm::createHexagonConstExtenders() {
2004   return new HexagonConstExtenders();
2005 }
2006