lowerer.cpp 47 KB
Newer Older
1
//*****************************************************************************
nmostafa's avatar
nmostafa committed
2
// Copyright 2017-2019 Intel Corporation
3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

17 18 19
// NOTE: This file follows nGraph format style and MLIR naming convention since it does
// not expose public API to the rest of nGraph codebase and heavily depends on MLIR API.

20
#include "lowerer.hpp"
21

Nagy Mostafa's avatar
Nagy Mostafa committed
22
#include "compiler.hpp"
23 24
#include "dialect/ops.hpp"
#include "dialect/type.hpp"
25 26
#include "ngraph/assertion.hpp"

27 28 29 30
#include <llvm/ADT/DenseSet.h>
#include <mlir/EDSC/Builders.h>
#include <mlir/EDSC/Helpers.h>
#include <mlir/EDSC/Intrinsics.h>
31 32
#include <mlir/IR/AffineExpr.h>
#include <mlir/IR/IntegerSet.h>
33 34 35 36 37 38
#include <mlir/IR/MLIRContext.h>
#include <mlir/IR/StandardTypes.h>
#include <mlir/Transforms/DialectConversion.h>

#include <map>

39 40 41 42 43 44
// anonymous namespace
// no need to expose any of the following outside of this file
namespace
{
    using namespace mlir;
    using namespace mlir::edsc;
45
    using namespace mlir::edsc::op;
46
    using namespace ngraph::runtime;
47
    using namespace ngraph::runtime::ngmlir;
48 49
    // Index notation to generate standard (i.e., non-affine) loads and stores.
    using StdIndexedValue = TemplatedIndexedValue<intrinsics::std_load, intrinsics::std_store>;
50 51

    class DialectLoweringPass;
52

53 54 55 56 57 58 59 60
    /// Base class for nGraph operation conversions to affine/standard dialect. Provides
    /// conversion patterns with an access to the DialectLoweringPass which holds the state of the
    /// conversion.
    class NGraphOpLowering : public ConversionPattern
    {
    public:
        NGraphOpLowering(StringRef rootOpName, MLIRContext* context, DialectLoweringPass& pass)
            : ConversionPattern(rootOpName, /*benefit=*/1, context)
61
            , pass(pass){};
62 63 64 65

    protected:
        // Back-reference to the lowering pass which contains the lowering state, including the
        // nGraph type converter.
66
        DialectLoweringPass& pass;
67 68
    };

69 70 71 72 73 74 75 76 77 78 79 80
// Conversion classes declarations
#define MLIR_OP(OP)                                                                                \
    class OP##Conversion : public NGraphOpLowering                                                 \
    {                                                                                              \
    public:                                                                                        \
        explicit OP##Conversion(mlir::MLIRContext* context, DialectLoweringPass& pass)             \
            : NGraphOpLowering(mlir::OP::getOperationName(), context, pass)                        \
        {                                                                                          \
        }                                                                                          \
                                                                                                   \
        PatternMatchResult matchAndRewrite(Operation* op,                                          \
                                           ArrayRef<Value*> operands,                              \
81
                                           ConversionPatternRewriter& rewriter) const override;    \
82 83
    };

84 85
#include "op_lowerers.inc"

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    // FuncOp Conversion pattern
    class FuncOpSignatureConversion : public ConversionPattern
    {
    public:
        FuncOpSignatureConversion(MLIRContext* ctx, TypeConverter& converter)
            : ConversionPattern(FuncOp::getOperationName(), 1, ctx)
            , converter(converter)
        {
        }

        /// Hook for derived classes to implement combined matching and rewriting.
        PatternMatchResult matchAndRewrite(Operation* op,
                                           ArrayRef<Value*> operands,
                                           ConversionPatternRewriter& rewriter) const override
        {
            auto funcOp = cast<FuncOp>(op);
            FunctionType type = funcOp.getType();

            // Convert the original function arguments.
            TypeConverter::SignatureConversion result(type.getNumInputs());
            for (unsigned i = 0, e = type.getNumInputs(); i != e; ++i)
                if (failed(converter.convertSignatureArg(i, type.getInput(i), result)))
                    return matchFailure();

            // Convert the original function results.
            SmallVector<Type, 4> convertedResults;
            if (failed(converter.convertTypes(type.getResults(), convertedResults)))
                return matchFailure();

            // Add result types as input args without mapping
            result.addInputs(convertedResults);

            // Create a new function with an updated signature.
            auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);
            rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(), newFuncOp.end());
            newFuncOp.setType(
                FunctionType::get(result.getConvertedTypes(), {/*void*/}, funcOp.getContext()));

            // Tell the rewriter to convert the region signature.
            rewriter.applySignatureConversion(&newFuncOp.getBody(), result);
            rewriter.replaceOp(op, llvm::None);
            return matchSuccess();
        }

        /// The type converter to use when rewriting the signature.
        TypeConverter& converter;
    };

nmostafa's avatar
nmostafa committed
134
    // Helpers
135 136 137 138
    template <typename RedOp>
    void lowerIndexReduction(Operation* op,
                             ArrayRef<Value*> operands,
                             PatternRewriter& rewriter,
139
                             DialectLoweringPass& pass);
nmostafa's avatar
nmostafa committed
140

141 142 143 144
    template <typename OP>
    void lower_binary_elementwise(Operation* op,
                                  ArrayRef<Value*> operands,
                                  PatternRewriter& rewriter,
145
                                  DialectLoweringPass& pass);
146

147 148 149 150 151 152
    template <typename OP>
    void lower_unary_elementwise(Operation* op,
                                 ArrayRef<Value*> operands,
                                 PatternRewriter& rewriter,
                                 DialectLoweringPass& pass);

153 154
    ValueHandle createZeroConstant(mlir::Type type);

155 156
    /// Conversion from types in the nGraph dialect to the Standard dialect.
    class NGraphTypeConverter : public TypeConverter
