torque-internal.tq 13 KB
Newer Older
1 2 3 4
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8 9
// Unfortunately, MutableSlice<> is currently not a subtype of ConstSlice.
// This would require struct subtyping, which is not yet supported.
type MutableSlice<T: type> extends torque_internal::Slice<T, &T>;
type ConstSlice<T: type> extends torque_internal::Slice<T, const &T>;

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
macro Subslice<T: type>(slice: ConstSlice<T>, start: intptr, length: intptr):
    ConstSlice<T>labels OutOfBounds {
  if (Unsigned(length) > Unsigned(slice.length)) goto OutOfBounds;
  if (Unsigned(start) > Unsigned(slice.length - length)) goto OutOfBounds;
  const offset = slice.offset + torque_internal::TimesSizeOf<T>(start);
  return torque_internal::unsafe::NewConstSlice<T>(
      slice.object, offset, length);
}
macro Subslice<T: type>(slice: MutableSlice<T>, start: intptr, length: intptr):
    MutableSlice<T>labels OutOfBounds {
  if (Unsigned(length) > Unsigned(slice.length)) goto OutOfBounds;
  if (Unsigned(start) > Unsigned(slice.length - length)) goto OutOfBounds;
  const offset = slice.offset + torque_internal::TimesSizeOf<T>(start);
  return torque_internal::unsafe::NewMutableSlice<T>(
      slice.object, offset, length);
}

27 28 29 30 31 32 33 34 35 36 37 38 39 40
namespace unsafe {

macro AddOffset<T: type>(ref: &T, offset: intptr): &T {
  return torque_internal::unsafe::NewReference<T>(
      ref.object, ref.offset + torque_internal::TimesSizeOf<T>(offset));
}

macro AddOffset<T: type>(ref: const &T, offset: intptr): const &T {
  return torque_internal::unsafe::NewReference<T>(
      ref.object, ref.offset + torque_internal::TimesSizeOf<T>(offset));
}

}  // namespace unsafe

