lowerer.cpp 54.1 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

22 23
#include "dialect/ops.hpp"
#include "dialect/type.hpp"
24 25
#include "ngraph/assertion.hpp"

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

#include <map>

38 39 40
#define PASS_NAME "convert-ngraph-to-affine"
#define DEBUG_TYPE PASS_NAME

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

    class DialectLoweringPass;
54

55 56 57 58 59 60 61 62
    /// 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)
63
            , pass(pass){};
64 65 66 67

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

71
// Conversion classes declarations
72
#define MLIR_OP(OP, INPLACE)                                                                       \
73 74 75 76 77 78 79 80 81 82
    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,                              \
83
                                           ConversionPatternRewriter& rewriter) const override;    \
84 85
    };

86 87
#include "op_lowerers.inc"

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    // 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)
109
            {
110
                if (failed(converter.convertSignatureArg(i, type.getInput(i), result)))
111
                {
112
                    return matchFailure();
113 114
                }
            }
115

116 117
            auto funcTypeResults = type.getResults();
            if (!funcTypeResults.empty())
118
            {
119 120 121 122 123 124
                // Convert the original function results.
                SmallVector<Type, 4> convertedResults;
                if (failed(converter.convertTypes(funcTypeResults, convertedResults)))
                {
                    return matchFailure();
                }
125

126 127 128
                // Add result types as input args without mapping
                result.addInputs(convertedResults);
            }
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

            // 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
146
    // Helpers
147 148 149 150
    template <typename RedOp>
    void lowerIndexReduction(Operation* op,
                             ArrayRef<Value*> operands,
                             PatternRewriter& rewriter,
151
                             DialectLoweringPass& pass);
nmostafa's avatar
nmostafa committed
152

153
    template <typename OP>
154 155 156 157
    void lowerBinaryElementwise(Operation* op,
                                ArrayRef<Value*> operands,
                                PatternRewriter& rewriter,
                                DialectLoweringPass& pass);
158

159
    template <typename OP>
160 161 162 163
    void lowerUnaryElementwise(Operation* op,
                               ArrayRef<Value*> operands,
                               PatternRewriter& rewriter,
                               DialectLoweringPass& pass);
164

165 166
    ValueHandle createZeroConstant(mlir::Type type);

167 168
    /// Conversion from types in the nGraph dialect to the Standard dialect.
    class NGraphTypeConverter : public TypeConverter
169 170
    {
    public:
171 172
        NGraphTypeConverter()
            : TypeConverter()
173 174 175 176 177 178 179 180 181 182 183
        {
        }

        Type convertType(Type t) override;
    };

    /// Dialect Lowering Pass to affine ops
    class DialectLoweringPass : public ModulePass<DialectLoweringPass>
    {
    public:
        void runOnModule() override;
184

185
        SmallVector<Value*, 4> buildOutputDefs(Operation* op, PatternRewriter& rewriter);
186
        Value* createTempTensor(Type type, PatternRewriter& rewriter);
187

188 189 190
        /// Inserts dealloc Ops for each temporary allocated by AllocOp
        void insertDeallocs(PatternRewriter& rewriter);

191
        NGraphTypeConverter& getTypeConverter() { return typeConverter; }
192
    private:
193 194 195
        /// Collect a set of patterns to convert from the nGraph dialect to Affine dialect.
        void populateNGraphToAffineConversionPatterns(OwningRewritePatternList& patterns);

196
        void findOutputValues();
197
        void insertNoAliasArgAttrs();
198 199

    private:
200
        NGraphTypeConverter typeConverter;
201
        // List of temporary memrefs to deallocate at end of function
202
        SmallVector<Value*, 4> memRefsToDealloc;
203 204 205 206 207 208

        // Ops maybe assigned mem-refs in previous memory optimization passes.
        // Track pre-assigned buffers  for each Value and re-use it if one is available.
        using IdToMemRefMap = std::unordered_map<unsigned, Value*>;
        IdToMemRefMap m_id_to_memref;

209 210
        // TODO: Workaround for findOutputValues and buildOutputDefs. See NGCPU-470.
        std::string funcName;
211 212 213 214
    };

    void DialectLoweringPass::runOnModule()
    {
215 216 217
        // Create type converter and initialize conversion patterns.
        NGraphTypeConverter converter;
        OwningRewritePatternList patterns;
218

219 220 221 222
        populateNGraphToAffineConversionPatterns(patterns);

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

224
        target.addLegalDialect<AffineOpsDialect, StandardOpsDialect>();
225
        target.addLegalOp<ModuleOp, ModuleTerminatorOp>();
226 227 228 229
        target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) {
            // FuncOp is legal only if types have been converted to Std types.
            return typeConverter.isSignatureLegal(op.getType());
        });
