blob: 56cf978d3d6d8f4e7dc7c0636cb4f05ac84c0355 [file] [log] [blame]
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_IA32_CODEGEN_IA32_H_
29#define V8_IA32_CODEGEN_IA32_H_
30
31namespace v8 {
32namespace internal {
33
34// Forward declarations
35class DeferredCode;
36class RegisterAllocator;
37class RegisterFile;
38
39enum InitState { CONST_INIT, NOT_CONST_INIT };
40enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
41
42
43// -------------------------------------------------------------------------
44// Reference support
45
Leon Clarkeeab96aa2010-01-27 16:31:12 +000046// A reference is a C++ stack-allocated object that keeps an ECMA
47// reference on the execution stack while in scope. For variables
48// the reference is empty, indicating that it isn't necessary to
49// store state on the stack for keeping track of references to those.
50// For properties, we keep either one (named) or two (indexed) values
51// on the execution stack to represent the reference.
52
Steve Blocka7e24c12009-10-30 11:49:00 +000053class Reference BASE_EMBEDDED {
54 public:
55 // The values of the types is important, see size().
Leon Clarkeeab96aa2010-01-27 16:31:12 +000056 enum Type { ILLEGAL = -1, SLOT = 0, NAMED = 1, KEYED = 2 };
57 Reference(CodeGenerator* cgen, Expression* expression);
Steve Blocka7e24c12009-10-30 11:49:00 +000058 ~Reference();
59
60 Expression* expression() const { return expression_; }
61 Type type() const { return type_; }
62 void set_type(Type value) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +000063 ASSERT(type_ == ILLEGAL);
Steve Blocka7e24c12009-10-30 11:49:00 +000064 type_ = value;
65 }
66
67 // The size the reference takes up on the stack.
Leon Clarkeeab96aa2010-01-27 16:31:12 +000068 int size() const { return (type_ == ILLEGAL) ? 0 : type_; }
Steve Blocka7e24c12009-10-30 11:49:00 +000069
70 bool is_illegal() const { return type_ == ILLEGAL; }
71 bool is_slot() const { return type_ == SLOT; }
72 bool is_property() const { return type_ == NAMED || type_ == KEYED; }
73
74 // Return the name. Only valid for named property references.
75 Handle<String> GetName();
76
77 // Generate code to push the value of the reference on top of the
78 // expression stack. The reference is expected to be already on top of
Leon Clarkeeab96aa2010-01-27 16:31:12 +000079 // the expression stack, and it is left in place with its value above it.
Steve Blockd0582a62009-12-15 09:54:21 +000080 void GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +000081
82 // Like GetValue except that the slot is expected to be written to before
Leon Clarkeeab96aa2010-01-27 16:31:12 +000083 // being read from again. Thae value of the reference may be invalidated,
Steve Blocka7e24c12009-10-30 11:49:00 +000084 // causing subsequent attempts to read it to fail.
Steve Blockd0582a62009-12-15 09:54:21 +000085 void TakeValue();
Steve Blocka7e24c12009-10-30 11:49:00 +000086
87 // Generate code to store the value on top of the expression stack in the
88 // reference. The reference is expected to be immediately below the value
Leon Clarkeeab96aa2010-01-27 16:31:12 +000089 // on the expression stack. The stored value is left in place (with the
90 // reference intact below it) to support chained assignments.
Steve Blocka7e24c12009-10-30 11:49:00 +000091 void SetValue(InitState init_state);
92
93 private:
94 CodeGenerator* cgen_;
95 Expression* expression_;
96 Type type_;
97};
98
99
100// -------------------------------------------------------------------------
101// Control destinations.
102
103// A control destination encapsulates a pair of jump targets and a
104// flag indicating which one is the preferred fall-through. The
105// preferred fall-through must be unbound, the other may be already
106// bound (ie, a backward target).
107//
108// The true and false targets may be jumped to unconditionally or
109// control may split conditionally. Unconditional jumping and
110// splitting should be emitted in tail position (as the last thing
111// when compiling an expression) because they can cause either label
112// to be bound or the non-fall through to be jumped to leaving an
113// invalid virtual frame.
114//
115// The labels in the control destination can be extracted and
116// manipulated normally without affecting the state of the
117// destination.
118
119class ControlDestination BASE_EMBEDDED {
120 public:
121 ControlDestination(JumpTarget* true_target,
122 JumpTarget* false_target,
123 bool true_is_fall_through)
124 : true_target_(true_target),
125 false_target_(false_target),
126 true_is_fall_through_(true_is_fall_through),
127 is_used_(false) {
128 ASSERT(true_is_fall_through ? !true_target->is_bound()
129 : !false_target->is_bound());
130 }
131
132 // Accessors for the jump targets. Directly jumping or branching to
133 // or binding the targets will not update the destination's state.
134 JumpTarget* true_target() const { return true_target_; }
135 JumpTarget* false_target() const { return false_target_; }
136
137 // True if the the destination has been jumped to unconditionally or
138 // control has been split to both targets. This predicate does not
139 // test whether the targets have been extracted and manipulated as
140 // raw jump targets.
141 bool is_used() const { return is_used_; }
142
143 // True if the destination is used and the true target (respectively
144 // false target) was the fall through. If the target is backward,
145 // "fall through" included jumping unconditionally to it.
146 bool true_was_fall_through() const {
147 return is_used_ && true_is_fall_through_;
148 }
149
150 bool false_was_fall_through() const {
151 return is_used_ && !true_is_fall_through_;
152 }
153
154 // Emit a branch to one of the true or false targets, and bind the
155 // other target. Because this binds the fall-through target, it
156 // should be emitted in tail position (as the last thing when
157 // compiling an expression).
158 void Split(Condition cc) {
159 ASSERT(!is_used_);
160 if (true_is_fall_through_) {
161 false_target_->Branch(NegateCondition(cc));
162 true_target_->Bind();
163 } else {
164 true_target_->Branch(cc);
165 false_target_->Bind();
166 }
167 is_used_ = true;
168 }
169
170 // Emit an unconditional jump in tail position, to the true target
171 // (if the argument is true) or the false target. The "jump" will
172 // actually bind the jump target if it is forward, jump to it if it
173 // is backward.
174 void Goto(bool where) {
175 ASSERT(!is_used_);
176 JumpTarget* target = where ? true_target_ : false_target_;
177 if (target->is_bound()) {
178 target->Jump();
179 } else {
180 target->Bind();
181 }
182 is_used_ = true;
183 true_is_fall_through_ = where;
184 }
185
186 // Mark this jump target as used as if Goto had been called, but
187 // without generating a jump or binding a label (the control effect
188 // should have already happened). This is used when the left
189 // subexpression of the short-circuit boolean operators are
190 // compiled.
191 void Use(bool where) {
192 ASSERT(!is_used_);
193 ASSERT((where ? true_target_ : false_target_)->is_bound());
194 is_used_ = true;
195 true_is_fall_through_ = where;
196 }
197
198 // Swap the true and false targets but keep the same actual label as
199 // the fall through. This is used when compiling negated
200 // expressions, where we want to swap the targets but preserve the
201 // state.
202 void Invert() {
203 JumpTarget* temp_target = true_target_;
204 true_target_ = false_target_;
205 false_target_ = temp_target;
206
207 true_is_fall_through_ = !true_is_fall_through_;
208 }
209
210 private:
211 // True and false jump targets.
212 JumpTarget* true_target_;
213 JumpTarget* false_target_;
214
215 // Before using the destination: true if the true target is the
216 // preferred fall through, false if the false target is. After
217 // using the destination: true if the true target was actually used
218 // as the fall through, false if the false target was.
219 bool true_is_fall_through_;
220
221 // True if the Split or Goto functions have been called.
222 bool is_used_;
223};
224
225
226// -------------------------------------------------------------------------
227// Code generation state
228
229// The state is passed down the AST by the code generator (and back up, in
230// the form of the state of the jump target pair). It is threaded through
231// the call stack. Constructing a state implicitly pushes it on the owning
232// code generator's stack of states, and destroying one implicitly pops it.
233//
234// The code generator state is only used for expressions, so statements have
235// the initial state.
236
237class CodeGenState BASE_EMBEDDED {
238 public:
239 // Create an initial code generator state. Destroying the initial state
240 // leaves the code generator with a NULL state.
241 explicit CodeGenState(CodeGenerator* owner);
242
243 // Create a code generator state based on a code generator's current
Steve Blockd0582a62009-12-15 09:54:21 +0000244 // state. The new state has its own control destination.
245 CodeGenState(CodeGenerator* owner, ControlDestination* destination);
Steve Blocka7e24c12009-10-30 11:49:00 +0000246
247 // Destroy a code generator state and restore the owning code generator's
248 // previous state.
249 ~CodeGenState();
250
251 // Accessors for the state.
Steve Blocka7e24c12009-10-30 11:49:00 +0000252 ControlDestination* destination() const { return destination_; }
253
254 private:
255 // The owning code generator.
256 CodeGenerator* owner_;
257
Steve Blocka7e24c12009-10-30 11:49:00 +0000258 // A control destination in case the expression has a control-flow
259 // effect.
260 ControlDestination* destination_;
261
262 // The previous state of the owning code generator, restored when
263 // this state is destroyed.
264 CodeGenState* previous_;
265};
266
267
268// -------------------------------------------------------------------------
Leon Clarkee46be812010-01-19 14:06:41 +0000269// Arguments allocation mode.
Steve Blocka7e24c12009-10-30 11:49:00 +0000270
271enum ArgumentsAllocationMode {
272 NO_ARGUMENTS_ALLOCATION,
273 EAGER_ARGUMENTS_ALLOCATION,
274 LAZY_ARGUMENTS_ALLOCATION
275};
276
277
278// -------------------------------------------------------------------------
279// CodeGenerator
280
281class CodeGenerator: public AstVisitor {
282 public:
283 // Takes a function literal, generates code for it. This function should only
284 // be called by compiler.cc.
285 static Handle<Code> MakeCode(FunctionLiteral* fun,
286 Handle<Script> script,
287 bool is_eval);
288
Steve Block3ce2e202009-11-05 08:53:23 +0000289 // Printing of AST, etc. as requested by flags.
290 static void MakeCodePrologue(FunctionLiteral* fun);
291
292 // Allocate and install the code.
293 static Handle<Code> MakeCodeEpilogue(FunctionLiteral* fun,
294 MacroAssembler* masm,
295 Code::Flags flags,
296 Handle<Script> script);
297
Steve Blocka7e24c12009-10-30 11:49:00 +0000298#ifdef ENABLE_LOGGING_AND_PROFILING
299 static bool ShouldGenerateLog(Expression* type);
300#endif
301
Steve Block3ce2e202009-11-05 08:53:23 +0000302 static void RecordPositions(MacroAssembler* masm, int pos);
303
Steve Blocka7e24c12009-10-30 11:49:00 +0000304 // Accessors
305 MacroAssembler* masm() { return masm_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000306 VirtualFrame* frame() const { return frame_; }
Steve Blockd0582a62009-12-15 09:54:21 +0000307 Handle<Script> script() { return script_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000308
309 bool has_valid_frame() const { return frame_ != NULL; }
310
311 // Set the virtual frame to be new_frame, with non-frame register
312 // reference counts given by non_frame_registers. The non-frame
313 // register reference counts of the old frame are returned in
314 // non_frame_registers.
315 void SetFrame(VirtualFrame* new_frame, RegisterFile* non_frame_registers);
316
317 void DeleteFrame();
318
319 RegisterAllocator* allocator() const { return allocator_; }
320
321 CodeGenState* state() { return state_; }
322 void set_state(CodeGenState* state) { state_ = state; }
323
324 void AddDeferred(DeferredCode* code) { deferred_.Add(code); }
325
326 bool in_spilled_code() const { return in_spilled_code_; }
327 void set_in_spilled_code(bool flag) { in_spilled_code_ = flag; }
328
329 private:
330 // Construction/Destruction
331 CodeGenerator(int buffer_size, Handle<Script> script, bool is_eval);
332 virtual ~CodeGenerator() { delete masm_; }
333
334 // Accessors
335 Scope* scope() const { return scope_; }
336 bool is_eval() { return is_eval_; }
337
338 // Generating deferred code.
339 void ProcessDeferred();
340
341 // State
Steve Blocka7e24c12009-10-30 11:49:00 +0000342 ControlDestination* destination() const { return state_->destination(); }
343
344 // Track loop nesting level.
345 int loop_nesting() const { return loop_nesting_; }
346 void IncrementLoopNesting() { loop_nesting_++; }
347 void DecrementLoopNesting() { loop_nesting_--; }
348
349 // Node visitors.
350 void VisitStatements(ZoneList<Statement*>* statements);
351
352#define DEF_VISIT(type) \
353 void Visit##type(type* node);
354 AST_NODE_LIST(DEF_VISIT)
355#undef DEF_VISIT
356
357 // Visit a statement and then spill the virtual frame if control flow can
358 // reach the end of the statement (ie, it does not exit via break,
359 // continue, return, or throw). This function is used temporarily while
360 // the code generator is being transformed.
361 void VisitAndSpill(Statement* statement);
362
363 // Visit a list of statements and then spill the virtual frame if control
364 // flow can reach the end of the list.
365 void VisitStatementsAndSpill(ZoneList<Statement*>* statements);
366
367 // Main code generation function
368 void GenCode(FunctionLiteral* fun);
369
370 // Generate the return sequence code. Should be called no more than
371 // once per compiled function, immediately after binding the return
372 // target (which can not be done more than once).
373 void GenerateReturnSequence(Result* return_value);
374
375 // Returns the arguments allocation mode.
376 ArgumentsAllocationMode ArgumentsMode() const;
377
378 // Store the arguments object and allocate it if necessary.
379 Result StoreArgumentsObject(bool initial);
380
381 // The following are used by class Reference.
382 void LoadReference(Reference* ref);
383 void UnloadReference(Reference* ref);
384
Steve Block3ce2e202009-11-05 08:53:23 +0000385 static Operand ContextOperand(Register context, int index) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 return Operand(context, Context::SlotOffset(index));
387 }
388
389 Operand SlotOperand(Slot* slot, Register tmp);
390
391 Operand ContextSlotOperandCheckExtensions(Slot* slot,
392 Result tmp,
393 JumpTarget* slow);
394
395 // Expressions
Steve Block3ce2e202009-11-05 08:53:23 +0000396 static Operand GlobalObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000397 return ContextOperand(esi, Context::GLOBAL_INDEX);
398 }
399
400 void LoadCondition(Expression* x,
Steve Blocka7e24c12009-10-30 11:49:00 +0000401 ControlDestination* destination,
402 bool force_control);
Steve Blockd0582a62009-12-15 09:54:21 +0000403 void Load(Expression* expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 void LoadGlobal();
405 void LoadGlobalReceiver();
406
407 // Generate code to push the value of an expression on top of the frame
408 // and then spill the frame fully to memory. This function is used
409 // temporarily while the code generator is being transformed.
Steve Blockd0582a62009-12-15 09:54:21 +0000410 void LoadAndSpill(Expression* expression);
Steve Blocka7e24c12009-10-30 11:49:00 +0000411
412 // Read a value from a slot and leave it on top of the expression stack.
413 void LoadFromSlot(Slot* slot, TypeofState typeof_state);
414 void LoadFromSlotCheckForArguments(Slot* slot, TypeofState typeof_state);
415 Result LoadFromGlobalSlotCheckExtensions(Slot* slot,
416 TypeofState typeof_state,
417 JumpTarget* slow);
418
419 // Store the value on top of the expression stack into a slot, leaving the
420 // value in place.
421 void StoreToSlot(Slot* slot, InitState init_state);
422
423 // Special code for typeof expressions: Unfortunately, we must
424 // be careful when loading the expression in 'typeof'
425 // expressions. We are not allowed to throw reference errors for
426 // non-existing properties of the global object, so we must make it
427 // look like an explicit property access, instead of an access
428 // through the context chain.
429 void LoadTypeofExpression(Expression* x);
430
431 // Translate the value on top of the frame into control flow to the
432 // control destination.
433 void ToBoolean(ControlDestination* destination);
434
435 void GenericBinaryOperation(
436 Token::Value op,
Leon Clarkee46be812010-01-19 14:06:41 +0000437 StaticType* type,
Steve Blocka7e24c12009-10-30 11:49:00 +0000438 OverwriteMode overwrite_mode);
439
440 // If possible, combine two constant smi values using op to produce
441 // a smi result, and push it on the virtual frame, all at compile time.
442 // Returns true if it succeeds. Otherwise it has no effect.
443 bool FoldConstantSmis(Token::Value op, int left, int right);
444
445 // Emit code to perform a binary operation on a constant
446 // smi and a likely smi. Consumes the Result *operand.
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000447 void ConstantSmiBinaryOperation(Token::Value op,
448 Result* operand,
449 Handle<Object> constant_operand,
450 StaticType* type,
451 bool reversed,
452 OverwriteMode overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000453
454 // Emit code to perform a binary operation on two likely smis.
455 // The code to handle smi arguments is produced inline.
456 // Consumes the Results *left and *right.
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000457 void LikelySmiBinaryOperation(Token::Value op,
458 Result* left,
459 Result* right,
460 OverwriteMode overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000461
Leon Clarkee46be812010-01-19 14:06:41 +0000462 void Comparison(AstNode* node,
463 Condition cc,
Steve Blocka7e24c12009-10-30 11:49:00 +0000464 bool strict,
465 ControlDestination* destination);
466
467 // To prevent long attacker-controlled byte sequences, integer constants
468 // from the JavaScript source are loaded in two parts if they are larger
469 // than 16 bits.
470 static const int kMaxSmiInlinedBits = 16;
471 bool IsUnsafeSmi(Handle<Object> value);
Steve Blockd0582a62009-12-15 09:54:21 +0000472 // Load an integer constant x into a register target or into the stack using
Steve Blocka7e24c12009-10-30 11:49:00 +0000473 // at most 16 bits of user-controlled data per assembly operation.
Steve Blockd0582a62009-12-15 09:54:21 +0000474 void MoveUnsafeSmi(Register target, Handle<Object> value);
475 void StoreUnsafeSmiToLocal(int offset, Handle<Object> value);
476 void PushUnsafeSmi(Handle<Object> value);
Steve Blocka7e24c12009-10-30 11:49:00 +0000477
Leon Clarkee46be812010-01-19 14:06:41 +0000478 void CallWithArguments(ZoneList<Expression*>* arguments,
479 CallFunctionFlags flags,
480 int position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000481
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000482 // Use an optimized version of Function.prototype.apply that avoid
483 // allocating the arguments object and just copies the arguments
484 // from the stack.
485 void CallApplyLazy(Property* apply,
Steve Blocka7e24c12009-10-30 11:49:00 +0000486 Expression* receiver,
487 VariableProxy* arguments,
488 int position);
489
490 void CheckStack();
491
492 struct InlineRuntimeLUT {
493 void (CodeGenerator::*method)(ZoneList<Expression*>*);
494 const char* name;
495 };
496
497 static InlineRuntimeLUT* FindInlineRuntimeLUT(Handle<String> name);
498 bool CheckForInlineRuntimeCall(CallRuntime* node);
499 static bool PatchInlineRuntimeEntry(Handle<String> name,
500 const InlineRuntimeLUT& new_entry,
501 InlineRuntimeLUT* old_entry);
502
Steve Blocka7e24c12009-10-30 11:49:00 +0000503 void ProcessDeclarations(ZoneList<Declaration*>* declarations);
504
Steve Block3ce2e202009-11-05 08:53:23 +0000505 static Handle<Code> ComputeCallInitialize(int argc, InLoopFlag in_loop);
Steve Blocka7e24c12009-10-30 11:49:00 +0000506
507 // Declare global variables and functions in the given array of
508 // name/value pairs.
509 void DeclareGlobals(Handle<FixedArray> pairs);
510
511 // Instantiate the function boilerplate.
512 void InstantiateBoilerplate(Handle<JSFunction> boilerplate);
513
514 // Support for type checks.
515 void GenerateIsSmi(ZoneList<Expression*>* args);
516 void GenerateIsNonNegativeSmi(ZoneList<Expression*>* args);
517 void GenerateIsArray(ZoneList<Expression*>* args);
Steve Blockd0582a62009-12-15 09:54:21 +0000518 void GenerateIsObject(ZoneList<Expression*>* args);
519 void GenerateIsFunction(ZoneList<Expression*>* args);
Steve Blocka7e24c12009-10-30 11:49:00 +0000520
521 // Support for construct call checks.
522 void GenerateIsConstructCall(ZoneList<Expression*>* args);
523
524 // Support for arguments.length and arguments[?].
525 void GenerateArgumentsLength(ZoneList<Expression*>* args);
526 void GenerateArgumentsAccess(ZoneList<Expression*>* args);
527
528 // Support for accessing the class and value fields of an object.
529 void GenerateClassOf(ZoneList<Expression*>* args);
530 void GenerateValueOf(ZoneList<Expression*>* args);
531 void GenerateSetValueOf(ZoneList<Expression*>* args);
532
533 // Fast support for charCodeAt(n).
534 void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
535
536 // Fast support for object equality testing.
537 void GenerateObjectEquals(ZoneList<Expression*>* args);
538
539 void GenerateLog(ZoneList<Expression*>* args);
540
541 void GenerateGetFramePointer(ZoneList<Expression*>* args);
542
543 // Fast support for Math.random().
544 void GenerateRandomPositiveSmi(ZoneList<Expression*>* args);
545
Steve Blockd0582a62009-12-15 09:54:21 +0000546 // Fast support for StringAdd.
547 void GenerateStringAdd(ZoneList<Expression*>* args);
548
Leon Clarkee46be812010-01-19 14:06:41 +0000549 // Fast support for SubString.
550 void GenerateSubString(ZoneList<Expression*>* args);
551
552 // Fast support for StringCompare.
553 void GenerateStringCompare(ZoneList<Expression*>* args);
554
555 // Support for direct calls from JavaScript to native RegExp code.
556 void GenerateRegExpExec(ZoneList<Expression*>* args);
557
Steve Block3ce2e202009-11-05 08:53:23 +0000558 // Simple condition analysis.
559 enum ConditionAnalysis {
560 ALWAYS_TRUE,
561 ALWAYS_FALSE,
562 DONT_KNOW
563 };
564 ConditionAnalysis AnalyzeCondition(Expression* cond);
565
Steve Blocka7e24c12009-10-30 11:49:00 +0000566 // Methods used to indicate which source code is generated for. Source
567 // positions are collected by the assembler and emitted with the relocation
568 // information.
569 void CodeForFunctionPosition(FunctionLiteral* fun);
570 void CodeForReturnPosition(FunctionLiteral* fun);
571 void CodeForStatementPosition(Statement* stmt);
Steve Blockd0582a62009-12-15 09:54:21 +0000572 void CodeForDoWhileConditionPosition(DoWhileStatement* stmt);
Steve Blocka7e24c12009-10-30 11:49:00 +0000573 void CodeForSourcePosition(int pos);
574
575#ifdef DEBUG
576 // True if the registers are valid for entry to a block. There should
577 // be no frame-external references to (non-reserved) registers.
578 bool HasValidEntryRegisters();
579#endif
580
581 bool is_eval_; // Tells whether code is generated for eval.
582 Handle<Script> script_;
583 ZoneList<DeferredCode*> deferred_;
584
585 // Assembler
586 MacroAssembler* masm_; // to generate code
587
588 // Code generation state
589 Scope* scope_;
590 VirtualFrame* frame_;
591 RegisterAllocator* allocator_;
592 CodeGenState* state_;
593 int loop_nesting_;
594
595 // Jump targets.
596 // The target of the return from the function.
597 BreakTarget function_return_;
598
599 // True if the function return is shadowed (ie, jumping to the target
600 // function_return_ does not jump to the true function return, but rather
601 // to some unlinking code).
602 bool function_return_is_shadowed_;
603
604 // True when we are in code that expects the virtual frame to be fully
605 // spilled. Some virtual frame function are disabled in DEBUG builds when
606 // called from spilled code, because they do not leave the virtual frame
607 // in a spilled state.
608 bool in_spilled_code_;
609
610 static InlineRuntimeLUT kInlineRuntimeLUT[];
611
612 friend class VirtualFrame;
613 friend class JumpTarget;
614 friend class Reference;
615 friend class Result;
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000616 friend class FastCodeGenerator;
617 friend class CodeGenSelector;
Steve Blocka7e24c12009-10-30 11:49:00 +0000618
619 friend class CodeGeneratorPatcher; // Used in test-log-stack-tracer.cc
620
621 DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
622};
623
624
Steve Blockd0582a62009-12-15 09:54:21 +0000625// Flag that indicates how to generate code for the stub GenericBinaryOpStub.
Steve Blocka7e24c12009-10-30 11:49:00 +0000626enum GenericBinaryFlags {
Steve Block3ce2e202009-11-05 08:53:23 +0000627 NO_GENERIC_BINARY_FLAGS = 0,
628 NO_SMI_CODE_IN_STUB = 1 << 0 // Omit smi code in stub.
Steve Blocka7e24c12009-10-30 11:49:00 +0000629};
630
631
632class GenericBinaryOpStub: public CodeStub {
633 public:
Steve Blockd0582a62009-12-15 09:54:21 +0000634 GenericBinaryOpStub(Token::Value op,
Steve Blocka7e24c12009-10-30 11:49:00 +0000635 OverwriteMode mode,
636 GenericBinaryFlags flags)
Steve Blockd0582a62009-12-15 09:54:21 +0000637 : op_(op),
Steve Block3ce2e202009-11-05 08:53:23 +0000638 mode_(mode),
639 flags_(flags),
640 args_in_registers_(false),
Leon Clarkee46be812010-01-19 14:06:41 +0000641 args_reversed_(false),
642 name_(NULL) {
Steve Blockd0582a62009-12-15 09:54:21 +0000643 use_sse3_ = CpuFeatures::IsSupported(SSE3);
Steve Blocka7e24c12009-10-30 11:49:00 +0000644 ASSERT(OpBits::is_valid(Token::NUM_TOKENS));
645 }
646
Steve Block3ce2e202009-11-05 08:53:23 +0000647 // Generate code to call the stub with the supplied arguments. This will add
648 // code at the call site to prepare arguments either in registers or on the
649 // stack together with the actual call.
650 void GenerateCall(MacroAssembler* masm, Register left, Register right);
651 void GenerateCall(MacroAssembler* masm, Register left, Smi* right);
652 void GenerateCall(MacroAssembler* masm, Smi* left, Register right);
Steve Blocka7e24c12009-10-30 11:49:00 +0000653
654 private:
655 Token::Value op_;
656 OverwriteMode mode_;
657 GenericBinaryFlags flags_;
Steve Block3ce2e202009-11-05 08:53:23 +0000658 bool args_in_registers_; // Arguments passed in registers not on the stack.
659 bool args_reversed_; // Left and right argument are swapped.
Steve Blocka7e24c12009-10-30 11:49:00 +0000660 bool use_sse3_;
Leon Clarkee46be812010-01-19 14:06:41 +0000661 char* name_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000662
663 const char* GetName();
664
665#ifdef DEBUG
666 void Print() {
Steve Block3ce2e202009-11-05 08:53:23 +0000667 PrintF("GenericBinaryOpStub (op %s), "
668 "(mode %d, flags %d, registers %d, reversed %d)\n",
Steve Blocka7e24c12009-10-30 11:49:00 +0000669 Token::String(op_),
670 static_cast<int>(mode_),
Steve Block3ce2e202009-11-05 08:53:23 +0000671 static_cast<int>(flags_),
672 static_cast<int>(args_in_registers_),
673 static_cast<int>(args_reversed_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000674 }
675#endif
676
Steve Block3ce2e202009-11-05 08:53:23 +0000677 // Minor key encoding in 16 bits FRASOOOOOOOOOOMM.
Steve Blocka7e24c12009-10-30 11:49:00 +0000678 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
Steve Block3ce2e202009-11-05 08:53:23 +0000679 class OpBits: public BitField<Token::Value, 2, 10> {};
680 class SSE3Bits: public BitField<bool, 12, 1> {};
681 class ArgsInRegistersBits: public BitField<bool, 13, 1> {};
682 class ArgsReversedBits: public BitField<bool, 14, 1> {};
Steve Blocka7e24c12009-10-30 11:49:00 +0000683 class FlagBits: public BitField<GenericBinaryFlags, 15, 1> {};
684
685 Major MajorKey() { return GenericBinaryOp; }
686 int MinorKey() {
687 // Encode the parameters in a unique 16 bit value.
688 return OpBits::encode(op_)
689 | ModeBits::encode(mode_)
690 | FlagBits::encode(flags_)
Steve Block3ce2e202009-11-05 08:53:23 +0000691 | SSE3Bits::encode(use_sse3_)
692 | ArgsInRegistersBits::encode(args_in_registers_)
693 | ArgsReversedBits::encode(args_reversed_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000694 }
Steve Block3ce2e202009-11-05 08:53:23 +0000695
Steve Blocka7e24c12009-10-30 11:49:00 +0000696 void Generate(MacroAssembler* masm);
Steve Block3ce2e202009-11-05 08:53:23 +0000697 void GenerateSmiCode(MacroAssembler* masm, Label* slow);
698 void GenerateLoadArguments(MacroAssembler* masm);
699 void GenerateReturn(MacroAssembler* masm);
700
701 bool ArgsInRegistersSupported() {
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000702 return ((op_ == Token::ADD) || (op_ == Token::SUB)
703 || (op_ == Token::MUL) || (op_ == Token::DIV))
704 && flags_ != NO_SMI_CODE_IN_STUB;
Steve Block3ce2e202009-11-05 08:53:23 +0000705 }
706 bool IsOperationCommutative() {
707 return (op_ == Token::ADD) || (op_ == Token::MUL);
708 }
709
710 void SetArgsInRegisters() { args_in_registers_ = true; }
711 void SetArgsReversed() { args_reversed_ = true; }
712 bool HasSmiCodeInStub() { return (flags_ & NO_SMI_CODE_IN_STUB) == 0; }
Leon Clarkeeab96aa2010-01-27 16:31:12 +0000713 bool HasArgumentsInRegisters() { return args_in_registers_; }
714 bool HasArgumentsReversed() { return args_reversed_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000715};
716
717
Steve Blockd0582a62009-12-15 09:54:21 +0000718// Flag that indicates how to generate code for the stub StringAddStub.
719enum StringAddFlags {
720 NO_STRING_ADD_FLAGS = 0,
721 NO_STRING_CHECK_IN_STUB = 1 << 0 // Omit string check in stub.
722};
723
724
Leon Clarkee46be812010-01-19 14:06:41 +0000725class StringStubBase: public CodeStub {
726 public:
727 // Generate code for copying characters using a simple loop. This should only
728 // be used in places where the number of characters is small and the
729 // additional setup and checking in GenerateCopyCharactersREP adds too much
730 // overhead. Copying of overlapping regions is not supported.
731 void GenerateCopyCharacters(MacroAssembler* masm,
732 Register dest,
733 Register src,
734 Register count,
735 Register scratch,
736 bool ascii);
737
738 // Generate code for copying characters using the rep movs instruction.
739 // Copies ecx characters from esi to edi. Copying of overlapping regions is
740 // not supported.
741 void GenerateCopyCharactersREP(MacroAssembler* masm,
742 Register dest, // Must be edi.
743 Register src, // Must be esi.
744 Register count, // Must be ecx.
745 Register scratch, // Neither of the above.
746 bool ascii);
747};
748
749
750class StringAddStub: public StringStubBase {
Steve Blockd0582a62009-12-15 09:54:21 +0000751 public:
752 explicit StringAddStub(StringAddFlags flags) {
753 string_check_ = ((flags & NO_STRING_CHECK_IN_STUB) == 0);
754 }
755
756 private:
757 Major MajorKey() { return StringAdd; }
758 int MinorKey() { return string_check_ ? 0 : 1; }
759
760 void Generate(MacroAssembler* masm);
761
Steve Blockd0582a62009-12-15 09:54:21 +0000762 // Should the stub check whether arguments are strings?
763 bool string_check_;
764};
765
766
Leon Clarkee46be812010-01-19 14:06:41 +0000767class SubStringStub: public StringStubBase {
768 public:
769 SubStringStub() {}
770
771 private:
772 Major MajorKey() { return SubString; }
773 int MinorKey() { return 0; }
774
775 void Generate(MacroAssembler* masm);
776};
777
778
779class StringCompareStub: public StringStubBase {
780 public:
781 explicit StringCompareStub() {
782 }
783
784 // Compare two flat ascii strings and returns result in eax after popping two
785 // arguments from the stack.
786 static void GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
787 Register left,
788 Register right,
789 Register scratch1,
790 Register scratch2,
791 Register scratch3);
792
793 private:
794 Major MajorKey() { return StringCompare; }
795 int MinorKey() { return 0; }
796
797 void Generate(MacroAssembler* masm);
798};
799
800
Steve Blocka7e24c12009-10-30 11:49:00 +0000801} } // namespace v8::internal
802
803#endif // V8_IA32_CODEGEN_IA32_H_