41
namespace torque_internal {
42 43 44 45 46 47 48 49 50
// Unsafe is a marker that we require to be passed when calling internal APIs
// that might lead to unsoundness when used incorrectly. Unsafe markers should
// therefore not be instantiated anywhere outside of this namespace.
struct Unsafe {}

// Size of a type in memory (on the heap). For class types, this is the size
// of the pointer, not of the instance.
intrinsic %SizeOf<T: type>(): constexpr int31;

51 52 53 54
macro TimesSizeOf<T: type>(i: intptr): intptr {
  return i * %SizeOf<T>();
}

55
struct Reference<T: type> {
56
  const object: HeapObject|TaggedZeroPattern;
57 58 59 60 61 62
  const offset: intptr;
  unsafeMarker: Unsafe;
}
type ConstReference<T: type> extends Reference<T>;
type MutableReference<T: type> extends ConstReference<T>;

63
namespace unsafe {
64 65
macro NewReference<T: type>(
    object: HeapObject|TaggedZeroPattern, offset: intptr):&T {
66 67 68
  return %RawDownCast<&T>(
      Reference<T>{object: object, offset: offset, unsafeMarker: Unsafe {}});
}
69 70 71 72 73 74 75
macro NewOffHeapReference<T: type>(ptr: RawPtr<T>):&T {
  return %RawDownCast<&T>(Reference<T>{
    object: kZeroBitPattern,
    offset: Convert<intptr>(Convert<RawPtr>(ptr)) + kHeapObjectTag,
    unsafeMarker: Unsafe {}
  });
}
76 77 78 79 80
macro ReferenceCast<T: type, U: type>(ref:&U):&T {
  const ref = NewReference<T>(ref.object, ref.offset);
  UnsafeCast<T>(*ref);
  return ref;
}
81 82 83 84

extern macro GCUnsafeReferenceToRawPtr(
    HeapObject | TaggedZeroPattern, intptr): RawPtr;

85
}  // namespace unsafe
86

87 88
struct Slice<T: type, Reference: type> {
  macro TryAtIndex(index: intptr): Reference labels OutOfBounds {
89
    if (Convert<uintptr>(index) < Convert<uintptr>(this.length)) {
90
      return this.UncheckedAtIndex(index);
91 92
    } else {
      goto OutOfBounds;
93
    }
94
  }
95 96 97 98
  macro UncheckedAtIndex(index: intptr): Reference {
    return unsafe::NewReference<T>(
        this.object, this.offset + TimesSizeOf<T>(index));
  }
99

100
  macro AtIndex(index: intptr): Reference {
101
    return this.TryAtIndex(index) otherwise unreachable;
102 103
  }

104
  macro AtIndex(index: uintptr): Reference {
105
    return this.TryAtIndex(Convert<intptr>(index)) otherwise unreachable;
106 107
  }

108 109 110 111
  macro AtIndex(index: constexpr IntegerLiteral): Reference {
    return this.AtIndex(FromConstexpr<uintptr>(index));
  }

112
  macro AtIndex(index: constexpr int31): Reference {
113 114
    const i: intptr = Convert<intptr>(index);
    return this.TryAtIndex(i) otherwise unreachable;
115
  }
Tobias Tebbi's avatar
Tobias Tebbi committed
116

117
  macro AtIndex(index: Smi): Reference {
118 119
    const i: intptr = Convert<intptr>(index);
    return this.TryAtIndex(i) otherwise unreachable;
120 121
  }

122
  macro Iterator(): SliceIterator<T, Reference> {
123
    const end = this.offset + TimesSizeOf<T>(this.length);
124
    return SliceIterator<T, Reference>{
125 126 127 128 129
      object: this.object,
      start: this.offset,
      end: end,
      unsafeMarker: Unsafe {}
    };
Tobias Tebbi's avatar
Tobias Tebbi committed
130
  }
131 132
  macro Iterator(
      startIndex: intptr, endIndex: intptr): SliceIterator<T, Reference> {
133 134 135
    check(
        Convert<uintptr>(endIndex) <= Convert<uintptr>(this.length) &&
        Convert<uintptr>(startIndex) <= Convert<uintptr>(endIndex));
136 137
    const start = this.offset + TimesSizeOf<T>(startIndex);
    const end = this.offset + TimesSizeOf<T>(endIndex);
138
    return SliceIterator<T, Reference>{
139 140 141 142 143
      object: this.object,
      start,
      end,
      unsafeMarker: Unsafe {}
    };
Tobias Tebbi's avatar
Tobias Tebbi committed
144
  }
145

146 147 148 149 150 151
  // WARNING: This can return a raw pointer into the heap, which is not GC-safe.
  macro GCUnsafeStartPointer(): RawPtr<T> {
    return %RawDownCast<RawPtr<T>>(
        unsafe::GCUnsafeReferenceToRawPtr(this.object, this.offset));
  }

152
  const object: HeapObject|TaggedZeroPattern;
153 154 155 156 157
  const offset: intptr;
  const length: intptr;
  unsafeMarker: Unsafe;
}

158 159
namespace unsafe {

160
macro NewMutableSlice<T: type>(
161 162
    object: HeapObject|TaggedZeroPattern, offset: intptr,
    length: intptr): MutableSlice<T> {
163 164 165 166 167 168 169 170 171
  return %RawDownCast<MutableSlice<T>>(Slice<T, &T>{
    object: object,
    offset: offset,
    length: length,
    unsafeMarker: Unsafe {}
  });
}

macro NewConstSlice<T: type>(
172 173
    object: HeapObject|TaggedZeroPattern, offset: intptr,
    length: intptr): ConstSlice<T> {
174
  return %RawDownCast<ConstSlice<T>>(Slice<T, const &T>{
175 176 177 178
    object: object,
    offset: offset,
    length: length,
    unsafeMarker: Unsafe {}
179
  });
180 181
}

182 183 184
macro NewOffHeapConstSlice<T: type>(
    startPointer: RawPtr<T>, length: intptr): ConstSlice<T> {
  return %RawDownCast<ConstSlice<T>>(Slice<T, const &T>{
185 186 187 188
    object: kZeroBitPattern,
    offset: Convert<intptr>(Convert<RawPtr>(startPointer)) + kHeapObjectTag,
    length: length,
    unsafeMarker: Unsafe {}
189
  });
190 191 192 193
}

}  // namespace unsafe

194
struct SliceIterator<T: type, Reference: type> {
195 196 197
  macro Empty(): bool {
    return this.start == this.end;
  }
198

199
  macro Next(): T labels NoMore {
200
    return *this.NextReference() otherwise NoMore;
201 202
  }

203
  macro NextReference(): Reference labels NoMore {
204 205 206
    if (this.Empty()) {
      goto NoMore;
    } else {
207
      const result = unsafe::NewReference<T>(this.object, this.start);
208 209
      this.start += %SizeOf<T>();
      return result;
210 211
    }
  }
212

213
  object: HeapObject|TaggedZeroPattern;
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  start: intptr;
  end: intptr;
  unsafeMarker: Unsafe;
}

macro AddIndexedFieldSizeToObjectSize(
    baseSize: intptr, arrayLength: intptr, fieldSize: constexpr int32): intptr {
  const arrayLength = Convert<int32>(arrayLength);
  const byteLength = TryInt32Mul(arrayLength, fieldSize)
      otherwise unreachable;
  return TryIntPtrAdd(baseSize, Convert<intptr>(byteLength))
      otherwise unreachable;
}

macro AlignTagged(x: intptr): intptr {
  // Round up to a multiple of kTaggedSize.
  return (x + kObjectAlignmentMask) & ~kObjectAlignmentMask;
}

macro IsTaggedAligned(x: intptr): bool {
  return (x & kObjectAlignmentMask) == 0;
}

macro ValidAllocationSize(sizeInBytes: intptr, map: Map): bool {
  if (sizeInBytes <= 0) return false;
  if (!IsTaggedAligned(sizeInBytes)) return false;
  const instanceSizeInWords = Convert<intptr>(map.instance_size_in_words);
  return instanceSizeInWords == kVariableSizeSentinel ||
      instanceSizeInWords * kTaggedSize == sizeInBytes;
}

type UninitializedHeapObject extends HeapObject;

extern macro GetInstanceTypeMap(constexpr InstanceType): Map;
248 249
extern macro Allocate(
    intptr, constexpr AllocationFlag): UninitializedHeapObject;
250

251 252 253 254
const kAllocateBaseFlags: constexpr AllocationFlag =
    AllocationFlag::kAllowLargeObjectAllocation;
macro AllocateFromNew(
    sizeInBytes: intptr, map: Map, pretenured: bool): UninitializedHeapObject {
255
  dcheck(ValidAllocationSize(sizeInBytes, map));
256 257 258 259
  if (pretenured) {
    return Allocate(
        sizeInBytes,
        %RawConstexprCast<constexpr AllocationFlag>(
260 261
            %RawConstexprCast<constexpr int32>(kAllocateBaseFlags) |
            %RawConstexprCast<constexpr int32>(AllocationFlag::kPretenured)));
262 263 264
  } else {
    return Allocate(sizeInBytes, kAllocateBaseFlags);
  }
265 266 267
}

macro InitializeFieldsFromIterator<T: type, Iterator: type>(
268
    target: MutableSlice<T>, originIterator: Iterator): void {
269 270 271 272
  let targetIterator = target.Iterator();
  let originIterator = originIterator;
  while (true) {
    const ref:&T = targetIterator.NextReference() otherwise break;
273
    *ref = originIterator.Next() otherwise unreachable;
274
  }
275 276 277
}
// Dummy implementations: do not initialize for UninitializedIterator.
InitializeFieldsFromIterator<char8, UninitializedIterator>(
278 279
    _target: MutableSlice<char8>,
    _originIterator: UninitializedIterator): void {}
280
InitializeFieldsFromIterator<char16, UninitializedIterator>(
281 282
    _target: MutableSlice<char16>,
    _originIterator: UninitializedIterator): void {}
283 284

extern macro IsDoubleHole(HeapObject, intptr): bool;
285
extern macro StoreDoubleHole(HeapObject, intptr): void;
286 287 288

macro LoadFloat64OrHole(r:&float64_or_hole): float64_or_hole {
  return float64_or_hole{
289 290
    is_hole: IsDoubleHole(
        %RawDownCast<HeapObject>(r.object), r.offset - kHeapObjectTag),
291
    value: *unsafe::NewReference<float64>(r.object, r.offset)
292 293
  };
}
294
macro StoreFloat64OrHole(r:&float64_or_hole, value: float64_or_hole): void {
295
  if (value.is_hole) {
296 297
    StoreDoubleHole(
        %RawDownCast<HeapObject>(r.object), r.offset - kHeapObjectTag);
298
  } else {
299
    *unsafe::NewReference<float64>(r.object, r.offset) = value.value;
300
  }
301
}
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

macro DownCastForTorqueClass<T : type extends HeapObject>(o: HeapObject):
    T labels CastError {
  const map = o.map;
  const minInstanceType = %MinInstanceType<T>();
  const maxInstanceType = %MaxInstanceType<T>();
  if constexpr (minInstanceType == maxInstanceType) {
    if constexpr (%ClassHasMapConstant<T>()) {
      if (map != %GetClassMapConstant<T>()) goto CastError;
    } else {
      if (map.instance_type != minInstanceType) goto CastError;
    }
  } else {
    const diff: int32 = maxInstanceType - minInstanceType;
    const offset = Convert<int32>(Convert<uint16>(map.instance_type)) -
        Convert<int32>(Convert<uint16>(
            FromConstexpr<InstanceType>(minInstanceType)));
    if (Unsigned(offset) > Unsigned(diff)) goto CastError;
  }
  return %RawDownCast<T>(o);
}

324
extern macro StaticAssert(bool, constexpr string): void;
325

326 327 328
// This is for the implementation of the dot operator. In any context where the
// dot operator is available, the correct way to get the length of an indexed
// field x from object o is `(&o.x).length`.
329
intrinsic %IndexedFieldLength<T: type>(o: T, f: constexpr string): intptr;
330

331 332 333 334 335 336 337
// If field x is defined as optional, then &o.x returns a reference to the field
// or crashes the program (unreachable) if the field is not present. Usually
// that's the most convenient behavior, but in rare cases such as the
// implementation of the dot operator, we may instead need to get a Slice to the
// optional field, which is either length zero or one depending on whether the
// field is present. This intrinsic provides Slices for both indexed fields
// (equivalent to &o.x) and optional fields.
338 339
intrinsic %FieldSlice<T: type, TSlice: type>(
    o: T, f: constexpr string): TSlice;
340

341 342 343 344 345 346 347 348 349 350
extern macro GetPendingMessage(): TheHole|JSMessageObject;
extern macro SetPendingMessage(TheHole | JSMessageObject): void;

// This is implicitly performed at the beginning of Torque catch-blocks.
macro GetAndResetPendingMessage(): TheHole|JSMessageObject {
  const message = GetPendingMessage();
  SetPendingMessage(TheHole);
  return message;
}

351 352 353 354 355
}  // namespace torque_internal

