blob: f4a0598c20368b1ae7e936d43196bd74f8e5f22f [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000031#include <stdlib.h>
32
kasperl@chromium.org71affb52009-05-26 05:44:31 +000033namespace v8 {
34namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035
36// ----------------------------------------------------------------------------
37// General helper functions
38
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +000039// Returns true iff x is a power of 2 (or zero). Cannot be used with the
40// maximally negative value of the type T (the -1 overflows).
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041template <typename T>
42static inline bool IsPowerOf2(T x) {
43 return (x & (x - 1)) == 0;
44}
45
46
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000047// The C++ standard leaves the semantics of '>>' undefined for
48// negative signed operands. Most implementations do the right thing,
49// though.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000050static inline int ArithmeticShiftRight(int x, int s) {
51 return x >> s;
52}
53
54
55// Compute the 0-relative offset of some absolute value x of type T.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000056// This allows conversion of Addresses and integral types into
57// 0-relative int offsets.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000058template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000059static inline intptr_t OffsetFrom(T x) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060 return x - static_cast<T>(0);
61}
62
63
64// Compute the absolute value of type T for some 0-relative offset x.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000065// This allows conversion of 0-relative int offsets into Addresses and
66// integral types.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000068static inline T AddressFrom(intptr_t x) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000069 return static_cast<T>(0) + x;
70}
71
72
73// Return the largest multiple of m which is <= x.
74template <typename T>
75static inline T RoundDown(T x, int m) {
76 ASSERT(IsPowerOf2(m));
77 return AddressFrom<T>(OffsetFrom(x) & -m);
78}
79
80
81// Return the smallest multiple of m which is >= x.
82template <typename T>
83static inline T RoundUp(T x, int m) {
84 return RoundDown(x + m - 1, m);
85}
86
87
ager@chromium.orga74f0da2008-12-03 16:05:52 +000088template <typename T>
89static int Compare(const T& a, const T& b) {
90 if (a == b)
91 return 0;
92 else if (a < b)
93 return -1;
94 else
95 return 1;
96}
97
98
99template <typename T>
100static int PointerValueCompare(const T* a, const T* b) {
101 return Compare<T>(*a, *b);
102}
103
104
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000105// Returns the smallest power of two which is >= x. If you pass in a
106// number that is already a power of two, it is returned as is.
107uint32_t RoundUpToPowerOf2(uint32_t x);
108
109
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110template <typename T>
111static inline bool IsAligned(T value, T alignment) {
112 ASSERT(IsPowerOf2(alignment));
113 return (value & (alignment - 1)) == 0;
114}
115
116
117// Returns true if (addr + offset) is aligned.
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000118static inline bool IsAddressAligned(Address addr,
119 intptr_t alignment,
120 int offset) {
121 intptr_t offs = OffsetFrom(addr + offset);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122 return IsAligned(offs, alignment);
123}
124
125
126// Returns the maximum of the two parameters.
127template <typename T>
128static T Max(T a, T b) {
129 return a < b ? b : a;
130}
131
132
133// Returns the minimum of the two parameters.
134template <typename T>
135static T Min(T a, T b) {
136 return a < b ? a : b;
137}
138
139
140// ----------------------------------------------------------------------------
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000141// BitField is a help template for encoding and decode bitfield with
142// unsigned content.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000143template<class T, int shift, int size>
144class BitField {
145 public:
146 // Tells whether the provided value fits into the bit field.
147 static bool is_valid(T value) {
148 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
149 }
150
151 // Returns a uint32_t mask of bit field.
152 static uint32_t mask() {
153 return (1U << (size + shift)) - (1U << shift);
154 }
155
156 // Returns a uint32_t with the bit field value encoded.
157 static uint32_t encode(T value) {
158 ASSERT(is_valid(value));
159 return static_cast<uint32_t>(value) << shift;
160 }
161
162 // Extracts the bit field from the value.
163 static T decode(uint32_t value) {
164 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
165 }
166};
167
168
169// ----------------------------------------------------------------------------
170// Support for compressed, machine-independent encoding
171// and decoding of integer values of arbitrary size.
172
173// Encoding and decoding from/to a buffer at position p;
174// the result is the position after the encoded integer.
175// Small signed integers in the range -64 <= x && x < 64
176// are encoded in 1 byte; larger values are encoded in 2
177// or more bytes. At most sizeof(int) + 1 bytes are used
178// in the worst case.
179byte* EncodeInt(byte* p, int x);
180byte* DecodeInt(byte* p, int* x);
181
182
183// Encoding and decoding from/to a buffer at position p - 1
184// moving backward; the result is the position of the last
185// byte written. These routines are useful to read/write
186// into a buffer starting at the end of the buffer.
187byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
188
189// The decoding function is inlined since its performance is
190// important to mark-sweep garbage collection.
191inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
192 byte b = *--p;
193 if (b >= 128) {
194 *x = static_cast<unsigned int>(b) - 128;
195 return p;
196 }
197 unsigned int r = static_cast<unsigned int>(b);
198 unsigned int s = 7;
199 b = *--p;
200 while (b < 128) {
201 r |= static_cast<unsigned int>(b) << s;
202 s += 7;
203 b = *--p;
204 }
205 // b >= 128
206 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
207 return p;
208}
209
210
211// ----------------------------------------------------------------------------
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000212// Hash function.
213
214uint32_t ComputeIntegerHash(uint32_t key);
215
216
217// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000218// I/O support.
219
220// Our version of printf(). Avoids compilation errors that we get
221// with standard printf when attempting to print pointers, etc.
222// (the errors are due to the extra compilation flags, which we
223// want elsewhere).
224void PrintF(const char* format, ...);
225
226// Our version of fflush.
227void Flush();
228
229
230// Read a line of characters after printing the prompt to stdout. The resulting
231// char* needs to be disposed off with DeleteArray by the caller.
232char* ReadLine(const char* prompt);
233
234
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000235// Read and return the raw bytes in a file. the size of the buffer is returned
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236// in size.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000237// The returned buffer must be freed by the caller.
238byte* ReadBytes(const char* filename, int* size, bool verbose = true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239
240
241// Write size chars from str to the file given by filename.
242// The file is overwritten. Returns the number of chars written.
243int WriteChars(const char* filename,
244 const char* str,
245 int size,
246 bool verbose = true);
247
248
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000249// Write size bytes to the file given by filename.
250// The file is overwritten. Returns the number of bytes written.
251int WriteBytes(const char* filename,
252 const byte* bytes,
253 int size,
254 bool verbose = true);
255
256
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000257// Write the C code
258// const char* <varname> = "<str>";
259// const int <varname>_len = <len>;
260// to the file given by filename. Only the first len chars are written.
261int WriteAsCFile(const char* filename, const char* varname,
262 const char* str, int size, bool verbose = true);
263
264
265// ----------------------------------------------------------------------------
266// Miscellaneous
267
268// A static resource holds a static instance that can be reserved in
269// a local scope using an instance of Access. Attempts to re-reserve
270// the instance will cause an error.
271template <typename T>
272class StaticResource {
273 public:
274 StaticResource() : is_reserved_(false) {}
275
276 private:
277 template <typename S> friend class Access;
278 T instance_;
279 bool is_reserved_;
280};
281
282
283// Locally scoped access to a static resource.
284template <typename T>
285class Access {
286 public:
287 explicit Access(StaticResource<T>* resource)
288 : resource_(resource)
289 , instance_(&resource->instance_) {
290 ASSERT(!resource->is_reserved_);
291 resource->is_reserved_ = true;
292 }
293
294 ~Access() {
295 resource_->is_reserved_ = false;
296 resource_ = NULL;
297 instance_ = NULL;
298 }
299
300 T* value() { return instance_; }
301 T* operator -> () { return instance_; }
302
303 private:
304 StaticResource<T>* resource_;
305 T* instance_;
306};
307
308
309template <typename T>
310class Vector {
311 public:
kasper.lund7276f142008-07-30 08:49:36 +0000312 Vector() : start_(NULL), length_(0) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313 Vector(T* data, int length) : start_(data), length_(length) {
314 ASSERT(length == 0 || (length > 0 && data != NULL));
315 }
316
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000317 static Vector<T> New(int length) {
318 return Vector<T>(NewArray<T>(length), length);
319 }
320
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000321 // Returns a vector using the same backing storage as this one,
322 // spanning from and including 'from', to but not including 'to'.
323 Vector<T> SubVector(int from, int to) {
324 ASSERT(from < length_);
325 ASSERT(to <= length_);
326 ASSERT(from < to);
327 return Vector<T>(start() + from, to - from);
328 }
329
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000330 // Returns the length of the vector.
331 int length() const { return length_; }
332
333 // Returns whether or not the vector is empty.
334 bool is_empty() const { return length_ == 0; }
335
336 // Returns the pointer to the start of the data in the vector.
337 T* start() const { return start_; }
338
339 // Access individual vector elements - checks bounds in debug mode.
340 T& operator[](int index) const {
341 ASSERT(0 <= index && index < length_);
342 return start_[index];
343 }
344
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000345 T& first() { return start_[0]; }
346
347 T& last() { return start_[length_ - 1]; }
348
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000349 // Returns a clone of this vector with a new backing store.
350 Vector<T> Clone() const {
351 T* result = NewArray<T>(length_);
352 for (int i = 0; i < length_; i++) result[i] = start_[i];
353 return Vector<T>(result, length_);
354 }
355
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000356 void Sort(int (*cmp)(const T*, const T*)) {
357 typedef int (*RawComparer)(const void*, const void*);
358 qsort(start(),
359 length(),
360 sizeof(T),
361 reinterpret_cast<RawComparer>(cmp));
362 }
363
364 void Sort() {
365 Sort(PointerValueCompare<T>);
366 }
367
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000368 void Truncate(int length) {
369 ASSERT(length <= length_);
370 length_ = length;
371 }
372
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000373 // Releases the array underlying this vector. Once disposed the
374 // vector is empty.
375 void Dispose() {
kasper.lund7276f142008-07-30 08:49:36 +0000376 if (is_empty()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000377 DeleteArray(start_);
378 start_ = NULL;
379 length_ = 0;
380 }
381
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000382 inline Vector<T> operator+(int offset) {
383 ASSERT(offset < length_);
384 return Vector<T>(start_ + offset, length_ - offset);
385 }
386
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000387 // Factory method for creating empty vectors.
388 static Vector<T> empty() { return Vector<T>(NULL, 0); }
389
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000390 protected:
391 void set_start(T* start) { start_ = start; }
392
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393 private:
394 T* start_;
395 int length_;
396};
397
398
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000399// A temporary assignment sets a (non-local) variable to a value on
400// construction and resets it the value on destruction.
401template <typename T>
402class TempAssign {
403 public:
404 TempAssign(T* var, T value): var_(var), old_value_(*var) {
405 *var = value;
406 }
407
408 ~TempAssign() { *var_ = old_value_; }
409
410 private:
411 T* var_;
412 T old_value_;
413};
414
415
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000416template <typename T, int kSize>
417class EmbeddedVector : public Vector<T> {
418 public:
419 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000420
421 // When copying, make underlying Vector to reference our buffer.
422 EmbeddedVector(const EmbeddedVector& rhs)
423 : Vector<T>(rhs) {
424 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
425 set_start(buffer_);
426 }
427
428 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
429 if (this == &rhs) return *this;
430 Vector<T>::operator=(rhs);
431 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
432 set_start(buffer_);
433 return *this;
434 }
435
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000436 private:
437 T buffer_[kSize];
438};
439
440
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000441template <typename T>
442class ScopedVector : public Vector<T> {
443 public:
444 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
445 ~ScopedVector() {
446 DeleteArray(this->start());
447 }
448};
449
450
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000451inline Vector<const char> CStrVector(const char* data) {
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000452 return Vector<const char>(data, static_cast<int>(strlen(data)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000453}
454
455inline Vector<char> MutableCStrVector(char* data) {
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000456 return Vector<char>(data, static_cast<int>(strlen(data)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000457}
458
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000459inline Vector<char> MutableCStrVector(char* data, int max) {
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000460 int length = static_cast<int>(strlen(data));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000461 return Vector<char>(data, (length < max) ? length : max);
462}
463
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000464template <typename T>
465inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
466 int length) {
467 return Vector< Handle<Object> >(
468 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
469}
470
471
472// Simple support to read a file into a 0-terminated C-string.
473// The returned buffer must be freed by the caller.
ager@chromium.org32912102009-01-16 10:38:43 +0000474// On return, *exits tells whether the file existed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475Vector<const char> ReadFile(const char* filename,
476 bool* exists,
477 bool verbose = true);
478
479
480// Simple wrapper that allows an ExternalString to refer to a
481// Vector<const char>. Doesn't assume ownership of the data.
482class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
483 public:
484 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
485
486 virtual const char* data() const { return data_.start(); }
487
488 virtual size_t length() const { return data_.length(); }
489
490 private:
491 Vector<const char> data_;
492};
493
494
kasper.lund7276f142008-07-30 08:49:36 +0000495// Helper class for building result strings in a character buffer. The
496// purpose of the class is to use safe operations that checks the
497// buffer bounds on all operations in debug mode.
498class StringBuilder {
499 public:
500 // Create a string builder with a buffer of the given size. The
501 // buffer is allocated through NewArray<char> and must be
502 // deallocated by the caller of Finalize().
503 explicit StringBuilder(int size);
504
505 StringBuilder(char* buffer, int size)
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000506 : buffer_(buffer, size), position_(0) { }
kasper.lund7276f142008-07-30 08:49:36 +0000507
508 ~StringBuilder() { if (!is_finalized()) Finalize(); }
509
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000510 int size() const { return buffer_.length(); }
kasper.lund7276f142008-07-30 08:49:36 +0000511
512 // Get the current position in the builder.
513 int position() const {
514 ASSERT(!is_finalized());
515 return position_;
516 }
517
518 // Reset the position.
519 void Reset() { position_ = 0; }
520
521 // Add a single character to the builder. It is not allowed to add
522 // 0-characters; use the Finalize() method to terminate the string
523 // instead.
524 void AddCharacter(char c) {
525 ASSERT(c != '\0');
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000526 ASSERT(!is_finalized() && position_ < buffer_.length());
kasper.lund7276f142008-07-30 08:49:36 +0000527 buffer_[position_++] = c;
528 }
529
530 // Add an entire string to the builder. Uses strlen() internally to
531 // compute the length of the input string.
532 void AddString(const char* s);
533
534 // Add the first 'n' characters of the given string 's' to the
535 // builder. The input string must have enough characters.
536 void AddSubstring(const char* s, int n);
537
538 // Add formatted contents to the builder just like printf().
539 void AddFormatted(const char* format, ...);
540
541 // Add character padding to the builder. If count is non-positive,
542 // nothing is added to the builder.
543 void AddPadding(char c, int count);
544
545 // Finalize the string by 0-terminating it and returning the buffer.
546 char* Finalize();
547
548 private:
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000549 Vector<char> buffer_;
kasper.lund7276f142008-07-30 08:49:36 +0000550 int position_;
551
552 bool is_finalized() const { return position_ < 0; }
mads.s.ager31e71382008-08-13 09:32:07 +0000553
554 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
kasper.lund7276f142008-07-30 08:49:36 +0000555};
556
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000557
558// Copy from ASCII/16bit chars to ASCII/16bit chars.
559template <typename sourcechar, typename sinkchar>
560static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
561 sinkchar* limit = dest + chars;
ager@chromium.org9085a012009-05-11 19:22:57 +0000562#ifdef V8_HOST_CAN_READ_UNALIGNED
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000563 if (sizeof(*dest) == sizeof(*src)) {
564 // Number of characters in a uint32_t.
565 static const int kStepSize = sizeof(uint32_t) / sizeof(*dest); // NOLINT
566 while (dest <= limit - kStepSize) {
567 *reinterpret_cast<uint32_t*>(dest) =
568 *reinterpret_cast<const uint32_t*>(src);
569 dest += kStepSize;
570 src += kStepSize;
571 }
572 }
573#endif
574 while (dest < limit) {
575 *dest++ = static_cast<sinkchar>(*src++);
576 }
577}
578
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000579
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000580} } // namespace v8::internal
581
582#endif // V8_UTILS_H_