230

231 232 233
        // Gather functions to be processed. Note that new functions will be added to module as part
        // of the function signature conversion so we have to collect the original ones before hand.
        SmallVector<FuncOp, 2> origFuncOps(getModule().getOps<FuncOp>());
234

235
        for (auto origFunc : origFuncOps)
236
        {
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            // TODO: Workaround for findOutputValues and buildOutputDefs. See NGCPU-470.
            funcName = origFunc.getName();

            // 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();

            // NOTE: Function signature conversion creates a new FuncOp that is inserted in the
            // module. References the original FuncOp are no longer valid after this point.
            if (failed(applyFullConversion(origFunc, target, std::move(patterns), &converter)))
            {
                emitError(mlir::UnknownLoc::get(&getContext()), "Error lowering nGraph dialect\n");
                signalPassFailure();
            }
nmostafa's avatar
nmostafa committed
252

253 254 255 256
            // TODO: Encode no alias attribute as part of the function signature conversion or as a
            // separate rewrite pattern. Retrieve new function after signature conversion.
            insertNoAliasArgAttrs();
        }
257 258
    }

259 260 261
    void DialectLoweringPass::populateNGraphToAffineConversionPatterns(
        OwningRewritePatternList& patterns)
    {
262 263
#define MLIR_OP(OP, INPLACE) OP##Conversion,
#define MLIR_LAST_OP(OP, INPLACE) OP##Conversion
264
        patterns.insert<
265
#include "op_lowerers.inc"
266
            >(&getContext(), *this);
267 268 269

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

272 273
    void DialectLoweringPass::findOutputValues()
    {
274 275 276
        FuncOp f = getModule().lookupSymbol<mlir::FuncOp>(funcName);
        NGRAPH_CHECK(f, "FuncOp '" + funcName + "' not found");

277 278
        SmallVector<Value*, 4> outputList;
        unsigned outputCount = 0;
279
        unsigned inputCount = f.getType().getNumInputs();
280 281
        // we find out output values by looking at returned values
        // any return should return all outputs of the subgraph
282
        f.walk([this, &outputCount, inputCount](NGReturnOp ret) {
283 284
            for (unsigned i = 0; i < ret.getNumOperands(); i++)
            {
285
                // annotate instructions defining outputs with the arg idx of the output
286 287
                auto outputValue = ret.getOperand(i);
                auto op = outputValue->getDefiningOp();
288 289 290 291

                op->setAttr(
                    "graphOutputIdx",
                    mlir::IntegerAttr::get(IntegerType::get(32, op->getContext()), i + inputCount));
292
            }
293 294
            NGRAPH_CHECK(outputCount == 0 || outputCount == ret.getNumOperands(),
                         "Inconsistent returns in function");
295 296 297
        });
    }

Nagy Mostafa's avatar
Nagy Mostafa committed
298
    SmallVector<Value*, 4> DialectLoweringPass::buildOutputDefs(Operation* op,
299
                                                                PatternRewriter& rewriter)
Nagy Mostafa's avatar
Nagy Mostafa committed
300
    {
301 302 303
        FuncOp f = getModule().lookupSymbol<mlir::FuncOp>(funcName);
        NGRAPH_CHECK(f, "FuncOp '" + funcName + "' not found");

Nagy Mostafa's avatar
Nagy Mostafa committed
304 305 306
        SmallVector<Value*, 4> newResults;
        for (auto origResult : op->getResults())
        {
307
            // find output arg if this operation produces any sub-graph outputs
308
            if (IntegerAttr attr = op->getAttrOfType<IntegerAttr>("graphOutputIdx"))
Nagy Mostafa's avatar
Nagy Mostafa committed
309
            {
310 311 312
                mlir::Block* entryBlock = &*(f.begin());
                unsigned argId = (unsigned)attr.getInt();
                newResults.push_back(entryBlock->getArgument(argId));
Nagy Mostafa's avatar
Nagy Mostafa committed
313 314 315
            }
            else
            {
316
                auto tensorType = origResult->getType().cast<NGTensorType>();
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
                Value* newResult;
                Attribute bufferIdAttr = getBufferId(op);
                if (!bufferIdAttr)
                {
                    // Allocate new memref
                    newResult = createTempTensor(typeConverter.convertType(tensorType), rewriter);
                }
                else
                {
                    unsigned bufferId = bufferIdAttr.cast<IntegerAttr>().getInt();
                    // Re-use a memref if it exist, else create a new one and update map
                    IdToMemRefMap::iterator it = m_id_to_memref.find(bufferId);
                    if (it == m_id_to_memref.end())
                    {
                        // create a new memref
                        newResult =
                            createTempTensor(typeConverter.convertType(tensorType), rewriter);
                        m_id_to_memref[bufferId] = newResult;
                    }
                    else
                    {
                        newResult = it->second;
                    }
                }
Nagy Mostafa's avatar
Nagy Mostafa committed
341 342 343 344 345 346
                newResults.push_back(newResult);
            }
        }
        return newResults;
    }

347
    Value* DialectLoweringPass::createTempTensor(Type type, PatternRewriter& rewriter)
348
    {
349 350 351 352 353
        MemRefType memRefType = type.cast<MemRefType>();

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

        Value* alloc = rewriter.create<mlir::AllocOp>(rewriter.getUnknownLoc(), memRefType);
354
        memRefsToDealloc.push_back(alloc);
355 356 357 358

        // TODO:
        // Enable dynamic memref allocation via call-back to nGraph allocator
        // We should create a list of Values representing each dynamic dim
359 360
        // The values would be computed based on the shape of the input to the ng op we are
        // lowering.
361 362
        // 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.
363 364
        // This is better be done via std.AllocOp but we need to make it hookable to nGraph
        // allocator call-back.
365 366

        return alloc;
367 368
    }

369 370 371 372
    /// Add llvm.noalias attribute to all the memref function arguments. We know that this is safe
    /// by nGraph op semantics.
    void DialectLoweringPass::insertNoAliasArgAttrs()
    {
373 374 375
        FuncOp func = getModule().lookupSymbol<mlir::FuncOp>(funcName);
        NGRAPH_CHECK(func, "FuncOp '" + funcName + "' not found");

376
        unsigned int argIdx = 0;
377
        for (auto* arg : func.getArguments())
378 379 380
        {
            if (arg->getType().isa<MemRefType>())
            {
381
                func.setArgAttr(argIdx, "llvm.noalias", BoolAttr::get(true, &getContext()));
382 383 384 385 386 387
            }

            ++argIdx;
        }
    }

388 389
    void DialectLoweringPass::insertDeallocs(PatternRewriter& rewriter)
    {
390
        for (auto value : memRefsToDealloc)
391 392 393 394 395
        {
            rewriter.create<DeallocOp>(rewriter.getUnknownLoc(), value);
        }
    }

396
    // NGDialect converters
397
    Type NGraphTypeConverter::convertType(Type type)
Nagy Mostafa's avatar
Nagy Mostafa committed
398
    {
399
        // We may need to refactor this code to a external utility if type conversion is needed
400
        // outside of the lowering context since NGraphTypeConverter is private.
401

402
        if (auto tensorType = type.dyn_cast<NGTensorType>())
Nagy Mostafa's avatar
Nagy Mostafa committed
403
        {
404 405
            // Convert NGTensorType to Std MemRefType directly instead of going to Std TensorType.
            // This may change in the future.
406 407
            return MemRefType::get(tensorType.getShape(),
                                   convertType(tensorType.getElementType()),
408 409
                                   {/* no map used */},
                                   0);
Nagy Mostafa's avatar
Nagy Mostafa committed
410
        }
411
        if (auto floatType = type.dyn_cast<NGFloatType>())
412
        {
413
            // Float types are already std type.
414
            return floatType;
415
        }
416
        if (auto intType = type.dyn_cast<NGIntegerType>())
417
        {
418
            return mlir::IntegerType::get(intType.getWidth(), intType.getContext());
419
        }
420
        if (auto boolType = type.dyn_cast<NGBoolType>())
421
        {
422
            return mlir::IntegerType::get(1 /* width */, boolType.getContext());
423
        }
424

425 426
        // Do not assert/NGRAPH_CHECK here. Type convertion infra expects `convertType` to return
        // the input type if the type is not supported.
427
        return type;
Nagy Mostafa's avatar
Nagy Mostafa committed
428 429
    }

430
#define REWRITER(OP)                                                                               \
431
    PatternMatchResult OP##Conversion::matchAndRewrite(                                            \
432
        Operation* op, ArrayRef<Value*> operands, ConversionPatternRewriter& rewriter) const