157 158
    {
    public:
159 160
        NGraphTypeConverter()
            : TypeConverter()
161 162 163 164 165 166 167 168 169 170
        {
        }

        Type convertType(Type t) override;
    };

    /// Dialect Lowering Pass to affine ops
    class DialectLoweringPass : public ModulePass<DialectLoweringPass>
    {
    public:
171
        DialectLoweringPass(ngmlir::MLIRCompiler& compiler)
172
            : compiler(compiler)
173 174
        {
        }
175

176
        void runOnModule() override;
177
        SmallVector<Value*, 4> buildOutputDefs(Operation* op, PatternRewriter& rewriter);
178
        Value* createTempTensor(Type type, PatternRewriter& rewriter);
179

180 181 182
        /// Inserts dealloc Ops for each temporary allocated by AllocOp
        void insertDeallocs(PatternRewriter& rewriter);

183
        NGraphTypeConverter& getTypeConverter() { return typeConverter; }
184
    private:
185 186 187
        /// Collect a set of patterns to convert from the nGraph dialect to Affine dialect.
        void populateNGraphToAffineConversionPatterns(OwningRewritePatternList& patterns);

188
        void findOutputValues();
189
        void insertNoAliasArgAttrs();
190 191

    private:
192
        NGraphTypeConverter typeConverter;
193
        // List of temporary memrefs to deallocate at end of function
194
        SmallVector<Value*, 4> memRefsToDealloc;
195
        ngmlir::MLIRCompiler& compiler;
196 197 198 199
    };

    void DialectLoweringPass::runOnModule()
    {
200 201 202
        // Create type converter and initialize conversion patterns.
        NGraphTypeConverter converter;
        OwningRewritePatternList patterns;
203

204 205 206 207
        populateNGraphToAffineConversionPatterns(patterns);

        // Create target that defines legal ops for nGraph dialect to be lowered to.
        ConversionTarget target(getContext());
208

209
        target.addLegalDialect<AffineOpsDialect, StandardOpsDialect>();
210
        target.addLegalOp<ModuleOp, ModuleTerminatorOp>();
211 212 213 214
        target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) {
            // FuncOp is legal only if types have been converted to Std types.
            return typeConverter.isSignatureLegal(op.getType());
        });
215

216 217 218 219 220
        // capture output values by looking for the Return and grabbing the values
        // the order of the returned values matches the order of the lowered func signature for
        // results. This is used to find the arg_id that a defined value maps to if it is an output
        findOutputValues();

221
        if (failed(applyFullConversion(getModule(), target, std::move(patterns), &converter)))
222
        {
223
            emitError(mlir::UnknownLoc::get(&getContext()), "Error lowering nGraph dialect\n");
224 225
            signalPassFailure();
        }
nmostafa's avatar
nmostafa committed
226

227
        insertNoAliasArgAttrs();
228 229
    }

230 231 232
    void DialectLoweringPass::populateNGraphToAffineConversionPatterns(
        OwningRewritePatternList& patterns)
    {
233 234
#define MLIR_OP(OP) OP##Conversion,
#define MLIR_LAST_OP(OP) OP##Conversion
235
        patterns.insert<
236
#include "op_lowerers.inc"
237
            >(&getContext(), *this);
238 239 240

        // FuncOp pattern
        patterns.insert<FuncOpSignatureConversion>(&getContext(), typeConverter);
241 242
    }

243 244
    void DialectLoweringPass::findOutputValues()
    {
Nagy Mostafa's avatar
Nagy Mostafa committed
245
        // get original function
246
        auto f = getModule().lookupSymbol<mlir::FuncOp>("main");
247 248
        SmallVector<Value*, 4> outputList;
        unsigned outputCount = 0;
249
        unsigned inputCount = f.getType().getNumInputs();
250 251
        // we find out output values by looking at returned values
        // any return should return all outputs of the subgraph
252
        f.walk([this, &outputCount, inputCount](NGReturnOp ret) {
253 254
            for (unsigned i = 0; i < ret.getNumOperands(); i++)
            {
255
                // annotate instructions defining outputs with the arg idx of the output
256 257
                auto outputValue = ret.getOperand(i);
                auto op = outputValue->getDefiningOp();
258 259 260 261

                op->setAttr(
                    "graphOutputIdx",
                    mlir::IntegerAttr::get(IntegerType::get(32, op->getContext()), i + inputCount));
262
            }
263 264
            NGRAPH_CHECK(outputCount == 0 || outputCount == ret.getNumOperands(),
                         "Inconsistent returns in function");
265 266 267
        });
    }

Nagy Mostafa's avatar
Nagy Mostafa committed
268
    SmallVector<Value*, 4> DialectLoweringPass::buildOutputDefs(Operation* op,
269
                                                                PatternRewriter& rewriter)
Nagy Mostafa's avatar
Nagy Mostafa committed
270 271 272 273
    {
        SmallVector<Value*, 4> newResults;
        for (auto origResult : op->getResults())
        {
274
            // find output arg if this operation produces any sub-graph outputs
275
            if (IntegerAttr attr = op->getAttrOfType<IntegerAttr>("graphOutputIdx"))
Nagy Mostafa's avatar
Nagy Mostafa committed
276
            {
277 278 279 280
                auto f = getModule().lookupSymbol<mlir::FuncOp>("main");
                mlir::Block* entryBlock = &*(f.begin());
                unsigned argId = (unsigned)attr.getInt();
                newResults.push_back(entryBlock->getArgument(argId));
Nagy Mostafa's avatar
Nagy Mostafa committed
281 282 283
            }
            else
            {
284
                auto tensorType = origResult->getType().cast<NGTensorType>();
285
                auto newResult = createTempTensor(typeConverter.convertType(tensorType), rewriter);
Nagy Mostafa's avatar
Nagy Mostafa committed
286 287 288 289 290 291
                newResults.push_back(newResult);
            }
        }
        return newResults;
    }

292
    Value* DialectLoweringPass::createTempTensor(Type type, PatternRewriter& rewriter)
293
    {
294 295 296 297 298
        MemRefType memRefType = type.cast<MemRefType>();

        NGRAPH_CHECK(memRefType.hasStaticShape(), "Dynamic shapes are not supported");

        Value* alloc = rewriter.create<mlir::AllocOp>(rewriter.getUnknownLoc(), memRefType);
299
        memRefsToDealloc.push_back(alloc);
300 301 302 303

        // TODO:
        // Enable dynamic memref allocation via call-back to nGraph allocator
        // We should create a list of Values representing each dynamic dim
304 305
        // The values would be computed based on the shape of the input to the ng op we are
        // lowering.
306 307
        // E.g. If lowering concat, Value for dynamic concat axis will be the sum of input dims.
        // The lowerer will generate code to compute the dims.
308 309
        // This is better be done via std.AllocOp but we need to make it hookable to nGraph
        // allocator call-back.
310 311

        return alloc;
312 313
    }

