Fixing a compile error in debug versions of MSVC. It seems that the range-based for...
[oota-llvm.git] / lib / Target / ARM64 / ARM64CollectLOH.cpp
1 //===-------------- ARM64CollectLOH.cpp - ARM64 collect LOH pass --*- C++ -*-=//
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 // This file contains a pass that collect the Linker Optimization Hint (LOH).
11 // This pass should be run at the very end of the compilation flow, just before
12 // assembly printer.
13 // To be useful for the linker, the LOH must be printed into the assembly file.
14 //
15 // A LOH describes a sequence of instructions that may be optimized by the
16 // linker.
17 // This same sequence cannot be optimized by the compiler because some of
18 // the information will be known at link time.
19 // For instance, consider the following sequence:
20 //     L1: adrp xA, sym@PAGE
21 //     L2: add xB, xA, sym@PAGEOFF
22 //     L3: ldr xC, [xB, #imm]
23 // This sequence can be turned into:
24 // A literal load if sym@PAGE + sym@PAGEOFF + #imm - address(L3) is < 1MB:
25 //     L3: ldr xC, sym+#imm
26 // It may also be turned into either the following more efficient
27 // code sequences:
28 // - If sym@PAGEOFF + #imm fits the encoding space of L3.
29 //     L1: adrp xA, sym@PAGE
30 //     L3: ldr xC, [xB, sym@PAGEOFF + #imm]
31 // - If sym@PAGE + sym@PAGEOFF - address(L1) < 1MB:
32 //     L1: adr xA, sym
33 //     L3: ldr xC, [xB, #imm]
34 //
35 // To be valid a LOH must meet all the requirements needed by all the related
36 // possible linker transformations.
37 // For instance, using the running example, the constraints to emit
38 // ".loh AdrpAddLdr" are:
39 // - L1, L2, and L3 instructions are of the expected type, i.e.,
40 //   respectively ADRP, ADD (immediate), and LD.
41 // - The result of L1 is used only by L2.
42 // - The register argument (xA) used in the ADD instruction is defined
43 //   only by L1.
44 // - The result of L2 is used only by L3.
45 // - The base address (xB) in L3 is defined only L2.
46 // - The ADRP in L1 and the ADD in L2 must reference the same symbol using
47 //   @PAGE/@PAGEOFF with no additional constants
48 //
49 // Currently supported LOHs are:
50 // * So called non-ADRP-related:
51 //   - .loh AdrpAddLdr L1, L2, L3:
52 //     L1: adrp xA, sym@PAGE
53 //     L2: add xB, xA, sym@PAGEOFF
54 //     L3: ldr xC, [xB, #imm]
55 //   - .loh AdrpLdrGotLdr L1, L2, L3:
56 //     L1: adrp xA, sym@GOTPAGE
57 //     L2: ldr xB, [xA, sym@GOTPAGEOFF]
58 //     L3: ldr xC, [xB, #imm]
59 //   - .loh AdrpLdr L1, L3:
60 //     L1: adrp xA, sym@PAGE
61 //     L3: ldr xC, [xA, sym@PAGEOFF]
62 //   - .loh AdrpAddStr L1, L2, L3:
63 //     L1: adrp xA, sym@PAGE
64 //     L2: add xB, xA, sym@PAGEOFF
65 //     L3: str xC, [xB, #imm]
66 //   - .loh AdrpLdrGotStr L1, L2, L3:
67 //     L1: adrp xA, sym@GOTPAGE
68 //     L2: ldr xB, [xA, sym@GOTPAGEOFF]
69 //     L3: str xC, [xB, #imm]
70 //   - .loh AdrpAdd L1, L2:
71 //     L1: adrp xA, sym@PAGE
72 //     L2: add xB, xA, sym@PAGEOFF
73 //   For all these LOHs, L1, L2, L3 form a simple chain:
74 //   L1 result is used only by L2 and L2 result by L3.
75 //   L3 LOH-related argument is defined only by L2 and L2 LOH-related argument
76 //   by L1.
77 // All these LOHs aim at using more efficient load/store patterns by folding
78 // some instructions used to compute the address directly into the load/store.
79 //
80 // * So called ADRP-related:
81 //  - .loh AdrpAdrp L2, L1:
82 //    L2: ADRP xA, sym1@PAGE
83 //    L1: ADRP xA, sym2@PAGE
84 //    L2 dominates L1 and xA is not redifined between L2 and L1
85 // This LOH aims at getting rid of redundant ADRP instructions.
86 //
87 // The overall design for emitting the LOHs is:
88 // 1. ARM64CollectLOH (this pass) records the LOHs in the ARM64FunctionInfo.
89 // 2. ARM64AsmPrinter reads the LOHs from ARM64FunctionInfo and it:
90 //     1. Associates them a label.
91 //     2. Emits them in a MCStreamer (EmitLOHDirective).
92 //         - The MCMachOStreamer records them into the MCAssembler.
93 //         - The MCAsmStreamer prints them.
94 //         - Other MCStreamers ignore them.
95 //     3. Closes the MCStreamer:
96 //         - The MachObjectWriter gets them from the MCAssembler and writes
97 //           them in the object file.
98 //         - Other ObjectWriters ignore them.
99 //===----------------------------------------------------------------------===//
100
101 #define DEBUG_TYPE "arm64-collect-loh"
102 #include "ARM64.h"
103 #include "ARM64InstrInfo.h"
104 #include "ARM64MachineFunctionInfo.h"
105 #include "MCTargetDesc/ARM64AddressingModes.h"
106 #include "llvm/ADT/BitVector.h"
107 #include "llvm/ADT/DenseMap.h"
108 #include "llvm/ADT/MapVector.h"
109 #include "llvm/ADT/SetVector.h"
110 #include "llvm/ADT/SmallVector.h"
111 #include "llvm/CodeGen/MachineBasicBlock.h"
112 #include "llvm/CodeGen/MachineDominators.h"
113 #include "llvm/CodeGen/MachineFunctionPass.h"
114 #include "llvm/CodeGen/MachineInstr.h"
115 #include "llvm/CodeGen/MachineInstrBuilder.h"
116 #include "llvm/Target/TargetInstrInfo.h"
117 #include "llvm/Target/TargetMachine.h"
118 #include "llvm/Target/TargetRegisterInfo.h"
119 #include "llvm/Support/CommandLine.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include "llvm/ADT/Statistic.h"
124 using namespace llvm;
125
126 static cl::opt<bool>
127 PreCollectRegister("arm64-collect-loh-pre-collect-register", cl::Hidden,
128                    cl::desc("Restrict analysis to registers invovled"
129                             " in LOHs"),
130                    cl::init(true));
131
132 static cl::opt<bool>
133 BasicBlockScopeOnly("arm64-collect-loh-bb-only", cl::Hidden,
134                     cl::desc("Restrict analysis at basic block scope"),
135                     cl::init(true));
136
137 STATISTIC(NumADRPSimpleCandidate,
138           "Number of simplifiable ADRP dominate by another");
139 STATISTIC(NumADRPComplexCandidate2,
140           "Number of simplifiable ADRP reachable by 2 defs");
141 STATISTIC(NumADRPComplexCandidate3,
142           "Number of simplifiable ADRP reachable by 3 defs");
143 STATISTIC(NumADRPComplexCandidateOther,
144           "Number of simplifiable ADRP reachable by 4 or more defs");
145 STATISTIC(NumADDToSTRWithImm,
146           "Number of simplifiable STR with imm reachable by ADD");
147 STATISTIC(NumLDRToSTRWithImm,
148           "Number of simplifiable STR with imm reachable by LDR");
149 STATISTIC(NumADDToSTR, "Number of simplifiable STR reachable by ADD");
150 STATISTIC(NumLDRToSTR, "Number of simplifiable STR reachable by LDR");
151 STATISTIC(NumADDToLDRWithImm,
152           "Number of simplifiable LDR with imm reachable by ADD");
153 STATISTIC(NumLDRToLDRWithImm,
154           "Number of simplifiable LDR with imm reachable by LDR");
155 STATISTIC(NumADDToLDR, "Number of simplifiable LDR reachable by ADD");
156 STATISTIC(NumLDRToLDR, "Number of simplifiable LDR reachable by LDR");
157 STATISTIC(NumADRPToLDR, "Number of simplifiable LDR reachable by ADRP");
158 STATISTIC(NumCplxLvl1, "Number of complex case of level 1");
159 STATISTIC(NumTooCplxLvl1, "Number of too complex case of level 1");
160 STATISTIC(NumCplxLvl2, "Number of complex case of level 2");
161 STATISTIC(NumTooCplxLvl2, "Number of too complex case of level 2");
162 STATISTIC(NumADRSimpleCandidate, "Number of simplifiable ADRP + ADD");
163 STATISTIC(NumADRComplexCandidate, "Number of too complex ADRP + ADD");
164
165 namespace llvm {
166 void initializeARM64CollectLOHPass(PassRegistry &);
167 }
168
169 namespace {
170 struct ARM64CollectLOH : public MachineFunctionPass {
171   static char ID;
172   ARM64CollectLOH() : MachineFunctionPass(ID) {
173     initializeARM64CollectLOHPass(*PassRegistry::getPassRegistry());
174   }
175
176   virtual bool runOnMachineFunction(MachineFunction &MF);
177
178   virtual const char *getPassName() const {
179     return "ARM64 Collect Linker Optimization Hint (LOH)";
180   }
181
182   void getAnalysisUsage(AnalysisUsage &AU) const {
183     AU.setPreservesAll();
184     MachineFunctionPass::getAnalysisUsage(AU);
185     AU.addRequired<MachineDominatorTree>();
186   }
187
188 private:
189 };
190
191 /// A set of MachineInstruction.
192 typedef SetVector<const MachineInstr *> SetOfMachineInstr;
193 /// Map a basic block to a set of instructions per register.
194 /// This is used to represent the exposed uses of a basic block
195 /// per register.
196 typedef MapVector<const MachineBasicBlock *, SetOfMachineInstr *>
197 BlockToSetOfInstrsPerColor;
198 /// Map a basic block to an instruction per register.
199 /// This is used to represent the live-out definitions of a basic block
200 /// per register.
201 typedef MapVector<const MachineBasicBlock *, const MachineInstr **>
202 BlockToInstrPerColor;
203 /// Map an instruction to a set of instructions. Used to represent the
204 /// mapping def to reachable uses or use to definitions.
205 typedef MapVector<const MachineInstr *, SetOfMachineInstr> InstrToInstrs;
206 /// Map a basic block to a BitVector.
207 /// This is used to record the kill registers per basic block.
208 typedef MapVector<const MachineBasicBlock *, BitVector> BlockToRegSet;
209
210 /// Map a register to a dense id.
211 typedef DenseMap<unsigned, unsigned> MapRegToId;
212 /// Map a dense id to a register. Used for debug purposes.
213 typedef SmallVector<unsigned, 32> MapIdToReg;
214 } // end anonymous namespace.
215
216 char ARM64CollectLOH::ID = 0;
217
218 INITIALIZE_PASS_BEGIN(ARM64CollectLOH, "arm64-collect-loh",
219                       "ARM64 Collect Linker Optimization Hint (LOH)", false,
220                       false)
221 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
222 INITIALIZE_PASS_END(ARM64CollectLOH, "arm64-collect-loh",
223                     "ARM64 Collect Linker Optimization Hint (LOH)", false,
224                     false)
225
226 /// Given a couple (MBB, reg) get the corresponding set of instruction from
227 /// the given "sets".
228 /// If this couple does not reference any set, an empty set is added to "sets"
229 /// for this couple and returned.
230 /// \param nbRegs is used internally allocate some memory. It must be consistent
231 /// with the way sets is used.
232 static SetOfMachineInstr &getSet(BlockToSetOfInstrsPerColor &sets,
233                                  const MachineBasicBlock &MBB, unsigned reg,
234                                  unsigned nbRegs) {
235   SetOfMachineInstr *result;
236   BlockToSetOfInstrsPerColor::iterator it = sets.find(&MBB);
237   if (it != sets.end())
238     result = it->second;
239   else
240     result = sets[&MBB] = new SetOfMachineInstr[nbRegs];
241
242   return result[reg];
243 }
244
245 /// Given a couple (reg, MI) get the corresponding set of instructions from the
246 /// the given "sets".
247 /// This is used to get the uses record in sets of a definition identified by
248 /// MI and reg, i.e., MI defines reg.
249 /// If the couple does not reference anything, an empty set is added to
250 /// "sets[reg]".
251 /// \pre set[reg] is valid.
252 static SetOfMachineInstr &getUses(InstrToInstrs *sets, unsigned reg,
253                                   const MachineInstr &MI) {
254   return sets[reg][&MI];
255 }
256
257 /// Same as getUses but does not modify the input map: sets.
258 /// \return NULL if the couple (reg, MI) is not in sets.
259 static const SetOfMachineInstr *getUses(const InstrToInstrs *sets, unsigned reg,
260                                         const MachineInstr &MI) {
261   InstrToInstrs::const_iterator Res = sets[reg].find(&MI);
262   if (Res != sets[reg].end())
263     return &(Res->second);
264   return NULL;
265 }
266
267 /// Initialize the reaching definition algorithm:
268 /// For each basic block BB in MF, record:
269 /// - its kill set.
270 /// - its reachable uses (uses that are exposed to BB's predecessors).
271 /// - its the generated definitions.
272 /// \param DummyOp if not NULL, specifies a Dummy Operation to be added to
273 /// the list of uses of exposed defintions.
274 /// \param ADRPMode specifies to only consider ADRP instructions for generated
275 /// definition. It also consider definitions of ADRP instructions as uses and
276 /// ignore other uses. The ADRPMode is used to collect the information for LHO
277 /// that involve ADRP operation only.
278 static void initReachingDef(MachineFunction &MF,
279                             InstrToInstrs *ColorOpToReachedUses,
280                             BlockToInstrPerColor &Gen, BlockToRegSet &Kill,
281                             BlockToSetOfInstrsPerColor &ReachableUses,
282                             const MapRegToId &RegToId,
283                             const MachineInstr *DummyOp, bool ADRPMode) {
284   const TargetMachine &TM = MF.getTarget();
285   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
286
287   unsigned NbReg = RegToId.size();
288
289   for (MachineBasicBlock &MBB : MF) {
290     const MachineInstr **&BBGen = Gen[&MBB];
291     BBGen = new const MachineInstr *[NbReg];
292     memset(BBGen, 0, sizeof(const MachineInstr *) * NbReg);
293
294     BitVector &BBKillSet = Kill[&MBB];
295     BBKillSet.resize(NbReg);
296     for (const MachineInstr &MI : MBB) {
297       bool IsADRP = MI.getOpcode() == ARM64::ADRP;
298
299       // Process uses first.
300       if (IsADRP || !ADRPMode)
301         for (const MachineOperand &MO : MI.operands()) {
302           // Treat ADRP def as use, as the goal of the analysis is to find
303           // ADRP defs reached by other ADRP defs.
304           if (!MO.isReg() || (!ADRPMode && !MO.isUse()) ||
305               (ADRPMode && (!IsADRP || !MO.isDef())))
306             continue;
307           unsigned CurReg = MO.getReg();
308           MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
309           if (ItCurRegId == RegToId.end())
310             continue;
311           CurReg = ItCurRegId->second;
312
313           // if CurReg has not been defined, this use is reachable.
314           if (!BBGen[CurReg] && !BBKillSet.test(CurReg))
315             getSet(ReachableUses, MBB, CurReg, NbReg).insert(&MI);
316           // current basic block definition for this color, if any, is in Gen.
317           if (BBGen[CurReg])
318             getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(&MI);
319         }
320
321       // Process clobbers.
322       for (const MachineOperand &MO : MI.operands()) {
323         if (!MO.isRegMask())
324           continue;
325         // Clobbers kill the related colors.
326         const uint32_t *PreservedRegs = MO.getRegMask();
327
328         // Set generated regs.
329         for (const auto Entry : RegToId) {
330           unsigned Reg = Entry.second;
331           // Use the global register ID when querying APIs external to this
332           // pass.
333           if (MachineOperand::clobbersPhysReg(PreservedRegs, Entry.first)) {
334             // Do not register clobbered definition for no ADRP.
335             // This definition is not used anyway (otherwise register
336             // allocation is wrong).
337             BBGen[Reg] = ADRPMode ? &MI : NULL;
338             BBKillSet.set(Reg);
339           }
340         }
341       }
342
343       // Process register defs.
344       for (const MachineOperand &MO : MI.operands()) {
345         if (!MO.isReg() || !MO.isDef())
346           continue;
347         unsigned CurReg = MO.getReg();
348         MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
349         if (ItCurRegId == RegToId.end())
350           continue;
351
352         for (MCRegAliasIterator AI(CurReg, TRI, true); AI.isValid(); ++AI) {
353           MapRegToId::const_iterator ItRegId = RegToId.find(*AI);
354           assert(ItRegId != RegToId.end() &&
355                  "Sub-register of an "
356                  "involved register, not recorded as involved!");
357           BBKillSet.set(ItRegId->second);
358           BBGen[ItRegId->second] = &MI;
359         }
360         BBGen[ItCurRegId->second] = &MI;
361       }
362     }
363
364     // If we restrict our analysis to basic block scope, conservatively add a
365     // dummy
366     // use for each generated value.
367     if (!ADRPMode && DummyOp && !MBB.succ_empty())
368       for (unsigned CurReg = 0; CurReg < NbReg; ++CurReg)
369         if (BBGen[CurReg])
370           getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(DummyOp);
371   }
372 }
373
374 /// Reaching def core algorithm:
375 /// while an Out has changed
376 ///    for each bb
377 ///       for each color
378 ///           In[bb][color] = U Out[bb.predecessors][color]
379 ///           insert reachableUses[bb][color] in each in[bb][color]
380 ///                 op.reachedUses
381 ///
382 ///           Out[bb] = Gen[bb] U (In[bb] - Kill[bb])
383 static void reachingDefAlgorithm(MachineFunction &MF,
384                                  InstrToInstrs *ColorOpToReachedUses,
385                                  BlockToSetOfInstrsPerColor &In,
386                                  BlockToSetOfInstrsPerColor &Out,
387                                  BlockToInstrPerColor &Gen, BlockToRegSet &Kill,
388                                  BlockToSetOfInstrsPerColor &ReachableUses,
389                                  unsigned NbReg) {
390   bool HasChanged;
391   do {
392     HasChanged = false;
393     for (MachineBasicBlock &MBB : MF) {
394       unsigned CurReg;
395       for (CurReg = 0; CurReg < NbReg; ++CurReg) {
396         SetOfMachineInstr &BBInSet = getSet(In, MBB, CurReg, NbReg);
397         SetOfMachineInstr &BBReachableUses =
398             getSet(ReachableUses, MBB, CurReg, NbReg);
399         SetOfMachineInstr &BBOutSet = getSet(Out, MBB, CurReg, NbReg);
400         unsigned Size = BBOutSet.size();
401         //   In[bb][color] = U Out[bb.predecessors][color]
402         for (MachineBasicBlock *PredMBB : MBB.predecessors()) {
403           SetOfMachineInstr &PredOutSet = getSet(Out, *PredMBB, CurReg, NbReg);
404           BBInSet.insert(PredOutSet.begin(), PredOutSet.end());
405         }
406         //   insert reachableUses[bb][color] in each in[bb][color] op.reachedses
407         for (const MachineInstr *MI : BBInSet) {
408           SetOfMachineInstr &OpReachedUses =
409               getUses(ColorOpToReachedUses, CurReg, *MI);
410           OpReachedUses.insert(BBReachableUses.begin(), BBReachableUses.end());
411         }
412         //           Out[bb] = Gen[bb] U (In[bb] - Kill[bb])
413         if (!Kill[&MBB].test(CurReg))
414           BBOutSet.insert(BBInSet.begin(), BBInSet.end());
415         if (Gen[&MBB][CurReg])
416           BBOutSet.insert(Gen[&MBB][CurReg]);
417         HasChanged |= BBOutSet.size() != Size;
418       }
419     }
420   } while (HasChanged);
421 }
422
423 /// Release all memory dynamically allocated during the reaching
424 /// definition algorithm.
425 static void finitReachingDef(BlockToSetOfInstrsPerColor &In,
426                              BlockToSetOfInstrsPerColor &Out,
427                              BlockToInstrPerColor &Gen,
428                              BlockToSetOfInstrsPerColor &ReachableUses) {
429   for (auto &IT : Out)
430     delete[] IT.second;
431   for (auto &IT : In)
432     delete[] IT.second;
433   for (auto &IT : ReachableUses)
434     delete[] IT.second;
435   for (auto &IT : Gen)
436     delete[] IT.second;
437 }
438
439 /// Reaching definition algorithm.
440 /// \param MF function on which the algorithm will operate.
441 /// \param[out] ColorOpToReachedUses will contain the result of the reaching
442 /// def algorithm.
443 /// \param ADRPMode specify whether the reaching def algorithm should be tuned
444 /// for ADRP optimization. \see initReachingDef for more details.
445 /// \param DummyOp if not NULL, the algorithm will work at
446 /// basic block scope and will set for every exposed definition a use to
447 /// @p DummyOp.
448 /// \pre ColorOpToReachedUses is an array of at least number of registers of
449 /// InstrToInstrs.
450 static void reachingDef(MachineFunction &MF,
451                         InstrToInstrs *ColorOpToReachedUses,
452                         const MapRegToId &RegToId, bool ADRPMode = false,
453                         const MachineInstr *DummyOp = NULL) {
454   // structures:
455   // For each basic block.
456   // Out: a set per color of definitions that reach the
457   //      out boundary of this block.
458   // In: Same as Out but for in boundary.
459   // Gen: generated color in this block (one operation per color).
460   // Kill: register set of killed color in this block.
461   // ReachableUses: a set per color of uses (operation) reachable
462   //                for "In" definitions.
463   BlockToSetOfInstrsPerColor Out, In, ReachableUses;
464   BlockToInstrPerColor Gen;
465   BlockToRegSet Kill;
466
467   // Initialize Gen, kill and reachableUses.
468   initReachingDef(MF, ColorOpToReachedUses, Gen, Kill, ReachableUses, RegToId,
469                   DummyOp, ADRPMode);
470
471   // Algo.
472   if (!DummyOp)
473     reachingDefAlgorithm(MF, ColorOpToReachedUses, In, Out, Gen, Kill,
474                          ReachableUses, RegToId.size());
475
476   // finit.
477   finitReachingDef(In, Out, Gen, ReachableUses);
478 }
479
480 #ifndef NDEBUG
481 /// print the result of the reaching definition algorithm.
482 static void printReachingDef(const InstrToInstrs *ColorOpToReachedUses,
483                              unsigned NbReg, const TargetRegisterInfo *TRI,
484                              const MapIdToReg &IdToReg) {
485   unsigned CurReg;
486   for (CurReg = 0; CurReg < NbReg; ++CurReg) {
487     if (ColorOpToReachedUses[CurReg].empty())
488       continue;
489     DEBUG(dbgs() << "*** Reg " << PrintReg(IdToReg[CurReg], TRI) << " ***\n");
490
491     for (const auto &DefsIt : ColorOpToReachedUses[CurReg]) {
492       DEBUG(dbgs() << "Def:\n");
493       DEBUG(DefsIt.first->print(dbgs()));
494       DEBUG(dbgs() << "Reachable uses:\n");
495       for (const MachineInstr *MI : DefsIt.second) {
496         DEBUG(MI->print(dbgs()));
497       }
498     }
499   }
500 }
501 #endif // NDEBUG
502
503 /// Answer the following question: Can Def be one of the definition
504 /// involved in a part of a LOH?
505 static bool canDefBePartOfLOH(const MachineInstr *Def) {
506   unsigned Opc = Def->getOpcode();
507   // Accept ADRP, ADDLow and LOADGot.
508   switch (Opc) {
509   default:
510     return false;
511   case ARM64::ADRP:
512     return true;
513   case ARM64::ADDXri:
514     // Check immediate to see if the immediate is an address.
515     switch (Def->getOperand(2).getType()) {
516     default:
517       return false;
518     case MachineOperand::MO_GlobalAddress:
519     case MachineOperand::MO_JumpTableIndex:
520     case MachineOperand::MO_ConstantPoolIndex:
521     case MachineOperand::MO_BlockAddress:
522       return true;
523     }
524   case ARM64::LDRXui:
525     // Check immediate to see if the immediate is an address.
526     switch (Def->getOperand(2).getType()) {
527     default:
528       return false;
529     case MachineOperand::MO_GlobalAddress:
530       return true;
531     }
532   }
533   // Unreachable.
534   return false;
535 }
536
537 /// Check whether the given instruction can the end of a LOH chain involving a
538 /// store.
539 static bool isCandidateStore(const MachineInstr *Instr) {
540   switch (Instr->getOpcode()) {
541   default:
542     return false;
543   case ARM64::STRBui:
544   case ARM64::STRHui:
545   case ARM64::STRWui:
546   case ARM64::STRXui:
547   case ARM64::STRSui:
548   case ARM64::STRDui:
549   case ARM64::STRQui:
550     // In case we have str xA, [xA, #imm], this is two different uses
551     // of xA and we cannot fold, otherwise the xA stored may be wrong,
552     // even if #imm == 0.
553     if (Instr->getOperand(0).getReg() != Instr->getOperand(1).getReg())
554       return true;
555   }
556   return false;
557 }
558
559 /// Given the result of a reaching definition algorithm in ColorOpToReachedUses,
560 /// Build the Use to Defs information and filter out obvious non-LOH candidates.
561 /// In ADRPMode, non-LOH candidates are "uses" with non-ADRP definitions.
562 /// In non-ADRPMode, non-LOH candidates are "uses" with several definition,
563 /// i.e., no simple chain.
564 /// \param ADRPMode -- \see initReachingDef.
565 static void reachedUsesToDefs(InstrToInstrs &UseToReachingDefs,
566                               const InstrToInstrs *ColorOpToReachedUses,
567                               const MapRegToId &RegToId,
568                               bool ADRPMode = false) {
569
570   SetOfMachineInstr NotCandidate;
571   unsigned NbReg = RegToId.size();
572   MapRegToId::const_iterator EndIt = RegToId.end();
573   for (unsigned CurReg = 0; CurReg < NbReg; ++CurReg) {
574     // If this color is never defined, continue.
575     if (ColorOpToReachedUses[CurReg].empty())
576       continue;
577
578     for (const auto &DefsIt : ColorOpToReachedUses[CurReg]) {
579       for (const MachineInstr *MI : DefsIt.second) {
580         const MachineInstr *Def = DefsIt.first;
581         MapRegToId::const_iterator It;
582         // if all the reaching defs are not adrp, this use will not be
583         // simplifiable.
584         if ((ADRPMode && Def->getOpcode() != ARM64::ADRP) ||
585             (!ADRPMode && !canDefBePartOfLOH(Def)) ||
586             (!ADRPMode && isCandidateStore(MI) &&
587              // store are LOH candidate iff the end of the chain is used as
588              // base.
589              ((It = RegToId.find((MI)->getOperand(1).getReg())) == EndIt ||
590               It->second != CurReg))) {
591           NotCandidate.insert(MI);
592           continue;
593         }
594         // Do not consider self reaching as a simplifiable case for ADRP.
595         if (!ADRPMode || MI != DefsIt.first) {
596           UseToReachingDefs[MI].insert(DefsIt.first);
597           // If UsesIt has several reaching definitions, it is not
598           // candidate for simplificaton in non-ADRPMode.
599           if (!ADRPMode && UseToReachingDefs[MI].size() > 1)
600             NotCandidate.insert(MI);
601         }
602       }
603     }
604   }
605   for (const MachineInstr *Elem : NotCandidate) {
606     DEBUG(dbgs() << "Too many reaching defs: " << *Elem << "\n");
607     // It would have been better if we could just remove the entry
608     // from the map.  Because of that, we have to filter the garbage
609     // (second.empty) in the subsequence analysis.
610     UseToReachingDefs[Elem].clear();
611   }
612 }
613
614 /// Based on the use to defs information (in ADRPMode), compute the
615 /// opportunities of LOH ADRP-related.
616 static void computeADRP(const InstrToInstrs &UseToDefs,
617                         ARM64FunctionInfo &ARM64FI,
618                         const MachineDominatorTree *MDT) {
619   DEBUG(dbgs() << "*** Compute LOH for ADRP\n");
620   for (const auto &Entry : UseToDefs) {
621     unsigned Size = Entry.second.size();
622     if (Size == 0)
623       continue;
624     if (Size == 1) {
625       const MachineInstr *L2 = *Entry.second.begin();
626       const MachineInstr *L1 = Entry.first;
627       if (!MDT->dominates(L2, L1)) {
628         DEBUG(dbgs() << "Dominance check failed:\n" << *L2 << '\n' << *L1
629                      << '\n');
630         continue;
631       }
632       DEBUG(dbgs() << "Record AdrpAdrp:\n" << *L2 << '\n' << *L1 << '\n');
633       SmallVector<const MachineInstr *, 2> Args;
634       Args.push_back(L2);
635       Args.push_back(L1);
636       ARM64FI.addLOHDirective(MCLOH_AdrpAdrp, Args);
637       ++NumADRPSimpleCandidate;
638     }
639 #ifdef DEBUG
640     else if (Size == 2)
641       ++NumADRPComplexCandidate2;
642     else if (Size == 3)
643       ++NumADRPComplexCandidate3;
644     else
645       ++NumADRPComplexCandidateOther;
646 #endif
647     // if Size < 1, the use should have been removed from the candidates
648     assert(Size >= 1 && "No reaching defs for that use!");
649   }
650 }
651
652 /// Check whether the given instruction can be the end of a LOH chain
653 /// involving a load.
654 static bool isCandidateLoad(const MachineInstr *Instr) {
655   switch (Instr->getOpcode()) {
656   default:
657     return false;
658   case ARM64::LDRSBWui:
659   case ARM64::LDRSBXui:
660   case ARM64::LDRSHWui:
661   case ARM64::LDRSHXui:
662   case ARM64::LDRSWui:
663   case ARM64::LDRBui:
664   case ARM64::LDRHui:
665   case ARM64::LDRWui:
666   case ARM64::LDRXui:
667   case ARM64::LDRSui:
668   case ARM64::LDRDui:
669   case ARM64::LDRQui:
670     if (Instr->getOperand(2).getTargetFlags() & ARM64II::MO_GOT)
671       return false;
672     return true;
673   }
674   // Unreachable.
675   return false;
676 }
677
678 /// Check whether the given instruction can load a litteral.
679 static bool supportLoadFromLiteral(const MachineInstr *Instr) {
680   switch (Instr->getOpcode()) {
681   default:
682     return false;
683   case ARM64::LDRSWui:
684   case ARM64::LDRWui:
685   case ARM64::LDRXui:
686   case ARM64::LDRSui:
687   case ARM64::LDRDui:
688   case ARM64::LDRQui:
689     return true;
690   }
691   // Unreachable.
692   return false;
693 }
694
695 /// Check whether the given instruction is a LOH candidate.
696 /// \param UseToDefs is used to check that Instr is at the end of LOH supported
697 /// chain.
698 /// \pre UseToDefs contains only on def per use, i.e., obvious non candidate are
699 /// already been filtered out.
700 static bool isCandidate(const MachineInstr *Instr,
701                         const InstrToInstrs &UseToDefs,
702                         const MachineDominatorTree *MDT) {
703   if (!isCandidateLoad(Instr) && !isCandidateStore(Instr))
704     return false;
705
706   const MachineInstr *Def = *UseToDefs.find(Instr)->second.begin();
707   if (Def->getOpcode() != ARM64::ADRP) {
708     // At this point, Def is ADDXri or LDRXui of the right type of
709     // symbol, because we filtered out the uses that were not defined
710     // by these kind of instructions (+ ADRP).
711
712     // Check if this forms a simple chain: each intermediate node must
713     // dominates the next one.
714     if (!MDT->dominates(Def, Instr))
715       return false;
716     // Move one node up in the simple chain.
717     if (UseToDefs.find(Def) ==
718             UseToDefs.end()
719             // The map may contain garbage we have to ignore.
720         ||
721         UseToDefs.find(Def)->second.empty())
722       return false;
723     Instr = Def;
724     Def = *UseToDefs.find(Def)->second.begin();
725   }
726   // Check if we reached the top of the simple chain:
727   // - top is ADRP.
728   // - check the simple chain property: each intermediate node must
729   // dominates the next one.
730   if (Def->getOpcode() == ARM64::ADRP)
731     return MDT->dominates(Def, Instr);
732   return false;
733 }
734
735 static bool registerADRCandidate(const MachineInstr &Use,
736                                  const InstrToInstrs &UseToDefs,
737                                  const InstrToInstrs *DefsPerColorToUses,
738                                  ARM64FunctionInfo &ARM64FI,
739                                  SetOfMachineInstr *InvolvedInLOHs,
740                                  const MapRegToId &RegToId) {
741   // Look for opportunities to turn ADRP -> ADD or
742   // ADRP -> LDR GOTPAGEOFF into ADR.
743   // If ADRP has more than one use. Give up.
744   if (Use.getOpcode() != ARM64::ADDXri &&
745       (Use.getOpcode() != ARM64::LDRXui ||
746        !(Use.getOperand(2).getTargetFlags() & ARM64II::MO_GOT)))
747     return false;
748   InstrToInstrs::const_iterator It = UseToDefs.find(&Use);
749   // The map may contain garbage that we need to ignore.
750   if (It == UseToDefs.end() || It->second.empty())
751     return false;
752   const MachineInstr &Def = **It->second.begin();
753   if (Def.getOpcode() != ARM64::ADRP)
754     return false;
755   // Check the number of users of ADRP.
756   const SetOfMachineInstr *Users =
757       getUses(DefsPerColorToUses,
758               RegToId.find(Def.getOperand(0).getReg())->second, Def);
759   if (Users->size() > 1) {
760     ++NumADRComplexCandidate;
761     return false;
762   }
763   ++NumADRSimpleCandidate;
764   assert((!InvolvedInLOHs || InvolvedInLOHs->insert(&Def)) &&
765          "ADRP already involved in LOH.");
766   assert((!InvolvedInLOHs || InvolvedInLOHs->insert(&Use)) &&
767          "ADD already involved in LOH.");
768   DEBUG(dbgs() << "Record AdrpAdd\n" << Def << '\n' << Use << '\n');
769
770   SmallVector<const MachineInstr *, 2> Args;
771   Args.push_back(&Def);
772   Args.push_back(&Use);
773
774   ARM64FI.addLOHDirective(Use.getOpcode() == ARM64::ADDXri ? MCLOH_AdrpAdd
775                                                            : MCLOH_AdrpLdrGot,
776                           Args);
777   return true;
778 }
779
780 /// Based on the use to defs information (in non-ADRPMode), compute the
781 /// opportunities of LOH non-ADRP-related
782 static void computeOthers(const InstrToInstrs &UseToDefs,
783                           const InstrToInstrs *DefsPerColorToUses,
784                           ARM64FunctionInfo &ARM64FI, const MapRegToId &RegToId,
785                           const MachineDominatorTree *MDT) {
786   SetOfMachineInstr *InvolvedInLOHs = NULL;
787 #ifdef DEBUG
788   SetOfMachineInstr InvolvedInLOHsStorage;
789   InvolvedInLOHs = &InvolvedInLOHsStorage;
790 #endif // DEBUG
791   DEBUG(dbgs() << "*** Compute LOH for Others\n");
792   // ADRP -> ADD/LDR -> LDR/STR pattern.
793   // Fall back to ADRP -> ADD pattern if we fail to catch the bigger pattern.
794
795   // FIXME: When the statistics are not important,
796   // This initial filtering loop can be merged into the next loop.
797   // Currently, we didn't do it to have the same code for both DEBUG and
798   // NDEBUG builds. Indeed, the iterator of the second loop would need
799   // to be changed.
800   SetOfMachineInstr PotentialCandidates;
801   SetOfMachineInstr PotentialADROpportunities;
802   for (auto &Use : UseToDefs) {
803     // If no definition is available, this is a non candidate.
804     if (Use.second.empty())
805       continue;
806     // Keep only instructions that are load or store and at the end of
807     // a ADRP -> ADD/LDR/Nothing chain.
808     // We already filtered out the no-chain cases.
809     if (!isCandidate(Use.first, UseToDefs, MDT)) {
810       PotentialADROpportunities.insert(Use.first);
811       continue;
812     }
813     PotentialCandidates.insert(Use.first);
814   }
815
816   // Make the following distinctions for statistics as the linker does
817   // know how to decode instructions:
818   // - ADD/LDR/Nothing make there different patterns.
819   // - LDR/STR make two different patterns.
820   // Hence, 6 - 1 base patterns.
821   // (because ADRP-> Nothing -> STR is not simplifiable)
822
823   // The linker is only able to have a simple semantic, i.e., if pattern A
824   // do B.
825   // However, we want to see the opportunity we may miss if we were able to
826   // catch more complex cases.
827
828   // PotentialCandidates are result of a chain ADRP -> ADD/LDR ->
829   // A potential candidate becomes a candidate, if its current immediate
830   // operand is zero and all nodes of the chain have respectively only one user
831 #ifdef DEBUG
832   SetOfMachineInstr DefsOfPotentialCandidates;
833 #endif
834   for (const MachineInstr *Candidate : PotentialCandidates) {
835     // Get the definition of the candidate i.e., ADD or LDR.
836     const MachineInstr *Def = *UseToDefs.find(Candidate)->second.begin();
837     // Record the elements of the chain.
838     const MachineInstr *L1 = Def;
839     const MachineInstr *L2 = NULL;
840     unsigned ImmediateDefOpc = Def->getOpcode();
841     if (Def->getOpcode() != ARM64::ADRP) {
842       // Check the number of users of this node.
843       const SetOfMachineInstr *Users =
844           getUses(DefsPerColorToUses,
845                   RegToId.find(Def->getOperand(0).getReg())->second, *Def);
846       if (Users->size() > 1) {
847 #ifdef DEBUG
848         // if all the uses of this def are in potential candidate, this is
849         // a complex candidate of level 2.
850         bool IsLevel2 = true;
851         for (const MachineInstr *MI : *Users) {
852           if (!PotentialCandidates.count(MI)) {
853             ++NumTooCplxLvl2;
854             IsLevel2 = false;
855             break;
856           }
857         }
858         if (IsLevel2)
859           ++NumCplxLvl2;
860 #endif // DEBUG
861         PotentialADROpportunities.insert(Def);
862         continue;
863       }
864       L2 = Def;
865       Def = *UseToDefs.find(Def)->second.begin();
866       L1 = Def;
867     } // else the element in the middle of the chain is nothing, thus
868       // Def already contains the first element of the chain.
869
870     // Check the number of users of the first node in the chain, i.e., ADRP
871     const SetOfMachineInstr *Users =
872         getUses(DefsPerColorToUses,
873                 RegToId.find(Def->getOperand(0).getReg())->second, *Def);
874     if (Users->size() > 1) {
875 #ifdef DEBUG
876       // if all the uses of this def are in the defs of the potential candidate,
877       // this is a complex candidate of level 1
878       if (DefsOfPotentialCandidates.empty()) {
879         // lazy init
880         DefsOfPotentialCandidates = PotentialCandidates;
881         for (const MachineInstr *Candidate : PotentialCandidates) {
882           if (!UseToDefs.find(Candidate)->second.empty())
883             DefsOfPotentialCandidates.insert(
884                 *UseToDefs.find(Candidate)->second.begin());
885         }
886       }
887       bool Found = false;
888       for (auto &Use : *Users) {
889         if (!DefsOfPotentialCandidates.count(Use)) {
890           ++NumTooCplxLvl1;
891           Found = true;
892           break;
893         }
894       }
895       if (!Found)
896         ++NumCplxLvl1;
897 #endif // DEBUG
898       continue;
899     }
900
901     bool IsL2Add = (ImmediateDefOpc == ARM64::ADDXri);
902     // If the chain is three instructions long and ldr is the second element,
903     // then this ldr must load form GOT, otherwise this is not a correct chain.
904     if (L2 && !IsL2Add && L2->getOperand(2).getTargetFlags() != ARM64II::MO_GOT)
905       continue;
906     SmallVector<const MachineInstr *, 3> Args;
907     MCLOHType Kind;
908     if (isCandidateLoad(Candidate)) {
909       if (L2 == NULL) {
910         // At this point, the candidate LOH indicates that the ldr instruction
911         // may use a direct access to the symbol. There is not such encoding
912         // for loads of byte and half.
913         if (!supportLoadFromLiteral(Candidate))
914           continue;
915
916         DEBUG(dbgs() << "Record AdrpLdr:\n" << *L1 << '\n' << *Candidate
917                      << '\n');
918         Kind = MCLOH_AdrpLdr;
919         Args.push_back(L1);
920         Args.push_back(Candidate);
921         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
922                "L1 already involved in LOH.");
923         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
924                "Candidate already involved in LOH.");
925         ++NumADRPToLDR;
926       } else {
927         DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
928                      << "Ldr:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
929                      << '\n');
930
931         Kind = IsL2Add ? MCLOH_AdrpAddLdr : MCLOH_AdrpLdrGotLdr;
932         Args.push_back(L1);
933         Args.push_back(L2);
934         Args.push_back(Candidate);
935
936         PotentialADROpportunities.remove(L2);
937         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
938                "L1 already involved in LOH.");
939         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L2)) &&
940                "L2 already involved in LOH.");
941         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
942                "Candidate already involved in LOH.");
943 #ifdef DEBUG
944         // get the immediate of the load
945         if (Candidate->getOperand(2).getImm() == 0)
946           if (ImmediateDefOpc == ARM64::ADDXri)
947             ++NumADDToLDR;
948           else
949             ++NumLDRToLDR;
950         else if (ImmediateDefOpc == ARM64::ADDXri)
951           ++NumADDToLDRWithImm;
952         else
953           ++NumLDRToLDRWithImm;
954 #endif // DEBUG
955       }
956     } else {
957       if (ImmediateDefOpc == ARM64::ADRP)
958         continue;
959       else {
960
961         DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
962                      << "Str:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
963                      << '\n');
964
965         Kind = IsL2Add ? MCLOH_AdrpAddStr : MCLOH_AdrpLdrGotStr;
966         Args.push_back(L1);
967         Args.push_back(L2);
968         Args.push_back(Candidate);
969
970         PotentialADROpportunities.remove(L2);
971         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
972                "L1 already involved in LOH.");
973         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L2)) &&
974                "L2 already involved in LOH.");
975         assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
976                "Candidate already involved in LOH.");
977 #ifdef DEBUG
978         // get the immediate of the store
979         if (Candidate->getOperand(2).getImm() == 0)
980           if (ImmediateDefOpc == ARM64::ADDXri)
981             ++NumADDToSTR;
982           else
983             ++NumLDRToSTR;
984         else if (ImmediateDefOpc == ARM64::ADDXri)
985           ++NumADDToSTRWithImm;
986         else
987           ++NumLDRToSTRWithImm;
988 #endif // DEBUG
989       }
990     }
991     ARM64FI.addLOHDirective(Kind, Args);
992   }
993
994   // Now, we grabbed all the big patterns, check ADR opportunities.
995   for (const MachineInstr *Candidate : PotentialADROpportunities)
996     registerADRCandidate(*Candidate, UseToDefs, DefsPerColorToUses, ARM64FI,
997                          InvolvedInLOHs, RegToId);
998 }
999
1000 /// Look for every register defined by potential LOHs candidates.
1001 /// Map these registers with dense id in @p RegToId and vice-versa in
1002 /// @p IdToReg. @p IdToReg is populated only in DEBUG mode.
1003 static void collectInvolvedReg(MachineFunction &MF, MapRegToId &RegToId,
1004                                MapIdToReg &IdToReg,
1005                                const TargetRegisterInfo *TRI) {
1006   unsigned CurRegId = 0;
1007   if (!PreCollectRegister) {
1008     unsigned NbReg = TRI->getNumRegs();
1009     for (; CurRegId < NbReg; ++CurRegId) {
1010       RegToId[CurRegId] = CurRegId;
1011       DEBUG(IdToReg.push_back(CurRegId));
1012       DEBUG(assert(IdToReg[CurRegId] == CurRegId && "Reg index mismatches"));
1013     }
1014     return;
1015   }
1016
1017   DEBUG(dbgs() << "** Collect Involved Register\n");
1018   for (const auto &MBB : MF) {
1019     for (const MachineInstr &MI : MBB) {
1020       if (!canDefBePartOfLOH(&MI))
1021         continue;
1022
1023       // Process defs
1024       for (MachineInstr::const_mop_iterator IO = MI.operands_begin(),
1025                                             IOEnd = MI.operands_end();
1026            IO != IOEnd; ++IO) {
1027         if (!IO->isReg() || !IO->isDef())
1028           continue;
1029         unsigned CurReg = IO->getReg();
1030         for (MCRegAliasIterator AI(CurReg, TRI, true); AI.isValid(); ++AI)
1031           if (RegToId.find(*AI) == RegToId.end()) {
1032             DEBUG(IdToReg.push_back(*AI);
1033                   assert(IdToReg[CurRegId] == *AI &&
1034                          "Reg index mismatches insertion index."));
1035             RegToId[*AI] = CurRegId++;
1036             DEBUG(dbgs() << "Register: " << PrintReg(*AI, TRI) << '\n');
1037           }
1038       }
1039     }
1040   }
1041 }
1042
1043 bool ARM64CollectLOH::runOnMachineFunction(MachineFunction &MF) {
1044   const TargetMachine &TM = MF.getTarget();
1045   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1046   const MachineDominatorTree *MDT = &getAnalysis<MachineDominatorTree>();
1047
1048   MapRegToId RegToId;
1049   MapIdToReg IdToReg;
1050   ARM64FunctionInfo *ARM64FI = MF.getInfo<ARM64FunctionInfo>();
1051   assert(ARM64FI && "No MachineFunctionInfo for this function!");
1052
1053   DEBUG(dbgs() << "Looking for LOH in " << MF.getName() << '\n');
1054
1055   collectInvolvedReg(MF, RegToId, IdToReg, TRI);
1056   if (RegToId.empty())
1057     return false;
1058
1059   MachineInstr *DummyOp = NULL;
1060   if (BasicBlockScopeOnly) {
1061     const ARM64InstrInfo *TII =
1062         static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
1063     // For local analysis, create a dummy operation to record uses that are not
1064     // local.
1065     DummyOp = MF.CreateMachineInstr(TII->get(ARM64::COPY), DebugLoc());
1066   }
1067
1068   unsigned NbReg = RegToId.size();
1069   bool Modified = false;
1070
1071   // Start with ADRP.
1072   InstrToInstrs *ColorOpToReachedUses = new InstrToInstrs[NbReg];
1073
1074   // Compute the reaching def in ADRP mode, meaning ADRP definitions
1075   // are first considered as uses.
1076   reachingDef(MF, ColorOpToReachedUses, RegToId, true, DummyOp);
1077   DEBUG(dbgs() << "ADRP reaching defs\n");
1078   DEBUG(printReachingDef(ColorOpToReachedUses, NbReg, TRI, IdToReg));
1079
1080   // Translate the definition to uses map into a use to definitions map to ease
1081   // statistic computation.
1082   InstrToInstrs ADRPToReachingDefs;
1083   reachedUsesToDefs(ADRPToReachingDefs, ColorOpToReachedUses, RegToId, true);
1084
1085   // Compute LOH for ADRP.
1086   computeADRP(ADRPToReachingDefs, *ARM64FI, MDT);
1087   delete[] ColorOpToReachedUses;
1088
1089   // Continue with general ADRP -> ADD/LDR -> LDR/STR pattern.
1090   ColorOpToReachedUses = new InstrToInstrs[NbReg];
1091
1092   // first perform a regular reaching def analysis.
1093   reachingDef(MF, ColorOpToReachedUses, RegToId, false, DummyOp);
1094   DEBUG(dbgs() << "All reaching defs\n");
1095   DEBUG(printReachingDef(ColorOpToReachedUses, NbReg, TRI, IdToReg));
1096
1097   // Turn that into a use to defs to ease statistic computation.
1098   InstrToInstrs UsesToReachingDefs;
1099   reachedUsesToDefs(UsesToReachingDefs, ColorOpToReachedUses, RegToId, false);
1100
1101   // Compute other than AdrpAdrp LOH.
1102   computeOthers(UsesToReachingDefs, ColorOpToReachedUses, *ARM64FI, RegToId,
1103                 MDT);
1104   delete[] ColorOpToReachedUses;
1105
1106   if (BasicBlockScopeOnly)
1107     MF.DeleteMachineInstr(DummyOp);
1108
1109   return Modified;
1110 }
1111
1112 /// createARM64CollectLOHPass - returns an instance of the Statistic for
1113 /// linker optimization pass.
1114 FunctionPass *llvm::createARM64CollectLOHPass() {
1115   return new ARM64CollectLOH();
1116 }