1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/lithium.h"
8 #include "src/scopes.h"
9 #include "src/serialize.h"
11 #if V8_TARGET_ARCH_IA32
12 #include "src/ia32/lithium-ia32.h" // NOLINT
13 #include "src/ia32/lithium-codegen-ia32.h" // NOLINT
14 #elif V8_TARGET_ARCH_X64
15 #include "src/x64/lithium-x64.h" // NOLINT
16 #include "src/x64/lithium-codegen-x64.h" // NOLINT
17 #elif V8_TARGET_ARCH_ARM
18 #include "src/arm/lithium-arm.h" // NOLINT
19 #include "src/arm/lithium-codegen-arm.h" // NOLINT
20 #elif V8_TARGET_ARCH_MIPS
21 #include "src/mips/lithium-mips.h" // NOLINT
22 #include "src/mips/lithium-codegen-mips.h" // NOLINT
23 #elif V8_TARGET_ARCH_ARM64
24 #include "src/arm64/lithium-arm64.h" // NOLINT
25 #include "src/arm64/lithium-codegen-arm64.h" // NOLINT
26 #elif V8_TARGET_ARCH_MIPS64
27 #include "src/mips64/lithium-mips64.h" // NOLINT
28 #include "src/mips64/lithium-codegen-mips64.h" // NOLINT
29 #elif V8_TARGET_ARCH_X87
30 #include "src/x87/lithium-x87.h" // NOLINT
31 #include "src/x87/lithium-codegen-x87.h" // NOLINT
33 #error "Unknown architecture."
40 void LOperand::PrintTo(StringStream* stream) {
41 LUnallocated* unalloc = NULL;
47 unalloc = LUnallocated::cast(this);
48 stream->Add("v%d", unalloc->virtual_register());
49 if (unalloc->basic_policy() == LUnallocated::FIXED_SLOT) {
50 stream->Add("(=%dS)", unalloc->fixed_slot_index());
53 switch (unalloc->extended_policy()) {
54 case LUnallocated::NONE:
56 case LUnallocated::FIXED_REGISTER: {
57 int reg_index = unalloc->fixed_register_index();
59 reg_index >= Register::kMaxNumAllocatableRegisters) {
60 stream->Add("(=invalid_reg#%d)", reg_index);
62 const char* register_name =
63 Register::AllocationIndexToString(reg_index);
64 stream->Add("(=%s)", register_name);
68 case LUnallocated::FIXED_DOUBLE_REGISTER: {
69 int reg_index = unalloc->fixed_register_index();
71 reg_index >= DoubleRegister::kMaxNumAllocatableRegisters) {
72 stream->Add("(=invalid_double_reg#%d)", reg_index);
74 const char* double_register_name =
75 DoubleRegister::AllocationIndexToString(reg_index);
76 stream->Add("(=%s)", double_register_name);
80 case LUnallocated::MUST_HAVE_REGISTER:
83 case LUnallocated::MUST_HAVE_DOUBLE_REGISTER:
86 case LUnallocated::WRITABLE_REGISTER:
89 case LUnallocated::SAME_AS_FIRST_INPUT:
92 case LUnallocated::ANY:
97 case CONSTANT_OPERAND:
98 stream->Add("[constant:%d]", index());
101 stream->Add("[stack:%d]", index());
103 case DOUBLE_STACK_SLOT:
104 stream->Add("[double_stack:%d]", index());
107 int reg_index = index();
108 if (reg_index < 0 || reg_index >= Register::kMaxNumAllocatableRegisters) {
109 stream->Add("(=invalid_reg#%d|R)", reg_index);
111 stream->Add("[%s|R]", Register::AllocationIndexToString(reg_index));
115 case DOUBLE_REGISTER: {
116 int reg_index = index();
118 reg_index >= DoubleRegister::kMaxNumAllocatableRegisters) {
119 stream->Add("(=invalid_double_reg#%d|R)", reg_index);
121 stream->Add("[%s|R]",
122 DoubleRegister::AllocationIndexToString(reg_index));
130 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
131 LSubKindOperand<kOperandKind, kNumCachedOperands>*
132 LSubKindOperand<kOperandKind, kNumCachedOperands>::cache = NULL;
135 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
136 void LSubKindOperand<kOperandKind, kNumCachedOperands>::SetUpCache() {
138 cache = new LSubKindOperand[kNumCachedOperands];
139 for (int i = 0; i < kNumCachedOperands; i++) {
140 cache[i].ConvertTo(kOperandKind, i);
145 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
146 void LSubKindOperand<kOperandKind, kNumCachedOperands>::TearDownCache() {
151 void LOperand::SetUpCaches() {
152 #define LITHIUM_OPERAND_SETUP(name, type, number) L##name::SetUpCache();
153 LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_SETUP)
154 #undef LITHIUM_OPERAND_SETUP
158 void LOperand::TearDownCaches() {
159 #define LITHIUM_OPERAND_TEARDOWN(name, type, number) L##name::TearDownCache();
160 LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_TEARDOWN)
161 #undef LITHIUM_OPERAND_TEARDOWN
165 bool LParallelMove::IsRedundant() const {
166 for (int i = 0; i < move_operands_.length(); ++i) {
167 if (!move_operands_[i].IsRedundant()) return false;
173 void LParallelMove::PrintDataTo(StringStream* stream) const {
175 for (int i = 0; i < move_operands_.length(); ++i) {
176 if (!move_operands_[i].IsEliminated()) {
177 LOperand* source = move_operands_[i].source();
178 LOperand* destination = move_operands_[i].destination();
179 if (!first) stream->Add(" ");
181 if (source->Equals(destination)) {
182 destination->PrintTo(stream);
184 destination->PrintTo(stream);
186 source->PrintTo(stream);
194 void LEnvironment::PrintTo(StringStream* stream) {
195 stream->Add("[id=%d|", ast_id().ToInt());
196 if (deoptimization_index() != Safepoint::kNoDeoptimizationIndex) {
197 stream->Add("deopt_id=%d|", deoptimization_index());
199 stream->Add("parameters=%d|", parameter_count());
200 stream->Add("arguments_stack_height=%d|", arguments_stack_height());
201 for (int i = 0; i < values_.length(); ++i) {
202 if (i != 0) stream->Add(";");
203 if (values_[i] == NULL) {
204 stream->Add("[hole]");
206 values_[i]->PrintTo(stream);
213 void LPointerMap::RecordPointer(LOperand* op, Zone* zone) {
214 // Do not record arguments as pointers.
215 if (op->IsStackSlot() && op->index() < 0) return;
216 DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
217 pointer_operands_.Add(op, zone);
221 void LPointerMap::RemovePointer(LOperand* op) {
222 // Do not record arguments as pointers.
223 if (op->IsStackSlot() && op->index() < 0) return;
224 DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
225 for (int i = 0; i < pointer_operands_.length(); ++i) {
226 if (pointer_operands_[i]->Equals(op)) {
227 pointer_operands_.Remove(i);
234 void LPointerMap::RecordUntagged(LOperand* op, Zone* zone) {
235 // Do not record arguments as pointers.
236 if (op->IsStackSlot() && op->index() < 0) return;
237 DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
238 untagged_operands_.Add(op, zone);
242 void LPointerMap::PrintTo(StringStream* stream) {
244 for (int i = 0; i < pointer_operands_.length(); ++i) {
245 if (i != 0) stream->Add(";");
246 pointer_operands_[i]->PrintTo(stream);
252 int StackSlotOffset(int index) {
254 // Local or spill slot. Skip the frame pointer, function, and
255 // context in the fixed part of the frame.
256 return -(index + 1) * kPointerSize -
257 StandardFrameConstants::kFixedFrameSizeFromFp;
259 // Incoming parameter. Skip the return address.
260 return -(index + 1) * kPointerSize + kFPOnStackSize + kPCOnStackSize;
265 LChunk::LChunk(CompilationInfo* info, HGraph* graph)
266 : spill_slot_count_(0),
269 instructions_(32, info->zone()),
270 pointer_maps_(8, info->zone()),
271 inlined_closures_(1, info->zone()),
272 deprecation_dependencies_(MapLess(), MapAllocator(info->zone())),
273 stability_dependencies_(MapLess(), MapAllocator(info->zone())) {}
276 LLabel* LChunk::GetLabel(int block_id) const {
277 HBasicBlock* block = graph_->blocks()->at(block_id);
278 int first_instruction = block->first_instruction_index();
279 return LLabel::cast(instructions_[first_instruction]);
283 int LChunk::LookupDestination(int block_id) const {
284 LLabel* cur = GetLabel(block_id);
285 while (cur->replacement() != NULL) {
286 cur = cur->replacement();
288 return cur->block_id();
291 Label* LChunk::GetAssemblyLabel(int block_id) const {
292 LLabel* label = GetLabel(block_id);
293 DCHECK(!label->HasReplacement());
294 return label->label();
298 void LChunk::MarkEmptyBlocks() {
299 LPhase phase("L_Mark empty blocks", this);
300 for (int i = 0; i < graph()->blocks()->length(); ++i) {
301 HBasicBlock* block = graph()->blocks()->at(i);
302 int first = block->first_instruction_index();
303 int last = block->last_instruction_index();
304 LInstruction* first_instr = instructions()->at(first);
305 LInstruction* last_instr = instructions()->at(last);
307 LLabel* label = LLabel::cast(first_instr);
308 if (last_instr->IsGoto()) {
309 LGoto* goto_instr = LGoto::cast(last_instr);
310 if (label->IsRedundant() &&
311 !label->is_loop_header()) {
312 bool can_eliminate = true;
313 for (int i = first + 1; i < last && can_eliminate; ++i) {
314 LInstruction* cur = instructions()->at(i);
316 LGap* gap = LGap::cast(cur);
317 if (!gap->IsRedundant()) {
318 can_eliminate = false;
321 can_eliminate = false;
325 label->set_replacement(GetLabel(goto_instr->block_id()));
333 void LChunk::AddInstruction(LInstruction* instr, HBasicBlock* block) {
334 LInstructionGap* gap = new (zone()) LInstructionGap(block);
335 gap->set_hydrogen_value(instr->hydrogen_value());
337 if (instr->IsControl()) {
338 instructions_.Add(gap, zone());
339 index = instructions_.length();
340 instructions_.Add(instr, zone());
342 index = instructions_.length();
343 instructions_.Add(instr, zone());
344 instructions_.Add(gap, zone());
346 if (instr->HasPointerMap()) {
347 pointer_maps_.Add(instr->pointer_map(), zone());
348 instr->pointer_map()->set_lithium_position(index);
353 LConstantOperand* LChunk::DefineConstantOperand(HConstant* constant) {
354 return LConstantOperand::Create(constant->id(), zone());
358 int LChunk::GetParameterStackSlot(int index) const {
359 // The receiver is at index 0, the first parameter at index 1, so we
360 // shift all parameter indexes down by the number of parameters, and
361 // make sure they end up negative so they are distinguishable from
363 int result = index - info()->num_parameters() - 1;
370 // A parameter relative to ebp in the arguments stub.
371 int LChunk::ParameterAt(int index) {
372 DCHECK(-1 <= index); // -1 is the receiver.
373 return (1 + info()->scope()->num_parameters() - index) *
378 LGap* LChunk::GetGapAt(int index) const {
379 return LGap::cast(instructions_[index]);
383 bool LChunk::IsGapAt(int index) const {
384 return instructions_[index]->IsGap();
388 int LChunk::NearestGapPos(int index) const {
389 while (!IsGapAt(index)) index--;
394 void LChunk::AddGapMove(int index, LOperand* from, LOperand* to) {
395 GetGapAt(index)->GetOrCreateParallelMove(
396 LGap::START, zone())->AddMove(from, to, zone());
400 HConstant* LChunk::LookupConstant(LConstantOperand* operand) const {
401 return HConstant::cast(graph_->LookupValue(operand->index()));
405 Representation LChunk::LookupLiteralRepresentation(
406 LConstantOperand* operand) const {
407 return graph_->LookupValue(operand->index())->representation();
411 void LChunk::CommitDependencies(Handle<Code> code) const {
412 for (MapSet::const_iterator it = deprecation_dependencies_.begin(),
413 iend = deprecation_dependencies_.end(); it != iend; ++it) {
414 Handle<Map> map = *it;
415 DCHECK(!map->is_deprecated());
416 DCHECK(map->CanBeDeprecated());
417 Map::AddDependentCode(map, DependentCode::kTransitionGroup, code);
420 for (MapSet::const_iterator it = stability_dependencies_.begin(),
421 iend = stability_dependencies_.end(); it != iend; ++it) {
422 Handle<Map> map = *it;
423 DCHECK(map->is_stable());
424 DCHECK(map->CanTransition());
425 Map::AddDependentCode(map, DependentCode::kPrototypeCheckGroup, code);
428 info_->CommitDependencies(code);
432 LChunk* LChunk::NewChunk(HGraph* graph) {
433 DisallowHandleAllocation no_handles;
434 DisallowHeapAllocation no_gc;
435 graph->DisallowAddingNewValues();
436 int values = graph->GetMaximumValueID();
437 CompilationInfo* info = graph->info();
438 if (values > LUnallocated::kMaxVirtualRegisters) {
439 info->set_bailout_reason(kNotEnoughVirtualRegistersForValues);
442 LAllocator allocator(values, graph);
443 LChunkBuilder builder(info, graph, &allocator);
444 LChunk* chunk = builder.Build();
445 if (chunk == NULL) return NULL;
447 if (!allocator.Allocate(chunk)) {
448 info->set_bailout_reason(kNotEnoughVirtualRegistersRegalloc);
452 chunk->set_allocated_double_registers(
453 allocator.assigned_double_registers());
459 Handle<Code> LChunk::Codegen() {
460 MacroAssembler assembler(info()->isolate(), NULL, 0);
461 LOG_CODE_EVENT(info()->isolate(),
462 CodeStartLinePosInfoRecordEvent(
463 assembler.positions_recorder()));
464 // TODO(yangguo) remove this once the code serializer handles code stubs.
465 if (info()->will_serialize()) assembler.enable_serializer();
466 LCodeGen generator(this, &assembler, info());
470 if (generator.GenerateCode()) {
471 generator.CheckEnvironmentUsage();
472 CodeGenerator::MakeCodePrologue(info(), "optimized");
473 Code::Flags flags = info()->flags();
475 CodeGenerator::MakeCodeEpilogue(&assembler, flags, info());
476 generator.FinishCode(code);
477 CommitDependencies(code);
478 code->set_is_crankshafted(true);
479 void* jit_handler_data =
480 assembler.positions_recorder()->DetachJITHandlerData();
481 LOG_CODE_EVENT(info()->isolate(),
482 CodeEndLinePosInfoRecordEvent(*code, jit_handler_data));
484 CodeGenerator::PrintCode(code, info());
485 DCHECK(!(info()->isolate()->serializer_enabled() &&
486 info()->GetMustNotHaveEagerFrame() &&
487 generator.NeedsEagerFrame()));
490 assembler.AbortedCodeGeneration();
491 return Handle<Code>::null();
495 void LChunk::set_allocated_double_registers(BitVector* allocated_registers) {
496 allocated_double_registers_ = allocated_registers;
497 BitVector* doubles = allocated_double_registers();
498 BitVector::Iterator iterator(doubles);
499 while (!iterator.Done()) {
500 if (info()->saves_caller_doubles()) {
501 if (kDoubleSize == kPointerSize * 2) {
502 spill_slot_count_ += 2;
512 LEnvironment* LChunkBuilderBase::CreateEnvironment(
513 HEnvironment* hydrogen_env,
514 int* argument_index_accumulator,
515 ZoneList<HValue*>* objects_to_materialize) {
516 if (hydrogen_env == NULL) return NULL;
518 LEnvironment* outer = CreateEnvironment(hydrogen_env->outer(),
519 argument_index_accumulator,
520 objects_to_materialize);
521 BailoutId ast_id = hydrogen_env->ast_id();
522 DCHECK(!ast_id.IsNone() ||
523 hydrogen_env->frame_type() != JS_FUNCTION);
524 int value_count = hydrogen_env->length() - hydrogen_env->specials_count();
525 LEnvironment* result =
526 new(zone()) LEnvironment(hydrogen_env->closure(),
527 hydrogen_env->frame_type(),
529 hydrogen_env->parameter_count(),
533 hydrogen_env->entry(),
535 int argument_index = *argument_index_accumulator;
537 // Store the environment description into the environment
538 // (with holes for nested objects)
539 for (int i = 0; i < hydrogen_env->length(); ++i) {
540 if (hydrogen_env->is_special_index(i)) continue;
543 HValue* value = hydrogen_env->values()->at(i);
544 CHECK(!value->IsPushArguments()); // Do not deopt outgoing arguments
545 if (value->IsArgumentsObject() || value->IsCapturedObject()) {
546 op = LEnvironment::materialization_marker();
551 value->representation(),
552 value->CheckFlag(HInstruction::kUint32));
555 // Recursively store the nested objects into the environment
556 for (int i = 0; i < hydrogen_env->length(); ++i) {
557 if (hydrogen_env->is_special_index(i)) continue;
559 HValue* value = hydrogen_env->values()->at(i);
560 if (value->IsArgumentsObject() || value->IsCapturedObject()) {
561 AddObjectToMaterialize(value, objects_to_materialize, result);
565 if (hydrogen_env->frame_type() == JS_FUNCTION) {
566 *argument_index_accumulator = argument_index;
573 // Add an object to the supplied environment and object materialization list.
577 // We are building three lists here:
579 // 1. In the result->object_mapping_ list (added to by the
580 // LEnvironment::Add*Object methods), we store the lengths (number
581 // of fields) of the captured objects in depth-first traversal order, or
582 // in case of duplicated objects, we store the index to the duplicate object
583 // (with a tag to differentiate between captured and duplicated objects).
585 // 2. The object fields are stored in the result->values_ list
586 // (added to by the LEnvironment.AddValue method) sequentially as lists
587 // of fields with holes for nested objects (the holes will be expanded
588 // later by LCodegen::AddToTranslation according to the
589 // LEnvironment.object_mapping_ list).
591 // 3. The auxiliary objects_to_materialize array stores the hydrogen values
592 // in the same order as result->object_mapping_ list. This is used
593 // to detect duplicate values and calculate the corresponding object index.
594 void LChunkBuilderBase::AddObjectToMaterialize(HValue* value,
595 ZoneList<HValue*>* objects_to_materialize, LEnvironment* result) {
596 int object_index = objects_to_materialize->length();
597 // Store the hydrogen value into the de-duplication array
598 objects_to_materialize->Add(value, zone());
599 // Find out whether we are storing a duplicated value
600 int previously_materialized_object = -1;
601 for (int prev = 0; prev < object_index; ++prev) {
602 if (objects_to_materialize->at(prev) == value) {
603 previously_materialized_object = prev;
607 // Store the captured object length (or duplicated object index)
608 // into the environment. For duplicated objects, we stop here.
609 int length = value->OperandCount();
610 bool is_arguments = value->IsArgumentsObject();
611 if (previously_materialized_object >= 0) {
612 result->AddDuplicateObject(previously_materialized_object);
615 result->AddNewObject(is_arguments ? length - 1 : length, is_arguments);
617 // Store the captured object's fields into the environment
618 for (int i = is_arguments ? 1 : 0; i < length; ++i) {
620 HValue* arg_value = value->OperandAt(i);
621 if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
622 // Insert a hole for nested objects
623 op = LEnvironment::materialization_marker();
625 DCHECK(!arg_value->IsPushArguments());
626 // For ordinary values, tell the register allocator we need the value
628 op = UseAny(arg_value);
631 arg_value->representation(),
632 arg_value->CheckFlag(HInstruction::kUint32));
634 // Recursively store all the nested captured objects into the environment
635 for (int i = is_arguments ? 1 : 0; i < length; ++i) {
636 HValue* arg_value = value->OperandAt(i);
637 if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
638 AddObjectToMaterialize(arg_value, objects_to_materialize, result);
645 if (ShouldProduceTraceOutput()) {
646 isolate()->GetHTracer()->TraceLithium(name(), chunk_);
651 } } // namespace v8::internal