types.cc 33 KB
Newer Older
1 2 3
// Copyright 2014 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.
4

5
#include <iomanip>
6

7
#include "src/compiler/types.h"
8

9
#include "src/handles-inl.h"
10
#include "src/objects-inl.h"
11
#include "src/ostreams.h"
12 13 14

namespace v8 {
namespace internal {
15
namespace compiler {
16

17 18
// NOTE: If code is marked as being a "shortcut", this means that removing
// the code won't affect the semantics of the surrounding function definition.
19

20 21 22 23
// static
bool Type::IsInteger(i::Object* x) {
  return x->IsNumber() && Type::IsInteger(x->Number());
}
24

25 26
// -----------------------------------------------------------------------------
// Range-related helper functions.
27

28
bool RangeType::Limits::IsEmpty() { return this->min > this->max; }
29

30
RangeType::Limits RangeType::Limits::Intersect(Limits lhs, Limits rhs) {
31 32
  DisallowHeapAllocation no_allocation;
  Limits result(lhs);
33 34
  if (lhs.min < rhs.min) result.min = rhs.min;
  if (lhs.max > rhs.max) result.max = rhs.max;
35
  return result;
36 37
}

38
RangeType::Limits RangeType::Limits::Union(Limits lhs, Limits rhs) {
39
  DisallowHeapAllocation no_allocation;
40 41
  if (lhs.IsEmpty()) return rhs;
  if (rhs.IsEmpty()) return lhs;
42
  Limits result(lhs);
43 44
  if (lhs.min > rhs.min) result.min = rhs.min;
  if (lhs.max < rhs.max) result.max = rhs.max;
45
  return result;
46 47
}

48
bool Type::Overlap(RangeType* lhs, RangeType* rhs) {
49
  DisallowHeapAllocation no_allocation;
50 51 52
  return !RangeType::Limits::Intersect(RangeType::Limits(lhs),
                                       RangeType::Limits(rhs))
              .IsEmpty();
53 54
}

55
bool Type::Contains(RangeType* lhs, RangeType* rhs) {
56
  DisallowHeapAllocation no_allocation;
57
  return lhs->Min() <= rhs->Min() && rhs->Max() <= lhs->Max();
58 59
}

60
bool Type::Contains(RangeType* range, i::Object* val) {
61
  DisallowHeapAllocation no_allocation;
62 63
  return IsInteger(val) && range->Min() <= val->Number() &&
         val->Number() <= range->Max();
64 65
}

66 67 68
// -----------------------------------------------------------------------------
// Min and Max computation.

69
double Type::Min() {
70
  DCHECK(this->Is(Number()));
71
  DCHECK(!this->Is(NaN()));
72 73
  if (this->IsBitset()) return BitsetType::Min(this->AsBitset());
  if (this->IsUnion()) {
74
    double min = +V8_INFINITY;
75
    for (int i = 1, n = this->AsUnion()->Length(); i < n; ++i) {
76 77
      min = std::min(min, this->AsUnion()->Get(i)->Min());
    }
78
    Type* bitset = this->AsUnion()->Get(0);
79
    if (!bitset->Is(NaN())) min = std::min(min, bitset->Min());
80 81
    return min;
  }
82
  if (this->IsRange()) return this->AsRange()->Min();
83 84
  DCHECK(this->IsOtherNumberConstant());
  return this->AsOtherNumberConstant()->Value();
85 86
}

87
double Type::Max() {
88
  DCHECK(this->Is(Number()));
89
  DCHECK(!this->Is(NaN()));
90 91
  if (this->IsBitset()) return BitsetType::Max(this->AsBitset());
  if (this->IsUnion()) {
92
    double max = -V8_INFINITY;
93
    for (int i = 1, n = this->AsUnion()->Length(); i < n; ++i) {
94 95
      max = std::max(max, this->AsUnion()->Get(i)->Max());
    }
96
    Type* bitset = this->AsUnion()->Get(0);
97
    if (!bitset->Is(NaN())) max = std::max(max, bitset->Max());
98 99
    return max;
  }
100
  if (this->IsRange()) return this->AsRange()->Max();
101 102
  DCHECK(this->IsOtherNumberConstant());
  return this->AsOtherNumberConstant()->Value();
103 104
}

105 106 107 108
// -----------------------------------------------------------------------------
// Glb and lub computation.

// The largest bitset subsumed by this type.
109
Type::bitset BitsetType::Glb(Type* type) {
110
  DisallowHeapAllocation no_allocation;
111
  // Fast case.
112
  if (IsBitset(type)) {
113 114 115
    return type->AsBitset();
  } else if (type->IsUnion()) {
    SLOW_DCHECK(type->AsUnion()->Wellformed());
116
    return type->AsUnion()->Get(0)->BitsetGlb() |
117
           type->AsUnion()->Get(1)->BitsetGlb();  // Shortcut.
118
  } else if (type->IsRange()) {
119 120 121
    bitset glb =
        BitsetType::Glb(type->AsRange()->Min(), type->AsRange()->Max());
    return glb;
122
  } else {
123
    return kNone;
124
  }
125 126
}

127
// The smallest bitset subsuming this type, possibly not a proper one.
128
Type::bitset BitsetType::Lub(Type* type) {
129
  DisallowHeapAllocation no_allocation;
130
  if (IsBitset(type)) return type->AsBitset();
131
  if (type->IsUnion()) {
132 133 134
    // Take the representation from the first element, which is always
    // a bitset.
    int bitset = type->AsUnion()->Get(0)->BitsetLub();
135
    for (int i = 0, n = type->AsUnion()->Length(); i < n; ++i) {
136
      // Other elements only contribute their semantic part.
137
      bitset |= type->AsUnion()->Get(i)->BitsetLub();
138 139
    }
    return bitset;
140
  }
141 142 143
  if (type->IsHeapConstant()) return type->AsHeapConstant()->Lub();
  if (type->IsOtherNumberConstant())
    return type->AsOtherNumberConstant()->Lub();
144
  if (type->IsRange()) return type->AsRange()->Lub();
145
  if (type->IsTuple()) return kOtherInternal;
146
  UNREACHABLE();
147 148
}

149
Type::bitset BitsetType::Lub(i::Map* map) {
150
  DisallowHeapAllocation no_allocation;
151 152
  switch (map->instance_type()) {
    case CONS_STRING_TYPE:
153
    case CONS_ONE_BYTE_STRING_TYPE:
154 155
    case THIN_STRING_TYPE:
    case THIN_ONE_BYTE_STRING_TYPE:
156
    case SLICED_STRING_TYPE:
157
    case SLICED_ONE_BYTE_STRING_TYPE:
158
    case EXTERNAL_STRING_TYPE:
159
    case EXTERNAL_ONE_BYTE_STRING_TYPE:
160 161
    case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
    case SHORT_EXTERNAL_STRING_TYPE:
162
    case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
163
    case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
164 165
    case STRING_TYPE:
    case ONE_BYTE_STRING_TYPE:
166
      return kString;
167
    case EXTERNAL_INTERNALIZED_STRING_TYPE:
168
    case EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE:
169 170
    case EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE:
    case SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE:
171
    case SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE:
172
    case SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE:
173 174
    case INTERNALIZED_STRING_TYPE:
    case ONE_BYTE_INTERNALIZED_STRING_TYPE:
175
      return kInternalizedString;
176 177
    case SYMBOL_TYPE:
      return kSymbol;
178 179
    case BIGINT_TYPE:
      return kBigInt;
180 181 182 183 184
    case ODDBALL_TYPE: {
      Heap* heap = map->GetHeap();
      if (map == heap->undefined_map()) return kUndefined;
      if (map == heap->null_map()) return kNull;
      if (map == heap->boolean_map()) return kBoolean;
185 186
      if (map == heap->the_hole_map()) return kHole;
      DCHECK(map == heap->uninitialized_map() ||
187
             map == heap->termination_exception_map() ||
188
             map == heap->arguments_marker_map() ||
189 190
             map == heap->optimized_out_map() ||
             map == heap->stale_register_map());
191
      return kOtherInternal;
192
    }
193
    case HEAP_NUMBER_TYPE:
194
      return kNumber;
195
    case JS_OBJECT_TYPE:
196 197
    case JS_ARGUMENTS_TYPE:
    case JS_ERROR_TYPE:
198 199
    case JS_GLOBAL_OBJECT_TYPE:
    case JS_GLOBAL_PROXY_TYPE:
200
    case JS_API_OBJECT_TYPE:
201
    case JS_SPECIAL_API_OBJECT_TYPE:
202 203 204 205 206 207 208 209 210 211 212
      if (map->is_undetectable()) {
        // Currently we assume that every undetectable receiver is also
        // callable, which is what we need to support document.all.  We
        // could add another Type bit to support other use cases in the
        // future if necessary.
        DCHECK(map->is_callable());
        return kOtherUndetectable;
      }
      if (map->is_callable()) {
        return kOtherCallable;
      }
213
      return kOtherObject;
214 215
    case JS_ARRAY_TYPE:
      return kArray;
216
    case JS_VALUE_TYPE:
217
    case JS_MESSAGE_OBJECT_TYPE:
218 219 220
    case JS_DATE_TYPE:
    case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
    case JS_GENERATOR_OBJECT_TYPE:
221
    case JS_ASYNC_GENERATOR_OBJECT_TYPE:
222
    case JS_MODULE_NAMESPACE_TYPE:
223
    case JS_ARRAY_BUFFER_TYPE:
224
    case JS_ARRAY_ITERATOR_TYPE:
225
    case JS_REGEXP_TYPE:  // TODO(rossberg): there should be a RegExp type.
226
    case JS_REGEXP_STRING_ITERATOR_TYPE:
227 228 229 230
    case JS_TYPED_ARRAY_TYPE:
    case JS_DATA_VIEW_TYPE:
    case JS_SET_TYPE:
    case JS_MAP_TYPE:
231 232 233 234 235
    case JS_SET_KEY_VALUE_ITERATOR_TYPE:
    case JS_SET_VALUE_ITERATOR_TYPE:
    case JS_MAP_KEY_ITERATOR_TYPE:
    case JS_MAP_KEY_VALUE_ITERATOR_TYPE:
    case JS_MAP_VALUE_ITERATOR_TYPE:
236
    case JS_STRING_ITERATOR_TYPE:
237
    case JS_ASYNC_FROM_SYNC_ITERATOR_TYPE:
238 239
    case JS_WEAK_MAP_TYPE:
    case JS_WEAK_SET_TYPE:
240
    case JS_PROMISE_TYPE:
241
    case WASM_MODULE_TYPE:
242
    case WASM_GLOBAL_TYPE:
243 244 245
    case WASM_INSTANCE_TYPE:
    case WASM_MEMORY_TYPE:
    case WASM_TABLE_TYPE:
246
      DCHECK(!map->is_callable());
247
      DCHECK(!map->is_undetectable());
248
      return kOtherObject;
249 250 251
    case JS_BOUND_FUNCTION_TYPE:
      DCHECK(!map->is_undetectable());
      return kBoundFunction;
252
    case JS_FUNCTION_TYPE:
253
      DCHECK(!map->is_undetectable());
254
      return kFunction;
255
    case JS_PROXY_TYPE:
256
      DCHECK(!map->is_undetectable());
257 258
      if (map->is_callable()) return kCallableProxy;
      return kOtherProxy;
259
    case MAP_TYPE:
260
    case ALLOCATION_SITE_TYPE:
261
    case ACCESSOR_INFO_TYPE:
262
    case SHARED_FUNCTION_INFO_TYPE:
263
    case FUNCTION_TEMPLATE_INFO_TYPE:
264 265
    case ACCESSOR_PAIR_TYPE:
    case FIXED_ARRAY_TYPE:
266
    case HASH_TABLE_TYPE:
267
    case WEAK_FIXED_ARRAY_TYPE:
268
    case WEAK_ARRAY_LIST_TYPE:
269
    case FIXED_DOUBLE_ARRAY_TYPE:
270
    case FEEDBACK_METADATA_TYPE:
271
    case BYTE_ARRAY_TYPE:
272
    case BYTECODE_ARRAY_TYPE:
273
    case BOILERPLATE_DESCRIPTION_TYPE:
274
    case DESCRIPTOR_ARRAY_TYPE:
275
    case TRANSITION_ARRAY_TYPE:
276
    case FEEDBACK_CELL_TYPE:
277
    case FEEDBACK_VECTOR_TYPE:
278
    case PROPERTY_ARRAY_TYPE:
279
    case FOREIGN_TYPE:
280
    case SCOPE_INFO_TYPE:
281 282 283 284 285 286 287 288 289
    case BLOCK_CONTEXT_TYPE:
    case CATCH_CONTEXT_TYPE:
    case DEBUG_EVALUATE_CONTEXT_TYPE:
    case EVAL_CONTEXT_TYPE:
    case FUNCTION_CONTEXT_TYPE:
    case MODULE_CONTEXT_TYPE:
    case NATIVE_CONTEXT_TYPE:
    case SCRIPT_CONTEXT_TYPE:
    case WITH_CONTEXT_TYPE:
290
    case SCRIPT_TYPE:
291
    case CODE_TYPE:
292
    case PROPERTY_CELL_TYPE:
293
    case MODULE_TYPE:
294
    case MODULE_INFO_ENTRY_TYPE:
295
    case CELL_TYPE:
296
      return kOtherInternal;
297 298

    // Remaining instance types are unsupported for now. If any of them do
299
    // require bit set types, they should get kOtherInternal.
300 301 302 303 304 305 306 307 308
    case MUTABLE_HEAP_NUMBER_TYPE:
    case FREE_SPACE_TYPE:
#define FIXED_TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case FIXED_##TYPE##_ARRAY_TYPE:

      TYPED_ARRAYS(FIXED_TYPED_ARRAY_CASE)
#undef FIXED_TYPED_ARRAY_CASE
    case FILLER_TYPE:
    case ACCESS_CHECK_INFO_TYPE:
309
    case CALL_HANDLER_INFO_TYPE:
310 311 312 313
    case INTERCEPTOR_INFO_TYPE:
    case OBJECT_TEMPLATE_INFO_TYPE:
    case ALLOCATION_MEMENTO_TYPE:
    case ALIASED_ARGUMENTS_ENTRY_TYPE:
314 315
    case PROMISE_CAPABILITY_TYPE:
    case PROMISE_REACTION_TYPE:
316
    case DEBUG_INFO_TYPE:
317
    case STACK_FRAME_INFO_TYPE:
318
    case WEAK_CELL_TYPE:
319
    case SMALL_ORDERED_HASH_MAP_TYPE:
320
    case SMALL_ORDERED_HASH_SET_TYPE:
321
    case PROTOTYPE_INFO_TYPE:
322
    case INTERPRETER_DATA_TYPE:
323
    case TUPLE2_TYPE:
324
    case TUPLE3_TYPE:
325
    case WASM_COMPILED_MODULE_TYPE:
326
    case WASM_DEBUG_INFO_TYPE:
327
    case WASM_SHARED_MODULE_DATA_TYPE:
328 329
    case LOAD_HANDLER_TYPE:
    case STORE_HANDLER_TYPE:
330
    case CONTEXT_EXTENSION_TYPE:
331
    case ASYNC_GENERATOR_REQUEST_TYPE:
332
    case CODE_DATA_CONTAINER_TYPE:
333 334 335 336 337
    case CALLBACK_TASK_TYPE:
    case CALLABLE_TASK_TYPE:
    case PROMISE_FULFILL_REACTION_JOB_TASK_TYPE:
    case PROMISE_REJECT_REACTION_JOB_TASK_TYPE:
    case PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE:
338
      UNREACHABLE();
339
  }
340
  UNREACHABLE();
341 342
}

343
Type::bitset BitsetType::Lub(i::Object* value) {
344 345
  DisallowHeapAllocation no_allocation;
  if (value->IsNumber()) {
346
    return Lub(value->Number());
347
  }
348
  return Lub(i::HeapObject::cast(value)->map());
349 350
}

351
Type::bitset BitsetType::Lub(double value) {
352
  DisallowHeapAllocation no_allocation;
353 354
  if (i::IsMinusZero(value)) return kMinusZero;
  if (std::isnan(value)) return kNaN;
355
  if (IsUint32Double(value) || IsInt32Double(value)) return Lub(value, value);
356
  return kOtherNumber;
357
}
358

359
// Minimum values of plain numeric bitsets.
360 361 362 363 364 365 366 367 368 369 370 371
const BitsetType::Boundary BitsetType::BoundariesArray[] = {
    {kOtherNumber, kPlainNumber, -V8_INFINITY},
    {kOtherSigned32, kNegative32, kMinInt},
    {kNegative31, kNegative31, -0x40000000},
    {kUnsigned30, kUnsigned30, 0},
    {kOtherUnsigned31, kUnsigned31, 0x40000000},
    {kOtherUnsigned32, kUnsigned32, 0x80000000},
    {kOtherNumber, kPlainNumber, static_cast<double>(kMaxUInt32) + 1}};

const BitsetType::Boundary* BitsetType::Boundaries() { return BoundariesArray; }

size_t BitsetType::BoundariesSize() {
372 373 374 375
  // Windows doesn't like arraysize here.
  // return arraysize(BoundariesArray);
  return 7;
}
376

377
Type::bitset BitsetType::ExpandInternals(Type::bitset bits) {
378
  DCHECK_IMPLIES(bits & kOtherString, (bits & kString) == kString);
379
  DisallowHeapAllocation no_allocation;
380
  if (!(bits & kPlainNumber)) return bits;  // Shortcut.
381 382 383
  const Boundary* boundaries = Boundaries();
  for (size_t i = 0; i < BoundariesSize(); ++i) {
    DCHECK(BitsetType::Is(boundaries[i].internal, boundaries[i].external));
384
    if (bits & boundaries[i].internal) bits |= boundaries[i].external;
385 386 387 388
  }
  return bits;
}

389
Type::bitset BitsetType::Lub(double min, double max) {
390 391
  DisallowHeapAllocation no_allocation;
  int lub = kNone;
392
  const Boundary* mins = Boundaries();
393

394
  for (size_t i = 1; i < BoundariesSize(); ++i) {
395
    if (min < mins[i].min) {
396
      lub |= mins[i - 1].internal;
397 398 399
      if (max < mins[i].min) return lub;
    }
  }
400
  return lub | mins[BoundariesSize() - 1].internal;
401 402
}

403
Type::bitset BitsetType::NumberBits(bitset bits) { return bits & kPlainNumber; }
404

405
Type::bitset BitsetType::Glb(double min, double max) {
406 407 408 409 410 411 412 413 414 415
  DisallowHeapAllocation no_allocation;
  int glb = kNone;
  const Boundary* mins = Boundaries();

  // If the range does not touch 0, the bound is empty.
  if (max < -1 || min > 0) return glb;

  for (size_t i = 1; i + 1 < BoundariesSize(); ++i) {
    if (min <= mins[i].min) {
      if (max + 1 < mins[i + 1].min) break;
416
      glb |= mins[i].external;
417 418 419
    }
  }
  // OtherNumber also contains float numbers, so it can never be
420
  // in the greatest lower bound.
421
  return glb & ~(kOtherNumber);
422 423
}

424
double BitsetType::Min(bitset bits) {
425
  DisallowHeapAllocation no_allocation;
426
  DCHECK(Is(bits, kNumber));
427
  DCHECK(!Is(bits, kNaN));
428
  const Boundary* mins = Boundaries();
429
  bool mz = bits & kMinusZero;
430
  for (size_t i = 0; i < BoundariesSize(); ++i) {
431
    if (Is(mins[i].internal, bits)) {
432 433
      return mz ? std::min(0.0, mins[i].min) : mins[i].min;
    }
434
  }
435 436
  DCHECK(mz);
  return 0;
437 438
}

439
double BitsetType::Max(bitset bits) {
440
  DisallowHeapAllocation no_allocation;
441
  DCHECK(Is(bits, kNumber));
442
  DCHECK(!Is(bits, kNaN));
443
  const Boundary* mins = Boundaries();
444 445
  bool mz = bits & kMinusZero;
  if (BitsetType::Is(mins[BoundariesSize() - 1].internal, bits)) {
446
    return +V8_INFINITY;
447
  }
448
  for (size_t i = BoundariesSize() - 1; i-- > 0;) {
449
    if (Is(mins[i].internal, bits)) {
450
      return mz ? std::max(0.0, mins[i + 1].min - 1) : mins[i + 1].min - 1;
451
    }
452
  }
453 454
  DCHECK(mz);
  return 0;
455 456
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470
// static
bool OtherNumberConstantType::IsOtherNumberConstant(double value) {
  // Not an integer, not NaN, and not -0.
  return !std::isnan(value) && !Type::IsInteger(value) &&
         !i::IsMinusZero(value);
}

// static
bool OtherNumberConstantType::IsOtherNumberConstant(Object* value) {
  return value->IsHeapNumber() &&
         IsOtherNumberConstant(HeapNumber::cast(value)->value());
}

HeapConstantType::HeapConstantType(BitsetType::bitset bitset,
471
                                   i::Handle<i::HeapObject> object)
472
    : TypeBase(kHeapConstant), bitset_(bitset), object_(object) {
473
  DCHECK(!object->IsHeapNumber());
474
  DCHECK_IMPLIES(object->IsString(), object->IsInternalizedString());
475 476
}

477 478 479
// -----------------------------------------------------------------------------
// Predicates.

480
bool Type::SimplyEquals(Type* that) {
481
  DisallowHeapAllocation no_allocation;
482 483
  if (this->IsHeapConstant()) {
    return that->IsHeapConstant() &&
484 485
           this->AsHeapConstant()->Value().address() ==
               that->AsHeapConstant()->Value().address();
486 487 488 489 490 491 492 493
  }
  if (this->IsOtherNumberConstant()) {
    return that->IsOtherNumberConstant() &&
           this->AsOtherNumberConstant()->Value() ==
               that->AsOtherNumberConstant()->Value();
  }
  if (this->IsRange()) {
    if (that->IsHeapConstant() || that->IsOtherNumberConstant()) return false;
494
  }
495 496 497 498 499 500 501 502 503 504 505 506
  if (this->IsTuple()) {
    if (!that->IsTuple()) return false;
    TupleType* this_tuple = this->AsTuple();
    TupleType* that_tuple = that->AsTuple();
    if (this_tuple->Arity() != that_tuple->Arity()) {
      return false;
    }
    for (int i = 0, n = this_tuple->Arity(); i < n; ++i) {
      if (!this_tuple->Element(i)->Equals(that_tuple->Element(i))) return false;
    }
    return true;
  }
507 508 509 510
  UNREACHABLE();
}

// Check if [this] <= [that].
511
bool Type::SlowIs(Type* that) {
512
  DisallowHeapAllocation no_allocation;
513

514
  // Fast bitset cases
515 516 517
  if (that->IsBitset()) {
    return BitsetType::Is(this->BitsetLub(), that->AsBitset());
  }
518

519 520 521 522 523
  if (this->IsBitset()) {
    return BitsetType::Is(this->AsBitset(), that->BitsetGlb());
  }

  // (T1 \/ ... \/ Tn) <= T  if  (T1 <= T) /\ ... /\ (Tn <= T)
524
  if (this->IsUnion()) {
525
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
526
      if (!this->AsUnion()->Get(i)->Is(that)) return false;
527 528 529 530
    }
    return true;
  }

531 532
  // T <= (T1 \/ ... \/ Tn)  if  (T <= T1) \/ ... \/ (T <= Tn)
  if (that->IsUnion()) {
533
    for (int i = 0, n = that->AsUnion()->Length(); i < n; ++i) {
534
      if (this->Is(that->AsUnion()->Get(i))) return true;
535 536 537
      if (i > 1 && this->IsRange()) return false;  // Shortcut.
    }
    return false;
538
  }
539 540

  if (that->IsRange()) {
541
    return (this->IsRange() && Contains(that->AsRange(), this->AsRange()));
542 543
  }
  if (this->IsRange()) return false;
544

545
  return this->SimplyEquals(that);
546 547
}

548
// Check if [this] and [that] overlap.
549
bool Type::Maybe(Type* that) {
550 551
  DisallowHeapAllocation no_allocation;

552
  if (BitsetType::IsNone(this->BitsetLub() & that->BitsetLub())) return false;
553

554
  // (T1 \/ ... \/ Tn) overlaps T  if  (T1 overlaps T) \/ ... \/ (Tn overlaps T)
555
  if (this->IsUnion()) {
556
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
557
      if (this->AsUnion()->Get(i)->Maybe(that)) return true;
558 559 560 561
    }
    return false;
  }

562
  // T overlaps (T1 \/ ... \/ Tn)  if  (T overlaps T1) \/ ... \/ (T overlaps Tn)
563
  if (that->IsUnion()) {
564
    for (int i = 0, n = that->AsUnion()->Length(); i < n; ++i) {
565
      if (this->Maybe(that->AsUnion()->Get(i))) return true;
566 567 568 569
    }
    return false;
  }

570
  if (this->IsBitset() && that->IsBitset()) return true;
571 572