433 434

    REWRITER(NGAddOp)
435
    {
436
        lowerBinaryElementwise<mlir::NGAddOp>(op, operands, rewriter, pass);
437 438
        return matchSuccess();
    }
439

440
    REWRITER(NGSubOp)
441
    {
442
        lowerBinaryElementwise<mlir::NGSubOp>(op, operands, rewriter, pass);
443 444
        return matchSuccess();
    }
445

446 447
    REWRITER(NGMulOp)
    {
448
        lowerBinaryElementwise<mlir::NGMulOp>(op, operands, rewriter, pass);
449 450
        return matchSuccess();
    }
451

452 453
    REWRITER(NGDivOp)
    {
454
        lowerBinaryElementwise<mlir::NGDivOp>(op, operands, rewriter, pass);
455 456
        return matchSuccess();
    }
457

458 459
    REWRITER(NGGreaterOp)
    {
460
        lowerBinaryElementwise<mlir::NGGreaterOp>(op, operands, rewriter, pass);
461 462 463 464 465
        return matchSuccess();
    }

    REWRITER(NGLessOp)
    {
466
        lowerBinaryElementwise<mlir::NGLessOp>(op, operands, rewriter, pass);
467 468
        return matchSuccess();
    }
469

470 471
    REWRITER(NGMaxOp)
    {
472
        lowerBinaryElementwise<mlir::NGMaxOp>(op, operands, rewriter, pass);
473 474 475 476 477
        return matchSuccess();
    }

    REWRITER(NGMinOp)
    {
478
        lowerBinaryElementwise<mlir::NGMinOp>(op, operands, rewriter, pass);
479
        return matchSuccess();
480 481
    }

