blob: 7c818671d52f0d7462b41d7eaf1c26a278904ec0 [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>
vegorov@chromium.orgf8372902010-03-15 10:26:20 +000032#include <string.h>
ager@chromium.orga74f0da2008-12-03 16:05:52 +000033
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034namespace v8 {
35namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
37// ----------------------------------------------------------------------------
38// General helper functions
39
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +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).
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000042template <typename T>
43static inline bool IsPowerOf2(T x) {
44 return (x & (x - 1)) == 0;
45}
46
47
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000048// The C++ standard leaves the semantics of '>>' undefined for
49// negative signed operands. Most implementations do the right thing,
50// though.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051static 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.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000057// This allows conversion of Addresses and integral types into
58// 0-relative int offsets.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000059template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000060static inline intptr_t OffsetFrom(T x) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000061 return x - static_cast<T>(0);
62}
63
64
65// Compute the absolute value of type T for some 0-relative offset x.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000066// This allows conversion of 0-relative int offsets into Addresses and
67// integral types.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000068template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000069static inline T AddressFrom(intptr_t x) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +000070 return static_cast<T>(static_cast<T>(0) + x);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000089template <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
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000106// 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
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000111template <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.
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000119static inline bool IsAddressAligned(Address addr,
120 intptr_t alignment,
121 int offset) {
122 intptr_t offs = OffsetFrom(addr + offset);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 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
ager@chromium.orgc4c92722009-11-18 14:12:51 +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
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000148// ----------------------------------------------------------------------------
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000149// BitField is a help template for encoding and decode bitfield with
150// unsigned content.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000151template<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() {
fschneider@chromium.orgb95b98b2010-02-23 10:34:29 +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);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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) {
fschneider@chromium.orgb95b98b2010-02-23 10:34:29 +0000174 return static_cast<T>((value & mask()) >> shift);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000175 }
176};
177
178
179// ----------------------------------------------------------------------------
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000180// Hash function.
181
182uint32_t ComputeIntegerHash(uint32_t key);
183
184
185// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000186// 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
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000203// Read and return the raw bytes in a file. the size of the buffer is returned
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204// in size.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000205// The returned buffer must be freed by the caller.
206byte* ReadBytes(const char* filename, int* size, bool verbose = true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000207
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
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000217// 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
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225// 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:
kasper.lund7276f142008-07-30 08:49:36 +0000280 Vector() : start_(NULL), length_(0) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000281 Vector(T* data, int length) : start_(data), length_(length) {
282 ASSERT(length == 0 || (length > 0 && data != NULL));
283 }
284
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000285 static Vector<T> New(int length) {
286 return Vector<T>(NewArray<T>(length), length);
287 }
288
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000289 // 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
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298 // 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000313 T& first() { return start_[0]; }
314
315 T& last() { return start_[length_ - 1]; }
316
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317 // 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000324 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
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000336 void Truncate(int length) {
337 ASSERT(length <= length_);
338 length_ = length;
339 }
340
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 // Releases the array underlying this vector. Once disposed the
342 // vector is empty.
343 void Dispose() {
344 DeleteArray(start_);
345 start_ = NULL;
346 length_ = 0;
347 }
348
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000349 inline Vector<T> operator+(int offset) {
350 ASSERT(offset < length_);
351 return Vector<T>(start_ + offset, length_ - offset);
352 }
353
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000354 // Factory method for creating empty vectors.
355 static Vector<T> empty() { return Vector<T>(NULL, 0); }
356
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000357 protected:
358 void set_start(T* start) { start_ = start; }
359
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 private:
361 T* start_;
362 int length_;
363};
364
365
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000366// 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
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000383template <typename T, int kSize>
384class EmbeddedVector : public Vector<T> {
385 public:
386 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000387
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);
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000399 this->set_start(buffer_);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000400 return *this;
401 }
402
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000403 private:
404 T buffer_[kSize];
405};
406
407
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000408template <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 }
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000415
416 private:
417 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000418};
419
420
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000421inline Vector<const char> CStrVector(const char* data) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000422 return Vector<const char>(data, StrLength(data));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000423}
424
425inline Vector<char> MutableCStrVector(char* data) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000426 return Vector<char>(data, StrLength(data));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427}
428
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000429inline Vector<char> MutableCStrVector(char* data, int max) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000430 int length = StrLength(data);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000431 return Vector<char>(data, (length < max) ? length : max);
432}
433
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434template <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.
ager@chromium.org32912102009-01-16 10:38:43 +0000444// On return, *exits tells whether the file existed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000445Vector<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
kasper.lund7276f142008-07-30 08:49:36 +0000465// 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)
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000476 : buffer_(buffer, size), position_(0) { }
kasper.lund7276f142008-07-30 08:49:36 +0000477
478 ~StringBuilder() { if (!is_finalized()) Finalize(); }
479
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000480 int size() const { return buffer_.length(); }
kasper.lund7276f142008-07-30 08:49:36 +0000481
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');
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000496 ASSERT(!is_finalized() && position_ < buffer_.length());
kasper.lund7276f142008-07-30 08:49:36 +0000497 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:
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000519 Vector<char> buffer_;
kasper.lund7276f142008-07-30 08:49:36 +0000520 int position_;
521
522 bool is_finalized() const { return position_ < 0; }
mads.s.ager31e71382008-08-13 09:32:07 +0000523
524 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
kasper.lund7276f142008-07-30 08:49:36 +0000525};
526
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000527
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;
ager@chromium.org9085a012009-05-11 19:22:57 +0000532#ifdef V8_HOST_CAN_READ_UNALIGNED
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000533 if (sizeof(*dest) == sizeof(*src)) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000534 // Number of characters in a uintptr_t.
535 static const int kStepSize = sizeof(uintptr_t) / sizeof(*dest); // NOLINT
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000536 while (dest <= limit - kStepSize) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000537 *reinterpret_cast<uintptr_t*>(dest) =
538 *reinterpret_cast<const uintptr_t*>(src);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000539 dest += kStepSize;
540 src += kStepSize;
541 }
542 }
543#endif
544 while (dest < limit) {
545 *dest++ = static_cast<sinkchar>(*src++);
546 }
547}
548
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000549
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000550// 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)
ager@chromium.orgb26c50a2010-03-26 09:27:16 +0000587 asm volatile(
588 "cld;"
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000589 "rep ; " STOS
ager@chromium.orgb26c50a2010-03-26 09:27:16 +0000590 : "+&c" (counter), "+&D" (dest)
591 : "a" (value)
592 : "memory", "cc");
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000593#else
594 for (int i = 0; i < counter; i++) {
595 dest[i] = value;
596 }
597#endif
598
599#undef STOS
600}
601
602
lrn@chromium.org25156de2010-04-06 13:10:27 +0000603// 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
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +0000624// Calculate 10^exponent.
625int TenToThe(int exponent);
626
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000627
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
vegorov@chromium.org82e0bf62010-04-09 08:25:26 +0000663} } // namespace v8::internal
lrn@chromium.org25156de2010-04-06 13:10:27 +0000664
whesse@chromium.orgb6e43bb2010-04-14 09:36:28 +0000665
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000666#endif // V8_UTILS_H_