Upstream version 8.37.186.0
[platform/framework/web/crosswalk.git] / src / v8 / src / lithium.cc
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.
4
5 #include "src/v8.h"
6 #include "src/lithium.h"
7 #include "src/scopes.h"
8 #include "src/serialize.h"
9
10 #if V8_TARGET_ARCH_IA32
11 #include "src/ia32/lithium-ia32.h"
12 #include "src/ia32/lithium-codegen-ia32.h"
13 #elif V8_TARGET_ARCH_X64
14 #include "src/x64/lithium-x64.h"
15 #include "src/x64/lithium-codegen-x64.h"
16 #elif V8_TARGET_ARCH_ARM
17 #include "src/arm/lithium-arm.h"
18 #include "src/arm/lithium-codegen-arm.h"
19 #elif V8_TARGET_ARCH_MIPS
20 #include "src/mips/lithium-mips.h"
21 #include "src/mips/lithium-codegen-mips.h"
22 #elif V8_TARGET_ARCH_ARM64
23 #include "src/arm64/lithium-arm64.h"
24 #include "src/arm64/lithium-codegen-arm64.h"
25 #elif V8_TARGET_ARCH_X87
26 #include "src/x87/lithium-x87.h"
27 #include "src/x87/lithium-codegen-x87.h"
28 #else
29 #error "Unknown architecture."
30 #endif
31
32 namespace v8 {
33 namespace internal {
34
35
36 void LOperand::PrintTo(StringStream* stream) {
37   LUnallocated* unalloc = NULL;
38   switch (kind()) {
39     case INVALID:
40       stream->Add("(0)");
41       break;
42     case UNALLOCATED:
43       unalloc = LUnallocated::cast(this);
44       stream->Add("v%d", unalloc->virtual_register());
45       if (unalloc->basic_policy() == LUnallocated::FIXED_SLOT) {
46         stream->Add("(=%dS)", unalloc->fixed_slot_index());
47         break;
48       }
49       switch (unalloc->extended_policy()) {
50         case LUnallocated::NONE:
51           break;
52         case LUnallocated::FIXED_REGISTER: {
53           int reg_index = unalloc->fixed_register_index();
54           const char* register_name =
55               Register::AllocationIndexToString(reg_index);
56           stream->Add("(=%s)", register_name);
57           break;
58         }
59         case LUnallocated::FIXED_DOUBLE_REGISTER: {
60           int reg_index = unalloc->fixed_register_index();
61           const char* double_register_name =
62               DoubleRegister::AllocationIndexToString(reg_index);
63           stream->Add("(=%s)", double_register_name);
64           break;
65         }
66         case LUnallocated::MUST_HAVE_REGISTER:
67           stream->Add("(R)");
68           break;
69         case LUnallocated::MUST_HAVE_DOUBLE_REGISTER:
70           stream->Add("(D)");
71           break;
72         case LUnallocated::WRITABLE_REGISTER:
73           stream->Add("(WR)");
74           break;
75         case LUnallocated::SAME_AS_FIRST_INPUT:
76           stream->Add("(1)");
77           break;
78         case LUnallocated::ANY:
79           stream->Add("(-)");
80           break;
81       }
82       break;
83     case CONSTANT_OPERAND:
84       stream->Add("[constant:%d]", index());
85       break;
86     case STACK_SLOT:
87       stream->Add("[stack:%d]", index());
88       break;
89     case DOUBLE_STACK_SLOT:
90       stream->Add("[double_stack:%d]", index());
91       break;
92     case FLOAT32x4_STACK_SLOT:
93       stream->Add("[float32x4_stack:%d]", index());
94       break;
95     case FLOAT64x2_STACK_SLOT:
96       stream->Add("[float64x2_stack:%d]", index());
97       break;
98     case INT32x4_STACK_SLOT:
99       stream->Add("[int32x4_stack:%d]", index());
100       break;
101     case REGISTER:
102       stream->Add("[%s|R]", Register::AllocationIndexToString(index()));
103       break;
104     case DOUBLE_REGISTER:
105       stream->Add("[%s|R]", DoubleRegister::AllocationIndexToString(index()));
106       break;
107     case FLOAT32x4_REGISTER:
108       stream->Add("[%s|R]",
109                   SIMD128Register::AllocationIndexToString(index()));
110       break;
111     case FLOAT64x2_REGISTER:
112       stream->Add("[%s|R]",
113                   SIMD128Register::AllocationIndexToString(index()));
114       break;
115     case INT32x4_REGISTER:
116       stream->Add("[%s|R]",
117                   SIMD128Register::AllocationIndexToString(index()));
118       break;
119   }
120 }
121
122
123 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
124 LSubKindOperand<kOperandKind, kNumCachedOperands>*
125 LSubKindOperand<kOperandKind, kNumCachedOperands>::cache = NULL;
126
127
128 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
129 void LSubKindOperand<kOperandKind, kNumCachedOperands>::SetUpCache() {
130   if (cache) return;
131   cache = new LSubKindOperand[kNumCachedOperands];
132   for (int i = 0; i < kNumCachedOperands; i++) {
133     cache[i].ConvertTo(kOperandKind, i);
134   }
135 }
136
137
138 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
139 void LSubKindOperand<kOperandKind, kNumCachedOperands>::TearDownCache() {
140   delete[] cache;
141 }
142
143
144 void LOperand::SetUpCaches() {
145 #define LITHIUM_OPERAND_SETUP(name, type, number) L##name::SetUpCache();
146   LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_SETUP)
147 #undef LITHIUM_OPERAND_SETUP
148 }
149
150
151 void LOperand::TearDownCaches() {
152 #define LITHIUM_OPERAND_TEARDOWN(name, type, number) L##name::TearDownCache();
153   LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_TEARDOWN)
154 #undef LITHIUM_OPERAND_TEARDOWN
155 }
156
157
158 bool LParallelMove::IsRedundant() const {
159   for (int i = 0; i < move_operands_.length(); ++i) {
160     if (!move_operands_[i].IsRedundant()) return false;
161   }
162   return true;
163 }
164
165
166 void LParallelMove::PrintDataTo(StringStream* stream) const {
167   bool first = true;
168   for (int i = 0; i < move_operands_.length(); ++i) {
169     if (!move_operands_[i].IsEliminated()) {
170       LOperand* source = move_operands_[i].source();
171       LOperand* destination = move_operands_[i].destination();
172       if (!first) stream->Add(" ");
173       first = false;
174       if (source->Equals(destination)) {
175         destination->PrintTo(stream);
176       } else {
177         destination->PrintTo(stream);
178         stream->Add(" = ");
179         source->PrintTo(stream);
180       }
181       stream->Add(";");
182     }
183   }
184 }
185
186
187 void LEnvironment::PrintTo(StringStream* stream) {
188   stream->Add("[id=%d|", ast_id().ToInt());
189   if (deoptimization_index() != Safepoint::kNoDeoptimizationIndex) {
190     stream->Add("deopt_id=%d|", deoptimization_index());
191   }
192   stream->Add("parameters=%d|", parameter_count());
193   stream->Add("arguments_stack_height=%d|", arguments_stack_height());
194   for (int i = 0; i < values_.length(); ++i) {
195     if (i != 0) stream->Add(";");
196     if (values_[i] == NULL) {
197       stream->Add("[hole]");
198     } else {
199       values_[i]->PrintTo(stream);
200     }
201   }
202   stream->Add("]");
203 }
204
205
206 void LPointerMap::RecordPointer(LOperand* op, Zone* zone) {
207   // Do not record arguments as pointers.
208   if (op->IsStackSlot() && op->index() < 0) return;
209   ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot() &&
210          !op->IsFloat32x4Register() && !op->IsFloat32x4StackSlot() &&
211          !op->IsFloat64x2Register() && !op->IsFloat64x2StackSlot() &&
212          !op->IsInt32x4Register() && !op->IsInt32x4StackSlot());
213   pointer_operands_.Add(op, zone);
214 }
215
216
217 void LPointerMap::RemovePointer(LOperand* op) {
218   // Do not record arguments as pointers.
219   if (op->IsStackSlot() && op->index() < 0) return;
220   ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot() &&
221          !op->IsFloat32x4Register() && !op->IsFloat32x4StackSlot() &&
222          !op->IsFloat64x2Register() && !op->IsFloat64x2StackSlot() &&
223          !op->IsInt32x4Register() && !op->IsInt32x4StackSlot());
224   for (int i = 0; i < pointer_operands_.length(); ++i) {
225     if (pointer_operands_[i]->Equals(op)) {
226       pointer_operands_.Remove(i);
227       --i;
228     }
229   }
230 }
231
232
233 void LPointerMap::RecordUntagged(LOperand* op, Zone* zone) {
234   // Do not record arguments as pointers.
235   if (op->IsStackSlot() && op->index() < 0) return;
236   ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot() &&
237          !op->IsFloat32x4Register() && !op->IsFloat32x4StackSlot() &&
238          !op->IsFloat64x2Register() && !op->IsFloat64x2StackSlot() &&
239          !op->IsInt32x4Register() && !op->IsInt32x4StackSlot());
240   untagged_operands_.Add(op, zone);
241 }
242
243
244 void LPointerMap::PrintTo(StringStream* stream) {
245   stream->Add("{");
246   for (int i = 0; i < pointer_operands_.length(); ++i) {
247     if (i != 0) stream->Add(";");
248     pointer_operands_[i]->PrintTo(stream);
249   }
250   stream->Add("}");
251 }
252
253
254 int StackSlotOffset(int index) {
255   if (index >= 0) {
256     // Local or spill slot. Skip the frame pointer, function, and
257     // context in the fixed part of the frame.
258     return -(index + 1) * kPointerSize -
259         StandardFrameConstants::kFixedFrameSizeFromFp;
260   } else {
261     // Incoming parameter. Skip the return address.
262     return -(index + 1) * kPointerSize + kFPOnStackSize + kPCOnStackSize;
263   }
264 }
265
266
267 LChunk::LChunk(CompilationInfo* info, HGraph* graph)
268     : spill_slot_count_(0),
269       info_(info),
270       graph_(graph),
271       instructions_(32, graph->zone()),
272       pointer_maps_(8, graph->zone()),
273       inlined_closures_(1, graph->zone()),
274       deprecation_dependencies_(MapLess(), MapAllocator(graph->zone())),
275       stability_dependencies_(MapLess(), MapAllocator(graph->zone())) {
276 }
277
278
279 LLabel* LChunk::GetLabel(int block_id) const {
280   HBasicBlock* block = graph_->blocks()->at(block_id);
281   int first_instruction = block->first_instruction_index();
282   return LLabel::cast(instructions_[first_instruction]);
283 }
284
285
286 int LChunk::LookupDestination(int block_id) const {
287   LLabel* cur = GetLabel(block_id);
288   while (cur->replacement() != NULL) {
289     cur = cur->replacement();
290   }
291   return cur->block_id();
292 }
293
294 Label* LChunk::GetAssemblyLabel(int block_id) const {
295   LLabel* label = GetLabel(block_id);
296   ASSERT(!label->HasReplacement());
297   return label->label();
298 }
299
300
301 void LChunk::MarkEmptyBlocks() {
302   LPhase phase("L_Mark empty blocks", this);
303   for (int i = 0; i < graph()->blocks()->length(); ++i) {
304     HBasicBlock* block = graph()->blocks()->at(i);
305     int first = block->first_instruction_index();
306     int last = block->last_instruction_index();
307     LInstruction* first_instr = instructions()->at(first);
308     LInstruction* last_instr = instructions()->at(last);
309
310     LLabel* label = LLabel::cast(first_instr);
311     if (last_instr->IsGoto()) {
312       LGoto* goto_instr = LGoto::cast(last_instr);
313       if (label->IsRedundant() &&
314           !label->is_loop_header()) {
315         bool can_eliminate = true;
316         for (int i = first + 1; i < last && can_eliminate; ++i) {
317           LInstruction* cur = instructions()->at(i);
318           if (cur->IsGap()) {
319             LGap* gap = LGap::cast(cur);
320             if (!gap->IsRedundant()) {
321               can_eliminate = false;
322             }
323           } else {
324             can_eliminate = false;
325           }
326         }
327         if (can_eliminate) {
328           label->set_replacement(GetLabel(goto_instr->block_id()));
329         }
330       }
331     }
332   }
333 }
334
335
336 void LChunk::AddInstruction(LInstruction* instr, HBasicBlock* block) {
337   LInstructionGap* gap = new(graph_->zone()) LInstructionGap(block);
338   gap->set_hydrogen_value(instr->hydrogen_value());
339   int index = -1;
340   if (instr->IsControl()) {
341     instructions_.Add(gap, zone());
342     index = instructions_.length();
343     instructions_.Add(instr, zone());
344   } else {
345     index = instructions_.length();
346     instructions_.Add(instr, zone());
347     instructions_.Add(gap, zone());
348   }
349   if (instr->HasPointerMap()) {
350     pointer_maps_.Add(instr->pointer_map(), zone());
351     instr->pointer_map()->set_lithium_position(index);
352   }
353 }
354
355
356 LConstantOperand* LChunk::DefineConstantOperand(HConstant* constant) {
357   return LConstantOperand::Create(constant->id(), zone());
358 }
359
360
361 int LChunk::GetParameterStackSlot(int index) const {
362   // The receiver is at index 0, the first parameter at index 1, so we
363   // shift all parameter indexes down by the number of parameters, and
364   // make sure they end up negative so they are distinguishable from
365   // spill slots.
366   int result = index - info()->num_parameters() - 1;
367
368   ASSERT(result < 0);
369   return result;
370 }
371
372
373 // A parameter relative to ebp in the arguments stub.
374 int LChunk::ParameterAt(int index) {
375   ASSERT(-1 <= index);  // -1 is the receiver.
376   return (1 + info()->scope()->num_parameters() - index) *
377       kPointerSize;
378 }
379
380
381 LGap* LChunk::GetGapAt(int index) const {
382   return LGap::cast(instructions_[index]);
383 }
384
385
386 bool LChunk::IsGapAt(int index) const {
387   return instructions_[index]->IsGap();
388 }
389
390
391 int LChunk::NearestGapPos(int index) const {
392   while (!IsGapAt(index)) index--;
393   return index;
394 }
395
396
397 void LChunk::AddGapMove(int index, LOperand* from, LOperand* to) {
398   GetGapAt(index)->GetOrCreateParallelMove(
399       LGap::START, zone())->AddMove(from, to, zone());
400 }
401
402
403 HConstant* LChunk::LookupConstant(LConstantOperand* operand) const {
404   return HConstant::cast(graph_->LookupValue(operand->index()));
405 }
406
407
408 Representation LChunk::LookupLiteralRepresentation(
409     LConstantOperand* operand) const {
410   return graph_->LookupValue(operand->index())->representation();
411 }
412
413
414 void LChunk::CommitDependencies(Handle<Code> code) const {
415   for (MapSet::const_iterator it = deprecation_dependencies_.begin(),
416        iend = deprecation_dependencies_.end(); it != iend; ++it) {
417     Handle<Map> map = *it;
418     ASSERT(!map->is_deprecated());
419     ASSERT(map->CanBeDeprecated());
420     Map::AddDependentCode(map, DependentCode::kTransitionGroup, code);
421   }
422
423   for (MapSet::const_iterator it = stability_dependencies_.begin(),
424        iend = stability_dependencies_.end(); it != iend; ++it) {
425     Handle<Map> map = *it;
426     ASSERT(map->is_stable());
427     ASSERT(map->CanTransition());
428     Map::AddDependentCode(map, DependentCode::kPrototypeCheckGroup, code);
429   }
430
431   info_->CommitDependencies(code);
432 }
433
434
435 LChunk* LChunk::NewChunk(HGraph* graph) {
436   DisallowHandleAllocation no_handles;
437   DisallowHeapAllocation no_gc;
438   graph->DisallowAddingNewValues();
439   int values = graph->GetMaximumValueID();
440   CompilationInfo* info = graph->info();
441   if (values > LUnallocated::kMaxVirtualRegisters) {
442     info->set_bailout_reason(kNotEnoughVirtualRegistersForValues);
443     return NULL;
444   }
445   LAllocator allocator(values, graph);
446   LChunkBuilder builder(info, graph, &allocator);
447   LChunk* chunk = builder.Build();
448   if (chunk == NULL) return NULL;
449
450   if (!allocator.Allocate(chunk)) {
451     info->set_bailout_reason(kNotEnoughVirtualRegistersRegalloc);
452     return NULL;
453   }
454
455   chunk->set_allocated_double_registers(
456       allocator.assigned_double_registers());
457
458   return chunk;
459 }
460
461
462 Handle<Code> LChunk::Codegen() {
463   MacroAssembler assembler(info()->isolate(), NULL, 0);
464   LOG_CODE_EVENT(info()->isolate(),
465                  CodeStartLinePosInfoRecordEvent(
466                      assembler.positions_recorder()));
467   LCodeGen generator(this, &assembler, info());
468
469   MarkEmptyBlocks();
470
471   if (generator.GenerateCode()) {
472     generator.CheckEnvironmentUsage();
473     CodeGenerator::MakeCodePrologue(info(), "optimized");
474     Code::Flags flags = info()->flags();
475     Handle<Code> code =
476         CodeGenerator::MakeCodeEpilogue(&assembler, flags, info());
477     generator.FinishCode(code);
478     CommitDependencies(code);
479     code->set_is_crankshafted(true);
480     void* jit_handler_data =
481         assembler.positions_recorder()->DetachJITHandlerData();
482     LOG_CODE_EVENT(info()->isolate(),
483                    CodeEndLinePosInfoRecordEvent(*code, jit_handler_data));
484
485     CodeGenerator::PrintCode(code, info());
486     ASSERT(!(info()->isolate()->serializer_enabled() &&
487              info()->GetMustNotHaveEagerFrame() &&
488              generator.NeedsEagerFrame()));
489     return code;
490   }
491   assembler.AbortedCodeGeneration();
492   return Handle<Code>::null();
493 }
494
495
496 void LChunk::set_allocated_double_registers(BitVector* allocated_registers) {
497   allocated_double_registers_ = allocated_registers;
498   BitVector* doubles = allocated_double_registers();
499   BitVector::Iterator iterator(doubles);
500   while (!iterator.Done()) {
501     if (info()->saves_caller_doubles()) {
502       if (kDoubleSize == kPointerSize * 2) {
503         spill_slot_count_ += 2;
504       } else {
505         spill_slot_count_++;
506       }
507     }
508     iterator.Advance();
509   }
510 }
511
512
513 LEnvironment* LChunkBuilderBase::CreateEnvironment(
514     HEnvironment* hydrogen_env,
515     int* argument_index_accumulator,
516     ZoneList<HValue*>* objects_to_materialize) {
517   if (hydrogen_env == NULL) return NULL;
518
519   LEnvironment* outer = CreateEnvironment(hydrogen_env->outer(),
520                                           argument_index_accumulator,
521                                           objects_to_materialize);
522   BailoutId ast_id = hydrogen_env->ast_id();
523   ASSERT(!ast_id.IsNone() ||
524          hydrogen_env->frame_type() != JS_FUNCTION);
525   int value_count = hydrogen_env->length() - hydrogen_env->specials_count();
526   LEnvironment* result =
527       new(zone()) LEnvironment(hydrogen_env->closure(),
528                                hydrogen_env->frame_type(),
529                                ast_id,
530                                hydrogen_env->parameter_count(),
531                                argument_count_,
532                                value_count,
533                                outer,
534                                hydrogen_env->entry(),
535                                zone());
536   int argument_index = *argument_index_accumulator;
537
538   // Store the environment description into the environment
539   // (with holes for nested objects)
540   for (int i = 0; i < hydrogen_env->length(); ++i) {
541     if (hydrogen_env->is_special_index(i)) continue;
542
543     LOperand* op;
544     HValue* value = hydrogen_env->values()->at(i);
545     CHECK(!value->IsPushArguments());  // Do not deopt outgoing arguments
546     if (value->IsArgumentsObject() || value->IsCapturedObject()) {
547       op = LEnvironment::materialization_marker();
548     } else {
549       op = UseAny(value);
550     }
551     result->AddValue(op,
552                      value->representation(),
553                      value->CheckFlag(HInstruction::kUint32));
554   }
555
556   // Recursively store the nested objects into the environment
557   for (int i = 0; i < hydrogen_env->length(); ++i) {
558     if (hydrogen_env->is_special_index(i)) continue;
559
560     HValue* value = hydrogen_env->values()->at(i);
561     if (value->IsArgumentsObject() || value->IsCapturedObject()) {
562       AddObjectToMaterialize(value, objects_to_materialize, result);
563     }
564   }
565
566   if (hydrogen_env->frame_type() == JS_FUNCTION) {
567     *argument_index_accumulator = argument_index;
568   }
569
570   return result;
571 }
572
573
574 // Add an object to the supplied environment and object materialization list.
575 //
576 // Notes:
577 //
578 // We are building three lists here:
579 //
580 // 1. In the result->object_mapping_ list (added to by the
581 //    LEnvironment::Add*Object methods), we store the lengths (number
582 //    of fields) of the captured objects in depth-first traversal order, or
583 //    in case of duplicated objects, we store the index to the duplicate object
584 //    (with a tag to differentiate between captured and duplicated objects).
585 //
586 // 2. The object fields are stored in the result->values_ list
587 //    (added to by the LEnvironment.AddValue method) sequentially as lists
588 //    of fields with holes for nested objects (the holes will be expanded
589 //    later by LCodegen::AddToTranslation according to the
590 //    LEnvironment.object_mapping_ list).
591 //
592 // 3. The auxiliary objects_to_materialize array stores the hydrogen values
593 //    in the same order as result->object_mapping_ list. This is used
594 //    to detect duplicate values and calculate the corresponding object index.
595 void LChunkBuilderBase::AddObjectToMaterialize(HValue* value,
596     ZoneList<HValue*>* objects_to_materialize, LEnvironment* result) {
597   int object_index = objects_to_materialize->length();
598   // Store the hydrogen value into the de-duplication array
599   objects_to_materialize->Add(value, zone());
600   // Find out whether we are storing a duplicated value
601   int previously_materialized_object = -1;
602   for (int prev = 0; prev < object_index; ++prev) {
603     if (objects_to_materialize->at(prev) == value) {
604       previously_materialized_object = prev;
605       break;
606     }
607   }
608   // Store the captured object length (or duplicated object index)
609   // into the environment. For duplicated objects, we stop here.
610   int length = value->OperandCount();
611   bool is_arguments = value->IsArgumentsObject();
612   if (previously_materialized_object >= 0) {
613     result->AddDuplicateObject(previously_materialized_object);
614     return;
615   } else {
616     result->AddNewObject(is_arguments ? length - 1 : length, is_arguments);
617   }
618   // Store the captured object's fields into the environment
619   for (int i = is_arguments ? 1 : 0; i < length; ++i) {
620     LOperand* op;
621     HValue* arg_value = value->OperandAt(i);
622     if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
623       // Insert a hole for nested objects
624       op = LEnvironment::materialization_marker();
625     } else {
626       ASSERT(!arg_value->IsPushArguments());
627       // For ordinary values, tell the register allocator we need the value
628       // to be alive here
629       op = UseAny(arg_value);
630     }
631     result->AddValue(op,
632                      arg_value->representation(),
633                      arg_value->CheckFlag(HInstruction::kUint32));
634   }
635   // Recursively store all the nested captured objects into the environment
636   for (int i = is_arguments ? 1 : 0; i < length; ++i) {
637     HValue* arg_value = value->OperandAt(i);
638     if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
639       AddObjectToMaterialize(arg_value, objects_to_materialize, result);
640     }
641   }
642 }
643
644
645 LPhase::~LPhase() {
646   if (ShouldProduceTraceOutput()) {
647     isolate()->GetHTracer()->TraceLithium(name(), chunk_);
648   }
649 }
650
651
652 } }  // namespace v8::internal