482 483
    REWRITER(NGArgMaxRedOp)
    {
484
        lowerIndexReduction<mlir::NGArgMaxRedOp>(op, operands, rewriter, pass);
485 486 487 488 489
        return matchSuccess();
    }

    REWRITER(NGArgMinRedOp)
    {
490
        lowerIndexReduction<mlir::NGArgMinRedOp>(op, operands, rewriter, pass);
491
        return matchSuccess();
492 493
    }

494 495 496 497 498
    // Relu
    REWRITER(NGReluOp)
    {
        auto loc = cast<NGReluOp>(op).getLoc();

499
        auto result = pass.buildOutputDefs(op, rewriter)[0];
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        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
516 517
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
518 519 520 521 522 523 524 525
        // 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);
526 527
            ValueHandle zero = createZeroConstant(elemTy);
            iRes(ivs) = intrinsics::select(val > zero, val, zero);
528 529 530 531 532 533
        });

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

534 535 536
    // Negative
    REWRITER(NGNegOp)
    {
537
        lowerUnaryElementwise<mlir::NGNegOp>(op, operands, rewriter, pass);
538 539 540
        return matchSuccess();
    }

541
    REWRITER(NGDotOp)
542
    {
543 544
        auto dot = cast<NGDotOp>(op);
        auto loc = dot.getLoc();
545 546 547 548 549

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

553 554 555 556 557 558
        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");
559

560 561
        Type elemTy = resultTy.getElementType();
        NGRAPH_CHECK(elemTy == lhsTy.getElementType() && elemTy == rhsTy.getElementType(),
562
                     "Types mismatch in DotOp");
563 564 565 566 567 568 569 570

        // 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.

571
        MemRefView vRes(result), vLhs(lhs), vRhs(rhs);
572

573
        NGRAPH_CHECK(vLhs.rank() == 2 && vRhs.rank() == 2 && vRes.rank() == 2,
574
                     "Dot operation is only supported for 2D tensors");
575

576 577 578 579
        // 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.
580
        IndexHandle n, m, k;
581 582 583 584 585 586
        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);
