Skip to content

Commit

Permalink
[ADT][mlir][NFCI] Do not use non-const lvalue-refs with enumerate
Browse files Browse the repository at this point in the history
Replace references to enumerate results with either result_pairs
(reference wrapper type) or structured bindings. I did not use
structured bindings everywhere as it wasn't clear to me it would
improve readability.

This is in preparation to the switch to zip semantics which won't
support non-const lvalue reference to elements:
https://reviews.llvm.org/D144503.

I chose to use values instead of const lvalue-refs because MLIR is
biased towards avoiding `const` local variables. This won't degrade
performance because currently `result_pair` is cheap to copy (size_t
+ iterator), and in the future, the enumerator iterator dereference
will return temporaries anyway.

Reviewed By: dblaikie

Differential Revision: https://reviews.llvm.org/D146006
  • Loading branch information
kuhar committed Mar 15, 2023
1 parent bc47a19 commit 8c258fd
Show file tree
Hide file tree
Showing 31 changed files with 92 additions and 93 deletions.
8 changes: 4 additions & 4 deletions mlir/lib/Analysis/DataFlow/SparseAnalysis.cpp
Expand Up @@ -191,13 +191,13 @@ void AbstractSparseDataFlowAnalysis::visitBlock(Block *block) {
dyn_cast<BranchOpInterface>(predecessor->getTerminator())) {
SuccessorOperands operands =
branch.getSuccessorOperands(it.getSuccessorIndex());
for (auto &it : llvm::enumerate(argLattices)) {
if (Value operand = operands[it.index()]) {
join(it.value(), *getLatticeElementFor(block, operand));
for (auto [idx, lattice] : llvm::enumerate(argLattices)) {
if (Value operand = operands[idx]) {
join(lattice, *getLatticeElementFor(block, operand));
} else {
// Conservatively consider internally produced arguments as entry
// points.
setAllToEntryStates(it.value());
setAllToEntryStates(lattice);
}
}
} else {
Expand Down
10 changes: 5 additions & 5 deletions mlir/lib/Bytecode/Writer/IRNumbering.cpp
Expand Up @@ -98,8 +98,8 @@ static void groupByDialectPerByte(T range) {
}

// Assign the entry numbers based on the sort order.
for (auto &entry : llvm::enumerate(range))
entry.value()->number = entry.index();
for (auto [idx, value] : llvm::enumerate(range))
value->number = idx;
}

IRNumberingState::IRNumberingState(Operation *op) {
Expand Down Expand Up @@ -132,8 +132,8 @@ IRNumberingState::IRNumberingState(Operation *op) {
// found, given that the number of dialects on average is small enough to fit
// within a singly byte (128). If we ever have real world use cases that have
// a huge number of dialects, this could be made more intelligent.
for (auto &it : llvm::enumerate(dialects))
it.value().second->number = it.index();
for (auto [idx, dialect] : llvm::enumerate(dialects))
dialect.second->number = idx;

// Number each of the recorded components within each dialect.

Expand Down Expand Up @@ -245,7 +245,7 @@ void IRNumberingState::number(Region &region) {

// Number the blocks within this region.
size_t blockCount = 0;
for (auto &it : llvm::enumerate(region)) {
for (auto it : llvm::enumerate(region)) {
blockIDs.try_emplace(&it.value(), it.index());
number(it.value());
++blockCount;
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Conversion/AMDGPUToROCDL/AMDGPUToROCDL.cpp
Expand Up @@ -200,7 +200,7 @@ struct RawBufferOpLowering : public ConvertOpToLLVMPattern<GpuOp> {

// Indexing (voffset)
Value voffset;
for (auto &pair : llvm::enumerate(adaptor.getIndices())) {
for (auto pair : llvm::enumerate(adaptor.getIndices())) {
size_t i = pair.index();
Value index = pair.value();
Value strideOp;
Expand Down
13 changes: 6 additions & 7 deletions mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
Expand Up @@ -134,7 +134,7 @@ static void wrapForExternalCallers(OpBuilder &rewriter, Location loc,

SmallVector<Value, 8> args;
size_t argOffset = resultStructType ? 1 : 0;
for (auto &[index, argType] : llvm::enumerate(type.getInputs())) {
for (auto [index, argType] : llvm::enumerate(type.getInputs())) {
Value arg = wrapperFuncOp.getArgument(index + argOffset);
if (auto memrefType = argType.dyn_cast<MemRefType>()) {
Value loaded = rewriter.create<LLVM::LoadOp>(
Expand Down Expand Up @@ -222,11 +222,11 @@ static void wrapExternalFunction(OpBuilder &builder, Location loc,

// Iterate over the inputs of the original function and pack values into
// memref descriptors if the original type is a memref.
for (auto &en : llvm::enumerate(type.getInputs())) {
for (Type input : type.getInputs()) {
Value arg;
int numToDrop = 1;
auto memRefType = en.value().dyn_cast<MemRefType>();
auto unrankedMemRefType = en.value().dyn_cast<UnrankedMemRefType>();
auto memRefType = input.dyn_cast<MemRefType>();
auto unrankedMemRefType = input.dyn_cast<UnrankedMemRefType>();
if (memRefType || unrankedMemRefType) {
numToDrop = memRefType
? MemRefDescriptor::getNumUnpackedValues(memRefType)
Expand Down Expand Up @@ -677,9 +677,8 @@ struct ReturnOpLowering : public ConvertOpToLLVMPattern<func::ReturnOp> {
getTypeConverter()->packFunctionResults(op.getOperandTypes());

Value packed = rewriter.create<LLVM::UndefOp>(loc, packedType);
for (auto &it : llvm::enumerate(updatedOperands)) {
packed = rewriter.create<LLVM::InsertValueOp>(loc, packed, it.value(),
it.index());
for (auto [idx, operand] : llvm::enumerate(updatedOperands)) {
packed = rewriter.create<LLVM::InsertValueOp>(loc, packed, operand, idx);
}
rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(op, TypeRange(), packed,
op->getAttrs());
Expand Down
5 changes: 2 additions & 3 deletions mlir/lib/Conversion/LLVMCommon/TypeConverter.cpp
Expand Up @@ -228,12 +228,11 @@ Type LLVMTypeConverter::convertFunctionSignature(
? barePtrFuncArgTypeConverter
: structFuncArgTypeConverter;
// Convert argument types one by one and check for errors.
for (auto &en : llvm::enumerate(funcTy.getInputs())) {
Type type = en.value();
for (auto [idx, type] : llvm::enumerate(funcTy.getInputs())) {
SmallVector<Type, 8> converted;
if (failed(funcArgConverter(*this, type, converted)))
return {};
result.addInputs(en.index(), converted);
result.addInputs(idx, converted);
}

// If function does not return anything, create the void result type,
Expand Down
26 changes: 13 additions & 13 deletions mlir/lib/Conversion/PDLToPDLInterp/PredicateTree.cpp
Expand Up @@ -185,20 +185,20 @@ getTreePredicates(std::vector<PositionalPredicate> &predList, Value val,
if (types.size() == 1 && types[0].getType().isa<pdl::RangeType>()) {
getTreePredicates(predList, types.front(), builder, inputs,
builder.getType(builder.getAllResults(opPos)));
} else {
bool foundVariableLength = false;
for (auto &resultIt : llvm::enumerate(types)) {
bool isVariadic = resultIt.value().getType().isa<pdl::RangeType>();
foundVariableLength |= isVariadic;
return;
}

auto *resultPos =
foundVariableLength
? builder.getResultGroup(pos, resultIt.index(), isVariadic)
: builder.getResult(pos, resultIt.index());
predList.emplace_back(resultPos, builder.getIsNotNull());
getTreePredicates(predList, resultIt.value(), builder, inputs,
builder.getType(resultPos));
}
bool foundVariableLength = false;
for (auto [idx, typeValue] : llvm::enumerate(types)) {
bool isVariadic = typeValue.getType().isa<pdl::RangeType>();
foundVariableLength |= isVariadic;

auto *resultPos = foundVariableLength
? builder.getResultGroup(pos, idx, isVariadic)
: builder.getResult(pos, idx);
predList.emplace_back(resultPos, builder.getIsNotNull());
getTreePredicates(predList, typeValue, builder, inputs,
builder.getType(resultPos));
}
}

Expand Down
4 changes: 2 additions & 2 deletions mlir/lib/Dialect/Affine/Analysis/Utils.cpp
Expand Up @@ -127,15 +127,15 @@ void ComputationSliceState::dump() const {
llvm::errs() << "\t\t" << iv << "\n";

llvm::errs() << "\tLBs:\n";
for (auto &en : llvm::enumerate(lbs)) {
for (auto en : llvm::enumerate(lbs)) {
llvm::errs() << "\t\t" << en.value() << "\n";
llvm::errs() << "\t\tOperands:\n";
for (Value lbOp : lbOperands[en.index()])
llvm::errs() << "\t\t\t" << lbOp << "\n";
}

llvm::errs() << "\tUBs:\n";
for (auto &en : llvm::enumerate(ubs)) {
for (auto en : llvm::enumerate(ubs)) {
llvm::errs() << "\t\t" << en.value() << "\n";
llvm::errs() << "\t\tOperands:\n";
for (Value ubOp : ubOperands[en.index()])
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
Expand Up @@ -2438,7 +2438,7 @@ OpFoldResult LLVM::GEPOp::fold(FoldAdaptor adaptor) {
// Canonicalize any dynamic indices of constant value to constant indices.
bool changed = false;
SmallVector<GEPArg> gepArgs;
for (auto &iter : llvm::enumerate(indices)) {
for (auto iter : llvm::enumerate(indices)) {
auto integer = iter.value().dyn_cast_or_null<IntegerAttr>();
// Constant indices can only be int32_t, so if integer does not fit we
// are forced to keep it dynamic, despite being a constant.
Expand Down
4 changes: 2 additions & 2 deletions mlir/lib/Dialect/Linalg/TransformOps/LinalgTransformOps.cpp
Expand Up @@ -2462,7 +2462,7 @@ transform::TileOp::apply(TransformResults &transformResults,
SmallVector<Operation *> tiled;
SmallVector<SmallVector<Operation *, 4>, 4> loops;
loops.resize(getLoops().size());
for (auto &[i, op] : llvm::enumerate(targets)) {
for (auto [i, op] : llvm::enumerate(targets)) {
auto tilingInterface = dyn_cast<TilingInterface>(op);
auto dpsInterface = dyn_cast<DestinationStyleOpInterface>(op);
if (!tilingInterface || !dpsInterface) {
Expand Down Expand Up @@ -2865,7 +2865,7 @@ transform::TileToScfForOp::apply(TransformResults &transformResults,
SmallVector<Operation *> tiled;
SmallVector<SmallVector<Operation *, 4>, 4> loops;
loops.resize(getLoops().size());
for (auto &en : llvm::enumerate(targets)) {
for (auto en : llvm::enumerate(targets)) {
auto tilingInterfaceOp = dyn_cast<TilingInterface>(en.value());
if (!tilingInterfaceOp) {
DiagnosedSilenceableFailure diag =
Expand Down
7 changes: 4 additions & 3 deletions mlir/lib/Dialect/Linalg/Transforms/SplitReduction.cpp
Expand Up @@ -156,10 +156,11 @@ FailureOr<SplitReductionResult> mlir::linalg::splitReduction(
newMaps.push_back(AffineMap::get(oldOutputMap.getNumDims() + 1, 0, outputExpr,
op.getContext()));
SmallVector<utils::IteratorType> newIteratorTypes;
for (auto &it : llvm::enumerate(op.getIteratorTypesArray())) {
if (insertSplitDimension == it.index())
for (auto [index, iteratorType] :
llvm::enumerate(op.getIteratorTypesArray())) {
if (insertSplitDimension == index)
newIteratorTypes.push_back(utils::IteratorType::parallel);
newIteratorTypes.push_back(it.value());
newIteratorTypes.push_back(iteratorType);
}
if (insertSplitDimension == op.getIteratorTypesArray().size()) {
newIteratorTypes.push_back(utils::IteratorType::parallel);
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/Linalg/Transforms/Tiling.cpp
Expand Up @@ -89,7 +89,7 @@ void mlir::linalg::transformIndexOps(
RewriterBase &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
SmallVector<Value> allIvs(op.getNumLoops(), nullptr);
for (auto &en : enumerate(allIvs)) {
for (auto en : enumerate(allIvs)) {
auto rangeIndex = loopIndexToRangeIndex.find(en.index());
if (rangeIndex == loopIndexToRangeIndex.end())
continue;
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp
Expand Up @@ -314,7 +314,7 @@ struct LinalgOpPartialReductionInterface
AffineMap oldOutputMap =
linalgOp.getMatchingIndexingMap(linalgOp.getDpsInitOperand(0));
SmallVector<AffineExpr> outputExpr;
for (auto &[idx, expr] : llvm::enumerate(oldOutputMap.getResults())) {
for (auto [idx, expr] : llvm::enumerate(oldOutputMap.getResults())) {
if (static_cast<int64_t>(idx) == insertSplitDimension) {
outputExpr.push_back(b.getAffineDimExpr(reductionDims[0]));
}
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/SCF/IR/SCF.cpp
Expand Up @@ -3663,7 +3663,7 @@ LogicalResult scf::IndexSwitchOp::verify() {

if (failed(verifyRegion(getDefaultRegion(), "default region")))
return failure();
for (auto &[idx, caseRegion] : llvm::enumerate(getCaseRegions()))
for (auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
if (failed(verifyRegion(caseRegion, "case region #" + Twine(idx))))
return failure();

Expand Down
Expand Up @@ -377,9 +377,9 @@ struct Sparse2SparseReshapeRewriter : public OpRewritePattern<ReshapeOp> {
ArrayRef<int64_t> dstShape = dstTp.getShape();
genReshapeDstShape(loc, rewriter, dstSizes, srcSizes, dstShape,
op.getReassociationIndices());
for (auto &d : llvm::enumerate(dstShape)) {
if (d.value() == ShapedType::kDynamic)
dstDynSizes.push_back(dstSizes[d.index()]);
for (auto [idx, shape] : llvm::enumerate(dstShape)) {
if (shape == ShapedType::kDynamic)
dstDynSizes.push_back(dstSizes[idx]);
}
}

Expand Down
6 changes: 3 additions & 3 deletions mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
Expand Up @@ -2773,7 +2773,7 @@ struct FoldOrthogonalPaddings : public OpRewritePattern<PadOp> {
// zero-offset and zero-padding tensor::ExtractSliceOp, tensor::PadOp pair
// exists.
SmallVector<OpFoldResult> newOffsets(rank, rewriter.getIndexAttr(0));
for (auto &en : enumerate(newOffsets)) {
for (auto en : enumerate(newOffsets)) {
OpFoldResult innerOffset = innerSliceOp.getMixedOffsets()[en.index()];
OpFoldResult outerOffset = outerSliceOp.getMixedOffsets()[en.index()];
if (!innerDims.test(en.index()) &&
Expand All @@ -2796,7 +2796,7 @@ struct FoldOrthogonalPaddings : public OpRewritePattern<PadOp> {
// tensor::ExtractSliceOp does not match the size of the padded dimension.
// Otherwise, take the size of the inner tensor::ExtractSliceOp.
SmallVector<OpFoldResult> newSizes = innerSliceOp.getMixedSizes();
for (auto &en : enumerate(newSizes)) {
for (auto en : enumerate(newSizes)) {
if (!outerDims.test(en.index()))
continue;
OpFoldResult sliceSize = innerSliceOp.getMixedSizes()[en.index()];
Expand All @@ -2813,7 +2813,7 @@ struct FoldOrthogonalPaddings : public OpRewritePattern<PadOp> {

// Combine the high paddings of the two tensor::PadOps.
SmallVector<OpFoldResult> newHighPad(rank, rewriter.getIndexAttr(0));
for (auto &en : enumerate(newHighPad)) {
for (auto en : enumerate(newHighPad)) {
if (innerDims.test(en.index()))
newHighPad[en.index()] = padOp.getMixedHighPad()[en.index()];
if (outerDims.test(en.index()))
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp
Expand Up @@ -969,7 +969,7 @@ void transform::detail::setApplyToOneResults(
continue;
assert(transformOp->getNumResults() == partialResults.size() &&
"expected as many partial results as op as results");
for (auto &[i, value] : llvm::enumerate(partialResults))
for (auto [i, value] : llvm::enumerate(partialResults))
transposed[i].push_back(value);
}

Expand Down
7 changes: 4 additions & 3 deletions mlir/lib/Dialect/Vector/Transforms/VectorDistribute.cpp
Expand Up @@ -205,9 +205,10 @@ static WarpExecuteOnLane0Op moveRegionToNewWarpOpAndAppendReturns(
indices.push_back(yieldValues.size() - 1);
} else {
// If the value already exit the region don't create a new output.
for (auto &yieldOperand : llvm::enumerate(yieldValues.getArrayRef())) {
if (yieldOperand.value() == std::get<0>(newRet)) {
indices.push_back(yieldOperand.index());
for (auto [idx, yieldOperand] :
llvm::enumerate(yieldValues.getArrayRef())) {
if (yieldOperand == std::get<0>(newRet)) {
indices.push_back(idx);
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Dialect/Vector/Transforms/VectorUnroll.cpp
Expand Up @@ -628,7 +628,7 @@ struct UnrollTransposePattern : public OpRewritePattern<vector::TransposeOp> {
SmallVector<int64_t> permutedOffsets(elementOffsets.size());
SmallVector<int64_t> permutedShape(elementOffsets.size());
// Compute the source offsets and shape.
for (auto &indices : llvm::enumerate(permutation)) {
for (auto indices : llvm::enumerate(permutation)) {
permutedOffsets[indices.value()] = elementOffsets[indices.index()];
permutedShape[indices.value()] = (*targetShape)[indices.index()];
}
Expand Down
6 changes: 3 additions & 3 deletions mlir/lib/Dialect/X86Vector/Transforms/AVXTranspose.cpp
Expand Up @@ -257,9 +257,9 @@ class TransposeOpLowering : public OpRewritePattern<vector::TransposeOp> {
return rewriter.notifyMatchFailure(op, "Unsupported vector element type");

SmallVector<int64_t> srcGtOneDims;
for (auto &en : llvm::enumerate(srcType.getShape()))
if (en.value() > 1)
srcGtOneDims.push_back(en.index());
for (auto [index, size] : llvm::enumerate(srcType.getShape()))
if (size > 1)
srcGtOneDims.push_back(index);

if (srcGtOneDims.size() != 2)
return rewriter.notifyMatchFailure(op, "Unsupported vector type");
Expand Down
10 changes: 5 additions & 5 deletions mlir/lib/ExecutionEngine/ExecutionEngine.cpp
Expand Up @@ -196,17 +196,17 @@ static void packFunctionArguments(Module *module) {
llvm::Value *argList = interfaceFunc->arg_begin();
SmallVector<llvm::Value *, 8> args;
args.reserve(llvm::size(func.args()));
for (auto &indexedArg : llvm::enumerate(func.args())) {
for (auto [index, arg] : llvm::enumerate(func.args())) {
llvm::Value *argIndex = llvm::Constant::getIntegerValue(
builder.getInt64Ty(), APInt(64, indexedArg.index()));
builder.getInt64Ty(), APInt(64, index));
llvm::Value *argPtrPtr =
builder.CreateGEP(builder.getInt8PtrTy(), argList, argIndex);
llvm::Value *argPtr =
builder.CreateLoad(builder.getInt8PtrTy(), argPtrPtr);
llvm::Type *argTy = indexedArg.value().getType();
llvm::Type *argTy = arg.getType();
argPtr = builder.CreateBitCast(argPtr, argTy->getPointerTo());
llvm::Value *arg = builder.CreateLoad(argTy, argPtr);
args.push_back(arg);
llvm::Value *load = builder.CreateLoad(argTy, argPtr);
args.push_back(load);
}

// Call the implementation function with the extracted arguments.
Expand Down
6 changes: 3 additions & 3 deletions mlir/lib/IR/AsmPrinter.cpp
Expand Up @@ -3274,9 +3274,9 @@ void OperationPrinter::printValueUsers(Value value) {
// One value might be used as the operand of an operation more than once.
// Only print the operations results once in that case.
SmallPtrSet<Operation *, 1> userSet;
for (auto &indexedUser : enumerate(value.getUsers())) {
if (userSet.insert(indexedUser.value()).second)
printUserIDs(indexedUser.value(), indexedUser.index());
for (auto [index, user] : enumerate(value.getUsers())) {
if (userSet.insert(user).second)
printUserIDs(user, index);
}
}

Expand Down
4 changes: 2 additions & 2 deletions mlir/lib/Pass/PassStatistics.cpp
Expand Up @@ -73,8 +73,8 @@ static void printResultsAsList(raw_ostream &os, OpPassManager &pm) {
for (Pass::Statistic *it : pass->getStatistics())
passEntry.push_back({it->getName(), it->getDesc(), it->getValue()});
} else {
for (auto &it : llvm::enumerate(pass->getStatistics()))
passEntry[it.index()].value += it.value()->getValue();
for (auto [idx, statistic] : llvm::enumerate(pass->getStatistics()))
passEntry[idx].value += statistic->getValue();
}
#endif
return;
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/TableGen/Operator.cpp
Expand Up @@ -408,7 +408,7 @@ void Operator::populateTypeInferenceInfo(

// For all results whose types are buildable, initialize their type inference
// nodes with an edge to themselves. Mark those nodes are fully-inferred.
for (auto &[idx, infer] : llvm::enumerate(inference)) {
for (auto [idx, infer] : llvm::enumerate(inference)) {
if (getResult(idx).constraint.getBuilderCall()) {
infer.sources.emplace_back(InferredResultType::mapResultIndex(idx),
"$_self");
Expand Down
4 changes: 1 addition & 3 deletions mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
Expand Up @@ -520,9 +520,7 @@ void mlir::LLVM::detail::connectPHINodes(Region &region,
auto phis = llvmBB->phis();
auto numArguments = bb.getNumArguments();
assert(numArguments == std::distance(phis.begin(), phis.end()));
for (auto &numberedPhiNode : llvm::enumerate(phis)) {
auto &phiNode = numberedPhiNode.value();
unsigned index = numberedPhiNode.index();
for (auto [index, phiNode] : llvm::enumerate(phis)) {
for (auto *pred : bb.getPredecessors()) {
// Find the LLVM IR block that contains the converted terminator
// instruction and use it in the PHI node. Note that this block is not
Expand Down
2 changes: 1 addition & 1 deletion mlir/lib/Transforms/TopologicalSort.cpp
Expand Up @@ -24,7 +24,7 @@ struct TopologicalSortPass
void runOnOperation() override {
// Topologically sort the regions of the operation without SSA dominance.
getOperation()->walk([](RegionKindInterface op) {
for (auto &it : llvm::enumerate(op->getRegions())) {
for (auto it : llvm::enumerate(op->getRegions())) {
if (op.hasSSADominance(it.index()))
continue;
for (Block &block : it.value())
Expand Down

0 comments on commit 8c258fd

Please sign in to comment.