// Indicates that an array-field should not be initialized.
// For safety reasons, this is only allowed for untagged types.
struct UninitializedIterator {}
Tobias Tebbi's avatar
Tobias Tebbi committed
356 357 358

// %RawDownCast should *never* be used anywhere in Torque code except for
// in Torque-based UnsafeCast operators preceeded by an appropriate
359
// type dcheck()
Tobias Tebbi's avatar
Tobias Tebbi committed
360 361
intrinsic %RawDownCast<To: type, From: type>(x: From): To;
intrinsic %RawConstexprCast<To: type, From: type>(f: From): To;
362

363 364 365 366 367 368
intrinsic %MinInstanceType<T: type>(): constexpr InstanceType;
intrinsic %MaxInstanceType<T: type>(): constexpr InstanceType;

intrinsic %ClassHasMapConstant<T: type>(): constexpr bool;
intrinsic %GetClassMapConstant<T: type>(): Map;

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
struct IteratorSequence<T: type, FirstIterator: type, SecondIterator: type> {
  macro Empty(): bool {
    return this.first.Empty() && this.second.Empty();
  }

  macro Next(): T labels NoMore {
    return this.first.Next()
        otherwise return (this.second.Next() otherwise NoMore);
  }

  first: FirstIterator;
  second: SecondIterator;
}

macro IteratorSequence<T: type, FirstIterator: type, SecondIterator: type>(
    first: FirstIterator, second: SecondIterator):
    IteratorSequence<T, FirstIterator, SecondIterator> {
  return IteratorSequence<T>{first, second};
}