587

588
        // Constants and indexed values to be used inside the loop nest.
589 590 591
        IndexedValue iRes(result), iLhs(lhs), iRhs(rhs);
        ValueHandle zeroInit(rewriter.create<ConstantOp>(loc, rewriter.getZeroAttr(elemTy)));

592 593 594 595 596
        {
            IndexHandle n, k;
            LoopBuilder(&n, nLb, nUb, nStep)(
                [&] { LoopBuilder(&k, kLb, kUb, kStep)([&] { iRes(n, k) = zeroInit; }); });
        }
597
        LoopBuilder(&n, nLb, nUb, nStep)([&] {
598 599
            LoopBuilder(&m, mLb, mUb, mStep)([&] {
                LoopBuilder(&k, kLb, kUb, kStep)([&] { iRes(n, k) += iLhs(n, m) * iRhs(m, k); });
600 601 602
            });
        });

603
        rewriter.replaceOp(op, {result});
Adam Procter's avatar
Adam Procter committed
604 605 606 607 608 609 610 611 612 613 614

        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.
615
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
Adam Procter's avatar
Adam Procter committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        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});
682

683
        return matchSuccess();
nmostafa's avatar
nmostafa committed
684
    }
685

686
    REWRITER(NGGatherOp)
nmostafa's avatar
nmostafa committed
687
    {
688 689 690 691 692
        auto gatherOp = cast<NGGatherOp>(op);
        auto loc = gatherOp.getLoc();
        ScopedContext scope(rewriter, loc);

        // Get operands
693
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
694 695 696 697 698 699 700 701 702
        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
703 704
        IndexedValue iRes(result), iIndices(indices);
        StdIndexedValue iParams(params);
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

        // 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
720 721 722 723
        NGRAPH_CHECK(paramsLbs.size() == vParams.rank() - 1 &&
                         paramsUbs.size() == paramsLbs.size() &&
                         paramsSteps.size() == paramsLbs.size(),
                     "Incorrect loop nest bounds size for gather params");
724

725 726
        paramsIVs = makeIndexHandles(vParams.rank() - 1);
        paramsIVPtrs = makeIndexHandlePointers(paramsIVs);
727 728 729 730

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

732 733
        auto indicesIVs = makeIndexHandles(vIndices.rank());
        auto indicesIVPtrs = makeIndexHandlePointers(indicesIVs);
734 735 736 737 738 739 740 741 742 743

        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
744 745
        // indices loops
        // for I_0:0 -> indices.dim[0]
746
        // ...
747 748 749 750 751
        //   for I_(M-1):0 -> indices.dim[M-1]
        //     params loops
        //     for P_0: 0 -> params.dim[0]
        //       for P_1: 0 -> params.dim[1]
        //         for P_2: 0 -> params.dim[2]
752
        // ...
753 754
        //           for P_(A-1):0 -> params.dim[A-1]
        //             for P_(A+1):0 -> params.dim[A+1]
755
        // ...
756
        //               for P_(N-1):0 -> params.dim[N-1]
nmostafa's avatar
nmostafa committed
757
        //                 res[P_0, P_1, .. P_(A-1), I_0, .., I_(M-1), P_(A+1), ... P_(N-1)] =
758 759
        //                   params[P_0, P_1, .. P_(A-1), indices[I_0, .., I_(M-1)],
        //                          P_(A+1), ... P_(N-1)];
760

761 762 763 764 765 766
        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());

            LoopNestBuilder(paramsIVPtrs, paramsLbs, paramsUbs, paramsSteps)([&] {
767 768 769 770 771 772 773 774
                // 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
775
                    else
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
                    {
                        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});
802
        return matchSuccess();
nmostafa's avatar
nmostafa committed
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
    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();

        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]

