1/*
2 * Copyright (c) 2023 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_LOOP_PEELING_H
17#define ECMASCRIPT_COMPILER_LOOP_PEELING_H
18
19#include "ecmascript/compiler/circuit.h"
20#include "ecmascript/compiler/circuit_builder.h"
21#include "ecmascript/compiler/bytecode_circuit_builder.h"
22#include "ecmascript/compiler/gate.h"
23#include "ecmascript/compiler/share_gate_meta_data.h"
24#include "ecmascript/compiler/loop_analysis.h"
25
26namespace panda::ecmascript::kungfu {
27
28class LoopPeeling {
29public:
30    LoopPeeling(BytecodeCircuitBuilder* bcBuilder, Circuit *circuit, bool enableLog,
31                const std::string& name, Chunk* chunk, LoopInfo* loopInfo)
32        : bcBuilder_(bcBuilder), circuit_(circuit), acc_(circuit), enableLog_(enableLog),
33          methodName_(name), chunk_(chunk), loopInfo_(loopInfo), copies_(chunk_) {}
34    ~LoopPeeling() = default;
35    void Peel();
36
37private:
38    void SetCopy(GateRef gate);
39    GateRef GetCopy(GateRef gate) const;
40    GateRef TryGetCopy(GateRef gate) const;
41    void CopyLoopBody();
42    void CopyLoopHeader();
43    void CopyLoopExit();
44    GateRef CopySelector(GateRef stateMerge, GateRef selector, size_t numLoopbacks);
45    void Print() const;
46    bool IsLogEnabled() const
47    {
48        return enableLog_;
49    }
50    std::string GetMethodName() const
51    {
52        return methodName_;
53    }
54    BytecodeCircuitBuilder* bcBuilder_{nullptr};
55    Circuit* circuit_;
56    GateAccessor acc_;
57    bool enableLog_{false};
58    std::string methodName_;
59    Chunk* chunk_{nullptr};
60    LoopInfo* loopInfo_{nullptr};
61    ChunkMap<GateRef, GateRef> copies_;
62};
63
64}  // panda::ecmascript::kungfu
65#endif  // ECMASCRIPT_COMPILER_LOOP_PEELING_H