1 /** 2 * Copyright (c) 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_RESERVE_STRING_BUILDER_BUFFER_H 17 #define COMPILER_OPTIMIZER_OPTIMIZATIONS_RESERVE_STRING_BUILDER_BUFFER_H 18 19 #include "optimizer/analysis/loop_analyzer.h" 20 #include "optimizer/ir/analysis.h" 21 #include "optimizer/ir/basicblock.h" 22 #include "optimizer/ir/graph.h" 23 #include "optimizer/ir/inst.h" 24 #include "optimizer/pass.h" 25 26 namespace ark::compiler { 27 28 using BlockWeightsMap = ArenaMap<BasicBlock *, uint64_t>; 29 using BlockPredicate = std::function<bool(BasicBlock *)>; 30 31 class ReserveStringBuilderBuffer : public Optimization { 32 public: 33 explicit ReserveStringBuilderBuffer(Graph *graph); 34 35 NO_MOVE_SEMANTIC(ReserveStringBuilderBuffer); 36 NO_COPY_SEMANTIC(ReserveStringBuilderBuffer); 37 ~ReserveStringBuilderBuffer() override = default; 38 39 bool RunImpl() override; 40 IsEnable()41 bool IsEnable() const override 42 { 43 return g_options.IsCompilerReserveStringBuilderBuffer(); 44 } 45 GetPassName()46 const char *GetPassName() const override 47 { 48 return "ReserveStringBuilderBuffer"; 49 } 50 51 private: 52 bool isApplied_ {false}; 53 uint64_t tlabArraySizeMax_ {0}; 54 BlockWeightsMap blockWeightsMap_; 55 SaveStateBridgesBuilder ssb_ {}; 56 57 uint64_t FindLongestPathLength(Inst *instance, Loop *loop, Marker visited); 58 uint64_t FindLongestPathLength( 59 Inst *instance, BasicBlock *block, Marker visited, 60 const BlockPredicate &stopAtBlock = [](auto) { return false; }); 61 62 void ReplaceInitialBufferSizeConstantInlined(Inst *instance, uint64_t appendCallsCount); 63 void ReplaceInitialBufferSizeConstantNotInlined(Inst *instance, uint64_t appendCallsCount); 64 uint64_t CountStringBuilderAppendCalls(Inst *instance); 65 uint64_t GetBufferSizeMin(Inst *instance) const; 66 uint64_t GetBufferSizeMax() const; 67 }; 68 69 } // namespace ark::compiler 70 71 #endif // COMPILER_OPTIMIZER_OPTIMIZATIONS_RESERVE_STRING_BUILDER_BUFFER_H 72