• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "emitter.h"
17 
18 #include "ir/irnode.h"
19 #include "util/helpers.h"
20 #include "varbinder/scope.h"
21 #include "varbinder/variable.h"
22 #include "compiler/base/literals.h"
23 #include "compiler/core/codeGen.h"
24 #include "compiler/core/regSpiller.h"
25 #include "compiler/debugger/debuginfoDumper.h"
26 #include "compiler/base/catchTable.h"
27 #include "es2panda.h"
28 #include "parser/program/program.h"
29 #include "checker/types/type.h"
30 #include "generated/isa.h"
31 #include "macros.h"
32 #include "public/public.h"
33 
34 #include <string>
35 #include <string_view>
36 #include <tuple>
37 #include <utility>
38 
39 namespace ark::es2panda::compiler {
40 using LiteralPair = std::pair<pandasm::LiteralArray::Literal, pandasm::LiteralArray::Literal>;
41 
TransformMethodLiterals(const compiler::Literal * literal)42 static LiteralPair TransformMethodLiterals(const compiler::Literal *literal)
43 {
44     pandasm::LiteralArray::Literal valueLit;
45     pandasm::LiteralArray::Literal tagLit;
46 
47     compiler::LiteralTag tag = literal->Tag();
48 
49     switch (tag) {
50         case compiler::LiteralTag::METHOD: {
51             valueLit.tag = panda_file::LiteralTag::METHOD;
52             valueLit.value = literal->GetMethod();
53             break;
54         }
55         case compiler::LiteralTag::ASYNC_METHOD: {
56             valueLit.tag = panda_file::LiteralTag::ASYNCMETHOD;
57             valueLit.value = literal->GetMethod();
58             break;
59         }
60         case compiler::LiteralTag::GENERATOR_METHOD: {
61             valueLit.tag = panda_file::LiteralTag::GENERATORMETHOD;
62             valueLit.value = literal->GetMethod();
63             break;
64         }
65         case compiler::LiteralTag::ASYNC_GENERATOR_METHOD: {
66             valueLit.tag = panda_file::LiteralTag::ASYNCGENERATORMETHOD;
67             valueLit.value = literal->GetMethod();
68             break;
69         }
70         default: {
71             UNREACHABLE();
72             break;
73         }
74     }
75 
76     tagLit.tag = panda_file::LiteralTag::TAGVALUE;
77     tagLit.value = static_cast<uint8_t>(valueLit.tag);
78 
79     return {tagLit, valueLit};
80 }
81 
TransformLiteral(const compiler::Literal * literal)82 static LiteralPair TransformLiteral(const compiler::Literal *literal)
83 {
84     pandasm::LiteralArray::Literal valueLit;
85     pandasm::LiteralArray::Literal tagLit;
86 
87     compiler::LiteralTag tag = literal->Tag();
88 
89     switch (tag) {
90         case compiler::LiteralTag::BOOLEAN: {
91             valueLit.tag = panda_file::LiteralTag::BOOL;
92             valueLit.value = literal->GetBoolean();
93             break;
94         }
95         case compiler::LiteralTag::INTEGER: {
96             valueLit.tag = panda_file::LiteralTag::INTEGER;
97             valueLit.value = literal->GetInteger();
98             break;
99         }
100         case compiler::LiteralTag::DOUBLE: {
101             valueLit.tag = panda_file::LiteralTag::DOUBLE;
102             valueLit.value = literal->GetDouble();
103             break;
104         }
105         case compiler::LiteralTag::STRING: {
106             valueLit.tag = panda_file::LiteralTag::STRING;
107             valueLit.value = literal->GetString();
108             break;
109         }
110         case compiler::LiteralTag::ACCESSOR: {
111             valueLit.tag = panda_file::LiteralTag::ACCESSOR;
112             valueLit.value = static_cast<uint8_t>(0);
113             break;
114         }
115         case compiler::LiteralTag::NULL_VALUE: {
116             valueLit.tag = panda_file::LiteralTag::NULLVALUE;
117             valueLit.value = static_cast<uint8_t>(0);
118             break;
119         }
120         default:
121             return TransformMethodLiterals(literal);
122     }
123 
124     tagLit.tag = panda_file::LiteralTag::TAGVALUE;
125     tagLit.value = static_cast<uint8_t>(valueLit.tag);
126 
127     return {tagLit, valueLit};
128 }
129 
Generate()130 void FunctionEmitter::Generate()
131 {
132     auto *func = GenFunctionSignature();
133     GenFunctionInstructions(func);
134     GenVariablesDebugInfo(func);
135     GenSourceFileDebugInfo(func);
136     GenFunctionCatchTables(func);
137     GenFunctionAnnotations(func);
138 }
139 
SourceCode() const140 util::StringView FunctionEmitter::SourceCode() const
141 {
142     return cg_->VarBinder()->Program()->SourceCode();
143 }
144 
MatchFormat(const IRNode * node,const Formats & formats)145 static Format MatchFormat(const IRNode *node, const Formats &formats)
146 {
147     std::array<const VReg *, IRNode::MAX_REG_OPERAND> regs {};
148     auto regCnt = node->Registers(&regs);
149     auto registers = Span<const VReg *>(regs.data(), regs.data() + regCnt);
150 
151     const auto *iter = formats.begin();
152 
153     for (; iter != formats.end(); iter++) {  // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
154         auto format = *iter;
155         size_t limit = 0;
156         for (const auto &formatItem : format.GetFormatItem()) {
157             if (formatItem.IsVReg()) {
158                 limit = 1U << formatItem.BitWidth();
159                 break;
160             }
161         }
162 
163         if (std::all_of(registers.begin(), registers.end(), [limit](const VReg *reg) { return reg->IsValid(limit); })) {
164             return format;
165         }
166     }
167 
168     UNREACHABLE();
169     return *iter;
170 }
171 
GetIRNodeWholeLength(const IRNode * node)172 static size_t GetIRNodeWholeLength(const IRNode *node)
173 {
174     Formats formats = node->GetFormats();
175     if (formats.empty()) {
176         return 0;
177     }
178 
179     size_t len = 1;
180     const auto format = MatchFormat(node, formats);
181 
182     for (auto fi : format.GetFormatItem()) {
183         len += fi.BitWidth() / 8U;
184     }
185 
186     return len;
187 }
188 
WholeLine(const util::StringView & source,lexer::SourceRange range)189 static std::string WholeLine(const util::StringView &source, lexer::SourceRange range)
190 {
191     if (source.Empty()) {
192         return {};
193     }
194     ASSERT(range.end.index <= source.Length());
195     return source.Substr(range.start.index, range.end.index).EscapeSymbol<util::StringView::Mutf8Encode>();
196 }
197 
GenInstructionDebugInfo(const IRNode * ins,pandasm::Ins * pandaIns)198 void FunctionEmitter::GenInstructionDebugInfo(const IRNode *ins, pandasm::Ins *pandaIns)
199 {
200     const ir::AstNode *astNode = ins->Node();
201 
202     ASSERT(astNode != nullptr);
203 
204     if (astNode == FIRST_NODE_OF_FUNCTION) {
205         astNode = cg_->Debuginfo().FirstStatement();
206         if (astNode == nullptr) {
207             return;
208         }
209     }
210 
211     pandaIns->insDebug.lineNumber = astNode->Range().start.line + 1;
212 
213     if (cg_->IsDebug()) {
214         size_t insLen = GetIRNodeWholeLength(ins);
215         if (insLen != 0) {
216             pandaIns->insDebug.boundLeft = offset_;
217             pandaIns->insDebug.boundRight = offset_ + insLen;
218         }
219 
220         offset_ += insLen;
221         pandaIns->insDebug.wholeLine = WholeLine(SourceCode(), astNode->Range());
222     }
223 }
224 
GenFunctionInstructions(pandasm::Function * func)225 void FunctionEmitter::GenFunctionInstructions(pandasm::Function *func)
226 {
227     func->ins.reserve(cg_->Insns().size());
228 
229     uint32_t totalRegs = cg_->TotalRegsNum();
230 
231     for (const auto *ins : cg_->Insns()) {
232         auto &pandaIns = func->ins.emplace_back();
233 
234         ins->Transform(&pandaIns, programElement_, totalRegs);
235         GenInstructionDebugInfo(ins, &pandaIns);
236     }
237 }
238 
GenFunctionAnnotations(pandasm::Function * func)239 void FunctionEmitter::GenFunctionAnnotations(pandasm::Function *func)
240 {
241     pandasm::AnnotationData funcAnnotationData("_ESAnnotation");
242     pandasm::AnnotationElement icSizeAnnotationElement(
243         "icSize",
244         std::make_unique<pandasm::ScalarValue>(pandasm::ScalarValue::Create<pandasm::Value::Type::U32>(cg_->IcSize())));
245     funcAnnotationData.AddElement(std::move(icSizeAnnotationElement));
246 
247     pandasm::AnnotationElement parameterLengthAnnotationElement(
248         "parameterLength", std::make_unique<pandasm::ScalarValue>(
249                                pandasm::ScalarValue::Create<pandasm::Value::Type::U32>(cg_->FormalParametersCount())));
250     funcAnnotationData.AddElement(std::move(parameterLengthAnnotationElement));
251 
252     pandasm::AnnotationElement funcNameAnnotationElement(
253         "funcName", std::make_unique<pandasm::ScalarValue>(
254                         pandasm::ScalarValue::Create<pandasm::Value::Type::STRING>(cg_->FunctionName().Mutf8())));
255     funcAnnotationData.AddElement(std::move(funcNameAnnotationElement));
256 
257     func->metadata->AddAnnotations({funcAnnotationData});
258 }
259 
GenFunctionCatchTables(pandasm::Function * func)260 void FunctionEmitter::GenFunctionCatchTables(pandasm::Function *func)
261 {
262     func->catchBlocks.reserve(cg_->CatchList().size());
263 
264     for (const auto *catchBlock : cg_->CatchList()) {
265         const auto &labelSet = catchBlock->LabelSet();
266 
267         auto &pandaCatchBlock = func->catchBlocks.emplace_back();
268         pandaCatchBlock.exceptionRecord = catchBlock->Exception();
269         pandaCatchBlock.tryBeginLabel = labelSet.TryBegin()->Id();
270         pandaCatchBlock.tryEndLabel = labelSet.TryEnd()->Id();
271         pandaCatchBlock.catchBeginLabel = labelSet.CatchBegin()->Id();
272         pandaCatchBlock.catchEndLabel = labelSet.CatchBegin()->Id();
273     }
274 }
275 
GenSourceFileDebugInfo(pandasm::Function * func)276 void FunctionEmitter::GenSourceFileDebugInfo(pandasm::Function *func)
277 {
278     func->sourceFile = std::string {cg_->VarBinder()->Program()->SourceFile().GetAbsolutePath()};
279 
280     if (!cg_->IsDebug()) {
281         return;
282     }
283 
284     if (cg_->RootNode()->IsProgram()) {
285         func->sourceCode = SourceCode().EscapeSymbol<util::StringView::Mutf8Encode>();
286     }
287 }
288 
GenLocalVariableInfo(pandasm::debuginfo::LocalVariable & variableDebug,varbinder::Variable * var,std::tuple<uint32_t,uint32_t,uint32_t> info,const ScriptExtension extension)289 static void GenLocalVariableInfo(pandasm::debuginfo::LocalVariable &variableDebug, varbinder::Variable *var,
290                                  std::tuple<uint32_t, uint32_t, uint32_t> info, const ScriptExtension extension)
291 {
292     const auto [start, varsLength, totalRegsNum] = info;
293 
294     variableDebug.name = var->Name().Mutf8();
295 
296     if (extension == ScriptExtension::JS) {
297         variableDebug.signature = "any";
298         variableDebug.signatureType = "any";
299     } else {
300         std::stringstream ss;
301         var->AsLocalVariable()->TsType()->ToDebugInfoType(ss);
302         variableDebug.signature = ss.str();
303         variableDebug.signatureType = ss.str();  // NOTE: Handle typeParams, either class or interface
304     }
305 
306     variableDebug.reg =
307         static_cast<int32_t>(IRNode::MapRegister(var->AsLocalVariable()->Vreg().GetIndex(), totalRegsNum));
308     variableDebug.start = start;
309     variableDebug.length = static_cast<uint32_t>(varsLength);
310 }
311 
GenScopeVariableInfoEnd(pandasm::Function * func,const varbinder::Scope * scope,uint32_t count,uint32_t start) const312 void FunctionEmitter::GenScopeVariableInfoEnd(pandasm::Function *func, const varbinder::Scope *scope, uint32_t count,
313                                               uint32_t start) const
314 {
315     const auto extension = cg_->VarBinder()->Program()->Extension();
316     auto varsLength = static_cast<uint32_t>(count - start + 1);
317 
318     if (scope->IsFunctionScope()) {
319         for (auto *param : scope->AsFunctionScope()->ParamScope()->Params()) {
320             auto &variableDebug = func->localVariableDebug.emplace_back();
321             GenLocalVariableInfo(variableDebug, param, std::make_tuple(start, varsLength, cg_->TotalRegsNum()),
322                                  extension);
323         }
324     }
325     const auto &unsortedBindings = scope->Bindings();
326     std::map<util::StringView, es2panda::varbinder::Variable *> bindings(unsortedBindings.begin(),
327                                                                          unsortedBindings.end());
328     for (const auto &[_, variable] : bindings) {
329         (void)_;
330         if (!variable->IsLocalVariable() || variable->LexicalBound() || variable->Declaration()->IsParameterDecl() ||
331             variable->Declaration()->IsTypeAliasDecl()) {
332             continue;
333         }
334 
335         auto &variableDebug = func->localVariableDebug.emplace_back();
336         GenLocalVariableInfo(variableDebug, variable, std::make_tuple(start, varsLength, cg_->TotalRegsNum()),
337                              extension);
338     }
339 }
340 
GenScopeVariableInfo(pandasm::Function * func,const varbinder::Scope * scope) const341 void FunctionEmitter::GenScopeVariableInfo(pandasm::Function *func, const varbinder::Scope *scope) const
342 {
343     const auto *startIns = scope->ScopeStart();
344     const auto *endIns = scope->ScopeEnd();
345 
346     uint32_t start = 0;
347     uint32_t count = 0;
348 
349     for (const auto *it : cg_->Insns()) {
350         if (startIns == it) {
351             start = count;
352         } else if (endIns == it) {
353             GenScopeVariableInfoEnd(func, scope, count, start);
354         }
355 
356         count++;
357     }
358 }
359 
GenVariablesDebugInfo(pandasm::Function * func)360 void FunctionEmitter::GenVariablesDebugInfo(pandasm::Function *func)
361 {
362     if (!cg_->IsDebug()) {
363         return;
364     }
365 
366     for (const auto *scope : cg_->Debuginfo().VariableDebugInfo()) {
367         GenScopeVariableInfo(func, scope);
368     }
369 }
370 
371 // Emitter
372 
Emitter(const public_lib::Context * context)373 Emitter::Emitter(const public_lib::Context *context) : context_(context)
374 {
375     prog_ = new pandasm::Program();
376 }
377 
~Emitter()378 Emitter::~Emitter()
379 {
380     delete prog_;
381 }
382 
UpdateLiteralBufferId(ark::pandasm::Ins * ins,uint32_t offset)383 static void UpdateLiteralBufferId([[maybe_unused]] ark::pandasm::Ins *ins, [[maybe_unused]] uint32_t offset)
384 {
385 #ifdef PANDA_WITH_ECMASCRIPT
386     switch (ins->opcode) {
387         case pandasm::Opcode::ECMA_DEFINECLASSWITHBUFFER: {
388             ins->imms.back() = std::get<int64_t>(ins->imms.back()) + offset;
389             break;
390         }
391         case pandasm::Opcode::ECMA_CREATEARRAYWITHBUFFER:
392         case pandasm::Opcode::ECMA_CREATEOBJECTWITHBUFFER:
393         case pandasm::Opcode::ECMA_CREATEOBJECTHAVINGMETHOD:
394         case pandasm::Opcode::ECMA_DEFINECLASSPRIVATEFIELDS: {
395             uint32_t storedOffset = std::stoi(ins->ids.back());
396             storedOffset += offset;
397             ins->ids.back() = std::to_string(storedOffset);
398             break;
399         }
400         default: {
401             UNREACHABLE();
402             break;
403         }
404     }
405 #else
406     UNREACHABLE();
407 #endif
408 }
409 
AddProgramElement(ProgramElement * programElement)410 void Emitter::AddProgramElement(ProgramElement *programElement)
411 {
412     prog_->strings.insert(programElement->Strings().begin(), programElement->Strings().end());
413 
414     uint32_t newLiteralBufferIndex = literalBufferIndex_;
415     for (const auto &buff : programElement->BuffStorage()) {
416         AddLiteralBuffer(buff, newLiteralBufferIndex++);
417     }
418 
419     for (auto *ins : programElement->LiteralBufferIns()) {
420         UpdateLiteralBufferId(ins, literalBufferIndex_);
421     }
422 
423     literalBufferIndex_ = newLiteralBufferIndex;
424 
425     auto *function = programElement->Function();
426     prog_->functionTable.emplace(function->name, std::move(*function));
427 }
428 
CanonicalizeName(std::string name)429 static std::string CanonicalizeName(std::string name)
430 {
431     std::replace_if(
432         name.begin(), name.end(), [](char c) { return (c == '<' || c == '>' || c == '.' || c == ':' || c == ';'); },
433         '-');
434     name.append(std::to_string(0));
435     return name;
436 }
437 
DumpAsm(const pandasm::Program * prog)438 void Emitter::DumpAsm(const pandasm::Program *prog)
439 {
440     auto &ss = std::cout;
441 
442     ss << ".language ECMAScript" << std::endl << std::endl;
443 
444     for (auto &[name, func] : prog->functionTable) {
445         ss << ".function any " << CanonicalizeName(name) << '(';
446 
447         for (uint32_t i = 0; i < func.GetParamsNum(); i++) {
448             ss << "any a" << std::to_string(i);
449 
450             if (i != func.GetParamsNum() - 1) {
451                 ss << ", ";
452             }
453         }
454 
455         ss << ") {" << std::endl;
456 
457         for (const auto &ins : func.ins) {
458             ss << (ins.setLabel ? "" : "\t") << ins.ToString("", true, func.GetTotalRegs()) << std::endl;
459         }
460 
461         ss << "}" << std::endl << std::endl;
462 
463         for (const auto &ct : func.catchBlocks) {
464             if (ct.exceptionRecord.empty()) {
465                 ss << ".catchall ";
466             } else {
467                 ss << ".catch " << ct.exceptionRecord << ", ";
468             }
469             ss << ct.tryBeginLabel << ", " << ct.tryEndLabel << ", " << ct.catchBeginLabel << std::endl << std::endl;
470         }
471     }
472 
473     ss << std::endl;
474 }
475 
AddLiteralBuffer(const LiteralBuffer & literals,uint32_t index)476 void Emitter::AddLiteralBuffer(const LiteralBuffer &literals, uint32_t index)
477 {
478     std::vector<pandasm::LiteralArray::Literal> literalArray;
479 
480     for (const auto &literal : literals) {
481         auto [tagLit, valueLit] = TransformLiteral(&literal);
482         literalArray.emplace_back(tagLit);
483         literalArray.emplace_back(valueLit);
484     }
485 
486     auto literalArrayInstance = pandasm::LiteralArray(std::move(literalArray));
487     prog_->literalarrayTable.emplace(std::to_string(index), std::move(literalArrayInstance));
488 }
489 
Finalize(bool dumpDebugInfo,std::string_view globalClass)490 pandasm::Program *Emitter::Finalize(bool dumpDebugInfo, std::string_view globalClass)
491 {
492     if (dumpDebugInfo) {
493         debuginfo::DebugInfoDumper dumper(prog_);
494         dumper.Dump();
495     }
496 
497     if (context_->parserProgram->VarBinder()->IsGenStdLib()) {
498         auto it = prog_->recordTable.find(std::string(globalClass));
499         if (it != prog_->recordTable.end()) {
500             prog_->recordTable.erase(it);
501         }
502     }
503     auto *prog = prog_;
504     prog_ = nullptr;
505     return prog;
506 }
507 }  // namespace ark::es2panda::compiler
508