314 315 316 317
    /// Add llvm.noalias attribute to all the memref function arguments. We know that this is safe
    /// by nGraph op semantics.
    void DialectLoweringPass::insertNoAliasArgAttrs()
    {
318
        auto func = getModule().lookupSymbol<mlir::FuncOp>("main");
319
        unsigned int argIdx = 0;
320
        for (auto* arg : func.getArguments())
321 322 323
        {
            if (arg->getType().isa<MemRefType>())
            {
324
                func.setArgAttr(argIdx, "llvm.noalias", BoolAttr::get(true, &getContext()));
325 326 327 328 329 330
            }

            ++argIdx;
        }
    }

331 332
    void DialectLoweringPass::insertDeallocs(PatternRewriter& rewriter)
    {
333
        for (auto value : memRefsToDealloc)
334 335 336 337 338
        {
            rewriter.create<DeallocOp>(rewriter.getUnknownLoc(), value);
        }
    }

339
    // NGDialect converters
340
    Type NGraphTypeConverter::convertType(Type type)
Nagy Mostafa's avatar
Nagy Mostafa committed
341
    {
342
        // We may need to refactor this code to a external utility if type conversion is needed
343
        // outside of the lowering context since NGraphTypeConverter is private.
344

345
        if (auto tensorType = type.dyn_cast<NGTensorType>())
Nagy Mostafa's avatar
Nagy Mostafa committed
346
        {
347 348
            // Convert NGTensorType to Std MemRefType directly instead of going to Std TensorType.
            // This may change in the future.
349 350
            return MemRefType::get(tensorType.getShape(),
                                   convertType(tensorType.getElementType()),
351 352
                                   {/* no map used */},
                                   0);
Nagy Mostafa's avatar
Nagy Mostafa committed
353
        }
354
        if (auto floatType = type.dyn_cast<NGFloatType>())
355
        {
356
            // Float types are already std type.
357
            return floatType;
358
        }
359
        if (auto intType = type.dyn_cast<NGIntegerType>())
360
        {
361
            return mlir::IntegerType::get(intType.getWidth(), intType.getContext());
362
        }
363
        if (auto boolType = type.dyn_cast<NGBoolType>())
364
        {
365
            return mlir::IntegerType::get(1 /* width */, boolType.getContext());
366
        }
367

368 369
        // Do not assert/NGRAPH_CHECK here. Type convertion infra expects `convertType` to return
        // the input type if the type is not supported.
370
        return type;
Nagy Mostafa's avatar
Nagy Mostafa committed
371 372
    }

373
#define REWRITER(OP)                                                                               \
374
    PatternMatchResult OP##Conversion::matchAndRewrite(                                            \
375
        Operation* op, ArrayRef<Value*> operands, ConversionPatternRewriter& rewriter) const
376 377

    REWRITER(NGAddOp)
378
    {
379
        lower_binary_elementwise<mlir::NGAddOp>(op, operands, rewriter, pass);
380 381
        return matchSuccess();
    }
382

383
    REWRITER(NGSubOp)
384
    {
385
        lower_binary_elementwise<mlir::NGSubOp>(op, operands, rewriter, pass);
386 387
        return matchSuccess();
    }
388

389 390
    REWRITER(NGMulOp)
    {
391
        lower_binary_elementwise<mlir::NGMulOp>(op, operands, rewriter, pass);
392 393
        return matchSuccess();
    }
394

395 396
    REWRITER(NGDivOp)
    {
397
        lower_binary_elementwise<mlir::NGDivOp>(op, operands, rewriter, pass);
398 399
        return matchSuccess();
    }
400

401 402
    REWRITER(NGGreaterOp)
    {
403
        lower_binary_elementwise<mlir::NGGreaterOp>(op, operands, rewriter, pass);
404 405 406 407 408
        return matchSuccess();
    }

    REWRITER(NGLessOp)
    {
409
        lower_binary_elementwise<mlir::NGLessOp>(op, operands, rewriter, pass);
410 411
        return matchSuccess();
    }
412

413 414
    REWRITER(NGMaxOp)
    {
415
        lower_binary_elementwise<mlir::NGMaxOp>(op, operands, rewriter, pass);
416 417 418 419 420
        return matchSuccess();
    }

    REWRITER(NGMinOp)
    {
421
        lower_binary_elementwise<mlir::NGMinOp>(op, operands, rewriter, pass);
422
        return matchSuccess();
423 424
    }

425 426
    REWRITER(NGArgMaxRedOp)
    {
427
        lowerIndexReduction<mlir::NGArgMaxRedOp>(op, operands, rewriter, pass);
428 429 430 431 432
        return matchSuccess();
    }

    REWRITER(NGArgMinRedOp)
    {
433
        lowerIndexReduction<mlir::NGArgMinRedOp>(op, operands, rewriter, pass);
434
        return matchSuccess();
435 436
    }

437 438 439 440 441
    // Relu
    REWRITER(NGReluOp)
    {
        auto loc = cast<NGReluOp>(op).getLoc();

442
        auto result = pass.buildOutputDefs(op, rewriter)[0];
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        NGRAPH_CHECK(result->getType().isa<MemRefType>());
        // Note that builder's current function is still the original function body.
        // use getBlock to get the new block instead.

        // get new operands
        Value* lhs = operands[0];

        ScopedContext scope(rewriter, loc);
        // Views
        MemRefView vRes(result), vLHS(lhs);
        // Index Values
        IndexedValue iRes(result), iLHS(lhs);
        // Bounds Index Handles
        auto lbs = vLHS.getLbs();
        auto ubs = vLHS.getUbs();
        // Loop induction vars
459 460
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
461 462 463 464 465 466 467 468
        // Steps
        auto steps = vLHS.getSteps();

        NGRAPH_CHECK(lhs->getType().isa<MemRefType>());
        Type elemTy = lhs->getType().dyn_cast<MemRefType>().getElementType();

        LoopNestBuilder(pivs, lbs, ubs, steps)([&] {
            ValueHandle val = iLHS(ivs);
469 470
            ValueHandle zero = createZeroConstant(elemTy);
            iRes(ivs) = intrinsics::select(val > zero, val, zero);
471 472 473 474 475 476
        });

        rewriter.replaceOp(op, {result});
        return matchSuccess();
    }

