test-torque.tq 33.2 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
@export
43
macro TestConstexpr1(): void {
44 45 46
  check(FromConstexpr<bool>(
      IsFastElementsKind(ElementsKind::PACKED_SMI_ELEMENTS)));
}
47

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

55
@export
56
macro TestConstexprReturn(): void {
57 58 59 60 61 62 63 64 65
  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
@export
106
macro TestBuiltinSpecialization(): void {
107 108 109 110 111
  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
@export
163
macro TestMacroSpecialization(): void {
164 165 166 167 168 169 170 171 172
  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
@export
macro TestVariableRedeclaration(implicit context: Context)(): Boolean {
199 200
  let _var1: int31 = FromConstexpr<bool>(42 == 0) ? FromConstexpr<int31>(0) : 1;
  let _var2: int31 = FromConstexpr<bool>(42 == 0) ? FromConstexpr<int31>(1) : 0;
201 202
  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
@export
211
macro TestFunctionPointerToGeneric(): void {
212 213
  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
@export
239
macro TestHexLiteral(): void {
240 241 242
  check(Convert<intptr>(0xffff) + 1 == 0x10000);
  check(Convert<intptr>(-0xffff) == -65535);
}
243

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

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

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

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

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

274
@export
275
macro TestLocalConstBindings(): void {
276 277 278 279 280
  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
macro TestStructInLabel(implicit context: Context)(): never labels
Foo(TestStructA) {
  goto Foo(TestStruct2());
}
@export  // Silence unused warning.
350
macro CallTestStructInLabel(implicit context: Context)(): void {
351 352 353 354
  try {
    TestStructInLabel() otherwise Foo;
  } label Foo(_s: TestStructA) {}
}
355

356 357 358
// This macro tests different versions of the for-loop where some parts
// are (not) present.
@export
359
macro TestForLoop(): void {
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
  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
@export
458
macro TestSubtyping(x: Smi): void {
459 460 461 462 463 464 465 466 467 468
  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
@export
504
macro TestTypeswitch(implicit context: Context)(): void {
505 506 507 508 509
  check(TypeswitchExample(FromConstexpr<Smi>(5)) == 26);
  const a: FixedArray = AllocateZeroedFixedArray(3);
  check(TypeswitchExample(a) == 13);
  check(TypeswitchExample(FromConstexpr<Number>(0.5)) == 27);
}
510

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

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

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

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

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

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

561
@export
562
macro TestLogicalOperators(): void {
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  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));
}
580

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

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

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

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

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

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

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

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

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

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

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

681 682 683 684 685 686
// 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)(
687
    o: JSReceiver, map: Map): void {
688 689 690
  try {
    const t1: JSAny = iterator::GetIteratorMethod(o);
    const t2: iterator::IteratorRecord = iterator::GetIterator(o);
691

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

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

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

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

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

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

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

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

744
@export
745
macro TestStructConstructor(implicit context: Context)(): void {
746 747 748 749 750 751 752 753 754 755 756 757
  // 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);
}
758

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

878 879 880 881 882 883
@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;
884 885
  }

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

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

904 905
  return Undefined;
}
906

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

  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)));
924 925 926 927 928 929 930 931 932 933 934 935
}

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

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

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

  box.value = 11;
  const v3 = box.value;
  const eleven: Smi = 11;
946
  static_assert(TaggedEqual(v3, eleven));
947 948 949
}

@export
950
macro TestLoadEliminationVariable(implicit context: Context)(): void {
951 952 953 954 955 956
  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];
957 958
  static_assert(TaggedEqual(v1, v2));
  static_assert(TaggedEqual(u1, u2));
959
}
960

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

976 977 978 979 980 981 982 983 984 985
@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): {
986 987
    }
  }
988 989
  return 1;
}
990

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

995 996 997 998 999 1000 1001 1002 1003 1004
@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;
}
1005

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

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

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
@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;
}
1027

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

1038
@export
1039 1040
macro TestBranchOnBoolOptimization(implicit context: Context)(input: Smi):
    void {
1041 1042 1043 1044
  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)) {
1045
    static_assert(box.value == 1);
1046
  } else {
1047
    static_assert(box.value == 2);
1048
  }
1049
}
1050

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

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

1068
@export
1069
macro TestBitFieldStore(val: TestBitFieldStruct): void {
1070 1071 1072 1073 1074
  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;
1075

1076 1077
  val.a = !a;
  TestBitFieldLoad(val, !a, b, c, d);
1078

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

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

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

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
// 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;
}
1104

1105 1106
@export
macro TestBitFieldUintptrOps(
1107
    val2: TestBitFieldStruct2, val3: TestBitFieldStruct3): void {
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  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);
}
1133

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
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
1147
macro TestBitFieldMultipleFlags(a: bool, b: int32, c: bool): void {
1148 1149 1150
  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);
