1 //===- RegionUtils.cpp - Region-related transformation utilities ----------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 
18 #include "mlir/Transforms/RegionUtils.h"
19 #include "mlir/IR/Block.h"
20 #include "mlir/IR/Operation.h"
21 #include "mlir/IR/Value.h"
22 
23 #include "llvm/ADT/SmallSet.h"
24 
25 using namespace mlir;
26 
27 void mlir::replaceAllUsesInRegionWith(Value *orig, Value *replacement,
28                                       Region &region) {
29   for (IROperand &use : llvm::make_early_inc_range(orig->getUses())) {
30     if (region.isAncestor(use.getOwner()->getParentRegion()))
31       use.set(replacement);
32   }
33 }
34 
35 void mlir::getUsedValuesDefinedAbove(Region &region, Region &limit,
36                                      llvm::SetVector<Value *> &values) {
37   assert(limit.isAncestor(&region) &&
38          "expected isolation limit to be an ancestor of the given region");
39 
40   // Collect proper ancestors of `limit` upfront to avoid traversing the region
41   // tree for every value.
42   llvm::SmallPtrSet<Region *, 4> properAncestors;
43   for (auto *reg = limit.getParentRegion(); reg != nullptr;
44        reg = reg->getParentRegion()) {
45     properAncestors.insert(reg);
46   }
47 
48   region.walk([&values, &properAncestors](Operation *op) {
49     for (Value *operand : op->getOperands())
50       // Collect values that are used by an operation and defined in a proper
51       // ancestor of region.
52       if (properAncestors.count(operand->getParentRegion()))
53         values.insert(operand);
54   });
55 }
56