1 /* 2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef COMPILER_OPTIMIZER_OPTIMIZATIONS_LOOP_UNROLL_H 17 #define COMPILER_OPTIMIZER_OPTIMIZATIONS_LOOP_UNROLL_H 18 19 #include "optimizer/optimizations/loop_transform.h" 20 #include "compiler_options.h" 21 22 namespace ark::compiler { 23 /** 24 * Loop unroll optimization 25 * @param inst_limit - the maximum number of loop instructions after its unrolling 26 * @param unroll_factor - the number of loop body copies including the original one 27 */ 28 class LoopUnroll : public LoopTransform<LoopExitPoint::LOOP_EXIT_BACKEDGE> { 29 struct UnrollParams { 30 uint32_t unrollFactor; 31 uint32_t cloneableInsts; 32 bool hasCall; 33 }; 34 35 public: LoopUnroll(Graph * graph,uint32_t instLimit,uint32_t unrollFactor)36 LoopUnroll(Graph *graph, uint32_t instLimit, uint32_t unrollFactor) 37 : LoopTransform(graph), instLimit_(instLimit), unrollFactor_(unrollFactor) 38 { 39 } 40 41 bool RunImpl() override; 42 IsEnable()43 bool IsEnable() const override 44 { 45 return g_options.IsCompilerLoopUnroll(); 46 } 47 GetPassName()48 const char *GetPassName() const override 49 { 50 return "LoopUnroll"; 51 } 52 53 void InvalidateAnalyses() override; 54 static bool HasPreHeaderCompare(Loop *loop, const CountableLoopInfo &loopInfo); 55 56 private: 57 bool TransformLoop(Loop *loop) override; 58 bool UnrollWithBranching(uint32_t unrollFactor, Loop *loop, std::optional<CountableLoopInfo> loopInfo, 59 std::optional<uint64_t> optIterations); 60 UnrollParams GetUnrollParams(Loop *loop); 61 void TransformLoopImpl(Loop *loop, std::optional<uint64_t> optIterations, bool noSideExits, uint32_t unrollFactor, 62 std::optional<CountableLoopInfo> loopInfo); 63 void FixCompareInst(const CountableLoopInfo &loopInfo, BasicBlock *header, uint32_t unrollFactor); 64 Inst *CreateNewTestInst(const CountableLoopInfo &loopInfo, Inst *constInst, Inst *preHeaderCmp); 65 66 private: 67 const uint32_t instLimit_ {0}; 68 const uint32_t unrollFactor_ {0}; 69 bool isApplied_ {false}; 70 }; 71 } // namespace ark::compiler 72 73 #endif // COMPILER_OPTIMIZER_OPTIMIZATIONS_LOOP_UNROLL_H 74