Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / v8 / src / lithium-allocator.h
1 // Copyright 2012 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_LITHIUM_ALLOCATOR_H_
29 #define V8_LITHIUM_ALLOCATOR_H_
30
31 #include "v8.h"
32
33 #include "allocation.h"
34 #include "lithium.h"
35 #include "zone.h"
36
37 namespace v8 {
38 namespace internal {
39
40 // Forward declarations.
41 class HBasicBlock;
42 class HGraph;
43 class HInstruction;
44 class HPhi;
45 class HTracer;
46 class HValue;
47 class BitVector;
48 class StringStream;
49
50 class LArgument;
51 class LPlatformChunk;
52 class LOperand;
53 class LUnallocated;
54 class LGap;
55 class LParallelMove;
56 class LPointerMap;
57
58
59 // This class represents a single point of a LOperand's lifetime.
60 // For each lithium instruction there are exactly two lifetime positions:
61 // the beginning and the end of the instruction. Lifetime positions for
62 // different lithium instructions are disjoint.
63 class LifetimePosition {
64  public:
65   // Return the lifetime position that corresponds to the beginning of
66   // the instruction with the given index.
67   static LifetimePosition FromInstructionIndex(int index) {
68     return LifetimePosition(index * kStep);
69   }
70
71   // Returns a numeric representation of this lifetime position.
72   int Value() const {
73     return value_;
74   }
75
76   // Returns the index of the instruction to which this lifetime position
77   // corresponds.
78   int InstructionIndex() const {
79     ASSERT(IsValid());
80     return value_ / kStep;
81   }
82
83   // Returns true if this lifetime position corresponds to the instruction
84   // start.
85   bool IsInstructionStart() const {
86     return (value_ & (kStep - 1)) == 0;
87   }
88
89   // Returns the lifetime position for the start of the instruction which
90   // corresponds to this lifetime position.
91   LifetimePosition InstructionStart() const {
92     ASSERT(IsValid());
93     return LifetimePosition(value_ & ~(kStep - 1));
94   }
95
96   // Returns the lifetime position for the end of the instruction which
97   // corresponds to this lifetime position.
98   LifetimePosition InstructionEnd() const {
99     ASSERT(IsValid());
100     return LifetimePosition(InstructionStart().Value() + kStep/2);
101   }
102
103   // Returns the lifetime position for the beginning of the next instruction.
104   LifetimePosition NextInstruction() const {
105     ASSERT(IsValid());
106     return LifetimePosition(InstructionStart().Value() + kStep);
107   }
108
109   // Returns the lifetime position for the beginning of the previous
110   // instruction.
111   LifetimePosition PrevInstruction() const {
112     ASSERT(IsValid());
113     ASSERT(value_ > 1);
114     return LifetimePosition(InstructionStart().Value() - kStep);
115   }
116
117   // Constructs the lifetime position which does not correspond to any
118   // instruction.
119   LifetimePosition() : value_(-1) {}
120
121   // Returns true if this lifetime positions corrensponds to some
122   // instruction.
123   bool IsValid() const { return value_ != -1; }
124
125   static inline LifetimePosition Invalid() { return LifetimePosition(); }
126
127   static inline LifetimePosition MaxPosition() {
128     // We have to use this kind of getter instead of static member due to
129     // crash bug in GDB.
130     return LifetimePosition(kMaxInt);
131   }
132
133  private:
134   static const int kStep = 2;
135
136   // Code relies on kStep being a power of two.
137   STATIC_ASSERT(IS_POWER_OF_TWO(kStep));
138
139   explicit LifetimePosition(int value) : value_(value) { }
140
141   int value_;
142 };
143
144
145 enum RegisterKind {
146   UNALLOCATED_REGISTERS,
147   GENERAL_REGISTERS,
148   DOUBLE_REGISTERS,
149   FLOAT32x4_REGISTERS,
150   INT32x4_REGISTERS
151 };
152
153
154 inline bool IsSIMD128RegisterKind(RegisterKind kind) {
155   return kind == FLOAT32x4_REGISTERS || kind == INT32x4_REGISTERS;
156 }
157
158
159 // A register-allocator view of a Lithium instruction. It contains the id of
160 // the output operand and a list of input operand uses.
161
162 class LInstruction;
163 class LEnvironment;
164
165 // Iterator for non-null temp operands.
166 class TempIterator BASE_EMBEDDED {
167  public:
168   inline explicit TempIterator(LInstruction* instr);
169   inline bool Done();
170   inline LOperand* Current();
171   inline void Advance();
172
173  private:
174   inline void SkipUninteresting();
175   LInstruction* instr_;
176   int limit_;
177   int current_;
178 };
179
180
181 // Iterator for non-constant input operands.
182 class InputIterator BASE_EMBEDDED {
183  public:
184   inline explicit InputIterator(LInstruction* instr);
185   inline bool Done();
186   inline LOperand* Current();
187   inline void Advance();
188
189  private:
190   inline void SkipUninteresting();
191   LInstruction* instr_;
192   int limit_;
193   int current_;
194 };
195
196
197 class UseIterator BASE_EMBEDDED {
198  public:
199   inline explicit UseIterator(LInstruction* instr);
200   inline bool Done();
201   inline LOperand* Current();
202   inline void Advance();
203
204  private:
205   InputIterator input_iterator_;
206   DeepIterator env_iterator_;
207 };
208
209
210 // Representation of the non-empty interval [start,end[.
211 class UseInterval: public ZoneObject {
212  public:
213   UseInterval(LifetimePosition start, LifetimePosition end)
214       : start_(start), end_(end), next_(NULL) {
215     ASSERT(start.Value() < end.Value());
216   }
217
218   LifetimePosition start() const { return start_; }
219   LifetimePosition end() const { return end_; }
220   UseInterval* next() const { return next_; }
221
222   // Split this interval at the given position without effecting the
223   // live range that owns it. The interval must contain the position.
224   void SplitAt(LifetimePosition pos, Zone* zone);
225
226   // If this interval intersects with other return smallest position
227   // that belongs to both of them.
228   LifetimePosition Intersect(const UseInterval* other) const {
229     if (other->start().Value() < start_.Value()) return other->Intersect(this);
230     if (other->start().Value() < end_.Value()) return other->start();
231     return LifetimePosition::Invalid();
232   }
233
234   bool Contains(LifetimePosition point) const {
235     return start_.Value() <= point.Value() && point.Value() < end_.Value();
236   }
237
238  private:
239   void set_start(LifetimePosition start) { start_ = start; }
240   void set_next(UseInterval* next) { next_ = next; }
241
242   LifetimePosition start_;
243   LifetimePosition end_;
244   UseInterval* next_;
245
246   friend class LiveRange;  // Assigns to start_.
247 };
248
249 // Representation of a use position.
250 class UsePosition: public ZoneObject {
251  public:
252   UsePosition(LifetimePosition pos, LOperand* operand, LOperand* hint);
253
254   LOperand* operand() const { return operand_; }
255   bool HasOperand() const { return operand_ != NULL; }
256
257   LOperand* hint() const { return hint_; }
258   bool HasHint() const;
259   bool RequiresRegister() const;
260   bool RegisterIsBeneficial() const;
261
262   LifetimePosition pos() const { return pos_; }
263   UsePosition* next() const { return next_; }
264
265  private:
266   void set_next(UsePosition* next) { next_ = next; }
267
268   LOperand* const operand_;
269   LOperand* const hint_;
270   LifetimePosition const pos_;
271   UsePosition* next_;
272   bool requires_reg_;
273   bool register_beneficial_;
274
275   friend class LiveRange;
276 };
277
278 // Representation of SSA values' live ranges as a collection of (continuous)
279 // intervals over the instruction ordering.
280 class LiveRange: public ZoneObject {
281  public:
282   static const int kInvalidAssignment = 0x7fffffff;
283
284   LiveRange(int id, Zone* zone);
285
286   UseInterval* first_interval() const { return first_interval_; }
287   UsePosition* first_pos() const { return first_pos_; }
288   LiveRange* parent() const { return parent_; }
289   LiveRange* TopLevel() { return (parent_ == NULL) ? this : parent_; }
290   LiveRange* next() const { return next_; }
291   bool IsChild() const { return parent() != NULL; }
292   int id() const { return id_; }
293   bool IsFixed() const { return id_ < 0; }
294   bool IsEmpty() const { return first_interval() == NULL; }
295   LOperand* CreateAssignedOperand(Zone* zone);
296   int assigned_register() const { return assigned_register_; }
297   int spill_start_index() const { return spill_start_index_; }
298   void set_assigned_register(int reg, Zone* zone);
299   void MakeSpilled(Zone* zone);
300
301   // Returns use position in this live range that follows both start
302   // and last processed use position.
303   // Modifies internal state of live range!
304   UsePosition* NextUsePosition(LifetimePosition start);
305
306   // Returns use position for which register is required in this live
307   // range and which follows both start and last processed use position
308   // Modifies internal state of live range!
309   UsePosition* NextRegisterPosition(LifetimePosition start);
310
311   // Returns use position for which register is beneficial in this live
312   // range and which follows both start and last processed use position
313   // Modifies internal state of live range!
314   UsePosition* NextUsePositionRegisterIsBeneficial(LifetimePosition start);
315
316   // Returns use position for which register is beneficial in this live
317   // range and which precedes start.
318   UsePosition* PreviousUsePositionRegisterIsBeneficial(LifetimePosition start);
319
320   // Can this live range be spilled at this position.
321   bool CanBeSpilled(LifetimePosition pos);
322
323   // Split this live range at the given position which must follow the start of
324   // the range.
325   // All uses following the given position will be moved from this
326   // live range to the result live range.
327   void SplitAt(LifetimePosition position, LiveRange* result, Zone* zone);
328
329   RegisterKind Kind() const { return kind_; }
330   bool HasRegisterAssigned() const {
331     return assigned_register_ != kInvalidAssignment;
332   }
333   bool IsSpilled() const { return spilled_; }
334
335   LOperand* current_hint_operand() const {
336     ASSERT(current_hint_operand_ == FirstHint());
337     return current_hint_operand_;
338   }
339   LOperand* FirstHint() const {
340     UsePosition* pos = first_pos_;
341     while (pos != NULL && !pos->HasHint()) pos = pos->next();
342     if (pos != NULL) return pos->hint();
343     return NULL;
344   }
345
346   LifetimePosition Start() const {
347     ASSERT(!IsEmpty());
348     return first_interval()->start();
349   }
350
351   LifetimePosition End() const {
352     ASSERT(!IsEmpty());
353     return last_interval_->end();
354   }
355
356   bool HasAllocatedSpillOperand() const;
357   LOperand* GetSpillOperand() const { return spill_operand_; }
358   void SetSpillOperand(LOperand* operand);
359
360   void SetSpillStartIndex(int start) {
361     spill_start_index_ = Min(start, spill_start_index_);
362   }
363
364   bool ShouldBeAllocatedBefore(const LiveRange* other) const;
365   bool CanCover(LifetimePosition position) const;
366   bool Covers(LifetimePosition position);
367   LifetimePosition FirstIntersection(LiveRange* other);
368
369   // Add a new interval or a new use position to this live range.
370   void EnsureInterval(LifetimePosition start,
371                       LifetimePosition end,
372                       Zone* zone);
373   void AddUseInterval(LifetimePosition start,
374                       LifetimePosition end,
375                       Zone* zone);
376   void AddUsePosition(LifetimePosition pos,
377                       LOperand* operand,
378                       LOperand* hint,
379                       Zone* zone);
380
381   // Shorten the most recently added interval by setting a new start.
382   void ShortenTo(LifetimePosition start);
383
384 #ifdef DEBUG
385   // True if target overlaps an existing interval.
386   bool HasOverlap(UseInterval* target) const;
387   void Verify() const;
388 #endif
389
390  private:
391   void ConvertOperands(Zone* zone);
392   UseInterval* FirstSearchIntervalForPosition(LifetimePosition position) const;
393   void AdvanceLastProcessedMarker(UseInterval* to_start_of,
394                                   LifetimePosition but_not_past) const;
395
396   int id_;
397   bool spilled_;
398   RegisterKind kind_;
399   int assigned_register_;
400   UseInterval* last_interval_;
401   UseInterval* first_interval_;
402   UsePosition* first_pos_;
403   LiveRange* parent_;
404   LiveRange* next_;
405   // This is used as a cache, it doesn't affect correctness.
406   mutable UseInterval* current_interval_;
407   UsePosition* last_processed_use_;
408   // This is used as a cache, it's invalid outside of BuildLiveRanges.
409   LOperand* current_hint_operand_;
410   LOperand* spill_operand_;
411   int spill_start_index_;
412
413   friend class LAllocator;  // Assigns to kind_.
414 };
415
416
417 class LAllocator BASE_EMBEDDED {
418  public:
419   LAllocator(int first_virtual_register, HGraph* graph);
420
421   static void TraceAlloc(const char* msg, ...);
422
423   // Checks whether the value of a given virtual register is tagged.
424   bool HasTaggedValue(int virtual_register) const;
425
426   // Returns the register kind required by the given virtual register.
427   RegisterKind RequiredRegisterKind(int virtual_register) const;
428
429   bool Allocate(LChunk* chunk);
430
431   const ZoneList<LiveRange*>* live_ranges() const { return &live_ranges_; }
432   const Vector<LiveRange*>* fixed_live_ranges() const {
433     return &fixed_live_ranges_;
434   }
435   const Vector<LiveRange*>* fixed_double_live_ranges() const {
436     return &fixed_double_live_ranges_;
437   }
438
439   LPlatformChunk* chunk() const { return chunk_; }
440   HGraph* graph() const { return graph_; }
441   Isolate* isolate() const { return graph_->isolate(); }
442   Zone* zone() { return &zone_; }
443
444   int GetVirtualRegister() {
445     if (next_virtual_register_ >= LUnallocated::kMaxVirtualRegisters) {
446       allocation_ok_ = false;
447       // Maintain the invariant that we return something below the maximum.
448       return 0;
449     }
450     return next_virtual_register_++;
451   }
452
453   bool AllocationOk() { return allocation_ok_; }
454
455   void MarkAsOsrEntry() {
456     // There can be only one.
457     ASSERT(!has_osr_entry_);
458     // Simply set a flag to find and process instruction later.
459     has_osr_entry_ = true;
460   }
461
462 #ifdef DEBUG
463   void Verify() const;
464 #endif
465
466   BitVector* assigned_registers() {
467     return assigned_registers_;
468   }
469   BitVector* assigned_double_registers() {
470     return assigned_double_registers_;
471   }
472
473  private:
474   void MeetRegisterConstraints();
475   void ResolvePhis();
476   void BuildLiveRanges();
477   void AllocateGeneralRegisters();
478   void AllocateDoubleRegisters();
479   void ConnectRanges();
480   void ResolveControlFlow();
481   void PopulatePointerMaps();
482   void AllocateRegisters();
483   bool CanEagerlyResolveControlFlow(HBasicBlock* block) const;
484   inline bool SafePointsAreInOrder() const;
485
486   // Liveness analysis support.
487   void InitializeLivenessAnalysis();
488   BitVector* ComputeLiveOut(HBasicBlock* block);
489   void AddInitialIntervals(HBasicBlock* block, BitVector* live_out);
490   void ProcessInstructions(HBasicBlock* block, BitVector* live);
491   void MeetRegisterConstraints(HBasicBlock* block);
492   void MeetConstraintsBetween(LInstruction* first,
493                               LInstruction* second,
494                               int gap_index);
495   void ResolvePhis(HBasicBlock* block);
496
497   // Helper methods for building intervals.
498   LOperand* AllocateFixed(LUnallocated* operand, int pos, bool is_tagged);
499   LiveRange* LiveRangeFor(LOperand* operand);
500   void Define(LifetimePosition position, LOperand* operand, LOperand* hint);
501   void Use(LifetimePosition block_start,
502            LifetimePosition position,
503            LOperand* operand,
504            LOperand* hint);
505   void AddConstraintsGapMove(int index, LOperand* from, LOperand* to);
506
507   // Helper methods for updating the life range lists.
508   void AddToActive(LiveRange* range);
509   void AddToInactive(LiveRange* range);
510   void AddToUnhandledSorted(LiveRange* range);
511   void AddToUnhandledUnsorted(LiveRange* range);
512   void SortUnhandled();
513   bool UnhandledIsSorted();
514   void ActiveToHandled(LiveRange* range);
515   void ActiveToInactive(LiveRange* range);
516   void InactiveToHandled(LiveRange* range);
517   void InactiveToActive(LiveRange* range);
518   void FreeSpillSlot(LiveRange* range);
519   LOperand* TryReuseSpillSlot(LiveRange* range);
520
521   // Helper methods for allocating registers.
522   bool TryAllocateFreeReg(LiveRange* range);
523   void AllocateBlockedReg(LiveRange* range);
524
525   // Live range splitting helpers.
526
527   // Split the given range at the given position.
528   // If range starts at or after the given position then the
529   // original range is returned.
530   // Otherwise returns the live range that starts at pos and contains
531   // all uses from the original range that follow pos. Uses at pos will
532   // still be owned by the original range after splitting.
533   LiveRange* SplitRangeAt(LiveRange* range, LifetimePosition pos);
534
535   // Split the given range in a position from the interval [start, end].
536   LiveRange* SplitBetween(LiveRange* range,
537                           LifetimePosition start,
538                           LifetimePosition end);
539
540   // Find a lifetime position in the interval [start, end] which
541   // is optimal for splitting: it is either header of the outermost
542   // loop covered by this interval or the latest possible position.
543   LifetimePosition FindOptimalSplitPos(LifetimePosition start,
544                                        LifetimePosition end);
545
546   // Spill the given life range after position pos.
547   void SpillAfter(LiveRange* range, LifetimePosition pos);
548
549   // Spill the given life range after position [start] and up to position [end].
550   void SpillBetween(LiveRange* range,
551                     LifetimePosition start,
552                     LifetimePosition end);
553
554   // Spill the given life range after position [start] and up to position [end].
555   // Range is guaranteed to be spilled at least until position [until].
556   void SpillBetweenUntil(LiveRange* range,
557                          LifetimePosition start,
558                          LifetimePosition until,
559                          LifetimePosition end);
560
561   void SplitAndSpillIntersecting(LiveRange* range);
562
563   // If we are trying to spill a range inside the loop try to
564   // hoist spill position out to the point just before the loop.
565   LifetimePosition FindOptimalSpillingPos(LiveRange* range,
566                                           LifetimePosition pos);
567
568   void Spill(LiveRange* range);
569   bool IsBlockBoundary(LifetimePosition pos);
570
571   // Helper methods for resolving control flow.
572   void ResolveControlFlow(LiveRange* range,
573                           HBasicBlock* block,
574                           HBasicBlock* pred);
575
576   inline void SetLiveRangeAssignedRegister(LiveRange* range, int reg);
577
578   // Return parallel move that should be used to connect ranges split at the
579   // given position.
580   LParallelMove* GetConnectingParallelMove(LifetimePosition pos);
581
582   // Return the block which contains give lifetime position.
583   HBasicBlock* GetBlock(LifetimePosition pos);
584
585   // Helper methods for the fixed registers.
586   int RegisterCount() const;
587   static int FixedLiveRangeID(int index) { return -index - 1; }
588   static int FixedDoubleLiveRangeID(int index);
589   LiveRange* FixedLiveRangeFor(int index);
590   LiveRange* FixedDoubleLiveRangeFor(int index);
591   LiveRange* LiveRangeFor(int index);
592   HPhi* LookupPhi(LOperand* operand) const;
593   LGap* GetLastGap(HBasicBlock* block);
594
595   const char* RegisterName(int allocation_index);
596
597   inline bool IsGapAt(int index);
598
599   inline LInstruction* InstructionAt(int index);
600
601   inline LGap* GapAt(int index);
602
603   Zone zone_;
604
605   LPlatformChunk* chunk_;
606
607   // During liveness analysis keep a mapping from block id to live_in sets
608   // for blocks already analyzed.
609   ZoneList<BitVector*> live_in_sets_;
610
611   // Liveness analysis results.
612   ZoneList<LiveRange*> live_ranges_;
613
614   // Lists of live ranges
615   EmbeddedVector<LiveRange*, Register::kMaxNumAllocatableRegisters>
616       fixed_live_ranges_;
617   EmbeddedVector<LiveRange*, DoubleRegister::kMaxNumAllocatableRegisters>
618       fixed_double_live_ranges_;
619   ZoneList<LiveRange*> unhandled_live_ranges_;
620   ZoneList<LiveRange*> active_live_ranges_;
621   ZoneList<LiveRange*> inactive_live_ranges_;
622   ZoneList<LiveRange*> reusable_slots_;
623   // Slots reusable for both float32x4 and int32x4 register spilling.
624   ZoneList<LiveRange*> reusable_simd128_slots_;
625
626   // Next virtual register number to be assigned to temporaries.
627   int next_virtual_register_;
628   int first_artificial_register_;
629   GrowableBitVector double_artificial_registers_;
630   GrowableBitVector float32x4_artificial_registers_;
631   GrowableBitVector int32x4_artificial_registers_;
632
633   RegisterKind mode_;
634   int num_registers_;
635
636   BitVector* assigned_registers_;
637   BitVector* assigned_double_registers_;
638
639   HGraph* graph_;
640
641   bool has_osr_entry_;
642
643   // Indicates success or failure during register allocation.
644   bool allocation_ok_;
645
646 #ifdef DEBUG
647   LifetimePosition allocation_finger_;
648 #endif
649
650   DISALLOW_COPY_AND_ASSIGN(LAllocator);
651 };
652
653
654 class LAllocatorPhase : public CompilationPhase {
655  public:
656   LAllocatorPhase(const char* name, LAllocator* allocator);
657   ~LAllocatorPhase();
658
659  private:
660   LAllocator* allocator_;
661   unsigned allocator_zone_start_allocation_size_;
662
663   DISALLOW_COPY_AND_ASSIGN(LAllocatorPhase);
664 };
665
666
667 } }  // namespace v8::internal
668
669 #endif  // V8_LITHIUM_ALLOCATOR_H_