blob: 956f424334f20251ee17b553b155501a05e4caea [file] [log] [blame]
Leon Clarked91b9f72010-01-27 17:25:45 +00001// Copyright 2010 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
Leon Clarke4515c472010-02-03 11:58:03 +000035class CompilationInfo;
Steve Blocka7e24c12009-10-30 11:49:00 +000036class DeferredCode;
37class RegisterAllocator;
38class RegisterFile;
39
40enum InitState { CONST_INIT, NOT_CONST_INIT };
41enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
42
43
44// -------------------------------------------------------------------------
45// Reference support
46
Leon Clarked91b9f72010-01-27 17:25:45 +000047// A reference is a C++ stack-allocated object that puts a
48// reference on the virtual frame. The reference may be consumed
49// by GetValue, TakeValue, SetValue, and Codegen::UnloadReference.
50// When the lifetime (scope) of a valid reference ends, it must have
51// been consumed, and be in state UNLOADED.
Steve Blocka7e24c12009-10-30 11:49:00 +000052class Reference BASE_EMBEDDED {
53 public:
54 // The values of the types is important, see size().
Leon Clarked91b9f72010-01-27 17:25:45 +000055 enum Type { UNLOADED = -2, ILLEGAL = -1, SLOT = 0, NAMED = 1, KEYED = 2 };
56 Reference(CodeGenerator* cgen,
57 Expression* expression,
58 bool persist_after_get = false);
Steve Blocka7e24c12009-10-30 11:49:00 +000059 ~Reference();
60
61 Expression* expression() const { return expression_; }
62 Type type() const { return type_; }
63 void set_type(Type value) {
Leon Clarked91b9f72010-01-27 17:25:45 +000064 ASSERT_EQ(ILLEGAL, type_);
Steve Blocka7e24c12009-10-30 11:49:00 +000065 type_ = value;
66 }
67
Leon Clarked91b9f72010-01-27 17:25:45 +000068 void set_unloaded() {
69 ASSERT_NE(ILLEGAL, type_);
70 ASSERT_NE(UNLOADED, type_);
71 type_ = UNLOADED;
72 }
Steve Blocka7e24c12009-10-30 11:49:00 +000073 // The size the reference takes up on the stack.
Leon Clarked91b9f72010-01-27 17:25:45 +000074 int size() const {
75 return (type_ < SLOT) ? 0 : type_;
76 }
Steve Blocka7e24c12009-10-30 11:49:00 +000077
78 bool is_illegal() const { return type_ == ILLEGAL; }
79 bool is_slot() const { return type_ == SLOT; }
80 bool is_property() const { return type_ == NAMED || type_ == KEYED; }
Leon Clarked91b9f72010-01-27 17:25:45 +000081 bool is_unloaded() const { return type_ == UNLOADED; }
Steve Blocka7e24c12009-10-30 11:49:00 +000082
83 // Return the name. Only valid for named property references.
84 Handle<String> GetName();
85
86 // Generate code to push the value of the reference on top of the
87 // expression stack. The reference is expected to be already on top of
Leon Clarked91b9f72010-01-27 17:25:45 +000088 // the expression stack, and it is consumed by the call unless the
89 // reference is for a compound assignment.
90 // If the reference is not consumed, it is left in place under its value.
Steve Blockd0582a62009-12-15 09:54:21 +000091 void GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +000092
93 // Like GetValue except that the slot is expected to be written to before
Leon Clarked91b9f72010-01-27 17:25:45 +000094 // being read from again. The value of the reference may be invalidated,
Steve Blocka7e24c12009-10-30 11:49:00 +000095 // causing subsequent attempts to read it to fail.
Steve Blockd0582a62009-12-15 09:54:21 +000096 void TakeValue();
Steve Blocka7e24c12009-10-30 11:49:00 +000097
98 // Generate code to store the value on top of the expression stack in the
99 // reference. The reference is expected to be immediately below the value
Leon Clarked91b9f72010-01-27 17:25:45 +0000100 // on the expression stack. The value is stored in the location specified
101 // by the reference, and is left on top of the stack, after the reference
102 // is popped from beneath it (unloaded).
Steve Blocka7e24c12009-10-30 11:49:00 +0000103 void SetValue(InitState init_state);
104
105 private:
106 CodeGenerator* cgen_;
107 Expression* expression_;
108 Type type_;
Leon Clarked91b9f72010-01-27 17:25:45 +0000109 // Keep the reference on the stack after get, so it can be used by set later.
110 bool persist_after_get_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000111};
112
113
114// -------------------------------------------------------------------------
115// Control destinations.
116
117// A control destination encapsulates a pair of jump targets and a
118// flag indicating which one is the preferred fall-through. The
119// preferred fall-through must be unbound, the other may be already
120// bound (ie, a backward target).
121//
122// The true and false targets may be jumped to unconditionally or
123// control may split conditionally. Unconditional jumping and
124// splitting should be emitted in tail position (as the last thing
125// when compiling an expression) because they can cause either label
126// to be bound or the non-fall through to be jumped to leaving an
127// invalid virtual frame.
128//
129// The labels in the control destination can be extracted and
130// manipulated normally without affecting the state of the
131// destination.
132
133class ControlDestination BASE_EMBEDDED {
134 public:
135 ControlDestination(JumpTarget* true_target,
136 JumpTarget* false_target,
137 bool true_is_fall_through)
138 : true_target_(true_target),
139 false_target_(false_target),
140 true_is_fall_through_(true_is_fall_through),
141 is_used_(false) {
142 ASSERT(true_is_fall_through ? !true_target->is_bound()
143 : !false_target->is_bound());
144 }
145
146 // Accessors for the jump targets. Directly jumping or branching to
147 // or binding the targets will not update the destination's state.
148 JumpTarget* true_target() const { return true_target_; }
149 JumpTarget* false_target() const { return false_target_; }
150
151 // True if the the destination has been jumped to unconditionally or
152 // control has been split to both targets. This predicate does not
153 // test whether the targets have been extracted and manipulated as
154 // raw jump targets.
155 bool is_used() const { return is_used_; }
156
157 // True if the destination is used and the true target (respectively
158 // false target) was the fall through. If the target is backward,
159 // "fall through" included jumping unconditionally to it.
160 bool true_was_fall_through() const {
161 return is_used_ && true_is_fall_through_;
162 }
163
164 bool false_was_fall_through() const {
165 return is_used_ && !true_is_fall_through_;
166 }
167
168 // Emit a branch to one of the true or false targets, and bind the
169 // other target. Because this binds the fall-through target, it
170 // should be emitted in tail position (as the last thing when
171 // compiling an expression).
172 void Split(Condition cc) {
173 ASSERT(!is_used_);
174 if (true_is_fall_through_) {
175 false_target_->Branch(NegateCondition(cc));
176 true_target_->Bind();
177 } else {
178 true_target_->Branch(cc);
179 false_target_->Bind();
180 }
181 is_used_ = true;
182 }
183
184 // Emit an unconditional jump in tail position, to the true target
185 // (if the argument is true) or the false target. The "jump" will
186 // actually bind the jump target if it is forward, jump to it if it
187 // is backward.
188 void Goto(bool where) {
189 ASSERT(!is_used_);
190 JumpTarget* target = where ? true_target_ : false_target_;
191 if (target->is_bound()) {
192 target->Jump();
193 } else {
194 target->Bind();
195 }
196 is_used_ = true;
197 true_is_fall_through_ = where;
198 }
199
200 // Mark this jump target as used as if Goto had been called, but
201 // without generating a jump or binding a label (the control effect
202 // should have already happened). This is used when the left
203 // subexpression of the short-circuit boolean operators are
204 // compiled.
205 void Use(bool where) {
206 ASSERT(!is_used_);
207 ASSERT((where ? true_target_ : false_target_)->is_bound());
208 is_used_ = true;
209 true_is_fall_through_ = where;
210 }
211
212 // Swap the true and false targets but keep the same actual label as
213 // the fall through. This is used when compiling negated
214 // expressions, where we want to swap the targets but preserve the
215 // state.
216 void Invert() {
217 JumpTarget* temp_target = true_target_;
218 true_target_ = false_target_;
219 false_target_ = temp_target;
220
221 true_is_fall_through_ = !true_is_fall_through_;
222 }
223
224 private:
225 // True and false jump targets.
226 JumpTarget* true_target_;
227 JumpTarget* false_target_;
228
229 // Before using the destination: true if the true target is the
230 // preferred fall through, false if the false target is. After
231 // using the destination: true if the true target was actually used
232 // as the fall through, false if the false target was.
233 bool true_is_fall_through_;
234
235 // True if the Split or Goto functions have been called.
236 bool is_used_;
237};
238
239
240// -------------------------------------------------------------------------
241// Code generation state
242
243// The state is passed down the AST by the code generator (and back up, in
244// the form of the state of the jump target pair). It is threaded through
245// the call stack. Constructing a state implicitly pushes it on the owning
246// code generator's stack of states, and destroying one implicitly pops it.
247//
248// The code generator state is only used for expressions, so statements have
249// the initial state.
250
251class CodeGenState BASE_EMBEDDED {
252 public:
253 // Create an initial code generator state. Destroying the initial state
254 // leaves the code generator with a NULL state.
255 explicit CodeGenState(CodeGenerator* owner);
256
257 // Create a code generator state based on a code generator's current
Steve Blockd0582a62009-12-15 09:54:21 +0000258 // state. The new state has its own control destination.
259 CodeGenState(CodeGenerator* owner, ControlDestination* destination);
Steve Blocka7e24c12009-10-30 11:49:00 +0000260
261 // Destroy a code generator state and restore the owning code generator's
262 // previous state.
263 ~CodeGenState();
264
265 // Accessors for the state.
Steve Blocka7e24c12009-10-30 11:49:00 +0000266 ControlDestination* destination() const { return destination_; }
267
268 private:
269 // The owning code generator.
270 CodeGenerator* owner_;
271
Steve Blocka7e24c12009-10-30 11:49:00 +0000272 // A control destination in case the expression has a control-flow
273 // effect.
274 ControlDestination* destination_;
275
276 // The previous state of the owning code generator, restored when
277 // this state is destroyed.
278 CodeGenState* previous_;
279};
280
281
282// -------------------------------------------------------------------------
Leon Clarkee46be812010-01-19 14:06:41 +0000283// Arguments allocation mode.
Steve Blocka7e24c12009-10-30 11:49:00 +0000284
285enum ArgumentsAllocationMode {
286 NO_ARGUMENTS_ALLOCATION,
287 EAGER_ARGUMENTS_ALLOCATION,
288 LAZY_ARGUMENTS_ALLOCATION
289};
290
291
292// -------------------------------------------------------------------------
293// CodeGenerator
294
295class CodeGenerator: public AstVisitor {
296 public:
Leon Clarke4515c472010-02-03 11:58:03 +0000297 // Compilation mode. Either the compiler is used as the primary
298 // compiler and needs to setup everything or the compiler is used as
299 // the secondary compiler for split compilation and has to handle
300 // bailouts.
301 enum Mode {
302 PRIMARY,
303 SECONDARY
304 };
305
Steve Blocka7e24c12009-10-30 11:49:00 +0000306 // Takes a function literal, generates code for it. This function should only
307 // be called by compiler.cc.
308 static Handle<Code> MakeCode(FunctionLiteral* fun,
309 Handle<Script> script,
Leon Clarke4515c472010-02-03 11:58:03 +0000310 bool is_eval,
311 CompilationInfo* info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000312
Steve Block3ce2e202009-11-05 08:53:23 +0000313 // Printing of AST, etc. as requested by flags.
314 static void MakeCodePrologue(FunctionLiteral* fun);
315
316 // Allocate and install the code.
317 static Handle<Code> MakeCodeEpilogue(FunctionLiteral* fun,
318 MacroAssembler* masm,
319 Code::Flags flags,
320 Handle<Script> script);
321
Steve Blocka7e24c12009-10-30 11:49:00 +0000322#ifdef ENABLE_LOGGING_AND_PROFILING
323 static bool ShouldGenerateLog(Expression* type);
324#endif
325
Steve Block3ce2e202009-11-05 08:53:23 +0000326 static void RecordPositions(MacroAssembler* masm, int pos);
327
Steve Blocka7e24c12009-10-30 11:49:00 +0000328 // Accessors
329 MacroAssembler* masm() { return masm_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000330 VirtualFrame* frame() const { return frame_; }
Steve Blockd0582a62009-12-15 09:54:21 +0000331 Handle<Script> script() { return script_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000332
333 bool has_valid_frame() const { return frame_ != NULL; }
334
335 // Set the virtual frame to be new_frame, with non-frame register
336 // reference counts given by non_frame_registers. The non-frame
337 // register reference counts of the old frame are returned in
338 // non_frame_registers.
339 void SetFrame(VirtualFrame* new_frame, RegisterFile* non_frame_registers);
340
341 void DeleteFrame();
342
343 RegisterAllocator* allocator() const { return allocator_; }
344
345 CodeGenState* state() { return state_; }
346 void set_state(CodeGenState* state) { state_ = state; }
347
348 void AddDeferred(DeferredCode* code) { deferred_.Add(code); }
349
350 bool in_spilled_code() const { return in_spilled_code_; }
351 void set_in_spilled_code(bool flag) { in_spilled_code_ = flag; }
352
353 private:
354 // Construction/Destruction
Leon Clarke4515c472010-02-03 11:58:03 +0000355 CodeGenerator(MacroAssembler* masm, Handle<Script> script, bool is_eval);
Steve Blocka7e24c12009-10-30 11:49:00 +0000356
357 // Accessors
358 Scope* scope() const { return scope_; }
359 bool is_eval() { return is_eval_; }
360
361 // Generating deferred code.
362 void ProcessDeferred();
363
364 // State
Steve Blocka7e24c12009-10-30 11:49:00 +0000365 ControlDestination* destination() const { return state_->destination(); }
366
367 // Track loop nesting level.
368 int loop_nesting() const { return loop_nesting_; }
369 void IncrementLoopNesting() { loop_nesting_++; }
370 void DecrementLoopNesting() { loop_nesting_--; }
371
372 // Node visitors.
373 void VisitStatements(ZoneList<Statement*>* statements);
374
375#define DEF_VISIT(type) \
376 void Visit##type(type* node);
377 AST_NODE_LIST(DEF_VISIT)
378#undef DEF_VISIT
379
380 // Visit a statement and then spill the virtual frame if control flow can
381 // reach the end of the statement (ie, it does not exit via break,
382 // continue, return, or throw). This function is used temporarily while
383 // the code generator is being transformed.
384 void VisitAndSpill(Statement* statement);
385
386 // Visit a list of statements and then spill the virtual frame if control
387 // flow can reach the end of the list.
388 void VisitStatementsAndSpill(ZoneList<Statement*>* statements);
389
390 // Main code generation function
Leon Clarke4515c472010-02-03 11:58:03 +0000391 void Generate(FunctionLiteral* fun, Mode mode, CompilationInfo* info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000392
393 // Generate the return sequence code. Should be called no more than
394 // once per compiled function, immediately after binding the return
395 // target (which can not be done more than once).
396 void GenerateReturnSequence(Result* return_value);
397
398 // Returns the arguments allocation mode.
399 ArgumentsAllocationMode ArgumentsMode() const;
400
401 // Store the arguments object and allocate it if necessary.
402 Result StoreArgumentsObject(bool initial);
403
404 // The following are used by class Reference.
405 void LoadReference(Reference* ref);
406 void UnloadReference(Reference* ref);
407
Steve Block3ce2e202009-11-05 08:53:23 +0000408 static Operand ContextOperand(Register context, int index) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000409 return Operand(context, Context::SlotOffset(index));
410 }
411
412 Operand SlotOperand(Slot* slot, Register tmp);
413
414 Operand ContextSlotOperandCheckExtensions(Slot* slot,
415 Result tmp,
416 JumpTarget* slow);
417
418 // Expressions
Steve Block3ce2e202009-11-05 08:53:23 +0000419 static Operand GlobalObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 return ContextOperand(esi, Context::GLOBAL_INDEX);
421 }
422
423 void LoadCondition(Expression* x,
Steve Blocka7e24c12009-10-30 11:49:00 +0000424 ControlDestination* destination,
425 bool force_control);
Steve Blockd0582a62009-12-15 09:54:21 +0000426 void Load(Expression* expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000427 void LoadGlobal();
428 void LoadGlobalReceiver();
429
430 // Generate code to push the value of an expression on top of the frame
431 // and then spill the frame fully to memory. This function is used
432 // temporarily while the code generator is being transformed.
Steve Blockd0582a62009-12-15 09:54:21 +0000433 void LoadAndSpill(Expression* expression);
Steve Blocka7e24c12009-10-30 11:49:00 +0000434
435 // Read a value from a slot and leave it on top of the expression stack.
436 void LoadFromSlot(Slot* slot, TypeofState typeof_state);
437 void LoadFromSlotCheckForArguments(Slot* slot, TypeofState typeof_state);
438 Result LoadFromGlobalSlotCheckExtensions(Slot* slot,
439 TypeofState typeof_state,
440 JumpTarget* slow);
441
442 // Store the value on top of the expression stack into a slot, leaving the
443 // value in place.
444 void StoreToSlot(Slot* slot, InitState init_state);
445
Leon Clarked91b9f72010-01-27 17:25:45 +0000446 // Load a property of an object, returning it in a Result.
447 // The object and the property name are passed on the stack, and
448 // not changed.
449 Result EmitKeyedLoad(bool is_global);
450
Steve Blocka7e24c12009-10-30 11:49:00 +0000451 // Special code for typeof expressions: Unfortunately, we must
452 // be careful when loading the expression in 'typeof'
453 // expressions. We are not allowed to throw reference errors for
454 // non-existing properties of the global object, so we must make it
455 // look like an explicit property access, instead of an access
456 // through the context chain.
457 void LoadTypeofExpression(Expression* x);
458
459 // Translate the value on top of the frame into control flow to the
460 // control destination.
461 void ToBoolean(ControlDestination* destination);
462
463 void GenericBinaryOperation(
464 Token::Value op,
Leon Clarkee46be812010-01-19 14:06:41 +0000465 StaticType* type,
Steve Blocka7e24c12009-10-30 11:49:00 +0000466 OverwriteMode overwrite_mode);
467
468 // If possible, combine two constant smi values using op to produce
469 // a smi result, and push it on the virtual frame, all at compile time.
470 // Returns true if it succeeds. Otherwise it has no effect.
471 bool FoldConstantSmis(Token::Value op, int left, int right);
472
473 // Emit code to perform a binary operation on a constant
474 // smi and a likely smi. Consumes the Result *operand.
Leon Clarked91b9f72010-01-27 17:25:45 +0000475 Result ConstantSmiBinaryOperation(Token::Value op,
476 Result* operand,
477 Handle<Object> constant_operand,
478 StaticType* type,
479 bool reversed,
480 OverwriteMode overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000481
482 // Emit code to perform a binary operation on two likely smis.
483 // The code to handle smi arguments is produced inline.
484 // Consumes the Results *left and *right.
Leon Clarked91b9f72010-01-27 17:25:45 +0000485 Result LikelySmiBinaryOperation(Token::Value op,
486 Result* left,
487 Result* right,
488 OverwriteMode overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000489
Leon Clarkee46be812010-01-19 14:06:41 +0000490 void Comparison(AstNode* node,
491 Condition cc,
Steve Blocka7e24c12009-10-30 11:49:00 +0000492 bool strict,
493 ControlDestination* destination);
494
495 // To prevent long attacker-controlled byte sequences, integer constants
496 // from the JavaScript source are loaded in two parts if they are larger
497 // than 16 bits.
498 static const int kMaxSmiInlinedBits = 16;
499 bool IsUnsafeSmi(Handle<Object> value);
Steve Blockd0582a62009-12-15 09:54:21 +0000500 // Load an integer constant x into a register target or into the stack using
Steve Blocka7e24c12009-10-30 11:49:00 +0000501 // at most 16 bits of user-controlled data per assembly operation.
Steve Blockd0582a62009-12-15 09:54:21 +0000502 void MoveUnsafeSmi(Register target, Handle<Object> value);
503 void StoreUnsafeSmiToLocal(int offset, Handle<Object> value);
504 void PushUnsafeSmi(Handle<Object> value);
Steve Blocka7e24c12009-10-30 11:49:00 +0000505
Leon Clarkee46be812010-01-19 14:06:41 +0000506 void CallWithArguments(ZoneList<Expression*>* arguments,
507 CallFunctionFlags flags,
508 int position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000509
Leon Clarked91b9f72010-01-27 17:25:45 +0000510 // An optimized implementation of expressions of the form
511 // x.apply(y, arguments). We call x the applicand and y the receiver.
512 // The optimization avoids allocating an arguments object if possible.
513 void CallApplyLazy(Expression* applicand,
Steve Blocka7e24c12009-10-30 11:49:00 +0000514 Expression* receiver,
515 VariableProxy* arguments,
516 int position);
517
518 void CheckStack();
519
520 struct InlineRuntimeLUT {
521 void (CodeGenerator::*method)(ZoneList<Expression*>*);
522 const char* name;
523 };
524
525 static InlineRuntimeLUT* FindInlineRuntimeLUT(Handle<String> name);
526 bool CheckForInlineRuntimeCall(CallRuntime* node);
527 static bool PatchInlineRuntimeEntry(Handle<String> name,
528 const InlineRuntimeLUT& new_entry,
529 InlineRuntimeLUT* old_entry);
530
Steve Blocka7e24c12009-10-30 11:49:00 +0000531 void ProcessDeclarations(ZoneList<Declaration*>* declarations);
532
Steve Block3ce2e202009-11-05 08:53:23 +0000533 static Handle<Code> ComputeCallInitialize(int argc, InLoopFlag in_loop);
Steve Blocka7e24c12009-10-30 11:49:00 +0000534
535 // Declare global variables and functions in the given array of
536 // name/value pairs.
537 void DeclareGlobals(Handle<FixedArray> pairs);
538
539 // Instantiate the function boilerplate.
540 void InstantiateBoilerplate(Handle<JSFunction> boilerplate);
541
542 // Support for type checks.
543 void GenerateIsSmi(ZoneList<Expression*>* args);
544 void GenerateIsNonNegativeSmi(ZoneList<Expression*>* args);
545 void GenerateIsArray(ZoneList<Expression*>* args);
Steve Blockd0582a62009-12-15 09:54:21 +0000546 void GenerateIsObject(ZoneList<Expression*>* args);
547 void GenerateIsFunction(ZoneList<Expression*>* args);
Leon Clarked91b9f72010-01-27 17:25:45 +0000548 void GenerateIsUndetectableObject(ZoneList<Expression*>* args);
Steve Blocka7e24c12009-10-30 11:49:00 +0000549
550 // Support for construct call checks.
551 void GenerateIsConstructCall(ZoneList<Expression*>* args);
552
553 // Support for arguments.length and arguments[?].
554 void GenerateArgumentsLength(ZoneList<Expression*>* args);
555 void GenerateArgumentsAccess(ZoneList<Expression*>* args);
556
557 // Support for accessing the class and value fields of an object.
558 void GenerateClassOf(ZoneList<Expression*>* args);
559 void GenerateValueOf(ZoneList<Expression*>* args);
560 void GenerateSetValueOf(ZoneList<Expression*>* args);
561
562 // Fast support for charCodeAt(n).
563 void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
564
565 // Fast support for object equality testing.
566 void GenerateObjectEquals(ZoneList<Expression*>* args);
567
568 void GenerateLog(ZoneList<Expression*>* args);
569
570 void GenerateGetFramePointer(ZoneList<Expression*>* args);
571
572 // Fast support for Math.random().
573 void GenerateRandomPositiveSmi(ZoneList<Expression*>* args);
574
Steve Blockd0582a62009-12-15 09:54:21 +0000575 // Fast support for StringAdd.
576 void GenerateStringAdd(ZoneList<Expression*>* args);
577
Leon Clarkee46be812010-01-19 14:06:41 +0000578 // Fast support for SubString.
579 void GenerateSubString(ZoneList<Expression*>* args);
580
581 // Fast support for StringCompare.
582 void GenerateStringCompare(ZoneList<Expression*>* args);
583
584 // Support for direct calls from JavaScript to native RegExp code.
585 void GenerateRegExpExec(ZoneList<Expression*>* args);
586
Steve Block3ce2e202009-11-05 08:53:23 +0000587 // Simple condition analysis.
588 enum ConditionAnalysis {
589 ALWAYS_TRUE,
590 ALWAYS_FALSE,
591 DONT_KNOW
592 };
593 ConditionAnalysis AnalyzeCondition(Expression* cond);
594
Steve Blocka7e24c12009-10-30 11:49:00 +0000595 // Methods used to indicate which source code is generated for. Source
596 // positions are collected by the assembler and emitted with the relocation
597 // information.
598 void CodeForFunctionPosition(FunctionLiteral* fun);
599 void CodeForReturnPosition(FunctionLiteral* fun);
600 void CodeForStatementPosition(Statement* stmt);
Steve Blockd0582a62009-12-15 09:54:21 +0000601 void CodeForDoWhileConditionPosition(DoWhileStatement* stmt);
Steve Blocka7e24c12009-10-30 11:49:00 +0000602 void CodeForSourcePosition(int pos);
603
604#ifdef DEBUG
605 // True if the registers are valid for entry to a block. There should
606 // be no frame-external references to (non-reserved) registers.
607 bool HasValidEntryRegisters();
608#endif
609
610 bool is_eval_; // Tells whether code is generated for eval.
611 Handle<Script> script_;
612 ZoneList<DeferredCode*> deferred_;
613
614 // Assembler
615 MacroAssembler* masm_; // to generate code
616
617 // Code generation state
618 Scope* scope_;
619 VirtualFrame* frame_;
620 RegisterAllocator* allocator_;
621 CodeGenState* state_;
622 int loop_nesting_;
623
624 // Jump targets.
625 // The target of the return from the function.
626 BreakTarget function_return_;
627
628 // True if the function return is shadowed (ie, jumping to the target
629 // function_return_ does not jump to the true function return, but rather
630 // to some unlinking code).
631 bool function_return_is_shadowed_;
632
633 // True when we are in code that expects the virtual frame to be fully
634 // spilled. Some virtual frame function are disabled in DEBUG builds when
635 // called from spilled code, because they do not leave the virtual frame
636 // in a spilled state.
637 bool in_spilled_code_;
638
639 static InlineRuntimeLUT kInlineRuntimeLUT[];
640
641 friend class VirtualFrame;
642 friend class JumpTarget;
643 friend class Reference;
644 friend class Result;
Leon Clarke4515c472010-02-03 11:58:03 +0000645 friend class FastCodeGenerator;
Leon Clarked91b9f72010-01-27 17:25:45 +0000646 friend class FullCodeGenerator;
647 friend class FullCodeGenSyntaxChecker;
Steve Blocka7e24c12009-10-30 11:49:00 +0000648
649 friend class CodeGeneratorPatcher; // Used in test-log-stack-tracer.cc
650
651 DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
652};
653
654
Steve Blockd0582a62009-12-15 09:54:21 +0000655// Flag that indicates how to generate code for the stub GenericBinaryOpStub.
Steve Blocka7e24c12009-10-30 11:49:00 +0000656enum GenericBinaryFlags {
Steve Block3ce2e202009-11-05 08:53:23 +0000657 NO_GENERIC_BINARY_FLAGS = 0,
658 NO_SMI_CODE_IN_STUB = 1 << 0 // Omit smi code in stub.
Steve Blocka7e24c12009-10-30 11:49:00 +0000659};
660
661
662class GenericBinaryOpStub: public CodeStub {
663 public:
Steve Blockd0582a62009-12-15 09:54:21 +0000664 GenericBinaryOpStub(Token::Value op,
Steve Blocka7e24c12009-10-30 11:49:00 +0000665 OverwriteMode mode,
666 GenericBinaryFlags flags)
Steve Blockd0582a62009-12-15 09:54:21 +0000667 : op_(op),
Steve Block3ce2e202009-11-05 08:53:23 +0000668 mode_(mode),
669 flags_(flags),
670 args_in_registers_(false),
Leon Clarkee46be812010-01-19 14:06:41 +0000671 args_reversed_(false),
672 name_(NULL) {
Steve Blockd0582a62009-12-15 09:54:21 +0000673 use_sse3_ = CpuFeatures::IsSupported(SSE3);
Steve Blocka7e24c12009-10-30 11:49:00 +0000674 ASSERT(OpBits::is_valid(Token::NUM_TOKENS));
675 }
676
Steve Block3ce2e202009-11-05 08:53:23 +0000677 // Generate code to call the stub with the supplied arguments. This will add
678 // code at the call site to prepare arguments either in registers or on the
679 // stack together with the actual call.
680 void GenerateCall(MacroAssembler* masm, Register left, Register right);
681 void GenerateCall(MacroAssembler* masm, Register left, Smi* right);
682 void GenerateCall(MacroAssembler* masm, Smi* left, Register right);
Steve Blocka7e24c12009-10-30 11:49:00 +0000683
Leon Clarked91b9f72010-01-27 17:25:45 +0000684 Result GenerateCall(MacroAssembler* masm,
685 VirtualFrame* frame,
686 Result* left,
687 Result* right);
688
Steve Blocka7e24c12009-10-30 11:49:00 +0000689 private:
690 Token::Value op_;
691 OverwriteMode mode_;
692 GenericBinaryFlags flags_;
Steve Block3ce2e202009-11-05 08:53:23 +0000693 bool args_in_registers_; // Arguments passed in registers not on the stack.
694 bool args_reversed_; // Left and right argument are swapped.
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 bool use_sse3_;
Leon Clarkee46be812010-01-19 14:06:41 +0000696 char* name_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000697
698 const char* GetName();
699
700#ifdef DEBUG
701 void Print() {
Steve Block3ce2e202009-11-05 08:53:23 +0000702 PrintF("GenericBinaryOpStub (op %s), "
703 "(mode %d, flags %d, registers %d, reversed %d)\n",
Steve Blocka7e24c12009-10-30 11:49:00 +0000704 Token::String(op_),
705 static_cast<int>(mode_),
Steve Block3ce2e202009-11-05 08:53:23 +0000706 static_cast<int>(flags_),
707 static_cast<int>(args_in_registers_),
708 static_cast<int>(args_reversed_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000709 }
710#endif
711
Steve Block3ce2e202009-11-05 08:53:23 +0000712 // Minor key encoding in 16 bits FRASOOOOOOOOOOMM.
Steve Blocka7e24c12009-10-30 11:49:00 +0000713 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
Steve Block3ce2e202009-11-05 08:53:23 +0000714 class OpBits: public BitField<Token::Value, 2, 10> {};
715 class SSE3Bits: public BitField<bool, 12, 1> {};
716 class ArgsInRegistersBits: public BitField<bool, 13, 1> {};
717 class ArgsReversedBits: public BitField<bool, 14, 1> {};
Steve Blocka7e24c12009-10-30 11:49:00 +0000718 class FlagBits: public BitField<GenericBinaryFlags, 15, 1> {};
719
720 Major MajorKey() { return GenericBinaryOp; }
721 int MinorKey() {
722 // Encode the parameters in a unique 16 bit value.
723 return OpBits::encode(op_)
724 | ModeBits::encode(mode_)
725 | FlagBits::encode(flags_)
Steve Block3ce2e202009-11-05 08:53:23 +0000726 | SSE3Bits::encode(use_sse3_)
727 | ArgsInRegistersBits::encode(args_in_registers_)
728 | ArgsReversedBits::encode(args_reversed_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000729 }
Steve Block3ce2e202009-11-05 08:53:23 +0000730
Steve Blocka7e24c12009-10-30 11:49:00 +0000731 void Generate(MacroAssembler* masm);
Steve Block3ce2e202009-11-05 08:53:23 +0000732 void GenerateSmiCode(MacroAssembler* masm, Label* slow);
733 void GenerateLoadArguments(MacroAssembler* masm);
734 void GenerateReturn(MacroAssembler* masm);
Leon Clarked91b9f72010-01-27 17:25:45 +0000735 void GenerateHeapResultAllocation(MacroAssembler* masm, Label* alloc_failure);
Steve Block3ce2e202009-11-05 08:53:23 +0000736
737 bool ArgsInRegistersSupported() {
Leon Clarked91b9f72010-01-27 17:25:45 +0000738 return op_ == Token::ADD || op_ == Token::SUB
739 || op_ == Token::MUL || op_ == Token::DIV;
Steve Block3ce2e202009-11-05 08:53:23 +0000740 }
741 bool IsOperationCommutative() {
742 return (op_ == Token::ADD) || (op_ == Token::MUL);
743 }
744
745 void SetArgsInRegisters() { args_in_registers_ = true; }
746 void SetArgsReversed() { args_reversed_ = true; }
747 bool HasSmiCodeInStub() { return (flags_ & NO_SMI_CODE_IN_STUB) == 0; }
Leon Clarked91b9f72010-01-27 17:25:45 +0000748 bool HasArgsInRegisters() { return args_in_registers_; }
749 bool HasArgsReversed() { return args_reversed_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000750};
751
752
Steve Blockd0582a62009-12-15 09:54:21 +0000753// Flag that indicates how to generate code for the stub StringAddStub.
754enum StringAddFlags {
755 NO_STRING_ADD_FLAGS = 0,
756 NO_STRING_CHECK_IN_STUB = 1 << 0 // Omit string check in stub.
757};
758
759
Leon Clarkee46be812010-01-19 14:06:41 +0000760class StringStubBase: public CodeStub {
761 public:
762 // Generate code for copying characters using a simple loop. This should only
763 // be used in places where the number of characters is small and the
764 // additional setup and checking in GenerateCopyCharactersREP adds too much
765 // overhead. Copying of overlapping regions is not supported.
766 void GenerateCopyCharacters(MacroAssembler* masm,
767 Register dest,
768 Register src,
769 Register count,
770 Register scratch,
771 bool ascii);
772
773 // Generate code for copying characters using the rep movs instruction.
774 // Copies ecx characters from esi to edi. Copying of overlapping regions is
775 // not supported.
776 void GenerateCopyCharactersREP(MacroAssembler* masm,
777 Register dest, // Must be edi.
778 Register src, // Must be esi.
779 Register count, // Must be ecx.
780 Register scratch, // Neither of the above.
781 bool ascii);
782};
783
784
785class StringAddStub: public StringStubBase {
Steve Blockd0582a62009-12-15 09:54:21 +0000786 public:
787 explicit StringAddStub(StringAddFlags flags) {
788 string_check_ = ((flags & NO_STRING_CHECK_IN_STUB) == 0);
789 }
790
791 private:
792 Major MajorKey() { return StringAdd; }
793 int MinorKey() { return string_check_ ? 0 : 1; }
794
795 void Generate(MacroAssembler* masm);
796
Steve Blockd0582a62009-12-15 09:54:21 +0000797 // Should the stub check whether arguments are strings?
798 bool string_check_;
799};
800
801
Leon Clarkee46be812010-01-19 14:06:41 +0000802class SubStringStub: public StringStubBase {
803 public:
804 SubStringStub() {}
805
806 private:
807 Major MajorKey() { return SubString; }
808 int MinorKey() { return 0; }
809
810 void Generate(MacroAssembler* masm);
811};
812
813
814class StringCompareStub: public StringStubBase {
815 public:
816 explicit StringCompareStub() {
817 }
818
819 // Compare two flat ascii strings and returns result in eax after popping two
820 // arguments from the stack.
821 static void GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
822 Register left,
823 Register right,
824 Register scratch1,
825 Register scratch2,
826 Register scratch3);
827
828 private:
829 Major MajorKey() { return StringCompare; }
830 int MinorKey() { return 0; }
831
832 void Generate(MacroAssembler* masm);
833};
834
835
Steve Blocka7e24c12009-10-30 11:49:00 +0000836} } // namespace v8::internal
837
838#endif // V8_IA32_CODEGEN_IA32_H_