File: | lib/CodeGen/RegisterCoalescer.cpp |
Warning: | line 3519, column 7 1st function call argument is an uninitialized value |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements the generic RegisterCoalescer interface which | |||
10 | // is used as the common interface used by all clients and | |||
11 | // implementations of register coalescing. | |||
12 | // | |||
13 | //===----------------------------------------------------------------------===// | |||
14 | ||||
15 | #include "RegisterCoalescer.h" | |||
16 | #include "llvm/ADT/ArrayRef.h" | |||
17 | #include "llvm/ADT/BitVector.h" | |||
18 | #include "llvm/ADT/DenseSet.h" | |||
19 | #include "llvm/ADT/STLExtras.h" | |||
20 | #include "llvm/ADT/SmallPtrSet.h" | |||
21 | #include "llvm/ADT/SmallVector.h" | |||
22 | #include "llvm/ADT/Statistic.h" | |||
23 | #include "llvm/Analysis/AliasAnalysis.h" | |||
24 | #include "llvm/CodeGen/LiveInterval.h" | |||
25 | #include "llvm/CodeGen/LiveIntervals.h" | |||
26 | #include "llvm/CodeGen/LiveRangeEdit.h" | |||
27 | #include "llvm/CodeGen/MachineBasicBlock.h" | |||
28 | #include "llvm/CodeGen/MachineFunction.h" | |||
29 | #include "llvm/CodeGen/MachineFunctionPass.h" | |||
30 | #include "llvm/CodeGen/MachineInstr.h" | |||
31 | #include "llvm/CodeGen/MachineInstrBuilder.h" | |||
32 | #include "llvm/CodeGen/MachineLoopInfo.h" | |||
33 | #include "llvm/CodeGen/MachineOperand.h" | |||
34 | #include "llvm/CodeGen/MachineRegisterInfo.h" | |||
35 | #include "llvm/CodeGen/Passes.h" | |||
36 | #include "llvm/CodeGen/RegisterClassInfo.h" | |||
37 | #include "llvm/CodeGen/SlotIndexes.h" | |||
38 | #include "llvm/CodeGen/TargetInstrInfo.h" | |||
39 | #include "llvm/CodeGen/TargetOpcodes.h" | |||
40 | #include "llvm/CodeGen/TargetRegisterInfo.h" | |||
41 | #include "llvm/CodeGen/TargetSubtargetInfo.h" | |||
42 | #include "llvm/IR/DebugLoc.h" | |||
43 | #include "llvm/MC/LaneBitmask.h" | |||
44 | #include "llvm/MC/MCInstrDesc.h" | |||
45 | #include "llvm/MC/MCRegisterInfo.h" | |||
46 | #include "llvm/Pass.h" | |||
47 | #include "llvm/Support/CommandLine.h" | |||
48 | #include "llvm/Support/Compiler.h" | |||
49 | #include "llvm/Support/Debug.h" | |||
50 | #include "llvm/Support/ErrorHandling.h" | |||
51 | #include "llvm/Support/raw_ostream.h" | |||
52 | #include <algorithm> | |||
53 | #include <cassert> | |||
54 | #include <iterator> | |||
55 | #include <limits> | |||
56 | #include <tuple> | |||
57 | #include <utility> | |||
58 | #include <vector> | |||
59 | ||||
60 | using namespace llvm; | |||
61 | ||||
62 | #define DEBUG_TYPE"regalloc" "regalloc" | |||
63 | ||||
64 | STATISTIC(numJoins , "Number of interval joins performed")static llvm::Statistic numJoins = {"regalloc", "numJoins", "Number of interval joins performed" , {0}, {false}}; | |||
65 | STATISTIC(numCrossRCs , "Number of cross class joins performed")static llvm::Statistic numCrossRCs = {"regalloc", "numCrossRCs" , "Number of cross class joins performed", {0}, {false}}; | |||
66 | STATISTIC(numCommutes , "Number of instruction commuting performed")static llvm::Statistic numCommutes = {"regalloc", "numCommutes" , "Number of instruction commuting performed", {0}, {false}}; | |||
67 | STATISTIC(numExtends , "Number of copies extended")static llvm::Statistic numExtends = {"regalloc", "numExtends" , "Number of copies extended", {0}, {false}}; | |||
68 | STATISTIC(NumReMats , "Number of instructions re-materialized")static llvm::Statistic NumReMats = {"regalloc", "NumReMats", "Number of instructions re-materialized" , {0}, {false}}; | |||
69 | STATISTIC(NumInflated , "Number of register classes inflated")static llvm::Statistic NumInflated = {"regalloc", "NumInflated" , "Number of register classes inflated", {0}, {false}}; | |||
70 | STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested")static llvm::Statistic NumLaneConflicts = {"regalloc", "NumLaneConflicts" , "Number of dead lane conflicts tested", {0}, {false}}; | |||
71 | STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved")static llvm::Statistic NumLaneResolves = {"regalloc", "NumLaneResolves" , "Number of dead lane conflicts resolved", {0}, {false}}; | |||
72 | STATISTIC(NumShrinkToUses, "Number of shrinkToUses called")static llvm::Statistic NumShrinkToUses = {"regalloc", "NumShrinkToUses" , "Number of shrinkToUses called", {0}, {false}}; | |||
73 | ||||
74 | static cl::opt<bool> EnableJoining("join-liveintervals", | |||
75 | cl::desc("Coalesce copies (default=true)"), | |||
76 | cl::init(true), cl::Hidden); | |||
77 | ||||
78 | static cl::opt<bool> UseTerminalRule("terminal-rule", | |||
79 | cl::desc("Apply the terminal rule"), | |||
80 | cl::init(false), cl::Hidden); | |||
81 | ||||
82 | /// Temporary flag to test critical edge unsplitting. | |||
83 | static cl::opt<bool> | |||
84 | EnableJoinSplits("join-splitedges", | |||
85 | cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden); | |||
86 | ||||
87 | /// Temporary flag to test global copy optimization. | |||
88 | static cl::opt<cl::boolOrDefault> | |||
89 | EnableGlobalCopies("join-globalcopies", | |||
90 | cl::desc("Coalesce copies that span blocks (default=subtarget)"), | |||
91 | cl::init(cl::BOU_UNSET), cl::Hidden); | |||
92 | ||||
93 | static cl::opt<bool> | |||
94 | VerifyCoalescing("verify-coalescing", | |||
95 | cl::desc("Verify machine instrs before and after register coalescing"), | |||
96 | cl::Hidden); | |||
97 | ||||
98 | static cl::opt<unsigned> LateRematUpdateThreshold( | |||
99 | "late-remat-update-threshold", cl::Hidden, | |||
100 | cl::desc("During rematerialization for a copy, if the def instruction has " | |||
101 | "many other copy uses to be rematerialized, delay the multiple " | |||
102 | "separate live interval update work and do them all at once after " | |||
103 | "all those rematerialization are done. It will save a lot of " | |||
104 | "repeated work. "), | |||
105 | cl::init(100)); | |||
106 | ||||
107 | static cl::opt<unsigned> LargeIntervalSizeThreshold( | |||
108 | "large-interval-size-threshold", cl::Hidden, | |||
109 | cl::desc("If the valnos size of an interval is larger than the threshold, " | |||
110 | "it is regarded as a large interval. "), | |||
111 | cl::init(100)); | |||
112 | ||||
113 | static cl::opt<unsigned> LargeIntervalFreqThreshold( | |||
114 | "large-interval-freq-threshold", cl::Hidden, | |||
115 | cl::desc("For a large interval, if it is coalesed with other live " | |||
116 | "intervals many times more than the threshold, stop its " | |||
117 | "coalescing to control the compile time. "), | |||
118 | cl::init(100)); | |||
119 | ||||
120 | namespace { | |||
121 | ||||
122 | class RegisterCoalescer : public MachineFunctionPass, | |||
123 | private LiveRangeEdit::Delegate { | |||
124 | MachineFunction* MF; | |||
125 | MachineRegisterInfo* MRI; | |||
126 | const TargetRegisterInfo* TRI; | |||
127 | const TargetInstrInfo* TII; | |||
128 | LiveIntervals *LIS; | |||
129 | const MachineLoopInfo* Loops; | |||
130 | AliasAnalysis *AA; | |||
131 | RegisterClassInfo RegClassInfo; | |||
132 | ||||
133 | /// A LaneMask to remember on which subregister live ranges we need to call | |||
134 | /// shrinkToUses() later. | |||
135 | LaneBitmask ShrinkMask; | |||
136 | ||||
137 | /// True if the main range of the currently coalesced intervals should be | |||
138 | /// checked for smaller live intervals. | |||
139 | bool ShrinkMainRange; | |||
140 | ||||
141 | /// True if the coalescer should aggressively coalesce global copies | |||
142 | /// in favor of keeping local copies. | |||
143 | bool JoinGlobalCopies; | |||
144 | ||||
145 | /// True if the coalescer should aggressively coalesce fall-thru | |||
146 | /// blocks exclusively containing copies. | |||
147 | bool JoinSplitEdges; | |||
148 | ||||
149 | /// Copy instructions yet to be coalesced. | |||
150 | SmallVector<MachineInstr*, 8> WorkList; | |||
151 | SmallVector<MachineInstr*, 8> LocalWorkList; | |||
152 | ||||
153 | /// Set of instruction pointers that have been erased, and | |||
154 | /// that may be present in WorkList. | |||
155 | SmallPtrSet<MachineInstr*, 8> ErasedInstrs; | |||
156 | ||||
157 | /// Dead instructions that are about to be deleted. | |||
158 | SmallVector<MachineInstr*, 8> DeadDefs; | |||
159 | ||||
160 | /// Virtual registers to be considered for register class inflation. | |||
161 | SmallVector<unsigned, 8> InflateRegs; | |||
162 | ||||
163 | /// The collection of live intervals which should have been updated | |||
164 | /// immediately after rematerialiation but delayed until | |||
165 | /// lateLiveIntervalUpdate is called. | |||
166 | DenseSet<unsigned> ToBeUpdated; | |||
167 | ||||
168 | /// Record how many times the large live interval with many valnos | |||
169 | /// has been tried to join with other live interval. | |||
170 | DenseMap<unsigned, unsigned long> LargeLIVisitCounter; | |||
171 | ||||
172 | /// Recursively eliminate dead defs in DeadDefs. | |||
173 | void eliminateDeadDefs(); | |||
174 | ||||
175 | /// LiveRangeEdit callback for eliminateDeadDefs(). | |||
176 | void LRE_WillEraseInstruction(MachineInstr *MI) override; | |||
177 | ||||
178 | /// Coalesce the LocalWorkList. | |||
179 | void coalesceLocals(); | |||
180 | ||||
181 | /// Join compatible live intervals | |||
182 | void joinAllIntervals(); | |||
183 | ||||
184 | /// Coalesce copies in the specified MBB, putting | |||
185 | /// copies that cannot yet be coalesced into WorkList. | |||
186 | void copyCoalesceInMBB(MachineBasicBlock *MBB); | |||
187 | ||||
188 | /// Tries to coalesce all copies in CurrList. Returns true if any progress | |||
189 | /// was made. | |||
190 | bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList); | |||
191 | ||||
192 | /// If one def has many copy like uses, and those copy uses are all | |||
193 | /// rematerialized, the live interval update needed for those | |||
194 | /// rematerializations will be delayed and done all at once instead | |||
195 | /// of being done multiple times. This is to save compile cost because | |||
196 | /// live interval update is costly. | |||
197 | void lateLiveIntervalUpdate(); | |||
198 | ||||
199 | /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the | |||
200 | /// src/dst of the copy instruction CopyMI. This returns true if the copy | |||
201 | /// was successfully coalesced away. If it is not currently possible to | |||
202 | /// coalesce this interval, but it may be possible if other things get | |||
203 | /// coalesced, then it returns true by reference in 'Again'. | |||
204 | bool joinCopy(MachineInstr *CopyMI, bool &Again); | |||
205 | ||||
206 | /// Attempt to join these two intervals. On failure, this | |||
207 | /// returns false. The output "SrcInt" will not have been modified, so we | |||
208 | /// can use this information below to update aliases. | |||
209 | bool joinIntervals(CoalescerPair &CP); | |||
210 | ||||
211 | /// Attempt joining two virtual registers. Return true on success. | |||
212 | bool joinVirtRegs(CoalescerPair &CP); | |||
213 | ||||
214 | /// If a live interval has many valnos and is coalesced with other | |||
215 | /// live intervals many times, we regard such live interval as having | |||
216 | /// high compile time cost. | |||
217 | bool isHighCostLiveInterval(LiveInterval &LI); | |||
218 | ||||
219 | /// Attempt joining with a reserved physreg. | |||
220 | bool joinReservedPhysReg(CoalescerPair &CP); | |||
221 | ||||
222 | /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI. | |||
223 | /// Subranges in @p LI which only partially interfere with the desired | |||
224 | /// LaneMask are split as necessary. @p LaneMask are the lanes that | |||
225 | /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange | |||
226 | /// lanemasks already adjusted to the coalesced register. | |||
227 | void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge, | |||
228 | LaneBitmask LaneMask, CoalescerPair &CP); | |||
229 | ||||
230 | /// Join the liveranges of two subregisters. Joins @p RRange into | |||
231 | /// @p LRange, @p RRange may be invalid afterwards. | |||
232 | void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, | |||
233 | LaneBitmask LaneMask, const CoalescerPair &CP); | |||
234 | ||||
235 | /// We found a non-trivially-coalescable copy. If the source value number is | |||
236 | /// defined by a copy from the destination reg see if we can merge these two | |||
237 | /// destination reg valno# into a single value number, eliminating a copy. | |||
238 | /// This returns true if an interval was modified. | |||
239 | bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); | |||
240 | ||||
241 | /// Return true if there are definitions of IntB | |||
242 | /// other than BValNo val# that can reach uses of AValno val# of IntA. | |||
243 | bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, | |||
244 | VNInfo *AValNo, VNInfo *BValNo); | |||
245 | ||||
246 | /// We found a non-trivially-coalescable copy. | |||
247 | /// If the source value number is defined by a commutable instruction and | |||
248 | /// its other operand is coalesced to the copy dest register, see if we | |||
249 | /// can transform the copy into a noop by commuting the definition. | |||
250 | /// This returns a pair of two flags: | |||
251 | /// - the first element is true if an interval was modified, | |||
252 | /// - the second element is true if the destination interval needs | |||
253 | /// to be shrunk after deleting the copy. | |||
254 | std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP, | |||
255 | MachineInstr *CopyMI); | |||
256 | ||||
257 | /// We found a copy which can be moved to its less frequent predecessor. | |||
258 | bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI); | |||
259 | ||||
260 | /// If the source of a copy is defined by a | |||
261 | /// trivial computation, replace the copy by rematerialize the definition. | |||
262 | bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI, | |||
263 | bool &IsDefCopy); | |||
264 | ||||
265 | /// Return true if a copy involving a physreg should be joined. | |||
266 | bool canJoinPhys(const CoalescerPair &CP); | |||
267 | ||||
268 | /// Replace all defs and uses of SrcReg to DstReg and update the subregister | |||
269 | /// number if it is not zero. If DstReg is a physical register and the | |||
270 | /// existing subregister number of the def / use being updated is not zero, | |||
271 | /// make sure to set it to the correct physical subregister. | |||
272 | void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx); | |||
273 | ||||
274 | /// If the given machine operand reads only undefined lanes add an undef | |||
275 | /// flag. | |||
276 | /// This can happen when undef uses were previously concealed by a copy | |||
277 | /// which we coalesced. Example: | |||
278 | /// %0:sub0<def,read-undef> = ... | |||
279 | /// %1 = COPY %0 <-- Coalescing COPY reveals undef | |||
280 | /// = use %1:sub1 <-- hidden undef use | |||
281 | void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, | |||
282 | MachineOperand &MO, unsigned SubRegIdx); | |||
283 | ||||
284 | /// Handle copies of undef values. If the undef value is an incoming | |||
285 | /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF. | |||
286 | /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise, | |||
287 | /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point). | |||
288 | MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI); | |||
289 | ||||
290 | /// Check whether or not we should apply the terminal rule on the | |||
291 | /// destination (Dst) of \p Copy. | |||
292 | /// When the terminal rule applies, Copy is not profitable to | |||
293 | /// coalesce. | |||
294 | /// Dst is terminal if it has exactly one affinity (Dst, Src) and | |||
295 | /// at least one interference (Dst, Dst2). If Dst is terminal, the | |||
296 | /// terminal rule consists in checking that at least one of | |||
297 | /// interfering node, say Dst2, has an affinity of equal or greater | |||
298 | /// weight with Src. | |||
299 | /// In that case, Dst2 and Dst will not be able to be both coalesced | |||
300 | /// with Src. Since Dst2 exposes more coalescing opportunities than | |||
301 | /// Dst, we can drop \p Copy. | |||
302 | bool applyTerminalRule(const MachineInstr &Copy) const; | |||
303 | ||||
304 | /// Wrapper method for \see LiveIntervals::shrinkToUses. | |||
305 | /// This method does the proper fixing of the live-ranges when the afore | |||
306 | /// mentioned method returns true. | |||
307 | void shrinkToUses(LiveInterval *LI, | |||
308 | SmallVectorImpl<MachineInstr * > *Dead = nullptr) { | |||
309 | NumShrinkToUses++; | |||
310 | if (LIS->shrinkToUses(LI, Dead)) { | |||
311 | /// Check whether or not \p LI is composed by multiple connected | |||
312 | /// components and if that is the case, fix that. | |||
313 | SmallVector<LiveInterval*, 8> SplitLIs; | |||
314 | LIS->splitSeparateComponents(*LI, SplitLIs); | |||
315 | } | |||
316 | } | |||
317 | ||||
318 | /// Wrapper Method to do all the necessary work when an Instruction is | |||
319 | /// deleted. | |||
320 | /// Optimizations should use this to make sure that deleted instructions | |||
321 | /// are always accounted for. | |||
322 | void deleteInstr(MachineInstr* MI) { | |||
323 | ErasedInstrs.insert(MI); | |||
324 | LIS->RemoveMachineInstrFromMaps(*MI); | |||
325 | MI->eraseFromParent(); | |||
326 | } | |||
327 | ||||
328 | public: | |||
329 | static char ID; ///< Class identification, replacement for typeinfo | |||
330 | ||||
331 | RegisterCoalescer() : MachineFunctionPass(ID) { | |||
332 | initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); | |||
333 | } | |||
334 | ||||
335 | void getAnalysisUsage(AnalysisUsage &AU) const override; | |||
336 | ||||
337 | void releaseMemory() override; | |||
338 | ||||
339 | /// This is the pass entry point. | |||
340 | bool runOnMachineFunction(MachineFunction&) override; | |||
341 | ||||
342 | /// Implement the dump method. | |||
343 | void print(raw_ostream &O, const Module* = nullptr) const override; | |||
344 | }; | |||
345 | ||||
346 | } // end anonymous namespace | |||
347 | ||||
348 | char RegisterCoalescer::ID = 0; | |||
349 | ||||
350 | char &llvm::RegisterCoalescerID = RegisterCoalescer::ID; | |||
351 | ||||
352 | INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",static void *initializeRegisterCoalescerPassOnce(PassRegistry &Registry) { | |||
353 | "Simple Register Coalescing", false, false)static void *initializeRegisterCoalescerPassOnce(PassRegistry &Registry) { | |||
354 | INITIALIZE_PASS_DEPENDENCY(LiveIntervals)initializeLiveIntervalsPass(Registry); | |||
355 | INITIALIZE_PASS_DEPENDENCY(SlotIndexes)initializeSlotIndexesPass(Registry); | |||
356 | INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)initializeMachineLoopInfoPass(Registry); | |||
357 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | |||
358 | INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",PassInfo *PI = new PassInfo( "Simple Register Coalescing", "simple-register-coalescing" , &RegisterCoalescer::ID, PassInfo::NormalCtor_t(callDefaultCtor <RegisterCoalescer>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeRegisterCoalescerPassFlag ; void llvm::initializeRegisterCoalescerPass(PassRegistry & Registry) { llvm::call_once(InitializeRegisterCoalescerPassFlag , initializeRegisterCoalescerPassOnce, std::ref(Registry)); } | |||
359 | "Simple Register Coalescing", false, false)PassInfo *PI = new PassInfo( "Simple Register Coalescing", "simple-register-coalescing" , &RegisterCoalescer::ID, PassInfo::NormalCtor_t(callDefaultCtor <RegisterCoalescer>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeRegisterCoalescerPassFlag ; void llvm::initializeRegisterCoalescerPass(PassRegistry & Registry) { llvm::call_once(InitializeRegisterCoalescerPassFlag , initializeRegisterCoalescerPassOnce, std::ref(Registry)); } | |||
360 | ||||
361 | static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, | |||
362 | unsigned &Src, unsigned &Dst, | |||
363 | unsigned &SrcSub, unsigned &DstSub) { | |||
364 | if (MI->isCopy()) { | |||
365 | Dst = MI->getOperand(0).getReg(); | |||
366 | DstSub = MI->getOperand(0).getSubReg(); | |||
367 | Src = MI->getOperand(1).getReg(); | |||
368 | SrcSub = MI->getOperand(1).getSubReg(); | |||
369 | } else if (MI->isSubregToReg()) { | |||
370 | Dst = MI->getOperand(0).getReg(); | |||
371 | DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(), | |||
372 | MI->getOperand(3).getImm()); | |||
373 | Src = MI->getOperand(2).getReg(); | |||
374 | SrcSub = MI->getOperand(2).getSubReg(); | |||
375 | } else | |||
376 | return false; | |||
377 | return true; | |||
378 | } | |||
379 | ||||
380 | /// Return true if this block should be vacated by the coalescer to eliminate | |||
381 | /// branches. The important cases to handle in the coalescer are critical edges | |||
382 | /// split during phi elimination which contain only copies. Simple blocks that | |||
383 | /// contain non-branches should also be vacated, but this can be handled by an | |||
384 | /// earlier pass similar to early if-conversion. | |||
385 | static bool isSplitEdge(const MachineBasicBlock *MBB) { | |||
386 | if (MBB->pred_size() != 1 || MBB->succ_size() != 1) | |||
387 | return false; | |||
388 | ||||
389 | for (const auto &MI : *MBB) { | |||
390 | if (!MI.isCopyLike() && !MI.isUnconditionalBranch()) | |||
391 | return false; | |||
392 | } | |||
393 | return true; | |||
394 | } | |||
395 | ||||
396 | bool CoalescerPair::setRegisters(const MachineInstr *MI) { | |||
397 | SrcReg = DstReg = 0; | |||
398 | SrcIdx = DstIdx = 0; | |||
399 | NewRC = nullptr; | |||
400 | Flipped = CrossClass = false; | |||
401 | ||||
402 | unsigned Src, Dst, SrcSub, DstSub; | |||
403 | if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) | |||
404 | return false; | |||
405 | Partial = SrcSub || DstSub; | |||
406 | ||||
407 | // If one register is a physreg, it must be Dst. | |||
408 | if (TargetRegisterInfo::isPhysicalRegister(Src)) { | |||
409 | if (TargetRegisterInfo::isPhysicalRegister(Dst)) | |||
410 | return false; | |||
411 | std::swap(Src, Dst); | |||
412 | std::swap(SrcSub, DstSub); | |||
413 | Flipped = true; | |||
414 | } | |||
415 | ||||
416 | const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo(); | |||
417 | ||||
418 | if (TargetRegisterInfo::isPhysicalRegister(Dst)) { | |||
419 | // Eliminate DstSub on a physreg. | |||
420 | if (DstSub) { | |||
421 | Dst = TRI.getSubReg(Dst, DstSub); | |||
422 | if (!Dst) return false; | |||
423 | DstSub = 0; | |||
424 | } | |||
425 | ||||
426 | // Eliminate SrcSub by picking a corresponding Dst superregister. | |||
427 | if (SrcSub) { | |||
428 | Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src)); | |||
429 | if (!Dst) return false; | |||
430 | } else if (!MRI.getRegClass(Src)->contains(Dst)) { | |||
431 | return false; | |||
432 | } | |||
433 | } else { | |||
434 | // Both registers are virtual. | |||
435 | const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); | |||
436 | const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); | |||
437 | ||||
438 | // Both registers have subreg indices. | |||
439 | if (SrcSub && DstSub) { | |||
440 | // Copies between different sub-registers are never coalescable. | |||
441 | if (Src == Dst && SrcSub != DstSub) | |||
442 | return false; | |||
443 | ||||
444 | NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, | |||
445 | SrcIdx, DstIdx); | |||
446 | if (!NewRC) | |||
447 | return false; | |||
448 | } else if (DstSub) { | |||
449 | // SrcReg will be merged with a sub-register of DstReg. | |||
450 | SrcIdx = DstSub; | |||
451 | NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub); | |||
452 | } else if (SrcSub) { | |||
453 | // DstReg will be merged with a sub-register of SrcReg. | |||
454 | DstIdx = SrcSub; | |||
455 | NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub); | |||
456 | } else { | |||
457 | // This is a straight copy without sub-registers. | |||
458 | NewRC = TRI.getCommonSubClass(DstRC, SrcRC); | |||
459 | } | |||
460 | ||||
461 | // The combined constraint may be impossible to satisfy. | |||
462 | if (!NewRC) | |||
463 | return false; | |||
464 | ||||
465 | // Prefer SrcReg to be a sub-register of DstReg. | |||
466 | // FIXME: Coalescer should support subregs symmetrically. | |||
467 | if (DstIdx && !SrcIdx) { | |||
468 | std::swap(Src, Dst); | |||
469 | std::swap(SrcIdx, DstIdx); | |||
470 | Flipped = !Flipped; | |||
471 | } | |||
472 | ||||
473 | CrossClass = NewRC != DstRC || NewRC != SrcRC; | |||
474 | } | |||
475 | // Check our invariants | |||
476 | assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual")((TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual" ) ? static_cast<void> (0) : __assert_fail ("TargetRegisterInfo::isVirtualRegister(Src) && \"Src must be virtual\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 476, __PRETTY_FUNCTION__)); | |||
477 | assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&((!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub ) && "Cannot have a physical SubIdx") ? static_cast< void> (0) : __assert_fail ("!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) && \"Cannot have a physical SubIdx\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 478, __PRETTY_FUNCTION__)) | |||
478 | "Cannot have a physical SubIdx")((!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub ) && "Cannot have a physical SubIdx") ? static_cast< void> (0) : __assert_fail ("!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) && \"Cannot have a physical SubIdx\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 478, __PRETTY_FUNCTION__)); | |||
479 | SrcReg = Src; | |||
480 | DstReg = Dst; | |||
481 | return true; | |||
482 | } | |||
483 | ||||
484 | bool CoalescerPair::flip() { | |||
485 | if (TargetRegisterInfo::isPhysicalRegister(DstReg)) | |||
486 | return false; | |||
487 | std::swap(SrcReg, DstReg); | |||
488 | std::swap(SrcIdx, DstIdx); | |||
489 | Flipped = !Flipped; | |||
490 | return true; | |||
491 | } | |||
492 | ||||
493 | bool CoalescerPair::isCoalescable(const MachineInstr *MI) const { | |||
494 | if (!MI) | |||
495 | return false; | |||
496 | unsigned Src, Dst, SrcSub, DstSub; | |||
497 | if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) | |||
498 | return false; | |||
499 | ||||
500 | // Find the virtual register that is SrcReg. | |||
501 | if (Dst == SrcReg) { | |||
502 | std::swap(Src, Dst); | |||
503 | std::swap(SrcSub, DstSub); | |||
504 | } else if (Src != SrcReg) { | |||
505 | return false; | |||
506 | } | |||
507 | ||||
508 | // Now check that Dst matches DstReg. | |||
509 | if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { | |||
510 | if (!TargetRegisterInfo::isPhysicalRegister(Dst)) | |||
511 | return false; | |||
512 | assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.")((!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state." ) ? static_cast<void> (0) : __assert_fail ("!DstIdx && !SrcIdx && \"Inconsistent CoalescerPair state.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 512, __PRETTY_FUNCTION__)); | |||
513 | // DstSub could be set for a physreg from INSERT_SUBREG. | |||
514 | if (DstSub) | |||
515 | Dst = TRI.getSubReg(Dst, DstSub); | |||
516 | // Full copy of Src. | |||
517 | if (!SrcSub) | |||
518 | return DstReg == Dst; | |||
519 | // This is a partial register copy. Check that the parts match. | |||
520 | return TRI.getSubReg(DstReg, SrcSub) == Dst; | |||
521 | } else { | |||
522 | // DstReg is virtual. | |||
523 | if (DstReg != Dst) | |||
524 | return false; | |||
525 | // Registers match, do the subregisters line up? | |||
526 | return TRI.composeSubRegIndices(SrcIdx, SrcSub) == | |||
527 | TRI.composeSubRegIndices(DstIdx, DstSub); | |||
528 | } | |||
529 | } | |||
530 | ||||
531 | void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const { | |||
532 | AU.setPreservesCFG(); | |||
533 | AU.addRequired<AAResultsWrapperPass>(); | |||
534 | AU.addRequired<LiveIntervals>(); | |||
535 | AU.addPreserved<LiveIntervals>(); | |||
536 | AU.addPreserved<SlotIndexes>(); | |||
537 | AU.addRequired<MachineLoopInfo>(); | |||
538 | AU.addPreserved<MachineLoopInfo>(); | |||
539 | AU.addPreservedID(MachineDominatorsID); | |||
540 | MachineFunctionPass::getAnalysisUsage(AU); | |||
541 | } | |||
542 | ||||
543 | void RegisterCoalescer::eliminateDeadDefs() { | |||
544 | SmallVector<unsigned, 8> NewRegs; | |||
545 | LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, | |||
546 | nullptr, this).eliminateDeadDefs(DeadDefs); | |||
547 | } | |||
548 | ||||
549 | void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) { | |||
550 | // MI may be in WorkList. Make sure we don't visit it. | |||
551 | ErasedInstrs.insert(MI); | |||
552 | } | |||
553 | ||||
554 | bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP, | |||
555 | MachineInstr *CopyMI) { | |||
556 | assert(!CP.isPartial() && "This doesn't work for partial copies.")((!CP.isPartial() && "This doesn't work for partial copies." ) ? static_cast<void> (0) : __assert_fail ("!CP.isPartial() && \"This doesn't work for partial copies.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 556, __PRETTY_FUNCTION__)); | |||
557 | assert(!CP.isPhys() && "This doesn't work for physreg copies.")((!CP.isPhys() && "This doesn't work for physreg copies." ) ? static_cast<void> (0) : __assert_fail ("!CP.isPhys() && \"This doesn't work for physreg copies.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 557, __PRETTY_FUNCTION__)); | |||
558 | ||||
559 | LiveInterval &IntA = | |||
560 | LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); | |||
561 | LiveInterval &IntB = | |||
562 | LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); | |||
563 | SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); | |||
564 | ||||
565 | // We have a non-trivially-coalescable copy with IntA being the source and | |||
566 | // IntB being the dest, thus this defines a value number in IntB. If the | |||
567 | // source value number (in IntA) is defined by a copy from B, see if we can | |||
568 | // merge these two pieces of B into a single value number, eliminating a copy. | |||
569 | // For example: | |||
570 | // | |||
571 | // A3 = B0 | |||
572 | // ... | |||
573 | // B1 = A3 <- this copy | |||
574 | // | |||
575 | // In this case, B0 can be extended to where the B1 copy lives, allowing the | |||
576 | // B1 value number to be replaced with B0 (which simplifies the B | |||
577 | // liveinterval). | |||
578 | ||||
579 | // BValNo is a value number in B that is defined by a copy from A. 'B1' in | |||
580 | // the example above. | |||
581 | LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx); | |||
582 | if (BS == IntB.end()) return false; | |||
583 | VNInfo *BValNo = BS->valno; | |||
584 | ||||
585 | // Get the location that B is defined at. Two options: either this value has | |||
586 | // an unknown definition point or it is defined at CopyIdx. If unknown, we | |||
587 | // can't process it. | |||
588 | if (BValNo->def != CopyIdx) return false; | |||
589 | ||||
590 | // AValNo is the value number in A that defines the copy, A3 in the example. | |||
591 | SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true); | |||
592 | LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx); | |||
593 | // The live segment might not exist after fun with physreg coalescing. | |||
594 | if (AS == IntA.end()) return false; | |||
595 | VNInfo *AValNo = AS->valno; | |||
596 | ||||
597 | // If AValNo is defined as a copy from IntB, we can potentially process this. | |||
598 | // Get the instruction that defines this value number. | |||
599 | MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def); | |||
600 | // Don't allow any partial copies, even if isCoalescable() allows them. | |||
601 | if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy()) | |||
602 | return false; | |||
603 | ||||
604 | // Get the Segment in IntB that this value number starts with. | |||
605 | LiveInterval::iterator ValS = | |||
606 | IntB.FindSegmentContaining(AValNo->def.getPrevSlot()); | |||
607 | if (ValS == IntB.end()) | |||
608 | return false; | |||
609 | ||||
610 | // Make sure that the end of the live segment is inside the same block as | |||
611 | // CopyMI. | |||
612 | MachineInstr *ValSEndInst = | |||
613 | LIS->getInstructionFromIndex(ValS->end.getPrevSlot()); | |||
614 | if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent()) | |||
615 | return false; | |||
616 | ||||
617 | // Okay, we now know that ValS ends in the same block that the CopyMI | |||
618 | // live-range starts. If there are no intervening live segments between them | |||
619 | // in IntB, we can merge them. | |||
620 | if (ValS+1 != BS) return false; | |||
621 | ||||
622 | LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg, TRI))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Extending: " << printReg (IntB.reg, TRI); } } while (false); | |||
623 | ||||
624 | SlotIndex FillerStart = ValS->end, FillerEnd = BS->start; | |||
625 | // We are about to delete CopyMI, so need to remove it as the 'instruction | |||
626 | // that defines this value #'. Update the valnum with the new defining | |||
627 | // instruction #. | |||
628 | BValNo->def = FillerStart; | |||
629 | ||||
630 | // Okay, we can merge them. We need to insert a new liverange: | |||
631 | // [ValS.end, BS.begin) of either value number, then we merge the | |||
632 | // two value numbers. | |||
633 | IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo)); | |||
634 | ||||
635 | // Okay, merge "B1" into the same value number as "B0". | |||
636 | if (BValNo != ValS->valno) | |||
637 | IntB.MergeValueNumberInto(BValNo, ValS->valno); | |||
638 | ||||
639 | // Do the same for the subregister segments. | |||
640 | for (LiveInterval::SubRange &S : IntB.subranges()) { | |||
641 | // Check for SubRange Segments of the form [1234r,1234d:0) which can be | |||
642 | // removed to prevent creating bogus SubRange Segments. | |||
643 | LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx); | |||
644 | if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) { | |||
645 | S.removeSegment(*SS, true); | |||
646 | continue; | |||
647 | } | |||
648 | VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); | |||
649 | S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo)); | |||
650 | VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot()); | |||
651 | if (SubBValNo != SubValSNo) | |||
652 | S.MergeValueNumberInto(SubBValNo, SubValSNo); | |||
653 | } | |||
654 | ||||
655 | LLVM_DEBUG(dbgs() << " result = " << IntB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << " result = " << IntB << '\n'; } } while (false); | |||
656 | ||||
657 | // If the source instruction was killing the source register before the | |||
658 | // merge, unset the isKill marker given the live range has been extended. | |||
659 | int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true); | |||
660 | if (UIdx != -1) { | |||
661 | ValSEndInst->getOperand(UIdx).setIsKill(false); | |||
662 | } | |||
663 | ||||
664 | // Rewrite the copy. | |||
665 | CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI); | |||
666 | // If the copy instruction was killing the destination register or any | |||
667 | // subrange before the merge trim the live range. | |||
668 | bool RecomputeLiveRange = AS->end == CopyIdx; | |||
669 | if (!RecomputeLiveRange) { | |||
670 | for (LiveInterval::SubRange &S : IntA.subranges()) { | |||
671 | LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx); | |||
672 | if (SS != S.end() && SS->end == CopyIdx) { | |||
673 | RecomputeLiveRange = true; | |||
674 | break; | |||
675 | } | |||
676 | } | |||
677 | } | |||
678 | if (RecomputeLiveRange) | |||
679 | shrinkToUses(&IntA); | |||
680 | ||||
681 | ++numExtends; | |||
682 | return true; | |||
683 | } | |||
684 | ||||
685 | bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA, | |||
686 | LiveInterval &IntB, | |||
687 | VNInfo *AValNo, | |||
688 | VNInfo *BValNo) { | |||
689 | // If AValNo has PHI kills, conservatively assume that IntB defs can reach | |||
690 | // the PHI values. | |||
691 | if (LIS->hasPHIKill(IntA, AValNo)) | |||
692 | return true; | |||
693 | ||||
694 | for (LiveRange::Segment &ASeg : IntA.segments) { | |||
695 | if (ASeg.valno != AValNo) continue; | |||
696 | LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start); | |||
697 | if (BI != IntB.begin()) | |||
698 | --BI; | |||
699 | for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) { | |||
700 | if (BI->valno == BValNo) | |||
701 | continue; | |||
702 | if (BI->start <= ASeg.start && BI->end > ASeg.start) | |||
703 | return true; | |||
704 | if (BI->start > ASeg.start && BI->start < ASeg.end) | |||
705 | return true; | |||
706 | } | |||
707 | } | |||
708 | return false; | |||
709 | } | |||
710 | ||||
711 | /// Copy segments with value number @p SrcValNo from liverange @p Src to live | |||
712 | /// range @Dst and use value number @p DstValNo there. | |||
713 | static std::pair<bool,bool> | |||
714 | addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, | |||
715 | const VNInfo *SrcValNo) { | |||
716 | bool Changed = false; | |||
717 | bool MergedWithDead = false; | |||
718 | for (const LiveRange::Segment &S : Src.segments) { | |||
719 | if (S.valno != SrcValNo) | |||
720 | continue; | |||
721 | // This is adding a segment from Src that ends in a copy that is about | |||
722 | // to be removed. This segment is going to be merged with a pre-existing | |||
723 | // segment in Dst. This works, except in cases when the corresponding | |||
724 | // segment in Dst is dead. For example: adding [192r,208r:1) from Src | |||
725 | // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst. | |||
726 | // Recognized such cases, so that the segments can be shrunk. | |||
727 | LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo); | |||
728 | LiveRange::Segment &Merged = *Dst.addSegment(Added); | |||
729 | if (Merged.end.isDead()) | |||
730 | MergedWithDead = true; | |||
731 | Changed = true; | |||
732 | } | |||
733 | return std::make_pair(Changed, MergedWithDead); | |||
734 | } | |||
735 | ||||
736 | std::pair<bool,bool> | |||
737 | RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP, | |||
738 | MachineInstr *CopyMI) { | |||
739 | assert(!CP.isPhys())((!CP.isPhys()) ? static_cast<void> (0) : __assert_fail ("!CP.isPhys()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 739, __PRETTY_FUNCTION__)); | |||
740 | ||||
741 | LiveInterval &IntA = | |||
742 | LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); | |||
743 | LiveInterval &IntB = | |||
744 | LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); | |||
745 | ||||
746 | // We found a non-trivially-coalescable copy with IntA being the source and | |||
747 | // IntB being the dest, thus this defines a value number in IntB. If the | |||
748 | // source value number (in IntA) is defined by a commutable instruction and | |||
749 | // its other operand is coalesced to the copy dest register, see if we can | |||
750 | // transform the copy into a noop by commuting the definition. For example, | |||
751 | // | |||
752 | // A3 = op A2 killed B0 | |||
753 | // ... | |||
754 | // B1 = A3 <- this copy | |||
755 | // ... | |||
756 | // = op A3 <- more uses | |||
757 | // | |||
758 | // ==> | |||
759 | // | |||
760 | // B2 = op B0 killed A2 | |||
761 | // ... | |||
762 | // B1 = B2 <- now an identity copy | |||
763 | // ... | |||
764 | // = op B2 <- more uses | |||
765 | ||||
766 | // BValNo is a value number in B that is defined by a copy from A. 'B1' in | |||
767 | // the example above. | |||
768 | SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); | |||
769 | VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx); | |||
770 | assert(BValNo != nullptr && BValNo->def == CopyIdx)((BValNo != nullptr && BValNo->def == CopyIdx) ? static_cast <void> (0) : __assert_fail ("BValNo != nullptr && BValNo->def == CopyIdx" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 770, __PRETTY_FUNCTION__)); | |||
771 | ||||
772 | // AValNo is the value number in A that defines the copy, A3 in the example. | |||
773 | VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true)); | |||
774 | assert(AValNo && !AValNo->isUnused() && "COPY source not live")((AValNo && !AValNo->isUnused() && "COPY source not live" ) ? static_cast<void> (0) : __assert_fail ("AValNo && !AValNo->isUnused() && \"COPY source not live\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 774, __PRETTY_FUNCTION__)); | |||
775 | if (AValNo->isPHIDef()) | |||
776 | return { false, false }; | |||
777 | MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def); | |||
778 | if (!DefMI) | |||
779 | return { false, false }; | |||
780 | if (!DefMI->isCommutable()) | |||
781 | return { false, false }; | |||
782 | // If DefMI is a two-address instruction then commuting it will change the | |||
783 | // destination register. | |||
784 | int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg); | |||
785 | assert(DefIdx != -1)((DefIdx != -1) ? static_cast<void> (0) : __assert_fail ("DefIdx != -1", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 785, __PRETTY_FUNCTION__)); | |||
786 | unsigned UseOpIdx; | |||
787 | if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx)) | |||
788 | return { false, false }; | |||
789 | ||||
790 | // FIXME: The code below tries to commute 'UseOpIdx' operand with some other | |||
791 | // commutable operand which is expressed by 'CommuteAnyOperandIndex'value | |||
792 | // passed to the method. That _other_ operand is chosen by | |||
793 | // the findCommutedOpIndices() method. | |||
794 | // | |||
795 | // That is obviously an area for improvement in case of instructions having | |||
796 | // more than 2 operands. For example, if some instruction has 3 commutable | |||
797 | // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3, | |||
798 | // op#2<->op#3) of commute transformation should be considered/tried here. | |||
799 | unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex; | |||
800 | if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx)) | |||
801 | return { false, false }; | |||
802 | ||||
803 | MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); | |||
804 | unsigned NewReg = NewDstMO.getReg(); | |||
805 | if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill()) | |||
806 | return { false, false }; | |||
807 | ||||
808 | // Make sure there are no other definitions of IntB that would reach the | |||
809 | // uses which the new definition can reach. | |||
810 | if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) | |||
811 | return { false, false }; | |||
812 | ||||
813 | // If some of the uses of IntA.reg is already coalesced away, return false. | |||
814 | // It's not possible to determine whether it's safe to perform the coalescing. | |||
815 | for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) { | |||
816 | MachineInstr *UseMI = MO.getParent(); | |||
817 | unsigned OpNo = &MO - &UseMI->getOperand(0); | |||
818 | SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI); | |||
819 | LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); | |||
820 | if (US == IntA.end() || US->valno != AValNo) | |||
821 | continue; | |||
822 | // If this use is tied to a def, we can't rewrite the register. | |||
823 | if (UseMI->isRegTiedToDefOperand(OpNo)) | |||
824 | return { false, false }; | |||
825 | } | |||
826 | ||||
827 | LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t' << *DefMI; } } while (false) | |||
828 | << *DefMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t' << *DefMI; } } while (false); | |||
829 | ||||
830 | // At this point we have decided that it is legal to do this | |||
831 | // transformation. Start by commuting the instruction. | |||
832 | MachineBasicBlock *MBB = DefMI->getParent(); | |||
833 | MachineInstr *NewMI = | |||
834 | TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx); | |||
835 | if (!NewMI) | |||
836 | return { false, false }; | |||
837 | if (TargetRegisterInfo::isVirtualRegister(IntA.reg) && | |||
838 | TargetRegisterInfo::isVirtualRegister(IntB.reg) && | |||
839 | !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg))) | |||
840 | return { false, false }; | |||
841 | if (NewMI != DefMI) { | |||
842 | LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI); | |||
843 | MachineBasicBlock::iterator Pos = DefMI; | |||
844 | MBB->insert(Pos, NewMI); | |||
845 | MBB->erase(DefMI); | |||
846 | } | |||
847 | ||||
848 | // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. | |||
849 | // A = or A, B | |||
850 | // ... | |||
851 | // B = A | |||
852 | // ... | |||
853 | // C = killed A | |||
854 | // ... | |||
855 | // = B | |||
856 | ||||
857 | // Update uses of IntA of the specific Val# with IntB. | |||
858 | for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg), | |||
859 | UE = MRI->use_end(); | |||
860 | UI != UE; /* ++UI is below because of possible MI removal */) { | |||
861 | MachineOperand &UseMO = *UI; | |||
862 | ++UI; | |||
863 | if (UseMO.isUndef()) | |||
864 | continue; | |||
865 | MachineInstr *UseMI = UseMO.getParent(); | |||
866 | if (UseMI->isDebugValue()) { | |||
867 | // FIXME These don't have an instruction index. Not clear we have enough | |||
868 | // info to decide whether to do this replacement or not. For now do it. | |||
869 | UseMO.setReg(NewReg); | |||
870 | continue; | |||
871 | } | |||
872 | SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true); | |||
873 | LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); | |||
874 | assert(US != IntA.end() && "Use must be live")((US != IntA.end() && "Use must be live") ? static_cast <void> (0) : __assert_fail ("US != IntA.end() && \"Use must be live\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 874, __PRETTY_FUNCTION__)); | |||
875 | if (US->valno != AValNo) | |||
876 | continue; | |||
877 | // Kill flags are no longer accurate. They are recomputed after RA. | |||
878 | UseMO.setIsKill(false); | |||
879 | if (TargetRegisterInfo::isPhysicalRegister(NewReg)) | |||
880 | UseMO.substPhysReg(NewReg, *TRI); | |||
881 | else | |||
882 | UseMO.setReg(NewReg); | |||
883 | if (UseMI == CopyMI) | |||
884 | continue; | |||
885 | if (!UseMI->isCopy()) | |||
886 | continue; | |||
887 | if (UseMI->getOperand(0).getReg() != IntB.reg || | |||
888 | UseMI->getOperand(0).getSubReg()) | |||
889 | continue; | |||
890 | ||||
891 | // This copy will become a noop. If it's defining a new val#, merge it into | |||
892 | // BValNo. | |||
893 | SlotIndex DefIdx = UseIdx.getRegSlot(); | |||
894 | VNInfo *DVNI = IntB.getVNInfoAt(DefIdx); | |||
895 | if (!DVNI) | |||
896 | continue; | |||
897 | LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI; } } while (false); | |||
898 | assert(DVNI->def == DefIdx)((DVNI->def == DefIdx) ? static_cast<void> (0) : __assert_fail ("DVNI->def == DefIdx", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 898, __PRETTY_FUNCTION__)); | |||
899 | BValNo = IntB.MergeValueNumberInto(DVNI, BValNo); | |||
900 | for (LiveInterval::SubRange &S : IntB.subranges()) { | |||
901 | VNInfo *SubDVNI = S.getVNInfoAt(DefIdx); | |||
902 | if (!SubDVNI) | |||
903 | continue; | |||
904 | VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); | |||
905 | assert(SubBValNo->def == CopyIdx)((SubBValNo->def == CopyIdx) ? static_cast<void> (0) : __assert_fail ("SubBValNo->def == CopyIdx", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 905, __PRETTY_FUNCTION__)); | |||
906 | S.MergeValueNumberInto(SubDVNI, SubBValNo); | |||
907 | } | |||
908 | ||||
909 | deleteInstr(UseMI); | |||
910 | } | |||
911 | ||||
912 | // Extend BValNo by merging in IntA live segments of AValNo. Val# definition | |||
913 | // is updated. | |||
914 | bool ShrinkB = false; | |||
915 | BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); | |||
916 | if (IntA.hasSubRanges() || IntB.hasSubRanges()) { | |||
917 | if (!IntA.hasSubRanges()) { | |||
918 | LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg); | |||
919 | IntA.createSubRangeFrom(Allocator, Mask, IntA); | |||
920 | } else if (!IntB.hasSubRanges()) { | |||
921 | LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg); | |||
922 | IntB.createSubRangeFrom(Allocator, Mask, IntB); | |||
923 | } | |||
924 | SlotIndex AIdx = CopyIdx.getRegSlot(true); | |||
925 | LaneBitmask MaskA; | |||
926 | const SlotIndexes &Indexes = *LIS->getSlotIndexes(); | |||
927 | for (LiveInterval::SubRange &SA : IntA.subranges()) { | |||
928 | VNInfo *ASubValNo = SA.getVNInfoAt(AIdx); | |||
929 | assert(ASubValNo != nullptr)((ASubValNo != nullptr) ? static_cast<void> (0) : __assert_fail ("ASubValNo != nullptr", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 929, __PRETTY_FUNCTION__)); | |||
930 | MaskA |= SA.LaneMask; | |||
931 | ||||
932 | IntB.refineSubRanges( | |||
933 | Allocator, SA.LaneMask, | |||
934 | [&Allocator, &SA, CopyIdx, ASubValNo, | |||
935 | &ShrinkB](LiveInterval::SubRange &SR) { | |||
936 | VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator) | |||
937 | : SR.getVNInfoAt(CopyIdx); | |||
938 | assert(BSubValNo != nullptr)((BSubValNo != nullptr) ? static_cast<void> (0) : __assert_fail ("BSubValNo != nullptr", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 938, __PRETTY_FUNCTION__)); | |||
939 | auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo); | |||
940 | ShrinkB |= P.second; | |||
941 | if (P.first) | |||
942 | BSubValNo->def = ASubValNo->def; | |||
943 | }, | |||
944 | Indexes, *TRI); | |||
945 | } | |||
946 | // Go over all subranges of IntB that have not been covered by IntA, | |||
947 | // and delete the segments starting at CopyIdx. This can happen if | |||
948 | // IntA has undef lanes that are defined in IntB. | |||
949 | for (LiveInterval::SubRange &SB : IntB.subranges()) { | |||
950 | if ((SB.LaneMask & MaskA).any()) | |||
951 | continue; | |||
952 | if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx)) | |||
953 | if (S->start.getBaseIndex() == CopyIdx.getBaseIndex()) | |||
954 | SB.removeSegment(*S, true); | |||
955 | } | |||
956 | } | |||
957 | ||||
958 | BValNo->def = AValNo->def; | |||
959 | auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo); | |||
960 | ShrinkB |= P.second; | |||
961 | LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\textended: " << IntB << '\n'; } } while (false); | |||
962 | ||||
963 | LIS->removeVRegDefAt(IntA, AValNo->def); | |||
964 | ||||
965 | LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttrimmed: " << IntA << '\n'; } } while (false); | |||
966 | ++numCommutes; | |||
967 | return { true, ShrinkB }; | |||
968 | } | |||
969 | ||||
970 | /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a | |||
971 | /// predecessor of BB2, and if B is not redefined on the way from A = B | |||
972 | /// in BB2 to B = A in BB2, B = A in BB2 is partially redundant if the | |||
973 | /// execution goes through the path from BB0 to BB2. We may move B = A | |||
974 | /// to the predecessor without such reversed copy. | |||
975 | /// So we will transform the program from: | |||
976 | /// BB0: | |||
977 | /// A = B; BB1: | |||
978 | /// ... ... | |||
979 | /// / \ / | |||
980 | /// BB2: | |||
981 | /// ... | |||
982 | /// B = A; | |||
983 | /// | |||
984 | /// to: | |||
985 | /// | |||
986 | /// BB0: BB1: | |||
987 | /// A = B; ... | |||
988 | /// ... B = A; | |||
989 | /// / \ / | |||
990 | /// BB2: | |||
991 | /// ... | |||
992 | /// | |||
993 | /// A special case is when BB0 and BB2 are the same BB which is the only | |||
994 | /// BB in a loop: | |||
995 | /// BB1: | |||
996 | /// ... | |||
997 | /// BB0/BB2: ---- | |||
998 | /// B = A; | | |||
999 | /// ... | | |||
1000 | /// A = B; | | |||
1001 | /// |------- | |||
1002 | /// | | |||
1003 | /// We may hoist B = A from BB0/BB2 to BB1. | |||
1004 | /// | |||
1005 | /// The major preconditions for correctness to remove such partial | |||
1006 | /// redundancy include: | |||
1007 | /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of | |||
1008 | /// the PHI is defined by the reversed copy A = B in BB0. | |||
1009 | /// 2. No B is referenced from the start of BB2 to B = A. | |||
1010 | /// 3. No B is defined from A = B to the end of BB0. | |||
1011 | /// 4. BB1 has only one successor. | |||
1012 | /// | |||
1013 | /// 2 and 4 implicitly ensure B is not live at the end of BB1. | |||
1014 | /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a | |||
1015 | /// colder place, which not only prevent endless loop, but also make sure | |||
1016 | /// the movement of copy is beneficial. | |||
1017 | bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP, | |||
1018 | MachineInstr &CopyMI) { | |||
1019 | assert(!CP.isPhys())((!CP.isPhys()) ? static_cast<void> (0) : __assert_fail ("!CP.isPhys()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1019, __PRETTY_FUNCTION__)); | |||
1020 | if (!CopyMI.isFullCopy()) | |||
1021 | return false; | |||
1022 | ||||
1023 | MachineBasicBlock &MBB = *CopyMI.getParent(); | |||
1024 | if (MBB.isEHPad()) | |||
1025 | return false; | |||
1026 | ||||
1027 | if (MBB.pred_size() != 2) | |||
1028 | return false; | |||
1029 | ||||
1030 | LiveInterval &IntA = | |||
1031 | LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); | |||
1032 | LiveInterval &IntB = | |||
1033 | LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); | |||
1034 | ||||
1035 | // A is defined by PHI at the entry of MBB. | |||
1036 | SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true); | |||
1037 | VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx); | |||
1038 | assert(AValNo && !AValNo->isUnused() && "COPY source not live")((AValNo && !AValNo->isUnused() && "COPY source not live" ) ? static_cast<void> (0) : __assert_fail ("AValNo && !AValNo->isUnused() && \"COPY source not live\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1038, __PRETTY_FUNCTION__)); | |||
1039 | if (!AValNo->isPHIDef()) | |||
1040 | return false; | |||
1041 | ||||
1042 | // No B is referenced before CopyMI in MBB. | |||
1043 | if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx)) | |||
1044 | return false; | |||
1045 | ||||
1046 | // MBB has two predecessors: one contains A = B so no copy will be inserted | |||
1047 | // for it. The other one will have a copy moved from MBB. | |||
1048 | bool FoundReverseCopy = false; | |||
1049 | MachineBasicBlock *CopyLeftBB = nullptr; | |||
1050 | for (MachineBasicBlock *Pred : MBB.predecessors()) { | |||
1051 | VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred)); | |||
1052 | MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def); | |||
1053 | if (!DefMI || !DefMI->isFullCopy()) { | |||
1054 | CopyLeftBB = Pred; | |||
1055 | continue; | |||
1056 | } | |||
1057 | // Check DefMI is a reverse copy and it is in BB Pred. | |||
1058 | if (DefMI->getOperand(0).getReg() != IntA.reg || | |||
1059 | DefMI->getOperand(1).getReg() != IntB.reg || | |||
1060 | DefMI->getParent() != Pred) { | |||
1061 | CopyLeftBB = Pred; | |||
1062 | continue; | |||
1063 | } | |||
1064 | // If there is any other def of B after DefMI and before the end of Pred, | |||
1065 | // we need to keep the copy of B = A at the end of Pred if we remove | |||
1066 | // B = A from MBB. | |||
1067 | bool ValB_Changed = false; | |||
1068 | for (auto VNI : IntB.valnos) { | |||
1069 | if (VNI->isUnused()) | |||
1070 | continue; | |||
1071 | if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) { | |||
1072 | ValB_Changed = true; | |||
1073 | break; | |||
1074 | } | |||
1075 | } | |||
1076 | if (ValB_Changed) { | |||
1077 | CopyLeftBB = Pred; | |||
1078 | continue; | |||
1079 | } | |||
1080 | FoundReverseCopy = true; | |||
1081 | } | |||
1082 | ||||
1083 | // If no reverse copy is found in predecessors, nothing to do. | |||
1084 | if (!FoundReverseCopy) | |||
1085 | return false; | |||
1086 | ||||
1087 | // If CopyLeftBB is nullptr, it means every predecessor of MBB contains | |||
1088 | // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated. | |||
1089 | // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and | |||
1090 | // update IntA/IntB. | |||
1091 | // | |||
1092 | // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so | |||
1093 | // MBB is hotter than CopyLeftBB. | |||
1094 | if (CopyLeftBB && CopyLeftBB->succ_size() > 1) | |||
1095 | return false; | |||
1096 | ||||
1097 | // Now (almost sure it's) ok to move copy. | |||
1098 | if (CopyLeftBB) { | |||
1099 | // Position in CopyLeftBB where we should insert new copy. | |||
1100 | auto InsPos = CopyLeftBB->getFirstTerminator(); | |||
1101 | ||||
1102 | // Make sure that B isn't referenced in the terminators (if any) at the end | |||
1103 | // of the predecessor since we're about to insert a new definition of B | |||
1104 | // before them. | |||
1105 | if (InsPos != CopyLeftBB->end()) { | |||
1106 | SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true); | |||
1107 | if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB))) | |||
1108 | return false; | |||
1109 | } | |||
1110 | ||||
1111 | LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremovePartialRedundancy: Move the copy to " << printMBBReference(*CopyLeftBB) << '\t' << CopyMI; } } while (false) | |||
1112 | << printMBBReference(*CopyLeftBB) << '\t' << CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremovePartialRedundancy: Move the copy to " << printMBBReference(*CopyLeftBB) << '\t' << CopyMI; } } while (false); | |||
1113 | ||||
1114 | // Insert new copy to CopyLeftBB. | |||
1115 | MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(), | |||
1116 | TII->get(TargetOpcode::COPY), IntB.reg) | |||
1117 | .addReg(IntA.reg); | |||
1118 | SlotIndex NewCopyIdx = | |||
1119 | LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot(); | |||
1120 | IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator()); | |||
1121 | for (LiveInterval::SubRange &SR : IntB.subranges()) | |||
1122 | SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator()); | |||
1123 | ||||
1124 | // If the newly created Instruction has an address of an instruction that was | |||
1125 | // deleted before (object recycled by the allocator) it needs to be removed from | |||
1126 | // the deleted list. | |||
1127 | ErasedInstrs.erase(NewCopyMI); | |||
1128 | } else { | |||
1129 | LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremovePartialRedundancy: Remove the copy from " << printMBBReference(MBB) << '\t' << CopyMI ; } } while (false) | |||
1130 | << printMBBReference(MBB) << '\t' << CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tremovePartialRedundancy: Remove the copy from " << printMBBReference(MBB) << '\t' << CopyMI ; } } while (false); | |||
1131 | } | |||
1132 | ||||
1133 | // Remove CopyMI. | |||
1134 | // Note: This is fine to remove the copy before updating the live-ranges. | |||
1135 | // While updating the live-ranges, we only look at slot indices and | |||
1136 | // never go back to the instruction. | |||
1137 | // Mark instructions as deleted. | |||
1138 | deleteInstr(&CopyMI); | |||
1139 | ||||
1140 | // Update the liveness. | |||
1141 | SmallVector<SlotIndex, 8> EndPoints; | |||
1142 | VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead(); | |||
1143 | LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(), | |||
1144 | &EndPoints); | |||
1145 | BValNo->markUnused(); | |||
1146 | // Extend IntB to the EndPoints of its original live interval. | |||
1147 | LIS->extendToIndices(IntB, EndPoints); | |||
1148 | ||||
1149 | // Now, do the same for its subranges. | |||
1150 | for (LiveInterval::SubRange &SR : IntB.subranges()) { | |||
1151 | EndPoints.clear(); | |||
1152 | VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead(); | |||
1153 | assert(BValNo && "All sublanes should be live")((BValNo && "All sublanes should be live") ? static_cast <void> (0) : __assert_fail ("BValNo && \"All sublanes should be live\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1153, __PRETTY_FUNCTION__)); | |||
1154 | LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints); | |||
1155 | BValNo->markUnused(); | |||
1156 | // We can have a situation where the result of the original copy is live, | |||
1157 | // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes | |||
1158 | // the copy appear as an endpoint from pruneValue(), but we don't want it | |||
1159 | // to because the copy has been removed. We can go ahead and remove that | |||
1160 | // endpoint; there is no other situation here that there could be a use at | |||
1161 | // the same place as we know that the copy is a full copy. | |||
1162 | for (unsigned I = 0; I != EndPoints.size(); ) { | |||
1163 | if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) { | |||
1164 | EndPoints[I] = EndPoints.back(); | |||
1165 | EndPoints.pop_back(); | |||
1166 | continue; | |||
1167 | } | |||
1168 | ++I; | |||
1169 | } | |||
1170 | LIS->extendToIndices(SR, EndPoints); | |||
1171 | } | |||
1172 | // If any dead defs were extended, truncate them. | |||
1173 | shrinkToUses(&IntB); | |||
1174 | ||||
1175 | // Finally, update the live-range of IntA. | |||
1176 | shrinkToUses(&IntA); | |||
1177 | return true; | |||
1178 | } | |||
1179 | ||||
1180 | /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just | |||
1181 | /// defining a subregister. | |||
1182 | static bool definesFullReg(const MachineInstr &MI, unsigned Reg) { | |||
1183 | assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&((!TargetRegisterInfo::isPhysicalRegister(Reg) && "This code cannot handle physreg aliasing" ) ? static_cast<void> (0) : __assert_fail ("!TargetRegisterInfo::isPhysicalRegister(Reg) && \"This code cannot handle physreg aliasing\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1184, __PRETTY_FUNCTION__)) | |||
1184 | "This code cannot handle physreg aliasing")((!TargetRegisterInfo::isPhysicalRegister(Reg) && "This code cannot handle physreg aliasing" ) ? static_cast<void> (0) : __assert_fail ("!TargetRegisterInfo::isPhysicalRegister(Reg) && \"This code cannot handle physreg aliasing\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1184, __PRETTY_FUNCTION__)); | |||
1185 | for (const MachineOperand &Op : MI.operands()) { | |||
1186 | if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg) | |||
1187 | continue; | |||
1188 | // Return true if we define the full register or don't care about the value | |||
1189 | // inside other subregisters. | |||
1190 | if (Op.getSubReg() == 0 || Op.isUndef()) | |||
1191 | return true; | |||
1192 | } | |||
1193 | return false; | |||
1194 | } | |||
1195 | ||||
1196 | bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP, | |||
1197 | MachineInstr *CopyMI, | |||
1198 | bool &IsDefCopy) { | |||
1199 | IsDefCopy = false; | |||
1200 | unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg(); | |||
1201 | unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx(); | |||
1202 | unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); | |||
1203 | unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx(); | |||
1204 | if (TargetRegisterInfo::isPhysicalRegister(SrcReg)) | |||
1205 | return false; | |||
1206 | ||||
1207 | LiveInterval &SrcInt = LIS->getInterval(SrcReg); | |||
1208 | SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); | |||
1209 | VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn(); | |||
1210 | if (!ValNo) | |||
1211 | return false; | |||
1212 | if (ValNo->isPHIDef() || ValNo->isUnused()) | |||
1213 | return false; | |||
1214 | MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def); | |||
1215 | if (!DefMI) | |||
1216 | return false; | |||
1217 | if (DefMI->isCopyLike()) { | |||
1218 | IsDefCopy = true; | |||
1219 | return false; | |||
1220 | } | |||
1221 | if (!TII->isAsCheapAsAMove(*DefMI)) | |||
1222 | return false; | |||
1223 | if (!TII->isTriviallyReMaterializable(*DefMI, AA)) | |||
1224 | return false; | |||
1225 | if (!definesFullReg(*DefMI, SrcReg)) | |||
1226 | return false; | |||
1227 | bool SawStore = false; | |||
1228 | if (!DefMI->isSafeToMove(AA, SawStore)) | |||
1229 | return false; | |||
1230 | const MCInstrDesc &MCID = DefMI->getDesc(); | |||
1231 | if (MCID.getNumDefs() != 1) | |||
1232 | return false; | |||
1233 | // Only support subregister destinations when the def is read-undef. | |||
1234 | MachineOperand &DstOperand = CopyMI->getOperand(0); | |||
1235 | unsigned CopyDstReg = DstOperand.getReg(); | |||
1236 | if (DstOperand.getSubReg() && !DstOperand.isUndef()) | |||
1237 | return false; | |||
1238 | ||||
1239 | // If both SrcIdx and DstIdx are set, correct rematerialization would widen | |||
1240 | // the register substantially (beyond both source and dest size). This is bad | |||
1241 | // for performance since it can cascade through a function, introducing many | |||
1242 | // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers | |||
1243 | // around after a few subreg copies). | |||
1244 | if (SrcIdx && DstIdx) | |||
1245 | return false; | |||
1246 | ||||
1247 | const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF); | |||
1248 | if (!DefMI->isImplicitDef()) { | |||
1249 | if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { | |||
1250 | unsigned NewDstReg = DstReg; | |||
1251 | ||||
1252 | unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), | |||
1253 | DefMI->getOperand(0).getSubReg()); | |||
1254 | if (NewDstIdx) | |||
1255 | NewDstReg = TRI->getSubReg(DstReg, NewDstIdx); | |||
1256 | ||||
1257 | // Finally, make sure that the physical subregister that will be | |||
1258 | // constructed later is permitted for the instruction. | |||
1259 | if (!DefRC->contains(NewDstReg)) | |||
1260 | return false; | |||
1261 | } else { | |||
1262 | // Theoretically, some stack frame reference could exist. Just make sure | |||
1263 | // it hasn't actually happened. | |||
1264 | assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&((TargetRegisterInfo::isVirtualRegister(DstReg) && "Only expect to deal with virtual or physical registers" ) ? static_cast<void> (0) : __assert_fail ("TargetRegisterInfo::isVirtualRegister(DstReg) && \"Only expect to deal with virtual or physical registers\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1265, __PRETTY_FUNCTION__)) | |||
1265 | "Only expect to deal with virtual or physical registers")((TargetRegisterInfo::isVirtualRegister(DstReg) && "Only expect to deal with virtual or physical registers" ) ? static_cast<void> (0) : __assert_fail ("TargetRegisterInfo::isVirtualRegister(DstReg) && \"Only expect to deal with virtual or physical registers\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1265, __PRETTY_FUNCTION__)); | |||
1266 | } | |||
1267 | } | |||
1268 | ||||
1269 | DebugLoc DL = CopyMI->getDebugLoc(); | |||
1270 | MachineBasicBlock *MBB = CopyMI->getParent(); | |||
1271 | MachineBasicBlock::iterator MII = | |||
1272 | std::next(MachineBasicBlock::iterator(CopyMI)); | |||
1273 | TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI); | |||
1274 | MachineInstr &NewMI = *std::prev(MII); | |||
1275 | NewMI.setDebugLoc(DL); | |||
1276 | ||||
1277 | // In a situation like the following: | |||
1278 | // %0:subreg = instr ; DefMI, subreg = DstIdx | |||
1279 | // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0 | |||
1280 | // instead of widening %1 to the register class of %0 simply do: | |||
1281 | // %1 = instr | |||
1282 | const TargetRegisterClass *NewRC = CP.getNewRC(); | |||
1283 | if (DstIdx != 0) { | |||
1284 | MachineOperand &DefMO = NewMI.getOperand(0); | |||
1285 | if (DefMO.getSubReg() == DstIdx) { | |||
1286 | assert(SrcIdx == 0 && CP.isFlipped()((SrcIdx == 0 && CP.isFlipped() && "Shouldn't have SrcIdx+DstIdx at this point" ) ? static_cast<void> (0) : __assert_fail ("SrcIdx == 0 && CP.isFlipped() && \"Shouldn't have SrcIdx+DstIdx at this point\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1287, __PRETTY_FUNCTION__)) | |||
1287 | && "Shouldn't have SrcIdx+DstIdx at this point")((SrcIdx == 0 && CP.isFlipped() && "Shouldn't have SrcIdx+DstIdx at this point" ) ? static_cast<void> (0) : __assert_fail ("SrcIdx == 0 && CP.isFlipped() && \"Shouldn't have SrcIdx+DstIdx at this point\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1287, __PRETTY_FUNCTION__)); | |||
1288 | const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); | |||
1289 | const TargetRegisterClass *CommonRC = | |||
1290 | TRI->getCommonSubClass(DefRC, DstRC); | |||
1291 | if (CommonRC != nullptr) { | |||
1292 | NewRC = CommonRC; | |||
1293 | DstIdx = 0; | |||
1294 | DefMO.setSubReg(0); | |||
1295 | DefMO.setIsUndef(false); // Only subregs can have def+undef. | |||
1296 | } | |||
1297 | } | |||
1298 | } | |||
1299 | ||||
1300 | // CopyMI may have implicit operands, save them so that we can transfer them | |||
1301 | // over to the newly materialized instruction after CopyMI is removed. | |||
1302 | SmallVector<MachineOperand, 4> ImplicitOps; | |||
1303 | ImplicitOps.reserve(CopyMI->getNumOperands() - | |||
1304 | CopyMI->getDesc().getNumOperands()); | |||
1305 | for (unsigned I = CopyMI->getDesc().getNumOperands(), | |||
1306 | E = CopyMI->getNumOperands(); | |||
1307 | I != E; ++I) { | |||
1308 | MachineOperand &MO = CopyMI->getOperand(I); | |||
1309 | if (MO.isReg()) { | |||
1310 | assert(MO.isImplicit() && "No explicit operands after implicit operands.")((MO.isImplicit() && "No explicit operands after implicit operands." ) ? static_cast<void> (0) : __assert_fail ("MO.isImplicit() && \"No explicit operands after implicit operands.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1310, __PRETTY_FUNCTION__)); | |||
1311 | // Discard VReg implicit defs. | |||
1312 | if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) | |||
1313 | ImplicitOps.push_back(MO); | |||
1314 | } | |||
1315 | } | |||
1316 | ||||
1317 | LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI); | |||
1318 | CopyMI->eraseFromParent(); | |||
1319 | ErasedInstrs.insert(CopyMI); | |||
1320 | ||||
1321 | // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86). | |||
1322 | // We need to remember these so we can add intervals once we insert | |||
1323 | // NewMI into SlotIndexes. | |||
1324 | SmallVector<unsigned, 4> NewMIImplDefs; | |||
1325 | for (unsigned i = NewMI.getDesc().getNumOperands(), | |||
1326 | e = NewMI.getNumOperands(); | |||
1327 | i != e; ++i) { | |||
1328 | MachineOperand &MO = NewMI.getOperand(i); | |||
1329 | if (MO.isReg() && MO.isDef()) { | |||
1330 | assert(MO.isImplicit() && MO.isDead() &&((MO.isImplicit() && MO.isDead() && TargetRegisterInfo ::isPhysicalRegister(MO.getReg())) ? static_cast<void> ( 0) : __assert_fail ("MO.isImplicit() && MO.isDead() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1331, __PRETTY_FUNCTION__)) | |||
1331 | TargetRegisterInfo::isPhysicalRegister(MO.getReg()))((MO.isImplicit() && MO.isDead() && TargetRegisterInfo ::isPhysicalRegister(MO.getReg())) ? static_cast<void> ( 0) : __assert_fail ("MO.isImplicit() && MO.isDead() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1331, __PRETTY_FUNCTION__)); | |||
1332 | NewMIImplDefs.push_back(MO.getReg()); | |||
1333 | } | |||
1334 | } | |||
1335 | ||||
1336 | if (TargetRegisterInfo::isVirtualRegister(DstReg)) { | |||
1337 | unsigned NewIdx = NewMI.getOperand(0).getSubReg(); | |||
1338 | ||||
1339 | if (DefRC != nullptr) { | |||
1340 | if (NewIdx) | |||
1341 | NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx); | |||
1342 | else | |||
1343 | NewRC = TRI->getCommonSubClass(NewRC, DefRC); | |||
1344 | assert(NewRC && "subreg chosen for remat incompatible with instruction")((NewRC && "subreg chosen for remat incompatible with instruction" ) ? static_cast<void> (0) : __assert_fail ("NewRC && \"subreg chosen for remat incompatible with instruction\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1344, __PRETTY_FUNCTION__)); | |||
1345 | } | |||
1346 | // Remap subranges to new lanemask and change register class. | |||
1347 | LiveInterval &DstInt = LIS->getInterval(DstReg); | |||
1348 | for (LiveInterval::SubRange &SR : DstInt.subranges()) { | |||
1349 | SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask); | |||
1350 | } | |||
1351 | MRI->setRegClass(DstReg, NewRC); | |||
1352 | ||||
1353 | // Update machine operands and add flags. | |||
1354 | updateRegDefsUses(DstReg, DstReg, DstIdx); | |||
1355 | NewMI.getOperand(0).setSubReg(NewIdx); | |||
1356 | // updateRegDefUses can add an "undef" flag to the definition, since | |||
1357 | // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make | |||
1358 | // sure that "undef" is not set. | |||
1359 | if (NewIdx == 0) | |||
1360 | NewMI.getOperand(0).setIsUndef(false); | |||
1361 | // Add dead subregister definitions if we are defining the whole register | |||
1362 | // but only part of it is live. | |||
1363 | // This could happen if the rematerialization instruction is rematerializing | |||
1364 | // more than actually is used in the register. | |||
1365 | // An example would be: | |||
1366 | // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs | |||
1367 | // ; Copying only part of the register here, but the rest is undef. | |||
1368 | // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit | |||
1369 | // ==> | |||
1370 | // ; Materialize all the constants but only using one | |||
1371 | // %2 = LOAD_CONSTANTS 5, 8 | |||
1372 | // | |||
1373 | // at this point for the part that wasn't defined before we could have | |||
1374 | // subranges missing the definition. | |||
1375 | if (NewIdx == 0 && DstInt.hasSubRanges()) { | |||
1376 | SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI); | |||
1377 | SlotIndex DefIndex = | |||
1378 | CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber()); | |||
1379 | LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg); | |||
1380 | VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator(); | |||
1381 | for (LiveInterval::SubRange &SR : DstInt.subranges()) { | |||
1382 | if (!SR.liveAt(DefIndex)) | |||
1383 | SR.createDeadDef(DefIndex, Alloc); | |||
1384 | MaxMask &= ~SR.LaneMask; | |||
1385 | } | |||
1386 | if (MaxMask.any()) { | |||
1387 | LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask); | |||
1388 | SR->createDeadDef(DefIndex, Alloc); | |||
1389 | } | |||
1390 | } | |||
1391 | ||||
1392 | // Make sure that the subrange for resultant undef is removed | |||
1393 | // For example: | |||
1394 | // %1:sub1<def,read-undef> = LOAD CONSTANT 1 | |||
1395 | // %2 = COPY %1 | |||
1396 | // ==> | |||
1397 | // %2:sub1<def, read-undef> = LOAD CONSTANT 1 | |||
1398 | // ; Correct but need to remove the subrange for %2:sub0 | |||
1399 | // ; as it is now undef | |||
1400 | if (NewIdx != 0 && DstInt.hasSubRanges()) { | |||
1401 | // The affected subregister segments can be removed. | |||
1402 | SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI); | |||
1403 | LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx); | |||
1404 | bool UpdatedSubRanges = false; | |||
1405 | for (LiveInterval::SubRange &SR : DstInt.subranges()) { | |||
1406 | if ((SR.LaneMask & DstMask).none()) { | |||
1407 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Removing undefined SubRange " << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n"; } } while (false) | |||
1408 | << "Removing undefined SubRange "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Removing undefined SubRange " << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n"; } } while (false) | |||
1409 | << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Removing undefined SubRange " << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n"; } } while (false); | |||
1410 | // VNI is in ValNo - remove any segments in this SubRange that have this ValNo | |||
1411 | if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) { | |||
1412 | SR.removeValNo(RmValNo); | |||
1413 | UpdatedSubRanges = true; | |||
1414 | } | |||
1415 | } | |||
1416 | } | |||
1417 | if (UpdatedSubRanges) | |||
1418 | DstInt.removeEmptySubRanges(); | |||
1419 | } | |||
1420 | } else if (NewMI.getOperand(0).getReg() != CopyDstReg) { | |||
1421 | // The New instruction may be defining a sub-register of what's actually | |||
1422 | // been asked for. If so it must implicitly define the whole thing. | |||
1423 | assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&((TargetRegisterInfo::isPhysicalRegister(DstReg) && "Only expect virtual or physical registers in remat" ) ? static_cast<void> (0) : __assert_fail ("TargetRegisterInfo::isPhysicalRegister(DstReg) && \"Only expect virtual or physical registers in remat\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1424, __PRETTY_FUNCTION__)) | |||
1424 | "Only expect virtual or physical registers in remat")((TargetRegisterInfo::isPhysicalRegister(DstReg) && "Only expect virtual or physical registers in remat" ) ? static_cast<void> (0) : __assert_fail ("TargetRegisterInfo::isPhysicalRegister(DstReg) && \"Only expect virtual or physical registers in remat\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1424, __PRETTY_FUNCTION__)); | |||
1425 | NewMI.getOperand(0).setIsDead(true); | |||
1426 | NewMI.addOperand(MachineOperand::CreateReg( | |||
1427 | CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/)); | |||
1428 | // Record small dead def live-ranges for all the subregisters | |||
1429 | // of the destination register. | |||
1430 | // Otherwise, variables that live through may miss some | |||
1431 | // interferences, thus creating invalid allocation. | |||
1432 | // E.g., i386 code: | |||
1433 | // %1 = somedef ; %1 GR8 | |||
1434 | // %2 = remat ; %2 GR32 | |||
1435 | // CL = COPY %2.sub_8bit | |||
1436 | // = somedef %1 ; %1 GR8 | |||
1437 | // => | |||
1438 | // %1 = somedef ; %1 GR8 | |||
1439 | // dead ECX = remat ; implicit-def CL | |||
1440 | // = somedef %1 ; %1 GR8 | |||
1441 | // %1 will see the interferences with CL but not with CH since | |||
1442 | // no live-ranges would have been created for ECX. | |||
1443 | // Fix that! | |||
1444 | SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI); | |||
1445 | for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI); | |||
1446 | Units.isValid(); ++Units) | |||
1447 | if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) | |||
1448 | LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); | |||
1449 | } | |||
1450 | ||||
1451 | if (NewMI.getOperand(0).getSubReg()) | |||
1452 | NewMI.getOperand(0).setIsUndef(); | |||
1453 | ||||
1454 | // Transfer over implicit operands to the rematerialized instruction. | |||
1455 | for (MachineOperand &MO : ImplicitOps) | |||
1456 | NewMI.addOperand(MO); | |||
1457 | ||||
1458 | SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI); | |||
1459 | for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) { | |||
1460 | unsigned Reg = NewMIImplDefs[i]; | |||
1461 | for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) | |||
1462 | if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) | |||
1463 | LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); | |||
1464 | } | |||
1465 | ||||
1466 | LLVM_DEBUG(dbgs() << "Remat: " << NewMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Remat: " << NewMI; } } while (false); | |||
1467 | ++NumReMats; | |||
1468 | ||||
1469 | // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs | |||
1470 | // to describe DstReg instead. | |||
1471 | if (MRI->use_nodbg_empty(SrcReg)) { | |||
1472 | for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) { | |||
1473 | MachineInstr *UseMI = UseMO.getParent(); | |||
1474 | if (UseMI->isDebugValue()) { | |||
1475 | if (TargetRegisterInfo::isPhysicalRegister(DstReg)) | |||
1476 | UseMO.substPhysReg(DstReg, *TRI); | |||
1477 | else | |||
1478 | UseMO.setReg(DstReg); | |||
1479 | // Move the debug value directly after the def of the rematerialized | |||
1480 | // value in DstReg. | |||
1481 | MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI); | |||
1482 | LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tupdated: " << *UseMI ; } } while (false); | |||
1483 | } | |||
1484 | } | |||
1485 | } | |||
1486 | ||||
1487 | if (ToBeUpdated.count(SrcReg)) | |||
1488 | return true; | |||
1489 | ||||
1490 | unsigned NumCopyUses = 0; | |||
1491 | for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) { | |||
1492 | if (UseMO.getParent()->isCopyLike()) | |||
1493 | NumCopyUses++; | |||
1494 | } | |||
1495 | if (NumCopyUses < LateRematUpdateThreshold) { | |||
1496 | // The source interval can become smaller because we removed a use. | |||
1497 | shrinkToUses(&SrcInt, &DeadDefs); | |||
1498 | if (!DeadDefs.empty()) | |||
1499 | eliminateDeadDefs(); | |||
1500 | } else { | |||
1501 | ToBeUpdated.insert(SrcReg); | |||
1502 | } | |||
1503 | return true; | |||
1504 | } | |||
1505 | ||||
1506 | MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) { | |||
1507 | // ProcessImplicitDefs may leave some copies of <undef> values, it only | |||
1508 | // removes local variables. When we have a copy like: | |||
1509 | // | |||
1510 | // %1 = COPY undef %2 | |||
1511 | // | |||
1512 | // We delete the copy and remove the corresponding value number from %1. | |||
1513 | // Any uses of that value number are marked as <undef>. | |||
1514 | ||||
1515 | // Note that we do not query CoalescerPair here but redo isMoveInstr as the | |||
1516 | // CoalescerPair may have a new register class with adjusted subreg indices | |||
1517 | // at this point. | |||
1518 | unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; | |||
1519 | isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx); | |||
1520 | ||||
1521 | SlotIndex Idx = LIS->getInstructionIndex(*CopyMI); | |||
1522 | const LiveInterval &SrcLI = LIS->getInterval(SrcReg); | |||
1523 | // CopyMI is undef iff SrcReg is not live before the instruction. | |||
1524 | if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) { | |||
1525 | LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx); | |||
1526 | for (const LiveInterval::SubRange &SR : SrcLI.subranges()) { | |||
1527 | if ((SR.LaneMask & SrcMask).none()) | |||
1528 | continue; | |||
1529 | if (SR.liveAt(Idx)) | |||
1530 | return nullptr; | |||
1531 | } | |||
1532 | } else if (SrcLI.liveAt(Idx)) | |||
1533 | return nullptr; | |||
1534 | ||||
1535 | // If the undef copy defines a live-out value (i.e. an input to a PHI def), | |||
1536 | // then replace it with an IMPLICIT_DEF. | |||
1537 | LiveInterval &DstLI = LIS->getInterval(DstReg); | |||
1538 | SlotIndex RegIndex = Idx.getRegSlot(); | |||
1539 | LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex); | |||
1540 | assert(Seg != nullptr && "No segment for defining instruction")((Seg != nullptr && "No segment for defining instruction" ) ? static_cast<void> (0) : __assert_fail ("Seg != nullptr && \"No segment for defining instruction\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1540, __PRETTY_FUNCTION__)); | |||
1541 | if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) { | |||
1542 | if (V->isPHIDef()) { | |||
1543 | CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); | |||
1544 | for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) { | |||
1545 | MachineOperand &MO = CopyMI->getOperand(i-1); | |||
1546 | if (MO.isReg() && MO.isUse()) | |||
1547 | CopyMI->RemoveOperand(i-1); | |||
1548 | } | |||
1549 | LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tReplaced copy of <undef> value with an " "implicit def\n"; } } while (false) | |||
1550 | "implicit def\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tReplaced copy of <undef> value with an " "implicit def\n"; } } while (false); | |||
1551 | return CopyMI; | |||
1552 | } | |||
1553 | } | |||
1554 | ||||
1555 | // Remove any DstReg segments starting at the instruction. | |||
1556 | LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tEliminating copy of <undef> value\n" ; } } while (false); | |||
1557 | ||||
1558 | // Remove value or merge with previous one in case of a subregister def. | |||
1559 | if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) { | |||
1560 | VNInfo *VNI = DstLI.getVNInfoAt(RegIndex); | |||
1561 | DstLI.MergeValueNumberInto(VNI, PrevVNI); | |||
1562 | ||||
1563 | // The affected subregister segments can be removed. | |||
1564 | LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx); | |||
1565 | for (LiveInterval::SubRange &SR : DstLI.subranges()) { | |||
1566 | if ((SR.LaneMask & DstMask).none()) | |||
1567 | continue; | |||
1568 | ||||
1569 | VNInfo *SVNI = SR.getVNInfoAt(RegIndex); | |||
1570 | assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex))((SVNI != nullptr && SlotIndex::isSameInstr(SVNI-> def, RegIndex)) ? static_cast<void> (0) : __assert_fail ("SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex)" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1570, __PRETTY_FUNCTION__)); | |||
1571 | SR.removeValNo(SVNI); | |||
1572 | } | |||
1573 | DstLI.removeEmptySubRanges(); | |||
1574 | } else | |||
1575 | LIS->removeVRegDefAt(DstLI, RegIndex); | |||
1576 | ||||
1577 | // Mark uses as undef. | |||
1578 | for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) { | |||
1579 | if (MO.isDef() /*|| MO.isUndef()*/) | |||
1580 | continue; | |||
1581 | const MachineInstr &MI = *MO.getParent(); | |||
1582 | SlotIndex UseIdx = LIS->getInstructionIndex(MI); | |||
1583 | LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); | |||
1584 | bool isLive; | |||
1585 | if (!UseMask.all() && DstLI.hasSubRanges()) { | |||
1586 | isLive = false; | |||
1587 | for (const LiveInterval::SubRange &SR : DstLI.subranges()) { | |||
1588 | if ((SR.LaneMask & UseMask).none()) | |||
1589 | continue; | |||
1590 | if (SR.liveAt(UseIdx)) { | |||
1591 | isLive = true; | |||
1592 | break; | |||
1593 | } | |||
1594 | } | |||
1595 | } else | |||
1596 | isLive = DstLI.liveAt(UseIdx); | |||
1597 | if (isLive) | |||
1598 | continue; | |||
1599 | MO.setIsUndef(true); | |||
1600 | LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tnew undef: " << UseIdx << '\t' << MI; } } while (false); | |||
1601 | } | |||
1602 | ||||
1603 | // A def of a subregister may be a use of the other subregisters, so | |||
1604 | // deleting a def of a subregister may also remove uses. Since CopyMI | |||
1605 | // is still part of the function (but about to be erased), mark all | |||
1606 | // defs of DstReg in it as <undef>, so that shrinkToUses would | |||
1607 | // ignore them. | |||
1608 | for (MachineOperand &MO : CopyMI->operands()) | |||
1609 | if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg) | |||
1610 | MO.setIsUndef(true); | |||
1611 | LIS->shrinkToUses(&DstLI); | |||
1612 | ||||
1613 | return CopyMI; | |||
1614 | } | |||
1615 | ||||
1616 | void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, | |||
1617 | MachineOperand &MO, unsigned SubRegIdx) { | |||
1618 | LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx); | |||
1619 | if (MO.isDef()) | |||
1620 | Mask = ~Mask; | |||
1621 | bool IsUndef = true; | |||
1622 | for (const LiveInterval::SubRange &S : Int.subranges()) { | |||
1623 | if ((S.LaneMask & Mask).none()) | |||
1624 | continue; | |||
1625 | if (S.liveAt(UseIdx)) { | |||
1626 | IsUndef = false; | |||
1627 | break; | |||
1628 | } | |||
1629 | } | |||
1630 | if (IsUndef) { | |||
1631 | MO.setIsUndef(true); | |||
1632 | // We found out some subregister use is actually reading an undefined | |||
1633 | // value. In some cases the whole vreg has become undefined at this | |||
1634 | // point so we have to potentially shrink the main range if the | |||
1635 | // use was ending a live segment there. | |||
1636 | LiveQueryResult Q = Int.Query(UseIdx); | |||
1637 | if (Q.valueOut() == nullptr) | |||
1638 | ShrinkMainRange = true; | |||
1639 | } | |||
1640 | } | |||
1641 | ||||
1642 | void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg, | |||
1643 | unsigned DstReg, | |||
1644 | unsigned SubIdx) { | |||
1645 | bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); | |||
1646 | LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg); | |||
1647 | ||||
1648 | if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) { | |||
1649 | for (MachineOperand &MO : MRI->reg_operands(DstReg)) { | |||
1650 | unsigned SubReg = MO.getSubReg(); | |||
1651 | if (SubReg == 0 || MO.isUndef()) | |||
1652 | continue; | |||
1653 | MachineInstr &MI = *MO.getParent(); | |||
1654 | if (MI.isDebugValue()) | |||
1655 | continue; | |||
1656 | SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true); | |||
1657 | addUndefFlag(*DstInt, UseIdx, MO, SubReg); | |||
1658 | } | |||
1659 | } | |||
1660 | ||||
1661 | SmallPtrSet<MachineInstr*, 8> Visited; | |||
1662 | for (MachineRegisterInfo::reg_instr_iterator | |||
1663 | I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end(); | |||
1664 | I != E; ) { | |||
1665 | MachineInstr *UseMI = &*(I++); | |||
1666 | ||||
1667 | // Each instruction can only be rewritten once because sub-register | |||
1668 | // composition is not always idempotent. When SrcReg != DstReg, rewriting | |||
1669 | // the UseMI operands removes them from the SrcReg use-def chain, but when | |||
1670 | // SrcReg is DstReg we could encounter UseMI twice if it has multiple | |||
1671 | // operands mentioning the virtual register. | |||
1672 | if (SrcReg == DstReg && !Visited.insert(UseMI).second) | |||
1673 | continue; | |||
1674 | ||||
1675 | SmallVector<unsigned,8> Ops; | |||
1676 | bool Reads, Writes; | |||
1677 | std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops); | |||
1678 | ||||
1679 | // If SrcReg wasn't read, it may still be the case that DstReg is live-in | |||
1680 | // because SrcReg is a sub-register. | |||
1681 | if (DstInt && !Reads && SubIdx && !UseMI->isDebugValue()) | |||
1682 | Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI)); | |||
1683 | ||||
1684 | // Replace SrcReg with DstReg in all UseMI operands. | |||
1685 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { | |||
1686 | MachineOperand &MO = UseMI->getOperand(Ops[i]); | |||
1687 | ||||
1688 | // Adjust <undef> flags in case of sub-register joins. We don't want to | |||
1689 | // turn a full def into a read-modify-write sub-register def and vice | |||
1690 | // versa. | |||
1691 | if (SubIdx && MO.isDef()) | |||
1692 | MO.setIsUndef(!Reads); | |||
1693 | ||||
1694 | // A subreg use of a partially undef (super) register may be a complete | |||
1695 | // undef use now and then has to be marked that way. | |||
1696 | if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) { | |||
1697 | if (!DstInt->hasSubRanges()) { | |||
1698 | BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); | |||
1699 | LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg); | |||
1700 | DstInt->createSubRangeFrom(Allocator, Mask, *DstInt); | |||
1701 | } | |||
1702 | SlotIndex MIIdx = UseMI->isDebugValue() | |||
1703 | ? LIS->getSlotIndexes()->getIndexBefore(*UseMI) | |||
1704 | : LIS->getInstructionIndex(*UseMI); | |||
1705 | SlotIndex UseIdx = MIIdx.getRegSlot(true); | |||
1706 | addUndefFlag(*DstInt, UseIdx, MO, SubIdx); | |||
1707 | } | |||
1708 | ||||
1709 | if (DstIsPhys) | |||
1710 | MO.substPhysReg(DstReg, *TRI); | |||
1711 | else | |||
1712 | MO.substVirtReg(DstReg, SubIdx, *TRI); | |||
1713 | } | |||
1714 | ||||
1715 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false) | |||
1716 | dbgs() << "\t\tupdated: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false) | |||
1717 | if (!UseMI->isDebugValue())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false) | |||
1718 | dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false) | |||
1719 | dbgs() << *UseMI;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false) | |||
1720 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI ->isDebugValue()) dbgs() << LIS->getInstructionIndex (*UseMI) << "\t"; dbgs() << *UseMI; }; } } while ( false); | |||
1721 | } | |||
1722 | } | |||
1723 | ||||
1724 | bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) { | |||
1725 | // Always join simple intervals that are defined by a single copy from a | |||
1726 | // reserved register. This doesn't increase register pressure, so it is | |||
1727 | // always beneficial. | |||
1728 | if (!MRI->isReserved(CP.getDstReg())) { | |||
1729 | LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tCan only merge into reserved registers.\n" ; } } while (false); | |||
1730 | return false; | |||
1731 | } | |||
1732 | ||||
1733 | LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg()); | |||
1734 | if (JoinVInt.containsOneValue()) | |||
1735 | return true; | |||
1736 | ||||
1737 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tCannot join complex intervals into reserved register.\n" ; } } while (false) | |||
1738 | dbgs() << "\tCannot join complex intervals into reserved register.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tCannot join complex intervals into reserved register.\n" ; } } while (false); | |||
1739 | return false; | |||
1740 | } | |||
1741 | ||||
1742 | bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) { | |||
1743 | Again = false; | |||
1744 | LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << LIS->getInstructionIndex(* CopyMI) << '\t' << *CopyMI; } } while (false); | |||
1745 | ||||
1746 | CoalescerPair CP(*TRI); | |||
1747 | if (!CP.setRegisters(CopyMI)) { | |||
1748 | LLVM_DEBUG(dbgs() << "\tNot coalescable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tNot coalescable.\n"; } } while (false); | |||
1749 | return false; | |||
1750 | } | |||
1751 | ||||
1752 | if (CP.getNewRC()) { | |||
1753 | auto SrcRC = MRI->getRegClass(CP.getSrcReg()); | |||
1754 | auto DstRC = MRI->getRegClass(CP.getDstReg()); | |||
1755 | unsigned SrcIdx = CP.getSrcIdx(); | |||
1756 | unsigned DstIdx = CP.getDstIdx(); | |||
1757 | if (CP.isFlipped()) { | |||
1758 | std::swap(SrcIdx, DstIdx); | |||
1759 | std::swap(SrcRC, DstRC); | |||
1760 | } | |||
1761 | if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx, | |||
1762 | CP.getNewRC(), *LIS)) { | |||
1763 | LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tSubtarget bailed on coalescing.\n" ; } } while (false); | |||
1764 | return false; | |||
1765 | } | |||
1766 | } | |||
1767 | ||||
1768 | // Dead code elimination. This really should be handled by MachineDCE, but | |||
1769 | // sometimes dead copies slip through, and we can't generate invalid live | |||
1770 | // ranges. | |||
1771 | if (!CP.isPhys() && CopyMI->allDefsAreDead()) { | |||
1772 | LLVM_DEBUG(dbgs() << "\tCopy is dead.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tCopy is dead.\n"; } } while (false); | |||
1773 | DeadDefs.push_back(CopyMI); | |||
1774 | eliminateDeadDefs(); | |||
1775 | return true; | |||
1776 | } | |||
1777 | ||||
1778 | // Eliminate undefs. | |||
1779 | if (!CP.isPhys()) { | |||
1780 | // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce. | |||
1781 | if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) { | |||
1782 | if (UndefMI->isImplicitDef()) | |||
1783 | return false; | |||
1784 | deleteInstr(CopyMI); | |||
1785 | return false; // Not coalescable. | |||
1786 | } | |||
1787 | } | |||
1788 | ||||
1789 | // Coalesced copies are normally removed immediately, but transformations | |||
1790 | // like removeCopyByCommutingDef() can inadvertently create identity copies. | |||
1791 | // When that happens, just join the values and remove the copy. | |||
1792 | if (CP.getSrcReg() == CP.getDstReg()) { | |||
1793 | LiveInterval &LI = LIS->getInterval(CP.getSrcReg()); | |||
1794 | LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tCopy already coalesced: " << LI << '\n'; } } while (false); | |||
1795 | const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); | |||
1796 | LiveQueryResult LRQ = LI.Query(CopyIdx); | |||
1797 | if (VNInfo *DefVNI = LRQ.valueDefined()) { | |||
1798 | VNInfo *ReadVNI = LRQ.valueIn(); | |||
1799 | assert(ReadVNI && "No value before copy and no <undef> flag.")((ReadVNI && "No value before copy and no <undef> flag." ) ? static_cast<void> (0) : __assert_fail ("ReadVNI && \"No value before copy and no <undef> flag.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1799, __PRETTY_FUNCTION__)); | |||
1800 | assert(ReadVNI != DefVNI && "Cannot read and define the same value.")((ReadVNI != DefVNI && "Cannot read and define the same value." ) ? static_cast<void> (0) : __assert_fail ("ReadVNI != DefVNI && \"Cannot read and define the same value.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1800, __PRETTY_FUNCTION__)); | |||
1801 | LI.MergeValueNumberInto(DefVNI, ReadVNI); | |||
1802 | ||||
1803 | // Process subregister liveranges. | |||
1804 | for (LiveInterval::SubRange &S : LI.subranges()) { | |||
1805 | LiveQueryResult SLRQ = S.Query(CopyIdx); | |||
1806 | if (VNInfo *SDefVNI = SLRQ.valueDefined()) { | |||
1807 | VNInfo *SReadVNI = SLRQ.valueIn(); | |||
1808 | S.MergeValueNumberInto(SDefVNI, SReadVNI); | |||
1809 | } | |||
1810 | } | |||
1811 | LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tMerged values: " << LI << '\n'; } } while (false); | |||
1812 | } | |||
1813 | deleteInstr(CopyMI); | |||
1814 | return true; | |||
1815 | } | |||
1816 | ||||
1817 | // Enforce policies. | |||
1818 | if (CP.isPhys()) { | |||
1819 | LLVM_DEBUG(dbgs() << "\tConsidering merging "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tConsidering merging " << printReg(CP.getSrcReg(), TRI) << " with " << printReg (CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while (false) | |||
1820 | << printReg(CP.getSrcReg(), TRI) << " with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tConsidering merging " << printReg(CP.getSrcReg(), TRI) << " with " << printReg (CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while (false) | |||
1821 | << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tConsidering merging " << printReg(CP.getSrcReg(), TRI) << " with " << printReg (CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while (false); | |||
1822 | if (!canJoinPhys(CP)) { | |||
1823 | // Before giving up coalescing, if definition of source is defined by | |||
1824 | // trivial computation, try rematerializing it. | |||
1825 | bool IsDefCopy; | |||
1826 | if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) | |||
1827 | return true; | |||
1828 | if (IsDefCopy) | |||
1829 | Again = true; // May be possible to coalesce later. | |||
1830 | return false; | |||
1831 | } | |||
1832 | } else { | |||
1833 | // When possible, let DstReg be the larger interval. | |||
1834 | if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() > | |||
1835 | LIS->getInterval(CP.getDstReg()).size()) | |||
1836 | CP.flip(); | |||
1837 | ||||
1838 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1839 | dbgs() << "\tConsidering merging to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1840 | << TRI->getRegClassName(CP.getNewRC()) << " with ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1841 | if (CP.getDstIdx() && CP.getSrcIdx())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1842 | dbgs() << printReg(CP.getDstReg()) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1843 | << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1844 | << printReg(CP.getSrcReg()) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1845 | << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1846 | elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1847 | dbgs() << printReg(CP.getSrcReg(), TRI) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1848 | << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false) | |||
1849 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tConsidering merging to " << TRI->getRegClassName(CP.getNewRC()) << " with " ; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() << printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName (CP.getDstIdx()) << " and " << printReg(CP.getSrcReg ()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx ()) << '\n'; else dbgs() << printReg(CP.getSrcReg (), TRI) << " in " << printReg(CP.getDstReg(), TRI , CP.getSrcIdx()) << '\n'; }; } } while (false); | |||
1850 | } | |||
1851 | ||||
1852 | ShrinkMask = LaneBitmask::getNone(); | |||
1853 | ShrinkMainRange = false; | |||
1854 | ||||
1855 | // Okay, attempt to join these two intervals. On failure, this returns false. | |||
1856 | // Otherwise, if one of the intervals being joined is a physreg, this method | |||
1857 | // always canonicalizes DstInt to be it. The output "SrcInt" will not have | |||
1858 | // been modified, so we can use this information below to update aliases. | |||
1859 | if (!joinIntervals(CP)) { | |||
1860 | // Coalescing failed. | |||
1861 | ||||
1862 | // If definition of source is defined by trivial computation, try | |||
1863 | // rematerializing it. | |||
1864 | bool IsDefCopy; | |||
1865 | if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) | |||
1866 | return true; | |||
1867 | ||||
1868 | // If we can eliminate the copy without merging the live segments, do so | |||
1869 | // now. | |||
1870 | if (!CP.isPartial() && !CP.isPhys()) { | |||
1871 | bool Changed = adjustCopiesBackFrom(CP, CopyMI); | |||
1872 | bool Shrink = false; | |||
1873 | if (!Changed) | |||
1874 | std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI); | |||
1875 | if (Changed) { | |||
1876 | deleteInstr(CopyMI); | |||
1877 | if (Shrink) { | |||
1878 | unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); | |||
1879 | LiveInterval &DstLI = LIS->getInterval(DstReg); | |||
1880 | shrinkToUses(&DstLI); | |||
1881 | LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tshrunk: " << DstLI << '\n'; } } while (false); | |||
1882 | } | |||
1883 | LLVM_DEBUG(dbgs() << "\tTrivial!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tTrivial!\n"; } } while (false ); | |||
1884 | return true; | |||
1885 | } | |||
1886 | } | |||
1887 | ||||
1888 | // Try and see if we can partially eliminate the copy by moving the copy to | |||
1889 | // its predecessor. | |||
1890 | if (!CP.isPartial() && !CP.isPhys()) | |||
1891 | if (removePartialRedundancy(CP, *CopyMI)) | |||
1892 | return true; | |||
1893 | ||||
1894 | // Otherwise, we are unable to join the intervals. | |||
1895 | LLVM_DEBUG(dbgs() << "\tInterference!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tInterference!\n"; } } while (false); | |||
1896 | Again = true; // May be possible to coalesce later. | |||
1897 | return false; | |||
1898 | } | |||
1899 | ||||
1900 | // Coalescing to a virtual register that is of a sub-register class of the | |||
1901 | // other. Make sure the resulting register is set to the right register class. | |||
1902 | if (CP.isCrossClass()) { | |||
1903 | ++numCrossRCs; | |||
1904 | MRI->setRegClass(CP.getDstReg(), CP.getNewRC()); | |||
1905 | } | |||
1906 | ||||
1907 | // Removing sub-register copies can ease the register class constraints. | |||
1908 | // Make sure we attempt to inflate the register class of DstReg. | |||
1909 | if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC())) | |||
1910 | InflateRegs.push_back(CP.getDstReg()); | |||
1911 | ||||
1912 | // CopyMI has been erased by joinIntervals at this point. Remove it from | |||
1913 | // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back | |||
1914 | // to the work list. This keeps ErasedInstrs from growing needlessly. | |||
1915 | ErasedInstrs.erase(CopyMI); | |||
1916 | ||||
1917 | // Rewrite all SrcReg operands to DstReg. | |||
1918 | // Also update DstReg operands to include DstIdx if it is set. | |||
1919 | if (CP.getDstIdx()) | |||
1920 | updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx()); | |||
1921 | updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx()); | |||
1922 | ||||
1923 | // Shrink subregister ranges if necessary. | |||
1924 | if (ShrinkMask.any()) { | |||
1925 | LiveInterval &LI = LIS->getInterval(CP.getDstReg()); | |||
1926 | for (LiveInterval::SubRange &S : LI.subranges()) { | |||
1927 | if ((S.LaneMask & ShrinkMask).none()) | |||
1928 | continue; | |||
1929 | LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask) << ")\n"; } } while (false) | |||
1930 | << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask) << ")\n"; } } while (false); | |||
1931 | LIS->shrinkToUses(S, LI.reg); | |||
1932 | } | |||
1933 | LI.removeEmptySubRanges(); | |||
1934 | } | |||
1935 | ||||
1936 | // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live | |||
1937 | // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval | |||
1938 | // is not up-to-date, need to update the merged live interval here. | |||
1939 | if (ToBeUpdated.count(CP.getSrcReg())) | |||
1940 | ShrinkMainRange = true; | |||
1941 | ||||
1942 | if (ShrinkMainRange) { | |||
1943 | LiveInterval &LI = LIS->getInterval(CP.getDstReg()); | |||
1944 | shrinkToUses(&LI); | |||
1945 | } | |||
1946 | ||||
1947 | // SrcReg is guaranteed to be the register whose live interval that is | |||
1948 | // being merged. | |||
1949 | LIS->removeInterval(CP.getSrcReg()); | |||
1950 | ||||
1951 | // Update regalloc hint. | |||
1952 | TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF); | |||
1953 | ||||
1954 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1955 | dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1956 | << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1957 | dbgs() << "\tResult = ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1958 | if (CP.isPhys())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1959 | dbgs() << printReg(CP.getDstReg(), TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1960 | elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1961 | dbgs() << LIS->getInterval(CP.getDstReg());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1962 | dbgs() << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false) | |||
1963 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\tSuccess: " << printReg (CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() << printReg(CP.getDstReg(), TRI); else dbgs() << LIS-> getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while (false); | |||
1964 | ||||
1965 | ++numJoins; | |||
1966 | return true; | |||
1967 | } | |||
1968 | ||||
1969 | bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) { | |||
1970 | unsigned DstReg = CP.getDstReg(); | |||
1971 | unsigned SrcReg = CP.getSrcReg(); | |||
1972 | assert(CP.isPhys() && "Must be a physreg copy")((CP.isPhys() && "Must be a physreg copy") ? static_cast <void> (0) : __assert_fail ("CP.isPhys() && \"Must be a physreg copy\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1972, __PRETTY_FUNCTION__)); | |||
1973 | assert(MRI->isReserved(DstReg) && "Not a reserved register")((MRI->isReserved(DstReg) && "Not a reserved register" ) ? static_cast<void> (0) : __assert_fail ("MRI->isReserved(DstReg) && \"Not a reserved register\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1973, __PRETTY_FUNCTION__)); | |||
1974 | LiveInterval &RHS = LIS->getInterval(SrcReg); | |||
1975 | LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tRHS = " << RHS << '\n'; } } while (false); | |||
1976 | ||||
1977 | assert(RHS.containsOneValue() && "Invalid join with reserved register")((RHS.containsOneValue() && "Invalid join with reserved register" ) ? static_cast<void> (0) : __assert_fail ("RHS.containsOneValue() && \"Invalid join with reserved register\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 1977, __PRETTY_FUNCTION__)); | |||
1978 | ||||
1979 | // Optimization for reserved registers like ESP. We can only merge with a | |||
1980 | // reserved physreg if RHS has a single value that is a copy of DstReg. | |||
1981 | // The live range of the reserved register will look like a set of dead defs | |||
1982 | // - we don't properly track the live range of reserved registers. | |||
1983 | ||||
1984 | // Deny any overlapping intervals. This depends on all the reserved | |||
1985 | // register live ranges to look like dead defs. | |||
1986 | if (!MRI->isConstantPhysReg(DstReg)) { | |||
1987 | for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) { | |||
1988 | // Abort if not all the regunits are reserved. | |||
1989 | for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) { | |||
1990 | if (!MRI->isReserved(*RI)) | |||
1991 | return false; | |||
1992 | } | |||
1993 | if (RHS.overlaps(LIS->getRegUnit(*UI))) { | |||
1994 | LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI) << '\n'; } } while (false) | |||
1995 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI) << '\n'; } } while (false); | |||
1996 | return false; | |||
1997 | } | |||
1998 | } | |||
1999 | ||||
2000 | // We must also check for overlaps with regmask clobbers. | |||
2001 | BitVector RegMaskUsable; | |||
2002 | if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) && | |||
2003 | !RegMaskUsable.test(DstReg)) { | |||
2004 | LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tRegMask interference\n"; } } while (false); | |||
2005 | return false; | |||
2006 | } | |||
2007 | } | |||
2008 | ||||
2009 | // Skip any value computations, we are not adding new values to the | |||
2010 | // reserved register. Also skip merging the live ranges, the reserved | |||
2011 | // register live range doesn't need to be accurate as long as all the | |||
2012 | // defs are there. | |||
2013 | ||||
2014 | // Delete the identity copy. | |||
2015 | MachineInstr *CopyMI; | |||
2016 | if (CP.isFlipped()) { | |||
2017 | // Physreg is copied into vreg | |||
2018 | // %y = COPY %physreg_x | |||
2019 | // ... //< no other def of %x here | |||
2020 | // use %y | |||
2021 | // => | |||
2022 | // ... | |||
2023 | // use %x | |||
2024 | CopyMI = MRI->getVRegDef(SrcReg); | |||
2025 | } else { | |||
2026 | // VReg is copied into physreg: | |||
2027 | // %y = def | |||
2028 | // ... //< no other def or use of %y here | |||
2029 | // %y = COPY %physreg_x | |||
2030 | // => | |||
2031 | // %y = def | |||
2032 | // ... | |||
2033 | if (!MRI->hasOneNonDBGUse(SrcReg)) { | |||
2034 | LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tMultiple vreg uses!\n"; } } while (false); | |||
2035 | return false; | |||
2036 | } | |||
2037 | ||||
2038 | if (!LIS->intervalIsInOneMBB(RHS)) { | |||
2039 | LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tComplex control flow!\n" ; } } while (false); | |||
2040 | return false; | |||
2041 | } | |||
2042 | ||||
2043 | MachineInstr &DestMI = *MRI->getVRegDef(SrcReg); | |||
2044 | CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg); | |||
2045 | SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); | |||
2046 | SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot(); | |||
2047 | ||||
2048 | if (!MRI->isConstantPhysReg(DstReg)) { | |||
2049 | // We checked above that there are no interfering defs of the physical | |||
2050 | // register. However, for this case, where we intend to move up the def of | |||
2051 | // the physical register, we also need to check for interfering uses. | |||
2052 | SlotIndexes *Indexes = LIS->getSlotIndexes(); | |||
2053 | for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx); | |||
2054 | SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) { | |||
2055 | MachineInstr *MI = LIS->getInstructionFromIndex(SI); | |||
2056 | if (MI->readsRegister(DstReg, TRI)) { | |||
2057 | LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tInterference (read): " << *MI; } } while (false); | |||
2058 | return false; | |||
2059 | } | |||
2060 | } | |||
2061 | } | |||
2062 | ||||
2063 | // We're going to remove the copy which defines a physical reserved | |||
2064 | // register, so remove its valno, etc. | |||
2065 | LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tRemoving phys reg def of " << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n"; } } while (false) | |||
2066 | << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tRemoving phys reg def of " << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n"; } } while (false); | |||
2067 | ||||
2068 | LIS->removePhysRegDefAt(DstReg, CopyRegIdx); | |||
2069 | // Create a new dead def at the new def location. | |||
2070 | for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) { | |||
2071 | LiveRange &LR = LIS->getRegUnit(*UI); | |||
2072 | LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator()); | |||
2073 | } | |||
2074 | } | |||
2075 | ||||
2076 | deleteInstr(CopyMI); | |||
2077 | ||||
2078 | // We don't track kills for reserved registers. | |||
2079 | MRI->clearKillFlags(CP.getSrcReg()); | |||
2080 | ||||
2081 | return true; | |||
2082 | } | |||
2083 | ||||
2084 | //===----------------------------------------------------------------------===// | |||
2085 | // Interference checking and interval joining | |||
2086 | //===----------------------------------------------------------------------===// | |||
2087 | // | |||
2088 | // In the easiest case, the two live ranges being joined are disjoint, and | |||
2089 | // there is no interference to consider. It is quite common, though, to have | |||
2090 | // overlapping live ranges, and we need to check if the interference can be | |||
2091 | // resolved. | |||
2092 | // | |||
2093 | // The live range of a single SSA value forms a sub-tree of the dominator tree. | |||
2094 | // This means that two SSA values overlap if and only if the def of one value | |||
2095 | // is contained in the live range of the other value. As a special case, the | |||
2096 | // overlapping values can be defined at the same index. | |||
2097 | // | |||
2098 | // The interference from an overlapping def can be resolved in these cases: | |||
2099 | // | |||
2100 | // 1. Coalescable copies. The value is defined by a copy that would become an | |||
2101 | // identity copy after joining SrcReg and DstReg. The copy instruction will | |||
2102 | // be removed, and the value will be merged with the source value. | |||
2103 | // | |||
2104 | // There can be several copies back and forth, causing many values to be | |||
2105 | // merged into one. We compute a list of ultimate values in the joined live | |||
2106 | // range as well as a mappings from the old value numbers. | |||
2107 | // | |||
2108 | // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI | |||
2109 | // predecessors have a live out value. It doesn't cause real interference, | |||
2110 | // and can be merged into the value it overlaps. Like a coalescable copy, it | |||
2111 | // can be erased after joining. | |||
2112 | // | |||
2113 | // 3. Copy of external value. The overlapping def may be a copy of a value that | |||
2114 | // is already in the other register. This is like a coalescable copy, but | |||
2115 | // the live range of the source register must be trimmed after erasing the | |||
2116 | // copy instruction: | |||
2117 | // | |||
2118 | // %src = COPY %ext | |||
2119 | // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext. | |||
2120 | // | |||
2121 | // 4. Clobbering undefined lanes. Vector registers are sometimes built by | |||
2122 | // defining one lane at a time: | |||
2123 | // | |||
2124 | // %dst:ssub0<def,read-undef> = FOO | |||
2125 | // %src = BAR | |||
2126 | // %dst:ssub1 = COPY %src | |||
2127 | // | |||
2128 | // The live range of %src overlaps the %dst value defined by FOO, but | |||
2129 | // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane | |||
2130 | // which was undef anyway. | |||
2131 | // | |||
2132 | // The value mapping is more complicated in this case. The final live range | |||
2133 | // will have different value numbers for both FOO and BAR, but there is no | |||
2134 | // simple mapping from old to new values. It may even be necessary to add | |||
2135 | // new PHI values. | |||
2136 | // | |||
2137 | // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that | |||
2138 | // is live, but never read. This can happen because we don't compute | |||
2139 | // individual live ranges per lane. | |||
2140 | // | |||
2141 | // %dst = FOO | |||
2142 | // %src = BAR | |||
2143 | // %dst:ssub1 = COPY %src | |||
2144 | // | |||
2145 | // This kind of interference is only resolved locally. If the clobbered | |||
2146 | // lane value escapes the block, the join is aborted. | |||
2147 | ||||
2148 | namespace { | |||
2149 | ||||
2150 | /// Track information about values in a single virtual register about to be | |||
2151 | /// joined. Objects of this class are always created in pairs - one for each | |||
2152 | /// side of the CoalescerPair (or one for each lane of a side of the coalescer | |||
2153 | /// pair) | |||
2154 | class JoinVals { | |||
2155 | /// Live range we work on. | |||
2156 | LiveRange &LR; | |||
2157 | ||||
2158 | /// (Main) register we work on. | |||
2159 | const unsigned Reg; | |||
2160 | ||||
2161 | /// Reg (and therefore the values in this liverange) will end up as | |||
2162 | /// subregister SubIdx in the coalesced register. Either CP.DstIdx or | |||
2163 | /// CP.SrcIdx. | |||
2164 | const unsigned SubIdx; | |||
2165 | ||||
2166 | /// The LaneMask that this liverange will occupy the coalesced register. May | |||
2167 | /// be smaller than the lanemask produced by SubIdx when merging subranges. | |||
2168 | const LaneBitmask LaneMask; | |||
2169 | ||||
2170 | /// This is true when joining sub register ranges, false when joining main | |||
2171 | /// ranges. | |||
2172 | const bool SubRangeJoin; | |||
2173 | ||||
2174 | /// Whether the current LiveInterval tracks subregister liveness. | |||
2175 | const bool TrackSubRegLiveness; | |||
2176 | ||||
2177 | /// Values that will be present in the final live range. | |||
2178 | SmallVectorImpl<VNInfo*> &NewVNInfo; | |||
2179 | ||||
2180 | const CoalescerPair &CP; | |||
2181 | LiveIntervals *LIS; | |||
2182 | SlotIndexes *Indexes; | |||
2183 | const TargetRegisterInfo *TRI; | |||
2184 | ||||
2185 | /// Value number assignments. Maps value numbers in LI to entries in | |||
2186 | /// NewVNInfo. This is suitable for passing to LiveInterval::join(). | |||
2187 | SmallVector<int, 8> Assignments; | |||
2188 | ||||
2189 | /// Conflict resolution for overlapping values. | |||
2190 | enum ConflictResolution { | |||
2191 | /// No overlap, simply keep this value. | |||
2192 | CR_Keep, | |||
2193 | ||||
2194 | /// Merge this value into OtherVNI and erase the defining instruction. | |||
2195 | /// Used for IMPLICIT_DEF, coalescable copies, and copies from external | |||
2196 | /// values. | |||
2197 | CR_Erase, | |||
2198 | ||||
2199 | /// Merge this value into OtherVNI but keep the defining instruction. | |||
2200 | /// This is for the special case where OtherVNI is defined by the same | |||
2201 | /// instruction. | |||
2202 | CR_Merge, | |||
2203 | ||||
2204 | /// Keep this value, and have it replace OtherVNI where possible. This | |||
2205 | /// complicates value mapping since OtherVNI maps to two different values | |||
2206 | /// before and after this def. | |||
2207 | /// Used when clobbering undefined or dead lanes. | |||
2208 | CR_Replace, | |||
2209 | ||||
2210 | /// Unresolved conflict. Visit later when all values have been mapped. | |||
2211 | CR_Unresolved, | |||
2212 | ||||
2213 | /// Unresolvable conflict. Abort the join. | |||
2214 | CR_Impossible | |||
2215 | }; | |||
2216 | ||||
2217 | /// Per-value info for LI. The lane bit masks are all relative to the final | |||
2218 | /// joined register, so they can be compared directly between SrcReg and | |||
2219 | /// DstReg. | |||
2220 | struct Val { | |||
2221 | ConflictResolution Resolution = CR_Keep; | |||
2222 | ||||
2223 | /// Lanes written by this def, 0 for unanalyzed values. | |||
2224 | LaneBitmask WriteLanes; | |||
2225 | ||||
2226 | /// Lanes with defined values in this register. Other lanes are undef and | |||
2227 | /// safe to clobber. | |||
2228 | LaneBitmask ValidLanes; | |||
2229 | ||||
2230 | /// Value in LI being redefined by this def. | |||
2231 | VNInfo *RedefVNI = nullptr; | |||
2232 | ||||
2233 | /// Value in the other live range that overlaps this def, if any. | |||
2234 | VNInfo *OtherVNI = nullptr; | |||
2235 | ||||
2236 | /// Is this value an IMPLICIT_DEF that can be erased? | |||
2237 | /// | |||
2238 | /// IMPLICIT_DEF values should only exist at the end of a basic block that | |||
2239 | /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be | |||
2240 | /// safely erased if they are overlapping a live value in the other live | |||
2241 | /// interval. | |||
2242 | /// | |||
2243 | /// Weird control flow graphs and incomplete PHI handling in | |||
2244 | /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with | |||
2245 | /// longer live ranges. Such IMPLICIT_DEF values should be treated like | |||
2246 | /// normal values. | |||
2247 | bool ErasableImplicitDef = false; | |||
2248 | ||||
2249 | /// True when the live range of this value will be pruned because of an | |||
2250 | /// overlapping CR_Replace value in the other live range. | |||
2251 | bool Pruned = false; | |||
2252 | ||||
2253 | /// True once Pruned above has been computed. | |||
2254 | bool PrunedComputed = false; | |||
2255 | ||||
2256 | /// True if this value is determined to be identical to OtherVNI | |||
2257 | /// (in valuesIdentical). This is used with CR_Erase where the erased | |||
2258 | /// copy is redundant, i.e. the source value is already the same as | |||
2259 | /// the destination. In such cases the subranges need to be updated | |||
2260 | /// properly. See comment at pruneSubRegValues for more info. | |||
2261 | bool Identical = false; | |||
2262 | ||||
2263 | Val() = default; | |||
2264 | ||||
2265 | bool isAnalyzed() const { return WriteLanes.any(); } | |||
2266 | }; | |||
2267 | ||||
2268 | /// One entry per value number in LI. | |||
2269 | SmallVector<Val, 8> Vals; | |||
2270 | ||||
2271 | /// Compute the bitmask of lanes actually written by DefMI. | |||
2272 | /// Set Redef if there are any partial register definitions that depend on the | |||
2273 | /// previous value of the register. | |||
2274 | LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const; | |||
2275 | ||||
2276 | /// Find the ultimate value that VNI was copied from. | |||
2277 | std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const; | |||
2278 | ||||
2279 | bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const; | |||
2280 | ||||
2281 | /// Analyze ValNo in this live range, and set all fields of Vals[ValNo]. | |||
2282 | /// Return a conflict resolution when possible, but leave the hard cases as | |||
2283 | /// CR_Unresolved. | |||
2284 | /// Recursively calls computeAssignment() on this and Other, guaranteeing that | |||
2285 | /// both OtherVNI and RedefVNI have been analyzed and mapped before returning. | |||
2286 | /// The recursion always goes upwards in the dominator tree, making loops | |||
2287 | /// impossible. | |||
2288 | ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other); | |||
2289 | ||||
2290 | /// Compute the value assignment for ValNo in RI. | |||
2291 | /// This may be called recursively by analyzeValue(), but never for a ValNo on | |||
2292 | /// the stack. | |||
2293 | void computeAssignment(unsigned ValNo, JoinVals &Other); | |||
2294 | ||||
2295 | /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute | |||
2296 | /// the extent of the tainted lanes in the block. | |||
2297 | /// | |||
2298 | /// Multiple values in Other.LR can be affected since partial redefinitions | |||
2299 | /// can preserve previously tainted lanes. | |||
2300 | /// | |||
2301 | /// 1 %dst = VLOAD <-- Define all lanes in %dst | |||
2302 | /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0 | |||
2303 | /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0 | |||
2304 | /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read | |||
2305 | /// | |||
2306 | /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes) | |||
2307 | /// entry to TaintedVals. | |||
2308 | /// | |||
2309 | /// Returns false if the tainted lanes extend beyond the basic block. | |||
2310 | bool | |||
2311 | taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other, | |||
2312 | SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent); | |||
2313 | ||||
2314 | /// Return true if MI uses any of the given Lanes from Reg. | |||
2315 | /// This does not include partial redefinitions of Reg. | |||
2316 | bool usesLanes(const MachineInstr &MI, unsigned, unsigned, LaneBitmask) const; | |||
2317 | ||||
2318 | /// Determine if ValNo is a copy of a value number in LR or Other.LR that will | |||
2319 | /// be pruned: | |||
2320 | /// | |||
2321 | /// %dst = COPY %src | |||
2322 | /// %src = COPY %dst <-- This value to be pruned. | |||
2323 | /// %dst = COPY %src <-- This value is a copy of a pruned value. | |||
2324 | bool isPrunedValue(unsigned ValNo, JoinVals &Other); | |||
2325 | ||||
2326 | public: | |||
2327 | JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask, | |||
2328 | SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp, | |||
2329 | LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin, | |||
2330 | bool TrackSubRegLiveness) | |||
2331 | : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask), | |||
2332 | SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness), | |||
2333 | NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()), | |||
2334 | TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums()) {} | |||
2335 | ||||
2336 | /// Analyze defs in LR and compute a value mapping in NewVNInfo. | |||
2337 | /// Returns false if any conflicts were impossible to resolve. | |||
2338 | bool mapValues(JoinVals &Other); | |||
2339 | ||||
2340 | /// Try to resolve conflicts that require all values to be mapped. | |||
2341 | /// Returns false if any conflicts were impossible to resolve. | |||
2342 | bool resolveConflicts(JoinVals &Other); | |||
2343 | ||||
2344 | /// Prune the live range of values in Other.LR where they would conflict with | |||
2345 | /// CR_Replace values in LR. Collect end points for restoring the live range | |||
2346 | /// after joining. | |||
2347 | void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints, | |||
2348 | bool changeInstrs); | |||
2349 | ||||
2350 | /// Removes subranges starting at copies that get removed. This sometimes | |||
2351 | /// happens when undefined subranges are copied around. These ranges contain | |||
2352 | /// no useful information and can be removed. | |||
2353 | void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask); | |||
2354 | ||||
2355 | /// Pruning values in subranges can lead to removing segments in these | |||
2356 | /// subranges started by IMPLICIT_DEFs. The corresponding segments in | |||
2357 | /// the main range also need to be removed. This function will mark | |||
2358 | /// the corresponding values in the main range as pruned, so that | |||
2359 | /// eraseInstrs can do the final cleanup. | |||
2360 | /// The parameter @p LI must be the interval whose main range is the | |||
2361 | /// live range LR. | |||
2362 | void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange); | |||
2363 | ||||
2364 | /// Erase any machine instructions that have been coalesced away. | |||
2365 | /// Add erased instructions to ErasedInstrs. | |||
2366 | /// Add foreign virtual registers to ShrinkRegs if their live range ended at | |||
2367 | /// the erased instrs. | |||
2368 | void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, | |||
2369 | SmallVectorImpl<unsigned> &ShrinkRegs, | |||
2370 | LiveInterval *LI = nullptr); | |||
2371 | ||||
2372 | /// Remove liverange defs at places where implicit defs will be removed. | |||
2373 | void removeImplicitDefs(); | |||
2374 | ||||
2375 | /// Get the value assignments suitable for passing to LiveInterval::join. | |||
2376 | const int *getAssignments() const { return Assignments.data(); } | |||
2377 | }; | |||
2378 | ||||
2379 | } // end anonymous namespace | |||
2380 | ||||
2381 | LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) | |||
2382 | const { | |||
2383 | LaneBitmask L; | |||
2384 | for (const MachineOperand &MO : DefMI->operands()) { | |||
2385 | if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef()) | |||
2386 | continue; | |||
2387 | L |= TRI->getSubRegIndexLaneMask( | |||
2388 | TRI->composeSubRegIndices(SubIdx, MO.getSubReg())); | |||
2389 | if (MO.readsReg()) | |||
2390 | Redef = true; | |||
2391 | } | |||
2392 | return L; | |||
2393 | } | |||
2394 | ||||
2395 | std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain( | |||
2396 | const VNInfo *VNI) const { | |||
2397 | unsigned TrackReg = Reg; | |||
2398 | ||||
2399 | while (!VNI->isPHIDef()) { | |||
2400 | SlotIndex Def = VNI->def; | |||
2401 | MachineInstr *MI = Indexes->getInstructionFromIndex(Def); | |||
2402 | assert(MI && "No defining instruction")((MI && "No defining instruction") ? static_cast<void > (0) : __assert_fail ("MI && \"No defining instruction\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2402, __PRETTY_FUNCTION__)); | |||
2403 | if (!MI->isFullCopy()) | |||
2404 | return std::make_pair(VNI, TrackReg); | |||
2405 | unsigned SrcReg = MI->getOperand(1).getReg(); | |||
2406 | if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) | |||
2407 | return std::make_pair(VNI, TrackReg); | |||
2408 | ||||
2409 | const LiveInterval &LI = LIS->getInterval(SrcReg); | |||
2410 | const VNInfo *ValueIn; | |||
2411 | // No subrange involved. | |||
2412 | if (!SubRangeJoin || !LI.hasSubRanges()) { | |||
2413 | LiveQueryResult LRQ = LI.Query(Def); | |||
2414 | ValueIn = LRQ.valueIn(); | |||
2415 | } else { | |||
2416 | // Query subranges. Ensure that all matching ones take us to the same def | |||
2417 | // (allowing some of them to be undef). | |||
2418 | ValueIn = nullptr; | |||
2419 | for (const LiveInterval::SubRange &S : LI.subranges()) { | |||
2420 | // Transform lanemask to a mask in the joined live interval. | |||
2421 | LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask); | |||
2422 | if ((SMask & LaneMask).none()) | |||
2423 | continue; | |||
2424 | LiveQueryResult LRQ = S.Query(Def); | |||
2425 | if (!ValueIn) { | |||
2426 | ValueIn = LRQ.valueIn(); | |||
2427 | continue; | |||
2428 | } | |||
2429 | if (LRQ.valueIn() && ValueIn != LRQ.valueIn()) | |||
2430 | return std::make_pair(VNI, TrackReg); | |||
2431 | } | |||
2432 | } | |||
2433 | if (ValueIn == nullptr) { | |||
2434 | // Reaching an undefined value is legitimate, for example: | |||
2435 | // | |||
2436 | // 1 undef %0.sub1 = ... ;; %0.sub0 == undef | |||
2437 | // 2 %1 = COPY %0 ;; %1 is defined here. | |||
2438 | // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition, | |||
2439 | // ;; but it's equivalent to "undef". | |||
2440 | return std::make_pair(nullptr, SrcReg); | |||
2441 | } | |||
2442 | VNI = ValueIn; | |||
2443 | TrackReg = SrcReg; | |||
2444 | } | |||
2445 | return std::make_pair(VNI, TrackReg); | |||
2446 | } | |||
2447 | ||||
2448 | bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1, | |||
2449 | const JoinVals &Other) const { | |||
2450 | const VNInfo *Orig0; | |||
2451 | unsigned Reg0; | |||
2452 | std::tie(Orig0, Reg0) = followCopyChain(Value0); | |||
2453 | if (Orig0 == Value1 && Reg0 == Other.Reg) | |||
2454 | return true; | |||
2455 | ||||
2456 | const VNInfo *Orig1; | |||
2457 | unsigned Reg1; | |||
2458 | std::tie(Orig1, Reg1) = Other.followCopyChain(Value1); | |||
2459 | // If both values are undefined, and the source registers are the same | |||
2460 | // register, the values are identical. Filter out cases where only one | |||
2461 | // value is defined. | |||
2462 | if (Orig0 == nullptr || Orig1 == nullptr) | |||
2463 | return Orig0 == Orig1 && Reg0 == Reg1; | |||
2464 | ||||
2465 | // The values are equal if they are defined at the same place and use the | |||
2466 | // same register. Note that we cannot compare VNInfos directly as some of | |||
2467 | // them might be from a copy created in mergeSubRangeInto() while the other | |||
2468 | // is from the original LiveInterval. | |||
2469 | return Orig0->def == Orig1->def && Reg0 == Reg1; | |||
2470 | } | |||
2471 | ||||
2472 | JoinVals::ConflictResolution | |||
2473 | JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) { | |||
2474 | Val &V = Vals[ValNo]; | |||
2475 | assert(!V.isAnalyzed() && "Value has already been analyzed!")((!V.isAnalyzed() && "Value has already been analyzed!" ) ? static_cast<void> (0) : __assert_fail ("!V.isAnalyzed() && \"Value has already been analyzed!\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2475, __PRETTY_FUNCTION__)); | |||
2476 | VNInfo *VNI = LR.getValNumInfo(ValNo); | |||
2477 | if (VNI->isUnused()) { | |||
2478 | V.WriteLanes = LaneBitmask::getAll(); | |||
2479 | return CR_Keep; | |||
2480 | } | |||
2481 | ||||
2482 | // Get the instruction defining this value, compute the lanes written. | |||
2483 | const MachineInstr *DefMI = nullptr; | |||
2484 | if (VNI->isPHIDef()) { | |||
2485 | // Conservatively assume that all lanes in a PHI are valid. | |||
2486 | LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0) | |||
2487 | : TRI->getSubRegIndexLaneMask(SubIdx); | |||
2488 | V.ValidLanes = V.WriteLanes = Lanes; | |||
2489 | } else { | |||
2490 | DefMI = Indexes->getInstructionFromIndex(VNI->def); | |||
2491 | assert(DefMI != nullptr)((DefMI != nullptr) ? static_cast<void> (0) : __assert_fail ("DefMI != nullptr", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2491, __PRETTY_FUNCTION__)); | |||
2492 | if (SubRangeJoin) { | |||
2493 | // We don't care about the lanes when joining subregister ranges. | |||
2494 | V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0); | |||
2495 | if (DefMI->isImplicitDef()) { | |||
2496 | V.ValidLanes = LaneBitmask::getNone(); | |||
2497 | V.ErasableImplicitDef = true; | |||
2498 | } | |||
2499 | } else { | |||
2500 | bool Redef = false; | |||
2501 | V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef); | |||
2502 | ||||
2503 | // If this is a read-modify-write instruction, there may be more valid | |||
2504 | // lanes than the ones written by this instruction. | |||
2505 | // This only covers partial redef operands. DefMI may have normal use | |||
2506 | // operands reading the register. They don't contribute valid lanes. | |||
2507 | // | |||
2508 | // This adds ssub1 to the set of valid lanes in %src: | |||
2509 | // | |||
2510 | // %src:ssub1 = FOO | |||
2511 | // | |||
2512 | // This leaves only ssub1 valid, making any other lanes undef: | |||
2513 | // | |||
2514 | // %src:ssub1<def,read-undef> = FOO %src:ssub2 | |||
2515 | // | |||
2516 | // The <read-undef> flag on the def operand means that old lane values are | |||
2517 | // not important. | |||
2518 | if (Redef) { | |||
2519 | V.RedefVNI = LR.Query(VNI->def).valueIn(); | |||
2520 | assert((TrackSubRegLiveness || V.RedefVNI) &&(((TrackSubRegLiveness || V.RedefVNI) && "Instruction is reading nonexistent value" ) ? static_cast<void> (0) : __assert_fail ("(TrackSubRegLiveness || V.RedefVNI) && \"Instruction is reading nonexistent value\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2521, __PRETTY_FUNCTION__)) | |||
2521 | "Instruction is reading nonexistent value")(((TrackSubRegLiveness || V.RedefVNI) && "Instruction is reading nonexistent value" ) ? static_cast<void> (0) : __assert_fail ("(TrackSubRegLiveness || V.RedefVNI) && \"Instruction is reading nonexistent value\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2521, __PRETTY_FUNCTION__)); | |||
2522 | if (V.RedefVNI != nullptr) { | |||
2523 | computeAssignment(V.RedefVNI->id, Other); | |||
2524 | V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes; | |||
2525 | } | |||
2526 | } | |||
2527 | ||||
2528 | // An IMPLICIT_DEF writes undef values. | |||
2529 | if (DefMI->isImplicitDef()) { | |||
2530 | // We normally expect IMPLICIT_DEF values to be live only until the end | |||
2531 | // of their block. If the value is really live longer and gets pruned in | |||
2532 | // another block, this flag is cleared again. | |||
2533 | // | |||
2534 | // Clearing the valid lanes is deferred until it is sure this can be | |||
2535 | // erased. | |||
2536 | V.ErasableImplicitDef = true; | |||
2537 | } | |||
2538 | } | |||
2539 | } | |||
2540 | ||||
2541 | // Find the value in Other that overlaps VNI->def, if any. | |||
2542 | LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def); | |||
2543 | ||||
2544 | // It is possible that both values are defined by the same instruction, or | |||
2545 | // the values are PHIs defined in the same block. When that happens, the two | |||
2546 | // values should be merged into one, but not into any preceding value. | |||
2547 | // The first value defined or visited gets CR_Keep, the other gets CR_Merge. | |||
2548 | if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) { | |||
2549 | assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ")((SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ") ? static_cast<void> (0) : __assert_fail ( "SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && \"Broken LRQ\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2549, __PRETTY_FUNCTION__)); | |||
2550 | ||||
2551 | // One value stays, the other is merged. Keep the earlier one, or the first | |||
2552 | // one we see. | |||
2553 | if (OtherVNI->def < VNI->def) | |||
2554 | Other.computeAssignment(OtherVNI->id, *this); | |||
2555 | else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) { | |||
2556 | // This is an early-clobber def overlapping a live-in value in the other | |||
2557 | // register. Not mergeable. | |||
2558 | V.OtherVNI = OtherLRQ.valueIn(); | |||
2559 | return CR_Impossible; | |||
2560 | } | |||
2561 | V.OtherVNI = OtherVNI; | |||
2562 | Val &OtherV = Other.Vals[OtherVNI->id]; | |||
2563 | // Keep this value, check for conflicts when analyzing OtherVNI. | |||
2564 | if (!OtherV.isAnalyzed()) | |||
2565 | return CR_Keep; | |||
2566 | // Both sides have been analyzed now. | |||
2567 | // Allow overlapping PHI values. Any real interference would show up in a | |||
2568 | // predecessor, the PHI itself can't introduce any conflicts. | |||
2569 | if (VNI->isPHIDef()) | |||
2570 | return CR_Merge; | |||
2571 | if ((V.ValidLanes & OtherV.ValidLanes).any()) | |||
2572 | // Overlapping lanes can't be resolved. | |||
2573 | return CR_Impossible; | |||
2574 | else | |||
2575 | return CR_Merge; | |||
2576 | } | |||
2577 | ||||
2578 | // No simultaneous def. Is Other live at the def? | |||
2579 | V.OtherVNI = OtherLRQ.valueIn(); | |||
2580 | if (!V.OtherVNI) | |||
2581 | // No overlap, no conflict. | |||
2582 | return CR_Keep; | |||
2583 | ||||
2584 | assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ")((!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ") ? static_cast<void> (0) : __assert_fail ( "!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && \"Broken LRQ\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2584, __PRETTY_FUNCTION__)); | |||
2585 | ||||
2586 | // We have overlapping values, or possibly a kill of Other. | |||
2587 | // Recursively compute assignments up the dominator tree. | |||
2588 | Other.computeAssignment(V.OtherVNI->id, *this); | |||
2589 | Val &OtherV = Other.Vals[V.OtherVNI->id]; | |||
2590 | ||||
2591 | if (OtherV.ErasableImplicitDef) { | |||
2592 | // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block. | |||
2593 | // This shouldn't normally happen, but ProcessImplicitDefs can leave such | |||
2594 | // IMPLICIT_DEF instructions behind, and there is nothing wrong with it | |||
2595 | // technically. | |||
2596 | // | |||
2597 | // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try | |||
2598 | // to erase the IMPLICIT_DEF instruction. | |||
2599 | if (DefMI && | |||
2600 | DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) { | |||
2601 | LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def << " extends into " << printMBBReference (*DefMI->getParent()) << ", keeping it.\n"; } } while (false) | |||
2602 | << " extends into "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def << " extends into " << printMBBReference (*DefMI->getParent()) << ", keeping it.\n"; } } while (false) | |||
2603 | << printMBBReference(*DefMI->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def << " extends into " << printMBBReference (*DefMI->getParent()) << ", keeping it.\n"; } } while (false) | |||
2604 | << ", keeping it.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def << " extends into " << printMBBReference (*DefMI->getParent()) << ", keeping it.\n"; } } while (false); | |||
2605 | OtherV.ErasableImplicitDef = false; | |||
2606 | } else { | |||
2607 | // We deferred clearing these lanes in case we needed to save them | |||
2608 | OtherV.ValidLanes &= ~OtherV.WriteLanes; | |||
2609 | } | |||
2610 | } | |||
2611 | ||||
2612 | // Allow overlapping PHI values. Any real interference would show up in a | |||
2613 | // predecessor, the PHI itself can't introduce any conflicts. | |||
2614 | if (VNI->isPHIDef()) | |||
2615 | return CR_Replace; | |||
2616 | ||||
2617 | // Check for simple erasable conflicts. | |||
2618 | if (DefMI->isImplicitDef()) { | |||
2619 | // We need the def for the subregister if there is nothing else live at the | |||
2620 | // subrange at this point. | |||
2621 | if (TrackSubRegLiveness | |||
2622 | && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none()) | |||
2623 | return CR_Replace; | |||
2624 | return CR_Erase; | |||
2625 | } | |||
2626 | ||||
2627 | // Include the non-conflict where DefMI is a coalescable copy that kills | |||
2628 | // OtherVNI. We still want the copy erased and value numbers merged. | |||
2629 | if (CP.isCoalescable(DefMI)) { | |||
2630 | // Some of the lanes copied from OtherVNI may be undef, making them undef | |||
2631 | // here too. | |||
2632 | V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes; | |||
2633 | return CR_Erase; | |||
2634 | } | |||
2635 | ||||
2636 | // This may not be a real conflict if DefMI simply kills Other and defines | |||
2637 | // VNI. | |||
2638 | if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def) | |||
2639 | return CR_Keep; | |||
2640 | ||||
2641 | // Handle the case where VNI and OtherVNI can be proven to be identical: | |||
2642 | // | |||
2643 | // %other = COPY %ext | |||
2644 | // %this = COPY %ext <-- Erase this copy | |||
2645 | // | |||
2646 | if (DefMI->isFullCopy() && !CP.isPartial() && | |||
2647 | valuesIdentical(VNI, V.OtherVNI, Other)) { | |||
2648 | V.Identical = true; | |||
2649 | return CR_Erase; | |||
2650 | } | |||
2651 | ||||
2652 | // The remaining checks apply to the lanes, which aren't tracked here. This | |||
2653 | // was already decided to be OK via the following CR_Replace condition. | |||
2654 | // CR_Replace. | |||
2655 | if (SubRangeJoin) | |||
2656 | return CR_Replace; | |||
2657 | ||||
2658 | // If the lanes written by this instruction were all undef in OtherVNI, it is | |||
2659 | // still safe to join the live ranges. This can't be done with a simple value | |||
2660 | // mapping, though - OtherVNI will map to multiple values: | |||
2661 | // | |||
2662 | // 1 %dst:ssub0 = FOO <-- OtherVNI | |||
2663 | // 2 %src = BAR <-- VNI | |||
2664 | // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy. | |||
2665 | // 4 BAZ killed %dst | |||
2666 | // 5 QUUX killed %src | |||
2667 | // | |||
2668 | // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace | |||
2669 | // handles this complex value mapping. | |||
2670 | if ((V.WriteLanes & OtherV.ValidLanes).none()) | |||
2671 | return CR_Replace; | |||
2672 | ||||
2673 | // If the other live range is killed by DefMI and the live ranges are still | |||
2674 | // overlapping, it must be because we're looking at an early clobber def: | |||
2675 | // | |||
2676 | // %dst<def,early-clobber> = ASM killed %src | |||
2677 | // | |||
2678 | // In this case, it is illegal to merge the two live ranges since the early | |||
2679 | // clobber def would clobber %src before it was read. | |||
2680 | if (OtherLRQ.isKill()) { | |||
2681 | // This case where the def doesn't overlap the kill is handled above. | |||
2682 | assert(VNI->def.isEarlyClobber() &&((VNI->def.isEarlyClobber() && "Only early clobber defs can overlap a kill" ) ? static_cast<void> (0) : __assert_fail ("VNI->def.isEarlyClobber() && \"Only early clobber defs can overlap a kill\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2683, __PRETTY_FUNCTION__)) | |||
2683 | "Only early clobber defs can overlap a kill")((VNI->def.isEarlyClobber() && "Only early clobber defs can overlap a kill" ) ? static_cast<void> (0) : __assert_fail ("VNI->def.isEarlyClobber() && \"Only early clobber defs can overlap a kill\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2683, __PRETTY_FUNCTION__)); | |||
2684 | return CR_Impossible; | |||
2685 | } | |||
2686 | ||||
2687 | // VNI is clobbering live lanes in OtherVNI, but there is still the | |||
2688 | // possibility that no instructions actually read the clobbered lanes. | |||
2689 | // If we're clobbering all the lanes in OtherVNI, at least one must be read. | |||
2690 | // Otherwise Other.RI wouldn't be live here. | |||
2691 | if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none()) | |||
2692 | return CR_Impossible; | |||
2693 | ||||
2694 | // We need to verify that no instructions are reading the clobbered lanes. To | |||
2695 | // save compile time, we'll only check that locally. Don't allow the tainted | |||
2696 | // value to escape the basic block. | |||
2697 | MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); | |||
2698 | if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB)) | |||
2699 | return CR_Impossible; | |||
2700 | ||||
2701 | // There are still some things that could go wrong besides clobbered lanes | |||
2702 | // being read, for example OtherVNI may be only partially redefined in MBB, | |||
2703 | // and some clobbered lanes could escape the block. Save this analysis for | |||
2704 | // resolveConflicts() when all values have been mapped. We need to know | |||
2705 | // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute | |||
2706 | // that now - the recursive analyzeValue() calls must go upwards in the | |||
2707 | // dominator tree. | |||
2708 | return CR_Unresolved; | |||
2709 | } | |||
2710 | ||||
2711 | void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) { | |||
2712 | Val &V = Vals[ValNo]; | |||
2713 | if (V.isAnalyzed()) { | |||
2714 | // Recursion should always move up the dominator tree, so ValNo is not | |||
2715 | // supposed to reappear before it has been assigned. | |||
2716 | assert(Assignments[ValNo] != -1 && "Bad recursion?")((Assignments[ValNo] != -1 && "Bad recursion?") ? static_cast <void> (0) : __assert_fail ("Assignments[ValNo] != -1 && \"Bad recursion?\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2716, __PRETTY_FUNCTION__)); | |||
2717 | return; | |||
2718 | } | |||
2719 | switch ((V.Resolution = analyzeValue(ValNo, Other))) { | |||
2720 | case CR_Erase: | |||
2721 | case CR_Merge: | |||
2722 | // Merge this ValNo into OtherVNI. | |||
2723 | assert(V.OtherVNI && "OtherVNI not assigned, can't merge.")((V.OtherVNI && "OtherVNI not assigned, can't merge." ) ? static_cast<void> (0) : __assert_fail ("V.OtherVNI && \"OtherVNI not assigned, can't merge.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2723, __PRETTY_FUNCTION__)); | |||
2724 | assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion")((Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion" ) ? static_cast<void> (0) : __assert_fail ("Other.Vals[V.OtherVNI->id].isAnalyzed() && \"Missing recursion\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2724, __PRETTY_FUNCTION__)); | |||
2725 | Assignments[ValNo] = Other.Assignments[V.OtherVNI->id]; | |||
2726 | LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tmerge " << printReg (Reg) << ':' << ValNo << '@' << LR.getValNumInfo (ValNo)->def << " into " << printReg(Other.Reg ) << ':' << V.OtherVNI->id << '@' << V.OtherVNI->def << " --> @" << NewVNInfo[Assignments [ValNo]]->def << '\n'; } } while (false) | |||
2727 | << LR.getValNumInfo(ValNo)->def << " into "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tmerge " << printReg (Reg) << ':' << ValNo << '@' << LR.getValNumInfo (ValNo)->def << " into " << printReg(Other.Reg ) << ':' << V.OtherVNI->id << '@' << V.OtherVNI->def << " --> @" << NewVNInfo[Assignments [ValNo]]->def << '\n'; } } while (false) | |||
2728 | << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tmerge " << printReg (Reg) << ':' << ValNo << '@' << LR.getValNumInfo (ValNo)->def << " into " << printReg(Other.Reg ) << ':' << V.OtherVNI->id << '@' << V.OtherVNI->def << " --> @" << NewVNInfo[Assignments [ValNo]]->def << '\n'; } } while (false) | |||
2729 | << V.OtherVNI->def << " --> @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tmerge " << printReg (Reg) << ':' << ValNo << '@' << LR.getValNumInfo (ValNo)->def << " into " << printReg(Other.Reg ) << ':' << V.OtherVNI->id << '@' << V.OtherVNI->def << " --> @" << NewVNInfo[Assignments [ValNo]]->def << '\n'; } } while (false) | |||
2730 | << NewVNInfo[Assignments[ValNo]]->def << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tmerge " << printReg (Reg) << ':' << ValNo << '@' << LR.getValNumInfo (ValNo)->def << " into " << printReg(Other.Reg ) << ':' << V.OtherVNI->id << '@' << V.OtherVNI->def << " --> @" << NewVNInfo[Assignments [ValNo]]->def << '\n'; } } while (false); | |||
2731 | break; | |||
2732 | case CR_Replace: | |||
2733 | case CR_Unresolved: { | |||
2734 | // The other value is going to be pruned if this join is successful. | |||
2735 | assert(V.OtherVNI && "OtherVNI not assigned, can't prune")((V.OtherVNI && "OtherVNI not assigned, can't prune") ? static_cast<void> (0) : __assert_fail ("V.OtherVNI && \"OtherVNI not assigned, can't prune\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2735, __PRETTY_FUNCTION__)); | |||
2736 | Val &OtherV = Other.Vals[V.OtherVNI->id]; | |||
2737 | // We cannot erase an IMPLICIT_DEF if we don't have valid values for all | |||
2738 | // its lanes. | |||
2739 | if (OtherV.ErasableImplicitDef && | |||
2740 | TrackSubRegLiveness && | |||
2741 | (OtherV.WriteLanes & ~V.ValidLanes).any()) { | |||
2742 | LLVM_DEBUG(dbgs() << "Cannot erase implicit_def with missing values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Cannot erase implicit_def with missing values\n" ; } } while (false); | |||
2743 | ||||
2744 | OtherV.ErasableImplicitDef = false; | |||
2745 | // The valid lanes written by the implicit_def were speculatively cleared | |||
2746 | // before, so make this more conservative. It may be better to track this, | |||
2747 | // I haven't found a testcase where it matters. | |||
2748 | OtherV.ValidLanes = LaneBitmask::getAll(); | |||
2749 | } | |||
2750 | ||||
2751 | OtherV.Pruned = true; | |||
2752 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2753 | } | |||
2754 | default: | |||
2755 | // This value number needs to go in the final joined live range. | |||
2756 | Assignments[ValNo] = NewVNInfo.size(); | |||
2757 | NewVNInfo.push_back(LR.getValNumInfo(ValNo)); | |||
2758 | break; | |||
2759 | } | |||
2760 | } | |||
2761 | ||||
2762 | bool JoinVals::mapValues(JoinVals &Other) { | |||
2763 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
2764 | computeAssignment(i, Other); | |||
2765 | if (Vals[i].Resolution == CR_Impossible) { | |||
2766 | LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i << '@' << LR .getValNumInfo(i)->def << '\n'; } } while (false) | |||
2767 | << '@' << LR.getValNumInfo(i)->def << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i << '@' << LR .getValNumInfo(i)->def << '\n'; } } while (false); | |||
2768 | return false; | |||
2769 | } | |||
2770 | } | |||
2771 | return true; | |||
2772 | } | |||
2773 | ||||
2774 | bool JoinVals:: | |||
2775 | taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other, | |||
2776 | SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) { | |||
2777 | VNInfo *VNI = LR.getValNumInfo(ValNo); | |||
2778 | MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); | |||
2779 | SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB); | |||
2780 | ||||
2781 | // Scan Other.LR from VNI.def to MBBEnd. | |||
2782 | LiveInterval::iterator OtherI = Other.LR.find(VNI->def); | |||
2783 | assert(OtherI != Other.LR.end() && "No conflict?")((OtherI != Other.LR.end() && "No conflict?") ? static_cast <void> (0) : __assert_fail ("OtherI != Other.LR.end() && \"No conflict?\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2783, __PRETTY_FUNCTION__)); | |||
2784 | do { | |||
2785 | // OtherI is pointing to a tainted value. Abort the join if the tainted | |||
2786 | // lanes escape the block. | |||
2787 | SlotIndex End = OtherI->end; | |||
2788 | if (End >= MBBEnd) { | |||
2789 | LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':' << OtherI->valno-> id << '@' << OtherI->start << '\n'; } } while (false) | |||
2790 | << OtherI->valno->id << '@' << OtherI->start << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':' << OtherI->valno-> id << '@' << OtherI->start << '\n'; } } while (false); | |||
2791 | return false; | |||
2792 | } | |||
2793 | LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttaints local " << printReg (Other.Reg) << ':' << OtherI->valno->id << '@' << OtherI->start << " to " << End << '\n'; } } while (false) | |||
2794 | << OtherI->valno->id << '@' << OtherI->start << " to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttaints local " << printReg (Other.Reg) << ':' << OtherI->valno->id << '@' << OtherI->start << " to " << End << '\n'; } } while (false) | |||
2795 | << End << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttaints local " << printReg (Other.Reg) << ':' << OtherI->valno->id << '@' << OtherI->start << " to " << End << '\n'; } } while (false); | |||
2796 | // A dead def is not a problem. | |||
2797 | if (End.isDead()) | |||
2798 | break; | |||
2799 | TaintExtent.push_back(std::make_pair(End, TaintedLanes)); | |||
2800 | ||||
2801 | // Check for another def in the MBB. | |||
2802 | if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd) | |||
2803 | break; | |||
2804 | ||||
2805 | // Lanes written by the new def are no longer tainted. | |||
2806 | const Val &OV = Other.Vals[OtherI->valno->id]; | |||
2807 | TaintedLanes &= ~OV.WriteLanes; | |||
2808 | if (!OV.RedefVNI) | |||
2809 | break; | |||
2810 | } while (TaintedLanes.any()); | |||
2811 | return true; | |||
2812 | } | |||
2813 | ||||
2814 | bool JoinVals::usesLanes(const MachineInstr &MI, unsigned Reg, unsigned SubIdx, | |||
2815 | LaneBitmask Lanes) const { | |||
2816 | if (MI.isDebugInstr()) | |||
2817 | return false; | |||
2818 | for (const MachineOperand &MO : MI.operands()) { | |||
2819 | if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg) | |||
2820 | continue; | |||
2821 | if (!MO.readsReg()) | |||
2822 | continue; | |||
2823 | unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg()); | |||
2824 | if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any()) | |||
2825 | return true; | |||
2826 | } | |||
2827 | return false; | |||
2828 | } | |||
2829 | ||||
2830 | bool JoinVals::resolveConflicts(JoinVals &Other) { | |||
2831 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
2832 | Val &V = Vals[i]; | |||
2833 | assert(V.Resolution != CR_Impossible && "Unresolvable conflict")((V.Resolution != CR_Impossible && "Unresolvable conflict" ) ? static_cast<void> (0) : __assert_fail ("V.Resolution != CR_Impossible && \"Unresolvable conflict\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2833, __PRETTY_FUNCTION__)); | |||
2834 | if (V.Resolution != CR_Unresolved) | |||
2835 | continue; | |||
2836 | LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tconflict at " << printReg (Reg) << ':' << i << '@' << LR.getValNumInfo (i)->def << '\n'; } } while (false) | |||
2837 | << LR.getValNumInfo(i)->def << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tconflict at " << printReg (Reg) << ':' << i << '@' << LR.getValNumInfo (i)->def << '\n'; } } while (false); | |||
2838 | if (SubRangeJoin) | |||
2839 | return false; | |||
2840 | ||||
2841 | ++NumLaneConflicts; | |||
2842 | assert(V.OtherVNI && "Inconsistent conflict resolution.")((V.OtherVNI && "Inconsistent conflict resolution.") ? static_cast<void> (0) : __assert_fail ("V.OtherVNI && \"Inconsistent conflict resolution.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2842, __PRETTY_FUNCTION__)); | |||
2843 | VNInfo *VNI = LR.getValNumInfo(i); | |||
2844 | const Val &OtherV = Other.Vals[V.OtherVNI->id]; | |||
2845 | ||||
2846 | // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the | |||
2847 | // join, those lanes will be tainted with a wrong value. Get the extent of | |||
2848 | // the tainted lanes. | |||
2849 | LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes; | |||
2850 | SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent; | |||
2851 | if (!taintExtent(i, TaintedLanes, Other, TaintExtent)) | |||
2852 | // Tainted lanes would extend beyond the basic block. | |||
2853 | return false; | |||
2854 | ||||
2855 | assert(!TaintExtent.empty() && "There should be at least one conflict.")((!TaintExtent.empty() && "There should be at least one conflict." ) ? static_cast<void> (0) : __assert_fail ("!TaintExtent.empty() && \"There should be at least one conflict.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2855, __PRETTY_FUNCTION__)); | |||
2856 | ||||
2857 | // Now look at the instructions from VNI->def to TaintExtent (inclusive). | |||
2858 | MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); | |||
2859 | MachineBasicBlock::iterator MI = MBB->begin(); | |||
2860 | if (!VNI->isPHIDef()) { | |||
2861 | MI = Indexes->getInstructionFromIndex(VNI->def); | |||
2862 | // No need to check the instruction defining VNI for reads. | |||
2863 | ++MI; | |||
2864 | } | |||
2865 | assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&((!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first ) && "Interference ends on VNI->def. Should have been handled earlier" ) ? static_cast<void> (0) : __assert_fail ("!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && \"Interference ends on VNI->def. Should have been handled earlier\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2866, __PRETTY_FUNCTION__)) | |||
2866 | "Interference ends on VNI->def. Should have been handled earlier")((!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first ) && "Interference ends on VNI->def. Should have been handled earlier" ) ? static_cast<void> (0) : __assert_fail ("!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && \"Interference ends on VNI->def. Should have been handled earlier\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2866, __PRETTY_FUNCTION__)); | |||
2867 | MachineInstr *LastMI = | |||
2868 | Indexes->getInstructionFromIndex(TaintExtent.front().first); | |||
2869 | assert(LastMI && "Range must end at a proper instruction")((LastMI && "Range must end at a proper instruction") ? static_cast<void> (0) : __assert_fail ("LastMI && \"Range must end at a proper instruction\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2869, __PRETTY_FUNCTION__)); | |||
2870 | unsigned TaintNum = 0; | |||
2871 | while (true) { | |||
2872 | assert(MI != MBB->end() && "Bad LastMI")((MI != MBB->end() && "Bad LastMI") ? static_cast< void> (0) : __assert_fail ("MI != MBB->end() && \"Bad LastMI\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2872, __PRETTY_FUNCTION__)); | |||
2873 | if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) { | |||
2874 | LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\ttainted lanes used by: " << *MI; } } while (false); | |||
2875 | return false; | |||
2876 | } | |||
2877 | // LastMI is the last instruction to use the current value. | |||
2878 | if (&*MI == LastMI) { | |||
2879 | if (++TaintNum == TaintExtent.size()) | |||
2880 | break; | |||
2881 | LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first); | |||
2882 | assert(LastMI && "Range must end at a proper instruction")((LastMI && "Range must end at a proper instruction") ? static_cast<void> (0) : __assert_fail ("LastMI && \"Range must end at a proper instruction\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2882, __PRETTY_FUNCTION__)); | |||
2883 | TaintedLanes = TaintExtent[TaintNum].second; | |||
2884 | } | |||
2885 | ++MI; | |||
2886 | } | |||
2887 | ||||
2888 | // The tainted lanes are unused. | |||
2889 | V.Resolution = CR_Replace; | |||
2890 | ++NumLaneResolves; | |||
2891 | } | |||
2892 | return true; | |||
2893 | } | |||
2894 | ||||
2895 | bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) { | |||
2896 | Val &V = Vals[ValNo]; | |||
2897 | if (V.Pruned || V.PrunedComputed) | |||
2898 | return V.Pruned; | |||
2899 | ||||
2900 | if (V.Resolution != CR_Erase && V.Resolution != CR_Merge) | |||
2901 | return V.Pruned; | |||
2902 | ||||
2903 | // Follow copies up the dominator tree and check if any intermediate value | |||
2904 | // has been pruned. | |||
2905 | V.PrunedComputed = true; | |||
2906 | V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this); | |||
2907 | return V.Pruned; | |||
2908 | } | |||
2909 | ||||
2910 | void JoinVals::pruneValues(JoinVals &Other, | |||
2911 | SmallVectorImpl<SlotIndex> &EndPoints, | |||
2912 | bool changeInstrs) { | |||
2913 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
2914 | SlotIndex Def = LR.getValNumInfo(i)->def; | |||
2915 | switch (Vals[i].Resolution) { | |||
2916 | case CR_Keep: | |||
2917 | break; | |||
2918 | case CR_Replace: { | |||
2919 | // This value takes precedence over the value in Other.LR. | |||
2920 | LIS->pruneValue(Other.LR, Def, &EndPoints); | |||
2921 | // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF | |||
2922 | // instructions are only inserted to provide a live-out value for PHI | |||
2923 | // predecessors, so the instruction should simply go away once its value | |||
2924 | // has been replaced. | |||
2925 | Val &OtherV = Other.Vals[Vals[i].OtherVNI->id]; | |||
2926 | bool EraseImpDef = OtherV.ErasableImplicitDef && | |||
2927 | OtherV.Resolution == CR_Keep; | |||
2928 | if (!Def.isBlock()) { | |||
2929 | if (changeInstrs) { | |||
2930 | // Remove <def,read-undef> flags. This def is now a partial redef. | |||
2931 | // Also remove dead flags since the joined live range will | |||
2932 | // continue past this instruction. | |||
2933 | for (MachineOperand &MO : | |||
2934 | Indexes->getInstructionFromIndex(Def)->operands()) { | |||
2935 | if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) { | |||
2936 | if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef) | |||
2937 | MO.setIsUndef(false); | |||
2938 | MO.setIsDead(false); | |||
2939 | } | |||
2940 | } | |||
2941 | } | |||
2942 | // This value will reach instructions below, but we need to make sure | |||
2943 | // the live range also reaches the instruction at Def. | |||
2944 | if (!EraseImpDef) | |||
2945 | EndPoints.push_back(Def); | |||
2946 | } | |||
2947 | LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tpruned " << printReg (Other.Reg) << " at " << Def << ": " << Other.LR << '\n'; } } while (false) | |||
2948 | << ": " << Other.LR << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tpruned " << printReg (Other.Reg) << " at " << Def << ": " << Other.LR << '\n'; } } while (false); | |||
2949 | break; | |||
2950 | } | |||
2951 | case CR_Erase: | |||
2952 | case CR_Merge: | |||
2953 | if (isPrunedValue(i, Other)) { | |||
2954 | // This value is ultimately a copy of a pruned value in LR or Other.LR. | |||
2955 | // We can no longer trust the value mapping computed by | |||
2956 | // computeAssignment(), the value that was originally copied could have | |||
2957 | // been replaced. | |||
2958 | LIS->pruneValue(LR, Def, &EndPoints); | |||
2959 | LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tpruned all of " << printReg(Reg) << " at " << Def << ": " << LR << '\n'; } } while (false) | |||
2960 | << Def << ": " << LR << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tpruned all of " << printReg(Reg) << " at " << Def << ": " << LR << '\n'; } } while (false); | |||
2961 | } | |||
2962 | break; | |||
2963 | case CR_Unresolved: | |||
2964 | case CR_Impossible: | |||
2965 | llvm_unreachable("Unresolved conflicts")::llvm::llvm_unreachable_internal("Unresolved conflicts", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 2965); | |||
2966 | } | |||
2967 | } | |||
2968 | } | |||
2969 | ||||
2970 | /// Consider the following situation when coalescing the copy between | |||
2971 | /// %31 and %45 at 800. (The vertical lines represent live range segments.) | |||
2972 | /// | |||
2973 | /// Main range Subrange 0004 (sub2) | |||
2974 | /// %31 %45 %31 %45 | |||
2975 | /// 544 %45 = COPY %28 + + | |||
2976 | /// | v1 | v1 | |||
2977 | /// 560B bb.1: + + | |||
2978 | /// 624 = %45.sub2 | v2 | v2 | |||
2979 | /// 800 %31 = COPY %45 + + + + | |||
2980 | /// | v0 | v0 | |||
2981 | /// 816 %31.sub1 = ... + | | |||
2982 | /// 880 %30 = COPY %31 | v1 + | |||
2983 | /// 928 %45 = COPY %30 | + + | |||
2984 | /// | | v0 | v0 <--+ | |||
2985 | /// 992B ; backedge -> bb.1 | + + | | |||
2986 | /// 1040 = %31.sub0 + | | |||
2987 | /// This value must remain | |||
2988 | /// live-out! | |||
2989 | /// | |||
2990 | /// Assuming that %31 is coalesced into %45, the copy at 928 becomes | |||
2991 | /// redundant, since it copies the value from %45 back into it. The | |||
2992 | /// conflict resolution for the main range determines that %45.v0 is | |||
2993 | /// to be erased, which is ok since %31.v1 is identical to it. | |||
2994 | /// The problem happens with the subrange for sub2: it has to be live | |||
2995 | /// on exit from the block, but since 928 was actually a point of | |||
2996 | /// definition of %45.sub2, %45.sub2 was not live immediately prior | |||
2997 | /// to that definition. As a result, when 928 was erased, the value v0 | |||
2998 | /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an | |||
2999 | /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2, | |||
3000 | /// providing an incorrect value to the use at 624. | |||
3001 | /// | |||
3002 | /// Since the main-range values %31.v1 and %45.v0 were proved to be | |||
3003 | /// identical, the corresponding values in subranges must also be the | |||
3004 | /// same. A redundant copy is removed because it's not needed, and not | |||
3005 | /// because it copied an undefined value, so any liveness that originated | |||
3006 | /// from that copy cannot disappear. When pruning a value that started | |||
3007 | /// at the removed copy, the corresponding identical value must be | |||
3008 | /// extended to replace it. | |||
3009 | void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) { | |||
3010 | // Look for values being erased. | |||
3011 | bool DidPrune = false; | |||
3012 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
3013 | Val &V = Vals[i]; | |||
3014 | // We should trigger in all cases in which eraseInstrs() does something. | |||
3015 | // match what eraseInstrs() is doing, print a message so | |||
3016 | if (V.Resolution != CR_Erase && | |||
3017 | (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)) | |||
3018 | continue; | |||
3019 | ||||
3020 | // Check subranges at the point where the copy will be removed. | |||
3021 | SlotIndex Def = LR.getValNumInfo(i)->def; | |||
3022 | SlotIndex OtherDef; | |||
3023 | if (V.Identical) | |||
3024 | OtherDef = V.OtherVNI->def; | |||
3025 | ||||
3026 | // Print message so mismatches with eraseInstrs() can be diagnosed. | |||
3027 | LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tExpecting instruction removal at " << Def << '\n'; } } while (false) | |||
3028 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tExpecting instruction removal at " << Def << '\n'; } } while (false); | |||
3029 | for (LiveInterval::SubRange &S : LI.subranges()) { | |||
3030 | LiveQueryResult Q = S.Query(Def); | |||
3031 | ||||
3032 | // If a subrange starts at the copy then an undefined value has been | |||
3033 | // copied and we must remove that subrange value as well. | |||
3034 | VNInfo *ValueOut = Q.valueOutOrDead(); | |||
3035 | if (ValueOut != nullptr && (Q.valueIn() == nullptr || | |||
3036 | (V.Identical && V.Resolution == CR_Erase && | |||
3037 | ValueOut->def == Def))) { | |||
3038 | LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask) << " at " << Def << "\n"; } } while (false) | |||
3039 | << " at " << Def << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask) << " at " << Def << "\n"; } } while (false); | |||
3040 | SmallVector<SlotIndex,8> EndPoints; | |||
3041 | LIS->pruneValue(S, Def, &EndPoints); | |||
3042 | DidPrune = true; | |||
3043 | // Mark value number as unused. | |||
3044 | ValueOut->markUnused(); | |||
3045 | ||||
3046 | if (V.Identical && S.Query(OtherDef).valueOutOrDead()) { | |||
3047 | // If V is identical to V.OtherVNI (and S was live at OtherDef), | |||
3048 | // then we can't simply prune V from S. V needs to be replaced | |||
3049 | // with V.OtherVNI. | |||
3050 | LIS->extendToIndices(S, EndPoints); | |||
3051 | } | |||
3052 | continue; | |||
3053 | } | |||
3054 | // If a subrange ends at the copy, then a value was copied but only | |||
3055 | // partially used later. Shrink the subregister range appropriately. | |||
3056 | if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) { | |||
3057 | LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask) << " at " << Def << "\n"; } } while (false) | |||
3058 | << PrintLaneMask(S.LaneMask) << " at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask) << " at " << Def << "\n"; } } while (false) | |||
3059 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask) << " at " << Def << "\n"; } } while (false); | |||
3060 | ShrinkMask |= S.LaneMask; | |||
3061 | } | |||
3062 | } | |||
3063 | } | |||
3064 | if (DidPrune) | |||
3065 | LI.removeEmptySubRanges(); | |||
3066 | } | |||
3067 | ||||
3068 | /// Check if any of the subranges of @p LI contain a definition at @p Def. | |||
3069 | static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) { | |||
3070 | for (LiveInterval::SubRange &SR : LI.subranges()) { | |||
3071 | if (VNInfo *VNI = SR.Query(Def).valueOutOrDead()) | |||
3072 | if (VNI->def == Def) | |||
3073 | return true; | |||
3074 | } | |||
3075 | return false; | |||
3076 | } | |||
3077 | ||||
3078 | void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) { | |||
3079 | assert(&static_cast<LiveRange&>(LI) == &LR)((&static_cast<LiveRange&>(LI) == &LR) ? static_cast <void> (0) : __assert_fail ("&static_cast<LiveRange&>(LI) == &LR" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3079, __PRETTY_FUNCTION__)); | |||
3080 | ||||
3081 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
3082 | if (Vals[i].Resolution != CR_Keep) | |||
3083 | continue; | |||
3084 | VNInfo *VNI = LR.getValNumInfo(i); | |||
3085 | if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def)) | |||
3086 | continue; | |||
3087 | Vals[i].Pruned = true; | |||
3088 | ShrinkMainRange = true; | |||
3089 | } | |||
3090 | } | |||
3091 | ||||
3092 | void JoinVals::removeImplicitDefs() { | |||
3093 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
3094 | Val &V = Vals[i]; | |||
3095 | if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned) | |||
3096 | continue; | |||
3097 | ||||
3098 | VNInfo *VNI = LR.getValNumInfo(i); | |||
3099 | VNI->markUnused(); | |||
3100 | LR.removeValNo(VNI); | |||
3101 | } | |||
3102 | } | |||
3103 | ||||
3104 | void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, | |||
3105 | SmallVectorImpl<unsigned> &ShrinkRegs, | |||
3106 | LiveInterval *LI) { | |||
3107 | for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { | |||
3108 | // Get the def location before markUnused() below invalidates it. | |||
3109 | SlotIndex Def = LR.getValNumInfo(i)->def; | |||
3110 | switch (Vals[i].Resolution) { | |||
3111 | case CR_Keep: { | |||
3112 | // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any | |||
3113 | // longer. The IMPLICIT_DEF instructions are only inserted by | |||
3114 | // PHIElimination to guarantee that all PHI predecessors have a value. | |||
3115 | if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned) | |||
3116 | break; | |||
3117 | // Remove value number i from LR. | |||
3118 | // For intervals with subranges, removing a segment from the main range | |||
3119 | // may require extending the previous segment: for each definition of | |||
3120 | // a subregister, there will be a corresponding def in the main range. | |||
3121 | // That def may fall in the middle of a segment from another subrange. | |||
3122 | // In such cases, removing this def from the main range must be | |||
3123 | // complemented by extending the main range to account for the liveness | |||
3124 | // of the other subrange. | |||
3125 | VNInfo *VNI = LR.getValNumInfo(i); | |||
3126 | SlotIndex Def = VNI->def; | |||
3127 | // The new end point of the main range segment to be extended. | |||
3128 | SlotIndex NewEnd; | |||
3129 | if (LI != nullptr) { | |||
3130 | LiveRange::iterator I = LR.FindSegmentContaining(Def); | |||
3131 | assert(I != LR.end())((I != LR.end()) ? static_cast<void> (0) : __assert_fail ("I != LR.end()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3131, __PRETTY_FUNCTION__)); | |||
3132 | // Do not extend beyond the end of the segment being removed. | |||
3133 | // The segment may have been pruned in preparation for joining | |||
3134 | // live ranges. | |||
3135 | NewEnd = I->end; | |||
3136 | } | |||
3137 | ||||
3138 | LR.removeValNo(VNI); | |||
3139 | // Note that this VNInfo is reused and still referenced in NewVNInfo, | |||
3140 | // make it appear like an unused value number. | |||
3141 | VNI->markUnused(); | |||
3142 | ||||
3143 | if (LI != nullptr && LI->hasSubRanges()) { | |||
3144 | assert(static_cast<LiveRange*>(LI) == &LR)((static_cast<LiveRange*>(LI) == &LR) ? static_cast <void> (0) : __assert_fail ("static_cast<LiveRange*>(LI) == &LR" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3144, __PRETTY_FUNCTION__)); | |||
3145 | // Determine the end point based on the subrange information: | |||
3146 | // minimum of (earliest def of next segment, | |||
3147 | // latest end point of containing segment) | |||
3148 | SlotIndex ED, LE; | |||
3149 | for (LiveInterval::SubRange &SR : LI->subranges()) { | |||
3150 | LiveRange::iterator I = SR.find(Def); | |||
3151 | if (I == SR.end()) | |||
3152 | continue; | |||
3153 | if (I->start > Def) | |||
3154 | ED = ED.isValid() ? std::min(ED, I->start) : I->start; | |||
3155 | else | |||
3156 | LE = LE.isValid() ? std::max(LE, I->end) : I->end; | |||
3157 | } | |||
3158 | if (LE.isValid()) | |||
3159 | NewEnd = std::min(NewEnd, LE); | |||
3160 | if (ED.isValid()) | |||
3161 | NewEnd = std::min(NewEnd, ED); | |||
3162 | ||||
3163 | // We only want to do the extension if there was a subrange that | |||
3164 | // was live across Def. | |||
3165 | if (LE.isValid()) { | |||
3166 | LiveRange::iterator S = LR.find(Def); | |||
3167 | if (S != LR.begin()) | |||
3168 | std::prev(S)->end = NewEnd; | |||
3169 | } | |||
3170 | } | |||
3171 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; if (LI != nullptr) dbgs() << "\t\t LHS = " << *LI << '\n'; }; } } while (false) | |||
3172 | dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; if (LI != nullptr) dbgs() << "\t\t LHS = " << *LI << '\n'; }; } } while (false) | |||
3173 | if (LI != nullptr)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; if (LI != nullptr) dbgs() << "\t\t LHS = " << *LI << '\n'; }; } } while (false) | |||
3174 | dbgs() << "\t\t LHS = " << *LI << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; if (LI != nullptr) dbgs() << "\t\t LHS = " << *LI << '\n'; }; } } while (false) | |||
3175 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; if (LI != nullptr) dbgs() << "\t\t LHS = " << *LI << '\n'; }; } } while (false); | |||
3176 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3177 | } | |||
3178 | ||||
3179 | case CR_Erase: { | |||
3180 | MachineInstr *MI = Indexes->getInstructionFromIndex(Def); | |||
3181 | assert(MI && "No instruction to erase")((MI && "No instruction to erase") ? static_cast<void > (0) : __assert_fail ("MI && \"No instruction to erase\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3181, __PRETTY_FUNCTION__)); | |||
3182 | if (MI->isCopy()) { | |||
3183 | unsigned Reg = MI->getOperand(1).getReg(); | |||
3184 | if (TargetRegisterInfo::isVirtualRegister(Reg) && | |||
3185 | Reg != CP.getSrcReg() && Reg != CP.getDstReg()) | |||
3186 | ShrinkRegs.push_back(Reg); | |||
3187 | } | |||
3188 | ErasedInstrs.insert(MI); | |||
3189 | LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\terased:\t" << Def << '\t' << *MI; } } while (false); | |||
3190 | LIS->RemoveMachineInstrFromMaps(*MI); | |||
3191 | MI->eraseFromParent(); | |||
3192 | break; | |||
3193 | } | |||
3194 | default: | |||
3195 | break; | |||
3196 | } | |||
3197 | } | |||
3198 | } | |||
3199 | ||||
3200 | void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, | |||
3201 | LaneBitmask LaneMask, | |||
3202 | const CoalescerPair &CP) { | |||
3203 | SmallVector<VNInfo*, 16> NewVNInfo; | |||
3204 | JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask, | |||
3205 | NewVNInfo, CP, LIS, TRI, true, true); | |||
3206 | JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask, | |||
3207 | NewVNInfo, CP, LIS, TRI, true, true); | |||
3208 | ||||
3209 | // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs()) | |||
3210 | // We should be able to resolve all conflicts here as we could successfully do | |||
3211 | // it on the mainrange already. There is however a problem when multiple | |||
3212 | // ranges get mapped to the "overflow" lane mask bit which creates unexpected | |||
3213 | // interferences. | |||
3214 | if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) { | |||
3215 | // We already determined that it is legal to merge the intervals, so this | |||
3216 | // should never fail. | |||
3217 | llvm_unreachable("*** Couldn't join subrange!\n")::llvm::llvm_unreachable_internal("*** Couldn't join subrange!\n" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3217); | |||
3218 | } | |||
3219 | if (!LHSVals.resolveConflicts(RHSVals) || | |||
3220 | !RHSVals.resolveConflicts(LHSVals)) { | |||
3221 | // We already determined that it is legal to merge the intervals, so this | |||
3222 | // should never fail. | |||
3223 | llvm_unreachable("*** Couldn't join subrange!\n")::llvm::llvm_unreachable_internal("*** Couldn't join subrange!\n" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3223); | |||
3224 | } | |||
3225 | ||||
3226 | // The merging algorithm in LiveInterval::join() can't handle conflicting | |||
3227 | // value mappings, so we need to remove any live ranges that overlap a | |||
3228 | // CR_Replace resolution. Collect a set of end points that can be used to | |||
3229 | // restore the live range after joining. | |||
3230 | SmallVector<SlotIndex, 8> EndPoints; | |||
3231 | LHSVals.pruneValues(RHSVals, EndPoints, false); | |||
3232 | RHSVals.pruneValues(LHSVals, EndPoints, false); | |||
3233 | ||||
3234 | LHSVals.removeImplicitDefs(); | |||
3235 | RHSVals.removeImplicitDefs(); | |||
3236 | ||||
3237 | LRange.verify(); | |||
3238 | RRange.verify(); | |||
3239 | ||||
3240 | // Join RRange into LHS. | |||
3241 | LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(), | |||
3242 | NewVNInfo); | |||
3243 | ||||
3244 | LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask) << ' ' << LRange << "\n"; } } while (false) | |||
3245 | << ' ' << LRange << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask) << ' ' << LRange << "\n"; } } while (false); | |||
3246 | if (EndPoints.empty()) | |||
3247 | return; | |||
3248 | ||||
3249 | // Recompute the parts of the live range we had to remove because of | |||
3250 | // CR_Replace conflicts. | |||
3251 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3252 | dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3253 | for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3254 | dbgs() << EndPoints[i];do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3255 | if (i != n-1)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3256 | dbgs() << ',';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3257 | }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3258 | dbgs() << ": " << LRange << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false) | |||
3259 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LRange << '\n'; }; } } while (false); | |||
3260 | LIS->extendToIndices(LRange, EndPoints); | |||
3261 | } | |||
3262 | ||||
3263 | void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI, | |||
3264 | const LiveRange &ToMerge, | |||
3265 | LaneBitmask LaneMask, | |||
3266 | CoalescerPair &CP) { | |||
3267 | BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); | |||
3268 | LI.refineSubRanges( | |||
3269 | Allocator, LaneMask, | |||
3270 | [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) { | |||
3271 | if (SR.empty()) { | |||
3272 | SR.assign(ToMerge, Allocator); | |||
3273 | } else { | |||
3274 | // joinSubRegRange() destroys the merged range, so we need a copy. | |||
3275 | LiveRange RangeCopy(ToMerge, Allocator); | |||
3276 | joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP); | |||
3277 | } | |||
3278 | }, | |||
3279 | *LIS->getSlotIndexes(), *TRI); | |||
3280 | } | |||
3281 | ||||
3282 | bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) { | |||
3283 | if (LI.valnos.size() < LargeIntervalSizeThreshold) | |||
3284 | return false; | |||
3285 | auto &Counter = LargeLIVisitCounter[LI.reg]; | |||
3286 | if (Counter < LargeIntervalFreqThreshold) { | |||
3287 | Counter++; | |||
3288 | return false; | |||
3289 | } | |||
3290 | return true; | |||
3291 | } | |||
3292 | ||||
3293 | bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) { | |||
3294 | SmallVector<VNInfo*, 16> NewVNInfo; | |||
3295 | LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); | |||
3296 | LiveInterval &LHS = LIS->getInterval(CP.getDstReg()); | |||
3297 | bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC()); | |||
3298 | JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(), | |||
3299 | NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness); | |||
3300 | JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(), | |||
3301 | NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness); | |||
3302 | ||||
3303 | LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n'; } } while (false); | |||
3304 | ||||
3305 | if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS)) | |||
3306 | return false; | |||
3307 | ||||
3308 | // First compute NewVNInfo and the simple value mappings. | |||
3309 | // Detect impossible conflicts early. | |||
3310 | if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) | |||
3311 | return false; | |||
3312 | ||||
3313 | // Some conflicts can only be resolved after all values have been mapped. | |||
3314 | if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals)) | |||
3315 | return false; | |||
3316 | ||||
3317 | // All clear, the live ranges can be merged. | |||
3318 | if (RHS.hasSubRanges() || LHS.hasSubRanges()) { | |||
3319 | BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); | |||
3320 | ||||
3321 | // Transform lanemasks from the LHS to masks in the coalesced register and | |||
3322 | // create initial subranges if necessary. | |||
3323 | unsigned DstIdx = CP.getDstIdx(); | |||
3324 | if (!LHS.hasSubRanges()) { | |||
3325 | LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask() | |||
3326 | : TRI->getSubRegIndexLaneMask(DstIdx); | |||
3327 | // LHS must support subregs or we wouldn't be in this codepath. | |||
3328 | assert(Mask.any())((Mask.any()) ? static_cast<void> (0) : __assert_fail ( "Mask.any()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3328, __PRETTY_FUNCTION__)); | |||
3329 | LHS.createSubRangeFrom(Allocator, Mask, LHS); | |||
3330 | } else if (DstIdx != 0) { | |||
3331 | // Transform LHS lanemasks to new register class if necessary. | |||
3332 | for (LiveInterval::SubRange &R : LHS.subranges()) { | |||
3333 | LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask); | |||
3334 | R.LaneMask = Mask; | |||
3335 | } | |||
3336 | } | |||
3337 | LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHSdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tLHST = " << printReg (CP.getDstReg()) << ' ' << LHS << '\n'; } } while (false) | |||
3338 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\t\tLHST = " << printReg (CP.getDstReg()) << ' ' << LHS << '\n'; } } while (false); | |||
3339 | ||||
3340 | // Determine lanemasks of RHS in the coalesced register and merge subranges. | |||
3341 | unsigned SrcIdx = CP.getSrcIdx(); | |||
3342 | if (!RHS.hasSubRanges()) { | |||
3343 | LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask() | |||
3344 | : TRI->getSubRegIndexLaneMask(SrcIdx); | |||
3345 | mergeSubRangeInto(LHS, RHS, Mask, CP); | |||
3346 | } else { | |||
3347 | // Pair up subranges and merge. | |||
3348 | for (LiveInterval::SubRange &R : RHS.subranges()) { | |||
3349 | LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask); | |||
3350 | mergeSubRangeInto(LHS, R, Mask, CP); | |||
3351 | } | |||
3352 | } | |||
3353 | LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "\tJoined SubRanges " << LHS << "\n"; } } while (false); | |||
3354 | ||||
3355 | // Pruning implicit defs from subranges may result in the main range | |||
3356 | // having stale segments. | |||
3357 | LHSVals.pruneMainSegments(LHS, ShrinkMainRange); | |||
3358 | ||||
3359 | LHSVals.pruneSubRegValues(LHS, ShrinkMask); | |||
3360 | RHSVals.pruneSubRegValues(LHS, ShrinkMask); | |||
3361 | } | |||
3362 | ||||
3363 | // The merging algorithm in LiveInterval::join() can't handle conflicting | |||
3364 | // value mappings, so we need to remove any live ranges that overlap a | |||
3365 | // CR_Replace resolution. Collect a set of end points that can be used to | |||
3366 | // restore the live range after joining. | |||
3367 | SmallVector<SlotIndex, 8> EndPoints; | |||
3368 | LHSVals.pruneValues(RHSVals, EndPoints, true); | |||
3369 | RHSVals.pruneValues(LHSVals, EndPoints, true); | |||
3370 | ||||
3371 | // Erase COPY and IMPLICIT_DEF instructions. This may cause some external | |||
3372 | // registers to require trimming. | |||
3373 | SmallVector<unsigned, 8> ShrinkRegs; | |||
3374 | LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS); | |||
3375 | RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); | |||
3376 | while (!ShrinkRegs.empty()) | |||
3377 | shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val())); | |||
3378 | ||||
3379 | // Join RHS into LHS. | |||
3380 | LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo); | |||
3381 | ||||
3382 | // Kill flags are going to be wrong if the live ranges were overlapping. | |||
3383 | // Eventually, we should simply clear all kill flags when computing live | |||
3384 | // ranges. They are reinserted after register allocation. | |||
3385 | MRI->clearKillFlags(LHS.reg); | |||
3386 | MRI->clearKillFlags(RHS.reg); | |||
3387 | ||||
3388 | if (!EndPoints.empty()) { | |||
3389 | // Recompute the parts of the live range we had to remove because of | |||
3390 | // CR_Replace conflicts. | |||
3391 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3392 | dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3393 | for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3394 | dbgs() << EndPoints[i];do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3395 | if (i != n-1)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3396 | dbgs() << ',';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3397 | }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3398 | dbgs() << ": " << LHS << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false) | |||
3399 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { { dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints [i]; if (i != n-1) dbgs() << ','; } dbgs() << ": " << LHS << '\n'; }; } } while (false); | |||
3400 | LIS->extendToIndices((LiveRange&)LHS, EndPoints); | |||
3401 | } | |||
3402 | ||||
3403 | return true; | |||
3404 | } | |||
3405 | ||||
3406 | bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) { | |||
3407 | return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP); | |||
3408 | } | |||
3409 | ||||
3410 | namespace { | |||
3411 | ||||
3412 | /// Information concerning MBB coalescing priority. | |||
3413 | struct MBBPriorityInfo { | |||
3414 | MachineBasicBlock *MBB; | |||
3415 | unsigned Depth; | |||
3416 | bool IsSplit; | |||
3417 | ||||
3418 | MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit) | |||
3419 | : MBB(mbb), Depth(depth), IsSplit(issplit) {} | |||
3420 | }; | |||
3421 | ||||
3422 | } // end anonymous namespace | |||
3423 | ||||
3424 | /// C-style comparator that sorts first based on the loop depth of the basic | |||
3425 | /// block (the unsigned), and then on the MBB number. | |||
3426 | /// | |||
3427 | /// EnableGlobalCopies assumes that the primary sort key is loop depth. | |||
3428 | static int compareMBBPriority(const MBBPriorityInfo *LHS, | |||
3429 | const MBBPriorityInfo *RHS) { | |||
3430 | // Deeper loops first | |||
3431 | if (LHS->Depth != RHS->Depth) | |||
3432 | return LHS->Depth > RHS->Depth ? -1 : 1; | |||
3433 | ||||
3434 | // Try to unsplit critical edges next. | |||
3435 | if (LHS->IsSplit != RHS->IsSplit) | |||
3436 | return LHS->IsSplit ? -1 : 1; | |||
3437 | ||||
3438 | // Prefer blocks that are more connected in the CFG. This takes care of | |||
3439 | // the most difficult copies first while intervals are short. | |||
3440 | unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size(); | |||
3441 | unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size(); | |||
3442 | if (cl != cr) | |||
3443 | return cl > cr ? -1 : 1; | |||
3444 | ||||
3445 | // As a last resort, sort by block number. | |||
3446 | return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1; | |||
3447 | } | |||
3448 | ||||
3449 | /// \returns true if the given copy uses or defines a local live range. | |||
3450 | static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) { | |||
3451 | if (!Copy->isCopy()) | |||
3452 | return false; | |||
3453 | ||||
3454 | if (Copy->getOperand(1).isUndef()) | |||
3455 | return false; | |||
3456 | ||||
3457 | unsigned SrcReg = Copy->getOperand(1).getReg(); | |||
3458 | unsigned DstReg = Copy->getOperand(0).getReg(); | |||
3459 | if (TargetRegisterInfo::isPhysicalRegister(SrcReg) | |||
3460 | || TargetRegisterInfo::isPhysicalRegister(DstReg)) | |||
3461 | return false; | |||
3462 | ||||
3463 | return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) | |||
3464 | || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg)); | |||
3465 | } | |||
3466 | ||||
3467 | void RegisterCoalescer::lateLiveIntervalUpdate() { | |||
3468 | for (unsigned reg : ToBeUpdated) { | |||
3469 | if (!LIS->hasInterval(reg)) | |||
3470 | continue; | |||
3471 | LiveInterval &LI = LIS->getInterval(reg); | |||
3472 | shrinkToUses(&LI, &DeadDefs); | |||
3473 | if (!DeadDefs.empty()) | |||
3474 | eliminateDeadDefs(); | |||
3475 | } | |||
3476 | ToBeUpdated.clear(); | |||
3477 | } | |||
3478 | ||||
3479 | bool RegisterCoalescer:: | |||
3480 | copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) { | |||
3481 | bool Progress = false; | |||
3482 | for (unsigned i = 0, e = CurrList.size(); i != e; ++i) { | |||
3483 | if (!CurrList[i]) | |||
3484 | continue; | |||
3485 | // Skip instruction pointers that have already been erased, for example by | |||
3486 | // dead code elimination. | |||
3487 | if (ErasedInstrs.count(CurrList[i])) { | |||
3488 | CurrList[i] = nullptr; | |||
3489 | continue; | |||
3490 | } | |||
3491 | bool Again = false; | |||
3492 | bool Success = joinCopy(CurrList[i], Again); | |||
3493 | Progress |= Success; | |||
3494 | if (Success || !Again) | |||
3495 | CurrList[i] = nullptr; | |||
3496 | } | |||
3497 | return Progress; | |||
3498 | } | |||
3499 | ||||
3500 | /// Check if DstReg is a terminal node. | |||
3501 | /// I.e., it does not have any affinity other than \p Copy. | |||
3502 | static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy, | |||
3503 | const MachineRegisterInfo *MRI) { | |||
3504 | assert(Copy.isCopyLike())((Copy.isCopyLike()) ? static_cast<void> (0) : __assert_fail ("Copy.isCopyLike()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3504, __PRETTY_FUNCTION__)); | |||
3505 | // Check if the destination of this copy as any other affinity. | |||
3506 | for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg)) | |||
3507 | if (&MI != &Copy && MI.isCopyLike()) | |||
3508 | return false; | |||
3509 | return true; | |||
3510 | } | |||
3511 | ||||
3512 | bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const { | |||
3513 | assert(Copy.isCopyLike())((Copy.isCopyLike()) ? static_cast<void> (0) : __assert_fail ("Copy.isCopyLike()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3513, __PRETTY_FUNCTION__)); | |||
3514 | if (!UseTerminalRule) | |||
3515 | return false; | |||
3516 | unsigned DstReg, DstSubReg, SrcReg, SrcSubReg; | |||
3517 | isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg); | |||
3518 | // Check if the destination of this copy has any other affinity. | |||
3519 | if (TargetRegisterInfo::isPhysicalRegister(DstReg) || | |||
| ||||
3520 | // If SrcReg is a physical register, the copy won't be coalesced. | |||
3521 | // Ignoring it may have other side effect (like missing | |||
3522 | // rematerialization). So keep it. | |||
3523 | TargetRegisterInfo::isPhysicalRegister(SrcReg) || | |||
3524 | !isTerminalReg(DstReg, Copy, MRI)) | |||
3525 | return false; | |||
3526 | ||||
3527 | // DstReg is a terminal node. Check if it interferes with any other | |||
3528 | // copy involving SrcReg. | |||
3529 | const MachineBasicBlock *OrigBB = Copy.getParent(); | |||
3530 | const LiveInterval &DstLI = LIS->getInterval(DstReg); | |||
3531 | for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) { | |||
3532 | // Technically we should check if the weight of the new copy is | |||
3533 | // interesting compared to the other one and update the weight | |||
3534 | // of the copies accordingly. However, this would only work if | |||
3535 | // we would gather all the copies first then coalesce, whereas | |||
3536 | // right now we interleave both actions. | |||
3537 | // For now, just consider the copies that are in the same block. | |||
3538 | if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB) | |||
3539 | continue; | |||
3540 | unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg; | |||
3541 | isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg, | |||
3542 | OtherSubReg); | |||
3543 | if (OtherReg == SrcReg) | |||
3544 | OtherReg = OtherSrcReg; | |||
3545 | // Check if OtherReg is a non-terminal. | |||
3546 | if (TargetRegisterInfo::isPhysicalRegister(OtherReg) || | |||
3547 | isTerminalReg(OtherReg, MI, MRI)) | |||
3548 | continue; | |||
3549 | // Check that OtherReg interfere with DstReg. | |||
3550 | if (LIS->getInterval(OtherReg).overlaps(DstLI)) { | |||
3551 | LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Apply terminal rule for: " << printReg(DstReg) << '\n'; } } while (false) | |||
3552 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Apply terminal rule for: " << printReg(DstReg) << '\n'; } } while (false); | |||
3553 | return true; | |||
3554 | } | |||
3555 | } | |||
3556 | return false; | |||
3557 | } | |||
3558 | ||||
3559 | void | |||
3560 | RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) { | |||
3561 | LLVM_DEBUG(dbgs() << MBB->getName() << ":\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << MBB->getName() << ":\n" ; } } while (false); | |||
3562 | ||||
3563 | // Collect all copy-like instructions in MBB. Don't start coalescing anything | |||
3564 | // yet, it might invalidate the iterator. | |||
3565 | const unsigned PrevSize = WorkList.size(); | |||
3566 | if (JoinGlobalCopies) { | |||
3567 | SmallVector<MachineInstr*, 2> LocalTerminals; | |||
3568 | SmallVector<MachineInstr*, 2> GlobalTerminals; | |||
3569 | // Coalesce copies bottom-up to coalesce local defs before local uses. They | |||
3570 | // are not inherently easier to resolve, but slightly preferable until we | |||
3571 | // have local live range splitting. In particular this is required by | |||
3572 | // cmp+jmp macro fusion. | |||
3573 | for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); | |||
3574 | MII != E; ++MII) { | |||
3575 | if (!MII->isCopyLike()) | |||
3576 | continue; | |||
3577 | bool ApplyTerminalRule = applyTerminalRule(*MII); | |||
3578 | if (isLocalCopy(&(*MII), LIS)) { | |||
3579 | if (ApplyTerminalRule) | |||
3580 | LocalTerminals.push_back(&(*MII)); | |||
3581 | else | |||
3582 | LocalWorkList.push_back(&(*MII)); | |||
3583 | } else { | |||
3584 | if (ApplyTerminalRule) | |||
3585 | GlobalTerminals.push_back(&(*MII)); | |||
3586 | else | |||
3587 | WorkList.push_back(&(*MII)); | |||
3588 | } | |||
3589 | } | |||
3590 | // Append the copies evicted by the terminal rule at the end of the list. | |||
3591 | LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end()); | |||
3592 | WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end()); | |||
3593 | } | |||
3594 | else { | |||
3595 | SmallVector<MachineInstr*, 2> Terminals; | |||
3596 | for (MachineInstr &MII : *MBB) | |||
3597 | if (MII.isCopyLike()) { | |||
3598 | if (applyTerminalRule(MII)) | |||
3599 | Terminals.push_back(&MII); | |||
3600 | else | |||
3601 | WorkList.push_back(&MII); | |||
3602 | } | |||
3603 | // Append the copies evicted by the terminal rule at the end of the list. | |||
3604 | WorkList.append(Terminals.begin(), Terminals.end()); | |||
3605 | } | |||
3606 | // Try coalescing the collected copies immediately, and remove the nulls. | |||
3607 | // This prevents the WorkList from getting too large since most copies are | |||
3608 | // joinable on the first attempt. | |||
3609 | MutableArrayRef<MachineInstr*> | |||
3610 | CurrList(WorkList.begin() + PrevSize, WorkList.end()); | |||
3611 | if (copyCoalesceWorkList(CurrList)) | |||
3612 | WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(), | |||
3613 | nullptr), WorkList.end()); | |||
3614 | } | |||
3615 | ||||
3616 | void RegisterCoalescer::coalesceLocals() { | |||
3617 | copyCoalesceWorkList(LocalWorkList); | |||
3618 | for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) { | |||
3619 | if (LocalWorkList[j]) | |||
3620 | WorkList.push_back(LocalWorkList[j]); | |||
3621 | } | |||
3622 | LocalWorkList.clear(); | |||
3623 | } | |||
3624 | ||||
3625 | void RegisterCoalescer::joinAllIntervals() { | |||
3626 | LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "********** JOINING INTERVALS ***********\n" ; } } while (false); | |||
3627 | assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.")((WorkList.empty() && LocalWorkList.empty() && "Old data still around.") ? static_cast<void> (0) : __assert_fail ("WorkList.empty() && LocalWorkList.empty() && \"Old data still around.\"" , "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3627, __PRETTY_FUNCTION__)); | |||
3628 | ||||
3629 | std::vector<MBBPriorityInfo> MBBs; | |||
3630 | MBBs.reserve(MF->size()); | |||
3631 | for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) { | |||
3632 | MachineBasicBlock *MBB = &*I; | |||
3633 | MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB), | |||
3634 | JoinSplitEdges && isSplitEdge(MBB))); | |||
3635 | } | |||
3636 | array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority); | |||
3637 | ||||
3638 | // Coalesce intervals in MBB priority order. | |||
3639 | unsigned CurrDepth = std::numeric_limits<unsigned>::max(); | |||
3640 | for (unsigned i = 0, e = MBBs.size(); i != e; ++i) { | |||
3641 | // Try coalescing the collected local copies for deeper loops. | |||
3642 | if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) { | |||
3643 | coalesceLocals(); | |||
3644 | CurrDepth = MBBs[i].Depth; | |||
3645 | } | |||
3646 | copyCoalesceInMBB(MBBs[i].MBB); | |||
3647 | } | |||
3648 | lateLiveIntervalUpdate(); | |||
3649 | coalesceLocals(); | |||
3650 | ||||
3651 | // Joining intervals can allow other intervals to be joined. Iteratively join | |||
3652 | // until we make no progress. | |||
3653 | while (copyCoalesceWorkList(WorkList)) | |||
3654 | /* empty */ ; | |||
3655 | lateLiveIntervalUpdate(); | |||
3656 | } | |||
3657 | ||||
3658 | void RegisterCoalescer::releaseMemory() { | |||
3659 | ErasedInstrs.clear(); | |||
3660 | WorkList.clear(); | |||
3661 | DeadDefs.clear(); | |||
3662 | InflateRegs.clear(); | |||
3663 | LargeLIVisitCounter.clear(); | |||
3664 | } | |||
3665 | ||||
3666 | bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) { | |||
3667 | MF = &fn; | |||
3668 | MRI = &fn.getRegInfo(); | |||
3669 | const TargetSubtargetInfo &STI = fn.getSubtarget(); | |||
3670 | TRI = STI.getRegisterInfo(); | |||
3671 | TII = STI.getInstrInfo(); | |||
3672 | LIS = &getAnalysis<LiveIntervals>(); | |||
3673 | AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); | |||
3674 | Loops = &getAnalysis<MachineLoopInfo>(); | |||
3675 | if (EnableGlobalCopies == cl::BOU_UNSET) | |||
| ||||
3676 | JoinGlobalCopies = STI.enableJoinGlobalCopies(); | |||
3677 | else | |||
3678 | JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE); | |||
3679 | ||||
3680 | // The MachineScheduler does not currently require JoinSplitEdges. This will | |||
3681 | // either be enabled unconditionally or replaced by a more general live range | |||
3682 | // splitting optimization. | |||
3683 | JoinSplitEdges = EnableJoinSplits; | |||
3684 | ||||
3685 | LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" << "********** Function: " << MF->getName() << '\n'; } } while (false) | |||
3686 | << "********** Function: " << MF->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" << "********** Function: " << MF->getName() << '\n'; } } while (false); | |||
3687 | ||||
3688 | if (VerifyCoalescing) | |||
3689 | MF->verify(this, "Before register coalescing"); | |||
3690 | ||||
3691 | RegClassInfo.runOnMachineFunction(fn); | |||
3692 | ||||
3693 | // Join (coalesce) intervals if requested. | |||
3694 | if (EnableJoining) | |||
3695 | joinAllIntervals(); | |||
3696 | ||||
3697 | // After deleting a lot of copies, register classes may be less constrained. | |||
3698 | // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 -> | |||
3699 | // DPR inflation. | |||
3700 | array_pod_sort(InflateRegs.begin(), InflateRegs.end()); | |||
3701 | InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()), | |||
3702 | InflateRegs.end()); | |||
3703 | LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n"; } } while (false) | |||
3704 | << " regs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n"; } } while (false); | |||
3705 | for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) { | |||
3706 | unsigned Reg = InflateRegs[i]; | |||
3707 | if (MRI->reg_nodbg_empty(Reg)) | |||
3708 | continue; | |||
3709 | if (MRI->recomputeRegClass(Reg)) { | |||
3710 | LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << printReg(Reg) << " inflated to " << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n'; } } while (false) | |||
3711 | << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dbgs() << printReg(Reg) << " inflated to " << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n'; } } while (false); | |||
3712 | ++NumInflated; | |||
3713 | ||||
3714 | LiveInterval &LI = LIS->getInterval(Reg); | |||
3715 | if (LI.hasSubRanges()) { | |||
3716 | // If the inflated register class does not support subregisters anymore | |||
3717 | // remove the subranges. | |||
3718 | if (!MRI->shouldTrackSubRegLiveness(Reg)) { | |||
3719 | LI.clearSubRanges(); | |||
3720 | } else { | |||
3721 | #ifndef NDEBUG | |||
3722 | LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); | |||
3723 | // If subranges are still supported, then the same subregs | |||
3724 | // should still be supported. | |||
3725 | for (LiveInterval::SubRange &S : LI.subranges()) { | |||
3726 | assert((S.LaneMask & ~MaxMask).none())(((S.LaneMask & ~MaxMask).none()) ? static_cast<void> (0) : __assert_fail ("(S.LaneMask & ~MaxMask).none()", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/RegisterCoalescer.cpp" , 3726, __PRETTY_FUNCTION__)); | |||
3727 | } | |||
3728 | #endif | |||
3729 | } | |||
3730 | } | |||
3731 | } | |||
3732 | } | |||
3733 | ||||
3734 | LLVM_DEBUG(dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("regalloc")) { dump(); } } while (false); | |||
3735 | if (VerifyCoalescing) | |||
3736 | MF->verify(this, "After register coalescing"); | |||
3737 | return true; | |||
3738 | } | |||
3739 | ||||
3740 | void RegisterCoalescer::print(raw_ostream &O, const Module* m) const { | |||
3741 | LIS->print(O, m); | |||
3742 | } |