blob: 069be4f8a5da01025d38b20d6c1aeb8a80cc675d [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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_UTILS_H_
29#define V8_UTILS_H_
30
31#include <stdlib.h>
Steve Block6ded16b2010-05-10 14:33:55 +010032#include <string.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000033
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080034#include "checks.h"
35
Steve Blocka7e24c12009-10-30 11:49:00 +000036namespace v8 {
37namespace internal {
38
39// ----------------------------------------------------------------------------
40// General helper functions
41
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010042#define IS_POWER_OF_TWO(x) (((x) & ((x) - 1)) == 0)
43
Steve Block3ce2e202009-11-05 08:53:23 +000044// Returns true iff x is a power of 2 (or zero). Cannot be used with the
45// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000046template <typename T>
47static inline bool IsPowerOf2(T x) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010048 return IS_POWER_OF_TWO(x);
Steve Blocka7e24c12009-10-30 11:49:00 +000049}
50
51
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010052// X must be a power of 2. Returns the number of trailing zeros.
53template <typename T>
54static inline int WhichPowerOf2(T x) {
55 ASSERT(IsPowerOf2(x));
56 ASSERT(x != 0);
57 if (x < 0) return 31;
58 int bits = 0;
59#ifdef DEBUG
60 int original_x = x;
61#endif
62 if (x >= 0x10000) {
63 bits += 16;
64 x >>= 16;
65 }
66 if (x >= 0x100) {
67 bits += 8;
68 x >>= 8;
69 }
70 if (x >= 0x10) {
71 bits += 4;
72 x >>= 4;
73 }
74 switch (x) {
75 default: UNREACHABLE();
76 case 8: bits++; // Fall through.
77 case 4: bits++; // Fall through.
78 case 2: bits++; // Fall through.
79 case 1: break;
80 }
81 ASSERT_EQ(1 << bits, original_x);
82 return bits;
83 return 0;
84}
85
86
Steve Blocka7e24c12009-10-30 11:49:00 +000087// The C++ standard leaves the semantics of '>>' undefined for
88// negative signed operands. Most implementations do the right thing,
89// though.
90static inline int ArithmeticShiftRight(int x, int s) {
91 return x >> s;
92}
93
94
95// Compute the 0-relative offset of some absolute value x of type T.
96// This allows conversion of Addresses and integral types into
97// 0-relative int offsets.
98template <typename T>
99static inline intptr_t OffsetFrom(T x) {
100 return x - static_cast<T>(0);
101}
102
103
104// Compute the absolute value of type T for some 0-relative offset x.
105// This allows conversion of 0-relative int offsets into Addresses and
106// integral types.
107template <typename T>
108static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +0000109 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +0000110}
111
112
113// Return the largest multiple of m which is <= x.
114template <typename T>
115static inline T RoundDown(T x, int m) {
116 ASSERT(IsPowerOf2(m));
117 return AddressFrom<T>(OffsetFrom(x) & -m);
118}
119
120
121// Return the smallest multiple of m which is >= x.
122template <typename T>
123static inline T RoundUp(T x, int m) {
124 return RoundDown(x + m - 1, m);
125}
126
127
128template <typename T>
129static int Compare(const T& a, const T& b) {
130 if (a == b)
131 return 0;
132 else if (a < b)
133 return -1;
134 else
135 return 1;
136}
137
138
139template <typename T>
140static int PointerValueCompare(const T* a, const T* b) {
141 return Compare<T>(*a, *b);
142}
143
144
145// Returns the smallest power of two which is >= x. If you pass in a
146// number that is already a power of two, it is returned as is.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800147// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
148// figure 3-3, page 48, where the function is called clp2.
149static inline uint32_t RoundUpToPowerOf2(uint32_t x) {
150 ASSERT(x <= 0x80000000u);
151 x = x - 1;
152 x = x | (x >> 1);
153 x = x | (x >> 2);
154 x = x | (x >> 4);
155 x = x | (x >> 8);
156 x = x | (x >> 16);
157 return x + 1;
158}
159
Steve Blocka7e24c12009-10-30 11:49:00 +0000160
161
162template <typename T>
163static inline bool IsAligned(T value, T alignment) {
164 ASSERT(IsPowerOf2(alignment));
165 return (value & (alignment - 1)) == 0;
166}
167
168
169// Returns true if (addr + offset) is aligned.
170static inline bool IsAddressAligned(Address addr,
171 intptr_t alignment,
172 int offset) {
173 intptr_t offs = OffsetFrom(addr + offset);
174 return IsAligned(offs, alignment);
175}
176
177
178// Returns the maximum of the two parameters.
179template <typename T>
180static T Max(T a, T b) {
181 return a < b ? b : a;
182}
183
184
185// Returns the minimum of the two parameters.
186template <typename T>
187static T Min(T a, T b) {
188 return a < b ? a : b;
189}
190
191
Steve Blockd0582a62009-12-15 09:54:21 +0000192inline int StrLength(const char* string) {
193 size_t length = strlen(string);
194 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
195 return static_cast<int>(length);
196}
197
198
Steve Blocka7e24c12009-10-30 11:49:00 +0000199// ----------------------------------------------------------------------------
200// BitField is a help template for encoding and decode bitfield with
201// unsigned content.
202template<class T, int shift, int size>
203class BitField {
204 public:
205 // Tells whether the provided value fits into the bit field.
206 static bool is_valid(T value) {
207 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
208 }
209
210 // Returns a uint32_t mask of bit field.
211 static uint32_t mask() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000212 // To use all bits of a uint32 in a bitfield without compiler warnings we
213 // have to compute 2^32 without using a shift count of 32.
214 return ((1U << shift) << size) - (1U << shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000215 }
216
217 // Returns a uint32_t with the bit field value encoded.
218 static uint32_t encode(T value) {
219 ASSERT(is_valid(value));
220 return static_cast<uint32_t>(value) << shift;
221 }
222
223 // Extracts the bit field from the value.
224 static T decode(uint32_t value) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000225 return static_cast<T>((value & mask()) >> shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000226 }
227};
228
229
230// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000231// Hash function.
232
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800233// Thomas Wang, Integer Hash Functions.
234// http://www.concentric.net/~Ttwang/tech/inthash.htm
235static inline uint32_t ComputeIntegerHash(uint32_t key) {
236 uint32_t hash = key;
237 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1;
238 hash = hash ^ (hash >> 12);
239 hash = hash + (hash << 2);
240 hash = hash ^ (hash >> 4);
241 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11);
242 hash = hash ^ (hash >> 16);
243 return hash;
244}
Steve Blocka7e24c12009-10-30 11:49:00 +0000245
246
247// ----------------------------------------------------------------------------
248// Miscellaneous
249
250// A static resource holds a static instance that can be reserved in
251// a local scope using an instance of Access. Attempts to re-reserve
252// the instance will cause an error.
253template <typename T>
254class StaticResource {
255 public:
256 StaticResource() : is_reserved_(false) {}
257
258 private:
259 template <typename S> friend class Access;
260 T instance_;
261 bool is_reserved_;
262};
263
264
265// Locally scoped access to a static resource.
266template <typename T>
267class Access {
268 public:
269 explicit Access(StaticResource<T>* resource)
270 : resource_(resource)
271 , instance_(&resource->instance_) {
272 ASSERT(!resource->is_reserved_);
273 resource->is_reserved_ = true;
274 }
275
276 ~Access() {
277 resource_->is_reserved_ = false;
278 resource_ = NULL;
279 instance_ = NULL;
280 }
281
282 T* value() { return instance_; }
283 T* operator -> () { return instance_; }
284
285 private:
286 StaticResource<T>* resource_;
287 T* instance_;
288};
289
290
291template <typename T>
292class Vector {
293 public:
294 Vector() : start_(NULL), length_(0) {}
295 Vector(T* data, int length) : start_(data), length_(length) {
296 ASSERT(length == 0 || (length > 0 && data != NULL));
297 }
298
299 static Vector<T> New(int length) {
300 return Vector<T>(NewArray<T>(length), length);
301 }
302
303 // Returns a vector using the same backing storage as this one,
304 // spanning from and including 'from', to but not including 'to'.
305 Vector<T> SubVector(int from, int to) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000306 ASSERT(to <= length_);
307 ASSERT(from < to);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100308 ASSERT(0 <= from);
Steve Blocka7e24c12009-10-30 11:49:00 +0000309 return Vector<T>(start() + from, to - from);
310 }
311
312 // Returns the length of the vector.
313 int length() const { return length_; }
314
315 // Returns whether or not the vector is empty.
316 bool is_empty() const { return length_ == 0; }
317
318 // Returns the pointer to the start of the data in the vector.
319 T* start() const { return start_; }
320
321 // Access individual vector elements - checks bounds in debug mode.
322 T& operator[](int index) const {
323 ASSERT(0 <= index && index < length_);
324 return start_[index];
325 }
326
327 T& first() { return start_[0]; }
328
329 T& last() { return start_[length_ - 1]; }
330
331 // Returns a clone of this vector with a new backing store.
332 Vector<T> Clone() const {
333 T* result = NewArray<T>(length_);
334 for (int i = 0; i < length_; i++) result[i] = start_[i];
335 return Vector<T>(result, length_);
336 }
337
338 void Sort(int (*cmp)(const T*, const T*)) {
339 typedef int (*RawComparer)(const void*, const void*);
340 qsort(start(),
341 length(),
342 sizeof(T),
343 reinterpret_cast<RawComparer>(cmp));
344 }
345
346 void Sort() {
347 Sort(PointerValueCompare<T>);
348 }
349
350 void Truncate(int length) {
351 ASSERT(length <= length_);
352 length_ = length;
353 }
354
355 // Releases the array underlying this vector. Once disposed the
356 // vector is empty.
357 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000358 DeleteArray(start_);
359 start_ = NULL;
360 length_ = 0;
361 }
362
363 inline Vector<T> operator+(int offset) {
364 ASSERT(offset < length_);
365 return Vector<T>(start_ + offset, length_ - offset);
366 }
367
368 // Factory method for creating empty vectors.
369 static Vector<T> empty() { return Vector<T>(NULL, 0); }
370
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100371 template<typename S>
372 static Vector<T> cast(Vector<S> input) {
373 return Vector<T>(reinterpret_cast<T*>(input.start()),
374 input.length() * sizeof(S) / sizeof(T));
375 }
376
Steve Blocka7e24c12009-10-30 11:49:00 +0000377 protected:
378 void set_start(T* start) { start_ = start; }
379
380 private:
381 T* start_;
382 int length_;
383};
384
385
Steve Blocka7e24c12009-10-30 11:49:00 +0000386template <typename T, int kSize>
387class EmbeddedVector : public Vector<T> {
388 public:
389 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
390
391 // When copying, make underlying Vector to reference our buffer.
392 EmbeddedVector(const EmbeddedVector& rhs)
393 : Vector<T>(rhs) {
394 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
395 set_start(buffer_);
396 }
397
398 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
399 if (this == &rhs) return *this;
400 Vector<T>::operator=(rhs);
401 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100402 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000403 return *this;
404 }
405
406 private:
407 T buffer_[kSize];
408};
409
410
411template <typename T>
412class ScopedVector : public Vector<T> {
413 public:
414 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
415 ~ScopedVector() {
416 DeleteArray(this->start());
417 }
Kristian Monsen25f61362010-05-21 11:50:48 +0100418
419 private:
420 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
Steve Blocka7e24c12009-10-30 11:49:00 +0000421};
422
423
424inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000425 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000426}
427
428inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000429 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000430}
431
432inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000433 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000434 return Vector<char>(data, (length < max) ? length : max);
435}
436
Steve Blocka7e24c12009-10-30 11:49:00 +0000437
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100438/*
439 * A class that collects values into a backing store.
440 * Specialized versions of the class can allow access to the backing store
441 * in different ways.
442 * There is no guarantee that the backing store is contiguous (and, as a
443 * consequence, no guarantees that consecutively added elements are adjacent
444 * in memory). The collector may move elements unless it has guaranteed not
445 * to.
446 */
447template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
448class Collector {
449 public:
450 explicit Collector(int initial_capacity = kMinCapacity)
451 : index_(0), size_(0) {
452 if (initial_capacity < kMinCapacity) {
453 initial_capacity = kMinCapacity;
454 }
455 current_chunk_ = Vector<T>::New(initial_capacity);
456 }
457
458 virtual ~Collector() {
459 // Free backing store (in reverse allocation order).
460 current_chunk_.Dispose();
461 for (int i = chunks_.length() - 1; i >= 0; i--) {
462 chunks_.at(i).Dispose();
463 }
464 }
465
466 // Add a single element.
467 inline void Add(T value) {
468 if (index_ >= current_chunk_.length()) {
469 Grow(1);
470 }
471 current_chunk_[index_] = value;
472 index_++;
473 size_++;
474 }
475
476 // Add a block of contiguous elements and return a Vector backed by the
477 // memory area.
478 // A basic Collector will keep this vector valid as long as the Collector
479 // is alive.
480 inline Vector<T> AddBlock(int size, T initial_value) {
481 ASSERT(size > 0);
482 if (size > current_chunk_.length() - index_) {
483 Grow(size);
484 }
485 T* position = current_chunk_.start() + index_;
486 index_ += size;
487 size_ += size;
488 for (int i = 0; i < size; i++) {
489 position[i] = initial_value;
490 }
491 return Vector<T>(position, size);
492 }
493
494
495 // Write the contents of the collector into the provided vector.
496 void WriteTo(Vector<T> destination) {
497 ASSERT(size_ <= destination.length());
498 int position = 0;
499 for (int i = 0; i < chunks_.length(); i++) {
500 Vector<T> chunk = chunks_.at(i);
501 for (int j = 0; j < chunk.length(); j++) {
502 destination[position] = chunk[j];
503 position++;
504 }
505 }
506 for (int i = 0; i < index_; i++) {
507 destination[position] = current_chunk_[i];
508 position++;
509 }
510 }
511
512 // Allocate a single contiguous vector, copy all the collected
513 // elements to the vector, and return it.
514 // The caller is responsible for freeing the memory of the returned
515 // vector (e.g., using Vector::Dispose).
516 Vector<T> ToVector() {
517 Vector<T> new_store = Vector<T>::New(size_);
518 WriteTo(new_store);
519 return new_store;
520 }
521
522 // Resets the collector to be empty.
523 virtual void Reset() {
524 for (int i = chunks_.length() - 1; i >= 0; i--) {
525 chunks_.at(i).Dispose();
526 }
527 chunks_.Rewind(0);
528 index_ = 0;
529 size_ = 0;
530 }
531
532 // Total number of elements added to collector so far.
533 inline int size() { return size_; }
534
535 protected:
536 static const int kMinCapacity = 16;
537 List<Vector<T> > chunks_;
538 Vector<T> current_chunk_; // Block of memory currently being written into.
539 int index_; // Current index in current chunk.
540 int size_; // Total number of elements in collector.
541
542 // Creates a new current chunk, and stores the old chunk in the chunks_ list.
543 void Grow(int min_capacity) {
544 ASSERT(growth_factor > 1);
545 int growth = current_chunk_.length() * (growth_factor - 1);
546 if (growth > max_growth) {
547 growth = max_growth;
548 }
549 int new_capacity = current_chunk_.length() + growth;
550 if (new_capacity < min_capacity) {
551 new_capacity = min_capacity + growth;
552 }
553 Vector<T> new_chunk = Vector<T>::New(new_capacity);
554 int new_index = PrepareGrow(new_chunk);
555 if (index_ > 0) {
556 chunks_.Add(current_chunk_.SubVector(0, index_));
557 } else {
558 // Can happen if the call to PrepareGrow moves everything into
559 // the new chunk.
560 current_chunk_.Dispose();
561 }
562 current_chunk_ = new_chunk;
563 index_ = new_index;
564 ASSERT(index_ + min_capacity <= current_chunk_.length());
565 }
566
567 // Before replacing the current chunk, give a subclass the option to move
568 // some of the current data into the new chunk. The function may update
569 // the current index_ value to represent data no longer in the current chunk.
570 // Returns the initial index of the new chunk (after copied data).
571 virtual int PrepareGrow(Vector<T> new_chunk) {
572 return 0;
573 }
574};
575
576
577/*
578 * A collector that allows sequences of values to be guaranteed to
579 * stay consecutive.
580 * If the backing store grows while a sequence is active, the current
581 * sequence might be moved, but after the sequence is ended, it will
582 * not move again.
583 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
584 * as well, if inside an active sequence where another element is added.
585 */
586template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
587class SequenceCollector : public Collector<T, growth_factor, max_growth> {
588 public:
589 explicit SequenceCollector(int initial_capacity)
590 : Collector<T, growth_factor, max_growth>(initial_capacity),
591 sequence_start_(kNoSequence) { }
592
593 virtual ~SequenceCollector() {}
594
595 void StartSequence() {
596 ASSERT(sequence_start_ == kNoSequence);
597 sequence_start_ = this->index_;
598 }
599
600 Vector<T> EndSequence() {
601 ASSERT(sequence_start_ != kNoSequence);
602 int sequence_start = sequence_start_;
603 sequence_start_ = kNoSequence;
604 if (sequence_start == this->index_) return Vector<T>();
605 return this->current_chunk_.SubVector(sequence_start, this->index_);
606 }
607
608 // Drops the currently added sequence, and all collected elements in it.
609 void DropSequence() {
610 ASSERT(sequence_start_ != kNoSequence);
611 int sequence_length = this->index_ - sequence_start_;
612 this->index_ = sequence_start_;
613 this->size_ -= sequence_length;
614 sequence_start_ = kNoSequence;
615 }
616
617 virtual void Reset() {
618 sequence_start_ = kNoSequence;
619 this->Collector<T, growth_factor, max_growth>::Reset();
620 }
621
622 private:
623 static const int kNoSequence = -1;
624 int sequence_start_;
625
626 // Move the currently active sequence to the new chunk.
627 virtual int PrepareGrow(Vector<T> new_chunk) {
628 if (sequence_start_ != kNoSequence) {
629 int sequence_length = this->index_ - sequence_start_;
630 // The new chunk is always larger than the current chunk, so there
631 // is room for the copy.
632 ASSERT(sequence_length < new_chunk.length());
633 for (int i = 0; i < sequence_length; i++) {
634 new_chunk[i] = this->current_chunk_[sequence_start_ + i];
635 }
636 this->index_ = sequence_start_;
637 sequence_start_ = 0;
638 return sequence_length;
639 }
640 return 0;
641 }
642};
643
644
Steve Block6ded16b2010-05-10 14:33:55 +0100645// Compare ASCII/16bit chars to ASCII/16bit chars.
646template <typename lchar, typename rchar>
647static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
648 const lchar* limit = lhs + chars;
649#ifdef V8_HOST_CAN_READ_UNALIGNED
650 if (sizeof(*lhs) == sizeof(*rhs)) {
651 // Number of characters in a uintptr_t.
652 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
653 while (lhs <= limit - kStepSize) {
654 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
655 *reinterpret_cast<const uintptr_t*>(rhs)) {
656 break;
657 }
658 lhs += kStepSize;
659 rhs += kStepSize;
660 }
661 }
662#endif
663 while (lhs < limit) {
664 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
665 if (r != 0) return r;
666 ++lhs;
667 ++rhs;
668 }
669 return 0;
670}
671
672
Steve Blockd0582a62009-12-15 09:54:21 +0000673// Calculate 10^exponent.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800674static inline int TenToThe(int exponent) {
675 ASSERT(exponent <= 9);
676 ASSERT(exponent >= 1);
677 int answer = 10;
678 for (int i = 1; i < exponent; i++) answer *= 10;
679 return answer;
680}
Steve Blockd0582a62009-12-15 09:54:21 +0000681
Steve Block6ded16b2010-05-10 14:33:55 +0100682
683// The type-based aliasing rule allows the compiler to assume that pointers of
684// different types (for some definition of different) never alias each other.
685// Thus the following code does not work:
686//
687// float f = foo();
688// int fbits = *(int*)(&f);
689//
690// The compiler 'knows' that the int pointer can't refer to f since the types
691// don't match, so the compiler may cache f in a register, leaving random data
692// in fbits. Using C++ style casts makes no difference, however a pointer to
693// char data is assumed to alias any other pointer. This is the 'memcpy
694// exception'.
695//
696// Bit_cast uses the memcpy exception to move the bits from a variable of one
697// type of a variable of another type. Of course the end result is likely to
698// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
699// will completely optimize BitCast away.
700//
701// There is an additional use for BitCast.
702// Recent gccs will warn when they see casts that may result in breakage due to
703// the type-based aliasing rule. If you have checked that there is no breakage
704// you can use BitCast to cast one pointer type to another. This confuses gcc
705// enough that it can no longer see that you have cast one pointer type to
706// another thus avoiding the warning.
707template <class Dest, class Source>
708inline Dest BitCast(const Source& source) {
709 // Compile time assertion: sizeof(Dest) == sizeof(Source)
710 // A compile error here means your Dest and Source have different sizes.
711 typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
712
713 Dest dest;
714 memcpy(&dest, &source, sizeof(dest));
715 return dest;
716}
717
Iain Merrick75681382010-08-19 15:07:18 +0100718template <class Dest, class Source>
Steve Block791712a2010-08-27 10:21:07 +0100719inline Dest BitCast(Source* source) {
720 return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
Iain Merrick75681382010-08-19 15:07:18 +0100721}
Steve Blocka7e24c12009-10-30 11:49:00 +0000722
Iain Merrick75681382010-08-19 15:07:18 +0100723} } // namespace v8::internal
Steve Block6ded16b2010-05-10 14:33:55 +0100724
Steve Blocka7e24c12009-10-30 11:49:00 +0000725#endif // V8_UTILS_H_