859 860 861 862 863 864 865
        // With padding, we check (using IntegerSets) whether each spatial dim in Images lie inside
        // non-padded spatial region. If true, we perform the computation:
        //
        //         for <j_1 .. j_f> : <0 .. 0> -> <F_1 .. F_f>
        //         if(indices in non-padded region):
        //           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]
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889

        // 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;
890 891 892
        SmallVector<int, 4> padBelowIntValues;
        bool withPadding = false;

893 894 895 896 897 898 899 900 901
        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));
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

            // Check if we have any padding and collect pad values
            IntegerAttr iAttr = padBelow[i].cast<IntegerAttr>();
            int padValue = iAttr.getInt();
            if (padValue)
            {
                withPadding = true;
            }
            padBelowIntValues.push_back(padValue);

            iAttr = padAbove[i].cast<IntegerAttr>();
            padValue = iAttr.getInt();
            if (padValue)
            {
                withPadding = true;
            }
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
        }

        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));
        }

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
        IntegerSet nonPaddedRange;
        if (withPadding)
        {
            // Create affine expressions and IntegerSet
            // IntegerSet (d0, d1, .. d_N-1)[LB_0, LB_1, .. LB_N-1, UB_0, UB_1, .. UB_N-1], where
            // for each dim:
            //   (d_dim - padBelow[dim] - LB_dim >= 0),
            //   (padBelow[dim] + UB_dim - d_dim - 1 >= 0)
            SmallVector<AffineExpr, 4> affineExprs;
            // Bool to indicate if expr is equality or inequality
            SmallVector<bool, 4> isEq;

            for (unsigned dim = 0; dim < spatialRank; dim++)
            {
                // i_dim
                auto dimExpr = rewriter.getAffineDimExpr(dim);
                auto imgLbExpr = rewriter.getAffineSymbolExpr(dim);

                // expr1 : i_dim - padBelow[dim] - imgLB >= 0
                auto padBelowExpr = rewriter.getAffineConstantExpr(padBelowIntValues[dim]);
                affineExprs.push_back(dimExpr - padBelowExpr - imgLbExpr);
                isEq.push_back(false);

                // expr2: padBelow[dim] + imgUB - i_dim - 1 >= 0
                auto imgUbExpr = rewriter.getAffineSymbolExpr(spatialRank + dim);
                auto oneExpr = rewriter.getAffineConstantExpr(1);
                affineExprs.push_back(padBelowExpr + imgUbExpr - dimExpr - oneExpr);
                isEq.push_back(false);
            }

            NGRAPH_CHECK(affineExprs.size() == isEq.size() && isEq.size() == 2 * spatialRank,
                         "Invalid number of expressions in the IntegerSet");
            nonPaddedRange =
                rewriter.getIntegerSet(spatialRank, 2 * spatialRank, affineExprs, isEq);
        }

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
        // 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