477 478 479 480 481 482 483
    // Negative
    REWRITER(NGNegOp)
    {
        lower_unary_elementwise<mlir::NGNegOp>(op, operands, rewriter, pass);
        return matchSuccess();
    }

484
    REWRITER(NGDotOp)
485
    {
486 487
        auto dot = cast<NGDotOp>(op);
        auto loc = dot.getLoc();
488 489 490 491 492

        // Retrieve/generate Values for operands and result.
        ScopedContext scope(rewriter, loc);
        Value* lhs = operands[0];
        Value* rhs = operands[1];
493
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
494
        NGRAPH_CHECK(lhs && rhs && result, "Unexpected null values in DotOp");
495

496 497 498 499 500 501
        auto resultTy = result->getType().dyn_cast<MemRefType>();
        auto lhsTy = lhs->getType().dyn_cast<MemRefType>();
        auto rhsTy = rhs->getType().dyn_cast<MemRefType>();
        NGRAPH_CHECK(resultTy, "Unexpected non-memref result type");
        NGRAPH_CHECK(lhsTy, "Unexpected non-memref LHS type");
        NGRAPH_CHECK(rhsTy, "Unexpected non-memref RHS type");
502

503 504
        Type elemTy = resultTy.getElementType();
        NGRAPH_CHECK(elemTy == lhsTy.getElementType() && elemTy == rhsTy.getElementType(),
505
                     "Types mismatch in DotOp");
506 507 508 509 510 511 512 513

        // Create the following loop nest for matmul operation:
        //   for(n, N, 1)
        //     for(m, M, 1)
        //       for(k, K, 1)
        //         res[n, k] += lhs[n, m] * rhs[m, k]
        // TODO (dcab): We currently generate a super naive loop nest. Improve loop nest layout.

514
        MemRefView vRes(result), vLhs(lhs), vRhs(rhs);
515

516
        NGRAPH_CHECK(vLhs.rank() == 2 && vRhs.rank() == 2 && vRes.rank() == 2,
517
                     "Dot operation is only supported for 2D tensors");
518

519 520 521 522
        // Create induction variables, lower bounds, upper bounds and steps of the loop nest.
        // It's important to note that MemRefView priovides lb/ub/step info is "reverse order",
        // i.e., fastest varying dimension is the last one, slowest varying dimention is the first
        // one.
523
        IndexHandle n, m, k;
524 525 526 527 528 529
        unsigned nDim = vLhs.fastestVarying() - 1;
        unsigned mDim = vRhs.fastestVarying();
        unsigned kDim = vRhs.fastestVarying();
        IndexHandle nLb(vLhs.lb(nDim)), mLb(vLhs.lb(mDim)), kLb(vRhs.lb(kDim));
        IndexHandle nUb(vLhs.ub(nDim)), mUb(vLhs.ub(mDim)), kUb(vRhs.ub(kDim));
        int64_t nStep = vLhs.step(nDim), mStep = vLhs.step(mDim), kStep = vRhs.step(kDim);
530

531
        // Constants and indexed values to be used inside the loop nest.
532 533 534 535 536 537 538
        IndexedValue iRes(result), iLhs(lhs), iRhs(rhs);
        ValueHandle zeroInit(rewriter.create<ConstantOp>(loc, rewriter.getZeroAttr(elemTy)));

        LoopBuilder(&n, nLb, nUb, nStep)([&] {
            LoopBuilder(&k, kLb, kUb, kStep)([&] {
                iRes(n, k) = zeroInit;
                LoopBuilder(&m, mLb, mUb, mStep)([&] { iRes(n, k) += iLhs(n, m) * iRhs(m, k); });
539 540 541
            });
        });

542
        rewriter.replaceOp(op, {result});
Adam Procter's avatar
Adam Procter committed
543 544 545 546 547 548 549 550 551 552 553

        return matchSuccess();
    }

    REWRITER(NGConcatOp)
    {
        auto concat = cast<NGConcatOp>(op);
        auto loc = concat.getLoc();
        ScopedContext scope(rewriter, loc);

        // Create Value for result, and extract type info.
554
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
Adam Procter's avatar
Adam Procter committed
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        NGRAPH_CHECK(result, "Unexpected null result in ConcatOp");

        // Create view to write into result.
        MemRefView vRes(result);
        auto rank = vRes.rank();

        // For each operand, generate a separate loop to copy into the target slice of "result".
        // We'll keep track of the slice offsets via concatenation_axis_pos.
        auto concatenationAxis = concat.concatenation_axis().getSExtValue();
        IndexHandle concatenationAxisPos(index_t(0));

        for (auto& operand : operands)
        {
            NGRAPH_CHECK(operand, "Unexpected null operand in ConcatOp");

            // Assuming rank = r, and the concatenation axis is A where A<r, we'll be creating
            // loops of this form:
            //
            //   for i_0 := 0 to operand.dims[0]:
            //    for i_1 := 0 to operand.dims[1]:
            //     ...
            //      for i_(r-2) := 0 to operand.dims[r-2]:
            //       for i_(r-1) := 0 to operand.dims[r-1]:
            //        result[i_0][i_1]...
            //              [i_(A-1)][i_A + concatenationAxisPos][i_(A+1)]...
            //              [i_(r-2)][i_(r-1)]
            //                  :=
            //        operand[i_0][i_1]...[i_(r-2)][i_(r-1)]
            MemRefView vOperand(operand);
            NGRAPH_CHECK(vOperand.rank() == rank, "Unexpected rank mismatch");

            llvm::SmallVector<ValueHandle, 5> indexVars;
            llvm::SmallVector<ValueHandle*, 5> indexVarPtrs;
            llvm::SmallVector<ValueHandle, 5> indexVarLbs;
            llvm::SmallVector<ValueHandle, 5> indexVarUbs;
            llvm::SmallVector<int64_t, 5> indexVarSteps;
            for (int i = 0; i < rank; i++)
            {
                indexVars.push_back(IndexHandle());
                indexVarPtrs.push_back(&(indexVars.back()));
                indexVarLbs.push_back(vOperand.lb(i));
                indexVarUbs.push_back(vOperand.ub(i));
                indexVarSteps.push_back(vOperand.step(i));
            }

            LoopNestBuilder(indexVarPtrs, indexVarLbs, indexVarUbs, indexVarSteps)([&] {
                IndexedValue ivRes(result);
                IndexedValue ivOperand(operand);

                // On the LHS of the assignment, adjust the index for the concatenation axis.
                llvm::SmallVector<ValueHandle, 5> resIndexHandles;
                for (int i = 0; i < rank; i++)
                {
                    resIndexHandles.push_back(i == concatenationAxis
                                                  ? indexVars[i] + concatenationAxisPos
                                                  : indexVars[i]);
                }

                ivRes(resIndexHandles) = ivOperand(indexVars);
            });

            // Move up concatenation_axis_pos for the next operand.
            concatenationAxisPos = concatenationAxisPos + vOperand.ub(concatenationAxis);
        }

        rewriter.replaceOp(op, {result});
621

622
        return matchSuccess();
nmostafa's avatar
nmostafa committed
623
    }
