forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESTreeIRGen.cpp
More file actions
1311 lines (1114 loc) · 45.5 KB
/
ESTreeIRGen.cpp
File metadata and controls
1311 lines (1114 loc) · 45.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ESTreeIRGen.h"
#include "llvh/ADT/StringSet.h"
#include "llvh/Support/Debug.h"
#include "llvh/Support/SaveAndRestore.h"
namespace hermes {
namespace irgen {
//===----------------------------------------------------------------------===//
// Free standing helpers.
Instruction *emitLoad(IRBuilder &builder, Value *from, bool inhibitThrow) {
if (auto *var = llvh::dyn_cast<Variable>(from)) {
if (Variable::declKindNeedsTDZ(var->getDeclKind()) &&
var->getRelatedVariable()) {
builder.createThrowIfUndefinedInst(
builder.createLoadFrameInst(var->getRelatedVariable()));
}
return builder.createLoadFrameInst(var);
} else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(from)) {
if (globalProp->isDeclared() || inhibitThrow)
return builder.createLoadPropertyInst(
builder.getGlobalObject(), globalProp->getName());
else
return builder.createTryLoadGlobalPropertyInst(globalProp);
} else {
llvm_unreachable("unvalid value to load from");
}
}
Instruction *
emitStore(IRBuilder &builder, Value *storedValue, Value *ptr, bool declInit) {
if (auto *var = llvh::dyn_cast<Variable>(ptr)) {
if (!declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) &&
var->getRelatedVariable()) {
// Must verify whether the variable is initialized.
builder.createThrowIfUndefinedInst(
builder.createLoadFrameInst(var->getRelatedVariable()));
}
auto *store = builder.createStoreFrameInst(storedValue, var);
if (declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) &&
var->getRelatedVariable()) {
builder.createStoreFrameInst(
builder.getLiteralBool(true), var->getRelatedVariable());
}
return store;
} else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(ptr)) {
if (globalProp->isDeclared() || !builder.getFunction()->isStrictMode())
return builder.createStorePropertyInst(
storedValue, builder.getGlobalObject(), globalProp->getName());
else
return builder.createTryStoreGlobalPropertyInst(storedValue, globalProp);
} else {
llvm_unreachable("unvalid value to load from");
}
}
/// \returns true if \p node is a constant expression.
bool isConstantExpr(ESTree::Node *node) {
// TODO: a little more agressive constant folding.
switch (node->getKind()) {
case ESTree::NodeKind::StringLiteral:
case ESTree::NodeKind::NumericLiteral:
case ESTree::NodeKind::NullLiteral:
case ESTree::NodeKind::BooleanLiteral:
return true;
default:
return false;
}
}
//===----------------------------------------------------------------------===//
// LReference
IRBuilder &LReference::getBuilder() {
return irgen_->Builder;
}
Value *LReference::emitLoad() {
auto &builder = getBuilder();
IRBuilder::ScopedLocationChange slc(builder, loadLoc_);
switch (kind_) {
case Kind::Empty:
assert(false && "empty cannot be loaded");
return builder.getLiteralUndefined();
case Kind::Member:
return builder.createLoadPropertyInst(base_, property_);
case Kind::VarOrGlobal:
return irgen::emitLoad(builder, base_);
case Kind::Destructuring:
assert(false && "destructuring cannot be loaded");
return builder.getLiteralUndefined();
case Kind::Error:
return builder.getLiteralUndefined();
}
llvm_unreachable("invalid LReference kind");
}
void LReference::emitStore(Value *value) {
auto &builder = getBuilder();
switch (kind_) {
case Kind::Empty:
return;
case Kind::Member:
builder.createStorePropertyInst(value, base_, property_);
return;
case Kind::VarOrGlobal:
irgen::emitStore(builder, value, base_, declInit_);
return;
case Kind::Error:
return;
case Kind::Destructuring:
return irgen_->emitDestructuringAssignment(
declInit_, destructuringTarget_, value);
}
llvm_unreachable("invalid LReference kind");
}
bool LReference::canStoreWithoutSideEffects() const {
return kind_ == Kind::VarOrGlobal && llvh::isa<Variable>(base_);
}
Variable *LReference::castAsVariable() const {
return kind_ == Kind::VarOrGlobal ? dyn_cast_or_null<Variable>(base_)
: nullptr;
}
GlobalObjectProperty *LReference::castAsGlobalObjectProperty() const {
return kind_ == Kind::VarOrGlobal
? dyn_cast_or_null<GlobalObjectProperty>(base_)
: nullptr;
}
//===----------------------------------------------------------------------===//
// ESTreeIRGen
ESTreeIRGen::ESTreeIRGen(
ESTree::Node *root,
const DeclarationFileListTy &declFileList,
Module *M,
const ScopeChain &scopeChain)
: Mod(M),
Builder(Mod),
instrumentIR_(M, Builder),
Root(root),
DeclarationFileList(declFileList),
lexicalScopeChain(resolveScopeIdentifiers(scopeChain)),
identEval_(Builder.createIdentifier("eval")),
identLet_(Builder.createIdentifier("let")),
identDefaultExport_(Builder.createIdentifier("?default")) {}
void ESTreeIRGen::doIt() {
LLVM_DEBUG(dbgs() << "Processing top level program.\n");
ESTree::ProgramNode *Program;
Program = llvh::dyn_cast<ESTree::ProgramNode>(Root);
if (!Program) {
Builder.getModule()->getContext().getSourceErrorManager().error(
SMLoc{}, "missing 'Program' AST node");
return;
}
LLVM_DEBUG(dbgs() << "Found Program decl.\n");
// The function which will "execute" the module.
Function *topLevelFunction;
// Function context used only when compiling in an existing lexical scope
// chain. It is only initialized if we have a lexical scope chain.
llvh::Optional<FunctionContext> wrapperFunctionContext{};
if (!lexicalScopeChain) {
topLevelFunction = Builder.createTopLevelFunction(
ESTree::isStrict(Program->strictness), Program->getSourceRange());
} else {
// If compiling in an existing lexical context, we need to install the
// scopes in a wrapper function, which represents the "global" code.
Function *wrapperFunction = Builder.createFunction(
"",
Function::DefinitionKind::ES5Function,
ESTree::isStrict(Program->strictness),
Program->getSourceRange(),
true);
// Initialize the wrapper context.
wrapperFunctionContext.emplace(this, wrapperFunction, nullptr);
// Populate it with dummy code so it doesn't crash the back-end.
genDummyFunction(wrapperFunction);
// Restore the previously saved parent scopes.
materializeScopesInChain(wrapperFunction, lexicalScopeChain, -1);
// Finally create the function which will actually be executed.
topLevelFunction = Builder.createFunction(
"eval",
Function::DefinitionKind::ES5Function,
ESTree::isStrict(Program->strictness),
Program->getSourceRange(),
false);
}
Mod->setTopLevelFunction(topLevelFunction);
// Function context for topLevelFunction.
FunctionContext topLevelFunctionContext{
this, topLevelFunction, Program->getSemInfo()};
// IRGen needs a pointer to the outer-most context, which is either
// topLevelContext or wrapperFunctionContext, depending on whether the latter
// was created.
// We want to set the pointer to that outer-most context, but ensure that it
// doesn't outlive the context it is pointing to.
llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext(
topLevelContext,
!wrapperFunctionContext.hasValue() ? &topLevelFunctionContext
: &wrapperFunctionContext.getValue());
// Now declare all externally supplied global properties, but only if we don't
// have a lexical scope chain.
if (!lexicalScopeChain) {
for (auto declFile : DeclarationFileList) {
processDeclarationFile(declFile);
}
}
emitFunctionPrologue(
Program,
Builder.createBasicBlock(topLevelFunction),
InitES5CaptureState::Yes,
DoEmitParameters::Yes);
Value *retVal;
{
// Allocate the return register, initialize it to undefined.
curFunction()->globalReturnRegister =
Builder.createAllocStackInst(genAnonymousLabelName("ret"));
Builder.createStoreStackInst(
Builder.getLiteralUndefined(), curFunction()->globalReturnRegister);
genBody(Program->_body);
// Terminate the top-level scope with a return statement.
retVal = Builder.createLoadStackInst(curFunction()->globalReturnRegister);
}
emitFunctionEpilogue(retVal);
}
void ESTreeIRGen::doCJSModule(
Function *topLevelFunction,
sem::FunctionInfo *semInfo,
uint32_t id,
llvh::StringRef filename) {
assert(Root && "no root in ESTreeIRGen");
auto *func = cast<ESTree::FunctionExpressionNode>(Root);
assert(func && "doCJSModule without a module");
FunctionContext topLevelFunctionContext{this, topLevelFunction, semInfo};
llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext(
topLevelContext, &topLevelFunctionContext);
// Now declare all externally supplied global properties, but only if we don't
// have a lexical scope chain.
assert(
!lexicalScopeChain &&
"Lexical scope chain not supported for CJS modules");
for (auto declFile : DeclarationFileList) {
processDeclarationFile(declFile);
}
Identifier functionName = Builder.createIdentifier("cjs_module");
Function *newFunc = genES5Function(functionName, nullptr, func);
Builder.getModule()->addCJSModule(
id, Builder.createIdentifier(filename), newFunc);
}
static int getDepth(const std::shared_ptr<SerializedScope> chain) {
int depth = 0;
const SerializedScope *current = chain.get();
while (current) {
depth += 1;
current = current->parentScope.get();
}
return depth;
}
std::pair<Function *, Function *> ESTreeIRGen::doLazyFunction(
hbc::LazyCompilationData *lazyData) {
// Create a top level function that will never be executed, because:
// 1. IRGen assumes the first function always has global scope
// 2. It serves as the root for dummy functions for lexical data
Function *topLevel = Builder.createTopLevelFunction(lazyData->strictMode, {});
FunctionContext topLevelFunctionContext{this, topLevel, nullptr};
// Save the top-level context, but ensure it doesn't outlive what it is
// pointing to.
llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext(
topLevelContext, &topLevelFunctionContext);
auto *node = cast<ESTree::FunctionLikeNode>(Root);
// We restore scoping information in two separate ways:
// 1. By adding them to ExternalScopes for resolution here
// 2. By adding dummy functions for lexical scoping debug info later
//
// Instruction selection determines the delta between the ExternalScope
// and the dummy function chain, so we add the ExternalScopes with
// positive depth.
lexicalScopeChain = lazyData->parentScope;
materializeScopesInChain(
topLevel, lexicalScopeChain, getDepth(lexicalScopeChain) - 1);
// If lazyData->closureAlias is specified, we must create an alias binding
// between originalName (which must be valid) and the variable identified by
// closureAlias.
Variable *parentVar = nullptr;
if (lazyData->closureAlias.isValid()) {
assert(lazyData->originalName.isValid() && "Original name invalid");
assert(
lazyData->originalName != lazyData->closureAlias &&
"Original name must be different from the alias");
// NOTE: the closureAlias target must exist and must be a Variable.
parentVar = cast<Variable>(nameTable_.lookup(lazyData->closureAlias));
// Re-create the alias.
nameTable_.insert(lazyData->originalName, parentVar);
}
assert(
!llvh::isa<ESTree::ArrowFunctionExpressionNode>(node) &&
"lazy compilation not supported for arrow functions");
auto *func = genES5Function(
lazyData->originalName,
parentVar,
node,
lazyData->isGeneratorInnerFunction);
addLexicalDebugInfo(func, topLevel, lexicalScopeChain);
return {func, topLevel};
}
std::pair<Value *, bool> ESTreeIRGen::declareVariableOrGlobalProperty(
Function *inFunc,
VarDecl::Kind declKind,
Identifier name) {
Value *found = nameTable_.lookup(name);
// If the variable is already declared in this scope, do not create a
// second instance.
if (found) {
if (auto *var = llvh::dyn_cast<Variable>(found)) {
if (var->getParent()->getFunction() == inFunc)
return {found, false};
} else {
assert(
llvh::isa<GlobalObjectProperty>(found) &&
"Invalid value found in name table");
if (inFunc->isGlobalScope())
return {found, false};
}
}
// Create a property if global scope, variable otherwise.
Value *res;
if (inFunc->isGlobalScope() && declKind == VarDecl::Kind::Var) {
res = Builder.createGlobalObjectProperty(name, true);
} else {
Variable::DeclKind vdc;
if (declKind == VarDecl::Kind::Let)
vdc = Variable::DeclKind::Let;
else if (declKind == VarDecl::Kind::Const)
vdc = Variable::DeclKind::Const;
else {
assert(declKind == VarDecl::Kind::Var);
vdc = Variable::DeclKind::Var;
}
auto *var = Builder.createVariable(inFunc->getFunctionScope(), vdc, name);
// For "let" and "const" create the related TDZ flag.
if (Variable::declKindNeedsTDZ(vdc) &&
Mod->getContext().getCodeGenerationSettings().enableTDZ) {
llvh::SmallString<32> strBuf{"tdz$"};
strBuf.append(name.str());
auto *related = Builder.createVariable(
var->getParent(),
Variable::DeclKind::Var,
genAnonymousLabelName(strBuf));
var->setRelatedVariable(related);
related->setRelatedVariable(var);
}
res = var;
}
// Register the variable in the scoped hash table.
nameTable_.insert(name, res);
return {res, true};
}
GlobalObjectProperty *ESTreeIRGen::declareAmbientGlobalProperty(
Identifier name) {
// Avoid redefining global properties.
auto *prop = dyn_cast_or_null<GlobalObjectProperty>(nameTable_.lookup(name));
if (prop)
return prop;
LLVM_DEBUG(
llvh::dbgs() << "declaring ambient global property " << name << " "
<< name.getUnderlyingPointer() << "\n");
prop = Builder.createGlobalObjectProperty(name, false);
nameTable_.insertIntoScope(&topLevelContext->scope, name, prop);
return prop;
}
namespace {
/// This visitor structs collects declarations within a single closure without
/// descending into child closures.
struct DeclHoisting {
/// The list of collected identifiers (variables and functions).
llvh::SmallVector<ESTree::VariableDeclaratorNode *, 8> decls{};
/// A list of functions that need to be hoisted and materialized before we
/// can generate the rest of the function.
llvh::SmallVector<ESTree::FunctionDeclarationNode *, 8> closures;
explicit DeclHoisting() = default;
~DeclHoisting() = default;
/// Extract the variable name from the nodes that can define new variables.
/// The nodes that can define a new variable in the scope are:
/// VariableDeclarator and FunctionDeclaration>
void collectDecls(ESTree::Node *V) {
if (auto VD = llvh::dyn_cast<ESTree::VariableDeclaratorNode>(V)) {
return decls.push_back(VD);
}
if (auto FD = llvh::dyn_cast<ESTree::FunctionDeclarationNode>(V)) {
return closures.push_back(FD);
}
}
bool shouldVisit(ESTree::Node *V) {
// Collect declared names, even if we don't descend into children nodes.
collectDecls(V);
// Do not descend to child closures because the variables they define are
// not exposed to the outside function.
if (llvh::isa<ESTree::FunctionDeclarationNode>(V) ||
llvh::isa<ESTree::FunctionExpressionNode>(V) ||
llvh::isa<ESTree::ArrowFunctionExpressionNode>(V))
return false;
return true;
}
void enter(ESTree::Node *V) {}
void leave(ESTree::Node *V) {}
};
} // anonymous namespace.
void ESTreeIRGen::processDeclarationFile(ESTree::ProgramNode *programNode) {
auto Program = dyn_cast_or_null<ESTree::ProgramNode>(programNode);
if (!Program)
return;
DeclHoisting DH;
Program->visit(DH);
// Create variable declarations for each of the hoisted variables.
for (auto vd : DH.decls)
declareAmbientGlobalProperty(getNameFieldFromID(vd->_id));
for (auto fd : DH.closures)
declareAmbientGlobalProperty(getNameFieldFromID(fd->_id));
}
Value *ESTreeIRGen::ensureVariableExists(ESTree::IdentifierNode *id) {
assert(id && "id must be a valid Identifier node");
Identifier name = getNameFieldFromID(id);
// Check if this is a known variable.
if (auto *var = nameTable_.lookup(name))
return var;
if (curFunction()->function->isStrictMode()) {
// Report a warning in strict mode.
auto currentFunc = Builder.getInsertionBlock()->getParent();
Builder.getModule()->getContext().getSourceErrorManager().warning(
Warning::UndefinedVariable,
id->getSourceRange(),
Twine("the variable \"") + name.str() + "\" was not declared in " +
currentFunc->getDescriptiveDefinitionKindStr() + " \"" +
currentFunc->getInternalNameStr() + "\"");
}
// Undeclared variable is an ambient global property.
return declareAmbientGlobalProperty(name);
}
Value *ESTreeIRGen::genMemberExpressionProperty(
ESTree::MemberExpressionLikeNode *Mem) {
// If computed is true, the node corresponds to a computed (a[b]) member
// lookup and '_property' is an Expression. Otherwise, the node
// corresponds to a static (a.b) member lookup and '_property' is an
// Identifier.
// Details of the computed field are available here:
// https://github.com/estree/estree/blob/master/spec.md#memberexpression
if (getComputed(Mem)) {
return genExpression(getProperty(Mem));
}
// Arrays and objects may be accessed with integer indices.
if (auto N = llvh::dyn_cast<ESTree::NumericLiteralNode>(getProperty(Mem))) {
return Builder.getLiteralNumber(N->_value);
}
// ESTree encodes property access as MemberExpression -> Identifier.
auto Id = cast<ESTree::IdentifierNode>(getProperty(Mem));
Identifier fieldName = getNameFieldFromID(Id);
LLVM_DEBUG(
dbgs() << "Emitting direct label access to field '" << fieldName
<< "'\n");
return Builder.getLiteralString(fieldName);
}
bool ESTreeIRGen::canCreateLRefWithoutSideEffects(
hermes::ESTree::Node *target) {
// Check for an identifier bound to an existing local variable.
if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(target)) {
return dyn_cast_or_null<Variable>(
nameTable_.lookup(getNameFieldFromID(iden)));
}
return false;
}
LReference ESTreeIRGen::createLRef(ESTree::Node *node, bool declInit) {
SMLoc sourceLoc = node->getDebugLoc();
IRBuilder::ScopedLocationChange slc(Builder, sourceLoc);
if (llvh::isa<ESTree::EmptyNode>(node)) {
LLVM_DEBUG(dbgs() << "Creating an LRef for EmptyNode.\n");
return LReference(
LReference::Kind::Empty, this, false, nullptr, nullptr, sourceLoc);
}
/// Create lref for member expression (ex: o.f).
if (auto *ME = llvh::dyn_cast<ESTree::MemberExpressionNode>(node)) {
LLVM_DEBUG(dbgs() << "Creating an LRef for member expression.\n");
Value *obj = genExpression(ME->_object);
Value *prop = genMemberExpressionProperty(ME);
return LReference(
LReference::Kind::Member, this, false, obj, prop, sourceLoc);
}
/// Create lref for identifiers (ex: a).
if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(node)) {
LLVM_DEBUG(dbgs() << "Creating an LRef for identifier.\n");
LLVM_DEBUG(
dbgs() << "Looking for identifier \"" << getNameFieldFromID(iden)
<< "\"\n");
auto *var = ensureVariableExists(iden);
return LReference(
LReference::Kind::VarOrGlobal, this, declInit, var, nullptr, sourceLoc);
}
/// Create lref for variable decls (ex: var a).
if (auto *V = llvh::dyn_cast<ESTree::VariableDeclarationNode>(node)) {
LLVM_DEBUG(dbgs() << "Creating an LRef for variable declaration.\n");
assert(V->_declarations.size() == 1 && "Malformed variable declaration");
auto *decl =
cast<ESTree::VariableDeclaratorNode>(&V->_declarations.front());
return createLRef(decl->_id, true);
}
// Destructuring assignment.
if (auto *pat = llvh::dyn_cast<ESTree::PatternNode>(node)) {
return LReference(this, declInit, pat);
}
Builder.getModule()->getContext().getSourceErrorManager().error(
node->getSourceRange(), "unsupported assignment target");
return LReference(
LReference::Kind::Error, this, false, nullptr, nullptr, sourceLoc);
}
Value *ESTreeIRGen::genHermesInternalCall(
StringRef name,
Value *thisValue,
ArrayRef<Value *> args) {
return Builder.createCallInst(
Builder.createLoadPropertyInst(
Builder.createTryLoadGlobalPropertyInst("HermesInternal"), name),
thisValue,
args);
}
Value *ESTreeIRGen::genBuiltinCall(
hermes::BuiltinMethod::Enum builtinIndex,
ArrayRef<Value *> args) {
return Builder.createCallBuiltinInst(builtinIndex, args);
}
void ESTreeIRGen::emitEnsureObject(Value *value, StringRef message) {
// TODO: use "thisArg" when builtins get fixed to support it.
genBuiltinCall(
BuiltinMethod::HermesBuiltin_ensureObject,
{value, Builder.getLiteralString(message)});
}
Value *ESTreeIRGen::emitIteratorSymbol() {
// FIXME: use the builtin value of @@iterator. Symbol could have been
// overridden.
return Builder.createLoadPropertyInst(
Builder.createTryLoadGlobalPropertyInst("Symbol"), "iterator");
}
ESTreeIRGen::IteratorRecordSlow ESTreeIRGen::emitGetIteratorSlow(Value *obj) {
auto *method = Builder.createLoadPropertyInst(obj, emitIteratorSymbol());
auto *iterator = Builder.createCallInst(method, obj, {});
emitEnsureObject(iterator, "iterator is not an object");
auto *nextMethod = Builder.createLoadPropertyInst(iterator, "next");
return {iterator, nextMethod};
}
Value *ESTreeIRGen::emitIteratorNextSlow(IteratorRecordSlow iteratorRecord) {
auto *nextResult = Builder.createCallInst(
iteratorRecord.nextMethod, iteratorRecord.iterator, {});
emitEnsureObject(nextResult, "iterator.next() did not return an object");
return nextResult;
}
Value *ESTreeIRGen::emitIteratorCompleteSlow(Value *iterResult) {
return Builder.createLoadPropertyInst(iterResult, "done");
}
Value *ESTreeIRGen::emitIteratorValueSlow(Value *iterResult) {
return Builder.createLoadPropertyInst(iterResult, "value");
}
void ESTreeIRGen::emitIteratorCloseSlow(
hermes::irgen::ESTreeIRGen::IteratorRecordSlow iteratorRecord,
bool ignoreInnerException) {
auto *haveReturn = Builder.createBasicBlock(Builder.getFunction());
auto *noReturn = Builder.createBasicBlock(Builder.getFunction());
auto *returnMethod = genBuiltinCall(
BuiltinMethod::HermesBuiltin_getMethod,
{iteratorRecord.iterator, Builder.getLiteralString("return")});
Builder.createCompareBranchInst(
returnMethod,
Builder.getLiteralUndefined(),
BinaryOperatorInst::OpKind::StrictlyEqualKind,
noReturn,
haveReturn);
Builder.setInsertionBlock(haveReturn);
if (ignoreInnerException) {
emitTryCatchScaffolding(
noReturn,
// emitBody.
[this, returnMethod, &iteratorRecord]() {
Builder.createCallInst(returnMethod, iteratorRecord.iterator, {});
},
// emitNormalCleanup.
[]() {},
// emitHandler.
[this](BasicBlock *nextBlock) {
// We need to catch the exception, even if we don't used it.
Builder.createCatchInst();
Builder.createBranchInst(nextBlock);
});
} else {
auto *innerResult =
Builder.createCallInst(returnMethod, iteratorRecord.iterator, {});
emitEnsureObject(innerResult, "iterator.return() did not return an object");
Builder.createBranchInst(noReturn);
}
Builder.setInsertionBlock(noReturn);
}
ESTreeIRGen::IteratorRecord ESTreeIRGen::emitGetIterator(Value *obj) {
// Each of these will be modified by "next", so we use a stack storage.
auto *iterStorage =
Builder.createAllocStackInst(genAnonymousLabelName("iter"));
auto *sourceOrNext =
Builder.createAllocStackInst(genAnonymousLabelName("sourceOrNext"));
Builder.createStoreStackInst(obj, sourceOrNext);
auto *iter = Builder.createIteratorBeginInst(sourceOrNext);
Builder.createStoreStackInst(iter, iterStorage);
return IteratorRecord{iterStorage, sourceOrNext};
}
void ESTreeIRGen::emitDestructuringAssignment(
bool declInit,
ESTree::PatternNode *target,
Value *source) {
if (auto *APN = llvh::dyn_cast<ESTree::ArrayPatternNode>(target))
return emitDestructuringArray(declInit, APN, source);
else if (auto *OPN = llvh::dyn_cast<ESTree::ObjectPatternNode>(target))
return emitDestructuringObject(declInit, OPN, source);
else {
Mod->getContext().getSourceErrorManager().error(
target->getSourceRange(), "unsupported destructuring target");
}
}
void ESTreeIRGen::emitDestructuringArray(
bool declInit,
ESTree::ArrayPatternNode *targetPat,
Value *source) {
const IteratorRecord iteratorRecord = emitGetIterator(source);
/// iteratorDone = undefined.
auto *iteratorDone =
Builder.createAllocStackInst(genAnonymousLabelName("iterDone"));
Builder.createStoreStackInst(Builder.getLiteralUndefined(), iteratorDone);
auto *value =
Builder.createAllocStackInst(genAnonymousLabelName("iterValue"));
SharedExceptionHandler handler{};
handler.exc = Builder.createAllocStackInst(genAnonymousLabelName("exc"));
// All exception handlers branch to this block.
handler.exceptionBlock = Builder.createBasicBlock(Builder.getFunction());
bool first = true;
bool emittedRest = false;
// The LReference created in the previous iteration of the destructuring
// loop. We need it because we want to put the previous store and the creation
// of the next LReference under one try block.
llvh::Optional<LReference> lref;
/// If the previous LReference is valid and non-empty, store "value" into
/// it and reset the LReference.
auto storePreviousValue = [&lref, &handler, this, value]() {
if (lref && !lref->isEmpty()) {
if (lref->canStoreWithoutSideEffects()) {
lref->emitStore(Builder.createLoadStackInst(value));
} else {
// If we can't store without side effects, wrap the store in try/catch.
emitTryWithSharedHandler(&handler, [this, &lref, value]() {
lref->emitStore(Builder.createLoadStackInst(value));
});
}
lref.reset();
}
};
for (auto &elem : targetPat->_elements) {
ESTree::Node *target = &elem;
ESTree::Node *init = nullptr;
if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(target)) {
storePreviousValue();
emitRestElement(declInit, rest, iteratorRecord, iteratorDone, &handler);
emittedRest = true;
break;
}
// If we have an initializer, unwrap it.
if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(target)) {
target = assign->_left;
init = assign->_right;
}
// Can we create the new LReference without side effects and avoid a
// try/catch. The complexity comes from having to check whether the last
// LReference also can avoid a try/catch or not.
if (canCreateLRefWithoutSideEffects(target)) {
// We don't need a try/catch, but last lref might. Just let the routine
// do the right thing.
storePreviousValue();
lref = createLRef(target, declInit);
} else {
// We need a try/catch, but last lref might not. If it doesn't, emit it
// directly and clear it, so we won't do anything inside our try/catch.
if (lref && lref->canStoreWithoutSideEffects()) {
lref->emitStore(Builder.createLoadStackInst(value));
lref.reset();
}
emitTryWithSharedHandler(
&handler, [this, &lref, value, target, declInit]() {
// Store the previous value, if we have one.
if (lref && !lref->isEmpty())
lref->emitStore(Builder.createLoadStackInst(value));
lref = createLRef(target, declInit);
});
}
// Pseudocode of the algorithm for a step:
//
// value = undefined;
// if (iteratorDone) goto nextBlock
// notDoneBlock:
// stepResult = IteratorNext(iteratorRecord)
// stepDone = IteratorComplete(stepResult)
// iteratorDone = stepDone
// if (stepDone) goto nextBlock
// newValueBlock:
// value = IteratorValue(stepResult)
// nextBlock:
// if (value !== undefined) goto storeBlock [if initializer present]
// value = initializer [if initializer present]
// storeBlock:
// lref.emitStore(value)
auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction());
auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction());
auto *nextBlock = Builder.createBasicBlock(Builder.getFunction());
auto *getDefaultBlock =
init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr;
auto *storeBlock =
init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr;
Builder.createStoreStackInst(Builder.getLiteralUndefined(), value);
// In the first iteration we know that "done" is false.
if (first) {
first = false;
Builder.createBranchInst(notDoneBlock);
} else {
Builder.createCondBranchInst(
Builder.createLoadStackInst(iteratorDone), nextBlock, notDoneBlock);
}
// notDoneBlock:
Builder.setInsertionBlock(notDoneBlock);
auto *stepValue = emitIteratorNext(iteratorRecord);
auto *stepDone = emitIteratorComplete(iteratorRecord);
Builder.createStoreStackInst(stepDone, iteratorDone);
Builder.createCondBranchInst(
stepDone, init ? getDefaultBlock : nextBlock, newValueBlock);
// newValueBlock:
Builder.setInsertionBlock(newValueBlock);
Builder.createStoreStackInst(stepValue, value);
Builder.createBranchInst(nextBlock);
// nextBlock:
Builder.setInsertionBlock(nextBlock);
// NOTE: we can't use emitOptionalInitializationHere() because we want to
// be able to jump directly to getDefaultBlock.
if (init) {
// if (value !== undefined) goto storeBlock [if initializer present]
// value = initializer [if initializer present]
// storeBlock:
Builder.createCondBranchInst(
Builder.createBinaryOperatorInst(
Builder.createLoadStackInst(value),
Builder.getLiteralUndefined(),
BinaryOperatorInst::OpKind::StrictlyNotEqualKind),
storeBlock,
getDefaultBlock);
Identifier nameHint = llvh::isa<ESTree::IdentifierNode>(target)
? getNameFieldFromID(target)
: Identifier{};
// getDefaultBlock:
Builder.setInsertionBlock(getDefaultBlock);
Builder.createStoreStackInst(genExpression(init, nameHint), value);
Builder.createBranchInst(storeBlock);
// storeBlock:
Builder.setInsertionBlock(storeBlock);
}
}
storePreviousValue();
// If in the end the iterator is not done, close it. We only need to do
// that if we didn't end with a rest element because it would have exhausted
// the iterator.
if (!emittedRest) {
auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction());
auto *doneBlock = Builder.createBasicBlock(Builder.getFunction());
Builder.createCondBranchInst(
Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock);
Builder.setInsertionBlock(notDoneBlock);
emitIteratorClose(iteratorRecord, false);
Builder.createBranchInst(doneBlock);
Builder.setInsertionBlock(doneBlock);
}
// If we emitted at least one try block, generate the exception handler.
if (handler.emittedTry) {
IRBuilder::SaveRestore saveRestore{Builder};
Builder.setInsertionBlock(handler.exceptionBlock);
auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction());
auto *doneBlock = Builder.createBasicBlock(Builder.getFunction());
Builder.createCondBranchInst(
Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock);
Builder.setInsertionBlock(notDoneBlock);
emitIteratorClose(iteratorRecord, true);
Builder.createBranchInst(doneBlock);
Builder.setInsertionBlock(doneBlock);
Builder.createThrowInst(Builder.createLoadStackInst(handler.exc));
} else {
// If we didn't use the exception block, we need to delete it, otherwise
// it fails IR validation even though it will be never executed.
handler.exceptionBlock->eraseFromParent();
// Delete the not needed exception stack allocation. It would be optimized
// out later, but it is nice to produce cleaner non-optimized IR, if it is
// easy to do so.
assert(
!handler.exc->hasUsers() &&
"should not have any users if no try/catch was emitted");
handler.exc->eraseFromParent();
}
}
void ESTreeIRGen::emitRestElement(
bool declInit,
ESTree::RestElementNode *rest,
hermes::irgen::ESTreeIRGen::IteratorRecord iteratorRecord,
hermes::AllocStackInst *iteratorDone,
SharedExceptionHandler *handler) {
// 13.3.3.8 BindingRestElement:...BindingIdentifier
auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction());
auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction());
auto *doneBlock = Builder.createBasicBlock(Builder.getFunction());
llvh::Optional<LReference> lref;
if (canCreateLRefWithoutSideEffects(rest->_argument)) {
lref = createLRef(rest->_argument, declInit);
} else {
emitTryWithSharedHandler(handler, [this, &lref, rest, declInit]() {
lref = createLRef(rest->_argument, declInit);
});
}
auto *A = Builder.createAllocArrayInst({}, 0);
auto *n = Builder.createAllocStackInst(genAnonymousLabelName("n"));
// n = 0.
Builder.createStoreStackInst(Builder.getLiteralPositiveZero(), n);
Builder.createCondBranchInst(
Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock);
// notDoneBlock:
Builder.setInsertionBlock(notDoneBlock);
auto *stepValue = emitIteratorNext(iteratorRecord);
auto *stepDone = emitIteratorComplete(iteratorRecord);
Builder.createStoreStackInst(stepDone, iteratorDone);
Builder.createCondBranchInst(stepDone, doneBlock, newValueBlock);
// newValueBlock:
Builder.setInsertionBlock(newValueBlock);
auto *nVal = Builder.createLoadStackInst(n);
nVal->setType(Type::createNumber());
// A[n] = stepValue;
// Unfortunately this can throw because our arrays can have limited range.
// The spec doesn't specify what to do in this case, but the reasonable thing
// to do is to what we would if this was a for-of loop doing the same thing.
// See section BindingRestElement:...BindingIdentifier, step f and g:
// https://www.ecma-international.org/ecma-262/9.0/index.html#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
emitTryWithSharedHandler(handler, [this, stepValue, A, nVal]() {
Builder.createStorePropertyInst(stepValue, A, nVal);
});