1026 1027
                            // Here we compute the virtual start index into the padded image.

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
                            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());

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 1076 1077 1078 1079 1080 1081
                            if (withPadding)
                            {
                                // if args : img dims, img lbs, img ubs
                                SmallVector<IndexHandle, 4>::iterator it = imgIndices.begin();
                                std::advance(it, 2);
                                SmallVector<Value*, 4> affineIfArgs(it, imgIndices.end());
                                affineIfArgs.insert(
                                    affineIfArgs.end(), imgSpatialLbs.begin(), imgSpatialLbs.end());
                                affineIfArgs.insert(
                                    affineIfArgs.end(), imgSpatialUbs.begin(), imgSpatialUbs.end());

                                auto affineIfOp =
                                    rewriter.create<AffineIfOp>(rewriter.getUnknownLoc(),
                                                                nonPaddedRange,
                                                                affineIfArgs,
                                                                /*withElseRegion=*/false);
                                {
                                    auto rewriter = affineIfOp.getThenBodyBuilder();
                                    ScopedContext scope(rewriter, loc);
                                    // We must subtract pad below before img load, since the
                                    // physical image is not padded
                                    SmallVector<IndexHandle, 4> adjustedImgIndices;
                                    adjustedImgIndices.push_back(n);
                                    adjustedImgIndices.push_back(c);
                                    for (auto i = 0; i < spatialRank; i++)
                                    {
                                        adjustedImgIndices.push_back(IndexHandle(
                                            imgIndices[2 + i] -
                                            intrinsics::constant_index(padBelowIntValues[i])));
                                    }
                                    iRes(resIndices) =
                                        iRes(resIndices) +
                                        (iImages(adjustedImgIndices) * iFilters(filtersIndices));
                                }
                            }
                            else
                            {
                                iRes(resIndices) = iRes(resIndices) +
                                                   (iImages(imgIndices) * iFilters(filtersIndices));
                            }
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
                        });
                    });
                });
            });
        });

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

1092
    REWRITER(NGReturnOp)
nmostafa's avatar
nmostafa committed
1093
    {
1094
        pass.insertDeallocs(rewriter);
1095
        rewriter.replaceOpWithNewOp<ReturnOp>(op);
nmostafa's avatar
nmostafa committed
1096 1097
        return matchSuccess();
    }
1098

nmostafa's avatar
nmostafa committed
1099
#undef REWRITER
nmostafa's avatar
nmostafa committed
1100
    /// End of pattern matchers
1101
    template <typename OP>
1102 1103 1104 1105
    void lowerUnaryElementwise(Operation* op,
                               ArrayRef<Value*> operands,
                               PatternRewriter& rewriter,
                               DialectLoweringPass& pass)
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    {
        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
1126 1127
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        // 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))
            {
1138 1139
                ValueHandle zero = createZeroConstant(elemTy);
                iRes(ivs) = zero - val;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
            }
            else
            {
                NGRAPH_CHECK(false, "Unsupported op");
            }
        });

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

1150
    template <typename OP>
1151 1152 1153 1154
    void lowerBinaryElementwise(Operation* op,
                                ArrayRef<Value*> operands,
                                PatternRewriter& rewriter,
                                DialectLoweringPass& pass)