624

625
    REWRITER(NGGatherOp)
nmostafa's avatar
nmostafa committed
626
    {
627 628 629 630 631
        auto gatherOp = cast<NGGatherOp>(op);
        auto loc = gatherOp.getLoc();
        ScopedContext scope(rewriter, loc);

        // Get operands
632
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
633 634 635 636 637 638 639 640 641
        NGRAPH_CHECK(result, "Unexpected null result in GatherOp");

        Value* params = operands[0];
        Value* indices = operands[1];
        auto axis = gatherOp.axis().getSExtValue();

        // Create view to write into result.
        MemRefView vRes(result), vParams(params), vIndices(indices);
        // Indexed Values
642 643
        IndexedValue iRes(result), iIndices(indices);
        StdIndexedValue iParams(params);
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

        // Construct outer loop for params dims. Exclude the axis dim.
        SmallVector<ValueHandle, 4> paramsLbs, paramsUbs;
        SmallVector<IndexHandle, 4> paramsIVs;
        SmallVector<int64_t, 4> paramsSteps;
        SmallVector<ValueHandle*, 4> paramsIVPtrs;
        for (auto i = 0; i < vParams.rank(); i++)
        {
            // skip gather axis
            if (i == axis)
                continue;
            paramsLbs.push_back(IndexHandle(vParams.lb(i)));
            paramsUbs.push_back(IndexHandle(vParams.ub(i)));
            paramsSteps.push_back(vParams.step(i));
        }
nmostafa's avatar
nmostafa committed
659 660 661 662
        NGRAPH_CHECK(paramsLbs.size() == vParams.rank() - 1 &&
                         paramsUbs.size() == paramsLbs.size() &&
                         paramsSteps.size() == paramsLbs.size(),
                     "Incorrect loop nest bounds size for gather params");
663

664 665
        paramsIVs = makeIndexHandles(vParams.rank() - 1);
        paramsIVPtrs = makeIndexHandlePointers(paramsIVs);
666 667 668 669

        auto indicesLbs = vIndices.getLbs();
        auto indicesUbs = vIndices.getUbs();
        auto indicesSteps = vIndices.getSteps();
nmostafa's avatar
nmostafa committed
670

671 672
        auto indicesIVs = makeIndexHandles(vIndices.rank());
        auto indicesIVPtrs = makeIndexHandlePointers(indicesIVs);
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695

        SmallVector<IndexHandle, 8> paramsIndices, resIndices;

        // Make sure we are going to create loops
        NGRAPH_CHECK(vParams.rank() > 0, "Invalid size for indices steps");

        // Let params rank : N
        // Let indices rank : M
        // Let axis be A
        // Generate
        // params loops
        // for P_0: 0 -> params.dim[0]
        //   for P_1: 0 -> params.dim[1]
        //     for P_2: 0 -> params.dim[2]
        // ...
        //       for P_(A-1):0 -> params.dim[A-1]
        //         for P_(A+1):0 -> params.dim[A+1]
        // ...
        //           for P_(N-1):0 -> params.dim[N-1]
        //             indices loops
        //             for I_0:0 -> indices.dim[0]
        // ...
        //               for I_(M-1):0 -> indices.dim[M-1]
nmostafa's avatar
nmostafa committed
696
        //                 res[P_0, P_1, .. P_(A-1), I_0, .., I_(M-1), P_(A+1), ... P_(N-1)] =
697 698
        //                   params[P_0, P_1, .. P_(A-1), indices[I_0, .., I_(M-1)],
        //                          P_(A+1), ... P_(N-1)];
699 700 701 702 703 704 705 706 707 708 709 710 711 712

        LoopNestBuilder(paramsIVPtrs, paramsLbs, paramsUbs, paramsSteps)([&] {
            LoopNestBuilder(indicesIVPtrs, indicesLbs, indicesUbs, indicesSteps)([&] {
                // Load axis value from indices array and cast it to Index Type
                ValueHandle axisIdx = ValueHandle::create<IndexCastOp>(
                    (ValueHandle)iIndices(indicesIVs), rewriter.getIndexType());
                // construct indices for param
                // [P_0, P_1, .. P_axis-1, Indices[I0, I1, .. I_k-1], P_axis+1, P_axis+2, .. P_n-1]
                for (auto i = 0, j = 0; i < vParams.rank(); i++)
                {
                    if (i == axis)
                    {
                        paramsIndices.push_back(IndexHandle(axisIdx));
                    }
nmostafa's avatar
nmostafa committed
713
                    else
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                    {
                        paramsIndices.push_back(paramsIVs[j++]);
                    }
                }

                // construct indices for result
                // [P_0, P_1, .. P_axis-1, I0, I1, .. I_k-1, P_axis+1, P_axis+2, .. P_n-1]
                for (auto i = 0, j = 0; i < vParams.rank() + vIndices.rank() - 1;)
                {
                    if (i == axis && indicesIVs.size() > 0)
                    {
                        resIndices.append(indicesIVs.begin(), indicesIVs.end());
                        i += indicesIVs.size();
                    }
                    else
                    {
                        resIndices.push_back(paramsIVs[j++]);
                        i++;
                    }
                }
                // Store into result
                iRes(resIndices) = iParams(paramsIndices);
            });
        });

        rewriter.replaceOp(op, {result});
740
        return matchSuccess();
nmostafa's avatar
nmostafa committed
741
    }