1151
  static_assert(simpleExpression == expectedReduction);
1152 1153
  simpleExpression = !f.a & f.b == 4 & f.c;
  expectedReduction = (Signed(f) & 0x1f) == Convert<int32>(4 << 1 | 1 << 4);
1154
  static_assert(simpleExpression == expectedReduction);
1155 1156
  simpleExpression = f.b == 0 & f.c;
  expectedReduction = (Signed(f) & 0x1e) == Convert<int32>(1 << 4);
1157
  static_assert(simpleExpression == expectedReduction);
1158 1159
  simpleExpression = f.a & f.c;
  expectedReduction = (Signed(f) & 0x11) == Convert<int32>(1 | 1 << 4);
1160
  static_assert(simpleExpression == expectedReduction);
1161 1162 1163
  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);
1164
  static_assert(simpleExpression == expectedReduction);
1165 1166
  simpleExpression = !f2.a & !f2.c;
  expectedReduction = (Signed(f2) & 0x180000) == Convert<int32>(0);
1167
  static_assert(simpleExpression == expectedReduction);
1168 1169
}

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

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

1183 1184 1185
@abstract
class AbstractInternalClass extends HeapObject {
}
1186

1187
class AbstractInternalClassSubclass1 extends AbstractInternalClass {}
1188

1189
class AbstractInternalClassSubclass2 extends AbstractInternalClass {}
1190

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

1197 1198 1199 1200
struct InternalClassStructElement {
  a: Smi;
  b: Smi;
}
1201

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

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

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

1226
@export
1227
macro TestFullyGeneratedClassWithElements(): void {
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  // 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
    }
  };
1239 1240 1241 1242 1243 1244
  dcheck(object1.length == 3);
  dcheck(object1.data == 0);
  dcheck(object1.object == Undefined);
  dcheck(object1.entries[0] == 11);
  dcheck(object1.entries[1] == 12);
  dcheck(object1.entries[2] == 13);
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259

  // 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
    }
  };

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
  dcheck(object2.dummy1 == 44);
  dcheck(object2.dummy2 == 45);
  dcheck(object2.count == 3);
  dcheck(object2.data == 55);
  dcheck(object2.object == Undefined);
  dcheck(object2.entries[0] == 3);
  dcheck(object2.entries[1] == 4);
  dcheck(object2.entries[2] == 5);
  dcheck(object2.more_entries[0].a == 1);
  dcheck(object2.more_entries[0].b == 2);
  dcheck(object2.more_entries[1].a == 3);
  dcheck(object2.more_entries[1].b == 4);
  dcheck(object2.more_entries[2].a == 5);
  dcheck(object2.more_entries[2].b == 6);
1274
}
1275

1276 1277 1278 1279 1280
@export
macro TestFullyGeneratedClassFromCpp(): ExportedSubClass {
  return new
  ExportedSubClass{a: Null, b: Null, c_field: 7, d_field: 8, e_field: 9};
}
1281 1282 1283 1284 1285 1286 1287 1288 1289

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

@export
1290
macro TestGeneratedCastOperators(implicit context: Context)(): void {
1291 1292 1293 1294 1295 1296 1297 1298
  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;
1299 1300 1301 1302 1303 1304 1305 1306
  dcheck(Is<ExportedSubClassBase>(aO));
  dcheck(Is<ExportedSubClass>(aO));
  dcheck(!Is<ExportedSubClass2>(aO));
  dcheck(Is<ExportedSubClassBase>(bO));
  dcheck(!Is<ExportedSubClass>(bO));
  dcheck(Is<ExportedSubClassBase>(cO));
  dcheck(!Is<ExportedSubClass>(cO));
  dcheck(Is<ExportedSubClass2>(cO));
1307

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

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

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

@export
1324
macro TestNewPretenured(implicit context: Context)(): void {
1325
  const obj = new (Pretenured) ExportedSubClassBase{a: Undefined, b: Null};
1326 1327
  dcheck(Is<ExportedSubClassBase>(obj));
  dcheck(InYoungGeneration(obj) == False);
1328
}
1329 1330

@export
1331
macro TestWord8Phi(): void {
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
  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));
  }
}
1342 1343

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

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

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

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
1367
macro TestCallMultiReturnBuiltin(implicit context: Context)(): void {
1368 1369 1370 1371
  const result = ReturnTwoValues(444, FromConstexpr<String>('hi'));
  check(result.a == 445);
  check(result.b == FromConstexpr<String>('hi').map);
}
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392

@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
1393
macro TestCreateLazyNodeFromTorque(): void {
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  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);
}
1415
}