1155 1156
    {
        auto loc = cast<OP>(op).getLoc();
1157
        auto result = pass.buildOutputDefs(op, rewriter)[0];
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        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
1172 1173
        auto ivs = makeIndexHandles(vLHS.rank());
        auto pivs = makeIndexHandlePointers(ivs);
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        // 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});
    }

1225
    template <typename RedOp>
1226 1227 1228
    void lowerIndexReduction(Operation* op,
                             ArrayRef<Value*> operands,
                             PatternRewriter& rewriter,
1229
                             DialectLoweringPass& pass)
nmostafa's avatar
nmostafa committed
1230
    {
1231 1232 1233 1234 1235 1236
        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();
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

        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];
1248

1249
        Value* result = pass.buildOutputDefs(op, rewriter)[0];
1250 1251 1252 1253

        // Views
        MemRefView vRes(result), vArg(arg);
        // Index Values
1254 1255
        StdIndexedValue iRes(result), stdArg(arg);
        IndexedValue affineArg(arg);
1256 1257 1258 1259 1260
        // Bounds Index Handles
        auto resLbs = vRes.getLbs();
        auto resUbs = vRes.getUbs();
        auto argLbs = vArg.getLbs();
        auto argUbs = vArg.getUbs();
1261 1262 1263

        Type resTy = result->getType().cast<MemRefType>().getElementType();
        // Generate loop nest that initializes result to lower bound of the axis to be reduced.
1264
        {
1265 1266
            auto ivs = makeIndexHandles(vRes.rank());
            auto pivs = makeIndexHandlePointers(ivs);
1267 1268
            auto steps = vRes.getSteps();
            auto initVal = vArg.lb(axis);
1269 1270 1271
            LoopNestBuilder(pivs, resLbs, resUbs, steps)(
                [&] { iRes(ivs) = ValueHandle::create<IndexCastOp>(initVal, resTy); });
        }
1272

1273 1274
        // Generate loop nest that computes the actual index reduction.
        {
1275 1276
            auto allIVs = makeIndexHandles(vArg.rank());
            auto pAllIVs = makeIndexHandlePointers(allIVs);
1277 1278
            auto steps = vArg.getSteps();
            SmallVector<IndexHandle, 8> nonRedIVs;
1279

1280 1281 1282
            Type resTy = result->getType().cast<MemRefType>().getElementType();
            NGRAPH_CHECK(resTy.isa<IntegerType>(),
                         "Expected integer result type in index reduction");
1283

1284 1285
            // iterate over all argument dimensions
            LoopNestBuilder(pAllIVs, argLbs, argUbs, steps)([&] {
nmostafa's avatar
nmostafa committed
1286 1287 1288 1289
                // build a list of non-reduction IVs
                for (auto i = 0; i < vArg.rank(); i++)
                {
                    if (i != axis)
1290
                    {
nmostafa's avatar
nmostafa committed
1291
                        nonRedIVs.push_back(allIVs[i]);
1292
                    }
nmostafa's avatar
nmostafa committed
1293
                }
1294 1295 1296 1297 1298 1299

                // 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
1300
                auto tempIVs = allIVs;
1301
                tempIVs[axis] = currRedIdx;
1302

1303 1304 1305 1306
                // 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(
1307
                              affineArg(allIVs) < stdArg(tempIVs), allIVs[axis], currRedIdx)
1308
                        : edsc::intrinsics::select(
1309
                              stdArg(tempIVs) < affineArg(allIVs), allIVs[axis], currRedIdx);
1310 1311 1312 1313 1314 1315 1316

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

        rewriter.replaceOp(op, result);
    }
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340

    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");
    }
1341 1342
}

1343
namespace mlir
1344
{
1345
    std::unique_ptr<Pass> createDialectLoweringPass()
1346
    {
1347
        return std::make_unique<DialectLoweringPass>();
1348
    }
1349
} // namespace mlir
1350 1351 1352

static PassRegistration<DialectLoweringPass> pass(PASS_NAME,
                                                  "Convert nGraph dialect to affine dialect");