1 //===-------------- ARM64CollectLOH.cpp - ARM64 collect LOH pass --*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
13 // To be useful for the linker, the LOH must be printed into the assembly file.
15 // A LOH describes a sequence of instructions that may be optimized by the
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
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:
33 // L3: ldr xC, [xB, #imm]
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
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
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
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.
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.
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 //===----------------------------------------------------------------------===//
101 #define DEBUG_TYPE "arm64-collect-loh"
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;
127 PreCollectRegister("arm64-collect-loh-pre-collect-register", cl::Hidden,
128 cl::desc("Restrict analysis to registers invovled"
133 BasicBlockScopeOnly("arm64-collect-loh-bb-only", cl::Hidden,
134 cl::desc("Restrict analysis at basic block scope"),
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");
166 void initializeARM64CollectLOHPass(PassRegistry &);
170 struct ARM64CollectLOH : public MachineFunctionPass {
172 ARM64CollectLOH() : MachineFunctionPass(ID) {
173 initializeARM64CollectLOHPass(*PassRegistry::getPassRegistry());
176 virtual bool runOnMachineFunction(MachineFunction &MF);
178 virtual const char *getPassName() const {
179 return "ARM64 Collect Linker Optimization Hint (LOH)";
182 void getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesAll();
184 MachineFunctionPass::getAnalysisUsage(AU);
185 AU.addRequired<MachineDominatorTree>();
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
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
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;
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.
216 char ARM64CollectLOH::ID = 0;
218 INITIALIZE_PASS_BEGIN(ARM64CollectLOH, "arm64-collect-loh",
219 "ARM64 Collect Linker Optimization Hint (LOH)", false,
221 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
222 INITIALIZE_PASS_END(ARM64CollectLOH, "arm64-collect-loh",
223 "ARM64 Collect Linker Optimization Hint (LOH)", false,
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,
235 SetOfMachineInstr *result;
236 BlockToSetOfInstrsPerColor::iterator it = sets.find(&MBB);
237 if (it != sets.end())
240 result = sets[&MBB] = new SetOfMachineInstr[nbRegs];
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
251 /// \pre set[reg] is valid.
252 static SetOfMachineInstr &getUses(InstrToInstrs *sets, unsigned reg,
253 const MachineInstr &MI) {
254 return sets[reg][&MI];
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);
267 /// Initialize the reaching definition algorithm:
268 /// For each basic block BB in MF, record:
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();
287 unsigned NbReg = RegToId.size();
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);
294 BitVector &BBKillSet = Kill[&MBB];
295 BBKillSet.resize(NbReg);
296 for (const MachineInstr &MI : MBB) {
297 bool IsADRP = MI.getOpcode() == ARM64::ADRP;
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())))
307 unsigned CurReg = MO.getReg();
308 MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
309 if (ItCurRegId == RegToId.end())
311 CurReg = ItCurRegId->second;
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.
318 getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(&MI);
322 for (const MachineOperand &MO : MI.operands()) {
325 // Clobbers kill the related colors.
326 const uint32_t *PreservedRegs = MO.getRegMask();
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
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;
343 // Process register defs.
344 for (const MachineOperand &MO : MI.operands()) {
345 if (!MO.isReg() || !MO.isDef())
347 unsigned CurReg = MO.getReg();
348 MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
349 if (ItCurRegId == RegToId.end())
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;
360 BBGen[ItCurRegId->second] = &MI;
364 // If we restrict our analysis to basic block scope, conservatively add a
366 // use for each generated value.
367 if (!ADRPMode && DummyOp && !MBB.succ_empty())
368 for (unsigned CurReg = 0; CurReg < NbReg; ++CurReg)
370 getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(DummyOp);
374 /// Reaching def core algorithm:
375 /// while an Out has changed
378 /// In[bb][color] = U Out[bb.predecessors][color]
379 /// insert reachableUses[bb][color] in each in[bb][color]
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,
393 for (MachineBasicBlock &MBB : MF) {
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());
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());
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;
420 } while (HasChanged);
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) {
433 for (auto &IT : ReachableUses)
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
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
448 /// \pre ColorOpToReachedUses is an array of at least number of registers of
450 static void reachingDef(MachineFunction &MF,
451 InstrToInstrs *ColorOpToReachedUses,
452 const MapRegToId &RegToId, bool ADRPMode = false,
453 const MachineInstr *DummyOp = NULL) {
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;
467 // Initialize Gen, kill and reachableUses.
468 initReachingDef(MF, ColorOpToReachedUses, Gen, Kill, ReachableUses, RegToId,
473 reachingDefAlgorithm(MF, ColorOpToReachedUses, In, Out, Gen, Kill,
474 ReachableUses, RegToId.size());
477 finitReachingDef(In, Out, Gen, ReachableUses);
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) {
486 for (CurReg = 0; CurReg < NbReg; ++CurReg) {
487 if (ColorOpToReachedUses[CurReg].empty())
489 DEBUG(dbgs() << "*** Reg " << PrintReg(IdToReg[CurReg], TRI) << " ***\n");
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()));
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.
514 // Check immediate to see if the immediate is an address.
515 switch (Def->getOperand(2).getType()) {
518 case MachineOperand::MO_GlobalAddress:
519 case MachineOperand::MO_JumpTableIndex:
520 case MachineOperand::MO_ConstantPoolIndex:
521 case MachineOperand::MO_BlockAddress:
525 // Check immediate to see if the immediate is an address.
526 switch (Def->getOperand(2).getType()) {
529 case MachineOperand::MO_GlobalAddress:
537 /// Check whether the given instruction can the end of a LOH chain involving a
539 static bool isCandidateStore(const MachineInstr *Instr) {
540 switch (Instr->getOpcode()) {
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())
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) {
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())
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
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
589 ((It = RegToId.find((MI)->getOperand(1).getReg())) == EndIt ||
590 It->second != CurReg))) {
591 NotCandidate.insert(MI);
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);
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();
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();
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
632 DEBUG(dbgs() << "Record AdrpAdrp:\n" << *L2 << '\n' << *L1 << '\n');
633 SmallVector<const MachineInstr *, 2> Args;
636 ARM64FI.addLOHDirective(MCLOH_AdrpAdrp, Args);
637 ++NumADRPSimpleCandidate;
641 ++NumADRPComplexCandidate2;
643 ++NumADRPComplexCandidate3;
645 ++NumADRPComplexCandidateOther;
647 // if Size < 1, the use should have been removed from the candidates
648 assert(Size >= 1 && "No reaching defs for that use!");
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()) {
658 case ARM64::LDRSBWui:
659 case ARM64::LDRSBXui:
660 case ARM64::LDRSHWui:
661 case ARM64::LDRSHXui:
670 if (Instr->getOperand(2).getTargetFlags() & ARM64II::MO_GOT)
678 /// Check whether the given instruction can load a litteral.
679 static bool supportLoadFromLiteral(const MachineInstr *Instr) {
680 switch (Instr->getOpcode()) {
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
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))
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).
712 // Check if this forms a simple chain: each intermediate node must
713 // dominates the next one.
714 if (!MDT->dominates(Def, Instr))
716 // Move one node up in the simple chain.
717 if (UseToDefs.find(Def) ==
719 // The map may contain garbage we have to ignore.
721 UseToDefs.find(Def)->second.empty())
724 Def = *UseToDefs.find(Def)->second.begin();
726 // Check if we reached the top of the simple chain:
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);
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)))
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())
752 const MachineInstr &Def = **It->second.begin();
753 if (Def.getOpcode() != ARM64::ADRP)
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;
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');
770 SmallVector<const MachineInstr *, 2> Args;
771 Args.push_back(&Def);
772 Args.push_back(&Use);
774 ARM64FI.addLOHDirective(Use.getOpcode() == ARM64::ADDXri ? MCLOH_AdrpAdd
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;
788 SetOfMachineInstr InvolvedInLOHsStorage;
789 InvolvedInLOHs = &InvolvedInLOHsStorage;
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.
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
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())
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);
813 PotentialCandidates.insert(Use.first);
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)
823 // The linker is only able to have a simple semantic, i.e., if pattern A
825 // However, we want to see the opportunity we may miss if we were able to
826 // catch more complex cases.
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
832 SetOfMachineInstr DefsOfPotentialCandidates;
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) {
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)) {
861 PotentialADROpportunities.insert(Def);
865 Def = *UseToDefs.find(Def)->second.begin();
867 } // else the element in the middle of the chain is nothing, thus
868 // Def already contains the first element of the chain.
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) {
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()) {
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());
888 for (auto &Use : *Users) {
889 if (!DefsOfPotentialCandidates.count(Use)) {
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)
906 SmallVector<const MachineInstr *, 3> Args;
908 if (isCandidateLoad(Candidate)) {
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))
916 DEBUG(dbgs() << "Record AdrpLdr:\n" << *L1 << '\n' << *Candidate
918 Kind = MCLOH_AdrpLdr;
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.");
927 DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
928 << "Ldr:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
931 Kind = IsL2Add ? MCLOH_AdrpAddLdr : MCLOH_AdrpLdrGotLdr;
934 Args.push_back(Candidate);
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.");
944 // get the immediate of the load
945 if (Candidate->getOperand(2).getImm() == 0)
946 if (ImmediateDefOpc == ARM64::ADDXri)
950 else if (ImmediateDefOpc == ARM64::ADDXri)
951 ++NumADDToLDRWithImm;
953 ++NumLDRToLDRWithImm;
957 if (ImmediateDefOpc == ARM64::ADRP)
961 DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
962 << "Str:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
965 Kind = IsL2Add ? MCLOH_AdrpAddStr : MCLOH_AdrpLdrGotStr;
968 Args.push_back(Candidate);
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.");
978 // get the immediate of the store
979 if (Candidate->getOperand(2).getImm() == 0)
980 if (ImmediateDefOpc == ARM64::ADDXri)
984 else if (ImmediateDefOpc == ARM64::ADDXri)
985 ++NumADDToSTRWithImm;
987 ++NumLDRToSTRWithImm;
991 ARM64FI.addLOHDirective(Kind, Args);
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);
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"));
1017 DEBUG(dbgs() << "** Collect Involved Register\n");
1018 for (const auto &MBB : MF) {
1019 for (const MachineInstr &MI : MBB) {
1020 if (!canDefBePartOfLOH(&MI))
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())
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');
1043 bool ARM64CollectLOH::runOnMachineFunction(MachineFunction &MF) {
1044 const TargetMachine &TM = MF.getTarget();
1045 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1046 const MachineDominatorTree *MDT = &getAnalysis<MachineDominatorTree>();
1050 ARM64FunctionInfo *ARM64FI = MF.getInfo<ARM64FunctionInfo>();
1051 assert(ARM64FI && "No MachineFunctionInfo for this function!");
1053 DEBUG(dbgs() << "Looking for LOH in " << MF.getName() << '\n');
1055 collectInvolvedReg(MF, RegToId, IdToReg, TRI);
1056 if (RegToId.empty())
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
1065 DummyOp = MF.CreateMachineInstr(TII->get(ARM64::COPY), DebugLoc());
1068 unsigned NbReg = RegToId.size();
1069 bool Modified = false;
1072 InstrToInstrs *ColorOpToReachedUses = new InstrToInstrs[NbReg];
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));
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);
1085 // Compute LOH for ADRP.
1086 computeADRP(ADRPToReachingDefs, *ARM64FI, MDT);
1087 delete[] ColorOpToReachedUses;
1089 // Continue with general ADRP -> ADD/LDR -> LDR/STR pattern.
1090 ColorOpToReachedUses = new InstrToInstrs[NbReg];
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));
1097 // Turn that into a use to defs to ease statistic computation.
1098 InstrToInstrs UsesToReachingDefs;
1099 reachedUsesToDefs(UsesToReachingDefs, ColorOpToReachedUses, RegToId, false);
1101 // Compute other than AdrpAdrp LOH.
1102 computeOthers(UsesToReachingDefs, ColorOpToReachedUses, *ARM64FI, RegToId,
1104 delete[] ColorOpToReachedUses;
1106 if (BasicBlockScopeOnly)
1107 MF.DeleteMachineInstr(DummyOp);
1112 /// createARM64CollectLOHPass - returns an instance of the Statistic for
1113 /// linker optimization pass.
1114 FunctionPass *llvm::createARM64CollectLOHPass() {
1115 return new ARM64CollectLOH();