742

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    REWRITER(NGConvolutionOp)
    {
        auto convolOp = cast<NGConvolutionOp>(op);
        auto loc = convolOp.getLoc();
        ScopedContext scope(rewriter, loc);

        // Get operands
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
        NGRAPH_CHECK(result, "Unexpected null result in Convolution Op");
        Value* images = operands[0];
        Value* filters = operands[1];
        auto strides = convolOp.strides().getValue();
        auto padBelow = convolOp.padBelow().getValue();
        auto padAbove = convolOp.padBelow().getValue();

        for (auto value : llvm::zip(padBelow, padAbove))
        {
            auto padAttr = std::get<0>(value);
            NGRAPH_CHECK(padAttr.cast<IntegerAttr>().getInt() == 0,
                         "No support for padding in convolution op");
            padAttr = std::get<1>(value);
            NGRAPH_CHECK(padAttr.cast<IntegerAttr>().getInt() == 0,
                         "No support for padding in convolution op");
        }

        Type elemTy = images->getType().cast<MemRefType>().getElementType();

        // Let Images shape be  [N, C_IN, D_1, ... D_f]
        // Let Filters shape be [C_OUT, C_IN, F_1, ... F_f]
        // Output shape will be [N, C_OUT, R_1, ..R_f]
        //   where R_i = (AdjD_i - AdjF_i + 1) / Strides[i]
        //
        // AdjD_i is adjusted image spatial dimension after padding and dilation
        //   AdjD_i = padBelow[i] + (dilation[i] * (D_i - 1) + 1) + padAbove[i]
        //
        // AdjF_i is adjusted filters spatial dimension after dilation
        //   AdjF_i = dilation[i] * (F_i - 1) + 1
        //
        //   If no padding, padAbove/Below[i] = 0
        //   If no dilation, dilation[i] is 1
        //
        // Generate the following (currently without padding/dilation support)
        //
        //
        // for n : 0 -> N
        //   for k : 0 -> C_OUT
        //     for <r_1 .. r_f> : <0 .. 0> -> <R_1 ... R_f>
        //       //initialize result to zero
        //       Output[n, k, r_1, .. r_f] = 0;
        //
        // for n : 0 -> N
        //   for k : 0 -> C_OUT
        //     for c : 0 -> C_IN
        //       // iterate over output spatial shape
        //       for <r_1 .. r_f> : <0 .. 0> -> <R_1 ... R_f> //
        //         //compute image start inputs indices
        //         i_1 = r_1 * strides[0];
        //         ..
        //         i_f = r_f * strides[f - 1];
        //         // iterate over kernel spatial shape
        //         for <j_1 .. j_f> : <0 .. 0> -> <F_1 .. F_f>
        //           Output[n, k, r_1, .. r_f] +=
        //             Images[n, c, i_1 + j_1, .. i_f + j_f] * Filters[k, c, j_1, .. j_f]

        // TODO: With padding, we need to check (using IntegerSets) whether each spatial dim in
        // Images lie within paddings
        // If yes, we init value to zero, else load from MemRef.
        // Q: Can this be done using a map from padded tensor to  unpadded one ? Will we load zero
        // if OOB ?

        // Create view to write into result.
        MemRefView vRes(result), vImages(images), vFilters(filters);

        // Indexed Values
        IndexedValue iRes(result), iImages(images), iFilters(filters);

        // Bounds on batch size N
        ValueHandle batchLb = vImages.lb(0), batchUb = vImages.ub(0);
        // Bounds on number of filters
        ValueHandle numFiltersLb = vFilters.lb(0), numFiltersUb = vFilters.ub(0);
        // Bound on number of channels
        ValueHandle numChannelsLb = vImages.lb(1), numChannelsUb = vImages.ub(1);
        // Bounds on result spatial dimensions
        SmallVector<ValueHandle, 4> resSpatialLbs, resSpatialUbs;
        SmallVector<ValueHandle, 4> imgSpatialLbs, imgSpatialUbs;
        SmallVector<ValueHandle, 4> filtersSpatialLbs, filtersSpatialUbs;
        // Spatial rank
        unsigned spatialRank = vImages.rank() - 2;

        // Result spatial indices and bounds
        auto resSpatialIndices = makeIndexHandles(spatialRank);
        auto resSpatialIndicesPtrs = makeIndexHandlePointers(resSpatialIndices);
        SmallVector<int64_t, 4> resSteps, filtersSteps;
        for (auto i = 0; i < spatialRank; i++)
        {
            // result spatial bounds and steps
            resSpatialLbs.push_back(vRes.lb(i + 2));
            resSpatialUbs.push_back(vRes.ub(i + 2));
            resSteps.push_back(vRes.step(i + 2));
            // image spatial bounds
            imgSpatialLbs.push_back(vImages.lb(i + 2));
            imgSpatialUbs.push_back(vImages.ub(i + 2));
        }

        NGRAPH_CHECK(vImages.rank() == vFilters.rank(), "Images and Filters have unequal ranks");
        NGRAPH_CHECK(resSpatialLbs.size() == resSpatialUbs.size() &&
                         resSpatialLbs.size() == spatialRank,
                     "Results spatial dims mismatches input");

        // Filters spatial indices and bounds
        auto filtersSpatialIndices = makeIndexHandles(spatialRank);
        auto filtersSpatialIndicesPtrs = makeIndexHandlePointers(filtersSpatialIndices);

        for (auto i = 0; i < spatialRank; i++)
        {
            filtersSpatialLbs.push_back(vFilters.lb(i + 2));
            filtersSpatialUbs.push_back(vFilters.ub(i + 2));
            filtersSteps.push_back(vFilters.step(i + 2));
        }

        // Initialize output to zero
        {
            IndexHandle n, k, c;
            auto resSpatialIndices = makeIndexHandles(spatialRank);
            auto resSpatialIndicesPtrs = makeIndexHandlePointers(resSpatialIndices);

            LoopBuilder(&n, batchLb, batchUb, 1)([&] {
                LoopBuilder(&k, numFiltersLb, numFiltersUb, 1)([&] {
                    LoopNestBuilder(
                        resSpatialIndicesPtrs, resSpatialLbs, resSpatialUbs, resSteps)([&] {
                        SmallVector<IndexHandle, 4> resIndices;
                        // Result indices
                        resIndices.push_back(n);
                        resIndices.push_back(k);
                        resIndices.insert(
                            resIndices.end(), resSpatialIndices.begin(), resSpatialIndices.end());
                        ValueHandle zero = createZeroConstant(elemTy);
                        iRes(resIndices) = zero;
                    });
                });
            });
        }

        IndexHandle n, k, c;
        // Convolution loop
        LoopBuilder(&n, batchLb, batchUb, 1)([&] {
            // Number of filters loop
            LoopBuilder(&k, numFiltersLb, numFiltersUb, 1)([&] {
                // Channels loop
                LoopBuilder(&c, numChannelsLb, numChannelsUb, 1)([&] {
                    // Results loop
                    LoopNestBuilder(
                        resSpatialIndicesPtrs, resSpatialLbs, resSpatialUbs, resSteps)([&] {
                        // Compute image start indices
                        SmallVector<IndexHandle, 4> imgStartIndices;
                        for (auto i = 0; i < spatialRank; i++)
                        {
                            IntegerAttr iAttr = strides[i].cast<IntegerAttr>();
                            auto stride = intrinsics::constant_index(iAttr.getInt());
                            imgStartIndices.push_back(IndexHandle(resSpatialIndices[i] * stride));
                        }
                        SmallVector<IndexHandle, 4> resIndices;
                        // Result indices
                        resIndices.push_back(n);
                        resIndices.push_back(k);
                        resIndices.insert(
                            resIndices.end(), resSpatialIndices.begin(), resSpatialIndices.end());
                        // Filters spatial loop
                        LoopNestBuilder(filtersSpatialIndicesPtrs,
                                        filtersSpatialLbs,
                                        filtersSpatialUbs,
                                        filtersSteps)([&] {
                            SmallVector<IndexHandle, 4> imgIndices, filtersIndices;
                            // Image indices
                            imgIndices.push_back(n);
                            imgIndices.push_back(c);
                            for (auto i = 0; i < spatialRank; i++)
                            {
                                imgIndices.push_back(
                                    IndexHandle(imgStartIndices[i] + filtersSpatialIndices[i]));
                            }
                            // Filter indices
                            filtersIndices.push_back(k);
                            filtersIndices.push_back(c);
                            filtersIndices.insert(filtersIndices.end(),
                                                  filtersSpatialIndices.begin(),
                                                  filtersSpatialIndices.end());

                            iRes(resIndices) =
                                iRes(resIndices) + (iImages(imgIndices) * iFilters(filtersIndices));
                        });
                    });
                });
            });
        });

        rewriter.replaceOp(op, {result});
        return matchSuccess();
    }