  if (this->IsRange()) {
573 574 575 576 577 578 579 580 581 582 583
    if (that->IsRange()) {
      return Overlap(this->AsRange(), that->AsRange());
    }
    if (that->IsBitset()) {
      bitset number_bits = BitsetType::NumberBits(that->AsBitset());
      if (number_bits == BitsetType::kNone) {
        return false;
      }
      double min = std::max(BitsetType::Min(number_bits), this->Min());
      double max = std::min(BitsetType::Max(number_bits), this->Max());
      return min <= max;
584
    }
585
  }
586
  if (that->IsRange()) {
587
    return that->Maybe(this);  // This case is handled above.
588 589
  }

590 591
  if (this->IsBitset() || that->IsBitset()) return true;

592
  return this->SimplyEquals(that);
593 594
}

595
// Return the range in [this], or [nullptr].
596
Type* Type::GetRange() {
597
  DisallowHeapAllocation no_allocation;
598
  if (this->IsRange()) return this;
599
  if (this->IsUnion() && this->AsUnion()->Get(1)->IsRange()) {
600
    return this->AsUnion()->Get(1);
601
  }
602
  return nullptr;
603 604
}

605
bool UnionType::Wellformed() {
606 607 608
  DisallowHeapAllocation no_allocation;
  // This checks the invariants of the union representation:
  // 1. There are at least two elements.
609 610
  // 2. The first element is a bitset, no other element is a bitset.
  // 3. At most one element is a range, and it must be the second one.
611
  // 4. No element is itself a union.
612
  // 5. No element (except the bitset) is a subtype of any other.
613 614
  // 6. If there is a range, then the bitset type does not contain
  //    plain number bits.
615
  DCHECK_LE(2, this->Length());      // (1)
616
  DCHECK(this->Get(0)->IsBitset());  // (2a)
617

618
  for (int i = 0; i < this->Length(); ++i) {
619
    if (i != 0) DCHECK(!this->Get(i)->IsBitset());  // (2b)
620 621
    if (i != 1) DCHECK(!this->Get(i)->IsRange());   // (3)
    DCHECK(!this->Get(i)->IsUnion());               // (4)
622
    for (int j = 0; j < this->Length(); ++j) {
623
      if (i != j && i != 0) DCHECK(!this->Get(i)->Is(this->Get(j)));  // (5)
624 625
    }
  }
626 627 628
  DCHECK(!this->Get(1)->IsRange() ||
         (BitsetType::NumberBits(this->Get(0)->AsBitset()) ==
          BitsetType::kNone));  // (6)
629 630 631 632 633 634
  return true;
}

// -----------------------------------------------------------------------------
// Union and intersection

635
Type* Type::Intersect(Type* type1, Type* type2, Zone* zone) {
636 637
  // Fast case: bit sets.
  if (type1->IsBitset() && type2->IsBitset()) {
638
    return BitsetType::New(type1->AsBitset() & type2->AsBitset());
639
  }
640 641 642 643 644 645 646 647 648 649

  // Fast case: top or bottom types.
  if (type1->IsNone() || type2->IsAny()) return type1;  // Shortcut.
  if (type2->IsNone() || type1->IsAny()) return type2;  // Shortcut.

  // Semi-fast case.
  if (type1->Is(type2)) return type1;
  if (type2->Is(type1)) return type2;

  // Slow case: create union.
650 651

  // Semantic subtyping check - this is needed for consistency with the
652 653
  // semi-fast case above.
  if (type1->Is(type2)) {
654
    type2 = Any();
655
  } else if (type2->Is(type1)) {
656
    type1 = Any();
657 658
  }

659
  bitset bits = type1->BitsetGlb() & type2->BitsetGlb();
660 661
  int size1 = type1->IsUnion() ? type1->AsUnion()->Length() : 1;
  int size2 = type2->IsUnion() ? type2->AsUnion()->Length() : 1;
662 663 664
  int size;
  if (base::bits::SignedAddOverflow32(size1, size2, &size)) return Any();
  if (base::bits::SignedAddOverflow32(size, 2, &size)) return Any();
665 666
  Type* result_type = UnionType::New(size, zone);
  UnionType* result = result_type->AsUnion();
667 668 669
  size = 0;

  // Deal with bitsets.
670
  result->Set(size++, BitsetType::New(bits));
671

672 673
  RangeType::Limits lims = RangeType::Limits::Empty();
  size = IntersectAux(type1, type2, result, size, &lims, zone);
674 675 676

  // If the range is not empty, then insert it into the union and
  // remove the number bits from the bitset.
677
  if (!lims.IsEmpty()) {
678
    size = UpdateRange(RangeType::New(lims, zone), result, size, zone);
679 680 681 682

    // Remove the number bits.
    bitset number_bits = BitsetType::NumberBits(bits);
    bits &= ~number_bits;
683
    result->Set(0, BitsetType::New(bits));
684
  }
685
  return NormalizeUnion(result_type, size, zone);
686 687
}

688
int Type::UpdateRange(Type* range, UnionType* result, int size, Zone* zone) {
689 690 691 692 693 694
  if (size == 1) {
    result->Set(size++, range);
  } else {
    // Make space for the range.
    result->Set(size++, result->Get(1));
    result->Set(1, range);
695 696 697
  }

  // Remove any components that just got subsumed.
698
  for (int i = 2; i < size;) {
699
    if (result->Get(i)->Is(range)) {
700 701 702
      result->Set(i, result->Get(--size));
    } else {
      ++i;
703
    }
704
  }
705
  return size;
706 707
}

708
RangeType::Limits Type::ToLimits(bitset bits, Zone* zone) {
709 710
  bitset number_bits = BitsetType::NumberBits(bits);

711
  if (number_bits == BitsetType::kNone) {
712
    return RangeType::Limits::Empty();
713 714
  }

715 716
  return RangeType::Limits(BitsetType::Min(number_bits),
                           BitsetType::Max(number_bits));
717 718
}

719 720 721 722 723
RangeType::Limits Type::IntersectRangeAndBitset(Type* range, Type* bitset,
                                                Zone* zone) {
  RangeType::Limits range_lims(range->AsRange());
  RangeType::Limits bitset_lims = ToLimits(bitset->AsBitset(), zone);
  return RangeType::Limits::Intersect(range_lims, bitset_lims);
724 725
}

726 727
int Type::IntersectAux(Type* lhs, Type* rhs, UnionType* result, int size,
                       RangeType::Limits* lims, Zone* zone) {
728
  if (lhs->IsUnion()) {
729
    for (int i = 0, n = lhs->AsUnion()->Length(); i < n; ++i) {
730
      size =
731
          IntersectAux(lhs->AsUnion()->Get(i), rhs, result, size, lims, zone);
732 733 734 735
    }
    return size;
  }
  if (rhs->IsUnion()) {
736
    for (int i = 0, n = rhs->AsUnion()->Length(); i < n; ++i) {
737
      size =
738
          IntersectAux(lhs, rhs->AsUnion()->Get(i), result, size, lims, zone);
739 740
    }
    return size;
741 742
  }

743
  if (BitsetType::IsNone(lhs->BitsetLub() & rhs->BitsetLub())) return size;
744

745
  if (lhs->IsRange()) {
746
    if (rhs->IsBitset()) {
747
      RangeType::Limits lim = IntersectRangeAndBitset(lhs, rhs, zone);
748

749
      if (!lim.IsEmpty()) {
750
        *lims = RangeType::Limits::Union(lim, *lims);
751 752 753 754
      }
      return size;
    }
    if (rhs->IsRange()) {
755 756
      RangeType::Limits lim = RangeType::Limits::Intersect(
          RangeType::Limits(lhs->AsRange()), RangeType::Limits(rhs->AsRange()));
757
      if (!lim.IsEmpty()) {
758
        *lims = RangeType::Limits::Union(lim, *lims);
759 760
      }
    }
761
    return size;
762
  }
763
  if (rhs->IsRange()) {
764
    // This case is handled symmetrically above.
765
    return IntersectAux(rhs, lhs, result, size, lims, zone);
766
  }
767
  if (lhs->IsBitset() || rhs->IsBitset()) {
768
    return AddToUnion(lhs->IsBitset() ? rhs : lhs, result, size, zone);
769
  }
770 771
  if (lhs->SimplyEquals(rhs)) {
    return AddToUnion(lhs, result, size, zone);
772 773
  }
  return size;
774 775
}

776 777
// Make sure that we produce a well-formed range and bitset:
// If the range is non-empty, the number bits in the bitset should be
778
// clear. Moreover, if we have a canonical range (such as Signed32),
779
// we want to produce a bitset rather than a range.
780
Type* Type::NormalizeRangeAndBitset(Type* range, bitset* bits, Zone* zone) {
781 782 783 784 785 786 787
  // Fast path: If the bitset does not mention numbers, we can just keep the
  // range.
  bitset number_bits = BitsetType::NumberBits(*bits);
  if (number_bits == 0) {
    return range;
  }

788 789
  // If the range is semantically contained within the bitset, return None and
  // leave the bitset untouched.
790
  bitset range_lub = range->BitsetLub();
791
  if (BitsetType::Is(range_lub, *bits)) {
792
    return None();
793 794 795 796 797 798
  }

  // Slow path: reconcile the bitset range and the range.
  double bitset_min = BitsetType::Min(number_bits);
  double bitset_max = BitsetType::Max(number_bits);

799 800
  double range_min = range->Min();
  double range_max = range->Max();
801 802

  // Remove the number bits from the bitset, they would just confuse us now.
803 804
  // NOTE: bits contains OtherNumber iff bits contains PlainNumber, in which
  // case we already returned after the subtype check above.
805 806
  *bits &= ~number_bits;

807
  if (range_min <= bitset_min && range_max >= bitset_max) {
808 809 810 811 812
    // Bitset is contained within the range, just return the range.
    return range;
  }

  if (bitset_min < range_min) {
813
    range_min = bitset_min;
814 815
  }
  if (bitset_max > range_max) {
816
    range_max = bitset_max;
817
  }
818
  return RangeType::New(range_min, range_max, zone);
819 820
}

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
Type* Type::NewConstant(double value, Zone* zone) {
  if (IsInteger(value)) {
    return Range(value, value, zone);
  } else if (i::IsMinusZero(value)) {
    return Type::MinusZero();
  } else if (std::isnan(value)) {
    return Type::NaN();
  }

  DCHECK(OtherNumberConstantType::IsOtherNumberConstant(value));
  return OtherNumberConstant(value, zone);
}

Type* Type::NewConstant(i::Handle<i::Object> value, Zone* zone) {
  if (IsInteger(*value)) {
    double v = value->Number();
    return Range(v, v, zone);
  } else if (value->IsHeapNumber()) {
    return NewConstant(value->Number(), zone);
840
  } else if (value->IsString() && !value->IsInternalizedString()) {
841
    return Type::String();
842
  }
843
  return HeapConstant(i::Handle<i::HeapObject>::cast(value), zone);
844 845
}

846
Type* Type::Union(Type* type1, Type* type2, Zone* zone) {
847
  // Fast case: bit sets.
848
  if (type1->IsBitset() && type2->IsBitset()) {
849
    return BitsetType::New(type1->AsBitset() | type2->AsBitset());
850 851
  }

852
  // Fast case: top or bottom types.
853 854
  if (type1->IsAny() || type2->IsNone()) return type1;
  if (type2->IsAny() || type1->IsNone()) return type2;
855

856 857 858 859 860 861 862
  // Semi-fast case.
  if (type1->Is(type2)) return type2;
  if (type2->Is(type1)) return type1;

  // Slow case: create union.
  int size1 = type1->IsUnion() ? type1->AsUnion()->Length() : 1;
  int size2 = type2->IsUnion() ? type2->AsUnion()->Length() : 1;
863 864 865
  int size;
  if (base::bits::SignedAddOverflow32(size1, size2, &size)) return Any();
  if (base::bits::SignedAddOverflow32(size, 2, &size)) return Any();
866 867
  Type* result_type = UnionType::New(size, zone);
  UnionType* result = result_type->AsUnion();
868 869
  size = 0;

870
  // Compute the new bitset.
871
  bitset new_bitset = type1->BitsetGlb() | type2->BitsetGlb();
872 873

  // Deal with ranges.
874 875 876
  Type* range = None();
  Type* range1 = type1->GetRange();
  Type* range2 = type2->GetRange();
877
  if (range1 != nullptr && range2 != nullptr) {
878 879 880
    RangeType::Limits lims =
        RangeType::Limits::Union(RangeType::Limits(range1->AsRange()),
                                 RangeType::Limits(range2->AsRange()));
881
    Type* union_range = RangeType::New(lims, zone);
882
    range = NormalizeRangeAndBitset(union_range, &new_bitset, zone);
883
  } else if (range1 != nullptr) {
884
    range = NormalizeRangeAndBitset(range1, &new_bitset, zone);
885
  } else if (range2 != nullptr) {
886
    range = NormalizeRangeAndBitset(range2, &new_bitset, zone);
887
  }
888
  Type* bits = BitsetType::New(new_bitset);
889
  result->Set(size++, bits);
890
  if (!range->IsNone()) result->Set(size++, range);
891

892 893 894
  size = AddToUnion(type1, result, size, zone);
  size = AddToUnion(type2, result, size, zone);
  return NormalizeUnion(result_type, size, zone);
895 896 897 898
}

// Add [type] to [result] unless [type] is bitset, range, or already subsumed.
// Return new size of [result].
899
int Type::AddToUnion(Type* type, UnionType* result, int size, Zone* zone) {
900 901
  if (type->IsBitset() || type->IsRange()) return size;
  if (type->IsUnion()) {
902
    for (int i = 0, n = type->AsUnion()->Length(); i < n; ++i) {
903
      size = AddToUnion(type->AsUnion()->Get(i), result, size, zone);
904 905
    }
    return size;
906
  }
907
  for (int i = 0; i < size; ++i) {
908
    if (type->Is(result->Get(i))) return size;
909
  }
910 911 912
  result->Set(size++, type);
  return size;
}
913

914 915
Type* Type::NormalizeUnion(Type* union_type, int size, Zone* zone) {
  UnionType* unioned = union_type->AsUnion();
916
  DCHECK_LE(1, size);
917 918 919 920
  DCHECK(unioned->Get(0)->IsBitset());
  // If the union has just one element, return it.
  if (size == 1) {
    return unioned->Get(0);
921
  }
922 923
  bitset bits = unioned->Get(0)->AsBitset();
  // If the union only consists of a range, we can get rid of the union.
924
  if (size == 2 && bits == BitsetType::kNone) {
925 926
    if (unioned->Get(1)->IsRange()) {
      return RangeType::New(unioned->Get(1)->AsRange()->Min(),
927
                            unioned->Get(1)->AsRange()->Max(), zone);
928
    }
929
  }
930 931
  unioned->Shrink(size);
  SLOW_DCHECK(unioned->Wellformed());
932
  return union_type;
933 934
}

935
int Type::NumConstants() {
936
  DisallowHeapAllocation no_allocation;
937
  if (this->IsHeapConstant() || this->IsOtherNumberConstant()) {
938 939 940
    return 1;
  } else if (this->IsUnion()) {
    int result = 0;
941
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
942
      if (this->AsUnion()->Get(i)->IsHeapConstant()) ++result;
943 944 945 946 947 948 949 950 951
    }
    return result;
  } else {
    return 0;
  }
}

// -----------------------------------------------------------------------------
// Printing.
952

953
const char* BitsetType::Name(bitset bits) {
954
  switch (bits) {
955 956
#define RETURN_NAMED_TYPE(type, value) \
  case k##type:                        \
957
    return #type;
958 959 960
    PROPER_BITSET_TYPE_LIST(RETURN_NAMED_TYPE)
    INTERNAL_BITSET_TYPE_LIST(RETURN_NAMED_TYPE)
#undef RETURN_NAMED_TYPE
961

962
    default:
963
      return nullptr;
964 965 966
  }
}

967 968
void BitsetType::Print(std::ostream& os,  // NOLINT
                       bitset bits) {
969
  DisallowHeapAllocation no_allocation;
970
  const char* name = Name(bits);
971
  if (name != nullptr) {
972 973 974 975
    os << name;
    return;
  }

976
  // clang-format off
977
  static const bitset named_bitsets[] = {
978
#define BITSET_CONSTANT(type, value) k##type,
979
    INTERNAL_BITSET_TYPE_LIST(BITSET_CONSTANT)
980
    PROPER_BITSET_TYPE_LIST(BITSET_CONSTANT)
981 982
#undef BITSET_CONSTANT
  };
983
  // clang-format on
984 985 986

  bool is_first = true;
  os << "(";
987 988 989
  for (int i(arraysize(named_bitsets) - 1); bits != 0 && i >= 0; --i) {
    bitset subset = named_bitsets[i];
    if ((bits & subset) == subset) {
990 991 992
      if (!is_first) os << " | ";
      is_first = false;
      os << Name(subset);
993
      bits -= subset;
994 995
    }
  }
996
  DCHECK_EQ(0, bits);
997
  os << ")";
998 999
}

1000
void Type::PrintTo(std::ostream& os) {
1001
  DisallowHeapAllocation no_allocation;
1002 1003
  if (this->IsBitset()) {
    BitsetType::Print(os, this->AsBitset());
1004 1005 1006 1007 1008
  } else if (this->IsHeapConstant()) {
    os << "HeapConstant(" << Brief(*this->AsHeapConstant()->Value()) << ")";
  } else if (this->IsOtherNumberConstant()) {
    os << "OtherNumberConstant(" << this->AsOtherNumberConstant()->Value()
       << ")";
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  } else if (this->IsRange()) {
    std::ostream::fmtflags saved_flags = os.setf(std::ios::fixed);
    std::streamsize saved_precision = os.precision(0);
    os << "Range(" << this->AsRange()->Min() << ", " << this->AsRange()->Max()
       << ")";
    os.flags(saved_flags);
    os.precision(saved_precision);
  } else if (this->IsUnion()) {
    os << "(";
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
      Type* type_i = this->AsUnion()->Get(i);
      if (i > 0) os << " | ";
      type_i->PrintTo(os);
1022
    }
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    os << ")";
  } else if (this->IsTuple()) {
    os << "<";
    for (int i = 0, n = this->AsTuple()->Arity(); i < n; ++i) {
      Type* type_i = this->AsTuple()->Element(i);
      if (i > 0) os << ", ";
      type_i->PrintTo(os);
    }
    os << ">";
  } else {
    UNREACHABLE();
1034 1035 1036
  }
}

1037
#ifdef DEBUG
1038
void Type::Print() {
1039 1040
  OFStream os(stdout);
  PrintTo(os);
1041
  os << std::endl;
1042
}
1043
void BitsetType::Print(bitset bits) {
1044 1045
  OFStream os(stdout);
  Print(os, bits);
1046
  os << std::endl;
1047
}
1048 1049
#endif

1050 1051 1052 1053 1054 1055 1056 1057
BitsetType::bitset BitsetType::SignedSmall() {
  return i::SmiValuesAre31Bits() ? kSigned31 : kSigned32;
}

BitsetType::bitset BitsetType::UnsignedSmall() {
  return i::SmiValuesAre31Bits() ? kUnsigned30 : kUnsigned31;
}

1058
}  // namespace compiler
1059 1060
}  // namespace internal
}  // namespace v8