1/*
2 * Copyright (c) 2021 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#include "ecmascript/compiler/stub.h"
16#include "ecmascript/compiler/stub_builder.h"
17#include "ecmascript/compiler/call_signature.h"
18
19namespace panda::ecmascript::kungfu {
20Stub::Stub(const CallSignature *callSignature, Circuit *circuit)
21    : callSignature_(callSignature),
22      builder_(circuit),
23      acc_(circuit),
24      env_(callSignature->GetParametersCount(), &builder_)
25{
26    ASSERT(callSignature_->HasConstructor());
27    stubBuilder_ = static_cast<StubBuilder*>(callSignature_->GetConstructor()(&env_));
28}
29
30void Stub::InitializeArguments()
31{
32    auto argLength = callSignature_->GetParametersCount();
33    auto paramsType = callSignature_->GetParametersType();
34    for (size_t i = 0; i < argLength; i++) {
35        GateRef argument = env_.GetArgument(i);
36        if (paramsType[i] == VariableType::NATIVE_POINTER()) {
37            auto type = env_.IsArch64Bit() ? MachineType::I64 : MachineType::I32;
38            acc_.SetMachineType(argument, type);
39        } else {
40            acc_.SetMachineType(argument, paramsType[i].GetMachineType());
41        }
42        acc_.SetGateType(argument, paramsType[i].GetGateType());
43    }
44}
45
46void Stub::GenerateCircuit(const CompilationConfig *cfg)
47{
48    env_.SetCompilationConfig(cfg);
49    InitializeArguments();
50    stubBuilder_->GenerateCircuit();
51}
52
53Stub::~Stub()
54{
55    if (stubBuilder_ != nullptr) {
56        delete stubBuilder_;
57        stubBuilder_ = nullptr;
58    }
59}
60}  // namespace panda::ecmascript::kungfu