blob: 7c818671d52f0d7462b41d7eaf1c26a278904ec0 [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
34namespace v8 {
35namespace internal {
36
37// ----------------------------------------------------------------------------
38// General helper functions
39
Steve Block3ce2e202009-11-05 08:53:23 +000040// Returns true iff x is a power of 2 (or zero). Cannot be used with the
41// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000042template <typename T>
43static inline bool IsPowerOf2(T x) {
44 return (x & (x - 1)) == 0;
45}
46
47
48// The C++ standard leaves the semantics of '>>' undefined for
49// negative signed operands. Most implementations do the right thing,
50// though.
51static inline int ArithmeticShiftRight(int x, int s) {
52 return x >> s;
53}
54
55
56// Compute the 0-relative offset of some absolute value x of type T.
57// This allows conversion of Addresses and integral types into
58// 0-relative int offsets.
59template <typename T>
60static inline intptr_t OffsetFrom(T x) {
61 return x - static_cast<T>(0);
62}
63
64
65// Compute the absolute value of type T for some 0-relative offset x.
66// This allows conversion of 0-relative int offsets into Addresses and
67// integral types.
68template <typename T>
69static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +000070 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +000071}
72
73
74// Return the largest multiple of m which is <= x.
75template <typename T>
76static inline T RoundDown(T x, int m) {
77 ASSERT(IsPowerOf2(m));
78 return AddressFrom<T>(OffsetFrom(x) & -m);
79}
80
81
82// Return the smallest multiple of m which is >= x.
83template <typename T>
84static inline T RoundUp(T x, int m) {
85 return RoundDown(x + m - 1, m);
86}
87
88
89template <typename T>
90static int Compare(const T& a, const T& b) {
91 if (a == b)
92 return 0;
93 else if (a < b)
94 return -1;
95 else
96 return 1;
97}
98
99
100template <typename T>
101static int PointerValueCompare(const T* a, const T* b) {
102 return Compare<T>(*a, *b);
103}
104
105
106// Returns the smallest power of two which is >= x. If you pass in a
107// number that is already a power of two, it is returned as is.
108uint32_t RoundUpToPowerOf2(uint32_t x);
109
110
111template <typename T>
112static inline bool IsAligned(T value, T alignment) {
113 ASSERT(IsPowerOf2(alignment));
114 return (value & (alignment - 1)) == 0;
115}
116
117
118// Returns true if (addr + offset) is aligned.
119static inline bool IsAddressAligned(Address addr,
120 intptr_t alignment,
121 int offset) {
122 intptr_t offs = OffsetFrom(addr + offset);
123 return IsAligned(offs, alignment);
124}
125
126
127// Returns the maximum of the two parameters.
128template <typename T>
129static T Max(T a, T b) {
130 return a < b ? b : a;
131}
132
133
134// Returns the minimum of the two parameters.
135template <typename T>
136static T Min(T a, T b) {
137 return a < b ? a : b;
138}
139
140
Steve Blockd0582a62009-12-15 09:54:21 +0000141inline int StrLength(const char* string) {
142 size_t length = strlen(string);
143 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
144 return static_cast<int>(length);
145}
146
147
Steve Blocka7e24c12009-10-30 11:49:00 +0000148// ----------------------------------------------------------------------------
149// BitField is a help template for encoding and decode bitfield with
150// unsigned content.
151template<class T, int shift, int size>
152class BitField {
153 public:
154 // Tells whether the provided value fits into the bit field.
155 static bool is_valid(T value) {
156 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
157 }
158
159 // Returns a uint32_t mask of bit field.
160 static uint32_t mask() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000161 // To use all bits of a uint32 in a bitfield without compiler warnings we
162 // have to compute 2^32 without using a shift count of 32.
163 return ((1U << shift) << size) - (1U << shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000164 }
165
166 // Returns a uint32_t with the bit field value encoded.
167 static uint32_t encode(T value) {
168 ASSERT(is_valid(value));
169 return static_cast<uint32_t>(value) << shift;
170 }
171
172 // Extracts the bit field from the value.
173 static T decode(uint32_t value) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000174 return static_cast<T>((value & mask()) >> shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000175 }
176};
177
178
179// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000180// Hash function.
181
182uint32_t ComputeIntegerHash(uint32_t key);
183
184
185// ----------------------------------------------------------------------------
186// I/O support.
187
188// Our version of printf(). Avoids compilation errors that we get
189// with standard printf when attempting to print pointers, etc.
190// (the errors are due to the extra compilation flags, which we
191// want elsewhere).
192void PrintF(const char* format, ...);
193
194// Our version of fflush.
195void Flush();
196
197
198// Read a line of characters after printing the prompt to stdout. The resulting
199// char* needs to be disposed off with DeleteArray by the caller.
200char* ReadLine(const char* prompt);
201
202
203// Read and return the raw bytes in a file. the size of the buffer is returned
204// in size.
205// The returned buffer must be freed by the caller.
206byte* ReadBytes(const char* filename, int* size, bool verbose = true);
207
208
209// Write size chars from str to the file given by filename.
210// The file is overwritten. Returns the number of chars written.
211int WriteChars(const char* filename,
212 const char* str,
213 int size,
214 bool verbose = true);
215
216
217// Write size bytes to the file given by filename.
218// The file is overwritten. Returns the number of bytes written.
219int WriteBytes(const char* filename,
220 const byte* bytes,
221 int size,
222 bool verbose = true);
223
224
225// Write the C code
226// const char* <varname> = "<str>";
227// const int <varname>_len = <len>;
228// to the file given by filename. Only the first len chars are written.
229int WriteAsCFile(const char* filename, const char* varname,
230 const char* str, int size, bool verbose = true);
231
232
233// ----------------------------------------------------------------------------
234// Miscellaneous
235
236// A static resource holds a static instance that can be reserved in
237// a local scope using an instance of Access. Attempts to re-reserve
238// the instance will cause an error.
239template <typename T>
240class StaticResource {
241 public:
242 StaticResource() : is_reserved_(false) {}
243
244 private:
245 template <typename S> friend class Access;
246 T instance_;
247 bool is_reserved_;
248};
249
250
251// Locally scoped access to a static resource.
252template <typename T>
253class Access {
254 public:
255 explicit Access(StaticResource<T>* resource)
256 : resource_(resource)
257 , instance_(&resource->instance_) {
258 ASSERT(!resource->is_reserved_);
259 resource->is_reserved_ = true;
260 }
261
262 ~Access() {
263 resource_->is_reserved_ = false;
264 resource_ = NULL;
265 instance_ = NULL;
266 }
267
268 T* value() { return instance_; }
269 T* operator -> () { return instance_; }
270
271 private:
272 StaticResource<T>* resource_;
273 T* instance_;
274};
275
276
277template <typename T>
278class Vector {
279 public:
280 Vector() : start_(NULL), length_(0) {}
281 Vector(T* data, int length) : start_(data), length_(length) {
282 ASSERT(length == 0 || (length > 0 && data != NULL));
283 }
284
285 static Vector<T> New(int length) {
286 return Vector<T>(NewArray<T>(length), length);
287 }
288
289 // Returns a vector using the same backing storage as this one,
290 // spanning from and including 'from', to but not including 'to'.
291 Vector<T> SubVector(int from, int to) {
292 ASSERT(from < length_);
293 ASSERT(to <= length_);
294 ASSERT(from < to);
295 return Vector<T>(start() + from, to - from);
296 }
297
298 // Returns the length of the vector.
299 int length() const { return length_; }
300
301 // Returns whether or not the vector is empty.
302 bool is_empty() const { return length_ == 0; }
303
304 // Returns the pointer to the start of the data in the vector.
305 T* start() const { return start_; }
306
307 // Access individual vector elements - checks bounds in debug mode.
308 T& operator[](int index) const {
309 ASSERT(0 <= index && index < length_);
310 return start_[index];
311 }
312
313 T& first() { return start_[0]; }
314
315 T& last() { return start_[length_ - 1]; }
316
317 // Returns a clone of this vector with a new backing store.
318 Vector<T> Clone() const {
319 T* result = NewArray<T>(length_);
320 for (int i = 0; i < length_; i++) result[i] = start_[i];
321 return Vector<T>(result, length_);
322 }
323
324 void Sort(int (*cmp)(const T*, const T*)) {
325 typedef int (*RawComparer)(const void*, const void*);
326 qsort(start(),
327 length(),
328 sizeof(T),
329 reinterpret_cast<RawComparer>(cmp));
330 }
331
332 void Sort() {
333 Sort(PointerValueCompare<T>);
334 }
335
336 void Truncate(int length) {
337 ASSERT(length <= length_);
338 length_ = length;
339 }
340
341 // Releases the array underlying this vector. Once disposed the
342 // vector is empty.
343 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000344 DeleteArray(start_);
345 start_ = NULL;
346 length_ = 0;
347 }
348
349 inline Vector<T> operator+(int offset) {
350 ASSERT(offset < length_);
351 return Vector<T>(start_ + offset, length_ - offset);
352 }
353
354 // Factory method for creating empty vectors.
355 static Vector<T> empty() { return Vector<T>(NULL, 0); }
356
357 protected:
358 void set_start(T* start) { start_ = start; }
359
360 private:
361 T* start_;
362 int length_;
363};
364
365
366// A temporary assignment sets a (non-local) variable to a value on
367// construction and resets it the value on destruction.
368template <typename T>
369class TempAssign {
370 public:
371 TempAssign(T* var, T value): var_(var), old_value_(*var) {
372 *var = value;
373 }
374
375 ~TempAssign() { *var_ = old_value_; }
376
377 private:
378 T* var_;
379 T old_value_;
380};
381
382
383template <typename T, int kSize>
384class EmbeddedVector : public Vector<T> {
385 public:
386 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
387
388 // When copying, make underlying Vector to reference our buffer.
389 EmbeddedVector(const EmbeddedVector& rhs)
390 : Vector<T>(rhs) {
391 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
392 set_start(buffer_);
393 }
394
395 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
396 if (this == &rhs) return *this;
397 Vector<T>::operator=(rhs);
398 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100399 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 return *this;
401 }
402
403 private:
404 T buffer_[kSize];
405};
406
407
408template <typename T>
409class ScopedVector : public Vector<T> {
410 public:
411 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
412 ~ScopedVector() {
413 DeleteArray(this->start());
414 }
Kristian Monsen25f61362010-05-21 11:50:48 +0100415
416 private:
417 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
Steve Blocka7e24c12009-10-30 11:49:00 +0000418};
419
420
421inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000422 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000423}
424
425inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000426 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000427}
428
429inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000430 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000431 return Vector<char>(data, (length < max) ? length : max);
432}
433
434template <typename T>
435inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
436 int length) {
437 return Vector< Handle<Object> >(
438 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
439}
440
441
442// Simple support to read a file into a 0-terminated C-string.
443// The returned buffer must be freed by the caller.
444// On return, *exits tells whether the file existed.
445Vector<const char> ReadFile(const char* filename,
446 bool* exists,
447 bool verbose = true);
448
449
450// Simple wrapper that allows an ExternalString to refer to a
451// Vector<const char>. Doesn't assume ownership of the data.
452class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
453 public:
454 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
455
456 virtual const char* data() const { return data_.start(); }
457
458 virtual size_t length() const { return data_.length(); }
459
460 private:
461 Vector<const char> data_;
462};
463
464
465// Helper class for building result strings in a character buffer. The
466// purpose of the class is to use safe operations that checks the
467// buffer bounds on all operations in debug mode.
468class StringBuilder {
469 public:
470 // Create a string builder with a buffer of the given size. The
471 // buffer is allocated through NewArray<char> and must be
472 // deallocated by the caller of Finalize().
473 explicit StringBuilder(int size);
474
475 StringBuilder(char* buffer, int size)
476 : buffer_(buffer, size), position_(0) { }
477
478 ~StringBuilder() { if (!is_finalized()) Finalize(); }
479
480 int size() const { return buffer_.length(); }
481
482 // Get the current position in the builder.
483 int position() const {
484 ASSERT(!is_finalized());
485 return position_;
486 }
487
488 // Reset the position.
489 void Reset() { position_ = 0; }
490
491 // Add a single character to the builder. It is not allowed to add
492 // 0-characters; use the Finalize() method to terminate the string
493 // instead.
494 void AddCharacter(char c) {
495 ASSERT(c != '\0');
496 ASSERT(!is_finalized() && position_ < buffer_.length());
497 buffer_[position_++] = c;
498 }
499
500 // Add an entire string to the builder. Uses strlen() internally to
501 // compute the length of the input string.
502 void AddString(const char* s);
503
504 // Add the first 'n' characters of the given string 's' to the
505 // builder. The input string must have enough characters.
506 void AddSubstring(const char* s, int n);
507
508 // Add formatted contents to the builder just like printf().
509 void AddFormatted(const char* format, ...);
510
511 // Add character padding to the builder. If count is non-positive,
512 // nothing is added to the builder.
513 void AddPadding(char c, int count);
514
515 // Finalize the string by 0-terminating it and returning the buffer.
516 char* Finalize();
517
518 private:
519 Vector<char> buffer_;
520 int position_;
521
522 bool is_finalized() const { return position_ < 0; }
523
524 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
525};
526
527
528// Copy from ASCII/16bit chars to ASCII/16bit chars.
529template <typename sourcechar, typename sinkchar>
530static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
531 sinkchar* limit = dest + chars;
532#ifdef V8_HOST_CAN_READ_UNALIGNED
533 if (sizeof(*dest) == sizeof(*src)) {
Steve Block6ded16b2010-05-10 14:33:55 +0100534 // Number of characters in a uintptr_t.
535 static const int kStepSize = sizeof(uintptr_t) / sizeof(*dest); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +0000536 while (dest <= limit - kStepSize) {
Steve Block6ded16b2010-05-10 14:33:55 +0100537 *reinterpret_cast<uintptr_t*>(dest) =
538 *reinterpret_cast<const uintptr_t*>(src);
Steve Blocka7e24c12009-10-30 11:49:00 +0000539 dest += kStepSize;
540 src += kStepSize;
541 }
542 }
543#endif
544 while (dest < limit) {
545 *dest++ = static_cast<sinkchar>(*src++);
546 }
547}
548
549
Steve Block6ded16b2010-05-10 14:33:55 +0100550// Compare ASCII/16bit chars to ASCII/16bit chars.
551template <typename lchar, typename rchar>
552static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
553 const lchar* limit = lhs + chars;
554#ifdef V8_HOST_CAN_READ_UNALIGNED
555 if (sizeof(*lhs) == sizeof(*rhs)) {
556 // Number of characters in a uintptr_t.
557 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
558 while (lhs <= limit - kStepSize) {
559 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
560 *reinterpret_cast<const uintptr_t*>(rhs)) {
561 break;
562 }
563 lhs += kStepSize;
564 rhs += kStepSize;
565 }
566 }
567#endif
568 while (lhs < limit) {
569 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
570 if (r != 0) return r;
571 ++lhs;
572 ++rhs;
573 }
574 return 0;
575}
576
577
578template <typename T>
579static inline void MemsetPointer(T** dest, T* value, int counter) {
580#if defined(V8_HOST_ARCH_IA32)
581#define STOS "stosl"
582#elif defined(V8_HOST_ARCH_X64)
583#define STOS "stosq"
584#endif
585
586#if defined(__GNUC__) && defined(STOS)
587 asm volatile(
588 "cld;"
589 "rep ; " STOS
590 : "+&c" (counter), "+&D" (dest)
591 : "a" (value)
592 : "memory", "cc");
593#else
594 for (int i = 0; i < counter; i++) {
595 dest[i] = value;
596 }
597#endif
598
599#undef STOS
600}
601
602
603// Copies data from |src| to |dst|. The data spans MUST not overlap.
604inline void CopyWords(Object** dst, Object** src, int num_words) {
605 ASSERT(Min(dst, src) + num_words <= Max(dst, src));
606 ASSERT(num_words > 0);
607
608 // Use block copying memcpy if the segment we're copying is
609 // enough to justify the extra call/setup overhead.
610 static const int kBlockCopyLimit = 16;
611
612 if (num_words >= kBlockCopyLimit) {
613 memcpy(dst, src, num_words * kPointerSize);
614 } else {
615 int remaining = num_words;
616 do {
617 remaining--;
618 *dst++ = *src++;
619 } while (remaining > 0);
620 }
621}
622
623
Steve Blockd0582a62009-12-15 09:54:21 +0000624// Calculate 10^exponent.
625int TenToThe(int exponent);
626
Steve Block6ded16b2010-05-10 14:33:55 +0100627
628// The type-based aliasing rule allows the compiler to assume that pointers of
629// different types (for some definition of different) never alias each other.
630// Thus the following code does not work:
631//
632// float f = foo();
633// int fbits = *(int*)(&f);
634//
635// The compiler 'knows' that the int pointer can't refer to f since the types
636// don't match, so the compiler may cache f in a register, leaving random data
637// in fbits. Using C++ style casts makes no difference, however a pointer to
638// char data is assumed to alias any other pointer. This is the 'memcpy
639// exception'.
640//
641// Bit_cast uses the memcpy exception to move the bits from a variable of one
642// type of a variable of another type. Of course the end result is likely to
643// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
644// will completely optimize BitCast away.
645//
646// There is an additional use for BitCast.
647// Recent gccs will warn when they see casts that may result in breakage due to
648// the type-based aliasing rule. If you have checked that there is no breakage
649// you can use BitCast to cast one pointer type to another. This confuses gcc
650// enough that it can no longer see that you have cast one pointer type to
651// another thus avoiding the warning.
652template <class Dest, class Source>
653inline Dest BitCast(const Source& source) {
654 // Compile time assertion: sizeof(Dest) == sizeof(Source)
655 // A compile error here means your Dest and Source have different sizes.
656 typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
657
658 Dest dest;
659 memcpy(&dest, &source, sizeof(dest));
660 return dest;
661}
662
Steve Blocka7e24c12009-10-30 11:49:00 +0000663} } // namespace v8::internal
664
Steve Block6ded16b2010-05-10 14:33:55 +0100665
Steve Blocka7e24c12009-10-30 11:49:00 +0000666#endif // V8_UTILS_H_