test-torque.tq 32.8 KB
Newer Older
1 2 3 4
// Copyright 2018 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
// Test line comment
/* Test mulitline
   comment
*/
9
/*multiline_without_whitespace*/
10

11
namespace test {
12 13
macro ElementsKindTestHelper1(kind: constexpr ElementsKind): bool {
  if constexpr (
14 15
      kind == ElementsKind::UINT8_ELEMENTS ||
      kind == ElementsKind::UINT16_ELEMENTS) {
16 17 18
    return true;
  } else {
    return false;
19
  }
20
}
21

22
macro ElementsKindTestHelper2(kind: constexpr ElementsKind): constexpr bool {
23 24
  return kind == ElementsKind::UINT8_ELEMENTS ||
      kind == ElementsKind::UINT16_ELEMENTS;
25
}
26

27 28 29 30
macro LabelTestHelper1(): never
    labels Label1 {
  goto Label1;
}
31

32 33 34 35
macro LabelTestHelper2(): never
    labels Label2(Smi) {
  goto Label2(42);
}
36

37 38 39 40
macro LabelTestHelper3(): never
    labels Label3(Oddball, Smi) {
  goto Label3(Null, 7);
}
41

42 43 44 45 46
@export
macro TestConstexpr1() {
  check(FromConstexpr<bool>(
      IsFastElementsKind(ElementsKind::PACKED_SMI_ELEMENTS)));
}
47

48 49 50 51 52 53
@export
macro TestConstexprIf() {
  check(ElementsKindTestHelper1(ElementsKind::UINT8_ELEMENTS));
  check(ElementsKindTestHelper1(ElementsKind::UINT16_ELEMENTS));
  check(!ElementsKindTestHelper1(ElementsKind::UINT32_ELEMENTS));
}
54

55 56 57 58 59 60 61 62 63 64 65
@export
macro TestConstexprReturn() {
  check(FromConstexpr<bool>(
      ElementsKindTestHelper2(ElementsKind::UINT8_ELEMENTS)));
  check(FromConstexpr<bool>(
      ElementsKindTestHelper2(ElementsKind::UINT16_ELEMENTS)));
  check(!FromConstexpr<bool>(
      ElementsKindTestHelper2(ElementsKind::UINT32_ELEMENTS)));
  check(FromConstexpr<bool>(
      !ElementsKindTestHelper2(ElementsKind::UINT32_ELEMENTS)));
}
66

67 68 69 70 71 72
@export
macro TestGotoLabel(): Boolean {
  try {
    LabelTestHelper1() otherwise Label1;
  } label Label1 {
    return True;
73
  }
74
}
75

76 77 78 79 80 81 82
@export
macro TestGotoLabelWithOneParameter(): Boolean {
  try {
    LabelTestHelper2() otherwise Label2;
  } label Label2(smi: Smi) {
    check(smi == 42);
    return True;
83
  }
84
}
85

86 87 88 89 90 91 92 93
@export
macro TestGotoLabelWithTwoParameters(): Boolean {
  try {
    LabelTestHelper3() otherwise Label3;
  } label Label3(o: Oddball, smi: Smi) {
    check(o == Null);
    check(smi == 7);
    return True;
94
  }
95
}
96

97 98 99
builtin GenericBuiltinTest<T: type>(_param: T): JSAny {
  return Null;
}
100

101 102 103
GenericBuiltinTest<JSAny>(param: JSAny): JSAny {
  return param;
}
104

105 106 107 108 109 110 111
@export
macro TestBuiltinSpecialization() {
  check(GenericBuiltinTest<Smi>(0) == Null);
  check(GenericBuiltinTest<Smi>(1) == Null);
  check(GenericBuiltinTest<JSAny>(Undefined) == Undefined);
  check(GenericBuiltinTest<JSAny>(Undefined) == Undefined);
}
112

113 114 115 116 117 118
macro LabelTestHelper4(flag: constexpr bool): never
    labels Label4, Label5 {
  if constexpr (flag) {
    goto Label4;
  } else {
    goto Label5;
119
  }
120
}
121

122 123 124 125 126 127 128
macro CallLabelTestHelper4(flag: constexpr bool): bool {
  try {
    LabelTestHelper4(flag) otherwise Label4, Label5;
  } label Label4 {
    return true;
  } label Label5 {
    return false;
129
  }
130
}
131

132 133 134 135
@export
macro TestPartiallyUnusedLabel(): Boolean {
  const r1: bool = CallLabelTestHelper4(true);
  const r2: bool = CallLabelTestHelper4(false);
136

137 138 139 140
  if (r1 && !r2) {
    return True;
  } else {
    return False;
141
  }
142
}
143

144 145 146
macro GenericMacroTest<T: type>(_param: T): Object {
  return Undefined;
}
147

148 149 150
GenericMacroTest<Object>(param2: Object): Object {
  return param2;
}
151

152 153 154 155
macro GenericMacroTestWithLabels<T: type>(_param: T): Object
labels _X {
  return Undefined;
}
156

157 158 159 160
GenericMacroTestWithLabels<Object>(param2: Object): Object
    labels Y {
  return Cast<Smi>(param2) otherwise Y;
}
161

162 163 164 165 166 167 168 169 170 171 172
@export
macro TestMacroSpecialization() {
  try {
    const _smi0: Smi = 0;
    check(GenericMacroTest<Smi>(0) == Undefined);
    check(GenericMacroTest<Smi>(1) == Undefined);
    check(GenericMacroTest<Object>(Null) == Null);
    check(GenericMacroTest<Object>(False) == False);
    check(GenericMacroTest<Object>(True) == True);
    check((GenericMacroTestWithLabels<Smi>(0) otherwise Fail) == Undefined);
    check((GenericMacroTestWithLabels<Smi>(0) otherwise Fail) == Undefined);
173
    try {
174 175 176 177
      GenericMacroTestWithLabels<Object>(False) otherwise Expected;
    } label Expected {}
  } label Fail {
    unreachable;
178
  }
179
}
180

181 182 183 184 185 186
builtin TestHelperPlus1(x: Smi): Smi {
  return x + 1;
}
builtin TestHelperPlus2(x: Smi): Smi {
  return x + 2;
}
187

188 189 190 191 192 193 194 195
@export
macro TestFunctionPointers(implicit context: Context)(): Boolean {
  let fptr: builtin(Smi) => Smi = TestHelperPlus1;
  check(fptr(42) == 43);
  fptr = TestHelperPlus2;
  check(fptr(42) == 44);
  return True;
}
196

197 198 199 200 201 202
@export
macro TestVariableRedeclaration(implicit context: Context)(): Boolean {
  let _var1: int31 = FromConstexpr<bool>(42 == 0) ? 0 : 1;
  let _var2: int31 = FromConstexpr<bool>(42 == 0) ? 1 : 0;
  return True;
}
203

204 205 206 207 208
@export
macro TestTernaryOperator(x: Smi): Smi {
  const b: bool = x < 0 ? true : false;
  return b ? x - 10 : x + 100;
}
209

210 211 212 213
@export
macro TestFunctionPointerToGeneric() {
  const fptr1: builtin(Smi) => JSAny = GenericBuiltinTest<Smi>;
  const fptr2: builtin(JSAny) => JSAny = GenericBuiltinTest<JSAny>;
214

215 216 217 218 219
  check(fptr1(0) == Null);
  check(fptr1(1) == Null);
  check(fptr2(Undefined) == Undefined);
  check(fptr2(Undefined) == Undefined);
}
220

221 222 223 224 225
type ObjectToObject = builtin(Context, JSAny) => JSAny;
@export
macro TestTypeAlias(x: ObjectToObject): BuiltinPtr {
  return x;
}
226

227 228 229 230
@export
macro TestUnsafeCast(implicit context: Context)(n: Number): Boolean {
  if (TaggedIsSmi(n)) {
    const m: Smi = UnsafeCast<Smi>(n);
231

232 233
    check(TestHelperPlus1(m) == 11);
    return True;
234
  }
235 236
  return False;
}
237

238 239 240 241 242
@export
macro TestHexLiteral() {
  check(Convert<intptr>(0xffff) + 1 == 0x10000);
  check(Convert<intptr>(-0xffff) == -65535);
}
243

244 245 246 247 248
@export
macro TestLargeIntegerLiterals(implicit c: Context)() {
  let _x: int32 = 0x40000000;
  let _y: int32 = 0x7fffffff;
}
249

250 251 252 253 254 255 256
@export
macro TestMultilineAssert() {
  const someVeryLongVariableNameThatWillCauseLineBreaks: Smi = 5;
  check(
      someVeryLongVariableNameThatWillCauseLineBreaks > 0 &&
      someVeryLongVariableNameThatWillCauseLineBreaks < 10);
}
257

258 259 260 261
@export
macro TestNewlineInString() {
  Print('Hello, World!\n');
}
262

263 264 265
const kConstexprConst: constexpr int31 = 5;
const kIntptrConst: intptr = 4;
const kSmiConst: Smi = 3;
266

267 268 269 270 271 272
@export
macro TestModuleConstBindings() {
  check(kConstexprConst == Int32Constant(5));
  check(kIntptrConst == 4);
  check(kSmiConst == 3);
}
273

274 275 276 277 278 279 280
@export
macro TestLocalConstBindings() {
  const x: constexpr int31 = 3;
  const xSmi: Smi = x;
  {
    const x: Smi = x + FromConstexpr<Smi>(1);
    check(x == xSmi + 1);
281
    const xSmi: Smi = x;
282
    check(x == xSmi);
283
    check(x == 4);
284
  }
285 286 287
  check(xSmi == 3);
  check(x == xSmi);
}
288

289 290 291 292 293
struct TestStructA {
  indexes: FixedArray;
  i: Smi;
  k: Number;
}
294

295 296 297 298
struct TestStructB {
  x: TestStructA;
  y: Smi;
}
299

300 301 302 303
@export
macro TestStruct1(i: TestStructA): Smi {
  return i.i;
}
304

305 306 307 308 309 310 311 312
@export
macro TestStruct2(implicit context: Context)(): TestStructA {
  return TestStructA{
    indexes: UnsafeCast<FixedArray>(kEmptyFixedArray),
    i: 27,
    k: 31
  };
}
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
@export
macro TestStruct3(implicit context: Context)(): TestStructA {
  let a: TestStructA =
  TestStructA{indexes: UnsafeCast<FixedArray>(kEmptyFixedArray), i: 13, k: 5};
  let _b: TestStructA = a;
  const c: TestStructA = TestStruct2();
  a.i = TestStruct1(c);
  a.k = a.i;
  let d: TestStructB;
  d.x = a;
  d = TestStructB{x: a, y: 7};
  let _e: TestStructA = d.x;
  let f: Smi = TestStructA{
    indexes: UnsafeCast<FixedArray>(kEmptyFixedArray),
    i: 27,
    k: 31
  }.i;
  f = TestStruct2().i;
  return a;
}
334

335 336 337 338
struct TestStructC {
  x: TestStructA;
  y: TestStructA;
}
339

340 341 342 343
@export
macro TestStruct4(implicit context: Context)(): TestStructC {
  return TestStructC{x: TestStruct2(), y: TestStruct2()};
}
344

345 346 347 348 349 350 351 352 353 354
macro TestStructInLabel(implicit context: Context)(): never labels
Foo(TestStructA) {
  goto Foo(TestStruct2());
}
@export  // Silence unused warning.
macro CallTestStructInLabel(implicit context: Context)() {
  try {
    TestStructInLabel() otherwise Foo;
  } label Foo(_s: TestStructA) {}
}
355

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
// This macro tests different versions of the for-loop where some parts
// are (not) present.
@export
macro TestForLoop() {
  let sum: Smi = 0;
  for (let i: Smi = 0; i < 5; ++i) sum += i;
  check(sum == 10);

  sum = 0;
  let j: Smi = 0;
  for (; j < 5; ++j) sum += j;
  check(sum == 10);

  sum = 0;
  j = 0;
  for (; j < 5;) sum += j++;
  check(sum == 10);

  // Check that break works. No test expression.
  sum = 0;
  for (let i: Smi = 0;; ++i) {
    if (i == 5) break;
    sum += i;
  }
  check(sum == 10);

  sum = 0;
  j = 0;
  for (;;) {
    if (j == 5) break;
    sum += j;
    j++;
  }
  check(sum == 10);

  // The following tests are the same as above, but use continue to skip
  // index 3.
  sum = 0;
  for (let i: Smi = 0; i < 5; ++i) {
    if (i == 3) continue;
    sum += i;
  }
  check(sum == 7);

  sum = 0;
  j = 0;
  for (; j < 5; ++j) {
    if (j == 3) continue;
    sum += j;
  }
  check(sum == 7);

  sum = 0;
  j = 0;
  for (; j < 5;) {
    if (j == 3) {
412
      j++;
413
      continue;
414
    }
415 416 417 418
    sum += j;
    j++;
  }
  check(sum == 7);
419

420 421 422 423 424 425 426
  sum = 0;
  for (let i: Smi = 0;; ++i) {
    if (i == 3) continue;
    if (i == 5) break;
    sum += i;
  }
  check(sum == 7);
427

428 429 430 431
  sum = 0;
  j = 0;
  for (;;) {
    if (j == 3) {
432
      j++;
433
      continue;
434
    }
435

436 437 438 439 440
    if (j == 5) break;
    sum += j;
    j++;
  }
  check(sum == 7);
441

442 443 444 445
  j = 0;
  try {
    for (;;) {
      if (++j == 10) goto Exit;
446
    }
447 448
  } label Exit {
    check(j == 10);
449
  }
450

451 452 453
  // Test if we can handle uninitialized values on the stack.
  let _i: Smi;
  for (let j: Smi = 0; j < 10; ++j) {
454
  }
455
}
456

457 458 459 460 461 462 463 464 465 466 467 468
@export
macro TestSubtyping(x: Smi) {
  const _foo: JSAny = x;
}

macro IncrementIfSmi<A: type>(x: A): A {
  typeswitch (x) {
    case (x: Smi): {
      return x + 1;
    }
    case (o: A): {
      return o;
469 470
    }
  }
471
}
472

473 474 475 476 477 478 479
type NumberOrFixedArray = Number|FixedArray;
macro TypeswitchExample(implicit context: Context)(x: NumberOrFixedArray):
    int32 {
  let result: int32 = 0;
  typeswitch (IncrementIfSmi(x)) {
    case (_x: FixedArray): {
      result = result + 1;
480
    }
481 482
    case (Number): {
      result = result + 2;
483 484 485
    }
  }

486
  result = result * 10;
487

488 489 490 491 492 493 494 495 496
  typeswitch (IncrementIfSmi(x)) {
    case (x: Smi): {
      result = result + Convert<int32>(x);
    }
    case (a: FixedArray): {
      result = result + Convert<int32>(a.length);
    }
    case (_x: HeapNumber): {
      result = result + 7;
497 498 499
    }
  }

500 501
  return result;
}
502

503 504 505 506 507 508 509
@export
macro TestTypeswitch(implicit context: Context)() {
  check(TypeswitchExample(FromConstexpr<Smi>(5)) == 26);
  const a: FixedArray = AllocateZeroedFixedArray(3);
  check(TypeswitchExample(a) == 13);
  check(TypeswitchExample(FromConstexpr<Number>(0.5)) == 27);
}
510

511 512 513 514 515 516 517 518 519 520 521
@export
macro TestTypeswitchAsanLsanFailure(implicit context: Context)(obj: Object) {
  typeswitch (obj) {
    case (_o: Smi): {
    }
    case (_o: JSTypedArray): {
    }
    case (_o: JSReceiver): {
    }
    case (_o: HeapObject): {
    }
522
  }
523
}
524

525 526 527 528 529 530
macro ExampleGenericOverload<A: type>(o: Object): A {
  return o;
}
macro ExampleGenericOverload<A: type>(o: Smi): A {
  return o + 1;
}
531

532 533 534 535 536 537 538
@export
macro TestGenericOverload(implicit context: Context)() {
  const xSmi: Smi = 5;
  const xObject: Object = xSmi;
  check(ExampleGenericOverload<Smi>(xSmi) == 6);
  check(UnsafeCast<Smi>(ExampleGenericOverload<Object>(xObject)) == 5);
}
539

540 541 542 543 544 545 546 547 548
@export
macro TestEquality(implicit context: Context)() {
  const notEqual: bool =
      AllocateHeapNumberWithValue(0.5) != AllocateHeapNumberWithValue(0.5);
  check(!notEqual);
  const equal: bool =
      AllocateHeapNumberWithValue(0.5) == AllocateHeapNumberWithValue(0.5);
  check(equal);
}
549

550 551 552 553
@export
macro TestOrAnd(x: bool, y: bool, z: bool): bool {
  return x || y && z ? true : false;
}
554

555 556 557 558
@export
macro TestAndOr(x: bool, y: bool, z: bool): bool {
  return x && y || z ? true : false;
}
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
@export
macro TestLogicalOperators() {
  check(TestAndOr(true, true, true));
  check(TestAndOr(true, true, false));
  check(TestAndOr(true, false, true));
  check(!TestAndOr(true, false, false));
  check(TestAndOr(false, true, true));
  check(!TestAndOr(false, true, false));
  check(TestAndOr(false, false, true));
  check(!TestAndOr(false, false, false));
  check(TestOrAnd(true, true, true));
  check(TestOrAnd(true, true, false));
  check(TestOrAnd(true, false, true));
  check(TestOrAnd(true, false, false));
  check(TestOrAnd(false, true, true));
  check(!TestOrAnd(false, true, false));
  check(!TestOrAnd(false, false, true));
  check(!TestOrAnd(false, false, false));
}
579

580 581 582 583 584
@export
macro TestCall(i: Smi): Smi labels A {
  if (i < 5) return i;
  goto A;
}
585

586 587 588 589 590 591 592 593
@export
macro TestOtherwiseWithCode1() {
  let v: Smi = 0;
  let s: Smi = 1;
  try {
    TestCall(10) otherwise goto B(++s);
  } label B(v1: Smi) {
    v = v1;
594
  }
595 596
  assert(v == 2);
}
597

598 599 600 601 602 603
@export
macro TestOtherwiseWithCode2() {
  let s: Smi = 0;
  for (let i: Smi = 0; i < 10; ++i) {
    TestCall(i) otherwise break;
    ++s;
604
  }
605 606
  assert(s == 5);
}
607

608 609 610 611 612
@export
macro TestOtherwiseWithCode3() {
  let s: Smi = 0;
  for (let i: Smi = 0; i < 10; ++i) {
    s += TestCall(i) otherwise break;
613
  }
614 615
  assert(s == 10);
}
616

617 618 619 620 621 622 623 624
@export
macro TestForwardLabel() {
  try {
    goto A;
  } label A {
    goto B(5);
  } label B(b: Smi) {
    assert(b == 5);
625
  }
626
}
627

628 629 630 631 632
@export
macro TestQualifiedAccess(implicit context: Context)() {
  const s: Smi = 0;
  check(!Is<JSArray>(s));
}
633

634 635 636 637
@export
macro TestCatch1(implicit context: Context)(): Smi {
  let r: Smi = 0;
  try {
638
    ThrowTypeError(MessageTemplate::kInvalidArrayLength);
639 640 641
  } catch (_e) {
    r = 1;
    return r;
642
  }
643
}
644

645 646 647 648 649 650 651 652 653 654 655 656 657
@export
macro TestCatch2Wrapper(implicit context: Context)(): never {
  ThrowTypeError(MessageTemplate::kInvalidArrayLength);
}

@export
macro TestCatch2(implicit context: Context)(): Smi {
  let r: Smi = 0;
  try {
    TestCatch2Wrapper();
  } catch (_e) {
    r = 2;
    return r;
658
  }
659
}
660

661 662 663 664 665
@export
macro TestCatch3WrapperWithLabel(implicit context: Context)():
    never labels _Abort {
  ThrowTypeError(MessageTemplate::kInvalidArrayLength);
}
666

667 668 669 670 671 672 673 674 675 676 677 678
@export
macro TestCatch3(implicit context: Context)(): Smi {
  let r: Smi = 0;
  try {
    TestCatch3WrapperWithLabel() otherwise Abort;
  } catch (_e) {
    r = 2;
    return r;
  } label Abort {
    return -1;
  }
}
679

680 681 682 683 684 685 686 687 688 689
// This test doesn't actually test the functionality of iterators,
// it's only purpose is to make sure tha the CSA macros in the
// IteratorBuiltinsAssembler match the signatures provided in
// iterator.tq.
@export
transitioning macro TestIterator(implicit context: Context)(
    o: JSReceiver, map: Map) {
  try {
    const t1: JSAny = iterator::GetIteratorMethod(o);
    const t2: iterator::IteratorRecord = iterator::GetIterator(o);
690

691 692
    const _t3: JSAny = iterator::IteratorStep(t2) otherwise Fail;
    const _t4: JSAny = iterator::IteratorStep(t2, map) otherwise Fail;
693

694 695
    const _t5: JSAny = iterator::IteratorValue(o);
    const _t6: JSAny = iterator::IteratorValue(o, map);
696

697
    const _t7: JSArray = iterator::IterableToList(t1, t1);
698

699 700 701
    iterator::IteratorCloseOnException(t2);
  } label Fail {}
}
702

703 704 705 706 707 708 709 710 711 712 713 714
@export
macro TestFrame1(implicit context: Context)() {
  const f: Frame = LoadFramePointer();
  const frameType: FrameType =
      Cast<FrameType>(f.context_or_frame_type) otherwise unreachable;
  assert(frameType == STUB_FRAME);
  assert(f.caller == LoadParentFramePointer());
  typeswitch (f) {
    case (_f: StandardFrame): {
      unreachable;
    }
    case (_f: StubFrame): {
715 716
    }
  }
717
}
718

719 720 721 722 723 724
@export
macro TestNew(implicit context: Context)() {
  const f: JSArray = NewJSArray();
  check(f.IsEmpty());
  f.length = 0;
}
725

726 727 728
struct TestInner {
  macro SetX(newValue: int32) {
    this.x = newValue;
729
  }
730 731
  macro GetX(): int32 {
    return this.x;
732
  }
733 734 735
  x: int32;
  y: int32;
}
736

737 738 739 740 741
struct TestOuter {
  a: int32;
  b: TestInner;
  c: int32;
}
742

743 744 745 746 747 748 749 750 751 752 753 754 755 756
@export
macro TestStructConstructor(implicit context: Context)() {
  // Test default constructor
  let a: TestOuter = TestOuter{a: 5, b: TestInner{x: 6, y: 7}, c: 8};
  check(a.a == 5);
  check(a.b.x == 6);
  check(a.b.y == 7);
  check(a.c == 8);
  a.b.x = 1;
  check(a.b.x == 1);
  a.b.SetX(2);
  check(a.b.x == 2);
  check(a.b.GetX() == 2);
}
757

758 759 760 761 762
class InternalClass extends HeapObject {
  macro Flip() labels NotASmi {
    const tmp = Cast<Smi>(this.b) otherwise NotASmi;
    this.b = this.a;
    this.a = tmp;
763
  }
764 765 766
  a: Smi;
  b: Number;
}
767

768 769 770
macro NewInternalClass(x: Smi): InternalClass {
  return new InternalClass{a: x, b: x + 1};
}
771

772 773 774 775 776 777 778
@export
macro TestInternalClass(implicit context: Context)() {
  const o = NewInternalClass(5);
  o.Flip() otherwise unreachable;
  check(o.a == 6);
  check(o.b == 5);
}
779

780 781 782
struct StructWithConst {
  macro TestMethod1(): int32 {
    return this.b;
783
  }
784 785
  macro TestMethod2(): Object {
    return this.a;
786
  }
787 788 789
  a: Object;
  const b: int32;
}
790

791 792 793 794 795 796
@export
macro TestConstInStructs() {
  const x = StructWithConst{a: Null, b: 1};
  let y = StructWithConst{a: Null, b: 1};
  y.a = Undefined;
  const _copy = x;
797

798 799 800
  check(x.TestMethod1() == 1);
  check(x.TestMethod2() == Null);
}
801

802 803 804 805 806 807 808
@export
macro TestParentFrameArguments(implicit context: Context)() {
  const parentFrame = LoadParentFramePointer();
  const castFrame = Cast<StandardFrame>(parentFrame) otherwise unreachable;
  const arguments = GetFrameArguments(castFrame, 1);
  ArgumentsIterator{arguments, current: 0};
}
809

810 811 812 813
struct TestIterator {
  macro Next(): Object labels NoMore {
    if (this.count-- == 0) goto NoMore;
    return TheHole;
814
  }
815 816
  count: Smi;
}
817

818 819 820 821 822
@export
macro TestNewFixedArrayFromSpread(implicit context: Context)(): Object {
  let i = TestIterator{count: 5};
  return new FixedArray{map: kFixedArrayMap, length: 5, objects: ...i};
}
823

824 825
class SmiPair extends HeapObject {
  macro GetA():&Smi {
826
    return &this.a;
827 828 829 830
  }
  a: Smi;
  b: Smi;
}
831

832
macro Swap<T: type>(a:&T, b:&T) {
833 834 835
  const tmp = *a;
  *a = *b;
  *b = tmp;
836
}
837

838 839 840
@export
macro TestReferences() {
  const array = new SmiPair{a: 7, b: 2};
841 842 843 844
  const ref:&Smi = &array.a;
  *ref = 3 + *ref;
  -- *ref;
  Swap(&array.b, array.GetA());
845 846 847
  check(array.a == 2);
  check(array.b == 9);
}
848

849 850 851 852 853
@export
macro TestSlices() {
  const it = TestIterator{count: 3};
  const a = new FixedArray{map: kFixedArrayMap, length: 3, objects: ...it};
  check(a.length == 3);
854

855 856
  const oneTwoThree = Convert<Smi>(123);
  a.objects[0] = oneTwoThree;
857 858
  const firstRef:&Object = &a.objects[0];
  check(TaggedEqual(*firstRef, oneTwoThree));
859

860
  const slice: MutableSlice<Object> = &a.objects;
861
  const firstRefAgain:&Object = slice.TryAtIndex(0) otherwise unreachable;
862
  check(TaggedEqual(*firstRefAgain, oneTwoThree));
863

864
  const threeTwoOne = Convert<Smi>(321);
865
  *firstRefAgain = threeTwoOne;
866
  check(TaggedEqual(a.objects[0], threeTwoOne));
867

868 869 870
  // *slice;             // error, not allowed
  // a.objects;          // error, not allowed
  // a.objects = slice;  // error, not allowed
871

872
  // TODO(gsps): Currently errors, but should be allowed:
873
  // const _sameSlice: MutableSlice<Object> = &(*slice);
874 875
  // (*slice)[0] : Smi
}
876

877 878 879 880 881 882
@export
macro TestSliceEnumeration(implicit context: Context)(): Undefined {
  const fixedArray: FixedArray = AllocateZeroedFixedArray(3);
  for (let i: intptr = 0; i < 3; i++) {
    check(UnsafeCast<Smi>(fixedArray.objects[i]) == 0);
    fixedArray.objects[i] = Convert<Smi>(i) + 3;
883 884
  }

885
  let slice = &fixedArray.objects;
886 887
  for (let i: intptr = 0; i < slice.length; i++) {
    let ref = slice.TryAtIndex(i) otherwise unreachable;
888
    const value = UnsafeCast<Smi>(*ref);
889
    check(value == Convert<Smi>(i) + 3);
890
    *ref = value + 4;
891 892
  }

893 894 895 896 897 898
  let it = slice.Iterator();
  let count: Smi = 0;
  while (true) {
    const value = UnsafeCast<Smi>(it.Next() otherwise break);
    check(value == count + 7);
    count++;
899
  }
900 901
  check(count == 3);
  check(it.Empty());
902

903 904
  return Undefined;
}
905

906 907
@export
macro TestStaticAssert() {
908
  static_assert(1 + 2 == 3);
909 910 911 912 913 914 915 916 917 918 919 920 921 922

  static_assert(Convert<uintptr>(5) < Convert<uintptr>(6));
  static_assert(!(Convert<uintptr>(5) < Convert<uintptr>(5)));
  static_assert(!(Convert<uintptr>(6) < Convert<uintptr>(5)));
  static_assert(Convert<uintptr>(5) <= Convert<uintptr>(5));
  static_assert(Convert<uintptr>(5) <= Convert<uintptr>(6));
  static_assert(!(Convert<uintptr>(6) <= Convert<uintptr>(5)));

  static_assert(Convert<intptr>(-6) < Convert<intptr>(-5));
  static_assert(!(Convert<intptr>(-5) < Convert<intptr>(-5)));
  static_assert(!(Convert<intptr>(-5) < Convert<intptr>(-6)));
  static_assert(Convert<intptr>(-5) <= Convert<intptr>(-5));
  static_assert(Convert<intptr>(-6) <= Convert<intptr>(-5));
  static_assert(!(Convert<intptr>(-5) <= Convert<intptr>(-6)));
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
}

class SmiBox extends HeapObject {
  value: Smi;
  unrelated: Smi;
}

builtin NewSmiBox(implicit context: Context)(value: Smi): SmiBox {
  return new SmiBox{value, unrelated: 0};
}

@export
macro TestLoadEliminationFixed(implicit context: Context)() {
  const box = NewSmiBox(123);
  const v1 = box.value;
  box.unrelated = 999;
  const v2 = (box.unrelated == 0) ? box.value : box.value;
940
  static_assert(TaggedEqual(v1, v2));
941 942 943 944

  box.value = 11;
  const v3 = box.value;
  const eleven: Smi = 11;
945
  static_assert(TaggedEqual(v3, eleven));
946 947 948 949 950 951 952 953 954 955
}

@export
macro TestLoadEliminationVariable(implicit context: Context)() {
  const a = UnsafeCast<FixedArray>(kEmptyFixedArray);
  const box = NewSmiBox(1);
  const v1 = a.objects[box.value];
  const u1 = a.objects[box.value + 2];
  const v2 = a.objects[box.value];
  const u2 = a.objects[box.value + 2];
956 957
  static_assert(TaggedEqual(v1, v2));
  static_assert(TaggedEqual(u1, u2));
958
}
959

960 961 962 963 964
@export
macro TestRedundantArrayElementCheck(implicit context: Context)(): Smi {
  const a = kEmptyFixedArray;
  for (let i: Smi = 0; i < a.length; i++) {
    if (a.objects[i] == TheHole) {
965
      if (a.objects[i] == TheHole) {
966 967
        return -1;
      } else {
968
        static_assert(false);
969 970 971
      }
    }
  }
972 973
  return 1;
}
974

975 976 977 978 979 980 981 982 983 984
@export
macro TestRedundantSmiCheck(implicit context: Context)(): Smi {
  const a = kEmptyFixedArray;
  const x = a.objects[1];
  typeswitch (x) {
    case (Smi): {
      Cast<Smi>(x) otherwise VerifiedUnreachable();
      return -1;
    }
    case (Object): {
985 986
    }
  }
987 988
  return 1;
}
989

990 991 992
struct SBox<T: type> {
  value: T;
}
993

994 995 996 997 998 999 1000 1001 1002 1003
@export
macro TestGenericStruct1(): intptr {
  const i: intptr = 123;
  let box = SBox{value: i};
  let boxbox: SBox<SBox<intptr>> = SBox{value: box};
  check(box.value == 123);
  boxbox.value.value *= 2;
  check(boxbox.value.value == 246);
  return boxbox.value.value;
}
1004

1005 1006 1007 1008
struct TestTuple<T1: type, T2: type> {
  const fst: T1;
  const snd: T2;
}
1009

1010 1011 1012 1013
macro TupleSwap<T1: type, T2: type>(tuple: TestTuple<T1, T2>):
    TestTuple<T2, T1> {
  return TestTuple{fst: tuple.snd, snd: tuple.fst};
}
1014

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
@export
macro TestGenericStruct2():
    TestTuple<TestTuple<intptr, Smi>, TestTuple<Smi, intptr>> {
  const intptrAndSmi = TestTuple<intptr, Smi>{fst: 1, snd: 2};
  const smiAndIntptr = TupleSwap(intptrAndSmi);
  check(intptrAndSmi.fst == smiAndIntptr.snd);
  check(intptrAndSmi.snd == smiAndIntptr.fst);
  const tupleTuple =
      TestTuple<TestTuple<intptr, Smi>>{fst: intptrAndSmi, snd: smiAndIntptr};
  return tupleTuple;
}
1026

1027 1028 1029 1030 1031 1032 1033
macro BranchAndWriteResult(x: Smi, box: SmiBox): bool {
  if (x > 5 || x < 0) {
    box.value = 1;
    return true;
  } else {
    box.value = 2;
    return false;
1034
  }
1035
}
1036

1037 1038 1039 1040 1041 1042
@export
macro TestBranchOnBoolOptimization(implicit context: Context)(input: Smi) {
  const box = NewSmiBox(1);
  // If the two branches get combined into one, we should be able to determine
  // the value of {box} statically.
  if (BranchAndWriteResult(input, box)) {
1043
    static_assert(box.value == 1);
1044
  } else {
1045
    static_assert(box.value == 2);
1046
  }
1047
}
1048

1049 1050 1051 1052 1053 1054
bitfield struct TestBitFieldStruct extends uint8 {
  a: bool: 1 bit;
  b: uint16: 3 bit;
  c: uint32: 3 bit;
  d: bool: 1 bit;
}
1055

1056 1057 1058 1059 1060 1061 1062 1063 1064
@export
macro TestBitFieldLoad(
    val: TestBitFieldStruct, expectedA: bool, expectedB: uint16,
    expectedC: uint32, expectedD: bool) {
  check(val.a == expectedA);
  check(val.b == expectedB);
  check(val.c == expectedC);
  check(val.d == expectedD);
}
1065

1066 1067 1068 1069 1070 1071 1072
@export
macro TestBitFieldStore(val: TestBitFieldStruct) {
  let val: TestBitFieldStruct = val;  // Get a mutable local copy.
  const a: bool = val.a;
  const b: uint16 = val.b;
  let c: uint32 = val.c;
  const d: bool = val.d;
1073

1074 1075
  val.a = !a;
  TestBitFieldLoad(val, !a, b, c, d);
1076

1077 1078 1079
  c = Unsigned(7 - Signed(val.c));
  val.c = c;
  TestBitFieldLoad(val, !a, b, c, d);
1080

1081 1082 1083
  val.d = val.b == val.c;
  TestBitFieldLoad(val, !a, b, c, b == c);
}
1084

1085 1086 1087 1088 1089
@export
macro TestBitFieldInit(a: bool, b: uint16, c: uint32, d: bool) {
  const val: TestBitFieldStruct = TestBitFieldStruct{a: a, b: b, c: c, d: d};
  TestBitFieldLoad(val, a, b, c, d);
}
1090

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
// Some other bitfield structs, to verify getting uintptr values out of word32
// structs and vice versa.
bitfield struct TestBitFieldStruct2 extends uint32 {
  a: uintptr: 5 bit;
  b: uintptr: 6 bit;
}
bitfield struct TestBitFieldStruct3 extends uintptr {
  c: bool: 1 bit;
  d: uint32: 9 bit;
  e: uintptr: 17 bit;
}
1102

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
@export
macro TestBitFieldUintptrOps(
    val2: TestBitFieldStruct2, val3: TestBitFieldStruct3) {
  let val2: TestBitFieldStruct2 = val2;  // Get a mutable local copy.
  let val3: TestBitFieldStruct3 = val3;  // Get a mutable local copy.

  // Caller is expected to provide these exact values, so we can verify
  // reading values before starting to write anything.
  check(val2.a == 3);
  check(val2.b == 61);
  check(val3.c);
  check(val3.d == 500);
  check(val3.e == 0x1cc);

  val2.b = 16;
  check(val2.a == 3);
  check(val2.b == 16);

  val2.b++;
  check(val2.a == 3);
  check(val2.b == 17);

  val3.d = 99;
  val3.e = 1234;
  check(val3.c);
  check(val3.d == 99);
  check(val3.e == 1234);
}
1131

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
bitfield struct TestBitFieldStruct4 extends uint31 {
  a: bool: 1 bit;
  b: int32: 3 bit;
  c: bool: 1 bit;
}

bitfield struct TestBitFieldStruct5 extends uint31 {
  b: int32: 19 bit;
  a: bool: 1 bit;
  c: bool: 1 bit;
}

@export
macro TestBitFieldMultipleFlags(a: bool, b: int32, c: bool) {
  const f = TestBitFieldStruct4{a: a, b: b, c: c};
  let simpleExpression = f.a & f.b == 3 & !f.c;
  let expectedReduction = (Signed(f) & 0x1f) == Convert<int32>(1 | 3 << 1);
1149
  static_assert(simpleExpression == expectedReduction);
1150 1151
  simpleExpression = !f.a & f.b == 4 & f.c;
  expectedReduction = (Signed(f) & 0x1f) == Convert<int32>(4 << 1 | 1 << 4);
1152
  static_assert(simpleExpression == expectedReduction);
1153 1154
  simpleExpression = f.b == 0 & f.c;
  expectedReduction = (Signed(f) & 0x1e) == Convert<int32>(1 << 4);
1155
  static_assert(simpleExpression == expectedReduction);
1156 1157
  simpleExpression = f.a & f.c;
  expectedReduction = (Signed(f) & 0x11) == Convert<int32>(1 | 1 << 4);
1158
  static_assert(simpleExpression == expectedReduction);
1159 1160 1161
  const f2 = TestBitFieldStruct5{b: b, a: a, c: c};
  simpleExpression = !f2.a & f2.b == 1234 & f2.c;
  expectedReduction = (Signed(f2) & 0x1fffff) == Convert<int32>(1234 | 1 << 20);
1162
  static_assert(simpleExpression == expectedReduction);
1163 1164
  simpleExpression = !f2.a & !f2.c;
  expectedReduction = (Signed(f2) & 0x180000) == Convert<int32>(0);
1165
  static_assert(simpleExpression == expectedReduction);
1166 1167
}

1168 1169 1170 1171 1172 1173
@export
class ExportedSubClass extends ExportedSubClassBase {
  c_field: int32;
  d_field: int32;
  e_field: Smi;
}
1174

1175 1176 1177 1178 1179
@export
class ExportedSubClassBase extends HeapObject {
  a: HeapObject;
  b: HeapObject;
}
1180

1181 1182 1183
@abstract
class AbstractInternalClass extends HeapObject {
}
1184

1185
class AbstractInternalClassSubclass1 extends AbstractInternalClass {}
1186

1187
class AbstractInternalClassSubclass2 extends AbstractInternalClass {}
1188

1189 1190 1191 1192 1193
class InternalClassWithSmiElements extends FixedArrayBase {
  data: Smi;
  object: Oddball;
  entries[length]: Smi;
}
1194

1195 1196 1197 1198
struct InternalClassStructElement {
  a: Smi;
  b: Smi;
}
1199

1200 1201 1202 1203 1204 1205 1206 1207 1208
class InternalClassWithStructElements extends HeapObject {
  dummy1: int32;
  dummy2: int32;
  const count: Smi;
  data: Smi;
  object: Object;
  entries[count]: Smi;
  more_entries[count]: InternalClassStructElement;
}
1209

1210 1211 1212
struct SmiGeneratorIterator {
  macro Next(): Smi labels _NoMore {
    return this.value++;
1213
  }
1214 1215
  value: Smi;
}
1216

1217 1218 1219
struct InternalClassStructElementGeneratorIterator {
  macro Next(): InternalClassStructElement labels _NoMore {
    return InternalClassStructElement{a: this.value++, b: this.value++};
1220
  }
1221 1222
  value: Smi;
}
1223

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
@export
macro TestFullyGeneratedClassWithElements() {
  // Test creation, initialization and access of a fully generated class with
  // simple (Smi) elements
  const length: Smi = Convert<Smi>(3);
  const object1 = new InternalClassWithSmiElements{
    length,
    data: 0,
    object: Undefined,
    entries: ...SmiGeneratorIterator {
      value: 11
    }
  };
  assert(object1.length == 3);
  assert(object1.data == 0);
  assert(object1.object == Undefined);
  assert(object1.entries[0] == 11);
  assert(object1.entries[1] == 12);
  assert(object1.entries[2] == 13);

  // Test creation, initialization and access of a fully generated class
  // with elements that are a struct.
  const object2 = new InternalClassWithStructElements{
    dummy1: 44,
    dummy2: 45,
    count: length,
    data: 55,
    object: Undefined,
    entries: ...SmiGeneratorIterator{value: 3},
    more_entries: ...InternalClassStructElementGeneratorIterator {
      value: 1
    }
  };

  assert(object2.dummy1 == 44);
  assert(object2.dummy2 == 45);
  assert(object2.count == 3);
  assert(object2.data == 55);
  assert(object2.object == Undefined);
  assert(object2.entries[0] == 3);
  assert(object2.entries[1] == 4);
  assert(object2.entries[2] == 5);
  assert(object2.more_entries[0].a == 1);
  assert(object2.more_entries[0].b == 2);
  assert(object2.more_entries[1].a == 3);
  assert(object2.more_entries[1].b == 4);
  assert(object2.more_entries[2].a == 5);
  assert(object2.more_entries[2].b == 6);
}
1273

1274 1275 1276 1277 1278
@export
macro TestFullyGeneratedClassFromCpp(): ExportedSubClass {
  return new
  ExportedSubClass{a: Null, b: Null, c_field: 7, d_field: 8, e_field: 9};
}
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

@export
class ExportedSubClass2 extends ExportedSubClassBase {
  x_field: int32;
  y_field: int32;
  z_field: Smi;
}

@export
macro TestGeneratedCastOperators(implicit context: Context)() {
  const a = new
  ExportedSubClass{a: Null, b: Null, c_field: 3, d_field: 4, e_field: 5};
  const b = new ExportedSubClassBase{a: Undefined, b: Null};
  const c = new
  ExportedSubClass2{a: Null, b: Null, x_field: 3, y_field: 4, z_field: 5};
  const aO: Object = a;
  const bO: Object = b;
  const cO: Object = c;
  assert(Is<ExportedSubClassBase>(aO));
  assert(Is<ExportedSubClass>(aO));
  assert(!Is<ExportedSubClass2>(aO));
  assert(Is<ExportedSubClassBase>(bO));
  assert(!Is<ExportedSubClass>(bO));
  assert(Is<ExportedSubClassBase>(cO));
  assert(!Is<ExportedSubClass>(cO));
  assert(Is<ExportedSubClass2>(cO));

1306 1307
  const jsf: JSFunction =
      *NativeContextSlot(ContextSlot::REGEXP_FUNCTION_INDEX);
1308 1309 1310 1311 1312 1313 1314 1315 1316
  assert(!Is<JSSloppyArgumentsObject>(jsf));

  const parameterValues = NewFixedArray(0, ConstantIterator(TheHole));
  const elements = NewSloppyArgumentsElements(
      0, context, parameterValues, ConstantIterator(TheHole));
  const fastArgs = arguments::NewJSFastAliasedArgumentsObject(
      elements, Convert<Smi>(0), jsf);
  assert(Is<JSArgumentsObject>(fastArgs));
}
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

extern runtime InYoungGeneration(implicit context: Context)(HeapObject):
    Boolean;

@export
macro TestNewPretenured(implicit context: Context)() {
  const obj = new (Pretenured) ExportedSubClassBase{a: Undefined, b: Null};
  assert(Is<ExportedSubClassBase>(obj));
  assert(InYoungGeneration(obj) == False);
}
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

@export
macro TestWord8Phi() {
  for (let i: intptr = -5; i < 5; ++i) {
    let x: int8;
    if (i == -1) {
      x = -1;
    } else {
      x = Convert<int8>(i);
    }
    check(x == Convert<int8>(i));
  }
}
1340 1341 1342 1343 1344 1345 1346

@export
macro TestOffHeapSlice(ptr: RawPtr<char8>, length: intptr) {
  const string = UnsafeCast<SeqOneByteString>(Convert<String>('Hello World!'));

  check(*torque_internal::unsafe::NewOffHeapReference(ptr) == string.chars[0]);

1347
  let offHeapSlice = torque_internal::unsafe::NewOffHeapConstSlice(ptr, length);
1348 1349 1350 1351 1352
  let onHeapSlice = &string.chars;
  for (let i: intptr = 0; i < onHeapSlice.length; ++i) {
    check(*onHeapSlice.AtIndex(i) == *offHeapSlice.AtIndex(i));
  }
}
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

struct TwoValues {
  a: Smi;
  b: Map;
}

builtin ReturnTwoValues(implicit context: Context)(
    value: Smi, obj: HeapObject): TwoValues {
  return TwoValues{a: value + 1, b: obj.map};
}

@export
macro TestCallMultiReturnBuiltin(implicit context: Context)() {
  const result = ReturnTwoValues(444, FromConstexpr<String>('hi'));
  check(result.a == 445);
  check(result.b == FromConstexpr<String>('hi').map);
}
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

@export
macro TestRunLazyTwice(lazySmi: Lazy<Smi>): Smi {
  const firstResult = RunLazy(lazySmi);
  const secondResult = RunLazy(lazySmi);
  return firstResult + secondResult;
}

macro GetLazySmi(): Smi {
  return 3;
}

macro AddTwoSmiValues(a: Smi, b: Smi): Smi {
  return a + b;
}

macro AddSmiAndConstexprValues(a: Smi, b: constexpr int31): Smi {
  return a + b;
}

@export
macro TestCreateLazyNodeFromTorque() {
  const lazy = %MakeLazy<Smi>('GetLazySmi');
  const result = TestRunLazyTwice(lazy);
  check(result == 6);

  // The macro can also be referred to using namespace qualifications.
  const lazy2 = %MakeLazy<Smi>('test::GetLazySmi');
  const result2 = TestRunLazyTwice(lazy2);
  check(result2 == 6);

  // We can save params to the macro. The most common usage is likely a
  // single-arg macro that just returns the arg, but we can use any number of
  // params.
  const lazy3 = %MakeLazy<Smi>('AddTwoSmiValues', 5, 6);
  const result3 = TestRunLazyTwice(lazy3);
  check(result3 == 22);

  // It's okay if some of the params are constexpr and some aren't.
  const lazy4 = %MakeLazy<Smi>('AddSmiAndConstexprValues', 7, 8);
  const result4 = TestRunLazyTwice(lazy4);
  check(result4 == 30);
}
1413
}