943
    REWRITER(NGReturnOp)
nmostafa's avatar
nmostafa committed
944
    {
945
        pass.insertDeallocs(rewriter);
946
        rewriter.replaceOpWithNewOp<ReturnOp>(op);
nmostafa's avatar
nmostafa committed
947 948
        return matchSuccess();
    }
949

nmostafa's avatar
nmostafa committed
950
#undef REWRITER
nmostafa's avatar
nmostafa committed
951
    /// End of pattern matchers
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    template <typename OP>
    void lower_unary_elementwise(Operation* op,
                                 ArrayRef<Value*> operands,
                                 PatternRewriter& rewriter,
                                 DialectLoweringPass& pass)
    {
        auto loc = cast<OP>(op).getLoc();

        auto result = pass.buildOutputDefs(op, rewriter)[0];
        NGRAPH_CHECK(result->getType().isa<MemRefType>());
        // Note that builder's current function is still the original function body.
        // use getBlock to get the new block instead.

        // get new operands
        Value* lhs = operands[0];

        ScopedContext scope(rewriter, loc);
        // Views
        MemRefView vRes(result), vLHS(lhs);
        // Index Values
        IndexedValue iRes(result), iLHS(lhs);
        // Bounds Index Handles
        auto lbs = vLHS.getLbs();
        auto ubs = vLHS.getUbs();
        // Loop induction vars
977 978
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
979 980 981 982 983 984 985 986 987 988
        // Steps
        auto steps = vLHS.getSteps();

        NGRAPH_CHECK(lhs->getType().isa<MemRefType>());
        Type elemTy = lhs->getType().cast<MemRefType>().getElementType();

        LoopNestBuilder(pivs, lbs, ubs, steps)([&] {
            ValueHandle val = iLHS(ivs);
            if (isa<NGNegOp>(op))
            {
989 990
                ValueHandle zero = createZeroConstant(elemTy);
                iRes(ivs) = zero - val;
991 992 993 994 995 996 997 998 999 1000
            }
            else
            {
                NGRAPH_CHECK(false, "Unsupported op");
            }
        });

        rewriter.replaceOp(op, {result});
    }

1001 1002 1003 1004
    template <typename OP>
    void lower_binary_elementwise(Operation* op,
                                  ArrayRef<Value*> operands,
                                  PatternRewriter& rewriter,
1005
                                  DialectLoweringPass& pass)
1006 1007
    {
        auto loc = cast<OP>(op).getLoc();
1008
        auto result = pass.buildOutputDefs(op, rewriter)[0];
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        NGRAPH_CHECK(result->getType().isa<MemRefType>());
        // get new operands
        Value* lhs = operands[0];
        Value* rhs = operands[1];

        ScopedContext scope(rewriter, loc);
        // Views
        MemRefView vRes(result), vLHS(lhs), vRHS(rhs);
        // Index Values
        IndexedValue iRes(result), iLHS(lhs), iRHS(rhs);
        // Bounds Index Handles
        auto lbs = vLHS.getLbs();
        auto ubs = vLHS.getUbs();
        // Loop induction vars
1023 1024
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        // Steps
        auto steps = vLHS.getSteps();
        LoopNestBuilder(pivs, lbs, ubs, steps)(
            // single stmt body
            [&] {
                if (isa<NGAddOp>(op))
                {
                    iRes(ivs) = iLHS(ivs) + iRHS(ivs);
                }
                else if (isa<NGSubOp>(op))
                {
                    iRes(ivs) = iLHS(ivs) - iRHS(ivs);
                }
                else if (isa<NGMulOp>(op))
                {
                    iRes(ivs) = iLHS(ivs) * iRHS(ivs);
                }
                else if (isa<NGDivOp>(op))
                {
                    iRes(ivs) = iLHS(ivs) / iRHS(ivs);
                }
                else if (isa<NGGreaterOp>(op))
                {
                    iRes(ivs) = ValueHandle(iLHS(ivs)) > ValueHandle(iRHS(ivs));
                }
                else if (isa<NGLessOp>(op))
                {
                    iRes(ivs) = ValueHandle(iLHS(ivs)) < ValueHandle(iRHS(ivs));
                }
                else if (isa<NGMaxOp>(op))
                {
                    iRes(ivs) =
                        edsc::intrinsics::select(ValueHandle(iLHS(ivs)) > ValueHandle(iRHS(ivs)),
                                                 ValueHandle(iLHS(ivs)),
                                                 ValueHandle(iRHS(ivs)));
                }
                else if (isa<NGMinOp>(op))
                {
                    iRes(ivs) =
                        edsc::intrinsics::select(ValueHandle(iLHS(ivs)) < ValueHandle(iRHS(ivs)),
                                                 ValueHandle(iLHS(ivs)),
                                                 ValueHandle(iRHS(ivs)));
                }
                else
                {
                    NGRAPH_CHECK(false, "Unsupported op");
                }
            });
        rewriter.replaceOp(op, {result});
    }

