Home | History | Annotate | Download | only in ia32
      1 // Copyright 2009 the V8 project authors. All rights reserved.
      2 // 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_VIRTUAL_FRAME_IA32_H_
     29 #define V8_IA32_VIRTUAL_FRAME_IA32_H_
     30 
     31 #include "number-info.h"
     32 #include "register-allocator.h"
     33 #include "scopes.h"
     34 
     35 namespace v8 {
     36 namespace internal {
     37 
     38 // -------------------------------------------------------------------------
     39 // Virtual frames
     40 //
     41 // The virtual frame is an abstraction of the physical stack frame.  It
     42 // encapsulates the parameters, frame-allocated locals, and the expression
     43 // stack.  It supports push/pop operations on the expression stack, as well
     44 // as random access to the expression stack elements, locals, and
     45 // parameters.
     46 
     47 class VirtualFrame: public ZoneObject {
     48  public:
     49   // A utility class to introduce a scope where the virtual frame is
     50   // expected to remain spilled.  The constructor spills the code
     51   // generator's current frame, but no attempt is made to require it
     52   // to stay spilled.  It is intended as documentation while the code
     53   // generator is being transformed.
     54   class SpilledScope BASE_EMBEDDED {
     55    public:
     56     SpilledScope() : previous_state_(cgen()->in_spilled_code()) {
     57       ASSERT(cgen()->has_valid_frame());
     58       cgen()->frame()->SpillAll();
     59       cgen()->set_in_spilled_code(true);
     60     }
     61 
     62     ~SpilledScope() {
     63       cgen()->set_in_spilled_code(previous_state_);
     64     }
     65 
     66    private:
     67     bool previous_state_;
     68 
     69     CodeGenerator* cgen() {return CodeGeneratorScope::Current();}
     70   };
     71 
     72   // An illegal index into the virtual frame.
     73   static const int kIllegalIndex = -1;
     74 
     75   // Construct an initial virtual frame on entry to a JS function.
     76   VirtualFrame();
     77 
     78   // Construct a virtual frame as a clone of an existing one.
     79   explicit VirtualFrame(VirtualFrame* original);
     80 
     81   CodeGenerator* cgen() { return CodeGeneratorScope::Current(); }
     82 
     83   MacroAssembler* masm() { return cgen()->masm(); }
     84 
     85   // Create a duplicate of an existing valid frame element.
     86   FrameElement CopyElementAt(int index,
     87     NumberInfo::Type info = NumberInfo::kUninitialized);
     88 
     89   // The number of elements on the virtual frame.
     90   int element_count() { return elements_.length(); }
     91 
     92   // The height of the virtual expression stack.
     93   int height() { return element_count() - expression_base_index(); }
     94 
     95   int register_location(int num) {
     96     ASSERT(num >= 0 && num < RegisterAllocator::kNumRegisters);
     97     return register_locations_[num];
     98   }
     99 
    100   int register_location(Register reg) {
    101     return register_locations_[RegisterAllocator::ToNumber(reg)];
    102   }
    103 
    104   void set_register_location(Register reg, int index) {
    105     register_locations_[RegisterAllocator::ToNumber(reg)] = index;
    106   }
    107 
    108   bool is_used(int num) {
    109     ASSERT(num >= 0 && num < RegisterAllocator::kNumRegisters);
    110     return register_locations_[num] != kIllegalIndex;
    111   }
    112 
    113   bool is_used(Register reg) {
    114     return register_locations_[RegisterAllocator::ToNumber(reg)]
    115         != kIllegalIndex;
    116   }
    117 
    118   // Add extra in-memory elements to the top of the frame to match an actual
    119   // frame (eg, the frame after an exception handler is pushed).  No code is
    120   // emitted.
    121   void Adjust(int count);
    122 
    123   // Forget count elements from the top of the frame all in-memory
    124   // (including synced) and adjust the stack pointer downward, to
    125   // match an external frame effect (examples include a call removing
    126   // its arguments, and exiting a try/catch removing an exception
    127   // handler).  No code will be emitted.
    128   void Forget(int count) {
    129     ASSERT(count >= 0);
    130     ASSERT(stack_pointer_ == element_count() - 1);
    131     stack_pointer_ -= count;
    132     ForgetElements(count);
    133   }
    134 
    135   // Forget count elements from the top of the frame without adjusting
    136   // the stack pointer downward.  This is used, for example, before
    137   // merging frames at break, continue, and return targets.
    138   void ForgetElements(int count);
    139 
    140   // Spill all values from the frame to memory.
    141   void SpillAll();
    142 
    143   // Spill all occurrences of a specific register from the frame.
    144   void Spill(Register reg) {
    145     if (is_used(reg)) SpillElementAt(register_location(reg));
    146   }
    147 
    148   // Spill all occurrences of an arbitrary register if possible.  Return the
    149   // register spilled or no_reg if it was not possible to free any register
    150   // (ie, they all have frame-external references).
    151   Register SpillAnyRegister();
    152 
    153   // Sync the range of elements in [begin, end] with memory.
    154   void SyncRange(int begin, int end);
    155 
    156   // Make this frame so that an arbitrary frame of the same height can
    157   // be merged to it.  Copies and constants are removed from the frame.
    158   void MakeMergable();
    159 
    160   // Prepare this virtual frame for merging to an expected frame by
    161   // performing some state changes that do not require generating
    162   // code.  It is guaranteed that no code will be generated.
    163   void PrepareMergeTo(VirtualFrame* expected);
    164 
    165   // Make this virtual frame have a state identical to an expected virtual
    166   // frame.  As a side effect, code may be emitted to make this frame match
    167   // the expected one.
    168   void MergeTo(VirtualFrame* expected);
    169 
    170   // Detach a frame from its code generator, perhaps temporarily.  This
    171   // tells the register allocator that it is free to use frame-internal
    172   // registers.  Used when the code generator's frame is switched from this
    173   // one to NULL by an unconditional jump.
    174   void DetachFromCodeGenerator() {
    175     RegisterAllocator* cgen_allocator = cgen()->allocator();
    176     for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
    177       if (is_used(i)) cgen_allocator->Unuse(i);
    178     }
    179   }
    180 
    181   // (Re)attach a frame to its code generator.  This informs the register
    182   // allocator that the frame-internal register references are active again.
    183   // Used when a code generator's frame is switched from NULL to this one by
    184   // binding a label.
    185   void AttachToCodeGenerator() {
    186     RegisterAllocator* cgen_allocator = cgen()->allocator();
    187     for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
    188       if (is_used(i)) cgen_allocator->Use(i);
    189     }
    190   }
    191 
    192   // Emit code for the physical JS entry and exit frame sequences.  After
    193   // calling Enter, the virtual frame is ready for use; and after calling
    194   // Exit it should not be used.  Note that Enter does not allocate space in
    195   // the physical frame for storing frame-allocated locals.
    196   void Enter();
    197   void Exit();
    198 
    199   // Prepare for returning from the frame by spilling locals.  This
    200   // avoids generating unnecessary merge code when jumping to the
    201   // shared return site.  Emits code for spills.
    202   void PrepareForReturn();
    203 
    204   // Number of local variables after when we use a loop for allocating.
    205   static const int kLocalVarBound = 10;
    206 
    207   // Allocate and initialize the frame-allocated locals.
    208   void AllocateStackSlots();
    209 
    210   // An element of the expression stack as an assembly operand.
    211   Operand ElementAt(int index) const {
    212     return Operand(esp, index * kPointerSize);
    213   }
    214 
    215   // Random-access store to a frame-top relative frame element.  The result
    216   // becomes owned by the frame and is invalidated.
    217   void SetElementAt(int index, Result* value);
    218 
    219   // Set a frame element to a constant.  The index is frame-top relative.
    220   void SetElementAt(int index, Handle<Object> value) {
    221     Result temp(value);
    222     SetElementAt(index, &temp);
    223   }
    224 
    225   void PushElementAt(int index) {
    226     PushFrameSlotAt(element_count() - index - 1);
    227   }
    228 
    229   void StoreToElementAt(int index) {
    230     StoreToFrameSlotAt(element_count() - index - 1);
    231   }
    232 
    233   // A frame-allocated local as an assembly operand.
    234   Operand LocalAt(int index) {
    235     ASSERT(0 <= index);
    236     ASSERT(index < local_count());
    237     return Operand(ebp, kLocal0Offset - index * kPointerSize);
    238   }
    239 
    240   // Push a copy of the value of a local frame slot on top of the frame.
    241   void PushLocalAt(int index) {
    242     PushFrameSlotAt(local0_index() + index);
    243   }
    244 
    245   // Push the value of a local frame slot on top of the frame and invalidate
    246   // the local slot.  The slot should be written to before trying to read
    247   // from it again.
    248   void TakeLocalAt(int index) {
    249     TakeFrameSlotAt(local0_index() + index);
    250   }
    251 
    252   // Store the top value on the virtual frame into a local frame slot.  The
    253   // value is left in place on top of the frame.
    254   void StoreToLocalAt(int index) {
    255     StoreToFrameSlotAt(local0_index() + index);
    256   }
    257 
    258   // Push the address of the receiver slot on the frame.
    259   void PushReceiverSlotAddress();
    260 
    261   // Push the function on top of the frame.
    262   void PushFunction() {
    263     PushFrameSlotAt(function_index());
    264   }
    265 
    266   // Save the value of the esi register to the context frame slot.
    267   void SaveContextRegister();
    268 
    269   // Restore the esi register from the value of the context frame
    270   // slot.
    271   void RestoreContextRegister();
    272 
    273   // A parameter as an assembly operand.
    274   Operand ParameterAt(int index) {
    275     ASSERT(-1 <= index);  // -1 is the receiver.
    276     ASSERT(index < parameter_count());
    277     return Operand(ebp, (1 + parameter_count() - index) * kPointerSize);
    278   }
    279 
    280   // Push a copy of the value of a parameter frame slot on top of the frame.
    281   void PushParameterAt(int index) {
    282     PushFrameSlotAt(param0_index() + index);
    283   }
    284 
    285   // Push the value of a paramter frame slot on top of the frame and
    286   // invalidate the parameter slot.  The slot should be written to before
    287   // trying to read from it again.
    288   void TakeParameterAt(int index) {
    289     TakeFrameSlotAt(param0_index() + index);
    290   }
    291 
    292   // Store the top value on the virtual frame into a parameter frame slot.
    293   // The value is left in place on top of the frame.
    294   void StoreToParameterAt(int index) {
    295     StoreToFrameSlotAt(param0_index() + index);
    296   }
    297 
    298   // The receiver frame slot.
    299   Operand Receiver() {
    300     return ParameterAt(-1);
    301   }
    302 
    303   // Push a try-catch or try-finally handler on top of the virtual frame.
    304   void PushTryHandler(HandlerType type);
    305 
    306   // Call stub given the number of arguments it expects on (and
    307   // removes from) the stack.
    308   Result CallStub(CodeStub* stub, int arg_count) {
    309     PrepareForCall(arg_count, arg_count);
    310     return RawCallStub(stub);
    311   }
    312 
    313   // Call stub that takes a single argument passed in eax.  The
    314   // argument is given as a result which does not have to be eax or
    315   // even a register.  The argument is consumed by the call.
    316   Result CallStub(CodeStub* stub, Result* arg);
    317 
    318   // Call stub that takes a pair of arguments passed in edx (arg0) and
    319   // eax (arg1).  The arguments are given as results which do not have
    320   // to be in the proper registers or even in registers.  The
    321   // arguments are consumed by the call.
    322   Result CallStub(CodeStub* stub, Result* arg0, Result* arg1);
    323 
    324   // Call runtime given the number of arguments expected on (and
    325   // removed from) the stack.
    326   Result CallRuntime(Runtime::Function* f, int arg_count);
    327   Result CallRuntime(Runtime::FunctionId id, int arg_count);
    328 
    329 #ifdef ENABLE_DEBUGGER_SUPPORT
    330   void DebugBreak();
    331 #endif
    332 
    333   // Invoke builtin given the number of arguments it expects on (and
    334   // removes from) the stack.
    335   Result InvokeBuiltin(Builtins::JavaScript id, InvokeFlag flag, int arg_count);
    336 
    337   // Call load IC.  Name and receiver are found on top of the frame.
    338   // Both are dropped.
    339   Result CallLoadIC(RelocInfo::Mode mode);
    340 
    341   // Call keyed load IC.  Key and receiver are found on top of the
    342   // frame.  Both are dropped.
    343   Result CallKeyedLoadIC(RelocInfo::Mode mode);
    344 
    345   // Call store IC.  If the load is contextual, value is found on top of the
    346   // frame.  If not, value and receiver are on the frame.  Both are dropped.
    347   Result CallStoreIC(Handle<String> name, bool is_contextual);
    348 
    349   // Call keyed store IC.  Value, key, and receiver are found on top
    350   // of the frame.  Key and receiver are not dropped.
    351   Result CallKeyedStoreIC();
    352 
    353   // Call call IC.  Function name, arguments, and receiver are found on top
    354   // of the frame and dropped by the call.  The argument count does not
    355   // include the receiver.
    356   Result CallCallIC(RelocInfo::Mode mode, int arg_count, int loop_nesting);
    357 
    358   // Allocate and call JS function as constructor.  Arguments,
    359   // receiver (global object), and function are found on top of the
    360   // frame.  Function is not dropped.  The argument count does not
    361   // include the receiver.
    362   Result CallConstructor(int arg_count);
    363 
    364   // Drop a number of elements from the top of the expression stack.  May
    365   // emit code to affect the physical frame.  Does not clobber any registers
    366   // excepting possibly the stack pointer.
    367   void Drop(int count);
    368 
    369   // Drop one element.
    370   void Drop() {
    371     Drop(1);
    372   }
    373 
    374   // Duplicate the top element of the frame.
    375   void Dup() {
    376     PushFrameSlotAt(element_count() - 1);
    377   }
    378 
    379   // Pop an element from the top of the expression stack.  Returns a
    380   // Result, which may be a constant or a register.
    381   Result Pop();
    382 
    383   // Pop and save an element from the top of the expression stack and
    384   // emit a corresponding pop instruction.
    385   void EmitPop(Register reg);
    386   void EmitPop(Operand operand);
    387 
    388   // Push an element on top of the expression stack and emit a
    389   // corresponding push instruction.
    390   void EmitPush(Register reg,
    391                 NumberInfo::Type info = NumberInfo::kUnknown);
    392   void EmitPush(Operand operand,
    393                 NumberInfo::Type info = NumberInfo::kUnknown);
    394   void EmitPush(Immediate immediate,
    395                 NumberInfo::Type info = NumberInfo::kUnknown);
    396 
    397   // Push an element on the virtual frame.
    398   void Push(Register reg, NumberInfo::Type info = NumberInfo::kUnknown);
    399   void Push(Handle<Object> value);
    400   void Push(Smi* value) {
    401     Push(Handle<Object> (value));
    402   }
    403 
    404   // Pushing a result invalidates it (its contents become owned by the
    405   // frame).
    406   void Push(Result* result) {
    407     // This assert will trigger if you try to push the same value twice.
    408     ASSERT(result->is_valid());
    409     if (result->is_register()) {
    410       Push(result->reg(), result->number_info());
    411     } else {
    412       ASSERT(result->is_constant());
    413       Push(result->handle());
    414     }
    415     result->Unuse();
    416   }
    417 
    418   // Pushing an expression expects that the expression is trivial (according
    419   // to Expression::IsTrivial).
    420   void Push(Expression* expr);
    421 
    422   // Nip removes zero or more elements from immediately below the top
    423   // of the frame, leaving the previous top-of-frame value on top of
    424   // the frame.  Nip(k) is equivalent to x = Pop(), Drop(k), Push(x).
    425   void Nip(int num_dropped);
    426 
    427  private:
    428   static const int kLocal0Offset = JavaScriptFrameConstants::kLocal0Offset;
    429   static const int kFunctionOffset = JavaScriptFrameConstants::kFunctionOffset;
    430   static const int kContextOffset = StandardFrameConstants::kContextOffset;
    431 
    432   static const int kHandlerSize = StackHandlerConstants::kSize / kPointerSize;
    433   static const int kPreallocatedElements = 5 + 8;  // 8 expression stack slots.
    434 
    435   ZoneList<FrameElement> elements_;
    436 
    437   // The index of the element that is at the processor's stack pointer
    438   // (the esp register).
    439   int stack_pointer_;
    440 
    441   // The index of the register frame element using each register, or
    442   // kIllegalIndex if a register is not on the frame.
    443   int register_locations_[RegisterAllocator::kNumRegisters];
    444 
    445   // The number of frame-allocated locals and parameters respectively.
    446   int parameter_count() {
    447     return cgen()->scope()->num_parameters();
    448   }
    449   int local_count() {
    450     return cgen()->scope()->num_stack_slots();
    451   }
    452 
    453   // The index of the element that is at the processor's frame pointer
    454   // (the ebp register).  The parameters, receiver, and return address
    455   // are below the frame pointer.
    456   int frame_pointer() {
    457     return parameter_count() + 2;
    458   }
    459 
    460   // The index of the first parameter.  The receiver lies below the first
    461   // parameter.
    462   int param0_index() {
    463     return 1;
    464   }
    465 
    466   // The index of the context slot in the frame.  It is immediately
    467   // above the frame pointer.
    468   int context_index() {
    469     return frame_pointer() + 1;
    470   }
    471 
    472   // The index of the function slot in the frame.  It is above the frame
    473   // pointer and the context slot.
    474   int function_index() {
    475     return frame_pointer() + 2;
    476   }
    477 
    478   // The index of the first local.  Between the frame pointer and the
    479   // locals lie the context and the function.
    480   int local0_index() {
    481     return frame_pointer() + 3;
    482   }
    483 
    484   // The index of the base of the expression stack.
    485   int expression_base_index() {
    486     return local0_index() + local_count();
    487   }
    488 
    489   // Convert a frame index into a frame pointer relative offset into the
    490   // actual stack.
    491   int fp_relative(int index) {
    492     ASSERT(index < element_count());
    493     ASSERT(frame_pointer() < element_count());  // FP is on the frame.
    494     return (frame_pointer() - index) * kPointerSize;
    495   }
    496 
    497   // Record an occurrence of a register in the virtual frame.  This has the
    498   // effect of incrementing the register's external reference count and
    499   // of updating the index of the register's location in the frame.
    500   void Use(Register reg, int index) {
    501     ASSERT(!is_used(reg));
    502     set_register_location(reg, index);
    503     cgen()->allocator()->Use(reg);
    504   }
    505 
    506   // Record that a register reference has been dropped from the frame.  This
    507   // decrements the register's external reference count and invalidates the
    508   // index of the register's location in the frame.
    509   void Unuse(Register reg) {
    510     ASSERT(is_used(reg));
    511     set_register_location(reg, kIllegalIndex);
    512     cgen()->allocator()->Unuse(reg);
    513   }
    514 
    515   // Spill the element at a particular index---write it to memory if
    516   // necessary, free any associated register, and forget its value if
    517   // constant.
    518   void SpillElementAt(int index);
    519 
    520   // Sync the element at a particular index.  If it is a register or
    521   // constant that disagrees with the value on the stack, write it to memory.
    522   // Keep the element type as register or constant, and clear the dirty bit.
    523   void SyncElementAt(int index);
    524 
    525   // Sync a single unsynced element that lies beneath or at the stack pointer.
    526   void SyncElementBelowStackPointer(int index);
    527 
    528   // Sync a single unsynced element that lies just above the stack pointer.
    529   void SyncElementByPushing(int index);
    530 
    531   // Push a copy of a frame slot (typically a local or parameter) on top of
    532   // the frame.
    533   void PushFrameSlotAt(int index);
    534 
    535   // Push a the value of a frame slot (typically a local or parameter) on
    536   // top of the frame and invalidate the slot.
    537   void TakeFrameSlotAt(int index);
    538 
    539   // Store the value on top of the frame to a frame slot (typically a local
    540   // or parameter).
    541   void StoreToFrameSlotAt(int index);
    542 
    543   // Spill all elements in registers. Spill the top spilled_args elements
    544   // on the frame.  Sync all other frame elements.
    545   // Then drop dropped_args elements from the virtual frame, to match
    546   // the effect of an upcoming call that will drop them from the stack.
    547   void PrepareForCall(int spilled_args, int dropped_args);
    548 
    549   // Move frame elements currently in registers or constants, that
    550   // should be in memory in the expected frame, to memory.
    551   void MergeMoveRegistersToMemory(VirtualFrame* expected);
    552 
    553   // Make the register-to-register moves necessary to
    554   // merge this frame with the expected frame.
    555   // Register to memory moves must already have been made,
    556   // and memory to register moves must follow this call.
    557   // This is because some new memory-to-register moves are
    558   // created in order to break cycles of register moves.
    559   // Used in the implementation of MergeTo().
    560   void MergeMoveRegistersToRegisters(VirtualFrame* expected);
    561 
    562   // Make the memory-to-register and constant-to-register moves
    563   // needed to make this frame equal the expected frame.
    564   // Called after all register-to-memory and register-to-register
    565   // moves have been made.  After this function returns, the frames
    566   // should be equal.
    567   void MergeMoveMemoryToRegisters(VirtualFrame* expected);
    568 
    569   // Invalidates a frame slot (puts an invalid frame element in it).
    570   // Copies on the frame are correctly handled, and if this slot was
    571   // the backing store of copies, the index of the new backing store
    572   // is returned.  Otherwise, returns kIllegalIndex.
    573   // Register counts are correctly updated.
    574   int InvalidateFrameSlotAt(int index);
    575 
    576   // Call a code stub that has already been prepared for calling (via
    577   // PrepareForCall).
    578   Result RawCallStub(CodeStub* stub);
    579 
    580   // Calls a code object which has already been prepared for calling
    581   // (via PrepareForCall).
    582   Result RawCallCodeObject(Handle<Code> code, RelocInfo::Mode rmode);
    583 
    584   bool Equals(VirtualFrame* other);
    585 
    586   // Classes that need raw access to the elements_ array.
    587   friend class DeferredCode;
    588   friend class JumpTarget;
    589 };
    590 
    591 } }  // namespace v8::internal
    592 
    593 #endif  // V8_IA32_VIRTUAL_FRAME_IA32_H_
    594