forked from mojombo/v8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen-ia32.cc
5370 lines (4481 loc) · 168 KB
/
codegen-ia32.cc
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 2006-2008 Google Inc. All Rights Reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "debug.h"
#include "prettyprinter.h"
#include "scopeinfo.h"
#include "scopes.h"
#include "runtime.h"
namespace v8 { namespace internal {
DEFINE_bool(trace, false, "trace function calls");
DEFINE_bool(defer_negation, true, "defer negation operation");
DECLARE_bool(debug_info);
DECLARE_bool(debug_code);
#ifdef ENABLE_DISASSEMBLER
DEFINE_bool(print_code, false, "print generated code");
#endif
#ifdef DEBUG
DECLARE_bool(gc_greedy);
DEFINE_bool(trace_codegen, false,
"print name of functions for which code is generated");
DEFINE_bool(print_builtin_code, false, "print generated code for builtins");
DEFINE_bool(print_source, false, "pretty print source code");
DEFINE_bool(print_builtin_source, false,
"pretty print source code for builtins");
DEFINE_bool(print_ast, false, "print source AST");
DEFINE_bool(print_builtin_ast, false, "print source AST for builtins");
DEFINE_bool(trace_calls, false, "trace calls");
DEFINE_bool(trace_builtin_calls, false, "trace builtins calls");
DEFINE_string(stop_at, "", "function name where to insert a breakpoint");
#endif // DEBUG
DEFINE_bool(check_stack, true,
"check stack for overflow, interrupt, breakpoint");
#define TOS (Operand(esp, 0))
class Ia32CodeGenerator;
// Mode to overwrite BinaryExpression values.
enum OverwriteMode { NO_OVERWRITE, OVERWRITE_LEFT, OVERWRITE_RIGHT };
// -----------------------------------------------------------------------------
// Reference support
// A reference is a C++ stack-allocated object that keeps an ECMA
// reference on the execution stack while in scope. For variables
// the reference is empty, indicating that it isn't necessary to
// store state on the stack for keeping track of references to those.
// For properties, we keep either one (named) or two (indexed) values
// on the execution stack to represent the reference.
class Reference BASE_EMBEDDED {
public:
enum Type { ILLEGAL = -1, EMPTY = 0, NAMED = 1, KEYED = 2 };
Reference(Ia32CodeGenerator* cgen, Expression* expression);
~Reference();
Expression* expression() const { return expression_; }
Type type() const { return type_; }
void set_type(Type value) {
ASSERT(type_ == ILLEGAL);
type_ = value;
}
int size() const { return type_; }
bool is_illegal() const { return type_ == ILLEGAL; }
private:
Ia32CodeGenerator* cgen_;
Expression* expression_;
Type type_;
};
// -----------------------------------------------------------------------------
// Code generation state
class CodeGenState BASE_EMBEDDED {
public:
enum AccessType {
UNDEFINED,
LOAD,
LOAD_TYPEOF_EXPR,
STORE,
INIT_CONST
};
CodeGenState()
: access_(UNDEFINED),
ref_(NULL),
true_target_(NULL),
false_target_(NULL) {
}
CodeGenState(AccessType access,
Reference* ref,
Label* true_target,
Label* false_target)
: access_(access),
ref_(ref),
true_target_(true_target),
false_target_(false_target) {
}
AccessType access() const { return access_; }
Reference* ref() const { return ref_; }
Label* true_target() const { return true_target_; }
Label* false_target() const { return false_target_; }
private:
AccessType access_;
Reference* ref_;
Label* true_target_;
Label* false_target_;
};
// -----------------------------------------------------------------------------
// Ia32CodeGenerator
class Ia32CodeGenerator: public CodeGenerator {
public:
static Handle<Code> MakeCode(FunctionLiteral* fun,
Handle<Script> script,
bool is_eval);
MacroAssembler* masm() { return masm_; }
private:
// Assembler
MacroAssembler* masm_; // to generate code
// Code generation state
Scope* scope_;
Condition cc_reg_;
CodeGenState* state_;
bool is_inside_try_;
int break_stack_height_;
// Labels
Label function_return_;
// Construction/destruction
Ia32CodeGenerator(int buffer_size,
Handle<Script> script,
bool is_eval);
virtual ~Ia32CodeGenerator() { delete masm_; }
// Main code generation function
void GenCode(FunctionLiteral* fun);
// The following are used by class Reference.
void LoadReference(Reference* ref);
void UnloadReference(Reference* ref);
friend class Reference;
// State
bool has_cc() const { return cc_reg_ >= 0; }
CodeGenState::AccessType access() const { return state_->access(); }
Reference* ref() const { return state_->ref(); }
bool is_referenced() const { return state_->ref() != NULL; }
Label* true_target() const { return state_->true_target(); }
Label* false_target() const { return state_->false_target(); }
// Expressions
Operand GlobalObject() const {
return ContextOperand(esi, Context::GLOBAL_INDEX);
}
// Support functions for accessing parameters.
Operand ParameterOperand(int index) const {
ASSERT(-2 <= index && index < scope_->num_parameters());
return Operand(ebp, (1 + scope_->num_parameters() - index) * kPointerSize);
}
Operand ReceiverOperand() const { return ParameterOperand(-1); }
Operand FunctionOperand() const {
return Operand(ebp, JavaScriptFrameConstants::kFunctionOffset);
}
Operand ContextOperand(Register context, int index) const {
return Operand(context, Context::SlotOffset(index));
}
Operand SlotOperand(Slot* slot, Register tmp);
void LoadCondition(Expression* x,
CodeGenState::AccessType access,
Label* true_target,
Label* false_target,
bool force_cc);
void Load(Expression* x,
CodeGenState::AccessType access = CodeGenState::LOAD);
void LoadGlobal();
// Special code for typeof expressions: Unfortunately, we must
// be careful when loading the expression in 'typeof'
// expressions. We are not allowed to throw reference errors for
// non-existing properties of the global object, so we must make it
// look like an explicit property access, instead of an access
// through the context chain.
void LoadTypeofExpression(Expression* x);
// References
void AccessReference(Reference* ref, CodeGenState::AccessType access);
void GetValue(Reference* ref) { AccessReference(ref, CodeGenState::LOAD); }
void SetValue(Reference* ref) { AccessReference(ref, CodeGenState::STORE); }
void InitConst(Reference* ref) {
AccessReference(ref, CodeGenState::INIT_CONST);
}
void ToBoolean(Label* true_target, Label* false_target);
// Access property from the reference (must be at the TOS).
void AccessReferenceProperty(Expression* key,
CodeGenState::AccessType access);
void GenericBinaryOperation(
Token::Value op,
const OverwriteMode overwrite_mode = NO_OVERWRITE);
void Comparison(Condition cc, bool strict = false);
// Inline small integer literals. To prevent long attacker-controlled byte
// sequences, we only inline small Smi:s.
static const int kMaxSmiInlinedBits = 16;
bool IsInlineSmi(Literal* literal);
void SmiComparison(Condition cc, Handle<Object> value, bool strict = false);
void SmiOperation(Token::Value op,
Handle<Object> value,
bool reversed,
OverwriteMode overwrite_mode);
void CallWithArguments(ZoneList<Expression*>* arguments, int position);
// Declare global variables and functions in the given array of
// name/value pairs.
virtual void DeclareGlobals(Handle<FixedArray> pairs);
// Instantiate the function boilerplate.
void InstantiateBoilerplate(Handle<JSFunction> boilerplate);
// Control flow
void Branch(bool if_true, Label* L);
void CheckStack();
void CleanStack(int num_bytes);
// Node visitors
#define DEF_VISIT(type) \
virtual void Visit##type(type* node);
NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
void RecordStatementPosition(Node* node);
// Activation frames.
void EnterJSFrame();
void ExitJSFrame();
virtual void GenerateShiftDownAndTailCall(ZoneList<Expression*>* args);
virtual void GenerateSetThisFunction(ZoneList<Expression*>* args);
virtual void GenerateGetThisFunction(ZoneList<Expression*>* args);
virtual void GenerateSetThis(ZoneList<Expression*>* args);
virtual void GenerateGetArgumentsLength(ZoneList<Expression*>* args);
virtual void GenerateSetArgumentsLength(ZoneList<Expression*>* args);
virtual void GenerateTailCallWithArguments(ZoneList<Expression*>* args);
virtual void GenerateSetArgument(ZoneList<Expression*>* args);
virtual void GenerateSquashFrame(ZoneList<Expression*>* args);
virtual void GenerateExpandFrame(ZoneList<Expression*>* args);
virtual void GenerateIsSmi(ZoneList<Expression*>* args);
virtual void GenerateIsArray(ZoneList<Expression*>* args);
virtual void GenerateArgumentsLength(ZoneList<Expression*>* args);
virtual void GenerateArgumentsAccess(ZoneList<Expression*>* args);
virtual void GenerateValueOf(ZoneList<Expression*>* args);
virtual void GenerateSetValueOf(ZoneList<Expression*>* args);
virtual void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
};
// -----------------------------------------------------------------------------
// Ia32CodeGenerator implementation
#define __ masm_->
Handle<Code> Ia32CodeGenerator::MakeCode(FunctionLiteral* flit,
Handle<Script> script,
bool is_eval) {
#ifdef ENABLE_DISASSEMBLER
bool print_code = FLAG_print_code && !Bootstrapper::IsActive();
#endif
#ifdef DEBUG
bool print_source = false;
bool print_ast = false;
const char* ftype;
if (Bootstrapper::IsActive()) {
print_source = FLAG_print_builtin_source;
print_ast = FLAG_print_builtin_ast;
print_code = FLAG_print_builtin_code;
ftype = "builtin";
} else {
print_source = FLAG_print_source;
print_ast = FLAG_print_ast;
ftype = "user-defined";
}
if (FLAG_trace_codegen || print_source || print_ast) {
PrintF("*** Generate code for %s function: ", ftype);
flit->name()->ShortPrint();
PrintF(" ***\n");
}
if (print_source) {
PrintF("--- Source from AST ---\n%s\n", PrettyPrinter().PrintProgram(flit));
}
if (print_ast) {
PrintF("--- AST ---\n%s\n", AstPrinter().PrintProgram(flit));
}
#endif // DEBUG
// Generate code.
const int initial_buffer_size = 4 * KB;
Ia32CodeGenerator cgen(initial_buffer_size, script, is_eval);
cgen.GenCode(flit);
if (cgen.HasStackOverflow()) {
ASSERT(!Top::has_pending_exception());
return Handle<Code>::null();
}
// Process any deferred code.
cgen.ProcessDeferred();
// Allocate and install the code.
CodeDesc desc;
cgen.masm()->GetCode(&desc);
ScopeInfo<> sinfo(flit->scope());
Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
Handle<Code> code = Factory::NewCode(desc, &sinfo, flags);
// Add unresolved entries in the code to the fixup list.
Bootstrapper::AddFixup(*code, cgen.masm());
#ifdef ENABLE_DISASSEMBLER
if (print_code) {
// Print the source code if available.
if (!script->IsUndefined() && !script->source()->IsUndefined()) {
PrintF("--- Raw source ---\n");
StringInputBuffer stream(String::cast(script->source()));
stream.Seek(flit->start_position());
// flit->end_position() points to the last character in the stream. We
// need to compensate by adding one to calculate the length.
int source_len = flit->end_position() - flit->start_position() + 1;
for (int i = 0; i < source_len; i++) {
if (stream.has_more()) PrintF("%c", stream.GetNext());
}
PrintF("\n\n");
}
PrintF("--- Code ---\n");
code->Disassemble();
}
#endif // ENABLE_DISASSEMBLER
return code;
}
Ia32CodeGenerator::Ia32CodeGenerator(int buffer_size,
Handle<Script> script,
bool is_eval)
: CodeGenerator(is_eval, script),
masm_(new MacroAssembler(NULL, buffer_size)),
scope_(NULL),
cc_reg_(no_condition),
state_(NULL),
is_inside_try_(false),
break_stack_height_(0) {
}
// Calling conventions:
// ebp: frame pointer
// esp: stack pointer
// edi: caller's parameter pointer
// esi: callee's context
void Ia32CodeGenerator::GenCode(FunctionLiteral* fun) {
// Record the position for debugging purposes.
__ RecordPosition(fun->start_position());
Scope* scope = fun->scope();
ZoneList<Statement*>* body = fun->body();
// Initialize state.
{ CodeGenState state;
state_ = &state;
scope_ = scope;
cc_reg_ = no_condition;
// Entry
// stack: function, receiver, arguments, return address
// esp: stack pointer
// ebp: frame pointer
// edi: caller's parameter pointer
// esi: callee's context
{ Comment cmnt(masm_, "[ enter JS frame");
EnterJSFrame();
}
// tos: code slot
#ifdef DEBUG
if (strlen(FLAG_stop_at) > 0 &&
fun->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
__ int3();
}
#endif
// This section now only allocates and copies the formals into the
// arguments object. It saves the address in ecx, which is saved
// at any point before either garbage collection or ecx is
// overwritten. The flag arguments_array_allocated communicates
// with the store into the arguments variable and guards the lazy
// pushes of ecx to TOS. The flag arguments_array_saved notes
// when the push has happened.
bool arguments_object_allocated = false;
bool arguments_object_saved = false;
// Allocate arguments object.
// The arguments object pointer needs to be saved in ecx, since we need
// to store arguments into the context.
if (scope->arguments() != NULL) {
ASSERT(scope->arguments_shadow() != NULL);
Comment cmnt(masm_, "[ allocate arguments object");
__ push(FunctionOperand());
__ CallRuntime(Runtime::kNewArguments, 1);
__ mov(ecx, Operand(eax));
arguments_object_allocated = true;
}
// Allocate space for locals and initialize them.
if (scope->num_stack_slots() > 0) {
Comment cmnt(masm_, "[ allocate space for locals");
__ Set(eax, Immediate(Factory::undefined_value()));
for (int i = scope->num_stack_slots(); i-- > 0; ) __ push(eax);
}
if (scope->num_heap_slots() > 0) {
Comment cmnt(masm_, "[ allocate local context");
// Save the arguments object pointer, if any.
if (arguments_object_allocated && !arguments_object_saved) {
__ push(Operand(ecx));
arguments_object_saved = true;
}
// Allocate local context.
// Get outer context and create a new context based on it.
__ push(FunctionOperand());
__ CallRuntime(Runtime::kNewContext, 1); // eax holds the result
if (kDebug) {
Label verified_true;
// Verify eax and esi are the same in debug mode
__ cmp(eax, Operand(esi));
__ j(equal, &verified_true);
__ int3();
__ bind(&verified_true);
}
// Update context local.
__ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
// Restore the arguments array pointer, if any.
}
// TODO(1241774): Improve this code:
// 1) only needed if we have a context
// 2) no need to recompute context ptr every single time
// 3) don't copy parameter operand code from SlotOperand!
{
Comment cmnt2(masm_, "[ copy context parameters into .context");
// Note that iteration order is relevant here! If we have the same
// parameter twice (e.g., function (x, y, x)), and that parameter
// needs to be copied into the context, it must be the last argument
// passed to the parameter that needs to be copied. This is a rare
// case so we don't check for it, instead we rely on the copying
// order: such a parameter is copied repeatedly into the same
// context location and thus the last value is what is seen inside
// the function.
for (int i = 0; i < scope->num_parameters(); i++) {
Variable* par = scope->parameter(i);
Slot* slot = par->slot();
if (slot != NULL && slot->type() == Slot::CONTEXT) {
// Save the arguments object pointer, if any.
if (arguments_object_allocated && !arguments_object_saved) {
__ push(Operand(ecx));
arguments_object_saved = true;
}
ASSERT(!scope->is_global_scope()); // no parameters in global scope
__ mov(eax, ParameterOperand(i));
// Loads ecx with context; used below in RecordWrite.
__ mov(SlotOperand(slot, ecx), eax);
int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
__ RecordWrite(ecx, offset, eax, ebx);
}
}
}
// This section stores the pointer to the arguments object that
// was allocated and copied into above. If the address was not
// saved to TOS, we push ecx onto the stack.
// Store the arguments object.
// This must happen after context initialization because
// the arguments object may be stored in the context
if (arguments_object_allocated) {
ASSERT(scope->arguments() != NULL);
ASSERT(scope->arguments_shadow() != NULL);
Comment cmnt(masm_, "[ store arguments object");
{
Reference target(this, scope->arguments());
if (!arguments_object_saved) {
__ push(Operand(ecx));
}
SetValue(&target);
}
// The value of arguments must also be stored in .arguments.
// TODO(1241813): This code can probably be improved by fusing it with
// the code that stores the arguments object above.
{
Reference target(this, scope->arguments_shadow());
Load(scope->arguments());
SetValue(&target);
}
}
// Generate code to 'execute' declarations and initialize
// functions (source elements). In case of an illegal
// redeclaration we need to handle that instead of processing the
// declarations.
if (scope->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ illegal redeclarations");
scope->VisitIllegalRedeclaration(this);
} else {
Comment cmnt(masm_, "[ declarations");
ProcessDeclarations(scope->declarations());
// Bail out if a stack-overflow exception occurred when
// processing declarations.
if (HasStackOverflow()) return;
}
if (FLAG_trace) {
__ CallRuntime(Runtime::kTraceEnter, 1);
__ push(eax);
}
CheckStack();
// Compile the body of the function in a vanilla state. Don't
// bother compiling all the code if the scope has an illegal
// redeclaration.
if (!scope->HasIllegalRedeclaration()) {
Comment cmnt(masm_, "[ function body");
#ifdef DEBUG
bool is_builtin = Bootstrapper::IsActive();
bool should_trace =
is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
if (should_trace) {
__ CallRuntime(Runtime::kDebugTrace, 1);
__ push(eax);
}
#endif
VisitStatements(body);
// Generate a return statement if necessary.
if (body->is_empty() || body->last()->AsReturnStatement() == NULL) {
Literal undefined(Factory::undefined_value());
ReturnStatement statement(&undefined);
statement.set_statement_pos(fun->end_position());
VisitReturnStatement(&statement);
}
}
state_ = NULL;
}
// Code generation state must be reset.
scope_ = NULL;
ASSERT(!has_cc());
ASSERT(state_ == NULL);
}
Operand Ia32CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
// Currently, this assertion will fail if we try to assign to
// a constant variable that is constant because it is read-only
// (such as the variable referring to a named function expression).
// We need to implement assignments to read-only variables.
// Ideally, we should do this during AST generation (by converting
// such assignments into expression statements); however, in general
// we may not be able to make the decision until past AST generation,
// that is when the entire program is known.
ASSERT(slot != NULL);
int index = slot->index();
switch (slot->type()) {
case Slot::PARAMETER: return ParameterOperand(index);
case Slot::LOCAL: {
ASSERT(0 <= index && index < scope_->num_stack_slots());
const int kLocal0Offset = JavaScriptFrameConstants::kLocal0Offset;
return Operand(ebp, kLocal0Offset - index * kPointerSize);
}
case Slot::CONTEXT: {
// Follow the context chain if necessary.
ASSERT(!tmp.is(esi)); // do not overwrite context register
Register context = esi;
int chain_length = scope_->ContextChainLength(slot->var()->scope());
for (int i = chain_length; i-- > 0;) {
// Load the closure.
// (All contexts, even 'with' contexts, have a closure,
// and it is the same for all contexts inside a function.
// There is no need to go to the function context first.)
__ mov(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
// Load the function context (which is the incoming, outer context).
__ mov(tmp, FieldOperand(tmp, JSFunction::kContextOffset));
context = tmp;
}
// We may have a 'with' context now. Get the function context.
// (In fact this mov may never be the needed, since the scope analysis
// may not permit a direct context access in this case and thus we are
// always at a function context. However it is safe to dereference be-
// cause the function context of a function context is itself. Before
// deleting this mov we should try to create a counter-example first,
// though...)
__ mov(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
return ContextOperand(tmp, index);
}
default:
UNREACHABLE();
return Operand(eax);
}
}
// Loads a value on TOS. If it is a boolean value, the result may have been
// (partially) translated into branches, or it may have set the condition code
// register. If force_cc is set, the value is forced to set the condition code
// register and no value is pushed. If the condition code register was set,
// has_cc() is true and cc_reg_ contains the condition to test for 'true'.
void Ia32CodeGenerator::LoadCondition(Expression* x,
CodeGenState::AccessType access,
Label* true_target,
Label* false_target,
bool force_cc) {
ASSERT(access == CodeGenState::LOAD ||
access == CodeGenState::LOAD_TYPEOF_EXPR);
ASSERT(!has_cc() && !is_referenced());
CodeGenState* old_state = state_;
CodeGenState new_state(access, NULL, true_target, false_target);
state_ = &new_state;
Visit(x);
state_ = old_state;
if (force_cc && !has_cc()) {
ToBoolean(true_target, false_target);
}
ASSERT(has_cc() || !force_cc);
}
void Ia32CodeGenerator::Load(Expression* x, CodeGenState::AccessType access) {
ASSERT(access == CodeGenState::LOAD ||
access == CodeGenState::LOAD_TYPEOF_EXPR);
Label true_target;
Label false_target;
LoadCondition(x, access, &true_target, &false_target, false);
if (has_cc()) {
// convert cc_reg_ into a bool
Label loaded, materialize_true;
__ j(cc_reg_, &materialize_true);
__ push(Immediate(Factory::false_value()));
__ jmp(&loaded);
__ bind(&materialize_true);
__ push(Immediate(Factory::true_value()));
__ bind(&loaded);
cc_reg_ = no_condition;
}
if (true_target.is_linked() || false_target.is_linked()) {
// we have at least one condition value
// that has been "translated" into a branch,
// thus it needs to be loaded explicitly again
Label loaded;
__ jmp(&loaded); // don't lose current TOS
bool both = true_target.is_linked() && false_target.is_linked();
// reincarnate "true", if necessary
if (true_target.is_linked()) {
__ bind(&true_target);
__ push(Immediate(Factory::true_value()));
}
// if both "true" and "false" need to be reincarnated,
// jump across code for "false"
if (both)
__ jmp(&loaded);
// reincarnate "false", if necessary
if (false_target.is_linked()) {
__ bind(&false_target);
__ push(Immediate(Factory::false_value()));
}
// everything is loaded at this point
__ bind(&loaded);
}
ASSERT(!has_cc());
}
void Ia32CodeGenerator::LoadGlobal() {
__ push(GlobalObject());
}
// TODO(1241834): Get rid of this function in favor of just using Load, now
// that we have the LOAD_TYPEOF_EXPR access type. => Need to handle
// global variables w/o reference errors elsewhere.
void Ia32CodeGenerator::LoadTypeofExpression(Expression* x) {
Variable* variable = x->AsVariableProxy()->AsVariable();
if (variable != NULL && !variable->is_this() && variable->is_global()) {
// NOTE: This is somewhat nasty. We force the compiler to load
// the variable as if through '<global>.<variable>' to make sure we
// do not get reference errors.
Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
Literal key(variable->name());
// TODO(1241834): Fetch the position from the variable instead of using
// no position.
Property property(&global, &key, kNoPosition);
Load(&property);
} else {
Load(x, CodeGenState::LOAD_TYPEOF_EXPR);
}
}
Reference::Reference(Ia32CodeGenerator* cgen, Expression* expression)
: cgen_(cgen), expression_(expression), type_(ILLEGAL) {
cgen->LoadReference(this);
}
Reference::~Reference() {
cgen_->UnloadReference(this);
}
void Ia32CodeGenerator::LoadReference(Reference* ref) {
Expression* e = ref->expression();
Property* property = e->AsProperty();
Variable* var = e->AsVariableProxy()->AsVariable();
if (property != NULL) {
Load(property->obj());
// Used a named reference if the key is a literal symbol.
// We don't use a named reference if they key is a string that can be
// legally parsed as an integer. This is because, otherwise we don't
// get into the slow case code that handles [] on String objects.
Literal* literal = property->key()->AsLiteral();
uint32_t dummy;
if (literal != NULL && literal->handle()->IsSymbol() &&
!String::cast(*(literal->handle()))->AsArrayIndex(&dummy)) {
ref->set_type(Reference::NAMED);
} else {
Load(property->key());
ref->set_type(Reference::KEYED);
}
} else if (var != NULL) {
if (var->is_global()) {
// global variable
LoadGlobal();
ref->set_type(Reference::NAMED);
} else {
// local variable
ref->set_type(Reference::EMPTY);
}
} else {
Load(e);
__ CallRuntime(Runtime::kThrowReferenceError, 1);
__ push(eax);
}
}
void Ia32CodeGenerator::UnloadReference(Reference* ref) {
// Pop n references on the stack while preserving TOS
Comment cmnt(masm_, "[ UnloadReference");
int size = ref->size();
if (size <= 0) {
// Do nothing. No popping is necessary.
} else if (size == 1) {
__ pop(eax);
__ mov(TOS, eax);
} else {
__ pop(eax);
__ add(Operand(esp), Immediate(size * kPointerSize));
__ push(eax);
}
}
void Ia32CodeGenerator::AccessReference(Reference* ref,
CodeGenState::AccessType access) {
ASSERT(!has_cc());
ASSERT(ref->type() != Reference::ILLEGAL);
CodeGenState* old_state = state_;
CodeGenState new_state(access, ref, true_target(), false_target());
state_ = &new_state;
Visit(ref->expression());
state_ = old_state;
}
#undef __
#define __ masm->
class ToBooleanStub: public CodeStub {
public:
ToBooleanStub() { }
void Generate(MacroAssembler* masm);
private:
Major MajorKey() { return ToBoolean; }
int MinorKey() { return 0; }
const char* GetName() { return "ToBooleanStub"; }
#ifdef DEBUG
void Print() {
PrintF("ToBooleanStub\n");
}
#endif
};
// NOTE: The stub does not handle the inlined cases (Smis, Booleans, undefined).
void ToBooleanStub::Generate(MacroAssembler* masm) {
Label false_result, true_result, not_string;
__ mov(eax, Operand(esp, 1 * kPointerSize));
// 'null' => false.
__ cmp(eax, Factory::null_value());
__ j(equal, &false_result);
// Get the map and type of the heap object.
__ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
__ movzx_b(ecx, FieldOperand(edx, Map::kInstanceTypeOffset));
// Undetectable => false.
__ movzx_b(ebx, FieldOperand(edx, Map::kBitFieldOffset));
__ and_(ebx, 1 << Map::kIsUndetectable);
__ j(not_zero, &false_result);
// JavaScript object => true.
__ cmp(ecx, JS_OBJECT_TYPE);
__ j(above_equal, &true_result);
// String value => false iff empty.
__ cmp(ecx, FIRST_NONSTRING_TYPE);
__ j(above_equal, ¬_string);
__ and_(ecx, kStringSizeMask);
__ cmp(ecx, kShortStringTag);
__ j(not_equal, &true_result); // Empty string is always short.
__ mov(edx, FieldOperand(eax, String::kLengthOffset));
__ shr(edx, String::kShortLengthShift);
__ j(zero, &false_result);
__ jmp(&true_result);
__ bind(¬_string);
// HeapNumber => false iff +0, -0, or NaN.
__ cmp(edx, Factory::heap_number_map());
__ j(not_equal, &true_result);
__ fldz();
__ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
__ fucompp();
__ push(eax);
__ fnstsw_ax();
__ sahf();
__ pop(eax);
__ j(zero, &false_result);
__ jmp(&true_result);
// Return 1/0 for true/false in eax.
__ bind(&true_result);
__ mov(eax, 1);
__ ret(1 * kPointerSize);
__ bind(&false_result);
__ mov(eax, 0);
__ ret(1 * kPointerSize);
}
#undef __
#define __ masm_->
// ECMA-262, section 9.2, page 30: ToBoolean(). Pop the top of stack and
// convert it to a boolean in the condition code register or jump to
// 'false_target'/'true_target' as appropriate.
void Ia32CodeGenerator::ToBoolean(Label* true_target, Label* false_target) {
Comment cmnt(masm_, "[ ToBoolean");
// The value to convert should be popped from the stack.
__ pop(eax);
// Fast case checks.
// 'false' => false.
__ cmp(eax, Factory::false_value());
__ j(equal, false_target);
// 'true' => true.
__ cmp(eax, Factory::true_value());
__ j(equal, true_target);
// 'undefined' => false.
__ cmp(eax, Factory::undefined_value());
__ j(equal, false_target);
// Smi => false iff zero.
ASSERT(kSmiTag == 0);
__ test(eax, Operand(eax));
__ j(zero, false_target);
__ test(eax, Immediate(kSmiTagMask));
__ j(zero, true_target);
// Call the stub for all other cases.
__ push(eax); // Undo the pop(eax) from above.
ToBooleanStub stub;
__ CallStub(&stub);
// Convert result (eax) to condition code.
__ test(eax, Operand(eax));
ASSERT(not_equal == not_zero);
cc_reg_ = not_equal;
}
void Ia32CodeGenerator::AccessReferenceProperty(
Expression* key,
CodeGenState::AccessType access) {
Reference::Type type = ref()->type();
ASSERT(type != Reference::ILLEGAL);
// TODO(1241834): Make sure that this is sufficient. If there is a chance
// that reference errors can be thrown below, we must distinguish
// between the 2 kinds of loads (typeof expression loads must not
// throw a reference error).