1076
    template <typename RedOp>
1077 1078 1079
    void lowerIndexReduction(Operation* op,
                             ArrayRef<Value*> operands,
                             PatternRewriter& rewriter,
1080
                             DialectLoweringPass& pass)
nmostafa's avatar
nmostafa committed
1081
    {
1082 1083 1084 1085 1086 1087
        static_assert(std::is_same<RedOp, NGArgMinRedOp>() || std::is_same<RedOp, NGArgMaxRedOp>(),
                      "Template parameter is not supported by lowerIndexReduction");

        RedOp redOp = cast<RedOp>(op);
        auto loc = redOp.getLoc();
        auto axesAttr = redOp.axes();
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

        NGRAPH_CHECK(axesAttr.size() == 1, "Index Reduction op should have one reduction axis");
        Attribute axisAttr = *axesAttr.begin();
        unsigned axis = axisAttr.dyn_cast<IntegerAttr>().getInt();

        NGRAPH_CHECK(operands.size() == 1 && operands[0] != nullptr,
                     "Expected one non-null operand in Index Reduction op");

        // Retrieve/generate Values for operands and result.
        ScopedContext scope(rewriter, loc);
        Value* arg = operands[0];
1099

1100
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
1101 1102 1103 1104

        // Views
        MemRefView vRes(result), vArg(arg);
        // Index Values
1105 1106
        StdIndexedValue iRes(result), stdArg(arg);
        IndexedValue affineArg(arg);
1107 1108 1109 1110 1111
        // Bounds Index Handles
        auto resLbs = vRes.getLbs();
        auto resUbs = vRes.getUbs();
        auto argLbs = vArg.getLbs();
        auto argUbs = vArg.getUbs();
1112 1113 1114

        Type resTy = result->getType().cast<MemRefType>().getElementType();
        // Generate loop nest that initializes result to lower bound of the axis to be reduced.
1115
        {
1116 1117
            auto ivs = makeIndexHandles(vRes.rank());
            auto pivs = makeIndexHandlePointers(ivs);
1118 1119
            auto steps = vRes.getSteps();
            auto initVal = vArg.lb(axis);
1120 1121 1122
            LoopNestBuilder(pivs, resLbs, resUbs, steps)(
                [&] { iRes(ivs) = ValueHandle::create<IndexCastOp>(initVal, resTy); });
        }
1123

1124 1125
        // Generate loop nest that computes the actual index reduction.
        {
1126 1127
            auto allIVs = makeIndexHandles(vArg.rank());
            auto pAllIVs = makeIndexHandlePointers(allIVs);
1128 1129
            auto steps = vArg.getSteps();
            SmallVector<IndexHandle, 8> nonRedIVs;
1130

1131 1132 1133
            Type resTy = result->getType().cast<MemRefType>().getElementType();
            NGRAPH_CHECK(resTy.isa<IntegerType>(),
                         "Expected integer result type in index reduction");
1134

1135 1136
            // iterate over all argument dimensions
            LoopNestBuilder(pAllIVs, argLbs, argUbs, steps)([&] {
nmostafa's avatar
nmostafa committed
1137 1138 1139 1140 1141 1142
                // build a list of non-reduction IVs
                for (auto i = 0; i < vArg.rank(); i++)
                {
                    if (i != axis)
                        nonRedIVs.push_back(allIVs[i]);
                }
1143 1144 1145 1146 1147 1148

                // Load current min index with integer data type and convert it to index data type.
                ValueHandle currRedIdx = ValueHandle::create<IndexCastOp>(
                    (ValueHandle)iRes(nonRedIVs), IndexType::get(resTy.getContext()));

                // Build list of IVs including current min index.
nmostafa's avatar
nmostafa committed
1149
                auto tempIVs = allIVs;
1150
                tempIVs[axis] = currRedIdx;
1151

1152 1153 1154 1155
                // Select the min/max value and cast it back to integer type before storing it.
                ValueHandle newRedIdx =
                    std::is_same<RedOp, NGArgMinRedOp>()
                        ? edsc::intrinsics::select(
1156
                              affineArg(allIVs) < stdArg(tempIVs), allIVs[axis], currRedIdx)
1157
                        : edsc::intrinsics::select(
1158
                              stdArg(tempIVs) < affineArg(allIVs), allIVs[axis], currRedIdx);
1159 1160 1161 1162 1163 1164 1165

                iRes(nonRedIVs) = ValueHandle::create<IndexCastOp>(newRedIdx, resTy);
            });
        }

        rewriter.replaceOp(op, result);
    }
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

    ValueHandle createZeroConstant(mlir::Type type)
    {
        if (auto floatTy = type.dyn_cast<FloatType>())
        {
            if (floatTy.isF32())
            {
                return intrinsics::constant_float(llvm::APFloat(0.0f), floatTy);
            }
            else if (floatTy.isF64())
            {
                return intrinsics::constant_float(llvm::APFloat(0.0), floatTy);
            }
            else
            {
                NGRAPH_UNREACHABLE("Unsupported floating-point precision");
            }
        }
        else if (auto intTy = type.dyn_cast<IntegerType>())
        {
            return intrinsics::constant_int(0, intTy.getWidth());
        }
        NGRAPH_UNREACHABLE("Unsupported type");
    }
1190 1191
}

1192
namespace mlir
1193
{
1194
    std::unique_ptr<Pass> createDialectLoweringPass(ngraph::runtime::ngmlir::MLIRCompiler* compiler)
1195
    {
1196
        return std::make_unique<DialectLoweringPass>(*compiler);
1197
    }
1198
} // namespace mlir