MLIR 24.0.0git
RemoveDeadValues.cpp
Go to the documentation of this file.
1//===- RemoveDeadValues.cpp - Remove Dead Values --------------------------===//
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// The goal of this pass is optimization (reducing runtime) by removing
10// unnecessary instructions. Unlike other passes that rely on local information
11// gathered from patterns to accomplish optimization, this pass uses a full
12// analysis of the IR, specifically, liveness analysis, and is thus more
13// powerful.
14//
15// Currently, this pass performs the following optimizations:
16// (A) Removes function arguments that are not live,
17// (B) Removes function return values that are not live across all callers of
18// the function,
19// (C) Removes unneccesary operands, results, region arguments, and region
20// terminator operands of region branch ops, and,
21// (D) Removes simple and region branch ops that have all non-live results and
22// don't affect memory in any way.
23//
24// Here, a "simple op" refers to an op that isn't a symbol op, symbol-user op,
25// region branch op, branch op, region branch terminator op, or return-like.
26//
27//===----------------------------------------------------------------------===//
28
32#include "mlir/IR/Builders.h"
34#include "mlir/IR/Dialect.h"
35#include "mlir/IR/Operation.h"
37#include "mlir/IR/SymbolTable.h"
38#include "mlir/IR/Value.h"
39#include "mlir/IR/ValueRange.h"
40#include "mlir/IR/Visitors.h"
45#include "mlir/Pass/Pass.h"
46#include "mlir/Support/LLVM.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/DebugLog.h"
52#include <cassert>
53#include <cstddef>
54#include <memory>
55#include <optional>
56#include <vector>
57
58#define DEBUG_TYPE "remove-dead-values"
59
60namespace mlir {
61#define GEN_PASS_DEF_REMOVEDEADVALUESPASS
62#include "mlir/Transforms/Passes.h.inc"
63} // namespace mlir
64
65using namespace mlir;
66using namespace mlir::dataflow;
67
68//===----------------------------------------------------------------------===//
69// RemoveDeadValues Pass
70//===----------------------------------------------------------------------===//
71
72namespace {
73
74// Set of structures below to be filled with operations and arguments to erase.
75// This is done to separate analysis and tree modification phases,
76// otherwise analysis is operating on half-deleted tree which is incorrect.
77
78struct FunctionToCleanUp {
79 FunctionOpInterface funcOp;
80 BitVector nonLiveArgs;
81 BitVector nonLiveRets;
82};
83
84struct ResultsToCleanup {
85 Operation *op;
86 BitVector nonLive;
87};
88
89struct OperandsToCleanup {
90 Operation *op;
91 BitVector nonLive;
92 // Optional: For CallOpInterface ops, stores the callee function.
93 Operation *callee = nullptr;
94 // Determines whether the operand should be replaced with a ub.poison result
95 // or erased entirely.
96 bool replaceWithPoison = false;
97};
98
99struct BlockArgsToCleanup {
100 Block *b;
101 BitVector nonLiveArgs;
102};
103
104struct SuccessorOperandsToCleanup {
105 BranchOpInterface branch;
106 unsigned successorIndex;
107 BitVector nonLiveOperands;
108};
109
110struct RDVFinalCleanupList {
111 SmallVector<Operation *> operations;
112 SmallVector<FunctionToCleanUp> functions;
113 SmallVector<OperandsToCleanup> operands;
114 SmallVector<ResultsToCleanup> results;
115 SmallVector<BlockArgsToCleanup> blocks;
116 SmallVector<SuccessorOperandsToCleanup> successorOperands;
117};
118
119// Some helper functions...
120
121/// Return true iff at least one value in `values` is live, given the liveness
122/// information in `la`.
123static bool hasLive(ValueRange values, const DenseSet<Value> &nonLiveSet,
125 for (Value value : values) {
126 if (nonLiveSet.contains(value)) {
127 LDBG() << "Value " << value << " is already marked non-live (dead)";
128 continue;
129 }
130
131 const Liveness *liveness = la.getLiveness(value);
132 if (!liveness) {
133 LDBG() << "Value " << value
134 << " has no liveness info, conservatively considered live";
135 return true;
136 }
137 if (liveness->isLive) {
138 LDBG() << "Value " << value << " is live according to liveness analysis";
139 return true;
140 }
141 LDBG() << "Value " << value << " is dead according to liveness analysis";
142 }
143 return false;
144}
145
146/// Return a BitVector of size `values.size()` where its i-th bit is 1 iff the
147/// i-th value in `values` is live, given the liveness information in `la`.
148static BitVector markLives(ValueRange values, const DenseSet<Value> &nonLiveSet,
150 BitVector lives(values.size(), true);
151
152 for (auto [index, value] : llvm::enumerate(values)) {
153 if (nonLiveSet.contains(value)) {
154 lives.reset(index);
155 LDBG() << "Value " << value
156 << " is already marked non-live (dead) at index " << index;
157 continue;
158 }
159
160 const Liveness *liveness = la.getLiveness(value);
161 // It is important to note that when `liveness` is null, we can't tell if
162 // `value` is live or not. So, the safe option is to consider it live. Also,
163 // the execution of this pass might create new SSA values when erasing some
164 // of the results of an op and we know that these new values are live
165 // (because they weren't erased) and also their liveness is null because
166 // liveness analysis ran before their creation.
167 if (!liveness) {
168 LDBG() << "Value " << value << " at index " << index
169 << " has no liveness info, conservatively considered live";
170 continue;
171 }
172 if (!liveness->isLive) {
173 lives.reset(index);
174 LDBG() << "Value " << value << " at index " << index
175 << " is dead according to liveness analysis";
176 } else {
177 LDBG() << "Value " << value << " at index " << index
178 << " is live according to liveness analysis";
179 }
180 }
181
182 return lives;
183}
184
185/// Collects values marked as "non-live" in the provided range and inserts them
186/// into the nonLiveSet. A value is considered "non-live" if the corresponding
187/// index in the `nonLive` bit vector is set.
188static void collectNonLiveValues(DenseSet<Value> &nonLiveSet, ValueRange range,
189 const BitVector &nonLive) {
190 for (auto [index, result] : llvm::enumerate(range)) {
191 if (!nonLive[index])
192 continue;
193 nonLiveSet.insert(result);
194 LDBG() << "Marking value " << result << " as non-live (dead) at index "
195 << index;
196 }
197}
198
199/// Drop the uses of the i-th result of `op` and then erase it iff toErase[i]
200/// is 1.
201static void dropUsesAndEraseResults(RewriterBase &rewriter, Operation *op,
202 BitVector toErase) {
203 assert(op->getNumResults() == toErase.size() &&
204 "expected the number of results in `op` and the size of `toErase` to "
205 "be the same");
206 for (auto idx : toErase.set_bits())
207 op->getResult(idx).dropAllUses();
208 rewriter.eraseOpResults(op, toErase);
209}
210
211/// Process a simple operation `op` using the liveness analysis `la`.
212/// If the operation has no memory effects and none of its results are live:
213/// 1. Add the operation to a list for future removal, and
214/// 2. Mark all its results as non-live values
215///
216/// The operation `op` is assumed to be simple. A simple operation is one that
217/// is NOT:
218/// - Function-like
219/// - Call-like
220/// - A region branch operation
221/// - A branch operation
222/// - A region branch terminator
223/// - Return-like
224static void processSimpleOp(Operation *op, RunLivenessAnalysis &la,
225 DenseSet<Value> &nonLiveSet,
226 RDVFinalCleanupList &cl) {
227 // Operations that have dead operands can be erased regardless of their
228 // side effects. The liveness analysis would not have marked an SSA value as
229 // "dead" if it had a side-effecting user that is reachable.
230 bool hasDeadOperand =
231 markLives(op->getOperands(), nonLiveSet, la).flip().any();
232 if (hasDeadOperand) {
233 LDBG() << "Simple op has dead operands, so the op must be dead: "
234 << OpWithFlags(op,
235 OpPrintingFlags().skipRegions().printGenericOpForm());
236 assert(!hasLive(op->getResults(), nonLiveSet, la) &&
237 "expected the op to have no live results");
238 cl.operations.push_back(op);
239 collectNonLiveValues(nonLiveSet, op->getResults(),
240 BitVector(op->getNumResults(), true));
241 return;
242 }
243
244 if (!isMemoryEffectFree(op) || hasLive(op->getResults(), nonLiveSet, la)) {
245 LDBG() << "Simple op is not memory effect free or has live results, "
246 "preserving it: "
247 << OpWithFlags(op,
248 OpPrintingFlags().skipRegions().printGenericOpForm());
249 return;
250 }
251
252 LDBG()
253 << "Simple op has all dead results and is memory effect free, scheduling "
254 "for removal: "
255 << OpWithFlags(op, OpPrintingFlags().skipRegions().printGenericOpForm());
256 cl.operations.push_back(op);
257 collectNonLiveValues(nonLiveSet, op->getResults(),
258 BitVector(op->getNumResults(), true));
259}
260
261/// Process a function-like operation `funcOp` using the liveness analysis `la`
262/// and `symbolUserMap`. If it is not public or external:
263/// (1) Adding its non-live arguments to a list for future removal.
264/// (2) Marking their corresponding operands in its callers for removal.
265/// (3) Identifying and enqueueing unnecessary terminator operands
266/// (return values that are non-live across all callers) for removal.
267/// (4) Enqueueing the non-live arguments and return values for removal.
268/// (5) Collecting the uses of these return values in its callers for future
269/// removal.
270/// (6) Marking all its results as non-live values.
271static void processFuncOp(FunctionOpInterface funcOp,
272 const SymbolUserMap &symbolUserMap,
273 RunLivenessAnalysis &la, DenseSet<Value> &nonLiveSet,
274 RDVFinalCleanupList &cl) {
275 LDBG() << "Processing function op: "
276 << OpWithFlags(funcOp,
277 OpPrintingFlags().skipRegions().printGenericOpForm());
278 if (funcOp.isPublic() || funcOp.isExternal()) {
279 LDBG() << "Function is public or external, skipping: "
280 << funcOp.getOperation()->getName();
281 return;
282 }
283 ArrayRef<Operation *> users = symbolUserMap.getUsers(funcOp);
284 if (!llvm::all_of(users, llvm::IsaPred<CallOpInterface>)) {
285 // If a non-call operation references the function (e.g. spirv.EntryPoint),
286 // we cannot safely remove arguments or return values since we don't know
287 // what the user expects. Skip this function entirely.
288 return;
289 }
290 // Get the list of unnecessary (non-live) arguments in `nonLiveArgs`.
291 SmallVector<Value> arguments(funcOp.getArguments());
292 BitVector nonLiveArgs = markLives(arguments, nonLiveSet, la);
293 nonLiveArgs = nonLiveArgs.flip();
294
295 // Do (1).
296 for (auto [index, arg] : llvm::enumerate(arguments))
297 if (arg && nonLiveArgs[index])
298 nonLiveSet.insert(arg);
299
300 // Do (2). (Skip creating generic operand cleanup entries for call ops.
301 // Call arguments will be removed in the call-site specific segment-aware
302 // cleanup, avoiding generic eraseOperands bitvector mechanics.)
303 for (Operation *callOp : users) {
304 // Push an empty operand cleanup entry so that call-site specific logic in
305 // cleanUpDeadVals runs (it keys off CallOpInterface). The BitVector is
306 // intentionally all false to avoid generic erasure.
307 // Store the funcOp as the callee to avoid expensive symbol lookup later.
308 cl.operands.push_back({callOp, BitVector(callOp->getNumOperands(), false),
309 funcOp.getOperation()});
310 }
311
312 // Do (3).
313 // Get the list of unnecessary terminator operands (return values that are
314 // non-live across all callers) in `nonLiveRets`. There is a very important
315 // subtlety here. Unnecessary terminator operands are NOT the operands of the
316 // terminator that are non-live. Instead, these are the return values of the
317 // callers such that a given return value is non-live across all callers. Such
318 // corresponding operands in the terminator could be live. An example to
319 // demonstrate this:
320 // func.func private @f(%arg0: memref<i32>) -> (i32, i32) {
321 // %c0_i32 = arith.constant 0 : i32
322 // %0 = arith.addi %c0_i32, %c0_i32 : i32
323 // memref.store %0, %arg0[] : memref<i32>
324 // return %c0_i32, %0 : i32, i32
325 // }
326 // func.func @main(%arg0: i32, %arg1: memref<i32>) -> (i32) {
327 // %1:2 = call @f(%arg1) : (memref<i32>) -> i32
328 // return %1#0 : i32
329 // }
330 // Here, we can see that %1#1 is never used. It is non-live. Thus, @f doesn't
331 // need to return %0. But, %0 is live. And, still, we want to stop it from
332 // being returned, in order to optimize our IR. So, this demonstrates how we
333 // can make our optimization strong by even removing a live return value (%0),
334 // since it forwards only to non-live value(s) (%1#1).
335 size_t numReturns = funcOp.getNumResults();
336 BitVector nonLiveRets(numReturns, true);
337 for (Operation *callOp : users) {
338 // Only the forwarded results of a call receive the values returned by the
339 // callee; any other result is produced by the call operation itself.
340 BitVector liveCallRets = markLives(
341 cast<CallOpInterface>(callOp).getForwardedResults(), nonLiveSet, la);
342 nonLiveRets &= liveCallRets.flip();
343 }
344
345 // Note that in the absence of control flow ops forcing the control to go from
346 // the entry (first) block to the other blocks, the control never reaches any
347 // block other than the entry block, because every block has a terminator.
348 for (Block &block : funcOp.getBlocks()) {
349 Operation *returnOp = block.getTerminator();
350 if (!returnOp->hasTrait<OpTrait::ReturnLike>())
351 continue;
352 if (returnOp && returnOp->getNumOperands() == numReturns)
353 cl.operands.push_back({returnOp, nonLiveRets});
354 }
355
356 // Do (4).
357 cl.functions.push_back({funcOp, nonLiveArgs, nonLiveRets});
358
359 // Do (5) and (6).
360 if (numReturns == 0)
361 return;
362 for (Operation *callOp : users) {
363 // `nonLiveRets` is indexed by callee result. Translate it into the index
364 // space of all results of the call operation, which is what the cleanup
365 // works on.
366 ResultRange forwardedResults =
367 cast<CallOpInterface>(callOp).getForwardedResults();
368 BitVector nonLiveCallResults(callOp->getNumResults(), false);
369 for (int index : nonLiveRets.set_bits())
370 nonLiveCallResults.set(forwardedResults[index].getResultNumber());
371 cl.results.push_back({callOp, nonLiveCallResults});
372 collectNonLiveValues(nonLiveSet, callOp->getResults(), nonLiveCallResults);
373 }
374}
375
376/// Process a region branch operation `regionBranchOp` using the liveness
377/// information in `la`. The processing involves two scenarios:
378///
379/// Scenario 1: If the operation has no memory effects and none of its results
380/// are live:
381/// 1.1. Enqueue all its uses for deletion.
382/// 1.2. Enqueue the branch itself for deletion.
383///
384/// Scenario 2: Otherwise:
385/// 2.1. Find all operands that are forwarded to only dead region successor
386/// inputs. I.e., forwarded to block arguments / op results that we do
387/// not want to keep.
388/// 2.2. Also find operands who's values are dead (i.e., are scheduled for
389/// erasure) due to other operations.
390/// 2.3. Enqueue all such operands for replacement with ub.poison.
391///
392/// Note: In scenario 2, block arguments and op results are not removed.
393/// However, the IR is simplified such that canonicalization patterns can
394/// remove them later.
395static void processRegionBranchOp(RegionBranchOpInterface regionBranchOp,
397 DenseSet<Value> &nonLiveSet,
398 RDVFinalCleanupList &cl) {
399 LDBG() << "Processing region branch op: "
400 << OpWithFlags(regionBranchOp,
401 OpPrintingFlags().skipRegions().printGenericOpForm());
402
403 // Scenario 1. This is the only case where the entire `regionBranchOp`
404 // is removed. It will not happen in any other scenario. Note that in this
405 // case, a non-forwarded operand of `regionBranchOp` could be live/non-live.
406 // It could never be live because of this op but its liveness could have been
407 // attributed to something else.
408 if (isMemoryEffectFree(regionBranchOp.getOperation()) &&
409 !hasLive(regionBranchOp->getResults(), nonLiveSet, la)) {
410 cl.operations.push_back(regionBranchOp.getOperation());
411 return;
412 }
413
414 // Mapping from operands to forwarded successor inputs. An operand can be
415 // forwarded to multiple successors.
416 //
417 // Example:
418 //
419 // %0 = scf.while : () -> i32 {
420 // scf.condition(...) %forwarded_value : i32
421 // } do {
422 // ^bb0(%arg0: i32):
423 // scf.yield
424 // }
425 // // No uses of %0.
426 //
427 // In the above example, %forwarded_value is forwarded to %arg0 and %0. Both
428 // %arg0 and %0 are dead, so %forwarded_value can be replaced with a
429 // ub.poison result.
430 //
431 // operandToSuccessorInputs[%forwarded_value] = {%arg0, %0}
432 //
433 RegionBranchSuccessorMapping operandToSuccessorInputs;
434 regionBranchOp.getSuccessorOperandInputMapping(operandToSuccessorInputs);
435
436 DenseMap<Operation *, BitVector> deadOperandsPerOp;
437 for (auto [opOperand, successorInputs] : operandToSuccessorInputs) {
438 // Helper function to mark the operand as dead, to be replaced with a
439 // ub.poison result.
440 auto markOperandDead = [&opOperand = opOperand, &deadOperandsPerOp]() {
441 // Create an entry in `deadOperandsPerOp` (initialized to "false", i.e.,
442 // no "dead" op operands) if it's the first time that we are seeing an op
443 // operand for this op. Otherwise, just take the existing bit vector from
444 // the map.
445 BitVector &deadOperands =
446 deadOperandsPerOp
447 .try_emplace(opOperand->getOwner(),
448 opOperand->getOwner()->getNumOperands(), false)
449 .first->second;
450 deadOperands.set(opOperand->getOperandNumber());
451 };
452
453 // The operand value is scheduled for removal. Mark it as dead.
454 if (!hasLive(opOperand->get(), nonLiveSet, la)) {
455 markOperandDead();
456 continue;
457 }
458
459 // If one of the successor inputs is live, the respective operand must be
460 // kept. Otherwise, ub.poison can be passed as operand.
461 if (!hasLive(successorInputs, nonLiveSet, la))
462 markOperandDead();
463 }
464
465 for (auto [op, deadOperands] : deadOperandsPerOp) {
466 cl.operands.push_back(
467 {op, deadOperands, nullptr, /*replaceWithPoison=*/true});
468 }
469}
470
471/// Steps to process a `BranchOpInterface` operation:
472///
473/// When a non-forwarded operand is dead (e.g., the condition value of a
474/// conditional branch op), the entire operation is dead.
475///
476/// Otherwise, iterate through each successor block of `branchOp`.
477/// (1) For each successor block, gather all operands from all successors.
478/// (2) Fetch their associated liveness analysis data and collect for future
479/// removal.
480/// (3) Identify and collect the dead operands from the successor block
481/// as well as their corresponding arguments.
482
483static void processBranchOp(BranchOpInterface branchOp, RunLivenessAnalysis &la,
484 DenseSet<Value> &nonLiveSet,
485 RDVFinalCleanupList &cl) {
486 LDBG() << "Processing branch op: " << *branchOp;
487
488 // Check for dead non-forwarded operands.
489 BitVector deadNonForwardedOperands =
490 markLives(branchOp->getOperands(), nonLiveSet, la).flip();
491 unsigned numSuccessors = branchOp->getNumSuccessors();
492 for (unsigned succIdx = 0; succIdx < numSuccessors; ++succIdx) {
493 SuccessorOperands successorOperands =
494 branchOp.getSuccessorOperands(succIdx);
495 // Remove all non-forwarded operands from the bit vector.
496 for (OpOperand &opOperand : successorOperands.getMutableForwardedOperands())
497 deadNonForwardedOperands[opOperand.getOperandNumber()] = false;
498 }
499 if (deadNonForwardedOperands.any()) {
500 cl.operations.push_back(branchOp.getOperation());
501 return;
502 }
503
504 for (unsigned succIdx = 0; succIdx < numSuccessors; ++succIdx) {
505 Block *successorBlock = branchOp->getSuccessor(succIdx);
506
507 // Do (1)
508 SuccessorOperands successorOperands =
509 branchOp.getSuccessorOperands(succIdx);
510 SmallVector<Value> operandValues;
511 for (unsigned operandIdx = 0; operandIdx < successorOperands.size();
512 ++operandIdx) {
513 operandValues.push_back(successorOperands[operandIdx]);
514 }
515
516 // Do (2)
517 BitVector successorNonLive =
518 markLives(operandValues, nonLiveSet, la).flip();
519 collectNonLiveValues(nonLiveSet, successorBlock->getArguments(),
520 successorNonLive);
521
522 // Do (3)
523 cl.blocks.push_back({successorBlock, successorNonLive});
524 cl.successorOperands.push_back({branchOp, succIdx, successorNonLive});
525 }
526}
527
528/// Create a ub.poison op for the given value. If it has no uses, return an
529/// "empty" value.
530static Value createPoisonedValue(OpBuilder &b, Value value) {
531 if (value.use_empty())
532 return Value();
533 return ub::PoisonOp::create(b, value.getLoc(), value.getType()).getResult();
534}
535
536namespace {
537/// A listener that keeps track of ub.poison ops.
538struct TrackingListener : public RewriterBase::Listener {
539 void notifyOperationErased(Operation *op) override {
540 if (auto poisonOp = dyn_cast<ub::PoisonOp>(op))
541 poisonOps.erase(poisonOp);
542 }
543 void notifyOperationInserted(Operation *op,
544 OpBuilder::InsertPoint previous) override {
545 if (auto poisonOp = dyn_cast<ub::PoisonOp>(op))
546 poisonOps.insert(poisonOp);
547 }
548 DenseSet<ub::PoisonOp> poisonOps;
549};
550} // namespace
551
552/// Removes dead values collected in RDVFinalCleanupList.
553/// To be run once when all dead values have been collected.
554static void cleanUpDeadVals(MLIRContext *ctx, RDVFinalCleanupList &list) {
555 LDBG() << "Starting cleanup of dead values...";
556
557 // New ub.poison ops may be inserted during cleanup. Some of these ops may no
558 // longer be needed after the cleanup. A tracking listener keeps track of all
559 // new ub.poison ops, so that they can be removed again after the cleanup.
560 TrackingListener listener;
561 IRRewriter rewriter(ctx, &listener);
562
563 // 1. Operands to replace with poison. These rewrites need the original
564 // operand values for their location and type, so they must run before any
565 // cleanup that can drop uses and leave operands temporarily null.
566 LDBG() << "Replacing dead operands with poison in " << list.operands.size()
567 << " operand lists";
568 for (OperandsToCleanup &o : list.operands) {
569 if (!o.replaceWithPoison || !o.nonLive.any())
570 continue;
571 LDBG_OS([&](raw_ostream &os) {
572 os << "Replacing non-live operands [";
573 llvm::interleaveComma(o.nonLive.set_bits(), os);
574 os << "] with poison in operation: "
575 << OpWithFlags(o.op,
576 OpPrintingFlags().skipRegions().printGenericOpForm());
577 });
578 rewriter.setInsertionPoint(o.op);
579 for (auto deadIdx : o.nonLive.set_bits()) {
580 Value operand = o.op->getOperand(deadIdx);
581 assert(operand && "expected non-null operand for poison replacement");
582 o.op->setOperand(deadIdx, createPoisonedValue(rewriter, operand));
583 }
584 }
585
586 // 2. Blocks, We must remove the block arguments and successor operands before
587 // deleting the operation, as they may reside in the region operation.
588 LDBG() << "Cleaning up " << list.blocks.size() << " block argument lists";
589 for (auto &b : list.blocks) {
590 // blocks that are accessed via multiple codepaths processed once
591 if (b.b->getNumArguments() != b.nonLiveArgs.size())
592 continue;
593 LDBG_OS([&](raw_ostream &os) {
594 os << "Erasing non-live arguments [";
595 llvm::interleaveComma(b.nonLiveArgs.set_bits(), os);
596 os << "] from block #" << b.b->computeBlockNumber() << " in region #"
597 << b.b->getParent()->getRegionNumber() << " of operation "
598 << OpWithFlags(b.b->getParent()->getParentOp(),
599 OpPrintingFlags().skipRegions().printGenericOpForm());
600 });
601 // Note: Iterate from the end to make sure that that indices of not yet
602 // processes arguments do not change.
603 for (int i = b.nonLiveArgs.size() - 1; i >= 0; --i) {
604 if (!b.nonLiveArgs[i])
605 continue;
606 b.b->getArgument(i).dropAllUses();
607 b.b->eraseArgument(i);
608 }
609 }
610
611 // 3. Successor Operands
612 LDBG() << "Cleaning up " << list.successorOperands.size()
613 << " successor operand lists";
614 for (auto &op : list.successorOperands) {
615 SuccessorOperands successorOperands =
616 op.branch.getSuccessorOperands(op.successorIndex);
617 // blocks that are accessed via multiple codepaths processed once
618 if (successorOperands.size() != op.nonLiveOperands.size())
619 continue;
620 LDBG_OS([&](raw_ostream &os) {
621 os << "Erasing non-live successor operands [";
622 llvm::interleaveComma(op.nonLiveOperands.set_bits(), os);
623 os << "] from successor " << op.successorIndex << " of branch: "
624 << OpWithFlags(op.branch.getOperation(),
625 OpPrintingFlags().skipRegions().printGenericOpForm());
626 });
627 // it iterates backwards because erase invalidates all successor indexes
628 for (int i = successorOperands.size() - 1; i >= 0; --i) {
629 if (!op.nonLiveOperands[i])
630 continue;
631 successorOperands.erase(i);
632 }
633 }
634
635 // 4. Functions
636 LDBG() << "Cleaning up " << list.functions.size() << " functions";
637 // Record which function arguments were erased so we can shrink call-site
638 // argument segments for CallOpInterface operations (e.g. ops using
639 // AttrSizedOperandSegments) in the next phase.
641 for (auto &f : list.functions) {
642 LDBG() << "Cleaning up function: " << f.funcOp.getName() << " ("
643 << f.funcOp.getOperation() << ")";
644 LDBG_OS([&](raw_ostream &os) {
645 os << " Erasing non-live arguments [";
646 llvm::interleaveComma(f.nonLiveArgs.set_bits(), os);
647 os << "]\n";
648 os << " Erasing non-live return values [";
649 llvm::interleaveComma(f.nonLiveRets.set_bits(), os);
650 os << "]";
651 });
652 // Drop all uses of the dead arguments.
653 for (auto deadIdx : f.nonLiveArgs.set_bits())
654 f.funcOp.getArgument(deadIdx).dropAllUses();
655 // Some functions may not allow erasing arguments or results. These calls
656 // return failure in such cases without modifying the function, so it's okay
657 // to proceed.
658 if (succeeded(f.funcOp.eraseArguments(f.nonLiveArgs))) {
659 // Record only if we actually erased something.
660 if (f.nonLiveArgs.any())
661 erasedFuncArgs.try_emplace(f.funcOp.getOperation(), f.nonLiveArgs);
662 } else {
663 LDBG() << "Failed to erase arguments for function: "
664 << f.funcOp.getName();
665 }
666 (void)f.funcOp.eraseResults(f.nonLiveRets);
667 }
668
669 // 5. Operands
670 LDBG() << "Cleaning up " << list.operands.size() << " operand lists";
671 for (OperandsToCleanup &o : list.operands) {
672 if (o.replaceWithPoison)
673 continue;
674 // Handle call-specific cleanup only when we have a cached callee reference.
675 // This avoids expensive symbol lookup and is defensive against future
676 // changes.
677 bool handledAsCall = false;
678 if (o.callee && isa<CallOpInterface>(o.op)) {
679 auto call = cast<CallOpInterface>(o.op);
680 auto it = erasedFuncArgs.find(o.callee);
681 if (it != erasedFuncArgs.end()) {
682 const BitVector &deadArgIdxs = it->second;
683 MutableOperandRange args = call.getArgOperandsMutable();
684 // First, erase the call arguments corresponding to erased callee
685 // args. We iterate backwards to preserve indices.
686 for (unsigned argIdx : llvm::reverse(deadArgIdxs.set_bits()))
687 args.erase(argIdx);
688 // If this operand cleanup entry also has a generic nonLive bitvector,
689 // clear bits for call arguments we already erased above to avoid
690 // double-erasing (which could impact other segments of ops with
691 // AttrSizedOperandSegments).
692 if (o.nonLive.any()) {
693 // Map the argument logical index to the operand number(s) recorded.
694 int operandOffset = call.getArgOperands().getBeginOperandIndex();
695 for (int argIdx : deadArgIdxs.set_bits()) {
696 int operandNumber = operandOffset + argIdx;
697 if (operandNumber < static_cast<int>(o.nonLive.size()))
698 o.nonLive.reset(operandNumber);
699 }
700 }
701 handledAsCall = true;
702 }
703 }
704 // Perform generic operand erasure for:
705 // - Non-call operations
706 // - Call operations without cached callee (where handledAsCall is false)
707 // But skip call operations that were already handled via segment-aware path
708 if (!handledAsCall && o.nonLive.any()) {
709 LDBG_OS([&](raw_ostream &os) {
710 os << "Erasing non-live operands [";
711 llvm::interleaveComma(o.nonLive.set_bits(), os);
712 os << "] from operation: "
713 << OpWithFlags(o.op,
714 OpPrintingFlags().skipRegions().printGenericOpForm());
715 });
716 o.op->eraseOperands(o.nonLive);
717 }
718 }
719
720 // 6. Results
721 LDBG() << "Cleaning up " << list.results.size() << " result lists";
722 for (auto &r : list.results) {
723 LDBG_OS([&](raw_ostream &os) {
724 os << "Erasing non-live results [";
725 llvm::interleaveComma(r.nonLive.set_bits(), os);
726 os << "] from operation: "
727 << OpWithFlags(r.op,
728 OpPrintingFlags().skipRegions().printGenericOpForm());
729 });
730 dropUsesAndEraseResults(rewriter, r.op, r.nonLive);
731 }
732
733 // 7. Operations
734 LDBG() << "Cleaning up " << list.operations.size() << " operations";
735 for (Operation *op : list.operations) {
736 LDBG() << "Erasing operation: "
737 << OpWithFlags(op,
738 OpPrintingFlags().skipRegions().printGenericOpForm());
739 rewriter.setInsertionPoint(op);
740 if (op->hasTrait<OpTrait::IsTerminator>()) {
741 // When erasing a terminator, insert an unreachable op in its place.
742 ub::UnreachableOp::create(rewriter, op->getLoc());
743 }
744
745 // Before erasing the operation, replace all result values with live-uses by
746 // ub.poison values. This is important to maintain IR validity. For example,
747 // if we have an op with one of its results used by another op, erasing the
748 // op without replacing its corresponding result would leave us with a
749 // dangling operand in the user op. By replacing the result with a ub.poison
750 // value, we ensure that the user op still has a valid operand, even though
751 // it's a poison value which will be cleaned up later if it can be cleaned
752 // up. This keeps the IR valid for further simplification and
753 // canonicalization.
754 auto opResults = op->getResults();
755 for (Value opResult : opResults) {
756 // Early continue for the case where the op result has no uses. No need to
757 // create a poison op here.
758 if (opResult.use_empty())
759 continue;
760
761 rewriter.setInsertionPoint(op);
762 Value poisonedValue = createPoisonedValue(rewriter, opResult);
763 rewriter.replaceAllUsesWith(opResult, poisonedValue);
764 }
765
766 op->dropAllUses();
767 rewriter.eraseOp(op);
768 }
769
770 // 8. Remove all dead poison ops.
771 for (ub::PoisonOp poisonOp : listener.poisonOps) {
772 if (poisonOp.use_empty())
773 poisonOp.erase();
774 }
775
776 LDBG() << "Finished cleanup of dead values";
777}
778
779struct RemoveDeadValues
780 : public impl::RemoveDeadValuesPassBase<RemoveDeadValues> {
781 using impl::RemoveDeadValuesPassBase<
782 RemoveDeadValues>::RemoveDeadValuesPassBase;
783 void runOnOperation() override;
784};
785} // namespace
786
787void RemoveDeadValues::runOnOperation() {
788 auto &la = getAnalysis<RunLivenessAnalysis>();
789 Operation *module = getOperation();
790
791 // Build a symbol user map once up front so that processFuncOp can look up the
792 // callers of each function in O(1). Otherwise, each call would walk the
793 // entire module to find the callers, making the pass O(numFunctions *
794 // numOperations).
795 SymbolTableCollection symbolTableCollection;
796 SymbolUserMap symbolUserMap(symbolTableCollection, module);
797
798 // Tracks values eligible for erasure - complements liveness analysis to
799 // identify "droppable" values.
800 DenseSet<Value> deadVals;
801
802 // Maintains a list of Ops, values, branches, etc., slated for cleanup at the
803 // end of this pass.
804 RDVFinalCleanupList finalCleanupList;
805
806 module->walk([&](Operation *op) {
807 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
808 processFuncOp(funcOp, symbolUserMap, la, deadVals, finalCleanupList);
809 } else if (auto regionBranchOp = dyn_cast<RegionBranchOpInterface>(op)) {
810 processRegionBranchOp(regionBranchOp, la, deadVals, finalCleanupList);
811 } else if (auto branchOp = dyn_cast<BranchOpInterface>(op)) {
812 processBranchOp(branchOp, la, deadVals, finalCleanupList);
813 } else if (op->hasTrait<::mlir::OpTrait::IsTerminator>()) {
814 // Nothing to do here because this is a terminator op and it should be
815 // honored with respect to its parent
816 } else if (isa<CallOpInterface>(op)) {
817 // Nothing to do because this op is associated with a function op and gets
818 // cleaned when the latter is cleaned.
819 } else {
820 processSimpleOp(op, la, deadVals, finalCleanupList);
821 }
822 });
823
824 MLIRContext *context = module->getContext();
825 cleanUpDeadVals(context, finalCleanupList);
826
827 if (!canonicalize)
828 return;
829
830 // Canonicalize all region branch ops.
831 SmallVector<Operation *> opsToCanonicalize;
832 module->walk([&](RegionBranchOpInterface regionBranchOp) {
833 opsToCanonicalize.push_back(regionBranchOp.getOperation());
834 });
835 // Collect all canonicalization patterns for region branch ops.
836 RewritePatternSet owningPatterns(context);
837 DenseSet<RegisteredOperationName> populatedPatterns;
838 for (Operation *op : opsToCanonicalize)
839 if (std::optional<RegisteredOperationName> info = op->getRegisteredInfo())
840 if (populatedPatterns.insert(*info).second)
841 info->getCanonicalizationPatterns(owningPatterns, context);
842 if (failed(applyOpPatternsGreedily(opsToCanonicalize,
843 std::move(owningPatterns)))) {
844 module->emitError("greedy pattern rewrite failed to converge");
845 signalPassFailure();
846 }
847}
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Block represents an ordered list of Operations.
Definition Block.h:33
BlockArgListType getArguments()
Definition Block.h:111
Block * getSuccessor(unsigned i)
Definition Block.cpp:274
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
This class provides a mutable adaptor for a range of operands.
Definition ValueRange.h:119
void erase(unsigned subStart, unsigned subLen=1)
Erase the operands within the given sub-range.
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
This class represents an operand of an operation.
Definition Value.h:254
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1162
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:794
void dropAllUses()
Drop all uses of results of this operation.
Definition Operation.h:879
void setOperand(unsigned idx, Value value)
Definition Operation.h:376
void eraseOperands(unsigned idx, unsigned length=1)
Erase the operands starting at position idx and ending at position 'idx'+'length'.
Definition Operation.h:385
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:432
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
std::optional< RegisteredOperationName > getRegisteredInfo()
If this operation has a registered operation description, return it.
Definition Operation.h:119
unsigned getNumOperands()
Definition Operation.h:371
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:403
result_range getResults()
Definition Operation.h:440
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:429
This class implements the result iterators for the Operation class.
Definition ValueRange.h:248
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Operation * eraseOpResults(Operation *op, const BitVector &eraseIndices)
Erase the specified results of the given operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class models how operands are forwarded to block arguments in control flow.
void erase(unsigned subStart, unsigned subLen=1)
Erase operands forwarded to the successor.
MutableOperandRange getMutableForwardedOperands() const
Get the range of operands that are simply forwarded to the successor.
unsigned size() const
Returns the amount of operands passed to the successor.
This class represents a map of symbols to users, and provides efficient implementations of symbol que...
ArrayRef< Operation * > getUsers(Operation *symbol) const
Return the users of the provided symbol operation.
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
void dropAllUses()
Drop all uses of this object from their respective owners.
Definition Value.h:144
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
DenseMap< OpOperand *, SmallVector< Value > > RegionBranchSuccessorMapping
A mapping from successor operands to successor inputs.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:122
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120
This trait indicates that a terminator operation is "return-like".
This lattice represents, for a given value, whether or not it is "live".
Runs liveness analysis on the IR defined by op.
const Liveness * getLiveness(Value val)