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 ECMASCRIPT_COMPILER_INDUCTION_VARIABLE_ANALYSIS_H
17#define ECMASCRIPT_COMPILER_INDUCTION_VARIABLE_ANALYSIS_H
18
19#include "ecmascript/compiler/circuit_builder.h"
20#include "ecmascript/compiler/graph_linearizer.h"
21#include "ecmascript/compiler/pass_manager.h"
22
23namespace panda::ecmascript::kungfu {
24class InductionVariableAnalysis {
25public:
26    InductionVariableAnalysis(Circuit* circuit, PassContext* ctx, bool enableLog,
27                              const std::string& name, Chunk* chunk, bool isTraced)
28        : enableLog_(enableLog), methodName_(name), circuit_(circuit),
29          builder_(circuit, ctx->GetCompilerConfig()), acc_(circuit),
30          graphLinearizer_(circuit, enableLog, name, chunk, false, true), isTraced_(isTraced) {}
31
32    void Run();
33private:
34    bool IsLogEnabled() const
35    {
36        return enableLog_;
37    }
38
39    bool IsTraced() const
40    {
41        return isTraced_;
42    }
43
44    const std::string& GetMethodName() const
45    {
46        return methodName_;
47    }
48    bool IsIntConstant(GateRef gate) const;
49    bool IsInductionVariable(GateRef gate) const;
50    bool IsLessOrGreaterCmp(GateRef gate) const;
51    std::pair<int32_t, int32_t> GetStartAndStride(GateRef gate) const;
52    bool TryGetLoopTimes(const GraphLinearizer::LoopInfo& loop, int32_t& loopTimes) const;
53    int32_t GetIntFromTaggedConstant(GateRef gate) const;
54    void CollectInductionSelector();
55    void TryReplaceOutOfLoopUses(GateRef gate, const GraphLinearizer::LoopInfo& loop, const int32_t result);
56    void ReplaceInductionVariable(const GraphLinearizer::LoopInfo& loop, const int32_t loopTimes);
57    bool enableLog_ {false};
58    std::string methodName_;
59    Circuit* circuit_ {nullptr};
60    CircuitBuilder builder_;
61    GateAccessor acc_;
62    GraphLinearizer graphLinearizer_;
63    bool isTraced_;
64};
65
66}
67#endif