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