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