Debian Codegraph @

js/src/jit/MIR.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "jit/MIR.h"
8
9 #include "mozilla/EndianUtils.h"
10 #include "mozilla/FloatingPoint.h"
11 #include "mozilla/MathAlgorithms.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/ScopeExit.h"
14
15 #include <array>
16 #include <utility>
17
18 #include "jslibmath.h"
19 #include "jsmath.h"
20 #include "jsnum.h"
21
22 #include "builtin/RegExp.h"
23 #include "jit/AtomicOperations.h"
24 #include "jit/CompileInfo.h"
25 #include "jit/KnownClass.h"
26 #include "jit/MIR-wasm.h"
27 #include "jit/MIRGraph.h"
28 #include "jit/RangeAnalysis.h"
29 #include "jit/VMFunctions.h"
30 #include "jit/WarpBuilderShared.h"
31 #include "js/Conversions.h"
32 #include "js/experimental/JitInfo.h" // JSJitInfo, JSTypedMethodJitInfo
33 #include "js/ScalarType.h" // js::Scalar::Type
34 #include "util/Text.h"
35 #include "util/Unicode.h"
36 #include "vm/BigIntType.h"
37 #include "vm/ConstantCompareOperand.h"
38 #include "vm/Float16.h"
39 #include "vm/Iteration.h" // js::NativeIterator
40 #include "vm/PlainObject.h" // js::PlainObject
41 #include "vm/Uint8Clamped.h"
42
43 #include "vm/BytecodeUtil-inl.h"
44 #include "vm/JSAtomUtils-inl.h" // TypeName
45
46 using namespace js;
47 using namespace js::jit;
48
49 using JS::ToInt32;
50
51 using mozilla::IsFloat32Representable;
52 using mozilla::IsPowerOfTwo;
53 using mozilla::NumbersAreIdentical;
54
55 NON_GC_POINTER_TYPE_ASSERTIONS_GENERATED
56
57 #ifdef DEBUG
58 size_t MUse::index() const { return consumer()->indexOf(this); }
59 #endif
60
61 template <size_t Op>
62 static void ConvertDefinitionToDouble(TempAllocator& alloc, MDefinition* def,
63 MInstruction* consumer) {
64 MInstruction* replace = MToDouble::New(alloc, def);
65 consumer->replaceOperand(Op, replace);
66 consumer->block()->insertBefore(consumer, replace);
67 }
68
69 template <size_t Arity, size_t Index>
70 static void ConvertOperandToDouble(MAryInstruction<Arity>* def,
71 TempAllocator& alloc) {
72 static_assert(Index < Arity);
73 auto* operand = def->getOperand(Index);
74 if (operand->type() == MIRType::Float32) {
75 ConvertDefinitionToDouble<Index>(alloc, operand, def);
76 }
77 }
78
79 template <size_t Arity, size_t... ISeq>
80 static void ConvertOperandsToDouble(MAryInstruction<Arity>* def,
81 TempAllocator& alloc,
82 std::index_sequence<ISeq...>) {
83 (ConvertOperandToDouble<Arity, ISeq>(def, alloc), ...);
84 }
85
86 template <size_t Arity>
87 static void ConvertOperandsToDouble(MAryInstruction<Arity>* def,
88 TempAllocator& alloc) {
89 ConvertOperandsToDouble<Arity>(def, alloc, std::make_index_sequence<Arity>{});
90 }
91
92 template <size_t Arity, size_t... ISeq>
93 static bool AllOperandsCanProduceFloat32(MAryInstruction<Arity>* def,
94 std::index_sequence<ISeq...>) {
95 return (def->getOperand(ISeq)->canProduceFloat32() && ...);
96 }
97
98 template <size_t Arity>
99 static bool AllOperandsCanProduceFloat32(MAryInstruction<Arity>* def) {
100 return AllOperandsCanProduceFloat32<Arity>(def,
101 std::make_index_sequence<Arity>{});
102 }
103
104 static bool CheckUsesAreFloat32Consumers(const MInstruction* ins) {
105 if (ins->isImplicitlyUsed()) {
106 return false;
107 }
108 bool allConsumerUses = true;
109 for (MUseDefIterator use(ins); allConsumerUses && use; use++) {
110 allConsumerUses &= use.def()->canConsumeFloat32(use.use());
111 }
112 return allConsumerUses;
113 }
114
115 #ifdef JS_JITSPEW
116 static const char* OpcodeName(MDefinition::Opcode op) {
117 static const char* const names[] = {
118 # define NAME(x) #x,
119 MIR_OPCODE_LIST(NAME)
120 # undef NAME
121 };
122 return names[unsigned(op)];
123 }
124
125 void MDefinition::PrintOpcodeName(GenericPrinter& out, Opcode op) {
126 out.printf("%s", OpcodeName(op));
127 }
128
129 uint32_t js::jit::GetMBasicBlockId(const MBasicBlock* block) {
130 return block->id();
131 }
132 #endif
133
134 static MConstant* EvaluateInt64ConstantOperands(TempAllocator& alloc,
135 MBinaryInstruction* ins) {
136 MDefinition* left = ins->getOperand(0);
137 MDefinition* right = ins->getOperand(1);
138
139 if (!left->isConstant() || !right->isConstant()) {
140 return nullptr;
141 }
142
143 MOZ_ASSERT(left->type() == MIRType::Int64);
144 MOZ_ASSERT(right->type() == MIRType::Int64);
145
146 int64_t lhs = left->toConstant()->toInt64();
147 int64_t rhs = right->toConstant()->toInt64();
148 int64_t ret;
149
150 switch (ins->op()) {
151 case MDefinition::Opcode::BitAnd:
152 ret = lhs & rhs;
153 break;
154 case MDefinition::Opcode::BitOr:
155 ret = lhs | rhs;
156 break;
157 case MDefinition::Opcode::BitXor:
158 ret = lhs ^ rhs;
159 break;
160 case MDefinition::Opcode::Lsh:
161 ret = lhs << (rhs & 0x3F);
162 break;
163 case MDefinition::Opcode::Rsh:
164 ret = lhs >> (rhs & 0x3F);
165 break;
166 case MDefinition::Opcode::Ursh:
167 ret = uint64_t(lhs) >> (uint64_t(rhs) & 0x3F);
168 break;
169 case MDefinition::Opcode::Add:
170 ret = lhs + rhs;
171 break;
172 case MDefinition::Opcode::Sub:
173 ret = lhs - rhs;
174 break;
175 case MDefinition::Opcode::Mul:
176 ret = lhs * rhs;
177 break;
178 case MDefinition::Opcode::Div:
179 if (rhs == 0) {
180 // Division by zero will trap at runtime.
181 return nullptr;
182 }
183 if (ins->toDiv()->isUnsigned()) {
184 ret = int64_t(uint64_t(lhs) / uint64_t(rhs));
185 } else if (lhs == INT64_MIN || rhs == -1) {
186 // Overflow will trap at runtime.
187 return nullptr;
188 } else {
189 ret = lhs / rhs;
190 }
191 break;
192 case MDefinition::Opcode::Mod:
193 if (rhs == 0) {
194 // Division by zero will trap at runtime.
195 return nullptr;
196 }
197 if (!ins->toMod()->isUnsigned() && (lhs < 0 || rhs < 0)) {
198 // Handle all negative values at runtime, for simplicity.
199 return nullptr;
200 }
201 ret = int64_t(uint64_t(lhs) % uint64_t(rhs));
202 break;
203 default:
204 MOZ_CRASH("NYI");
205 }
206
207 return MConstant::NewInt64(alloc, ret);
208 }
209
210 static MConstant* EvaluateConstantOperands(TempAllocator& alloc,
211 MBinaryInstruction* ins) {
212 MDefinition* left = ins->getOperand(0);
213 MDefinition* right = ins->getOperand(1);
214
215 MOZ_ASSERT(IsTypeRepresentableAsDouble(left->type()));
216 MOZ_ASSERT(IsTypeRepresentableAsDouble(right->type()));
217
218 if (!left->isConstant() || !right->isConstant()) {
219 return nullptr;
220 }
221
222 MConstant* lhs = left->toConstant();
223 MConstant* rhs = right->toConstant();
224 double ret = JS::GenericNaN();
225
226 switch (ins->op()) {
227 case MDefinition::Opcode::BitAnd:
228 ret = double(lhs->toInt32() & rhs->toInt32());
229 break;
230 case MDefinition::Opcode::BitOr:
231 ret = double(lhs->toInt32() | rhs->toInt32());
232 break;
233 case MDefinition::Opcode::BitXor:
234 ret = double(lhs->toInt32() ^ rhs->toInt32());
235 break;
236 case MDefinition::Opcode::Lsh:
237 ret = double(uint32_t(lhs->toInt32()) << (rhs->toInt32() & 0x1F));
238 break;
239 case MDefinition::Opcode::Rsh:
240 ret = double(lhs->toInt32() >> (rhs->toInt32() & 0x1F));
241 break;
242 case MDefinition::Opcode::Ursh:
243 ret = double(uint32_t(lhs->toInt32()) >> (rhs->toInt32() & 0x1F));
244 break;
245 case MDefinition::Opcode::Add:
246 ret = lhs->numberToDouble() + rhs->numberToDouble();
247 break;
248 case MDefinition::Opcode::Sub:
249 ret = lhs->numberToDouble() - rhs->numberToDouble();
250 break;
251 case MDefinition::Opcode::Mul:
252 ret = lhs->numberToDouble() * rhs->numberToDouble();
253 break;
254 case MDefinition::Opcode::Div:
255 if (ins->toDiv()->isUnsigned()) {
256 if (rhs->isInt32(0)) {
257 if (ins->toDiv()->trapOnError()) {
258 return nullptr;
259 }
260 ret = 0.0;
261 } else {
262 ret = double(uint32_t(lhs->toInt32()) / uint32_t(rhs->toInt32()));
263 }
264 } else {
265 ret = NumberDiv(lhs->numberToDouble(), rhs->numberToDouble());
266 }
267 break;
268 case MDefinition::Opcode::Mod:
269 if (ins->toMod()->isUnsigned()) {
270 if (rhs->isInt32(0)) {
271 if (ins->toMod()->trapOnError()) {
272 return nullptr;
273 }
274 ret = 0.0;
275 } else {
276 ret = double(uint32_t(lhs->toInt32()) % uint32_t(rhs->toInt32()));
277 }
278 } else {
279 ret = NumberMod(lhs->numberToDouble(), rhs->numberToDouble());
280 }
281 break;
282 default:
283 MOZ_CRASH("NYI");
284 }
285
286 if (ins->type() == MIRType::Float32) {
287 return MConstant::NewFloat32(alloc, float(ret));
288 }
289 if (ins->type() == MIRType::Double) {
290 return MConstant::New(alloc, DoubleValue(ret));
291 }
292 MOZ_ASSERT(ins->type() == MIRType::Int32);
293
294 // If the result isn't an int32 (for example, a division where the numerator
295 // isn't evenly divisible by the denominator), decline folding.
296 int32_t intRet;
297 if (!mozilla::NumberIsInt32(ret, &intRet)) {
298 return nullptr;
299 }
300 return MConstant::New(alloc, Int32Value(intRet));
301 }
302
303 static MConstant* EvaluateConstantNaNOperand(MBinaryInstruction* ins) {
304 auto* left = ins->lhs();
305 auto* right = ins->rhs();
306
307 MOZ_ASSERT(IsTypeRepresentableAsDouble(left->type()));
308 MOZ_ASSERT(IsTypeRepresentableAsDouble(right->type()));
309 MOZ_ASSERT(left->type() == ins->type());
310 MOZ_ASSERT(right->type() == ins->type());
311
312 // Don't fold NaN if we can't return a floating point type.
313 if (!IsFloatingPointType(ins->type())) {
314 return nullptr;
315 }
316
317 MOZ_ASSERT(!left->isConstant() || !right->isConstant(),
318 "EvaluateConstantOperands should have handled this case");
319
320 // One operand must be a constant NaN.
321 MConstant* cst;
322 if (left->isConstant()) {
323 cst = left->toConstant();
324 } else if (right->isConstant()) {
325 cst = right->toConstant();
326 } else {
327 return nullptr;
328 }
329 if (!std::isnan(cst->numberToDouble())) {
330 return nullptr;
331 }
332
333 // Fold to constant NaN.
334 return cst;
335 }
336
337 static MMul* EvaluateExactReciprocal(TempAllocator& alloc, MDiv* ins) {
338 // we should fold only when it is a floating point operation
339 if (!IsFloatingPointType(ins->type())) {
340 return nullptr;
341 }
342
343 MDefinition* left = ins->getOperand(0);
344 MDefinition* right = ins->getOperand(1);
345
346 if (!right->isConstant()) {
347 return nullptr;
348 }
349
350 int32_t num;
351 if (!mozilla::NumberIsInt32(right->toConstant()->numberToDouble(), &num)) {
352 return nullptr;
353 }
354
355 // check if rhs is a power of two
356 if (mozilla::Abs(num) & (mozilla::Abs(num) - 1)) {
357 return nullptr;
358 }
359
360 Value ret;
361 ret.setDouble(1.0 / double(num));
362
363 MConstant* foldedRhs;
364 if (ins->type() == MIRType::Float32) {
365 foldedRhs = MConstant::NewFloat32(alloc, ret.toDouble());
366 } else {
367 foldedRhs = MConstant::New(alloc, ret);
368 }
369
370 MOZ_ASSERT(foldedRhs->type() == ins->type());
371 ins->block()->insertBefore(ins, foldedRhs);
372
373 MMul* mul = MMul::New(alloc, left, foldedRhs, ins->type());
374 mul->setMustPreserveNaN(ins->mustPreserveNaN());
375 return mul;
376 }
377
378 #ifdef JS_JITSPEW
379 const char* MDefinition::opName() const { return OpcodeName(op()); }
380
381 void MDefinition::printName(GenericPrinter& out) const {
382 PrintOpcodeName(out, op());
383 out.printf("#%u", id());
384 }
385 #endif
386
387 HashNumber MDefinition::valueHash() const {
388 HashNumber out = HashNumber(op());
389 for (size_t i = 0, e = numOperands(); i < e; i++) {
390 out = addU32ToHash(out, getOperand(i)->id());
391 }
392 if (MDefinition* dep = dependency()) {
393 out = addU32ToHash(out, dep->id());
394 }
395 return out;
396 }
397
398 HashNumber MNullaryInstruction::valueHash() const {
399 HashNumber hash = HashNumber(op());
400 if (MDefinition* dep = dependency()) {
401 hash = addU32ToHash(hash, dep->id());
402 }
403 MOZ_ASSERT(hash == MDefinition::valueHash());
404 return hash;
405 }
406
407 HashNumber MUnaryInstruction::valueHash() const {
408 HashNumber hash = HashNumber(op());
409 hash = addU32ToHash(hash, getOperand(0)->id());
410 if (MDefinition* dep = dependency()) {
411 hash = addU32ToHash(hash, dep->id());
412 }
413 MOZ_ASSERT(hash == MDefinition::valueHash());
414 return hash;
415 }
416
417 HashNumber MBinaryInstruction::valueHash() const {
418 HashNumber hash = HashNumber(op());
419 hash = addU32ToHash(hash, getOperand(0)->id());
420 hash = addU32ToHash(hash, getOperand(1)->id());
421 if (MDefinition* dep = dependency()) {
422 hash = addU32ToHash(hash, dep->id());
423 }
424 MOZ_ASSERT(hash == MDefinition::valueHash());
425 return hash;
426 }
427
428 HashNumber MTernaryInstruction::valueHash() const {
429 HashNumber hash = HashNumber(op());
430 hash = addU32ToHash(hash, getOperand(0)->id());
431 hash = addU32ToHash(hash, getOperand(1)->id());
432 hash = addU32ToHash(hash, getOperand(2)->id());
433 if (MDefinition* dep = dependency()) {
434 hash = addU32ToHash(hash, dep->id());
435 }
436 MOZ_ASSERT(hash == MDefinition::valueHash());
437 return hash;
438 }
439
440 HashNumber MQuaternaryInstruction::valueHash() const {
441 HashNumber hash = HashNumber(op());
442 hash = addU32ToHash(hash, getOperand(0)->id());
443 hash = addU32ToHash(hash, getOperand(1)->id());
444 hash = addU32ToHash(hash, getOperand(2)->id());
445 hash = addU32ToHash(hash, getOperand(3)->id());
446 if (MDefinition* dep = dependency()) {
447 hash = addU32ToHash(hash, dep->id());
448 }
449 MOZ_ASSERT(hash == MDefinition::valueHash());
450 return hash;
451 }
452
453 const MDefinition* MDefinition::skipObjectGuards() const {
454 const MDefinition* result = this;
455 // These instructions don't modify the object and just guard specific
456 // properties.
457 while (true) {
458 if (result->isGuardShape()) {
459 result = result->toGuardShape()->object();
460 continue;
461 }
462 if (result->isGuardNullProto()) {
463 result = result->toGuardNullProto()->object();
464 continue;
465 }
466 if (result->isGuardProto()) {
467 result = result->toGuardProto()->object();
468 continue;
469 }
470
471 break;
472 }
473
474 return result;
475 }
476
477 bool MDefinition::congruentIfOperandsEqual(const MDefinition* ins) const {
478 if (op() != ins->op()) {
479 return false;
480 }
481
482 if (type() != ins->type()) {
483 return false;
484 }
485
486 if (isEffectful() || ins->isEffectful()) {
487 return false;
488 }
489
490 if (numOperands() != ins->numOperands()) {
491 return false;
492 }
493
494 for (size_t i = 0, e = numOperands(); i < e; i++) {
495 if (getOperand(i) != ins->getOperand(i)) {
496 return false;
497 }
498 }
499
500 return true;
501 }
502
503 MDefinition* MDefinition::foldsTo(TempAllocator& alloc) {
504 // In the default case, there are no constants to fold.
505 return this;
506 }
507
508 MDefinition* MInstruction::foldsToStore(TempAllocator& alloc) {
509 if (!dependency()) {
510 return nullptr;
511 }
512
513 MDefinition* store = dependency();
514 if (mightAlias(store) != AliasType::MustAlias) {
515 return nullptr;
516 }
517
518 if (!store->block()->dominates(block())) {
519 return nullptr;
520 }
521
522 MDefinition* value;
523 switch (store->op()) {
524 case Opcode::StoreFixedSlot:
525 value = store->toStoreFixedSlot()->value();
526 break;
527 case Opcode::StoreDynamicSlot:
528 value = store->toStoreDynamicSlot()->value();
529 break;
530 case Opcode::StoreElement:
531 value = store->toStoreElement()->value();
532 break;
533 default:
534 MOZ_CRASH("unknown store");
535 }
536
537 // If the type are matching then we return the value which is used as
538 // argument of the store.
539 if (value->type() != type()) {
540 // If we expect to read a type which is more generic than the type seen
541 // by the store, then we box the value used by the store.
542 if (type() != MIRType::Value) {
543 return nullptr;
544 }
545
546 MOZ_ASSERT(value->type() < MIRType::Value);
547 MBox* box = MBox::New(alloc, value);
548 value = box;
549 }
550
551 return value;
552 }
553
554 void MDefinition::analyzeEdgeCasesForward() {}
555
556 void MDefinition::analyzeEdgeCasesBackward() {}
557
558 void MInstruction::setResumePoint(MResumePoint* resumePoint) {
559 MOZ_ASSERT(!resumePoint_);
560 resumePoint_ = resumePoint;
561 resumePoint_->setInstruction(this);
562 }
563
564 void MInstruction::stealResumePoint(MInstruction* other) {
565 MResumePoint* resumePoint = other->resumePoint_;
566 other->resumePoint_ = nullptr;
567
568 resumePoint->resetInstruction();
569 setResumePoint(resumePoint);
570 }
571
572 void MInstruction::moveResumePointAsEntry() {
573 MOZ_ASSERT(isNop());
574 block()->clearEntryResumePoint();
575 block()->setEntryResumePoint(resumePoint_);
576 resumePoint_->resetInstruction();
577 resumePoint_ = nullptr;
578 }
579
580 void MInstruction::clearResumePoint() {
581 resumePoint_->resetInstruction();
582 block()->discardPreAllocatedResumePoint(resumePoint_);
583 resumePoint_ = nullptr;
584 }
585
586 MDefinition* MTest::foldsDoubleNegation(TempAllocator& alloc) {
587 MDefinition* op = getOperand(0);
588
589 if (op->isNot()) {
590 // If the operand of the Not is itself a Not, they cancel out.
591 MDefinition* opop = op->getOperand(0);
592 if (opop->isNot()) {
593 return MTest::New(alloc, opop->toNot()->input(), ifTrue(), ifFalse());
594 }
595 return MTest::New(alloc, op->toNot()->input(), ifFalse(), ifTrue());
596 }
597 return nullptr;
598 }
599
600 MDefinition* MTest::foldsConstant(TempAllocator& alloc) {
601 MDefinition* op = getOperand(0);
602 if (MConstant* opConst = op->maybeConstantValue()) {
603 bool b;
604 if (opConst->valueToBoolean(&b)) {
605 return MGoto::New(alloc, b ? ifTrue() : ifFalse());
606 }
607 }
608 return nullptr;
609 }
610
611 MDefinition* MTest::foldsTypes(TempAllocator& alloc) {
612 MDefinition* op = getOperand(0);
613
614 switch (op->type()) {
615 case MIRType::Undefined:
616 case MIRType::Null:
617 return MGoto::New(alloc, ifFalse());
618 case MIRType::Symbol:
619 return MGoto::New(alloc, ifTrue());
620 default:
621 break;
622 }
623 return nullptr;
624 }
625
626 class UsesIterator {
627 MDefinition* def_;
628
629 public:
630 explicit UsesIterator(MDefinition* def) : def_(def) {}
631 auto begin() const { return def_->usesBegin(); }
632 auto end() const { return def_->usesEnd(); }
633 };
634
635 static bool AllInstructionsDeadIfUnused(MBasicBlock* block) {
636 for (auto* ins : *block) {
637 // Skip trivial instructions.
638 if (ins->isNop() || ins->isGoto()) {
639 continue;
640 }
641
642 // All uses must be within the current block.
643 for (auto* use : UsesIterator(ins)) {
644 if (use->consumer()->block() != block) {
645 return false;
646 }
647 }
648
649 // All instructions within this block must be dead if unused.
650 if (!DeadIfUnused(ins)) {
651 return false;
652 }
653 }
654 return true;
655 }
656
657 MDefinition* MTest::foldsNeedlessControlFlow(TempAllocator& alloc) {
658 // All instructions within both successors need be dead if unused.
659 if (!AllInstructionsDeadIfUnused(ifTrue()) ||
660 !AllInstructionsDeadIfUnused(ifFalse())) {
661 return nullptr;
662 }
663
664 // Both successors must have the same target successor.
665 if (ifTrue()->numSuccessors() != 1 || ifFalse()->numSuccessors() != 1) {
666 return nullptr;
667 }
668 if (ifTrue()->getSuccessor(0) != ifFalse()->getSuccessor(0)) {
669 return nullptr;
670 }
671
672 // The target successor's phis must be redundant. Redundant phis should have
673 // been removed in an earlier pass, so only check if any phis are present,
674 // which is a stronger condition.
675 if (ifTrue()->successorWithPhis()) {
676 return nullptr;
677 }
678
679 return MGoto::New(alloc, ifTrue());
680 }
681
682 // If a test is dominated by either the true or false path of a previous test of
683 // the same condition, then the test is redundant and can be converted into a
684 // goto true or goto false, respectively.
685 MDefinition* MTest::foldsRedundantTest(TempAllocator& alloc) {
686 MBasicBlock* myBlock = this->block();
687 MDefinition* originalInput = getOperand(0);
688
689 // Handle single and double negatives. This ensures that we do not miss a
690 // folding opportunity due to a condition being inverted.
691 MDefinition* newInput = input();
692 bool inverted = false;
693 if (originalInput->isNot()) {
694 newInput = originalInput->toNot()->input();
695 inverted = true;
696 if (originalInput->toNot()->input()->isNot()) {
697 newInput = originalInput->toNot()->input()->toNot()->input();
698 inverted = false;
699 }
700 }
701
702 // The specific order of traversal does not matter. If there are multiple
703 // dominating redundant tests, they will either agree on direction (in which
704 // case we will prune the same way regardless of order), or they will
705 // disagree, in which case we will eventually be marked entirely dead by the
706 // folding of the redundant parent.
707 for (MUseIterator i(newInput->usesBegin()), e(newInput->usesEnd()); i != e;
708 ++i) {
709 if (!i->consumer()->isDefinition()) {
710 continue;
711 }
712 if (!i->consumer()->toDefinition()->isTest()) {
713 continue;
714 }
715 MTest* otherTest = i->consumer()->toDefinition()->toTest();
716 if (otherTest == this) {
717 continue;
718 }
719
720 if (otherTest->ifFalse()->dominates(myBlock)) {
721 // This test cannot be true, so fold to a goto false.
722 return MGoto::New(alloc, inverted ? ifTrue() : ifFalse());
723 }
724 if (otherTest->ifTrue()->dominates(myBlock)) {
725 // This test cannot be false, so fold to a goto true.
726 return MGoto::New(alloc, inverted ? ifFalse() : ifTrue());
727 }
728 }
729
730 return nullptr;
731 }
732
733 MDefinition* MTest::foldsTo(TempAllocator& alloc) {
734 if (MDefinition* def = foldsRedundantTest(alloc)) {
735 return def;
736 }
737
738 if (MDefinition* def = foldsDoubleNegation(alloc)) {
739 return def;
740 }
741
742 if (MDefinition* def = foldsConstant(alloc)) {
743 return def;
744 }
745
746 if (MDefinition* def = foldsTypes(alloc)) {
747 return def;
748 }
749
750 if (MDefinition* def = foldsNeedlessControlFlow(alloc)) {
751 return def;
752 }
753
754 return this;
755 }
756
757 AliasSet MThrow::getAliasSet() const {
758 return AliasSet::Store(AliasSet::ExceptionState);
759 }
760
761 AliasSet MThrowWithStack::getAliasSet() const {
762 return AliasSet::Store(AliasSet::ExceptionState);
763 }
764
765 AliasSet MNewArrayDynamicLength::getAliasSet() const {
766 return AliasSet::Store(AliasSet::ExceptionState);
767 }
768
769 AliasSet MNewTypedArrayDynamicLength::getAliasSet() const {
770 return AliasSet::Store(AliasSet::ExceptionState);
771 }
772
773 #ifdef JS_JITSPEW
774 void MDefinition::printOpcode(GenericPrinter& out) const {
775 PrintOpcodeName(out, op());
776 if (numOperands() > 0) {
777 out.printf(" <- ");
778 }
779 for (size_t j = 0, e = numOperands(); j < e; j++) {
780 if (j > 0) {
781 out.printf(", ");
782 }
783 if (getUseFor(j)->hasProducer()) {
784 getOperand(j)->printName(out);
785 } else {
786 out.printf("(null)");
787 }
788 }
789 }
790
791 void MDefinition::dump(GenericPrinter& out) const {
792 printName(out);
793 out.printf(":%s", StringFromMIRType(type()));
794 out.printf(" = ");
795 printOpcode(out);
796 out.printf("\n");
797
798 if (isInstruction()) {
799 if (MResumePoint* resume = toInstruction()->resumePoint()) {
800 resume->dump(out);
801 }
802 }
803 }
804
805 void MDefinition::dump() const {
806 Fprinter out(stderr);
807 dump(out);
808 out.finish();
809 }
810
811 void MDefinition::dumpLocation(GenericPrinter& out) const {
812 MResumePoint* rp = nullptr;
813 const char* linkWord = nullptr;
814 if (isInstruction() && toInstruction()->resumePoint()) {
815 rp = toInstruction()->resumePoint();
816 linkWord = "at";
817 } else {
818 rp = block()->entryResumePoint();
819 linkWord = "after";
820 }
821
822 while (rp) {
823 JSScript* script = rp->block()->info().script();
824 uint32_t lineno = PCToLineNumber(rp->block()->info().script(), rp->pc());
825 out.printf(" %s %s:%u\n", linkWord, script->filename(), lineno);
826 rp = rp->caller();
827 linkWord = "in";
828 }
829 }
830
831 void MDefinition::dumpLocation() const {
832 Fprinter out(stderr);
833 dumpLocation(out);
834 out.finish();
835 }
836 #endif
837
838 #if defined(DEBUG) || defined(JS_JITSPEW)
839 size_t MDefinition::useCount() const {
840 size_t count = 0;
841 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
842 count++;
843 }
844 return count;
845 }
846
847 size_t MDefinition::defUseCount() const {
848 size_t count = 0;
849 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
850 if ((*i)->consumer()->isDefinition()) {
851 count++;
852 }
853 }
854 return count;
855 }
856 #endif
857
858 bool MDefinition::hasOneUse() const {
859 MUseIterator i(uses_.begin());
860 if (i == uses_.end()) {
861 return false;
862 }
863 i++;
864 return i == uses_.end();
865 }
866
867 bool MDefinition::hasOneDefUse() const {
868 bool hasOneDefUse = false;
869 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
870 if (!(*i)->consumer()->isDefinition()) {
871 continue;
872 }
873
874 // We already have a definition use. So 1+
875 if (hasOneDefUse) {
876 return false;
877 }
878
879 // We saw one definition. Loop to test if there is another.
880 hasOneDefUse = true;
881 }
882
883 return hasOneDefUse;
884 }
885
886 bool MDefinition::hasOneLiveDefUse() const {
887 bool hasOneDefUse = false;
888 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
889 if (!(*i)->consumer()->isDefinition()) {
890 continue;
891 }
892
893 MDefinition* def = (*i)->consumer()->toDefinition();
894 if (def->isRecoveredOnBailout()) {
895 continue;
896 }
897
898 // We already have a definition use. So 1+
899 if (hasOneDefUse) {
900 return false;
901 }
902
903 // We saw one definition. Loop to test if there is another.
904 hasOneDefUse = true;
905 }
906
907 return hasOneDefUse;
908 }
909
910 bool MDefinition::hasDefUses() const {
911 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
912 if ((*i)->consumer()->isDefinition()) {
913 return true;
914 }
915 }
916
917 return false;
918 }
919
920 bool MDefinition::hasLiveDefUses() const {
921 for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
922 MNode* ins = (*i)->consumer();
923 if (ins->isDefinition()) {
924 if (!ins->toDefinition()->isRecoveredOnBailout()) {
925 return true;
926 }
927 } else {
928 MOZ_ASSERT(ins->isResumePoint());
929 if (!ins->toResumePoint()->isRecoverableOperand(*i)) {
930 return true;
931 }
932 }
933 }
934 return false;
935 }
936
937 MDefinition* MDefinition::maybeSingleDefUse() const {
938 MUseDefIterator use(this);
939 if (!use) {
940 // No def-uses.
941 return nullptr;
942 }
943
944 MDefinition* useDef = use.def();
945
946 use++;
947 if (use) {
948 // More than one def-use.
949 return nullptr;
950 }
951
952 return useDef;
953 }
954
955 MDefinition* MDefinition::maybeMostRecentlyAddedDefUse() const {
956 MUseDefIterator use(this);
957 if (!use) {
958 // No def-uses.
959 return nullptr;
960 }
961
962 MDefinition* mostRecentUse = use.def();
963
964 #ifdef DEBUG
965 // This function relies on addUse adding new uses to the front of the list.
966 // Check this invariant by asserting the next few uses are 'older'. Skip this
967 // for phis because setBackedge can add a new use for a loop phi even if the
968 // loop body has a use with an id greater than the loop phi's id.
969 if (!mostRecentUse->isPhi()) {
970 static constexpr size_t NumUsesToCheck = 3;
971 use++;
972 for (size_t i = 0; use && i < NumUsesToCheck; i++, use++) {
973 MOZ_ASSERT(use.def()->id() <= mostRecentUse->id());
974 }
975 }
976 #endif
977
978 return mostRecentUse;
979 }
980
981 void MDefinition::replaceAllUsesWith(MDefinition* dom) {
982 for (size_t i = 0, e = numOperands(); i < e; ++i) {
983 getOperand(i)->setImplicitlyUsedUnchecked();
984 }
985
986 justReplaceAllUsesWith(dom);
987 }
988
989 void MDefinition::justReplaceAllUsesWith(MDefinition* dom) {
990 MOZ_ASSERT(dom != nullptr);
991 MOZ_ASSERT(dom != this);
992
993 // Carry over the fact the value has uses which are no longer inspectable
994 // with the graph.
995 if (isImplicitlyUsed()) {
996 dom->setImplicitlyUsedUnchecked();
997 }
998
999 for (MUseIterator i(usesBegin()), e(usesEnd()); i != e; ++i) {
1000 i->setProducerUnchecked(dom);
1001 }
1002 dom->uses_.takeElements(uses_);
1003 }
1004
1005 bool MDefinition::optimizeOutAllUses(TempAllocator& alloc) {
1006 for (MUseIterator i(usesBegin()), e(usesEnd()); i != e;) {
1007 MUse* use = *i++;
1008 MConstant* constant = use->consumer()->block()->optimizedOutConstant(alloc);
1009 if (!alloc.ensureBallast()) {
1010 return false;
1011 }
1012
1013 // Update the resume point operand to use the optimized-out constant.
1014 use->setProducerUnchecked(constant);
1015 constant->addUseUnchecked(use);
1016 }
1017
1018 // Remove dangling pointers.
1019 this->uses_.clear();
1020 return true;
1021 }
1022
1023 void MDefinition::replaceAllLiveUsesWith(MDefinition* dom) {
1024 for (MUseIterator i(usesBegin()), e(usesEnd()); i != e;) {
1025 MUse* use = *i++;
1026 MNode* consumer = use->consumer();
1027 if (consumer->isResumePoint()) {
1028 continue;
1029 }
1030 if (consumer->isDefinition() &&
1031 consumer->toDefinition()->isRecoveredOnBailout()) {
1032 continue;
1033 }
1034
1035 // Update the operand to use the dominating definition.
1036 use->replaceProducer(dom);
1037 }
1038 }
1039
1040 MConstant* MConstant::New(TempAllocator& alloc, const Value& v) {
1041 return new (alloc) MConstant(alloc, v);
1042 }
1043
1044 MConstant* MConstant::New(TempAllocator::Fallible alloc, const Value& v) {
1045 return new (alloc) MConstant(alloc.alloc, v);
1046 }
1047
1048 MConstant* MConstant::NewFloat32(TempAllocator& alloc, double d) {
1049 MOZ_ASSERT(std::isnan(d) || d == double(float(d)));
1050 return new (alloc) MConstant(float(d));
1051 }
1052
1053 MConstant* MConstant::NewInt64(TempAllocator& alloc, int64_t i) {
1054 return new (alloc) MConstant(MIRType::Int64, i);
1055 }
1056
1057 MConstant* MConstant::NewIntPtr(TempAllocator& alloc, intptr_t i) {
1058 return new (alloc) MConstant(MIRType::IntPtr, i);
1059 }
1060
1061 MConstant* MConstant::New(TempAllocator& alloc, const Value& v, MIRType type) {
1062 if (type == MIRType::Float32) {
1063 return NewFloat32(alloc, v.toNumber());
1064 }
1065 MConstant* res = New(alloc, v);
1066 MOZ_ASSERT(res->type() == type);
1067 return res;
1068 }
1069
1070 MConstant* MConstant::NewObject(TempAllocator& alloc, JSObject* v) {
1071 return new (alloc) MConstant(v);
1072 }
1073
1074 MConstant* MConstant::NewShape(TempAllocator& alloc, Shape* s) {
1075 return new (alloc) MConstant(s);
1076 }
1077
1078 static MIRType MIRTypeFromValue(const js::Value& vp) {
1079 if (vp.isDouble()) {
1080 return MIRType::Double;
1081 }
1082 if (vp.isMagic()) {
1083 switch (vp.whyMagic()) {
1084 case JS_OPTIMIZED_OUT:
1085 return MIRType::MagicOptimizedOut;
1086 case JS_ELEMENTS_HOLE:
1087 return MIRType::MagicHole;
1088 case JS_IS_CONSTRUCTING:
1089 return MIRType::MagicIsConstructing;
1090 case JS_UNINITIALIZED_LEXICAL:
1091 return MIRType::MagicUninitializedLexical;
1092 default:
1093 MOZ_ASSERT_UNREACHABLE("Unexpected magic constant");
1094 }
1095 }
1096 return MIRTypeFromValueType(vp.extractNonDoubleType());
1097 }
1098
1099 MConstant::MConstant(TempAllocator& alloc, const js::Value& vp)
1100 : MNullaryInstruction(classOpcode) {
1101 setResultType(MIRTypeFromValue(vp));
1102
1103 MOZ_ASSERT(payload_.asBits == 0);
1104
1105 switch (type()) {
1106 case MIRType::Undefined:
1107 case MIRType::Null:
1108 break;
1109 case MIRType::Boolean:
1110 payload_.b = vp.toBoolean();
1111 break;
1112 case MIRType::Int32:
1113 payload_.i32 = vp.toInt32();
1114 break;
1115 case MIRType::Double:
1116 payload_.d = vp.toDouble();
1117 break;
1118 case MIRType::String: {
1119 JSString* str = vp.toString();
1120 if (str->isAtomRef()) {
1121 str = str->atom();
1122 }
1123 MOZ_ASSERT(!IsInsideNursery(str));
1124 MOZ_ASSERT(str->isAtom());
1125 payload_.str = vp.toString();
1126 break;
1127 }
1128 case MIRType::Symbol:
1129 payload_.sym = vp.toSymbol();
1130 break;
1131 case MIRType::BigInt:
1132 MOZ_ASSERT(!IsInsideNursery(vp.toBigInt()));
1133 payload_.bi = vp.toBigInt();
1134 break;
1135 case MIRType::Object:
1136 MOZ_ASSERT(!IsInsideNursery(&vp.toObject()));
1137 payload_.obj = &vp.toObject();
1138 break;
1139 case MIRType::MagicOptimizedOut:
1140 case MIRType::MagicHole:
1141 case MIRType::MagicIsConstructing:
1142 case MIRType::MagicUninitializedLexical:
1143 break;
1144 default:
1145 MOZ_CRASH("Unexpected type");
1146 }
1147
1148 setMovable();
1149 }
1150
1151 MConstant::MConstant(JSObject* obj) : MNullaryInstruction(classOpcode) {
1152 MOZ_ASSERT(!IsInsideNursery(obj));
1153 setResultType(MIRType::Object);
1154 payload_.obj = obj;
1155 setMovable();
1156 }
1157
1158 MConstant::MConstant(Shape* shape) : MNullaryInstruction(classOpcode) {
1159 setResultType(MIRType::Shape);
1160 payload_.shape = shape;
1161 setMovable();
1162 }
1163
1164 MConstant::MConstant(float f) : MNullaryInstruction(classOpcode) {
1165 setResultType(MIRType::Float32);
1166 payload_.f = f;
1167 setMovable();
1168 }
1169
1170 MConstant::MConstant(MIRType type, int64_t i)
1171 : MNullaryInstruction(classOpcode) {
1172 MOZ_ASSERT(type == MIRType::Int64 || type == MIRType::IntPtr);
1173 setResultType(type);
1174 if (type == MIRType::Int64) {
1175 payload_.i64 = i;
1176 } else {
1177 payload_.iptr = i;
1178 }
1179 setMovable();
1180 }
1181
1182 #ifdef DEBUG
1183 void MConstant::assertInitializedPayload() const {
1184 // valueHash() and equals() expect the unused payload bits to be
1185 // initialized to zero. Assert this in debug builds.
1186
1187 switch (type()) {
1188 case MIRType::Int32:
1189 case MIRType::Float32:
1190 # if MOZ_LITTLE_ENDIAN()
1191 MOZ_ASSERT((payload_.asBits >> 32) == 0);
1192 # else
1193 MOZ_ASSERT((payload_.asBits << 32) == 0);
1194 # endif
1195 break;
1196 case MIRType::Boolean:
1197 # if MOZ_LITTLE_ENDIAN()
1198 MOZ_ASSERT((payload_.asBits >> 1) == 0);
1199 # else
1200 MOZ_ASSERT((payload_.asBits & ~(1ULL << 56)) == 0);
1201 # endif
1202 break;
1203 case MIRType::Double:
1204 case MIRType::Int64:
1205 break;
1206 case MIRType::String:
1207 case MIRType::Object:
1208 case MIRType::Symbol:
1209 case MIRType::BigInt:
1210 case MIRType::IntPtr:
1211 case MIRType::Shape:
1212 # if MOZ_LITTLE_ENDIAN()
1213 MOZ_ASSERT_IF(JS_BITS_PER_WORD == 32, (payload_.asBits >> 32) == 0);
1214 # else
1215 MOZ_ASSERT_IF(JS_BITS_PER_WORD == 32, (payload_.asBits << 32) == 0);
1216 # endif
1217 break;
1218 default:
1219 MOZ_ASSERT(IsNullOrUndefined(type()) || IsMagicType(type()));
1220 MOZ_ASSERT(payload_.asBits == 0);
1221 break;
1222 }
1223 }
1224 #endif
1225
1226 HashNumber MConstant::valueHash() const {
1227 static_assert(sizeof(Payload) == sizeof(uint64_t),
1228 "Code below assumes payload fits in 64 bits");
1229
1230 assertInitializedPayload();
1231 return ConstantValueHash(type(), payload_.asBits);
1232 }
1233
1234 HashNumber MConstantProto::valueHash() const {
1235 HashNumber hash = protoObject()->valueHash();
1236 const MDefinition* receiverObject = getReceiverObject();
1237 if (receiverObject) {
1238 hash = addU32ToHash(hash, receiverObject->id());
1239 }
1240 return hash;
1241 }
1242
1243 bool MConstant::congruentTo(const MDefinition* ins) const {
1244 return ins->isConstant() && equals(ins->toConstant());
1245 }
1246
1247 #ifdef JS_JITSPEW
1248 void MConstant::printOpcode(GenericPrinter& out) const {
1249 PrintOpcodeName(out, op());
1250 out.printf(" ");
1251 switch (type()) {
1252 case MIRType::Undefined:
1253 out.printf("undefined");
1254 break;
1255 case MIRType::Null:
1256 out.printf("null");
1257 break;
1258 case MIRType::Boolean:
1259 out.printf(toBoolean() ? "true" : "false");
1260 break;
1261 case MIRType::Int32:
1262 out.printf("0x%x", uint32_t(toInt32()));
1263 break;
1264 case MIRType::Int64:
1265 out.printf("0x%" PRIx64, uint64_t(toInt64()));
1266 break;
1267 case MIRType::IntPtr:
1268 out.printf("0x%" PRIxPTR, uintptr_t(toIntPtr()));
1269 break;
1270 case MIRType::Double:
1271 out.printf("%.16g", toDouble());
1272 break;
1273 case MIRType::Float32: {
1274 float val = toFloat32();
1275 out.printf("%.16g", val);
1276 break;
1277 }
1278 case MIRType::Object:
1279 if (toObject().is<JSFunction>()) {
1280 JSFunction* fun = &toObject().as<JSFunction>();
1281 if (fun->maybePartialDisplayAtom()) {
1282 out.put("function ");
1283 EscapedStringPrinter(out, fun->maybePartialDisplayAtom(), 0);
1284 } else {
1285 out.put("unnamed function");
1286 }
1287 if (fun->hasBaseScript()) {
1288 BaseScript* script = fun->baseScript();
1289 out.printf(" (%s:%u)", script->filename() ? script->filename() : "",
1290 script->lineno());
1291 }
1292 out.printf(" at %p", (void*)fun);
1293 break;
1294 }
1295 out.printf("object %p (%s)", (void*)&toObject(),
1296 toObject().getClass()->name);
1297 break;
1298 case MIRType::Symbol:
1299 out.printf("symbol at %p", (void*)toSymbol());
1300 break;
1301 case MIRType::BigInt:
1302 out.printf("BigInt at %p", (void*)toBigInt());
1303 break;
1304 case MIRType::String:
1305 out.printf("string %p", (void*)toString());
1306 break;
1307 case MIRType::Shape:
1308 out.printf("shape at %p", (void*)toShape());
1309 break;
1310 case MIRType::MagicHole:
1311 out.printf("magic hole");
1312 break;
1313 case MIRType::MagicIsConstructing:
1314 out.printf("magic is-constructing");
1315 break;
1316 case MIRType::MagicOptimizedOut:
1317 out.printf("magic optimized-out");
1318 break;
1319 case MIRType::MagicUninitializedLexical:
1320 out.printf("magic uninitialized-lexical");
1321 break;
1322 default:
1323 MOZ_CRASH("unexpected type");
1324 }
1325 }
1326 #endif
1327
1328 bool MConstant::canProduceFloat32() const {
1329 if (!isTypeRepresentableAsDouble()) {
1330 return false;
1331 }
1332
1333 if (type() == MIRType::Int32) {
1334 return IsFloat32Representable(static_cast<double>(toInt32()));
1335 }
1336 if (type() == MIRType::Double) {
1337 return IsFloat32Representable(toDouble());
1338 }
1339 MOZ_ASSERT(type() == MIRType::Float32);
1340 return true;
1341 }
1342
1343 Value MConstant::toJSValue() const {
1344 // Wasm has types like int64 that cannot be stored as js::Value. It also
1345 // doesn't want the NaN canonicalization enforced by js::Value.
1346 MOZ_ASSERT(!IsCompilingWasm());
1347
1348 switch (type()) {
1349 case MIRType::Undefined:
1350 return UndefinedValue();
1351 case MIRType::Null:
1352 return NullValue();
1353 case MIRType::Boolean:
1354 return BooleanValue(toBoolean());
1355 case MIRType::Int32:
1356 return Int32Value(toInt32());
1357 case MIRType::Double:
1358 return DoubleValue(toDouble());
1359 case MIRType::Float32:
1360 return Float32Value(toFloat32());
1361 case MIRType::String:
1362 return StringValue(toString());
1363 case MIRType::Symbol:
1364 return SymbolValue(toSymbol());
1365 case MIRType::BigInt:
1366 return BigIntValue(toBigInt());
1367 case MIRType::Object:
1368 return ObjectValue(toObject());
1369 case MIRType::Shape:
1370 return PrivateGCThingValue(toShape());
1371 case MIRType::MagicOptimizedOut:
1372 return MagicValue(JS_OPTIMIZED_OUT);
1373 case MIRType::MagicHole:
1374 return MagicValue(JS_ELEMENTS_HOLE);
1375 case MIRType::MagicIsConstructing:
1376 return MagicValue(JS_IS_CONSTRUCTING);
1377 case MIRType::MagicUninitializedLexical:
1378 return MagicValue(JS_UNINITIALIZED_LEXICAL);
1379 default:
1380 MOZ_CRASH("Unexpected type");
1381 }
1382 }
1383
1384 bool MConstant::valueToBoolean(bool* res) const {
1385 switch (type()) {
1386 case MIRType::Boolean:
1387 *res = toBoolean();
1388 return true;
1389 case MIRType::Int32:
1390 *res = toInt32() != 0;
1391 return true;
1392 case MIRType::Int64:
1393 *res = toInt64() != 0;
1394 return true;
1395 case MIRType::IntPtr:
1396 *res = toIntPtr() != 0;
1397 return true;
1398 case MIRType::Double:
1399 *res = !std::isnan(toDouble()) && toDouble() != 0.0;
1400 return true;
1401 case MIRType::Float32:
1402 *res = !std::isnan(toFloat32()) && toFloat32() != 0.0f;
1403 return true;
1404 case MIRType::Null:
1405 case MIRType::Undefined:
1406 *res = false;
1407 return true;
1408 case MIRType::Symbol:
1409 *res = true;
1410 return true;
1411 case MIRType::BigInt:
1412 *res = !toBigInt()->isZero();
1413 return true;
1414 case MIRType::String:
1415 *res = toString()->length() != 0;
1416 return true;
1417 case MIRType::Object:
1418 // TODO(Warp): Lazy groups have been removed.
1419 // We have to call EmulatesUndefined but that reads obj->group->clasp
1420 // and so it's racy when the object has a lazy group. The main callers
1421 // of this (MTest, MNot) already know how to fold the object case, so
1422 // just give up.
1423 return false;
1424 default:
1425 MOZ_ASSERT(IsMagicType(type()));
1426 return false;
1427 }
1428 }
1429
1430 #ifdef JS_JITSPEW
1431 void MControlInstruction::printOpcode(GenericPrinter& out) const {
1432 MDefinition::printOpcode(out);
1433 if (numSuccessors() > 0) {
1434 out.printf(" -> ");
1435 }
1436 for (size_t j = 0; j < numSuccessors(); j++) {
1437 if (j > 0) {
1438 out.printf(", ");
1439 }
1440 if (getSuccessor(j)) {
1441 out.printf("block %u", getSuccessor(j)->id());
1442 } else {
1443 out.printf("(null-to-be-patched)");
1444 }
1445 }
1446 }
1447
1448 void MCompare::printOpcode(GenericPrinter& out) const {
1449 MDefinition::printOpcode(out);
1450 out.printf(" %s", CodeName(jsop()));
1451 }
1452
1453 void MTypeOfIs::printOpcode(GenericPrinter& out) const {
1454 MDefinition::printOpcode(out);
1455 out.printf(" %s", CodeName(jsop()));
1456
1457 const char* name = "";
1458 switch (jstype()) {
1459 case JSTYPE_UNDEFINED:
1460 name = "undefined";
1461 break;
1462 case JSTYPE_OBJECT:
1463 name = "object";
1464 break;
1465 case JSTYPE_FUNCTION:
1466 name = "function";
1467 break;
1468 case JSTYPE_STRING:
1469 name = "string";
1470 break;
1471 case JSTYPE_NUMBER:
1472 name = "number";
1473 break;
1474 case JSTYPE_BOOLEAN:
1475 name = "boolean";
1476 break;
1477 case JSTYPE_SYMBOL:
1478 name = "symbol";
1479 break;
1480 case JSTYPE_BIGINT:
1481 name = "bigint";
1482 break;
1483 case JSTYPE_LIMIT:
1484 MOZ_CRASH("Unexpected type");
1485 }
1486 out.printf(" '%s'", name);
1487 }
1488
1489 void MLoadUnboxedScalar::printOpcode(GenericPrinter& out) const {
1490 MDefinition::printOpcode(out);
1491 out.printf(" %s", Scalar::name(storageType()));
1492 }
1493
1494 void MLoadDataViewElement::printOpcode(GenericPrinter& out) const {
1495 MDefinition::printOpcode(out);
1496 out.printf(" %s", Scalar::name(storageType()));
1497 }
1498
1499 void MAssertRange::printOpcode(GenericPrinter& out) const {
1500 MDefinition::printOpcode(out);
1501 out.put(" ");
1502 assertedRange()->dump(out);
1503 }
1504
1505 void MNearbyInt::printOpcode(GenericPrinter& out) const {
1506 MDefinition::printOpcode(out);
1507 const char* roundingModeStr = nullptr;
1508 switch (roundingMode_) {
1509 case RoundingMode::Up:
1510 roundingModeStr = "(up)";
1511 break;
1512 case RoundingMode::Down:
1513 roundingModeStr = "(down)";
1514 break;
1515 case RoundingMode::NearestTiesToEven:
1516 roundingModeStr = "(nearest ties even)";
1517 break;
1518 case RoundingMode::TowardsZero:
1519 roundingModeStr = "(towards zero)";
1520 break;
1521 }
1522 out.printf(" %s", roundingModeStr);
1523 }
1524 #endif
1525
1526 AliasSet MRandom::getAliasSet() const { return AliasSet::Store(AliasSet::RNG); }
1527
1528 MDefinition* MSign::foldsTo(TempAllocator& alloc) {
1529 MDefinition* input = getOperand(0);
1530 if (!input->isConstant() ||
1531 !input->toConstant()->isTypeRepresentableAsDouble()) {
1532 return this;
1533 }
1534
1535 double in = input->toConstant()->numberToDouble();
1536 double out = js::math_sign_impl(in);
1537
1538 if (type() == MIRType::Int32) {
1539 // Decline folding if this is an int32 operation, but the result type
1540 // isn't an int32.
1541 Value outValue = NumberValue(out);
1542 if (!outValue.isInt32()) {
1543 return this;
1544 }
1545
1546 return MConstant::New(alloc, outValue);
1547 }
1548
1549 return MConstant::New(alloc, DoubleValue(out));
1550 }
1551
1552 const char* MMathFunction::FunctionName(UnaryMathFunction function) {
1553 return GetUnaryMathFunctionName(function);
1554 }
1555
1556 #ifdef JS_JITSPEW
1557 void MMathFunction::printOpcode(GenericPrinter& out) const {
1558 MDefinition::printOpcode(out);
1559 out.printf(" %s", FunctionName(function()));
1560 }
1561 #endif
1562
1563 MDefinition* MMathFunction::foldsTo(TempAllocator& alloc) {
1564 MDefinition* input = getOperand(0);
1565 if (!input->isConstant() ||
1566 !input->toConstant()->isTypeRepresentableAsDouble()) {
1567 return this;
1568 }
1569
1570 UnaryMathFunctionType funPtr = GetUnaryMathFunctionPtr(function());
1571
1572 double in = input->toConstant()->numberToDouble();
1573
1574 // The function pointer call can't GC.
1575 JS::AutoSuppressGCAnalysis nogc;
1576 double out = funPtr(in);
1577
1578 if (input->type() == MIRType::Float32) {
1579 return MConstant::NewFloat32(alloc, out);
1580 }
1581 return MConstant::New(alloc, DoubleValue(out));
1582 }
1583
1584 MDefinition* MAtomicIsLockFree::foldsTo(TempAllocator& alloc) {
1585 MDefinition* input = getOperand(0);
1586 if (!input->isConstant() || input->type() != MIRType::Int32) {
1587 return this;
1588 }
1589
1590 int32_t i = input->toConstant()->toInt32();
1591 return MConstant::New(alloc, BooleanValue(AtomicOperations::isLockfreeJS(i)));
1592 }
1593
1594 // Define |THIS_SLOT| as part of this translation unit, as it is used to
1595 // specialized the parameterized |New| function calls introduced by
1596 // TRIVIAL_NEW_WRAPPERS.
1597 const int32_t MParameter::THIS_SLOT;
1598
1599 #ifdef JS_JITSPEW
1600 void MParameter::printOpcode(GenericPrinter& out) const {
1601 PrintOpcodeName(out, op());
1602 if (index() == THIS_SLOT) {
1603 out.printf(" THIS_SLOT");
1604 } else {
1605 out.printf(" %d", index());
1606 }
1607 }
1608 #endif
1609
1610 HashNumber MParameter::valueHash() const {
1611 HashNumber hash = MDefinition::valueHash();
1612 hash = addU32ToHash(hash, index_);
1613 return hash;
1614 }
1615
1616 bool MParameter::congruentTo(const MDefinition* ins) const {
1617 if (!ins->isParameter()) {
1618 return false;
1619 }
1620
1621 return ins->toParameter()->index() == index_;
1622 }
1623
1624 WrappedFunction::WrappedFunction(JSFunction* nativeFun, uint16_t nargs,
1625 FunctionFlags flags)
1626 : nativeFun_(nativeFun), nargs_(nargs), flags_(flags) {
1627 MOZ_ASSERT_IF(nativeFun, isNativeWithoutJitEntry());
1628
1629 #ifdef DEBUG
1630 // If we are not running off-main thread we can assert that the
1631 // metadata is consistent.
1632 if (!CanUseExtraThreads() && nativeFun) {
1633 MOZ_ASSERT(nativeFun->nargs() == nargs);
1634
1635 MOZ_ASSERT(nativeFun->isNativeWithoutJitEntry() ==
1636 isNativeWithoutJitEntry());
1637 MOZ_ASSERT(nativeFun->hasJitEntry() == hasJitEntry());
1638 MOZ_ASSERT(nativeFun->isConstructor() == isConstructor());
1639 MOZ_ASSERT(nativeFun->isClassConstructor() == isClassConstructor());
1640 }
1641 #endif
1642 }
1643
1644 MCall* MCall::New(TempAllocator& alloc, WrappedFunction* target, size_t maxArgc,
1645 size_t numActualArgs, bool construct, bool ignoresReturnValue,
1646 bool isDOMCall, mozilla::Maybe<DOMObjectKind> objectKind,
1647 mozilla::Maybe<gc::Heap> initialHeap) {
1648 MOZ_ASSERT(isDOMCall == objectKind.isSome());
1649 MOZ_ASSERT(isDOMCall == initialHeap.isSome());
1650
1651 MOZ_ASSERT(maxArgc >= numActualArgs);
1652 MCall* ins;
1653 if (isDOMCall) {
1654 MOZ_ASSERT(!construct);
1655 ins = new (alloc)
1656 MCallDOMNative(target, numActualArgs, *objectKind, *initialHeap);
1657 } else {
1658 ins =
1659 new (alloc) MCall(target, numActualArgs, construct, ignoresReturnValue);
1660 }
1661 if (!ins->init(alloc, maxArgc + NumNonArgumentOperands)) {
1662 return nullptr;
1663 }
1664 return ins;
1665 }
1666
1667 AliasSet MCallDOMNative::getAliasSet() const {
1668 const JSJitInfo* jitInfo = getJitInfo();
1669
1670 // If we don't know anything about the types of our arguments, we have to
1671 // assume that type-coercions can have side-effects, so we need to alias
1672 // everything.
1673 if (jitInfo->aliasSet() == JSJitInfo::AliasEverything ||
1674 !jitInfo->isTypedMethodJitInfo()) {
1675 return AliasSet::Store(AliasSet::Any);
1676 }
1677
1678 uint32_t argIndex = 0;
1679 const JSTypedMethodJitInfo* methodInfo =
1680 reinterpret_cast<const JSTypedMethodJitInfo*>(jitInfo);
1681 for (const JSJitInfo::ArgType* argType = methodInfo->argTypes;
1682 *argType != JSJitInfo::ArgTypeListEnd; ++argType, ++argIndex) {
1683 if (argIndex >= numActualArgs()) {
1684 // Passing through undefined can't have side-effects
1685 continue;
1686 }
1687 // getArg(0) is "this", so skip it
1688 MDefinition* arg = getArg(argIndex + 1);
1689 MIRType actualType = arg->type();
1690 // The only way to reliably avoid side-effects given the information we
1691 // have here is if we're passing in a known primitive value to an
1692 // argument that expects a primitive value.
1693 //
1694 // XXXbz maybe we need to communicate better information. For example,
1695 // a sequence argument will sort of unavoidably have side effects, while
1696 // a typed array argument won't have any, but both are claimed to be
1697 // JSJitInfo::Object. But if we do that, we need to watch out for our
1698 // movability/DCE-ability bits: if we have an arg type that can reliably
1699 // throw an exception on conversion, that might not affect our alias set
1700 // per se, but it should prevent us being moved or DCE-ed, unless we
1701 // know the incoming things match that arg type and won't throw.
1702 //
1703 if ((actualType == MIRType::Value || actualType == MIRType::Object) ||
1704 (*argType & JSJitInfo::Object)) {
1705 return AliasSet::Store(AliasSet::Any);
1706 }
1707 }
1708
1709 // We checked all the args, and they check out. So we only alias DOM
1710 // mutations or alias nothing, depending on the alias set in the jitinfo.
1711 if (jitInfo->aliasSet() == JSJitInfo::AliasNone) {
1712 return AliasSet::None();
1713 }
1714
1715 MOZ_ASSERT(jitInfo->aliasSet() == JSJitInfo::AliasDOMSets);
1716 return AliasSet::Load(AliasSet::DOMProperty);
1717 }
1718
1719 void MCallDOMNative::computeMovable() {
1720 // We are movable if the jitinfo says we can be and if we're also not
1721 // effectful. The jitinfo can't check for the latter, since it depends on
1722 // the types of our arguments.
1723 const JSJitInfo* jitInfo = getJitInfo();
1724
1725 MOZ_ASSERT_IF(jitInfo->isMovable,
1726 jitInfo->aliasSet() != JSJitInfo::AliasEverything);
1727
1728 if (jitInfo->isMovable && !isEffectful()) {
1729 setMovable();
1730 }
1731 }
1732
1733 bool MCallDOMNative::congruentTo(const MDefinition* ins) const {
1734 if (!isMovable()) {
1735 return false;
1736 }
1737
1738 if (!ins->isCall()) {
1739 return false;
1740 }
1741
1742 const MCall* call = ins->toCall();
1743
1744 if (!call->isCallDOMNative()) {
1745 return false;
1746 }
1747
1748 if (getSingleTarget() != call->getSingleTarget()) {
1749 return false;
1750 }
1751
1752 if (isConstructing() != call->isConstructing()) {
1753 return false;
1754 }
1755
1756 if (numActualArgs() != call->numActualArgs()) {
1757 return false;
1758 }
1759
1760 if (!congruentIfOperandsEqual(call)) {
1761 return false;
1762 }
1763
1764 // The other call had better be movable at this point!
1765 MOZ_ASSERT(call->isMovable());
1766
1767 return true;
1768 }
1769
1770 const JSJitInfo* MCallDOMNative::getJitInfo() const {
1771 MOZ_ASSERT(getSingleTarget()->hasJitInfo());
1772 return getSingleTarget()->jitInfo();
1773 }
1774
1775 MCallClassHook* MCallClassHook::New(TempAllocator& alloc, JSNative target,
1776 uint32_t argc, bool constructing) {
1777 auto* ins = new (alloc) MCallClassHook(target, constructing);
1778
1779 // Add callee + |this| + (if constructing) newTarget.
1780 uint32_t numOperands = 2 + argc + constructing;
1781
1782 if (!ins->init(alloc, numOperands)) {
1783 return nullptr;
1784 }
1785
1786 return ins;
1787 }
1788
1789 MDefinition* MStringLength::foldsTo(TempAllocator& alloc) {
1790 if (string()->isConstant()) {
1791 JSString* str = string()->toConstant()->toString();
1792 return MConstant::New(alloc, Int32Value(str->length()));
1793 }
1794
1795 // MFromCharCode returns a one-element string.
1796 if (string()->isFromCharCode()) {
1797 return MConstant::New(alloc, Int32Value(1));
1798 }
1799
1800 return this;
1801 }
1802
1803 MDefinition* MConcat::foldsTo(TempAllocator& alloc) {
1804 if (lhs()->isConstant() && lhs()->toConstant()->toString()->empty()) {
1805 return rhs();
1806 }
1807
1808 if (rhs()->isConstant() && rhs()->toConstant()->toString()->empty()) {
1809 return lhs();
1810 }
1811
1812 return this;
1813 }
1814
1815 MDefinition* MStringConvertCase::foldsTo(TempAllocator& alloc) {
1816 MDefinition* string = this->string();
1817
1818 // Handle the pattern |str[idx].toUpperCase()| and simplify it from
1819 // |StringConvertCase(FromCharCode(CharCodeAt(str, idx)))| to just
1820 // |CharCodeConvertCase(CharCodeAt(str, idx))|.
1821 if (string->isFromCharCode()) {
1822 auto* charCode = string->toFromCharCode()->code();
1823 auto mode = mode_ == Mode::LowerCase ? MCharCodeConvertCase::LowerCase
1824 : MCharCodeConvertCase::UpperCase;
1825 return MCharCodeConvertCase::New(alloc, charCode, mode);
1826 }
1827
1828 // Handle the pattern |num.toString(base).toUpperCase()| and simplify it to
1829 // directly return the string representation in the correct case.
1830 if (string->isInt32ToStringWithBase()) {
1831 auto* toString = string->toInt32ToStringWithBase();
1832
1833 bool lowerCase = mode_ == Mode::LowerCase;
1834 if (toString->lowerCase() == lowerCase) {
1835 return toString;
1836 }
1837 return MInt32ToStringWithBase::New(alloc, toString->input(),
1838 toString->base(), lowerCase);
1839 }
1840
1841 return this;
1842 }
1843
1844 static bool IsSubstrTo(MSubstr* substr, int32_t len) {
1845 // We want to match this pattern:
1846 //
1847 // Substr(string, Constant(0), Min(Constant(length), StringLength(string)))
1848 //
1849 // which is generated for the self-hosted `String.p.{substring,slice,substr}`
1850 // functions when called with constants `start` and `end` parameters.
1851
1852 auto isConstantZero = [](auto* def) {
1853 return def->isConstant() && def->toConstant()->isInt32(0);
1854 };
1855
1856 if (!isConstantZero(substr->begin())) {
1857 return false;
1858 }
1859
1860 auto* length = substr->length();
1861 if (length->isBitOr()) {
1862 // Unnecessary bit-ops haven't yet been removed.
1863 auto* bitOr = length->toBitOr();
1864 if (isConstantZero(bitOr->lhs())) {
1865 length = bitOr->rhs();
1866 } else if (isConstantZero(bitOr->rhs())) {
1867 length = bitOr->lhs();
1868 }
1869 }
1870 if (!length->isMinMax() || length->toMinMax()->isMax()) {
1871 return false;
1872 }
1873
1874 auto* min = length->toMinMax();
1875 if (!min->lhs()->isConstant() && !min->rhs()->isConstant()) {
1876 return false;
1877 }
1878
1879 auto* minConstant = min->lhs()->isConstant() ? min->lhs()->toConstant()
1880 : min->rhs()->toConstant();
1881
1882 auto* minOperand = min->lhs()->isConstant() ? min->rhs() : min->lhs();
1883 if (!minOperand->isStringLength() ||
1884 minOperand->toStringLength()->string() != substr->string()) {
1885 return false;
1886 }
1887
1888 // Ensure |len| matches the substring's length.
1889 return minConstant->isInt32(len);
1890 }
1891
1892 MDefinition* MSubstr::foldsTo(TempAllocator& alloc) {
1893 // Fold |str.substring(0, 1)| to |str.charAt(0)|.
1894 if (!IsSubstrTo(this, 1)) {
1895 return this;
1896 }
1897
1898 auto* charCode = MCharCodeAtOrNegative::New(alloc, string(), begin());
1899 block()->insertBefore(this, charCode);
1900
1901 return MFromCharCodeEmptyIfNegative::New(alloc, charCode);
1902 }
1903
1904 MDefinition* MCharCodeAt::foldsTo(TempAllocator& alloc) {
1905 MDefinition* string = this->string();
1906 if (!string->isConstant() && !string->isFromCharCode()) {
1907 return this;
1908 }
1909
1910 MDefinition* index = this->index();
1911 if (index->isSpectreMaskIndex()) {
1912 index = index->toSpectreMaskIndex()->index();
1913 }
1914 if (!index->isConstant()) {
1915 return this;
1916 }
1917 int32_t idx = index->toConstant()->toInt32();
1918
1919 // Handle the pattern |s[idx].charCodeAt(0)|.
1920 if (string->isFromCharCode()) {
1921 if (idx != 0) {
1922 return this;
1923 }
1924
1925 // Simplify |CharCodeAt(FromCharCode(CharCodeAt(s, idx)), 0)| to just
1926 // |CharCodeAt(s, idx)|.
1927 auto* charCode = string->toFromCharCode()->code();
1928 if (!charCode->isCharCodeAt()) {
1929 return this;
1930 }
1931
1932 return charCode;
1933 }
1934
1935 JSLinearString* str = &string->toConstant()->toString()->asLinear();
1936 if (idx < 0 || uint32_t(idx) >= str->length()) {
1937 return this;
1938 }
1939
1940 char16_t ch = str->latin1OrTwoByteChar(idx);
1941 return MConstant::New(alloc, Int32Value(ch));
1942 }
1943
1944 MDefinition* MCodePointAt::foldsTo(TempAllocator& alloc) {
1945 MDefinition* string = this->string();
1946 if (!string->isConstant() && !string->isFromCharCode()) {
1947 return this;
1948 }
1949
1950 MDefinition* index = this->index();
1951 if (index->isSpectreMaskIndex()) {
1952 index = index->toSpectreMaskIndex()->index();
1953 }
1954 if (!index->isConstant()) {
1955 return this;
1956 }
1957 int32_t idx = index->toConstant()->toInt32();
1958
1959 // Handle the pattern |s[idx].codePointAt(0)|.
1960 if (string->isFromCharCode()) {
1961 if (idx != 0) {
1962 return this;
1963 }
1964
1965 // Simplify |CodePointAt(FromCharCode(CharCodeAt(s, idx)), 0)| to just
1966 // |CharCodeAt(s, idx)|.
1967 auto* charCode = string->toFromCharCode()->code();
1968 if (!charCode->isCharCodeAt()) {
1969 return this;
1970 }
1971
1972 return charCode;
1973 }
1974
1975 JSLinearString* str = &string->toConstant()->toString()->asLinear();
1976 if (idx < 0 || uint32_t(idx) >= str->length()) {
1977 return this;
1978 }
1979
1980 char32_t first = str->latin1OrTwoByteChar(idx);
1981 if (unicode::IsLeadSurrogate(first) && uint32_t(idx) + 1 < str->length()) {
1982 char32_t second = str->latin1OrTwoByteChar(idx + 1);
1983 if (unicode::IsTrailSurrogate(second)) {
1984 first = unicode::UTF16Decode(first, second);
1985 }
1986 }
1987 return MConstant::New(alloc, Int32Value(first));
1988 }
1989
1990 MDefinition* MToRelativeStringIndex::foldsTo(TempAllocator& alloc) {
1991 MDefinition* index = this->index();
1992 MDefinition* length = this->length();
1993
1994 if (!index->isConstant()) {
1995 return this;
1996 }
1997 if (!length->isStringLength() && !length->isConstant()) {
1998 return this;
1999 }
2000 MOZ_ASSERT_IF(length->isConstant(), length->toConstant()->toInt32() >= 0);
2001
2002 int32_t relativeIndex = index->toConstant()->toInt32();
2003 if (relativeIndex >= 0) {
2004 return index;
2005 }
2006
2007 // Safe to truncate because |length| is never negative.
2008 return MAdd::New(alloc, index, length, TruncateKind::Truncate);
2009 }
2010
2011 template <size_t Arity>
2012 [[nodiscard]] static bool EnsureFloatInputOrConvert(
2013 MAryInstruction<Arity>* owner, TempAllocator& alloc) {
2014 MOZ_ASSERT(!IsFloatingPointType(owner->type()),
2015 "Floating point types must check consumers");
2016
2017 if (AllOperandsCanProduceFloat32(owner)) {
2018 return true;
2019 }
2020 ConvertOperandsToDouble(owner, alloc);
2021 return false;
2022 }
2023
2024 template <size_t Arity>
2025 [[nodiscard]] static bool EnsureFloatConsumersAndInputOrConvert(
2026 MAryInstruction<Arity>* owner, TempAllocator& alloc) {
2027 MOZ_ASSERT(IsFloatingPointType(owner->type()),
2028 "Integer types don't need to check consumers");
2029
2030 if (AllOperandsCanProduceFloat32(owner) &&
2031 CheckUsesAreFloat32Consumers(owner)) {
2032 return true;
2033 }
2034 ConvertOperandsToDouble(owner, alloc);
2035 return false;
2036 }
2037
2038 void MFloor::trySpecializeFloat32(TempAllocator& alloc) {
2039 MOZ_ASSERT(type() == MIRType::Int32);
2040 if (EnsureFloatInputOrConvert(this, alloc)) {
2041 specialization_ = MIRType::Float32;
2042 }
2043 }
2044
2045 void MCeil::trySpecializeFloat32(TempAllocator& alloc) {
2046 MOZ_ASSERT(type() == MIRType::Int32);
2047 if (EnsureFloatInputOrConvert(this, alloc)) {
2048 specialization_ = MIRType::Float32;
2049 }
2050 }
2051
2052 void MRound::trySpecializeFloat32(TempAllocator& alloc) {
2053 MOZ_ASSERT(type() == MIRType::Int32);
2054 if (EnsureFloatInputOrConvert(this, alloc)) {
2055 specialization_ = MIRType::Float32;
2056 }
2057 }
2058
2059 void MTrunc::trySpecializeFloat32(TempAllocator& alloc) {
2060 MOZ_ASSERT(type() == MIRType::Int32);
2061 if (EnsureFloatInputOrConvert(this, alloc)) {
2062 specialization_ = MIRType::Float32;
2063 }
2064 }
2065
2066 void MNearbyInt::trySpecializeFloat32(TempAllocator& alloc) {
2067 if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
2068 specialization_ = MIRType::Float32;
2069 setResultType(MIRType::Float32);
2070 }
2071 }
2072
2073 MGoto* MGoto::New(TempAllocator& alloc, MBasicBlock* target) {
2074 return new (alloc) MGoto(target);
2075 }
2076
2077 MGoto* MGoto::New(TempAllocator::Fallible alloc, MBasicBlock* target) {
2078 MOZ_ASSERT(target);
2079 return new (alloc) MGoto(target);
2080 }
2081
2082 MGoto* MGoto::New(TempAllocator& alloc) { return new (alloc) MGoto(nullptr); }
2083
2084 MDefinition* MBox::foldsTo(TempAllocator& alloc) {
2085 if (input()->isUnbox()) {
2086 return input()->toUnbox()->input();
2087 }
2088 return this;
2089 }
2090
2091 #ifdef JS_JITSPEW
2092 void MUnbox::printOpcode(GenericPrinter& out) const {
2093 PrintOpcodeName(out, op());
2094 out.printf(" ");
2095 getOperand(0)->printName(out);
2096 out.printf(" ");
2097
2098 switch (type()) {
2099 case MIRType::Int32:
2100 out.printf("to Int32");
2101 break;
2102 case MIRType::Double:
2103 out.printf("to Double");
2104 break;
2105 case MIRType::Boolean:
2106 out.printf("to Boolean");
2107 break;
2108 case MIRType::String:
2109 out.printf("to String");
2110 break;
2111 case MIRType::Symbol:
2112 out.printf("to Symbol");
2113 break;
2114 case MIRType::BigInt:
2115 out.printf("to BigInt");
2116 break;
2117 case MIRType::Object:
2118 out.printf("to Object");
2119 break;
2120 default:
2121 break;
2122 }
2123
2124 switch (mode()) {
2125 case Fallible:
2126 out.printf(" (fallible)");
2127 break;
2128 case Infallible:
2129 out.printf(" (infallible)");
2130 break;
2131 default:
2132 break;
2133 }
2134 }
2135 #endif
2136
2137 MDefinition* MUnbox::foldsTo(TempAllocator& alloc) {
2138 if (input()->isBox()) {
2139 MDefinition* unboxed = input()->toBox()->input();
2140
2141 // Fold MUnbox(MBox(x)) => x if types match.
2142 if (unboxed->type() == type()) {
2143 if (fallible()) {
2144 unboxed->setImplicitlyUsedUnchecked();
2145 }
2146 return unboxed;
2147 }
2148
2149 // Fold MUnbox(MBox(x)) => MToDouble(x) if possible.
2150 if (type() == MIRType::Double &&
2151 IsTypeRepresentableAsDouble(unboxed->type())) {
2152 if (unboxed->isConstant()) {
2153 return MConstant::New(
2154 alloc, DoubleValue(unboxed->toConstant()->numberToDouble()));
2155 }
2156
2157 return MToDouble::New(alloc, unboxed);
2158 }
2159
2160 // MUnbox<Int32>(MBox<Double>(x)) will always fail, even if x can be
2161 // represented as an Int32. Fold to avoid unnecessary bailouts.
2162 if (type() == MIRType::Int32 && unboxed->type() == MIRType::Double) {
2163 auto* folded = MToNumberInt32::New(alloc, unboxed,
2164 IntConversionInputKind::NumbersOnly);
2165 folded->setGuard();
2166 return folded;
2167 }
2168 }
2169
2170 return this;
2171 }
2172
2173 #ifdef DEBUG
2174 void MPhi::assertLoopPhi() const {
2175 // getLoopPredecessorOperand and getLoopBackedgeOperand rely on these
2176 // predecessors being at known indices.
2177 if (block()->numPredecessors() == 2) {
2178 MBasicBlock* pred = block()->getPredecessor(0);
2179 MBasicBlock* back = block()->getPredecessor(1);
2180 MOZ_ASSERT(pred == block()->loopPredecessor());
2181 MOZ_ASSERT(pred->successorWithPhis() == block());
2182 MOZ_ASSERT(pred->positionInPhiSuccessor() == 0);
2183 MOZ_ASSERT(back == block()->backedge());
2184 MOZ_ASSERT(back->successorWithPhis() == block());
2185 MOZ_ASSERT(back->positionInPhiSuccessor() == 1);
2186 } else {
2187 // After we remove fake loop predecessors for loop headers that
2188 // are only reachable via OSR, the only predecessor is the
2189 // loop backedge.
2190 MOZ_ASSERT(block()->numPredecessors() == 1);
2191 MOZ_ASSERT(block()->graph().osrBlock());
2192 MOZ_ASSERT(!block()->graph().canBuildDominators());
2193 MBasicBlock* back = block()->getPredecessor(0);
2194 MOZ_ASSERT(back == block()->backedge());
2195 MOZ_ASSERT(back->successorWithPhis() == block());
2196 MOZ_ASSERT(back->positionInPhiSuccessor() == 0);
2197 }
2198 }
2199 #endif
2200
2201 MDefinition* MPhi::getLoopPredecessorOperand() const {
2202 // This should not be called after removing fake loop predecessors.
2203 MOZ_ASSERT(block()->numPredecessors() == 2);
2204 assertLoopPhi();
2205 return getOperand(0);
2206 }
2207
2208 MDefinition* MPhi::getLoopBackedgeOperand() const {
2209 assertLoopPhi();
2210 uint32_t idx = block()->numPredecessors() == 2 ? 1 : 0;
2211 return getOperand(idx);
2212 }
2213
2214 void MPhi::removeOperand(size_t index) {
2215 MOZ_ASSERT(index < numOperands());
2216 MOZ_ASSERT(getUseFor(index)->index() == index);
2217 MOZ_ASSERT(getUseFor(index)->consumer() == this);
2218
2219 // If we have phi(..., a, b, c, d, ..., z) and we plan
2220 // on removing a, then first shift downward so that we have
2221 // phi(..., b, c, d, ..., z, z):
2222 MUse* p = inputs_.begin() + index;
2223 MUse* e = inputs_.end();
2224 p->producer()->removeUse(p);
2225 for (; p < e - 1; ++p) {
2226 MDefinition* producer = (p + 1)->producer();
2227 p->setProducerUnchecked(producer);
2228 producer->replaceUse(p + 1, p);
2229 }
2230
2231 // truncate the inputs_ list:
2232 inputs_.popBack();
2233 }
2234
2235 void MPhi::removeAllOperands() {
2236 for (MUse& p : inputs_) {
2237 p.producer()->removeUse(&p);
2238 }
2239 inputs_.clear();
2240 }
2241
2242 MDefinition* MPhi::foldsTernary(TempAllocator& alloc) {
2243 /* Look if this MPhi is a ternary construct.
2244 * This is a very loose term as it actually only checks for
2245 *
2246 * MTest X
2247 * / \
2248 * ... ...
2249 * \ /
2250 * MPhi X Y
2251 *
2252 * Which we will simply call:
2253 * x ? x : y or x ? y : x
2254 */
2255
2256 if (numOperands() != 2) {
2257 return nullptr;
2258 }
2259
2260 MOZ_ASSERT(block()->numPredecessors() == 2);
2261
2262 MBasicBlock* pred = block()->immediateDominator();
2263 if (!pred || !pred->lastIns()->isTest()) {
2264 return nullptr;
2265 }
2266
2267 MTest* test = pred->lastIns()->toTest();
2268
2269 // True branch may only dominate one edge of MPhi.
2270 if (test->ifTrue()->dominates(block()->getPredecessor(0)) ==
2271 test->ifTrue()->dominates(block()->getPredecessor(1))) {
2272 return nullptr;
2273 }
2274
2275 // False branch may only dominate one edge of MPhi.
2276 if (test->ifFalse()->dominates(block()->getPredecessor(0)) ==
2277 test->ifFalse()->dominates(block()->getPredecessor(1))) {
2278 return nullptr;
2279 }
2280
2281 // True and false branch must dominate different edges of MPhi.
2282 if (test->ifTrue()->dominates(block()->getPredecessor(0)) ==
2283 test->ifFalse()->dominates(block()->getPredecessor(0))) {
2284 return nullptr;
2285 }
2286
2287 // We found a ternary construct.
2288 bool firstIsTrueBranch =
2289 test->ifTrue()->dominates(block()->getPredecessor(0));
2290 MDefinition* trueDef = firstIsTrueBranch ? getOperand(0) : getOperand(1);
2291 MDefinition* falseDef = firstIsTrueBranch ? getOperand(1) : getOperand(0);
2292
2293 // Accept either
2294 // testArg ? testArg : constant or
2295 // testArg ? constant : testArg
2296 if (!trueDef->isConstant() && !falseDef->isConstant()) {
2297 return nullptr;
2298 }
2299
2300 MConstant* c =
2301 trueDef->isConstant() ? trueDef->toConstant() : falseDef->toConstant();
2302 MDefinition* testArg = (trueDef == c) ? falseDef : trueDef;
2303 if (testArg != test->input()) {
2304 return nullptr;
2305 }
2306
2307 // This check should be a tautology, except that the constant might be the
2308 // result of the removal of a branch. In such case the domination scope of
2309 // the block which is holding the constant might be incomplete. This
2310 // condition is used to prevent doing this optimization based on incomplete
2311 // information.
2312 //
2313 // As GVN removed a branch, it will update the dominations rules before
2314 // trying to fold this MPhi again. Thus, this condition does not inhibit
2315 // this optimization.
2316 MBasicBlock* truePred = block()->getPredecessor(firstIsTrueBranch ? 0 : 1);
2317 MBasicBlock* falsePred = block()->getPredecessor(firstIsTrueBranch ? 1 : 0);
2318 if (!trueDef->block()->dominates(truePred) ||
2319 !falseDef->block()->dominates(falsePred)) {
2320 return nullptr;
2321 }
2322
2323 // If testArg is an int32 type we can:
2324 // - fold testArg ? testArg : 0 to testArg
2325 // - fold testArg ? 0 : testArg to 0
2326 if (testArg->type() == MIRType::Int32 && c->numberToDouble() == 0) {
2327 testArg->setGuardRangeBailoutsUnchecked();
2328
2329 // When folding to the constant we need to hoist it.
2330 if (trueDef == c && !c->block()->dominates(block())) {
2331 c->block()->moveBefore(pred->lastIns(), c);
2332 }
2333 return trueDef;
2334 }
2335
2336 // If testArg is an double type we can:
2337 // - fold testArg ? testArg : 0.0 to MNaNToZero(testArg)
2338 if (testArg->type() == MIRType::Double &&
2339 mozilla::IsPositiveZero(c->numberToDouble()) && c != trueDef) {
2340 MNaNToZero* replace = MNaNToZero::New(alloc, testArg);
2341 test->block()->insertBefore(test, replace);
2342 return replace;
2343 }
2344
2345 // If testArg is a string type we can:
2346 // - fold testArg ? testArg : "" to testArg
2347 // - fold testArg ? "" : testArg to ""
2348 if (testArg->type() == MIRType::String &&
2349 c->toString() == GetJitContext()->runtime->emptyString()) {
2350 // When folding to the constant we need to hoist it.
2351 if (trueDef == c && !c->block()->dominates(block())) {
2352 c->block()->moveBefore(pred->lastIns(), c);
2353 }
2354 return trueDef;
2355 }
2356
2357 return nullptr;
2358 }
2359
2360 MDefinition* MPhi::operandIfRedundant() {
2361 if (inputs_.length() == 0) {
2362 return nullptr;
2363 }
2364
2365 // If this phi is redundant (e.g., phi(a,a) or b=phi(a,this)),
2366 // returns the operand that it will always be equal to (a, in
2367 // those two cases).
2368 MDefinition* first = getOperand(0);
2369 for (size_t i = 1, e = numOperands(); i < e; i++) {
2370 MDefinition* op = getOperand(i);
2371 if (op != first && op != this) {
2372 return nullptr;
2373 }
2374 }
2375 return first;
2376 }
2377
2378 MDefinition* MPhi::foldsTo(TempAllocator& alloc) {
2379 if (MDefinition* def = operandIfRedundant()) {
2380 return def;
2381 }
2382
2383 if (MDefinition* def = foldsTernary(alloc)) {
2384 return def;
2385 }
2386
2387 return this;
2388 }
2389
2390 bool MPhi::congruentTo(const MDefinition* ins) const {
2391 if (!ins->isPhi()) {
2392 return false;
2393 }
2394
2395 // Phis in different blocks may have different control conditions.
2396 // For example, these phis:
2397 //
2398 // if (p)
2399 // goto a
2400 // a:
2401 // t = phi(x, y)
2402 //
2403 // if (q)
2404 // goto b
2405 // b:
2406 // s = phi(x, y)
2407 //
2408 // have identical operands, but they are not equvalent because t is
2409 // effectively p?x:y and s is effectively q?x:y.
2410 //
2411 // For now, consider phis in different blocks incongruent.
2412 if (ins->block() != block()) {
2413 return false;
2414 }
2415
2416 return congruentIfOperandsEqual(ins);
2417 }
2418
2419 void MPhi::updateForReplacement(MPhi* other) {
2420 // This function is called to fix the current Phi flags using it as a
2421 // replacement of the other Phi instruction |other|.
2422 //
2423 // When dealing with usage analysis, any Use will replace all other values,
2424 // such as Unused and Unknown. Unless both are Unused, the merge would be
2425 // Unknown.
2426 if (usageAnalysis_ == PhiUsage::Used ||
2427 other->usageAnalysis_ == PhiUsage::Used) {
2428 usageAnalysis_ = PhiUsage::Used;
2429 } else if (usageAnalysis_ != other->usageAnalysis_) {
2430 // this == unused && other == unknown
2431 // or this == unknown && other == unused
2432 usageAnalysis_ = PhiUsage::Unknown;
2433 } else {
2434 // this == unused && other == unused
2435 // or this == unknown && other = unknown
2436 MOZ_ASSERT(usageAnalysis_ == PhiUsage::Unused ||
2437 usageAnalysis_ == PhiUsage::Unknown);
2438 MOZ_ASSERT(usageAnalysis_ == other->usageAnalysis_);
2439 }
2440 }
2441
2442 /* static */
2443 bool MPhi::markIteratorPhis(const PhiVector& iterators) {
2444 // Find and mark phis that must transitively hold an iterator live.
2445
2446 Vector<MPhi*, 8, SystemAllocPolicy> worklist;
2447
2448 for (MPhi* iter : iterators) {
2449 if (!iter->isInWorklist()) {
2450 if (!worklist.append(iter)) {
2451 return false;
2452 }
2453 iter->setInWorklist();
2454 }
2455 }
2456
2457 while (!worklist.empty()) {
2458 MPhi* phi = worklist.popCopy();
2459 phi->setNotInWorklist();
2460
2461 phi->setIterator();
2462 phi->setImplicitlyUsedUnchecked();
2463
2464 for (MUseDefIterator iter(phi); iter; iter++) {
2465 MDefinition* use = iter.def();
2466 if (!use->isInWorklist() && use->isPhi() && !use->toPhi()->isIterator()) {
2467 if (!worklist.append(use->toPhi())) {
2468 return false;
2469 }
2470 use->setInWorklist();
2471 }
2472 }
2473 }
2474
2475 return true;
2476 }
2477
2478 bool MPhi::typeIncludes(MDefinition* def) {
2479 MOZ_ASSERT(!IsMagicType(def->type()));
2480
2481 if (def->type() == this->type()) {
2482 return true;
2483 }
2484
2485 // This phi must be able to be any value.
2486 if (this->type() == MIRType::Value) {
2487 return true;
2488 }
2489
2490 if (def->type() == MIRType::Int32 && this->type() == MIRType::Double) {
2491 return true;
2492 }
2493
2494 return false;
2495 }
2496
2497 void MCallBase::addArg(size_t argnum, MDefinition* arg) {
2498 // The operand vector is initialized in reverse order by WarpBuilder.
2499 // It cannot be checked for consistency until all arguments are added.
2500 // FixedList doesn't initialize its elements, so do an unchecked init.
2501 initOperand(argnum + NumNonArgumentOperands, arg);
2502 }
2503
2504 static inline bool IsConstant(MDefinition* def, double v) {
2505 if (!def->isConstant()) {
2506 return false;
2507 }
2508
2509 return NumbersAreIdentical(def->toConstant()->numberToDouble(), v);
2510 }
2511
2512 MDefinition* MBinaryBitwiseInstruction::foldsTo(TempAllocator& alloc) {
2513 // Identity operations are removed (for int32 only) in foldUnnecessaryBitop.
2514
2515 if (type() == MIRType::Int32) {
2516 if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
2517 return folded;
2518 }
2519 } else if (type() == MIRType::Int64) {
2520 if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
2521 return folded;
2522 }
2523 }
2524
2525 return this;
2526 }
2527
2528 MDefinition* MBinaryBitwiseInstruction::foldUnnecessaryBitop() {
2529 // It's probably OK to perform this optimization only for int32, as it will
2530 // have the greatest effect for asm.js code that is compiled with the JS
2531 // pipeline, and that code will not see int64 values.
2532
2533 if (type() != MIRType::Int32) {
2534 return this;
2535 }
2536
2537 // Fold unsigned shift right operator when the second operand is zero and
2538 // the only use is an unsigned modulo. Thus, the expression
2539 // |(x >>> 0) % y| becomes |x % y|.
2540 if (isUrsh() && IsUint32Type(this)) {
2541 MDefinition* defUse = maybeSingleDefUse();
2542 if (defUse && defUse->isMod() && defUse->toMod()->isUnsigned()) {
2543 return getOperand(0);
2544 }
2545 }
2546
2547 // Eliminate bitwise operations that are no-ops when used on integer
2548 // inputs, such as (x | 0).
2549
2550 MDefinition* lhs = getOperand(0);
2551 MDefinition* rhs = getOperand(1);
2552
2553 if (IsConstant(lhs, 0)) {
2554 return foldIfZero(0);
2555 }
2556
2557 if (IsConstant(rhs, 0)) {
2558 return foldIfZero(1);
2559 }
2560
2561 if (IsConstant(lhs, -1)) {
2562 return foldIfNegOne(0);
2563 }
2564
2565 if (IsConstant(rhs, -1)) {
2566 return foldIfNegOne(1);
2567 }
2568
2569 if (lhs == rhs) {
2570 return foldIfEqual();
2571 }
2572
2573 if (maskMatchesRightRange) {
2574 MOZ_ASSERT(lhs->isConstant());
2575 MOZ_ASSERT(lhs->type() == MIRType::Int32);
2576 return foldIfAllBitsSet(0);
2577 }
2578
2579 if (maskMatchesLeftRange) {
2580 MOZ_ASSERT(rhs->isConstant());
2581 MOZ_ASSERT(rhs->type() == MIRType::Int32);
2582 return foldIfAllBitsSet(1);
2583 }
2584
2585 return this;
2586 }
2587
2588 static inline bool CanProduceNegativeZero(MDefinition* def) {
2589 // Test if this instruction can produce negative zero even when bailing out
2590 // and changing types.
2591 switch (def->op()) {
2592 case MDefinition::Opcode::Constant:
2593 if (def->type() == MIRType::Double &&
2594 def->toConstant()->toDouble() == -0.0) {
2595 return true;
2596 }
2597 [[fallthrough]];
2598 case MDefinition::Opcode::BitAnd:
2599 case MDefinition::Opcode::BitOr:
2600 case MDefinition::Opcode::BitXor:
2601 case MDefinition::Opcode::BitNot:
2602 case MDefinition::Opcode::Lsh:
2603 case MDefinition::Opcode::Rsh:
2604 return false;
2605 default:
2606 return true;
2607 }
2608 }
2609
2610 static inline bool NeedNegativeZeroCheck(MDefinition* def) {
2611 if (def->isGuard() || def->isGuardRangeBailouts()) {
2612 return true;
2613 }
2614
2615 // Test if all uses have the same semantics for -0 and 0
2616 for (MUseIterator use = def->usesBegin(); use != def->usesEnd(); use++) {
2617 if (use->consumer()->isResumePoint()) {
2618 return true;
2619 }
2620
2621 MDefinition* use_def = use->consumer()->toDefinition();
2622 switch (use_def->op()) {
2623 case MDefinition::Opcode::Add: {
2624 // If add is truncating -0 and 0 are observed as the same.
2625 if (use_def->toAdd()->isTruncated()) {
2626 break;
2627 }
2628
2629 // x + y gives -0, when both x and y are -0
2630
2631 // Figure out the order in which the addition's operands will
2632 // execute. EdgeCaseAnalysis::analyzeLate has renumbered the MIR
2633 // definitions for us so that this just requires comparing ids.
2634 MDefinition* first = use_def->toAdd()->lhs();
2635 MDefinition* second = use_def->toAdd()->rhs();
2636 if (first->id() > second->id()) {
2637 std::swap(first, second);
2638 }
2639 // Negative zero checks can be removed on the first executed
2640 // operand only if it is guaranteed the second executed operand
2641 // will produce a value other than -0. While the second is
2642 // typed as an int32, a bailout taken between execution of the
2643 // operands may change that type and cause a -0 to flow to the
2644 // second.
2645 //
2646 // There is no way to test whether there are any bailouts
2647 // between execution of the operands, so remove negative
2648 // zero checks from the first only if the second's type is
2649 // independent from type changes that may occur after bailing.
2650 if (def == first && CanProduceNegativeZero(second)) {
2651 return true;
2652 }
2653
2654 // The negative zero check can always be removed on the second
2655 // executed operand; by the time this executes the first will have
2656 // been evaluated as int32 and the addition's result cannot be -0.
2657 break;
2658 }
2659 case MDefinition::Opcode::Sub: {
2660 // If sub is truncating -0 and 0 are observed as the same
2661 if (use_def->toSub()->isTruncated()) {
2662 break;
2663 }
2664
2665 // x + y gives -0, when x is -0 and y is 0
2666
2667 // We can remove the negative zero check on the rhs, only if we
2668 // are sure the lhs isn't negative zero.
2669
2670 // The lhs is typed as integer (i.e. not -0.0), but it can bailout
2671 // and change type. This should be fine if the lhs is executed
2672 // first. However if the rhs is executed first, the lhs can bail,
2673 // change type and become -0.0 while the rhs has already been
2674 // optimized to not make a difference between zero and negative zero.
2675 MDefinition* lhs = use_def->toSub()->lhs();
2676 MDefinition* rhs = use_def->toSub()->rhs();
2677 if (rhs->id() < lhs->id() && CanProduceNegativeZero(lhs)) {
2678 return true;
2679 }
2680
2681 [[fallthrough]];
2682 }
2683 case MDefinition::Opcode::StoreElement:
2684 case MDefinition::Opcode::StoreHoleValueElement:
2685 case MDefinition::Opcode::LoadElement:
2686 case MDefinition::Opcode::LoadElementHole:
2687 case MDefinition::Opcode::LoadUnboxedScalar:
2688 case MDefinition::Opcode::LoadDataViewElement:
2689 case MDefinition::Opcode::LoadTypedArrayElementHole:
2690 case MDefinition::Opcode::CharCodeAt:
2691 case MDefinition::Opcode::Mod:
2692 case MDefinition::Opcode::InArray:
2693 // Only allowed to remove check when definition is the second operand
2694 if (use_def->getOperand(0) == def) {
2695 return true;
2696 }
2697 for (size_t i = 2, e = use_def->numOperands(); i < e; i++) {
2698 if (use_def->getOperand(i) == def) {
2699 return true;
2700 }
2701 }
2702 break;
2703 case MDefinition::Opcode::BoundsCheck:
2704 // Only allowed to remove check when definition is the first operand
2705 if (use_def->toBoundsCheck()->getOperand(1) == def) {
2706 return true;
2707 }
2708 break;
2709 case MDefinition::Opcode::ToString:
2710 case MDefinition::Opcode::FromCharCode:
2711 case MDefinition::Opcode::FromCodePoint:
2712 case MDefinition::Opcode::TableSwitch:
2713 case MDefinition::Opcode::Compare:
2714 case MDefinition::Opcode::BitAnd:
2715 case MDefinition::Opcode::BitOr:
2716 case MDefinition::Opcode::BitXor:
2717 case MDefinition::Opcode::Abs:
2718 case MDefinition::Opcode::TruncateToInt32:
2719 // Always allowed to remove check. No matter which operand.
2720 break;
2721 case MDefinition::Opcode::StoreElementHole:
2722 case MDefinition::Opcode::StoreTypedArrayElementHole:
2723 case MDefinition::Opcode::PostWriteElementBarrier:
2724 // Only allowed to remove check when definition is the third operand.
2725 for (size_t i = 0, e = use_def->numOperands(); i < e; i++) {
2726 if (i == 2) {
2727 continue;
2728 }
2729 if (use_def->getOperand(i) == def) {
2730 return true;
2731 }
2732 }
2733 break;
2734 default:
2735 return true;
2736 }
2737 }
2738 return false;
2739 }
2740
2741 #ifdef JS_JITSPEW
2742 void MBinaryArithInstruction::printOpcode(GenericPrinter& out) const {
2743 MDefinition::printOpcode(out);
2744
2745 switch (type()) {
2746 case MIRType::Int32:
2747 if (isDiv()) {
2748 out.printf(" [%s]", toDiv()->isUnsigned() ? "uint32" : "int32");
2749 } else if (isMod()) {
2750 out.printf(" [%s]", toMod()->isUnsigned() ? "uint32" : "int32");
2751 } else {
2752 out.printf(" [int32]");
2753 }
2754 break;
2755 case MIRType::Int64:
2756 if (isDiv()) {
2757 out.printf(" [%s]", toDiv()->isUnsigned() ? "uint64" : "int64");
2758 } else if (isMod()) {
2759 out.printf(" [%s]", toMod()->isUnsigned() ? "uint64" : "int64");
2760 } else {
2761 out.printf(" [int64]");
2762 }
2763 break;
2764 case MIRType::Float32:
2765 out.printf(" [float]");
2766 break;
2767 case MIRType::Double:
2768 out.printf(" [double]");
2769 break;
2770 default:
2771 break;
2772 }
2773 }
2774 #endif
2775
2776 MDefinition* MRsh::foldsTo(TempAllocator& alloc) {
2777 MDefinition* f = MBinaryBitwiseInstruction::foldsTo(alloc);
2778
2779 if (f != this) {
2780 return f;
2781 }
2782
2783 MDefinition* lhs = getOperand(0);
2784 MDefinition* rhs = getOperand(1);
2785
2786 // It's probably OK to perform this optimization only for int32, as it will
2787 // have the greatest effect for asm.js code that is compiled with the JS
2788 // pipeline, and that code will not see int64 values.
2789
2790 if (!lhs->isLsh() || !rhs->isConstant() || rhs->type() != MIRType::Int32) {
2791 return this;
2792 }
2793
2794 if (!lhs->getOperand(1)->isConstant() ||
2795 lhs->getOperand(1)->type() != MIRType::Int32) {
2796 return this;
2797 }
2798
2799 uint32_t shift = rhs->toConstant()->toInt32();
2800 uint32_t shift_lhs = lhs->getOperand(1)->toConstant()->toInt32();
2801 if (shift != shift_lhs) {
2802 return this;
2803 }
2804
2805 switch (shift) {
2806 case 16:
2807 return MSignExtendInt32::New(alloc, lhs->getOperand(0),
2808 MSignExtendInt32::Half);
2809 case 24:
2810 return MSignExtendInt32::New(alloc, lhs->getOperand(0),
2811 MSignExtendInt32::Byte);
2812 }
2813
2814 return this;
2815 }
2816
2817 MDefinition* MBinaryArithInstruction::foldsTo(TempAllocator& alloc) {
2818 MOZ_ASSERT(IsNumberType(type()));
2819
2820 MDefinition* lhs = getOperand(0);
2821 MDefinition* rhs = getOperand(1);
2822
2823 if (type() == MIRType::Int64) {
2824 MOZ_ASSERT(!isTruncated());
2825
2826 if (MConstant* folded = EvaluateInt64ConstantOperands(alloc, this)) {
2827 if (!folded->block()) {
2828 block()->insertBefore(this, folded);
2829 }
2830 return folded;
2831 }
2832 if (isSub() || isDiv() || isMod()) {
2833 return this;
2834 }
2835 if (rhs->isConstant() &&
2836 rhs->toConstant()->toInt64() == int64_t(getIdentity())) {
2837 return lhs;
2838 }
2839 if (lhs->isConstant() &&
2840 lhs->toConstant()->toInt64() == int64_t(getIdentity())) {
2841 return rhs;
2842 }
2843 return this;
2844 }
2845
2846 if (MConstant* folded = EvaluateConstantOperands(alloc, this)) {
2847 if (isTruncated()) {
2848 if (!folded->block()) {
2849 block()->insertBefore(this, folded);
2850 }
2851 if (folded->type() != MIRType::Int32) {
2852 return MTruncateToInt32::New(alloc, folded);
2853 }
2854 }
2855 return folded;
2856 }
2857
2858 if (MConstant* folded = EvaluateConstantNaNOperand(this)) {
2859 MOZ_ASSERT(!isTruncated());
2860 return folded;
2861 }
2862
2863 if (mustPreserveNaN_) {
2864 return this;
2865 }
2866
2867 // 0 + -0 = 0. So we can't remove addition
2868 if (isAdd() && type() != MIRType::Int32) {
2869 return this;
2870 }
2871
2872 if (IsConstant(rhs, getIdentity())) {
2873 if (isTruncated()) {
2874 return MTruncateToInt32::New(alloc, lhs);
2875 }
2876 return lhs;
2877 }
2878
2879 // subtraction isn't commutative. So we can't remove subtraction when lhs
2880 // equals 0
2881 if (isSub()) {
2882 return this;
2883 }
2884
2885 if (IsConstant(lhs, getIdentity())) {
2886 if (isTruncated()) {
2887 return MTruncateToInt32::New(alloc, rhs);
2888 }
2889 return rhs; // id op x => x
2890 }
2891
2892 return this;
2893 }
2894
2895 void MBinaryArithInstruction::trySpecializeFloat32(TempAllocator& alloc) {
2896 MOZ_ASSERT(IsNumberType(type()));
2897
2898 // Do not use Float32 if we can use int32.
2899 if (type() == MIRType::Int32) {
2900 return;
2901 }
2902
2903 if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
2904 setResultType(MIRType::Float32);
2905 }
2906 }
2907
2908 void MMinMax::trySpecializeFloat32(TempAllocator& alloc) {
2909 if (type() == MIRType::Int32) {
2910 return;
2911 }
2912
2913 MDefinition* left = lhs();
2914 MDefinition* right = rhs();
2915
2916 if ((left->canProduceFloat32() ||
2917 (left->isMinMax() && left->type() == MIRType::Float32)) &&
2918 (right->canProduceFloat32() ||
2919 (right->isMinMax() && right->type() == MIRType::Float32))) {
2920 setResultType(MIRType::Float32);
2921 } else {
2922 ConvertOperandsToDouble(this, alloc);
2923 }
2924 }
2925
2926 MDefinition* MMinMax::foldsTo(TempAllocator& alloc) {
2927 MOZ_ASSERT(lhs()->type() == type());
2928 MOZ_ASSERT(rhs()->type() == type());
2929
2930 if (lhs() == rhs()) {
2931 return lhs();
2932 }
2933
2934 auto foldConstants = [&alloc](MDefinition* lhs, MDefinition* rhs,
2935 bool isMax) -> MConstant* {
2936 MOZ_ASSERT(lhs->type() == rhs->type());
2937 MOZ_ASSERT(lhs->toConstant()->isTypeRepresentableAsDouble());
2938 MOZ_ASSERT(rhs->toConstant()->isTypeRepresentableAsDouble());
2939
2940 double lnum = lhs->toConstant()->numberToDouble();
2941 double rnum = rhs->toConstant()->numberToDouble();
2942
2943 double result;
2944 if (isMax) {
2945 result = js::math_max_impl(lnum, rnum);
2946 } else {
2947 result = js::math_min_impl(lnum, rnum);
2948 }
2949
2950 // The folded MConstant should maintain the same MIRType with the original
2951 // inputs.
2952 if (lhs->type() == MIRType::Int32) {
2953 int32_t cast;
2954 if (mozilla::NumberEqualsInt32(result, &cast)) {
2955 return MConstant::New(alloc, Int32Value(cast));
2956 }
2957 return nullptr;
2958 }
2959 if (lhs->type() == MIRType::Float32) {
2960 return MConstant::NewFloat32(alloc, result);
2961 }
2962 MOZ_ASSERT(lhs->type() == MIRType::Double);
2963 return MConstant::New(alloc, DoubleValue(result));
2964 };
2965
2966 // Try to fold the following patterns when |x| and |y| are constants.
2967 //
2968 // min(min(x, z), min(y, z)) = min(min(x, y), z)
2969 // max(max(x, z), max(y, z)) = max(max(x, y), z)
2970 // max(min(x, z), min(y, z)) = min(max(x, y), z)
2971 // min(max(x, z), max(y, z)) = max(min(x, y), z)
2972 if (lhs()->isMinMax() && rhs()->isMinMax()) {
2973 do {
2974 auto* left = lhs()->toMinMax();
2975 auto* right = rhs()->toMinMax();
2976 if (left->isMax() != right->isMax()) {
2977 break;
2978 }
2979
2980 MDefinition* x;
2981 MDefinition* y;
2982 MDefinition* z;
2983 if (left->lhs() == right->lhs()) {
2984 std::tie(x, y, z) = std::tuple{left->rhs(), right->rhs(), left->lhs()};
2985 } else if (left->lhs() == right->rhs()) {
2986 std::tie(x, y, z) = std::tuple{left->rhs(), right->lhs(), left->lhs()};
2987 } else if (left->rhs() == right->lhs()) {
2988 std::tie(x, y, z) = std::tuple{left->lhs(), right->rhs(), left->rhs()};
2989 } else if (left->rhs() == right->rhs()) {
2990 std::tie(x, y, z) = std::tuple{left->lhs(), right->lhs(), left->rhs()};
2991 } else {
2992 break;
2993 }
2994
2995 if (!x->isConstant() || !x->toConstant()->isTypeRepresentableAsDouble() ||
2996 !y->isConstant() || !y->toConstant()->isTypeRepresentableAsDouble()) {
2997 break;
2998 }
2999
3000 if (auto* folded = foldConstants(x, y, isMax())) {
3001 block()->insertBefore(this, folded);
3002 return MMinMax::New(alloc, folded, z, type(), left->isMax());
3003 }
3004 } while (false);
3005 }
3006
3007 // Fold min/max operations with same inputs.
3008 if (lhs()->isMinMax() || rhs()->isMinMax()) {
3009 auto* other = lhs()->isMinMax() ? lhs()->toMinMax() : rhs()->toMinMax();
3010 auto* operand = lhs()->isMinMax() ? rhs() : lhs();
3011
3012 if (operand == other->lhs() || operand == other->rhs()) {
3013 if (isMax() == other->isMax()) {
3014 // min(x, min(x, y)) = min(x, y)
3015 // max(x, max(x, y)) = max(x, y)
3016 return other;
3017 }
3018 if (!IsFloatingPointType(type())) {
3019 // When neither value is NaN:
3020 // max(x, min(x, y)) = x
3021 // min(x, max(x, y)) = x
3022
3023 // Ensure that any bailouts that we depend on to guarantee that |y| is
3024 // Int32 are not removed.
3025 auto* otherOp = operand == other->lhs() ? other->rhs() : other->lhs();
3026 otherOp->setGuardRangeBailoutsUnchecked();
3027
3028 return operand;
3029 }
3030 }
3031 }
3032
3033 if (!lhs()->isConstant() && !rhs()->isConstant()) {
3034 return this;
3035 }
3036
3037 // Directly apply math utility to compare the rhs() and lhs() when
3038 // they are both constants.
3039 if (lhs()->isConstant() && rhs()->isConstant()) {
3040 if (!lhs()->toConstant()->isTypeRepresentableAsDouble() ||
3041 !rhs()->toConstant()->isTypeRepresentableAsDouble()) {
3042 return this;
3043 }
3044
3045 if (auto* folded = foldConstants(lhs(), rhs(), isMax())) {
3046 return folded;
3047 }
3048 }
3049
3050 MDefinition* operand = lhs()->isConstant() ? rhs() : lhs();
3051 MConstant* constant =
3052 lhs()->isConstant() ? lhs()->toConstant() : rhs()->toConstant();
3053
3054 if (operand->isToDouble() &&
3055 operand->getOperand(0)->type() == MIRType::Int32) {
3056 // min(int32, cte >= INT32_MAX) = int32
3057 if (!isMax() && constant->isTypeRepresentableAsDouble() &&
3058 constant->numberToDouble() >= INT32_MAX) {
3059 MLimitedTruncate* limit = MLimitedTruncate::New(
3060 alloc, operand->getOperand(0), TruncateKind::NoTruncate);
3061 block()->insertBefore(this, limit);
3062 MToDouble* toDouble = MToDouble::New(alloc, limit);
3063 return toDouble;
3064 }
3065
3066 // max(int32, cte <= INT32_MIN) = int32
3067 if (isMax() && constant->isTypeRepresentableAsDouble() &&
3068 constant->numberToDouble() <= INT32_MIN) {
3069 MLimitedTruncate* limit = MLimitedTruncate::New(
3070 alloc, operand->getOperand(0), TruncateKind::NoTruncate);
3071 block()->insertBefore(this, limit);
3072 MToDouble* toDouble = MToDouble::New(alloc, limit);
3073 return toDouble;
3074 }
3075 }
3076
3077 auto foldLength = [](MDefinition* operand, MConstant* constant,
3078 bool isMax) -> MDefinition* {
3079 if ((operand->isArrayLength() || operand->isArrayBufferViewLength() ||
3080 operand->isArgumentsLength() || operand->isStringLength()) &&
3081 constant->type() == MIRType::Int32) {
3082 // (Array|ArrayBufferView|Arguments|String)Length is always >= 0.
3083 // max(array.length, cte <= 0) = array.length
3084 // min(array.length, cte <= 0) = cte
3085 if (constant->toInt32() <= 0) {
3086 return isMax ? operand : constant;
3087 }
3088 }
3089 return nullptr;
3090 };
3091
3092 if (auto* folded = foldLength(operand, constant, isMax())) {
3093 return folded;
3094 }
3095
3096 // Attempt to fold nested min/max operations which are produced by
3097 // self-hosted built-in functions.
3098 if (operand->isMinMax()) {
3099 auto* other = operand->toMinMax();
3100 MOZ_ASSERT(other->lhs()->type() == type());
3101 MOZ_ASSERT(other->rhs()->type() == type());
3102
3103 MConstant* otherConstant = nullptr;
3104 MDefinition* otherOperand = nullptr;
3105 if (other->lhs()->isConstant()) {
3106 otherConstant = other->lhs()->toConstant();
3107 otherOperand = other->rhs();
3108 } else if (other->rhs()->isConstant()) {
3109 otherConstant = other->rhs()->toConstant();
3110 otherOperand = other->lhs();
3111 }
3112
3113 if (otherConstant && constant->isTypeRepresentableAsDouble() &&
3114 otherConstant->isTypeRepresentableAsDouble()) {
3115 if (isMax() == other->isMax()) {
3116 // Fold min(x, min(y, z)) to min(min(x, y), z) with constant min(x, y).
3117 // Fold max(x, max(y, z)) to max(max(x, y), z) with constant max(x, y).
3118 if (auto* left = foldConstants(constant, otherConstant, isMax())) {
3119 block()->insertBefore(this, left);
3120 return MMinMax::New(alloc, left, otherOperand, type(), isMax());
3121 }
3122 } else {
3123 // Fold min(x, max(y, z)) to max(min(x, y), min(x, z)).
3124 // Fold max(x, min(y, z)) to min(max(x, y), max(x, z)).
3125 //
3126 // But only do this when min(x, z) can also be simplified.
3127 if (auto* right = foldLength(otherOperand, constant, isMax())) {
3128 if (auto* left = foldConstants(constant, otherConstant, isMax())) {
3129 block()->insertBefore(this, left);
3130 return MMinMax::New(alloc, left, right, type(), !isMax());
3131 }
3132 }
3133 }
3134 }
3135 }
3136
3137 return this;
3138 }
3139
3140 #ifdef JS_JITSPEW
3141 void MMinMax::printOpcode(GenericPrinter& out) const {
3142 MDefinition::printOpcode(out);
3143 out.printf(" (%s)", isMax() ? "max" : "min");
3144 }
3145
3146 void MMinMaxArray::printOpcode(GenericPrinter& out) const {
3147 MDefinition::printOpcode(out);
3148 out.printf(" (%s)", isMax() ? "max" : "min");
3149 }
3150 #endif
3151
3152 MDefinition* MPow::foldsConstant(TempAllocator& alloc) {
3153 // Both `x` and `p` in `x^p` must be constants in order to precompute.
3154 if (!input()->isConstant() || !power()->isConstant()) {
3155 return nullptr;
3156 }
3157 if (!power()->toConstant()->isTypeRepresentableAsDouble()) {
3158 return nullptr;
3159 }
3160 if (!input()->toConstant()->isTypeRepresentableAsDouble()) {
3161 return nullptr;
3162 }
3163
3164 double x = input()->toConstant()->numberToDouble();
3165 double p = power()->toConstant()->numberToDouble();
3166 double result = js::ecmaPow(x, p);
3167 if (type() == MIRType::Int32) {
3168 int32_t cast;
3169 if (!mozilla::NumberIsInt32(result, &cast)) {
3170 // Reject folding if the result isn't an int32, because we'll bail anyway.
3171 return nullptr;
3172 }
3173 return MConstant::New(alloc, Int32Value(cast));
3174 }
3175 return MConstant::New(alloc, DoubleValue(result));
3176 }
3177
3178 MDefinition* MPow::foldsConstantPower(TempAllocator& alloc) {
3179 // If `p` in `x^p` isn't constant, we can't apply these folds.
3180 if (!power()->isConstant()) {
3181 return nullptr;
3182 }
3183 if (!power()->toConstant()->isTypeRepresentableAsDouble()) {
3184 return nullptr;
3185 }
3186
3187 MOZ_ASSERT(type() == MIRType::Double || type() == MIRType::Int32);
3188
3189 // NOTE: The optimizations must match the optimizations used in |js::ecmaPow|
3190 // resp. |js::powi| to avoid differential testing issues.
3191
3192 double pow = power()->toConstant()->numberToDouble();
3193
3194 // Math.pow(x, 0.5) is a sqrt with edge-case detection.
3195 if (pow == 0.5) {
3196 MOZ_ASSERT(type() == MIRType::Double);
3197 return MPowHalf::New(alloc, input());
3198 }
3199
3200 // Math.pow(x, -0.5) == 1 / Math.pow(x, 0.5), even for edge cases.
3201 if (pow == -0.5) {
3202 MOZ_ASSERT(type() == MIRType::Double);
3203 MPowHalf* half = MPowHalf::New(alloc, input());
3204 block()->insertBefore(this, half);
3205 MConstant* one = MConstant::New(alloc, DoubleValue(1.0));
3206 block()->insertBefore(this, one);
3207 return MDiv::New(alloc, one, half, MIRType::Double);
3208 }
3209
3210 // Math.pow(x, 1) == x.
3211 if (pow == 1.0) {
3212 return input();
3213 }
3214
3215 auto multiply = [this, &alloc](MDefinition* lhs, MDefinition* rhs) {
3216 MMul* mul = MMul::New(alloc, lhs, rhs, type());
3217 mul->setBailoutKind(bailoutKind());
3218
3219 // Multiplying the same number can't yield negative zero.
3220 mul->setCanBeNegativeZero(lhs != rhs && canBeNegativeZero());
3221 return mul;
3222 };
3223
3224 // Math.pow(x, 2) == x*x.
3225 if (pow == 2.0) {
3226 return multiply(input(), input());
3227 }
3228
3229 // Math.pow(x, 3) == x*x*x.
3230 if (pow == 3.0) {
3231 MMul* mul1 = multiply(input(), input());
3232 block()->insertBefore(this, mul1);
3233 return multiply(input(), mul1);
3234 }
3235
3236 // Math.pow(x, 4) == y*y, where y = x*x.
3237 if (pow == 4.0) {
3238 MMul* y = multiply(input(), input());
3239 block()->insertBefore(this, y);
3240 return multiply(y, y);
3241 }
3242
3243 // Math.pow(x, NaN) == NaN.
3244 if (std::isnan(pow)) {
3245 return power();
3246 }
3247
3248 // No optimization
3249 return nullptr;
3250 }
3251
3252 MDefinition* MPow::foldsTo(TempAllocator& alloc) {
3253 if (MDefinition* def = foldsConstant(alloc)) {
3254 return def;
3255 }
3256 if (MDefinition* def = foldsConstantPower(alloc)) {
3257 return def;
3258 }
3259 return this;
3260 }
3261
3262 MDefinition* MBigIntPow::foldsTo(TempAllocator& alloc) {
3263 auto* base = lhs();
3264 MOZ_ASSERT(base->type() == MIRType::BigInt);
3265
3266 auto* power = rhs();
3267 MOZ_ASSERT(power->type() == MIRType::BigInt);
3268
3269 // |power| must be a constant.
3270 if (!power->isConstant()) {
3271 return this;
3272 }
3273
3274 int32_t pow;
3275 if (BigInt::isInt32(power->toConstant()->toBigInt(), &pow)) {
3276 // x ** 1n == x.
3277 if (pow == 1) {
3278 return base;
3279 }
3280
3281 // x ** 2n == x*x.
3282 if (pow == 2) {
3283 auto* mul = MBigIntMul::New(alloc, base, base);
3284 mul->setBailoutKind(bailoutKind());
3285 return mul;
3286 }
3287 }
3288
3289 // No optimization
3290 return this;
3291 }
3292
3293 MDefinition* MBigIntAsIntN::foldsTo(TempAllocator& alloc) {
3294 auto* bitsDef = bits();
3295 if (!bitsDef->isConstant()) {
3296 return this;
3297 }
3298
3299 // Negative |bits| throw an error and too large |bits| don't fit into Int64.
3300 int32_t bitsInt = bitsDef->toConstant()->toInt32();
3301 if (bitsInt < 0 || bitsInt > 64) {
3302 return this;
3303 }
3304
3305 // Prefer sign-extension if possible.
3306 bool canSignExtend = false;
3307 switch (bitsInt) {
3308 case 8:
3309 case 16:
3310 case 32:
3311 case 64:
3312 canSignExtend = true;
3313 break;
3314 }
3315
3316 // Ensure the input is either IntPtr or Int64 typed.
3317 auto* inputDef = input();
3318 if (inputDef->isIntPtrToBigInt()) {
3319 inputDef = inputDef->toIntPtrToBigInt()->input();
3320
3321 if (!canSignExtend) {
3322 auto* int64 = MIntPtrToInt64::New(alloc, inputDef);
3323 block()->insertBefore(this, int64);
3324 inputDef = int64;
3325 }
3326 } else if (inputDef->isInt64ToBigInt()) {
3327 inputDef = inputDef->toInt64ToBigInt()->input();
3328 } else {
3329 auto* truncate = MTruncateBigIntToInt64::New(alloc, inputDef);
3330 block()->insertBefore(this, truncate);
3331 inputDef = truncate;
3332 }
3333
3334 if (inputDef->type() == MIRType::IntPtr) {
3335 MOZ_ASSERT(canSignExtend);
3336
3337 // If |bits| is larger-or-equal to |BigInt::DigitBits|, return the input.
3338 if (size_t(bitsInt) >= BigInt::DigitBits) {
3339 auto* limited = MIntPtrLimitedTruncate::New(alloc, inputDef);
3340 block()->insertBefore(this, limited);
3341 inputDef = limited;
3342 } else {
3343 MOZ_ASSERT(bitsInt < 64);
3344
3345 // Otherwise extension is the way to go.
3346 MSignExtendIntPtr::Mode mode;
3347 switch (bitsInt) {
3348 case 8:
3349 mode = MSignExtendIntPtr::Byte;
3350 break;
3351 case 16:
3352 mode = MSignExtendIntPtr::Half;
3353 break;
3354 case 32:
3355 mode = MSignExtendIntPtr::Word;
3356 break;
3357 }
3358
3359 auto* extend = MSignExtendIntPtr::New(alloc, inputDef, mode);
3360 block()->insertBefore(this, extend);
3361 inputDef = extend;
3362 }
3363
3364 return MIntPtrToBigInt::New(alloc, inputDef);
3365 }
3366 MOZ_ASSERT(inputDef->type() == MIRType::Int64);
3367
3368 if (canSignExtend) {
3369 // If |bits| is equal to 64, return the input.
3370 if (bitsInt == 64) {
3371 auto* limited = MInt64LimitedTruncate::New(alloc, inputDef);
3372 block()->insertBefore(this, limited);
3373 inputDef = limited;
3374 } else {
3375 MOZ_ASSERT(bitsInt < 64);
3376
3377 // Otherwise extension is the way to go.
3378 MSignExtendInt64::Mode mode;
3379 switch (bitsInt) {
3380 case 8:
3381 mode = MSignExtendInt64::Byte;
3382 break;
3383 case 16:
3384 mode = MSignExtendInt64::Half;
3385 break;
3386 case 32:
3387 mode = MSignExtendInt64::Word;
3388 break;
3389 }
3390
3391 auto* extend = MSignExtendInt64::New(alloc, inputDef, mode);
3392 block()->insertBefore(this, extend);
3393 inputDef = extend;
3394 }
3395 } else {
3396 MOZ_ASSERT(bitsInt < 64);
3397
3398 uint64_t mask = 0;
3399 if (bitsInt > 0) {
3400 mask = uint64_t(-1) >> (64 - bitsInt);
3401 }
3402
3403 auto* cst = MConstant::NewInt64(alloc, int64_t(mask));
3404 block()->insertBefore(this, cst);
3405
3406 // Mask off any excess bits.
3407 auto* bitAnd = MBitAnd::New(alloc, inputDef, cst, MIRType::Int64);
3408 block()->insertBefore(this, bitAnd);
3409
3410 auto* shift = MConstant::NewInt64(alloc, int64_t(64 - bitsInt));
3411 block()->insertBefore(this, shift);
3412
3413 // Left-shift to make the sign-bit the left-most bit.
3414 auto* lsh = MLsh::New(alloc, bitAnd, shift, MIRType::Int64);
3415 block()->insertBefore(this, lsh);
3416
3417 // Right-shift to propagate the sign-bit.
3418 auto* rsh = MRsh::New(alloc, lsh, shift, MIRType::Int64);
3419 block()->insertBefore(this, rsh);
3420
3421 inputDef = rsh;
3422 }
3423
3424 return MInt64ToBigInt::New(alloc, inputDef, /* isSigned = */ true);
3425 }
3426
3427 MDefinition* MBigIntAsUintN::foldsTo(TempAllocator& alloc) {
3428 auto* bitsDef = bits();
3429 if (!bitsDef->isConstant()) {
3430 return this;
3431 }
3432
3433 // Negative |bits| throw an error and too large |bits| don't fit into Int64.
3434 int32_t bitsInt = bitsDef->toConstant()->toInt32();
3435 if (bitsInt < 0 || bitsInt > 64) {
3436 return this;
3437 }
3438
3439 // Ensure the input is Int64 typed.
3440 auto* inputDef = input();
3441 if (inputDef->isIntPtrToBigInt()) {
3442 inputDef = inputDef->toIntPtrToBigInt()->input();
3443
3444 auto* int64 = MIntPtrToInt64::New(alloc, inputDef);
3445 block()->insertBefore(this, int64);
3446 inputDef = int64;
3447 } else if (inputDef->isInt64ToBigInt()) {
3448 inputDef = inputDef->toInt64ToBigInt()->input();
3449 } else {
3450 auto* truncate = MTruncateBigIntToInt64::New(alloc, inputDef);
3451 block()->insertBefore(this, truncate);
3452 inputDef = truncate;
3453 }
3454 MOZ_ASSERT(inputDef->type() == MIRType::Int64);
3455
3456 if (bitsInt < 64) {
3457 uint64_t mask = 0;
3458 if (bitsInt > 0) {
3459 mask = uint64_t(-1) >> (64 - bitsInt);
3460 }
3461
3462 // Mask off any excess bits.
3463 auto* cst = MConstant::NewInt64(alloc, int64_t(mask));
3464 block()->insertBefore(this, cst);
3465
3466 auto* bitAnd = MBitAnd::New(alloc, inputDef, cst, MIRType::Int64);
3467 block()->insertBefore(this, bitAnd);
3468
3469 inputDef = bitAnd;
3470 }
3471
3472 return MInt64ToBigInt::New(alloc, inputDef, /* isSigned = */ false);
3473 }
3474
3475 bool MBigIntPtrBinaryArithInstruction::isMaybeZero(MDefinition* ins) {
3476 MOZ_ASSERT(ins->type() == MIRType::IntPtr);
3477 if (ins->isBigIntToIntPtr()) {
3478 ins = ins->toBigIntToIntPtr()->input();
3479 }
3480 if (ins->isConstant()) {
3481 if (ins->type() == MIRType::IntPtr) {
3482 return ins->toConstant()->toIntPtr() == 0;
3483 }
3484 MOZ_ASSERT(ins->type() == MIRType::BigInt);
3485 return ins->toConstant()->toBigInt()->isZero();
3486 }
3487 return true;
3488 }
3489
3490 bool MBigIntPtrBinaryArithInstruction::isMaybeNegative(MDefinition* ins) {
3491 MOZ_ASSERT(ins->type() == MIRType::IntPtr);
3492 if (ins->isBigIntToIntPtr()) {
3493 ins = ins->toBigIntToIntPtr()->input();
3494 }
3495 if (ins->isConstant()) {
3496 if (ins->type() == MIRType::IntPtr) {
3497 return ins->toConstant()->toIntPtr() < 0;
3498 }
3499 MOZ_ASSERT(ins->type() == MIRType::BigInt);
3500 return ins->toConstant()->toBigInt()->isNegative();
3501 }
3502 return true;
3503 }
3504
3505 MDefinition* MInt32ToIntPtr::foldsTo(TempAllocator& alloc) {
3506 MDefinition* def = input();
3507 if (def->isConstant()) {
3508 int32_t i = def->toConstant()->toInt32();
3509 return MConstant::NewIntPtr(alloc, intptr_t(i));
3510 }
3511
3512 if (def->isNonNegativeIntPtrToInt32()) {
3513 return def->toNonNegativeIntPtrToInt32()->input();
3514 }
3515
3516 return this;
3517 }
3518
3519 bool MAbs::fallible() const {
3520 return !implicitTruncate_ && (!range() || !range()->hasInt32Bounds());
3521 }
3522
3523 void MAbs::trySpecializeFloat32(TempAllocator& alloc) {
3524 // Do not use Float32 if we can use int32.
3525 if (input()->type() == MIRType::Int32) {
3526 return;
3527 }
3528
3529 if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
3530 setResultType(MIRType::Float32);
3531 }
3532 }
3533
3534 MDefinition* MDiv::foldsTo(TempAllocator& alloc) {
3535 MOZ_ASSERT(IsNumberType(type()));
3536
3537 if (type() == MIRType::Int64) {
3538 if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
3539 return folded;
3540 }
3541 return this;
3542 }
3543
3544 if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
3545 return folded;
3546 }
3547
3548 if (MDefinition* folded = EvaluateExactReciprocal(alloc, this)) {
3549 return folded;
3550 }
3551
3552 return this;
3553 }
3554
3555 void MDiv::analyzeEdgeCasesForward() {
3556 // This is only meaningful when doing integer division.
3557 if (type() != MIRType::Int32) {
3558 return;
3559 }
3560
3561 MOZ_ASSERT(lhs()->type() == MIRType::Int32);
3562 MOZ_ASSERT(rhs()->type() == MIRType::Int32);
3563
3564 // Try removing divide by zero check
3565 if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(0)) {
3566 canBeDivideByZero_ = false;
3567 }
3568
3569 // If lhs is a constant int != INT32_MIN, then
3570 // negative overflow check can be skipped.
3571 if (lhs()->isConstant() && !lhs()->toConstant()->isInt32(INT32_MIN)) {
3572 canBeNegativeOverflow_ = false;
3573 }
3574
3575 // If rhs is a constant int != -1, likewise.
3576 if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(-1)) {
3577 canBeNegativeOverflow_ = false;
3578 }
3579
3580 // If lhs is != 0, then negative zero check can be skipped.
3581 if (lhs()->isConstant() && !lhs()->toConstant()->isInt32(0)) {
3582 setCanBeNegativeZero(false);
3583 }
3584
3585 // If rhs is >= 0, likewise.
3586 if (rhs()->isConstant() && rhs()->type() == MIRType::Int32) {
3587 if (rhs()->toConstant()->toInt32() >= 0) {
3588 setCanBeNegativeZero(false);
3589 }
3590 }
3591 }
3592
3593 void MDiv::analyzeEdgeCasesBackward() {
3594 // In general, canBeNegativeZero_ is only valid for integer divides.
3595 // It's fine to access here because we're only using it to avoid
3596 // wasting effort to decide whether we can clear an already cleared
3597 // flag.
3598 if (canBeNegativeZero_ && !NeedNegativeZeroCheck(this)) {
3599 setCanBeNegativeZero(false);
3600 }
3601 }
3602
3603 bool MDiv::fallible() const { return !isTruncated(); }
3604
3605 MDefinition* MMod::foldsTo(TempAllocator& alloc) {
3606 MOZ_ASSERT(IsNumberType(type()));
3607
3608 if (type() == MIRType::Int64) {
3609 if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
3610 return folded;
3611 }
3612 } else {
3613 if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
3614 return folded;
3615 }
3616 }
3617 return this;
3618 }
3619
3620 void MMod::analyzeEdgeCasesForward() {
3621 // These optimizations make sense only for integer division
3622 if (type() != MIRType::Int32) {
3623 return;
3624 }
3625
3626 if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(0)) {
3627 canBeDivideByZero_ = false;
3628 }
3629
3630 if (rhs()->isConstant()) {
3631 int32_t n = rhs()->toConstant()->toInt32();
3632 if (n > 0 && !IsPowerOfTwo(uint32_t(n))) {
3633 canBePowerOfTwoDivisor_ = false;
3634 }
3635 }
3636 }
3637
3638 bool MMod::fallible() const {
3639 return !isTruncated() &&
3640 (isUnsigned() || canBeDivideByZero() || canBeNegativeDividend());
3641 }
3642
3643 void MMathFunction::trySpecializeFloat32(TempAllocator& alloc) {
3644 if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
3645 setResultType(MIRType::Float32);
3646 specialization_ = MIRType::Float32;
3647 }
3648 }
3649
3650 bool MMathFunction::isFloat32Commutative() const {
3651 switch (function_) {
3652 case UnaryMathFunction::Floor:
3653 case UnaryMathFunction::Ceil:
3654 case UnaryMathFunction::Round:
3655 case UnaryMathFunction::Trunc:
3656 return true;
3657 default:
3658 return false;
3659 }
3660 }
3661
3662 MHypot* MHypot::New(TempAllocator& alloc, const MDefinitionVector& vector) {
3663 uint32_t length = vector.length();
3664 MHypot* hypot = new (alloc) MHypot;
3665 if (!hypot->init(alloc, length)) {
3666 return nullptr;
3667 }
3668
3669 for (uint32_t i = 0; i < length; ++i) {
3670 hypot->initOperand(i, vector[i]);
3671 }
3672 return hypot;
3673 }
3674
3675 bool MAdd::fallible() const {
3676 // the add is fallible if range analysis does not say that it is finite, AND
3677 // either the truncation analysis shows that there are non-truncated uses.
3678 if (truncateKind() >= TruncateKind::IndirectTruncate) {
3679 return false;
3680 }
3681 if (range() && range()->hasInt32Bounds()) {
3682 return false;
3683 }
3684 return true;
3685 }
3686
3687 bool MSub::fallible() const {
3688 // see comment in MAdd::fallible()
3689 if (truncateKind() >= TruncateKind::IndirectTruncate) {
3690 return false;
3691 }
3692 if (range() && range()->hasInt32Bounds()) {
3693 return false;
3694 }
3695 return true;
3696 }
3697
3698 MDefinition* MSub::foldsTo(TempAllocator& alloc) {
3699 MDefinition* out = MBinaryArithInstruction::foldsTo(alloc);
3700 if (out != this) {
3701 return out;
3702 }
3703
3704 if (type() != MIRType::Int32) {
3705 return this;
3706 }
3707
3708 // Optimize X - X to 0. This optimization is only valid for Int32
3709 // values. Subtracting a floating point value from itself returns
3710 // NaN when the operand is either Infinity or NaN.
3711 if (lhs() == rhs()) {
3712 // Ensure that any bailouts that we depend on to guarantee that X
3713 // is Int32 are not removed.
3714 lhs()->setGuardRangeBailoutsUnchecked();
3715 return MConstant::New(alloc, Int32Value(0));
3716 }
3717
3718 return this;
3719 }
3720
3721 MDefinition* MMul::foldsTo(TempAllocator& alloc) {
3722 MDefinition* out = MBinaryArithInstruction::foldsTo(alloc);
3723 if (out != this) {
3724 return out;
3725 }
3726
3727 if (type() != MIRType::Int32) {
3728 return this;
3729 }
3730
3731 if (lhs() == rhs()) {
3732 setCanBeNegativeZero(false);
3733 }
3734
3735 return this;
3736 }
3737
3738 void MMul::analyzeEdgeCasesForward() {
3739 // Try to remove the check for negative zero
3740 // This only makes sense when using the integer multiplication
3741 if (type() != MIRType::Int32) {
3742 return;
3743 }
3744
3745 // If lhs is > 0, no need for negative zero check.
3746 if (lhs()->isConstant() && lhs()->type() == MIRType::Int32) {
3747 if (lhs()->toConstant()->toInt32() > 0) {
3748 setCanBeNegativeZero(false);
3749 }
3750 }
3751
3752 // If rhs is > 0, likewise.
3753 if (rhs()->isConstant() && rhs()->type() == MIRType::Int32) {
3754 if (rhs()->toConstant()->toInt32() > 0) {
3755 setCanBeNegativeZero(false);
3756 }
3757 }
3758 }
3759
3760 void MMul::analyzeEdgeCasesBackward() {
3761 if (canBeNegativeZero() && !NeedNegativeZeroCheck(this)) {
3762 setCanBeNegativeZero(false);
3763 }
3764 }
3765
3766 bool MMul::canOverflow() const {
3767 if (isTruncated()) {
3768 return false;
3769 }
3770 return !range() || !range()->hasInt32Bounds();
3771 }
3772
3773 bool MUrsh::fallible() const {
3774 if (bailoutsDisabled()) {
3775 return false;
3776 }
3777 return !range() || !range()->hasInt32Bounds();
3778 }
3779
3780 static inline bool MustBeUInt32(MDefinition* def, MDefinition** pwrapped) {
3781 if (def->isUrsh()) {
3782 *pwrapped = def->toUrsh()->lhs();
3783 MDefinition* rhs = def->toUrsh()->rhs();
3784 return def->toUrsh()->bailoutsDisabled() && rhs->maybeConstantValue() &&
3785 rhs->maybeConstantValue()->isInt32(0);
3786 }
3787
3788 if (MConstant* defConst = def->maybeConstantValue()) {
3789 *pwrapped = defConst;
3790 return defConst->type() == MIRType::Int32 && defConst->toInt32() >= 0;
3791 }
3792
3793 *pwrapped = nullptr; // silence GCC warning
3794 return false;
3795 }
3796
3797 /* static */
3798 bool MBinaryInstruction::unsignedOperands(MDefinition* left,
3799 MDefinition* right) {
3800 MDefinition* replace;
3801 if (!MustBeUInt32(left, &replace)) {
3802 return false;
3803 }
3804 if (replace->type() != MIRType::Int32) {
3805 return false;
3806 }
3807 if (!MustBeUInt32(right, &replace)) {
3808 return false;
3809 }
3810 if (replace->type() != MIRType::Int32) {
3811 return false;
3812 }
3813 return true;
3814 }
3815
3816 bool MBinaryInstruction::unsignedOperands() {
3817 return unsignedOperands(getOperand(0), getOperand(1));
3818 }
3819
3820 void MBinaryInstruction::replaceWithUnsignedOperands() {
3821 MOZ_ASSERT(unsignedOperands());
3822
3823 for (size_t i = 0; i < numOperands(); i++) {
3824 MDefinition* replace;
3825 MustBeUInt32(getOperand(i), &replace);
3826 if (replace == getOperand(i)) {
3827 continue;
3828 }
3829
3830 getOperand(i)->setImplicitlyUsedUnchecked();
3831 replaceOperand(i, replace);
3832 }
3833 }
3834
3835 MDefinition* MBitNot::foldsTo(TempAllocator& alloc) {
3836 if (type() == MIRType::Int64) {
3837 return this;
3838 }
3839 MOZ_ASSERT(type() == MIRType::Int32);
3840
3841 MDefinition* input = getOperand(0);
3842
3843 if (input->isConstant()) {
3844 js::Value v = Int32Value(~(input->toConstant()->toInt32()));
3845 return MConstant::New(alloc, v);
3846 }
3847
3848 if (input->isBitNot()) {
3849 MOZ_ASSERT(input->toBitNot()->type() == MIRType::Int32);
3850 MOZ_ASSERT(input->toBitNot()->getOperand(0)->type() == MIRType::Int32);
3851 return MTruncateToInt32::New(alloc,
3852 input->toBitNot()->input()); // ~~x => x | 0
3853 }
3854
3855 return this;
3856 }
3857
3858 static void AssertKnownClass(TempAllocator& alloc, MInstruction* ins,
3859 MDefinition* obj) {
3860 #ifdef DEBUG
3861 const JSClass* clasp = GetObjectKnownJSClass(obj);
3862 MOZ_ASSERT(clasp);
3863
3864 auto* assert = MAssertClass::New(alloc, obj, clasp);
3865 ins->block()->insertBefore(ins, assert);
3866 #endif
3867 }
3868
3869 MDefinition* MBoxNonStrictThis::foldsTo(TempAllocator& alloc) {
3870 MDefinition* in = input();
3871 if (!in->isBox()) {
3872 return this;
3873 }
3874
3875 MDefinition* unboxed = in->toBox()->input();
3876 if (unboxed->type() == MIRType::Object) {
3877 return unboxed;
3878 }
3879
3880 return this;
3881 }
3882
3883 AliasSet MLoadArgumentsObjectArg::getAliasSet() const {
3884 return AliasSet::Load(AliasSet::Any);
3885 }
3886
3887 AliasSet MLoadArgumentsObjectArgHole::getAliasSet() const {
3888 return AliasSet::Load(AliasSet::Any);
3889 }
3890
3891 AliasSet MInArgumentsObjectArg::getAliasSet() const {
3892 // Loads |arguments.length|, but not the actual element, so we can use the
3893 // same alias-set as MArgumentsObjectLength.
3894 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
3895 AliasSet::DynamicSlot);
3896 }
3897
3898 AliasSet MArgumentsObjectLength::getAliasSet() const {
3899 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
3900 AliasSet::DynamicSlot);
3901 }
3902
3903 bool MGuardArgumentsObjectFlags::congruentTo(const MDefinition* ins) const {
3904 if (!ins->isGuardArgumentsObjectFlags() ||
3905 ins->toGuardArgumentsObjectFlags()->flags() != flags()) {
3906 return false;
3907 }
3908 return congruentIfOperandsEqual(ins);
3909 }
3910
3911 AliasSet MGuardArgumentsObjectFlags::getAliasSet() const {
3912 // The flags are packed with the length in a fixed private slot.
3913 return AliasSet::Load(AliasSet::FixedSlot);
3914 }
3915
3916 MDefinition* MIdToStringOrSymbol::foldsTo(TempAllocator& alloc) {
3917 if (idVal()->isBox()) {
3918 auto* input = idVal()->toBox()->input();
3919 MIRType idType = input->type();
3920 if (idType == MIRType::String || idType == MIRType::Symbol) {
3921 return idVal();
3922 }
3923 if (idType == MIRType::Int32) {
3924 auto* toString =
3925 MToString::New(alloc, input, MToString::SideEffectHandling::Bailout);
3926 block()->insertBefore(this, toString);
3927
3928 return MBox::New(alloc, toString);
3929 }
3930 }
3931
3932 return this;
3933 }
3934
3935 MDefinition* MReturnFromCtor::foldsTo(TempAllocator& alloc) {
3936 MDefinition* rval = value();
3937 if (!rval->isBox()) {
3938 return this;
3939 }
3940
3941 MDefinition* unboxed = rval->toBox()->input();
3942 if (unboxed->type() == MIRType::Object) {
3943 return unboxed;
3944 }
3945
3946 return object();
3947 }
3948
3949 MDefinition* MTypeOf::foldsTo(TempAllocator& alloc) {
3950 MDefinition* unboxed = input();
3951 if (unboxed->isBox()) {
3952 unboxed = unboxed->toBox()->input();
3953 }
3954
3955 JSType type;
3956 switch (unboxed->type()) {
3957 case MIRType::Double:
3958 case MIRType::Float32:
3959 case MIRType::Int32:
3960 type = JSTYPE_NUMBER;
3961 break;
3962 case MIRType::String:
3963 type = JSTYPE_STRING;
3964 break;
3965 case MIRType::Symbol:
3966 type = JSTYPE_SYMBOL;
3967 break;
3968 case MIRType::BigInt:
3969 type = JSTYPE_BIGINT;
3970 break;
3971 case MIRType::Null:
3972 type = JSTYPE_OBJECT;
3973 break;
3974 case MIRType::Undefined:
3975 type = JSTYPE_UNDEFINED;
3976 break;
3977 case MIRType::Boolean:
3978 type = JSTYPE_BOOLEAN;
3979 break;
3980 case MIRType::Object: {
3981 KnownClass known = GetObjectKnownClass(unboxed);
3982 if (known != KnownClass::None) {
3983 if (known == KnownClass::Function) {
3984 type = JSTYPE_FUNCTION;
3985 } else {
3986 type = JSTYPE_OBJECT;
3987 }
3988
3989 AssertKnownClass(alloc, this, unboxed);
3990 break;
3991 }
3992 [[fallthrough]];
3993 }
3994 default:
3995 return this;
3996 }
3997
3998 return MConstant::New(alloc, Int32Value(static_cast<int32_t>(type)));
3999 }
4000
4001 MDefinition* MTypeOfName::foldsTo(TempAllocator& alloc) {
4002 MOZ_ASSERT(input()->type() == MIRType::Int32);
4003
4004 if (!input()->isConstant()) {
4005 return this;
4006 }
4007
4008 static_assert(JSTYPE_UNDEFINED == 0);
4009
4010 int32_t type = input()->toConstant()->toInt32();
4011 MOZ_ASSERT(JSTYPE_UNDEFINED <= type && type < JSTYPE_LIMIT);
4012
4013 JSString* name =
4014 TypeName(static_cast<JSType>(type), GetJitContext()->runtime->names());
4015 return MConstant::New(alloc, StringValue(name));
4016 }
4017
4018 MUrsh* MUrsh::NewWasm(TempAllocator& alloc, MDefinition* left,
4019 MDefinition* right, MIRType type) {
4020 MUrsh* ins = new (alloc) MUrsh(left, right, type);
4021
4022 // Since Ion has no UInt32 type, we use Int32 and we have a special
4023 // exception to the type rules: we can return values in
4024 // (INT32_MIN,UINT32_MAX] and still claim that we have an Int32 type
4025 // without bailing out. This is necessary because Ion has no UInt32
4026 // type and we can't have bailouts in wasm code.
4027 ins->bailoutsDisabled_ = true;
4028
4029 return ins;
4030 }
4031
4032 MResumePoint* MResumePoint::New(TempAllocator& alloc, MBasicBlock* block,
4033 jsbytecode* pc, ResumeMode mode) {
4034 MResumePoint* resume = new (alloc) MResumePoint(block, pc, mode);
4035 if (!resume->init(alloc)) {
4036 block->discardPreAllocatedResumePoint(resume);
4037 return nullptr;
4038 }
4039 resume->inherit(block);
4040 return resume;
4041 }
4042
4043 MResumePoint::MResumePoint(MBasicBlock* block, jsbytecode* pc, ResumeMode mode)
4044 : MNode(block, Kind::ResumePoint),
4045 pc_(pc),
4046 instruction_(nullptr),
4047 mode_(mode) {
4048 block->addResumePoint(this);
4049 }
4050
4051 bool MResumePoint::init(TempAllocator& alloc) {
4052 return operands_.init(alloc, block()->stackDepth());
4053 }
4054
4055 MResumePoint* MResumePoint::caller() const {
4056 return block()->callerResumePoint();
4057 }
4058
4059 void MResumePoint::inherit(MBasicBlock* block) {
4060 // FixedList doesn't initialize its elements, so do unchecked inits.
4061 for (size_t i = 0; i < stackDepth(); i++) {
4062 initOperand(i, block->getSlot(i));
4063 }
4064 }
4065
4066 void MResumePoint::addStore(TempAllocator& alloc, MDefinition* store,
4067 const MResumePoint* cache) {
4068 MOZ_ASSERT(block()->outerResumePoint() != this);
4069 MOZ_ASSERT_IF(cache, !cache->stores_.empty());
4070
4071 if (cache && cache->stores_.begin()->operand == store) {
4072 // If the last resume point had the same side-effect stack, then we can
4073 // reuse the current side effect without cloning it. This is a simple
4074 // way to share common context by making a spaghetti stack.
4075 if (++cache->stores_.begin() == stores_.begin()) {
4076 stores_.copy(cache->stores_);
4077 return;
4078 }
4079 }
4080
4081 // Ensure that the store would not be deleted by DCE.
4082 MOZ_ASSERT(store->isEffectful());
4083
4084 MStoreToRecover* top = new (alloc) MStoreToRecover(store);
4085 stores_.push(top);
4086 }
4087
4088 #ifdef JS_JITSPEW
4089 void MResumePoint::dump(GenericPrinter& out) const {
4090 out.printf("resumepoint mode=");
4091
4092 switch (mode()) {
4093 case ResumeMode::ResumeAt:
4094 if (instruction_) {
4095 out.printf("ResumeAt(%u)", instruction_->id());
4096 } else {
4097 out.printf("ResumeAt");
4098 }
4099 break;
4100 default:
4101 out.put(ResumeModeToString(mode()));
4102 break;
4103 }
4104
4105 if (MResumePoint* c = caller()) {
4106 out.printf(" (caller in block%u)", c->block()->id());
4107 }
4108
4109 for (size_t i = 0; i < numOperands(); i++) {
4110 out.printf(" ");
4111 if (operands_[i].hasProducer()) {
4112 getOperand(i)->printName(out);
4113 } else {
4114 out.printf("(null)");
4115 }
4116 }
4117 out.printf("\n");
4118 }
4119
4120 void MResumePoint::dump() const {
4121 Fprinter out(stderr);
4122 dump(out);
4123 out.finish();
4124 }
4125 #endif
4126
4127 bool MResumePoint::isObservableOperand(MUse* u) const {
4128 return isObservableOperand(indexOf(u));
4129 }
4130
4131 bool MResumePoint::isObservableOperand(size_t index) const {
4132 return block()->info().isObservableSlot(index);
4133 }
4134
4135 bool MResumePoint::isRecoverableOperand(MUse* u) const {
4136 return block()->info().isRecoverableOperand(indexOf(u));
4137 }
4138
4139 MDefinition* MBigIntToIntPtr::foldsTo(TempAllocator& alloc) {
4140 MDefinition* def = input();
4141
4142 // If the operand converts an IntPtr to BigInt, drop both conversions.
4143 if (def->isIntPtrToBigInt()) {
4144 return def->toIntPtrToBigInt()->input();
4145 }
4146
4147 // Fold this operation if the input operand is constant.
4148 if (def->isConstant()) {
4149 BigInt* bigInt = def->toConstant()->toBigInt();
4150 intptr_t i;
4151 if (BigInt::isIntPtr(bigInt, &i)) {
4152 return MConstant::NewIntPtr(alloc, i);
4153 }
4154 }
4155
4156 // Fold BigIntToIntPtr(Int64ToBigInt(int64)) to Int64ToIntPtr(int64)
4157 if (def->isInt64ToBigInt()) {
4158 auto* toBigInt = def->toInt64ToBigInt();
4159 return MInt64ToIntPtr::New(alloc, toBigInt->input(), toBigInt->isSigned());
4160 }
4161
4162 return this;
4163 }
4164
4165 MDefinition* MIntPtrToBigInt::foldsTo(TempAllocator& alloc) {
4166 MDefinition* def = input();
4167
4168 // If the operand converts a BigInt to IntPtr, drop both conversions.
4169 if (def->isBigIntToIntPtr()) {
4170 return def->toBigIntToIntPtr()->input();
4171 }
4172
4173 return this;
4174 }
4175
4176 MDefinition* MTruncateBigIntToInt64::foldsTo(TempAllocator& alloc) {
4177 MDefinition* input = this->input();
4178 MOZ_ASSERT(input->type() == MIRType::BigInt);
4179
4180 // If the operand converts an I64 to BigInt, drop both conversions.
4181 if (input->isInt64ToBigInt()) {
4182 return input->toInt64ToBigInt()->input();
4183 }
4184
4185 // If the operand is an IntPtr, extend the IntPtr to I64.
4186 if (input->isIntPtrToBigInt()) {
4187 auto* intPtr = input->toIntPtrToBigInt()->input();
4188 if (intPtr->isConstant()) {
4189 intptr_t c = intPtr->toConstant()->toIntPtr();
4190 return MConstant::NewInt64(alloc, int64_t(c));
4191 }
4192 return MIntPtrToInt64::New(alloc, intPtr);
4193 }
4194
4195 // Fold this operation if the input operand is constant.
4196 if (input->isConstant()) {
4197 return MConstant::NewInt64(
4198 alloc, BigInt::toInt64(input->toConstant()->toBigInt()));
4199 }
4200
4201 return this;
4202 }
4203
4204 MDefinition* MToInt64::foldsTo(TempAllocator& alloc) {
4205 MDefinition* input = getOperand(0);
4206
4207 if (input->isBox()) {
4208 input = input->getOperand(0);
4209 }
4210
4211 // Unwrap MInt64ToBigInt: MToInt64(MInt64ToBigInt(int64)) = int64.
4212 if (input->isInt64ToBigInt()) {
4213 return input->getOperand(0);
4214 }
4215
4216 // Unwrap IntPtrToBigInt:
4217 // MToInt64(MIntPtrToBigInt(intptr)) = MIntPtrToInt64(intptr).
4218 if (input->isIntPtrToBigInt()) {
4219 auto* intPtr = input->toIntPtrToBigInt()->input();
4220 if (intPtr->isConstant()) {
4221 intptr_t c = intPtr->toConstant()->toIntPtr();
4222 return MConstant::NewInt64(alloc, int64_t(c));
4223 }
4224 return MIntPtrToInt64::New(alloc, intPtr);
4225 }
4226
4227 // When the input is an Int64 already, just return it.
4228 if (input->type() == MIRType::Int64) {
4229 return input;
4230 }
4231
4232 // Fold this operation if the input operand is constant.
4233 if (input->isConstant()) {
4234 switch (input->type()) {
4235 case MIRType::Boolean:
4236 return MConstant::NewInt64(alloc, input->toConstant()->toBoolean());
4237 default:
4238 break;
4239 }
4240 }
4241
4242 return this;
4243 }
4244
4245 MDefinition* MToNumberInt32::foldsTo(TempAllocator& alloc) {
4246 // Fold this operation if the input operand is constant.
4247 if (MConstant* cst = input()->maybeConstantValue()) {
4248 switch (cst->type()) {
4249 case MIRType::Null:
4250 if (conversion() == IntConversionInputKind::Any) {
4251 return MConstant::New(alloc, Int32Value(0));
4252 }
4253 break;
4254 case MIRType::Boolean:
4255 if (conversion() == IntConversionInputKind::Any) {
4256 return MConstant::New(alloc, Int32Value(cst->toBoolean()));
4257 }
4258 break;
4259 case MIRType::Int32:
4260 return MConstant::New(alloc, Int32Value(cst->toInt32()));
4261 case MIRType::Float32:
4262 case MIRType::Double:
4263 int32_t ival;
4264 // Only the value within the range of Int32 can be substituted as
4265 // constant.
4266 if (mozilla::NumberIsInt32(cst->numberToDouble(), &ival)) {
4267 return MConstant::New(alloc, Int32Value(ival));
4268 }
4269 break;
4270 default:
4271 break;
4272 }
4273 }
4274
4275 MDefinition* input = getOperand(0);
4276 if (input->isBox()) {
4277 input = input->toBox()->input();
4278 }
4279
4280 // Do not fold the TruncateToInt32 node when the input is uint32 (e.g. ursh
4281 // with a zero constant. Consider the test jit-test/tests/ion/bug1247880.js,
4282 // where the relevant code is: |(imul(1, x >>> 0) % 2)|. The imul operator
4283 // is folded to a MTruncateToInt32 node, which will result in this MIR:
4284 // MMod(MTruncateToInt32(MUrsh(x, MConstant(0))), MConstant(2)). Note that
4285 // the MUrsh node's type is int32 (since uint32 is not implemented), and
4286 // that would fold the MTruncateToInt32 node. This will make the modulo
4287 // unsigned, while is should have been signed.
4288 if (input->type() == MIRType::Int32 && !IsUint32Type(input)) {
4289 return input;
4290 }
4291
4292 return this;
4293 }
4294
4295 MDefinition* MBooleanToInt32::foldsTo(TempAllocator& alloc) {
4296 MDefinition* input = getOperand(0);
4297 MOZ_ASSERT(input->type() == MIRType::Boolean);
4298
4299 if (input->isConstant()) {
4300 return MConstant::New(alloc, Int32Value(input->toConstant()->toBoolean()));
4301 }
4302
4303 return this;
4304 }
4305
4306 void MToNumberInt32::analyzeEdgeCasesBackward() {
4307 if (!NeedNegativeZeroCheck(this)) {
4308 setNeedsNegativeZeroCheck(false);
4309 }
4310 }
4311
4312 MDefinition* MTruncateToInt32::foldsTo(TempAllocator& alloc) {
4313 MDefinition* input = getOperand(0);
4314 if (input->isBox()) {
4315 input = input->getOperand(0);
4316 }
4317
4318 // Do not fold the TruncateToInt32 node when the input is uint32 (e.g. ursh
4319 // with a zero constant. Consider the test jit-test/tests/ion/bug1247880.js,
4320 // where the relevant code is: |(imul(1, x >>> 0) % 2)|. The imul operator
4321 // is folded to a MTruncateToInt32 node, which will result in this MIR:
4322 // MMod(MTruncateToInt32(MUrsh(x, MConstant(0))), MConstant(2)). Note that
4323 // the MUrsh node's type is int32 (since uint32 is not implemented), and
4324 // that would fold the MTruncateToInt32 node. This will make the modulo
4325 // unsigned, while is should have been signed.
4326 if (input->type() == MIRType::Int32 && !IsUint32Type(input)) {
4327 return input;
4328 }
4329
4330 if (input->type() == MIRType::Double && input->isConstant()) {
4331 int32_t ret = ToInt32(input->toConstant()->toDouble());
4332 return MConstant::New(alloc, Int32Value(ret));
4333 }
4334
4335 return this;
4336 }
4337
4338 MDefinition* MWrapInt64ToInt32::foldsTo(TempAllocator& alloc) {
4339 MDefinition* input = this->input();
4340 if (input->isConstant()) {
4341 uint64_t c = input->toConstant()->toInt64();
4342 int32_t output = bottomHalf() ? int32_t(c) : int32_t(c >> 32);
4343 return MConstant::New(alloc, Int32Value(output));
4344 }
4345
4346 return this;
4347 }
4348
4349 MDefinition* MExtendInt32ToInt64::foldsTo(TempAllocator& alloc) {
4350 MDefinition* input = this->input();
4351 if (input->isConstant()) {
4352 int32_t c = input->toConstant()->toInt32();
4353 int64_t res = isUnsigned() ? int64_t(uint32_t(c)) : int64_t(c);
4354 return MConstant::NewInt64(alloc, res);
4355 }
4356
4357 return this;
4358 }
4359
4360 MDefinition* MSignExtendInt32::foldsTo(TempAllocator& alloc) {
4361 MDefinition* input = this->input();
4362 if (input->isConstant()) {
4363 int32_t c = input->toConstant()->toInt32();
4364 int32_t res;
4365 switch (mode_) {
4366 case Byte:
4367 res = int32_t(int8_t(c & 0xFF));
4368 break;
4369 case Half:
4370 res = int32_t(int16_t(c & 0xFFFF));
4371 break;
4372 }
4373 return MConstant::New(alloc, Int32Value(res));
4374 }
4375
4376 return this;
4377 }
4378
4379 MDefinition* MSignExtendInt64::foldsTo(TempAllocator& alloc) {
4380 MDefinition* input = this->input();
4381 if (input->isConstant()) {
4382 int64_t c = input->toConstant()->toInt64();
4383 int64_t res;
4384 switch (mode_) {
4385 case Byte:
4386 res = int64_t(int8_t(c & 0xFF));
4387 break;
4388 case Half:
4389 res = int64_t(int16_t(c & 0xFFFF));
4390 break;
4391 case Word:
4392 res = int64_t(int32_t(c & 0xFFFFFFFFU));
4393 break;
4394 }
4395 return MConstant::NewInt64(alloc, res);
4396 }
4397
4398 return this;
4399 }
4400
4401 MDefinition* MSignExtendIntPtr::foldsTo(TempAllocator& alloc) {
4402 MDefinition* input = this->input();
4403 if (input->isConstant()) {
4404 intptr_t c = input->toConstant()->toIntPtr();
4405 intptr_t res;
4406 switch (mode_) {
4407 case Byte:
4408 res = intptr_t(int8_t(c & 0xFF));
4409 break;
4410 case Half:
4411 res = intptr_t(int16_t(c & 0xFFFF));
4412 break;
4413 case Word:
4414 res = intptr_t(int32_t(c & 0xFFFFFFFFU));
4415 break;
4416 }
4417 return MConstant::NewIntPtr(alloc, res);
4418 }
4419
4420 return this;
4421 }
4422
4423 MDefinition* MToDouble::foldsTo(TempAllocator& alloc) {
4424 MDefinition* input = getOperand(0);
4425 if (input->isBox()) {
4426 input = input->getOperand(0);
4427 }
4428
4429 if (input->type() == MIRType::Double) {
4430 return input;
4431 }
4432
4433 if (input->isConstant() &&
4434 input->toConstant()->isTypeRepresentableAsDouble()) {
4435 return MConstant::New(alloc,
4436 DoubleValue(input->toConstant()->numberToDouble()));
4437 }
4438
4439 return this;
4440 }
4441
4442 MDefinition* MToFloat32::foldsTo(TempAllocator& alloc) {
4443 MDefinition* input = getOperand(0);
4444 if (input->isBox()) {
4445 input = input->getOperand(0);
4446 }
4447
4448 if (input->type() == MIRType::Float32) {
4449 return input;
4450 }
4451
4452 // If x is a Float32, Float32(Double(x)) == x
4453 if (!mustPreserveNaN_ && input->isToDouble() &&
4454 input->toToDouble()->input()->type() == MIRType::Float32) {
4455 return input->toToDouble()->input();
4456 }
4457
4458 if (input->isConstant() &&
4459 input->toConstant()->isTypeRepresentableAsDouble()) {
4460 return MConstant::NewFloat32(alloc,
4461 float(input->toConstant()->numberToDouble()));
4462 }
4463
4464 // Fold ToFloat32(ToDouble(int32)) to ToFloat32(int32).
4465 if (input->isToDouble() &&
4466 input->toToDouble()->input()->type() == MIRType::Int32) {
4467 return MToFloat32::New(alloc, input->toToDouble()->input());
4468 }
4469
4470 return this;
4471 }
4472
4473 MDefinition* MToFloat16::foldsTo(TempAllocator& alloc) {
4474 MDefinition* in = input();
4475 if (in->isBox()) {
4476 in = in->toBox()->input();
4477 }
4478
4479 if (in->isConstant()) {
4480 auto* cst = in->toConstant();
4481 if (cst->isTypeRepresentableAsDouble()) {
4482 double num = cst->numberToDouble();
4483 return MConstant::NewFloat32(alloc, static_cast<float>(js::float16{num}));
4484 }
4485 }
4486
4487 auto isFloat16 = [](auto* def) -> MDefinition* {
4488 // ToFloat16(ToDouble(float16)) => float16
4489 // ToFloat16(ToFloat32(float16)) => float16
4490 if (def->isToDouble()) {
4491 def = def->toToDouble()->input();
4492 } else if (def->isToFloat32()) {
4493 def = def->toToFloat32()->input();
4494 }
4495
4496 // ToFloat16(ToFloat16(x)) => ToFloat16(x)
4497 if (def->isToFloat16()) {
4498 return def;
4499 }
4500
4501 // ToFloat16(LoadFloat16(x)) => LoadFloat16(x)
4502 if (def->isLoadUnboxedScalar() &&
4503 def->toLoadUnboxedScalar()->storageType() == Scalar::Float16) {
4504 return def;
4505 }
4506 if (def->isLoadDataViewElement() &&
4507 def->toLoadDataViewElement()->storageType() == Scalar::Float16) {
4508 return def;
4509 }
4510 return nullptr;
4511 };
4512
4513 // Fold loads which are guaranteed to return Float16.
4514 if (auto* f16 = isFloat16(in)) {
4515 return f16;
4516 }
4517
4518 // Fold ToFloat16(ToDouble(float32)) to ToFloat16(float32).
4519 // Fold ToFloat16(ToDouble(int32)) to ToFloat16(int32).
4520 if (in->isToDouble()) {
4521 auto* toDoubleInput = in->toToDouble()->input();
4522 if (toDoubleInput->type() == MIRType::Float32 ||
4523 toDoubleInput->type() == MIRType::Int32) {
4524 return MToFloat16::New(alloc, toDoubleInput);
4525 }
4526 }
4527
4528 return this;
4529 }
4530
4531 MDefinition* MToString::foldsTo(TempAllocator& alloc) {
4532 MDefinition* in = input();
4533 if (in->isBox()) {
4534 in = in->getOperand(0);
4535 }
4536
4537 if (in->type() == MIRType::String) {
4538 return in;
4539 }
4540 return this;
4541 }
4542
4543 MDefinition* MClampToUint8::foldsTo(TempAllocator& alloc) {
4544 if (MConstant* inputConst = input()->maybeConstantValue()) {
4545 if (inputConst->isTypeRepresentableAsDouble()) {
4546 int32_t clamped = ClampDoubleToUint8(inputConst->numberToDouble());
4547 return MConstant::New(alloc, Int32Value(clamped));
4548 }
4549 }
4550 return this;
4551 }
4552
4553 bool MCompare::tryFoldEqualOperands(bool* result) {
4554 if (lhs() != rhs()) {
4555 return false;
4556 }
4557
4558 // Intuitively somebody would think that if lhs === rhs,
4559 // then we can just return true. (Or false for !==)
4560 // However NaN !== NaN is true! So we spend some time trying
4561 // to eliminate this case.
4562
4563 if (!IsEqualityOp(jsop())) {
4564 return false;
4565 }
4566
4567 switch (compareType_) {
4568 case Compare_Int32:
4569 case Compare_UInt32:
4570 case Compare_Int64:
4571 case Compare_UInt64:
4572 case Compare_IntPtr:
4573 case Compare_UIntPtr:
4574 case Compare_Float32:
4575 case Compare_Double:
4576 case Compare_String:
4577 case Compare_Object:
4578 case Compare_Symbol:
4579 case Compare_BigInt:
4580 case Compare_WasmAnyRef:
4581 case Compare_Null:
4582 case Compare_Undefined:
4583 break;
4584 case Compare_BigInt_Int32:
4585 case Compare_BigInt_String:
4586 case Compare_BigInt_Double:
4587 MOZ_CRASH("Expecting different operands for lhs and rhs");
4588 }
4589
4590 if (isDoubleComparison() || isFloat32Comparison()) {
4591 if (!operandsAreNeverNaN()) {
4592 return false;
4593 }
4594 } else {
4595 MOZ_ASSERT(!IsFloatingPointType(lhs()->type()));
4596 }
4597
4598 lhs()->setGuardRangeBailoutsUnchecked();
4599
4600 *result = (jsop() == JSOp::StrictEq || jsop() == JSOp::Eq);
4601 return true;
4602 }
4603
4604 static JSType TypeOfName(const JSLinearString* str) {
4605 static constexpr std::array types = {
4606 JSTYPE_UNDEFINED, JSTYPE_OBJECT, JSTYPE_FUNCTION, JSTYPE_STRING,
4607 JSTYPE_NUMBER, JSTYPE_BOOLEAN, JSTYPE_SYMBOL, JSTYPE_BIGINT,
4608 };
4609 static_assert(types.size() == JSTYPE_LIMIT);
4610
4611 const JSAtomState& names = GetJitContext()->runtime->names();
4612 for (auto type : types) {
4613 if (EqualStrings(str, TypeName(type, names))) {
4614 return type;
4615 }
4616 }
4617 return JSTYPE_LIMIT;
4618 }
4619
4620 struct TypeOfCompareInput {
4621 // The `typeof expr` side of the comparison.
4622 // MTypeOfName for JSOp::Typeof/JSOp::TypeofExpr, and
4623 // MTypeOf for JSOp::TypeofEq (same pointer as typeOf).
4624 MDefinition* typeOfSide;
4625
4626 // The actual `typeof` operation.
4627 MTypeOf* typeOf;
4628
4629 // The string side of the comparison.
4630 JSType type;
4631
4632 // True if the comparison uses raw JSType (Generated for JSOp::TypeofEq).
4633 bool isIntComparison;
4634
4635 TypeOfCompareInput(MDefinition* typeOfSide, MTypeOf* typeOf, JSType type,
4636 bool isIntComparison)
4637 : typeOfSide(typeOfSide),
4638 typeOf(typeOf),
4639 type(type),
4640 isIntComparison(isIntComparison) {}
4641 };
4642
4643 static mozilla::Maybe<TypeOfCompareInput> IsTypeOfCompare(MCompare* ins) {
4644 if (!IsEqualityOp(ins->jsop())) {
4645 return mozilla::Nothing();
4646 }
4647
4648 if (ins->compareType() == MCompare::Compare_Int32) {
4649 auto* lhs = ins->lhs();
4650 auto* rhs = ins->rhs();
4651
4652 // NOTE: The comparison is generated inside JIT, and typeof should always
4653 // be in the LHS.
4654 if (!lhs->isTypeOf() || !rhs->isConstant()) {
4655 return mozilla::Nothing();
4656 }
4657
4658 MOZ_ASSERT(ins->type() == MIRType::Boolean);
4659 MOZ_ASSERT(lhs->type() == MIRType::Int32);
4660 MOZ_ASSERT(rhs->type() == MIRType::Int32);
4661
4662 auto* typeOf = lhs->toTypeOf();
4663 auto* constant = rhs->toConstant();
4664
4665 JSType type = JSType(constant->toInt32());
4666 return mozilla::Some(TypeOfCompareInput(typeOf, typeOf, type, true));
4667 }
4668
4669 if (ins->compareType() != MCompare::Compare_String) {
4670 return mozilla::Nothing();
4671 }
4672
4673 auto* lhs = ins->lhs();
4674 auto* rhs = ins->rhs();
4675
4676 MOZ_ASSERT(ins->type() == MIRType::Boolean);
4677 MOZ_ASSERT(lhs->type() == MIRType::String);
4678 MOZ_ASSERT(rhs->type() == MIRType::String);
4679
4680 if (!lhs->isTypeOfName() && !rhs->isTypeOfName()) {
4681 return mozilla::Nothing();
4682 }
4683 if (!lhs->isConstant() && !rhs->isConstant()) {
4684 return mozilla::Nothing();
4685 }
4686
4687 auto* typeOfName =
4688 lhs->isTypeOfName() ? lhs->toTypeOfName() : rhs->toTypeOfName();
4689 auto* typeOf = typeOfName->input()->toTypeOf();
4690
4691 auto* constant = lhs->isConstant() ? lhs->toConstant() : rhs->toConstant();
4692
4693 JSType type = TypeOfName(&constant->toString()->asLinear());
4694 return mozilla::Some(TypeOfCompareInput(typeOfName, typeOf, type, false));
4695 }
4696
4697 bool MCompare::tryFoldTypeOf(bool* result) {
4698 auto typeOfCompare = IsTypeOfCompare(this);
4699 if (!typeOfCompare) {
4700 return false;
4701 }
4702 auto* typeOf = typeOfCompare->typeOf;
4703 JSType type = typeOfCompare->type;
4704
4705 // Can't fold if the input is boxed. (Unless the typeof string is bogus.)
4706 MIRType inputType = typeOf->input()->type();
4707 if (inputType == MIRType::Value && type != JSTYPE_LIMIT) {
4708 return false;
4709 }
4710
4711 bool matchesInputType;
4712 switch (type) {
4713 case JSTYPE_BOOLEAN:
4714 matchesInputType = (inputType == MIRType::Boolean);
4715 break;
4716 case JSTYPE_NUMBER:
4717 matchesInputType = IsTypeRepresentableAsDouble(inputType);
4718 break;
4719 case JSTYPE_STRING:
4720 matchesInputType = (inputType == MIRType::String);
4721 break;
4722 case JSTYPE_SYMBOL:
4723 matchesInputType = (inputType == MIRType::Symbol);
4724 break;
4725 case JSTYPE_BIGINT:
4726 matchesInputType = (inputType == MIRType::BigInt);
4727 break;
4728 case JSTYPE_OBJECT:
4729 // Watch out for `object-emulating-undefined` and callable objects.
4730 if (inputType == MIRType::Object) {
4731 return false;
4732 }
4733 matchesInputType = (inputType == MIRType::Null);
4734 break;
4735 case JSTYPE_UNDEFINED:
4736 // Watch out for `object-emulating-undefined`.
4737 if (inputType == MIRType::Object) {
4738 return false;
4739 }
4740 matchesInputType = (inputType == MIRType::Undefined);
4741 break;
4742 case JSTYPE_FUNCTION:
4743 // Can't decide at compile-time if an object is callable.
4744 if (inputType == MIRType::Object) {
4745 return false;
4746 }
4747 matchesInputType = false;
4748 break;
4749 case JSTYPE_LIMIT:
4750 matchesInputType = false;
4751 break;
4752 }
4753
4754 if (matchesInputType) {
4755 *result = (jsop() == JSOp::StrictEq || jsop() == JSOp::Eq);
4756 } else {
4757 *result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
4758 }
4759 return true;
4760 }
4761
4762 bool MCompare::tryFold(bool* result) {
4763 JSOp op = jsop();
4764
4765 if (tryFoldEqualOperands(result)) {
4766 return true;
4767 }
4768
4769 if (tryFoldTypeOf(result)) {
4770 return true;
4771 }
4772
4773 if (compareType_ == Compare_Null || compareType_ == Compare_Undefined) {
4774 // The LHS is the value we want to test against null or undefined.
4775 if (IsStrictEqualityOp(op)) {
4776 MIRType expectedType =
4777 compareType_ == Compare_Null ? MIRType::Null : MIRType::Undefined;
4778 if (lhs()->type() == expectedType) {
4779 *result = (op == JSOp::StrictEq);
4780 return true;
4781 }
4782 if (lhs()->type() != MIRType::Value) {
4783 *result = (op == JSOp::StrictNe);
4784 return true;
4785 }
4786 } else {
4787 MOZ_ASSERT(IsLooseEqualityOp(op));
4788 if (IsNullOrUndefined(lhs()->type())) {
4789 *result = (op == JSOp::Eq);
4790 return true;
4791 }
4792 if (lhs()->type() != MIRType::Object && lhs()->type() != MIRType::Value) {
4793 *result = (op == JSOp::Ne);
4794 return true;
4795 }
4796 }
4797 return false;
4798 }
4799
4800 return false;
4801 }
4802
4803 template <typename T>
4804 static bool FoldComparison(JSOp op, T left, T right) {
4805 switch (op) {
4806 case JSOp::Lt:
4807 return left < right;
4808 case JSOp::Le:
4809 return left <= right;
4810 case JSOp::Gt:
4811 return left > right;
4812 case JSOp::Ge:
4813 return left >= right;
4814 case JSOp::StrictEq:
4815 case JSOp::Eq:
4816 return left == right;
4817 case JSOp::StrictNe:
4818 case JSOp::Ne:
4819 return left != right;
4820 default:
4821 MOZ_CRASH("Unexpected op.");
4822 }
4823 }
4824
4825 static bool FoldBigIntComparison(JSOp op, const BigInt* left, double right) {
4826 switch (op) {
4827 case JSOp::Lt:
4828 return BigInt::lessThan(left, right).valueOr(false);
4829 case JSOp::Le:
4830 return !BigInt::lessThan(right, left).valueOr(true);
4831 case JSOp::Gt:
4832 return BigInt::lessThan(right, left).valueOr(false);
4833 case JSOp::Ge:
4834 return !BigInt::lessThan(left, right).valueOr(true);
4835 case JSOp::StrictEq:
4836 case JSOp::Eq:
4837 return BigInt::equal(left, right);
4838 case JSOp::StrictNe:
4839 case JSOp::Ne:
4840 return !BigInt::equal(left, right);
4841 default:
4842 MOZ_CRASH("Unexpected op.");
4843 }
4844 }
4845
4846 bool MCompare::evaluateConstantOperands(TempAllocator& alloc, bool* result) {
4847 if (type() != MIRType::Boolean && type() != MIRType::Int32) {
4848 return false;
4849 }
4850
4851 MDefinition* left = getOperand(0);
4852 MDefinition* right = getOperand(1);
4853
4854 if (compareType() == Compare_Double) {
4855 // Optimize "MCompare MConstant (MToDouble SomethingInInt32Range).
4856 // In most cases the MToDouble was added, because the constant is
4857 // a double.
4858 // e.g. v < 9007199254740991, where v is an int32 is always true.
4859 if (!lhs()->isConstant() && !rhs()->isConstant()) {
4860 return false;
4861 }
4862
4863 MDefinition* operand = left->isConstant() ? right : left;
4864 MConstant* constant =
4865 left->isConstant() ? left->toConstant() : right->toConstant();
4866 MOZ_ASSERT(constant->type() == MIRType::Double);
4867 double cte = constant->toDouble();
4868
4869 if (operand->isToDouble() &&
4870 operand->getOperand(0)->type() == MIRType::Int32) {
4871 bool replaced = false;
4872 switch (jsop_) {
4873 case JSOp::Lt:
4874 if (cte > INT32_MAX || cte < INT32_MIN) {
4875 *result = !((constant == lhs()) ^ (cte < INT32_MIN));
4876 replaced = true;
4877 }
4878 break;
4879 case JSOp::Le:
4880 if (constant == lhs()) {
4881 if (cte > INT32_MAX || cte <= INT32_MIN) {
4882 *result = (cte <= INT32_MIN);
4883 replaced = true;
4884 }
4885 } else {
4886 if (cte >= INT32_MAX || cte < INT32_MIN) {
4887 *result = (cte >= INT32_MIN);
4888 replaced = true;
4889 }
4890 }
4891 break;
4892 case JSOp::Gt:
4893 if (cte > INT32_MAX || cte < INT32_MIN) {
4894 *result = !((constant == rhs()) ^ (cte < INT32_MIN));
4895 replaced = true;
4896 }
4897 break;
4898 case JSOp::Ge:
4899 if (constant == lhs()) {
4900 if (cte >= INT32_MAX || cte < INT32_MIN) {
4901 *result = (cte >= INT32_MAX);
4902 replaced = true;
4903 }
4904 } else {
4905 if (cte > INT32_MAX || cte <= INT32_MIN) {
4906 *result = (cte <= INT32_MIN);
4907 replaced = true;
4908 }
4909 }
4910 break;
4911 case JSOp::StrictEq: // Fall through.
4912 case JSOp::Eq:
4913 if (cte > INT32_MAX || cte < INT32_MIN) {
4914 *result = false;
4915 replaced = true;
4916 }
4917 break;
4918 case JSOp::StrictNe: // Fall through.
4919 case JSOp::Ne:
4920 if (cte > INT32_MAX || cte < INT32_MIN) {
4921 *result = true;
4922 replaced = true;
4923 }
4924 break;
4925 default:
4926 MOZ_CRASH("Unexpected op.");
4927 }
4928 if (replaced) {
4929 MLimitedTruncate* limit = MLimitedTruncate::New(
4930 alloc, operand->getOperand(0), TruncateKind::NoTruncate);
4931 limit->setGuardUnchecked();
4932 block()->insertBefore(this, limit);
4933 return true;
4934 }
4935 }
4936
4937 // Optimize comparison against NaN.
4938 if (std::isnan(cte)) {
4939 switch (jsop_) {
4940 case JSOp::Lt:
4941 case JSOp::Le:
4942 case JSOp::Gt:
4943 case JSOp::Ge:
4944 case JSOp::Eq:
4945 case JSOp::StrictEq:
4946 *result = false;
4947 break;
4948 case JSOp::Ne:
4949 case JSOp::StrictNe:
4950 *result = true;
4951 break;
4952 default:
4953 MOZ_CRASH("Unexpected op.");
4954 }
4955 return true;
4956 }
4957 }
4958
4959 if (!left->isConstant() || !right->isConstant()) {
4960 return false;
4961 }
4962
4963 MConstant* lhs = left->toConstant();
4964 MConstant* rhs = right->toConstant();
4965
4966 switch (compareType()) {
4967 case Compare_Int32:
4968 case Compare_Double:
4969 case Compare_Float32: {
4970 *result =
4971 FoldComparison(jsop_, lhs->numberToDouble(), rhs->numberToDouble());
4972 return true;
4973 }
4974 case Compare_UInt32: {
4975 *result = FoldComparison(jsop_, uint32_t(lhs->toInt32()),
4976 uint32_t(rhs->toInt32()));
4977 return true;
4978 }
4979 case Compare_Int64: {
4980 *result = FoldComparison(jsop_, lhs->toInt64(), rhs->toInt64());
4981 return true;
4982 }
4983 case Compare_UInt64: {
4984 *result = FoldComparison(jsop_, uint64_t(lhs->toInt64()),
4985 uint64_t(rhs->toInt64()));
4986 return true;
4987 }
4988 case Compare_IntPtr: {
4989 *result = FoldComparison(jsop_, lhs->toIntPtr(), rhs->toIntPtr());
4990 return true;
4991 }
4992 case Compare_UIntPtr: {
4993 *result = FoldComparison(jsop_, uintptr_t(lhs->toIntPtr()),
4994 uintptr_t(rhs->toIntPtr()));
4995 return true;
4996 }
4997 case Compare_String: {
4998 int32_t comp = CompareStrings(&lhs->toString()->asLinear(),
4999 &rhs->toString()->asLinear());
5000 *result = FoldComparison(jsop_, comp, 0);
5001 return true;
5002 }
5003 case Compare_BigInt: {
5004 int32_t comp = BigInt::compare(lhs->toBigInt(), rhs->toBigInt());
5005 *result = FoldComparison(jsop_, comp, 0);
5006 return true;
5007 }
5008 case Compare_BigInt_Int32:
5009 case Compare_BigInt_Double: {
5010 *result =
5011 FoldBigIntComparison(jsop_, lhs->toBigInt(), rhs->numberToDouble());
5012 return true;
5013 }
5014 case Compare_BigInt_String: {
5015 JSLinearString* linear = &rhs->toString()->asLinear();
5016 if (!linear->hasIndexValue()) {
5017 return false;
5018 }
5019 *result =
5020 FoldBigIntComparison(jsop_, lhs->toBigInt(), linear->getIndexValue());
5021 return true;
5022 }
5023
5024 case Compare_Undefined:
5025 case Compare_Null:
5026 case Compare_Symbol:
5027 case Compare_Object:
5028 case Compare_WasmAnyRef:
5029 return false;
5030 }
5031
5032 MOZ_CRASH("unexpected compare type");
5033 }
5034
5035 MDefinition* MCompare::tryFoldTypeOf(TempAllocator& alloc) {
5036 auto typeOfCompare = IsTypeOfCompare(this);
5037 if (!typeOfCompare) {
5038 return this;
5039 }
5040 auto* typeOf = typeOfCompare->typeOf;
5041 JSType type = typeOfCompare->type;
5042
5043 auto* input = typeOf->input();
5044 MOZ_ASSERT(input->type() == MIRType::Value ||
5045 input->type() == MIRType::Object);
5046
5047 // Constant typeof folding handles the other cases.
5048 MOZ_ASSERT_IF(input->type() == MIRType::Object, type == JSTYPE_UNDEFINED ||
5049 type == JSTYPE_OBJECT ||
5050 type == JSTYPE_FUNCTION);
5051
5052 MOZ_ASSERT(type != JSTYPE_LIMIT, "unknown typeof strings folded earlier");
5053
5054 // If there's only a single use, assume this |typeof| is used in a simple
5055 // comparison context.
5056 //
5057 // if (typeof thing === "number") { ... }
5058 //
5059 // It'll be compiled into something similar to:
5060 //
5061 // if (IsNumber(thing)) { ... }
5062 //
5063 // This heuristic can go wrong when repeated |typeof| are used in consecutive
5064 // if-statements.
5065 //
5066 // if (typeof thing === "number") { ... }
5067 // else if (typeof thing === "string") { ... }
5068 // ... repeated for all possible types
5069 //
5070 // In that case it'd more efficient to emit MTypeOf compared to MTypeOfIs. We
5071 // don't yet handle that case, because it'd require a separate optimization
5072 // pass to correctly detect it.
5073 if (typeOfCompare->typeOfSide->hasOneUse()) {
5074 return MTypeOfIs::New(alloc, input, jsop(), type);
5075 }
5076
5077 if (typeOfCompare->isIntComparison) {
5078 // Already optimized.
5079 return this;
5080 }
5081
5082 MConstant* cst = MConstant::New(alloc, Int32Value(type));
5083 block()->insertBefore(this, cst);
5084
5085 return MCompare::New(alloc, typeOf, cst, jsop(), MCompare::Compare_Int32);
5086 }
5087
5088 MDefinition* MCompare::tryFoldCharCompare(TempAllocator& alloc) {
5089 if (compareType() != Compare_String) {
5090 return this;
5091 }
5092
5093 MDefinition* left = lhs();
5094 MOZ_ASSERT(left->type() == MIRType::String);
5095
5096 MDefinition* right = rhs();
5097 MOZ_ASSERT(right->type() == MIRType::String);
5098
5099 // |str[i]| is compiled as |MFromCharCode(MCharCodeAt(str, i))|.
5100 // Out-of-bounds access is compiled as
5101 // |FromCharCodeEmptyIfNegative(CharCodeAtOrNegative(str, i))|.
5102 auto isCharAccess = [](MDefinition* ins) {
5103 if (ins->isFromCharCode()) {
5104 return ins->toFromCharCode()->code()->isCharCodeAt();
5105 }
5106 if (ins->isFromCharCodeEmptyIfNegative()) {
5107 auto* fromCharCode = ins->toFromCharCodeEmptyIfNegative();
5108 return fromCharCode->code()->isCharCodeAtOrNegative();
5109 }
5110 return false;
5111 };
5112
5113 auto charAccessCode = [](MDefinition* ins) {
5114 if (ins->isFromCharCode()) {
5115 return ins->toFromCharCode()->code();
5116 }
5117 return ins->toFromCharCodeEmptyIfNegative()->code();
5118 };
5119
5120 if (left->isConstant() || right->isConstant()) {
5121 // Try to optimize |MConstant(string) <compare> (MFromCharCode MCharCodeAt)|
5122 // as |MConstant(charcode) <compare> MCharCodeAt|.
5123 MConstant* constant;
5124 MDefinition* operand;
5125 if (left->isConstant()) {
5126 constant = left->toConstant();
5127 operand = right;
5128 } else {
5129 constant = right->toConstant();
5130 operand = left;
5131 }
5132
5133 if (constant->toString()->length() != 1 || !isCharAccess(operand)) {
5134 return this;
5135 }
5136
5137 char16_t charCode = constant->toString()->asLinear().latin1OrTwoByteChar(0);
5138 MConstant* charCodeConst = MConstant::New(alloc, Int32Value(charCode));
5139 block()->insertBefore(this, charCodeConst);
5140
5141 MDefinition* charCodeAt = charAccessCode(operand);
5142
5143 if (left->isConstant()) {
5144 left = charCodeConst;
5145 right = charCodeAt;
5146 } else {
5147 left = charCodeAt;
5148 right = charCodeConst;
5149 }
5150 } else if (isCharAccess(left) && isCharAccess(right)) {
5151 // Try to optimize |(MFromCharCode MCharCodeAt) <compare> (MFromCharCode
5152 // MCharCodeAt)| as |MCharCodeAt <compare> MCharCodeAt|.
5153
5154 left = charAccessCode(left);
5155 right = charAccessCode(right);
5156 } else {
5157 return this;
5158 }
5159
5160 return MCompare::New(alloc, left, right, jsop(), MCompare::Compare_Int32);
5161 }
5162
5163 MDefinition* MCompare::tryFoldStringCompare(TempAllocator& alloc) {
5164 if (compareType() != Compare_String) {
5165 return this;
5166 }
5167
5168 MDefinition* left = lhs();
5169 MOZ_ASSERT(left->type() == MIRType::String);
5170
5171 MDefinition* right = rhs();
5172 MOZ_ASSERT(right->type() == MIRType::String);
5173
5174 if (!left->isConstant() && !right->isConstant()) {
5175 return this;
5176 }
5177
5178 // Try to optimize |string <compare> MConstant("")| as |MStringLength(string)
5179 // <compare> MConstant(0)|.
5180
5181 MConstant* constant =
5182 left->isConstant() ? left->toConstant() : right->toConstant();
5183 if (!constant->toString()->empty()) {
5184 return this;
5185 }
5186
5187 MDefinition* operand = left->isConstant() ? right : left;
5188
5189 auto* strLength = MStringLength::New(alloc, operand);
5190 block()->insertBefore(this, strLength);
5191
5192 auto* zero = MConstant::New(alloc, Int32Value(0));
5193 block()->insertBefore(this, zero);
5194
5195 if (left->isConstant()) {
5196 left = zero;
5197 right = strLength;
5198 } else {
5199 left = strLength;
5200 right = zero;
5201 }
5202
5203 return MCompare::New(alloc, left, right, jsop(), MCompare::Compare_Int32);
5204 }
5205
5206 MDefinition* MCompare::tryFoldStringSubstring(TempAllocator& alloc) {
5207 if (compareType() != Compare_String) {
5208 return this;
5209 }
5210 if (!IsEqualityOp(jsop())) {
5211 return this;
5212 }
5213
5214 auto* left = lhs();
5215 MOZ_ASSERT(left->type() == MIRType::String);
5216
5217 auto* right = rhs();
5218 MOZ_ASSERT(right->type() == MIRType::String);
5219
5220 // One operand must be a constant string.
5221 if (!left->isConstant() && !right->isConstant()) {
5222 return this;
5223 }
5224
5225 // The constant string must be non-empty.
5226 auto* constant =
5227 left->isConstant() ? left->toConstant() : right->toConstant();
5228 if (constant->toString()->empty()) {
5229 return this;
5230 }
5231
5232 // The other operand must be a substring operation.
5233 auto* operand = left->isConstant() ? right : left;
5234 if (!operand->isSubstr()) {
5235 return this;
5236 }
5237 auto* substr = operand->toSubstr();
5238
5239 static_assert(JSString::MAX_LENGTH < INT32_MAX,
5240 "string length can be casted to int32_t");
5241
5242 if (!IsSubstrTo(substr, int32_t(constant->toString()->length()))) {
5243 return this;
5244 }
5245
5246 // Now fold code like |str.substring(0, 2) == "aa"| to |str.startsWith("aa")|.
5247
5248 auto* startsWith = MStringStartsWith::New(alloc, substr->string(), constant);
5249 if (jsop() == JSOp::Eq || jsop() == JSOp::StrictEq) {
5250 return startsWith;
5251 }
5252
5253 // Invert for inequality.
5254 MOZ_ASSERT(jsop() == JSOp::Ne || jsop() == JSOp::StrictNe);
5255
5256 block()->insertBefore(this, startsWith);
5257 return MNot::New(alloc, startsWith);
5258 }
5259
5260 MDefinition* MCompare::tryFoldStringIndexOf(TempAllocator& alloc) {
5261 if (compareType() != Compare_Int32) {
5262 return this;
5263 }
5264 if (!IsEqualityOp(jsop())) {
5265 return this;
5266 }
5267
5268 auto* left = lhs();
5269 MOZ_ASSERT(left->type() == MIRType::Int32);
5270
5271 auto* right = rhs();
5272 MOZ_ASSERT(right->type() == MIRType::Int32);
5273
5274 // One operand must be a constant integer.
5275 if (!left->isConstant() && !right->isConstant()) {
5276 return this;
5277 }
5278
5279 // The constant must be zero.
5280 auto* constant =
5281 left->isConstant() ? left->toConstant() : right->toConstant();
5282 if (!constant->isInt32(0)) {
5283 return this;
5284 }
5285
5286 // The other operand must be an indexOf operation.
5287 auto* operand = left->isConstant() ? right : left;
5288 if (!operand->isStringIndexOf()) {
5289 return this;
5290 }
5291
5292 // Fold |str.indexOf(searchStr) == 0| to |str.startsWith(searchStr)|.
5293
5294 auto* indexOf = operand->toStringIndexOf();
5295 auto* startsWith =
5296 MStringStartsWith::New(alloc, indexOf->string(), indexOf->searchString());
5297 if (jsop() == JSOp::Eq || jsop() == JSOp::StrictEq) {
5298 return startsWith;
5299 }
5300
5301 // Invert for inequality.
5302 MOZ_ASSERT(jsop() == JSOp::Ne || jsop() == JSOp::StrictNe);
5303
5304 block()->insertBefore(this, startsWith);
5305 return MNot::New(alloc, startsWith);
5306 }
5307
5308 MDefinition* MCompare::tryFoldBigInt64(TempAllocator& alloc) {
5309 if (compareType() == Compare_BigInt) {
5310 auto* left = lhs();
5311 MOZ_ASSERT(left->type() == MIRType::BigInt);
5312
5313 auto* right = rhs();
5314 MOZ_ASSERT(right->type() == MIRType::BigInt);
5315
5316 // At least one operand must be MInt64ToBigInt.
5317 if (!left->isInt64ToBigInt() && !right->isInt64ToBigInt()) {
5318 return this;
5319 }
5320
5321 // Unwrap MInt64ToBigInt on both sides and perform a Int64 comparison.
5322 if (left->isInt64ToBigInt() && right->isInt64ToBigInt()) {
5323 auto* lhsInt64 = left->toInt64ToBigInt();
5324 auto* rhsInt64 = right->toInt64ToBigInt();
5325
5326 // Don't optimize if Int64 against Uint64 comparison.
5327 if (lhsInt64->isSigned() != rhsInt64->isSigned()) {
5328 return this;
5329 }
5330
5331 bool isSigned = lhsInt64->isSigned();
5332 auto compareType =
5333 isSigned ? MCompare::Compare_Int64 : MCompare::Compare_UInt64;
5334 return MCompare::New(alloc, lhsInt64->input(), rhsInt64->input(), jsop_,
5335 compareType);
5336 }
5337
5338 // Optimize IntPtr x Int64 comparison to Int64 x Int64 comparison.
5339 if (left->isIntPtrToBigInt() || right->isIntPtrToBigInt()) {
5340 auto* int64ToBigInt = left->isInt64ToBigInt() ? left->toInt64ToBigInt()
5341 : right->toInt64ToBigInt();
5342
5343 // Can't optimize when comparing Uint64 against IntPtr.
5344 if (!int64ToBigInt->isSigned()) {
5345 return this;
5346 }
5347
5348 auto* intPtrToBigInt = left->isIntPtrToBigInt()
5349 ? left->toIntPtrToBigInt()
5350 : right->toIntPtrToBigInt();
5351
5352 auto* intPtrToInt64 = MIntPtrToInt64::New(alloc, intPtrToBigInt->input());
5353 block()->insertBefore(this, intPtrToInt64);
5354
5355 if (left == int64ToBigInt) {
5356 left = int64ToBigInt->input();
5357 right = intPtrToInt64;
5358 } else {
5359 left = intPtrToInt64;
5360 right = int64ToBigInt->input();
5361 }
5362 return MCompare::New(alloc, left, right, jsop_, MCompare::Compare_Int64);
5363 }
5364
5365 // The other operand must be a constant.
5366 if (!left->isConstant() && !right->isConstant()) {
5367 return this;
5368 }
5369
5370 auto* int64ToBigInt = left->isInt64ToBigInt() ? left->toInt64ToBigInt()
5371 : right->toInt64ToBigInt();
5372 bool isSigned = int64ToBigInt->isSigned();
5373
5374 auto* constant =
5375 left->isConstant() ? left->toConstant() : right->toConstant();
5376 auto* bigInt = constant->toBigInt();
5377
5378 // Extract the BigInt value if representable as Int64/Uint64.
5379 mozilla::Maybe<int64_t> value;
5380 if (isSigned) {
5381 int64_t x;
5382 if (BigInt::isInt64(bigInt, &x)) {
5383 value = mozilla::Some(x);
5384 }
5385 } else {
5386 uint64_t x;
5387 if (BigInt::isUint64(bigInt, &x)) {
5388 value = mozilla::Some(static_cast<int64_t>(x));
5389 }
5390 }
5391
5392 // The comparison is a constant if the BigInt has too many digits.
5393 if (!value) {
5394 int32_t repr = bigInt->isNegative() ? -1 : 1;
5395
5396 bool result;
5397 if (left == int64ToBigInt) {
5398 result = FoldComparison(jsop_, 0, repr);
5399 } else {
5400 result = FoldComparison(jsop_, repr, 0);
5401 }
5402 return MConstant::New(alloc, BooleanValue(result));
5403 }
5404
5405 auto* cst = MConstant::NewInt64(alloc, *value);
5406 block()->insertBefore(this, cst);
5407
5408 auto compareType =
5409 isSigned ? MCompare::Compare_Int64 : MCompare::Compare_UInt64;
5410 if (left == int64ToBigInt) {
5411 return MCompare::New(alloc, int64ToBigInt->input(), cst, jsop_,
5412 compareType);
5413 }
5414 return MCompare::New(alloc, cst, int64ToBigInt->input(), jsop_,
5415 compareType);
5416 }
5417
5418 if (compareType() == Compare_BigInt_Int32) {
5419 auto* left = lhs();
5420 MOZ_ASSERT(left->type() == MIRType::BigInt);
5421
5422 auto* right = rhs();
5423 MOZ_ASSERT(right->type() == MIRType::Int32);
5424
5425 // Optimize MInt64ToBigInt against a constant int32.
5426 if (!left->isInt64ToBigInt() || !right->isConstant()) {
5427 return this;
5428 }
5429
5430 auto* int64ToBigInt = left->toInt64ToBigInt();
5431 bool isSigned = int64ToBigInt->isSigned();
5432
5433 int32_t constInt32 = right->toConstant()->toInt32();
5434
5435 // The unsigned comparison against a negative operand is a constant.
5436 if (!isSigned && constInt32 < 0) {
5437 bool result = FoldComparison(jsop_, 0, constInt32);
5438 return MConstant::New(alloc, BooleanValue(result));
5439 }
5440
5441 auto* cst = MConstant::NewInt64(alloc, int64_t(constInt32));
5442 block()->insertBefore(this, cst);
5443
5444 auto compareType =
5445 isSigned ? MCompare::Compare_Int64 : MCompare::Compare_UInt64;
5446 return MCompare::New(alloc, int64ToBigInt->input(), cst, jsop_,
5447 compareType);
5448 }
5449
5450 return this;
5451 }
5452
5453 MDefinition* MCompare::tryFoldBigIntPtr(TempAllocator& alloc) {
5454 if (compareType() == Compare_BigInt) {
5455 auto* left = lhs();
5456 MOZ_ASSERT(left->type() == MIRType::BigInt);
5457
5458 auto* right = rhs();
5459 MOZ_ASSERT(right->type() == MIRType::BigInt);
5460
5461 // At least one operand must be MIntPtrToBigInt.
5462 if (!left->isIntPtrToBigInt() && !right->isIntPtrToBigInt()) {
5463 return this;
5464 }
5465
5466 // Unwrap MIntPtrToBigInt on both sides and perform an IntPtr comparison.
5467 if (left->isIntPtrToBigInt() && right->isIntPtrToBigInt()) {
5468 auto* lhsIntPtr = left->toIntPtrToBigInt();
5469 auto* rhsIntPtr = right->toIntPtrToBigInt();
5470
5471 return MCompare::New(alloc, lhsIntPtr->input(), rhsIntPtr->input(), jsop_,
5472 MCompare::Compare_IntPtr);
5473 }
5474
5475 // The other operand must be a constant.
5476 if (!left->isConstant() && !right->isConstant()) {
5477 return this;
5478 }
5479
5480 auto* intPtrToBigInt = left->isIntPtrToBigInt() ? left->toIntPtrToBigInt()
5481 : right->toIntPtrToBigInt();
5482
5483 auto* constant =
5484 left->isConstant() ? left->toConstant() : right->toConstant();
5485 auto* bigInt = constant->toBigInt();
5486
5487 // Extract the BigInt value if representable as intptr_t.
5488 intptr_t value;
5489 if (!BigInt::isIntPtr(bigInt, &value)) {
5490 // The comparison is a constant if the BigInt has too many digits.
5491 int32_t repr = bigInt->isNegative() ? -1 : 1;
5492
5493 bool result;
5494 if (left == intPtrToBigInt) {
5495 result = FoldComparison(jsop_, 0, repr);
5496 } else {
5497 result = FoldComparison(jsop_, repr, 0);
5498 }
5499 return MConstant::New(alloc, BooleanValue(result));
5500 }
5501
5502 auto* cst = MConstant::NewIntPtr(alloc, value);
5503 block()->insertBefore(this, cst);
5504
5505 if (left == intPtrToBigInt) {
5506 left = intPtrToBigInt->input();
5507 right = cst;
5508 } else {
5509 left = cst;
5510 right = intPtrToBigInt->input();
5511 }
5512 return MCompare::New(alloc, left, right, jsop_, MCompare::Compare_IntPtr);
5513 }
5514
5515 if (compareType() == Compare_BigInt_Int32) {
5516 auto* left = lhs();
5517 MOZ_ASSERT(left->type() == MIRType::BigInt);
5518
5519 auto* right = rhs();
5520 MOZ_ASSERT(right->type() == MIRType::Int32);
5521
5522 // Optimize MIntPtrToBigInt against a constant int32.
5523 if (!left->isIntPtrToBigInt() || !right->isConstant()) {
5524 return this;
5525 }
5526
5527 auto* cst =
5528 MConstant::NewIntPtr(alloc, intptr_t(right->toConstant()->toInt32()));
5529 block()->insertBefore(this, cst);
5530
5531 return MCompare::New(alloc, left->toIntPtrToBigInt()->input(), cst, jsop_,
5532 MCompare::Compare_IntPtr);
5533 }
5534
5535 return this;
5536 }
5537
5538 MDefinition* MCompare::tryFoldBigInt(TempAllocator& alloc) {
5539 if (compareType() != Compare_BigInt) {
5540 return this;
5541 }
5542
5543 auto* left = lhs();
5544 MOZ_ASSERT(left->type() == MIRType::BigInt);
5545
5546 auto* right = rhs();
5547 MOZ_ASSERT(right->type() == MIRType::BigInt);
5548
5549 // One operand must be a constant.
5550 if (!left->isConstant() && !right->isConstant()) {
5551 return this;
5552 }
5553
5554 auto* constant =
5555 left->isConstant() ? left->toConstant() : right->toConstant();
5556 auto* operand = left->isConstant() ? right : left;
5557
5558 // The constant must be representable as an Int32.
5559 int32_t x;
5560 if (!BigInt::isInt32(constant->toBigInt(), &x)) {
5561 return this;
5562 }
5563
5564 MConstant* int32Const = MConstant::New(alloc, Int32Value(x));
5565 block()->insertBefore(this, int32Const);
5566
5567 auto op = jsop();
5568 if (IsStrictEqualityOp(op)) {
5569 // Compare_BigInt_Int32 is only valid for loose comparison.
5570 op = op == JSOp::StrictEq ? JSOp::Eq : JSOp::Ne;
5571 } else if (operand == right) {
5572 // Reverse the comparison operator if the operands were reordered.
5573 op = ReverseCompareOp(op);
5574 }
5575
5576 return MCompare::New(alloc, operand, int32Const, op,
5577 MCompare::Compare_BigInt_Int32);
5578 }
5579
5580 MDefinition* MCompare::foldsTo(TempAllocator& alloc) {
5581 bool result;
5582
5583 if (tryFold(&result) || evaluateConstantOperands(alloc, &result)) {
5584 if (type() == MIRType::Int32) {
5585 return MConstant::New(alloc, Int32Value(result));
5586 }
5587
5588 MOZ_ASSERT(type() == MIRType::Boolean);
5589 return MConstant::New(alloc, BooleanValue(result));
5590 }
5591
5592 if (MDefinition* folded = tryFoldTypeOf(alloc); folded != this) {
5593 return folded;
5594 }
5595
5596 if (MDefinition* folded = tryFoldCharCompare(alloc); folded != this) {
5597 return folded;
5598 }
5599
5600 if (MDefinition* folded = tryFoldStringCompare(alloc); folded != this) {
5601 return folded;
5602 }
5603
5604 if (MDefinition* folded = tryFoldStringSubstring(alloc); folded != this) {
5605 return folded;
5606 }
5607
5608 if (MDefinition* folded = tryFoldStringIndexOf(alloc); folded != this) {
5609 return folded;
5610 }
5611
5612 if (MDefinition* folded = tryFoldBigInt64(alloc); folded != this) {
5613 return folded;
5614 }
5615
5616 if (MDefinition* folded = tryFoldBigIntPtr(alloc); folded != this) {
5617 return folded;
5618 }
5619
5620 if (MDefinition* folded = tryFoldBigInt(alloc); folded != this) {
5621 return folded;
5622 }
5623
5624 return this;
5625 }
5626
5627 void MCompare::trySpecializeFloat32(TempAllocator& alloc) {
5628 if (AllOperandsCanProduceFloat32(this) && compareType_ == Compare_Double) {
5629 compareType_ = Compare_Float32;
5630 } else {
5631 ConvertOperandsToDouble(this, alloc);
5632 }
5633 }
5634
5635 MDefinition* MSameValue::foldsTo(TempAllocator& alloc) {
5636 MDefinition* lhs = left();
5637 if (lhs->isBox()) {
5638 lhs = lhs->toBox()->input();
5639 }
5640
5641 MDefinition* rhs = right();
5642 if (rhs->isBox()) {
5643 rhs = rhs->toBox()->input();
5644 }
5645
5646 // Trivially true if both operands are the same.
5647 if (lhs == rhs) {
5648 return MConstant::New(alloc, BooleanValue(true));
5649 }
5650
5651 // CacheIR optimizes the following cases, so don't bother to handle them here:
5652 // 1. Both inputs are numbers (int32 or double).
5653 // 2. Both inputs are strictly different types.
5654 // 3. Both inputs are the same type.
5655
5656 // Optimize when one operand is guaranteed to be |null|.
5657 if (lhs->type() == MIRType::Null || rhs->type() == MIRType::Null) {
5658 // The `null` value must be the right-hand side operand.
5659 auto* input = lhs->type() == MIRType::Null ? rhs : lhs;
5660 auto* cst = lhs->type() == MIRType::Null ? lhs : rhs;
5661 return MCompare::New(alloc, input, cst, JSOp::StrictEq,
5662 MCompare::Compare_Null);
5663 }
5664
5665 // Optimize when one operand is guaranteed to be |undefined|.
5666 if (lhs->type() == MIRType::Undefined || rhs->type() == MIRType::Undefined) {
5667 // The `undefined` value must be the right-hand side operand.
5668 auto* input = lhs->type() == MIRType::Undefined ? rhs : lhs;
5669 auto* cst = lhs->type() == MIRType::Undefined ? lhs : rhs;
5670 return MCompare::New(alloc, input, cst, JSOp::StrictEq,
5671 MCompare::Compare_Undefined);
5672 }
5673
5674 return this;
5675 }
5676
5677 MDefinition* MSameValueDouble::foldsTo(TempAllocator& alloc) {
5678 // Trivially true if both operands are the same.
5679 if (left() == right()) {
5680 return MConstant::New(alloc, BooleanValue(true));
5681 }
5682
5683 // At least one operand must be a constant.
5684 if (!left()->isConstant() && !right()->isConstant()) {
5685 return this;
5686 }
5687
5688 auto* input = left()->isConstant() ? right() : left();
5689 auto* cst = left()->isConstant() ? left() : right();
5690 double dbl = cst->toConstant()->toDouble();
5691
5692 // Use bitwise comparison for +/-0.
5693 if (dbl == 0.0) {
5694 auto* reinterp = MReinterpretCast::New(alloc, input, MIRType::Int64);
5695 block()->insertBefore(this, reinterp);
5696
5697 auto* zeroBitsCst =
5698 MConstant::NewInt64(alloc, mozilla::BitwiseCast<int64_t>(dbl));
5699 block()->insertBefore(this, zeroBitsCst);
5700
5701 return MCompare::New(alloc, reinterp, zeroBitsCst, JSOp::StrictEq,
5702 MCompare::Compare_Int64);
5703 }
5704
5705 // Fold `Object.is(d, NaN)` to `d !== d`.
5706 if (std::isnan(dbl)) {
5707 return MCompare::New(alloc, input, input, JSOp::StrictNe,
5708 MCompare::Compare_Double);
5709 }
5710
5711 // Otherwise fold to MCompare.
5712 return MCompare::New(alloc, left(), right(), JSOp::StrictEq,
5713 MCompare::Compare_Double);
5714 }
5715
5716 MDefinition* MNot::foldsTo(TempAllocator& alloc) {
5717 auto foldConstant = [&alloc](MDefinition* input, MIRType type) -> MConstant* {
5718 MConstant* inputConst = input->maybeConstantValue();
5719 if (!inputConst) {
5720 return nullptr;
5721 }
5722 bool b;
5723 if (!inputConst->valueToBoolean(&b)) {
5724 return nullptr;
5725 }
5726 if (type == MIRType::Int32) {
5727 return MConstant::New(alloc, Int32Value(!b));
5728 }
5729 MOZ_ASSERT(type == MIRType::Boolean);
5730 return MConstant::New(alloc, BooleanValue(!b));
5731 };
5732
5733 // Fold if the input is constant.
5734 if (MConstant* folded = foldConstant(input(), type())) {
5735 return folded;
5736 }
5737
5738 // If the operand of the Not is itself a Not, they cancel out. But we can't
5739 // always convert Not(Not(x)) to x because that may loose the conversion to
5740 // boolean. We can simplify Not(Not(Not(x))) to Not(x) though.
5741 MDefinition* op = getOperand(0);
5742 if (op->isNot()) {
5743 MDefinition* opop = op->getOperand(0);
5744 if (opop->isNot()) {
5745 return opop;
5746 }
5747 }
5748
5749 // Not of an undefined or null value is always true
5750 if (input()->type() == MIRType::Undefined ||
5751 input()->type() == MIRType::Null) {
5752 return MConstant::New(alloc, BooleanValue(true));
5753 }
5754
5755 // Not of a symbol is always false.
5756 if (input()->type() == MIRType::Symbol) {
5757 return MConstant::New(alloc, BooleanValue(false));
5758 }
5759
5760 // Drop the conversion in `Not(Int64ToBigInt(int64))` to `Not(int64)`.
5761 if (input()->isInt64ToBigInt()) {
5762 MDefinition* int64 = input()->toInt64ToBigInt()->input();
5763 if (MConstant* folded = foldConstant(int64, type())) {
5764 return folded;
5765 }
5766 return MNot::New(alloc, int64);
5767 }
5768
5769 // Drop the conversion in `Not(IntPtrToBigInt(intptr))` to `Not(intptr)`.
5770 if (input()->isIntPtrToBigInt()) {
5771 MDefinition* intPtr = input()->toIntPtrToBigInt()->input();
5772 if (MConstant* folded = foldConstant(intPtr, type())) {
5773 return folded;
5774 }
5775 return MNot::New(alloc, intPtr);
5776 }
5777
5778 return this;
5779 }
5780
5781 void MNot::trySpecializeFloat32(TempAllocator& alloc) {
5782 (void)EnsureFloatInputOrConvert(this, alloc);
5783 }
5784
5785 #ifdef JS_JITSPEW
5786 void MBeta::printOpcode(GenericPrinter& out) const {
5787 MDefinition::printOpcode(out);
5788
5789 out.printf(" ");
5790 comparison_->dump(out);
5791 }
5792 #endif
5793
5794 AliasSet MCreateThis::getAliasSet() const {
5795 return AliasSet::Load(AliasSet::Any);
5796 }
5797
5798 bool MGetArgumentsObjectArg::congruentTo(const MDefinition* ins) const {
5799 if (!ins->isGetArgumentsObjectArg()) {
5800 return false;
5801 }
5802 if (ins->toGetArgumentsObjectArg()->argno() != argno()) {
5803 return false;
5804 }
5805 return congruentIfOperandsEqual(ins);
5806 }
5807
5808 AliasSet MGetArgumentsObjectArg::getAliasSet() const {
5809 return AliasSet::Load(AliasSet::Any);
5810 }
5811
5812 AliasSet MSetArgumentsObjectArg::getAliasSet() const {
5813 return AliasSet::Store(AliasSet::Any);
5814 }
5815
5816 MObjectState::MObjectState(MObjectState* state)
5817 : MVariadicInstruction(classOpcode),
5818 numSlots_(state->numSlots_),
5819 numFixedSlots_(state->numFixedSlots_) {
5820 // This instruction is only used as a summary for bailout paths.
5821 setResultType(MIRType::Object);
5822 setRecoveredOnBailout();
5823 }
5824
5825 MObjectState::MObjectState(JSObject* templateObject)
5826 : MObjectState(templateObject->as<NativeObject>().shape()) {}
5827
5828 MObjectState::MObjectState(const Shape* shape)
5829 : MVariadicInstruction(classOpcode) {
5830 // This instruction is only used as a summary for bailout paths.
5831 setResultType(MIRType::Object);
5832 setRecoveredOnBailout();
5833
5834 numSlots_ = shape->asShared().slotSpan();
5835 numFixedSlots_ = shape->asShared().numFixedSlots();
5836 }
5837
5838 /* static */
5839 JSObject* MObjectState::templateObjectOf(MDefinition* obj) {
5840 // MNewPlainObject uses a shape constant, not an object.
5841 MOZ_ASSERT(!obj->isNewPlainObject());
5842
5843 if (obj->isNewObject()) {
5844 return obj->toNewObject()->templateObject();
5845 } else if (obj->isNewCallObject()) {
5846 return obj->toNewCallObject()->templateObject();
5847 } else if (obj->isNewIterator()) {
5848 return obj->toNewIterator()->templateObject();
5849 }
5850
5851 MOZ_CRASH("unreachable");
5852 }
5853
5854 bool MObjectState::init(TempAllocator& alloc, MDefinition* obj) {
5855 if (!MVariadicInstruction::init(alloc, numSlots() + 1)) {
5856 return false;
5857 }
5858 // +1, for the Object.
5859 initOperand(0, obj);
5860 return true;
5861 }
5862
5863 void MObjectState::initFromTemplateObject(TempAllocator& alloc,
5864 MDefinition* undefinedVal) {
5865 if (object()->isNewPlainObject()) {
5866 MOZ_ASSERT(object()->toNewPlainObject()->shape()->asShared().slotSpan() ==
5867 numSlots());
5868 for (size_t i = 0; i < numSlots(); i++) {
5869 initSlot(i, undefinedVal);
5870 }
5871 return;
5872 }
5873
5874 JSObject* templateObject = templateObjectOf(object());
5875
5876 // Initialize all the slots of the object state with the value contained in
5877 // the template object. This is needed to account values which are baked in
5878 // the template objects and not visible in IonMonkey, such as the
5879 // uninitialized-lexical magic value of call objects.
5880
5881 MOZ_ASSERT(templateObject->is<NativeObject>());
5882 NativeObject& nativeObject = templateObject->as<NativeObject>();
5883 MOZ_ASSERT(nativeObject.slotSpan() == numSlots());
5884
5885 for (size_t i = 0; i < numSlots(); i++) {
5886 Value val = nativeObject.getSlot(i);
5887 MDefinition* def = undefinedVal;
5888 if (!val.isUndefined()) {
5889 MConstant* ins = MConstant::New(alloc, val);
5890 block()->insertBefore(this, ins);
5891 def = ins;
5892 }
5893 initSlot(i, def);
5894 }
5895 }
5896
5897 MObjectState* MObjectState::New(TempAllocator& alloc, MDefinition* obj) {
5898 MObjectState* res;
5899 if (obj->isNewPlainObject()) {
5900 const Shape* shape = obj->toNewPlainObject()->shape();
5901 res = new (alloc) MObjectState(shape);
5902 } else {
5903 JSObject* templateObject = templateObjectOf(obj);
5904 MOZ_ASSERT(templateObject, "Unexpected object creation.");
5905 res = new (alloc) MObjectState(templateObject);
5906 }
5907
5908 if (!res || !res->init(alloc, obj)) {
5909 return nullptr;
5910 }
5911 return res;
5912 }
5913
5914 MObjectState* MObjectState::Copy(TempAllocator& alloc, MObjectState* state) {
5915 MObjectState* res = new (alloc) MObjectState(state);
5916 if (!res || !res->init(alloc, state->object())) {
5917 return nullptr;
5918 }
5919 for (size_t i = 0; i < res->numSlots(); i++) {
5920 res->initSlot(i, state->getSlot(i));
5921 }
5922 return res;
5923 }
5924
5925 MArrayState::MArrayState(MDefinition* arr) : MVariadicInstruction(classOpcode) {
5926 // This instruction is only used as a summary for bailout paths.
5927 setResultType(MIRType::Object);
5928 setRecoveredOnBailout();
5929 if (arr->isNewArrayObject()) {
5930 numElements_ = arr->toNewArrayObject()->length();
5931 } else {
5932 numElements_ = arr->toNewArray()->length();
5933 }
5934 }
5935
5936 bool MArrayState::init(TempAllocator& alloc, MDefinition* obj,
5937 MDefinition* len) {
5938 if (!MVariadicInstruction::init(alloc, numElements() + 2)) {
5939 return false;
5940 }
5941 // +1, for the Array object.
5942 initOperand(0, obj);
5943 // +1, for the length value of the array.
5944 initOperand(1, len);
5945 return true;
5946 }
5947
5948 void MArrayState::initFromTemplateObject(TempAllocator& alloc,
5949 MDefinition* undefinedVal) {
5950 for (size_t i = 0; i < numElements(); i++) {
5951 initElement(i, undefinedVal);
5952 }
5953 }
5954
5955 MArrayState* MArrayState::New(TempAllocator& alloc, MDefinition* arr,
5956 MDefinition* initLength) {
5957 MArrayState* res = new (alloc) MArrayState(arr);
5958 if (!res || !res->init(alloc, arr, initLength)) {
5959 return nullptr;
5960 }
5961 return res;
5962 }
5963
5964 MArrayState* MArrayState::Copy(TempAllocator& alloc, MArrayState* state) {
5965 MDefinition* arr = state->array();
5966 MDefinition* len = state->initializedLength();
5967 MArrayState* res = new (alloc) MArrayState(arr);
5968 if (!res || !res->init(alloc, arr, len)) {
5969 return nullptr;
5970 }
5971 for (size_t i = 0; i < res->numElements(); i++) {
5972 res->initElement(i, state->getElement(i));
5973 }
5974 return res;
5975 }
5976
5977 MNewArray::MNewArray(uint32_t length, MConstant* templateConst,
5978 gc::Heap initialHeap, bool vmCall)
5979 : MUnaryInstruction(classOpcode, templateConst),
5980 length_(length),
5981 initialHeap_(initialHeap),
5982 vmCall_(vmCall) {
5983 setResultType(MIRType::Object);
5984 }
5985
5986 MDefinition::AliasType MLoadFixedSlot::mightAlias(
5987 const MDefinition* def) const {
5988 if (def->isStoreFixedSlot()) {
5989 const MStoreFixedSlot* store = def->toStoreFixedSlot();
5990 if (store->slot() != slot()) {
5991 return AliasType::NoAlias;
5992 }
5993 if (store->object() != object()) {
5994 return AliasType::MayAlias;
5995 }
5996 return AliasType::MustAlias;
5997 }
5998 return AliasType::MayAlias;
5999 }
6000
6001 MDefinition* MLoadFixedSlot::foldsTo(TempAllocator& alloc) {
6002 if (MDefinition* def = foldsToStore(alloc)) {
6003 return def;
6004 }
6005
6006 return this;
6007 }
6008
6009 MDefinition::AliasType MLoadFixedSlotAndUnbox::mightAlias(
6010 const MDefinition* def) const {
6011 if (def->isStoreFixedSlot()) {
6012 const MStoreFixedSlot* store = def->toStoreFixedSlot();
6013 if (store->slot() != slot()) {
6014 return AliasType::NoAlias;
6015 }
6016 if (store->object() != object()) {
6017 return AliasType::MayAlias;
6018 }
6019 return AliasType::MustAlias;
6020 }
6021 return AliasType::MayAlias;
6022 }
6023
6024 MDefinition* MLoadFixedSlotAndUnbox::foldsTo(TempAllocator& alloc) {
6025 if (MDefinition* def = foldsToStore(alloc)) {
6026 return def;
6027 }
6028
6029 return this;
6030 }
6031
6032 MDefinition::AliasType MLoadDynamicSlot::mightAlias(
6033 const MDefinition* def) const {
6034 if (def->isStoreDynamicSlot()) {
6035 const MStoreDynamicSlot* store = def->toStoreDynamicSlot();
6036 if (store->slot() != slot()) {
6037 return AliasType::NoAlias;
6038 }
6039
6040 if (store->slots() != slots()) {
6041 return AliasType::MayAlias;
6042 }
6043
6044 return AliasType::MustAlias;
6045 }
6046 return AliasType::MayAlias;
6047 }
6048
6049 HashNumber MLoadDynamicSlot::valueHash() const {
6050 HashNumber hash = MDefinition::valueHash();
6051 hash = addU32ToHash(hash, slot_);
6052 return hash;
6053 }
6054
6055 MDefinition* MLoadDynamicSlot::foldsTo(TempAllocator& alloc) {
6056 if (MDefinition* def = foldsToStore(alloc)) {
6057 return def;
6058 }
6059
6060 return this;
6061 }
6062
6063 #ifdef JS_JITSPEW
6064 void MLoadDynamicSlot::printOpcode(GenericPrinter& out) const {
6065 MDefinition::printOpcode(out);
6066 out.printf(" (slot %u)", slot());
6067 }
6068
6069 void MLoadDynamicSlotAndUnbox::printOpcode(GenericPrinter& out) const {
6070 MDefinition::printOpcode(out);
6071 out.printf(" (slot %zu)", slot());
6072 }
6073
6074 void MStoreDynamicSlot::printOpcode(GenericPrinter& out) const {
6075 MDefinition::printOpcode(out);
6076 out.printf(" (slot %u)", slot());
6077 }
6078
6079 void MLoadFixedSlot::printOpcode(GenericPrinter& out) const {
6080 MDefinition::printOpcode(out);
6081 out.printf(" (slot %zu)", slot());
6082 }
6083
6084 void MLoadFixedSlotAndUnbox::printOpcode(GenericPrinter& out) const {
6085 MDefinition::printOpcode(out);
6086 out.printf(" (slot %zu)", slot());
6087 }
6088
6089 void MStoreFixedSlot::printOpcode(GenericPrinter& out) const {
6090 MDefinition::printOpcode(out);
6091 out.printf(" (slot %zu)", slot());
6092 }
6093 #endif
6094
6095 MDefinition* MGuardFunctionScript::foldsTo(TempAllocator& alloc) {
6096 MDefinition* in = input();
6097 if (in->isLambda() &&
6098 in->toLambda()->templateFunction()->baseScript() == expected()) {
6099 return in;
6100 }
6101 return this;
6102 }
6103
6104 MDefinition* MFunctionEnvironment::foldsTo(TempAllocator& alloc) {
6105 if (input()->isLambda()) {
6106 return input()->toLambda()->environmentChain();
6107 }
6108 if (input()->isFunctionWithProto()) {
6109 return input()->toFunctionWithProto()->environmentChain();
6110 }
6111 return this;
6112 }
6113
6114 static bool AddIsANonZeroAdditionOf(MAdd* add, MDefinition* ins) {
6115 if (add->lhs() != ins && add->rhs() != ins) {
6116 return false;
6117 }
6118 MDefinition* other = (add->lhs() == ins) ? add->rhs() : add->lhs();
6119 if (!IsNumberType(other->type())) {
6120 return false;
6121 }
6122 if (!other->isConstant()) {
6123 return false;
6124 }
6125 if (other->toConstant()->numberToDouble() == 0) {
6126 return false;
6127 }
6128 return true;
6129 }
6130
6131 // Skip over instructions that usually appear between the actual index
6132 // value being used and the MLoadElement.
6133 // They don't modify the index value in a meaningful way.
6134 static MDefinition* SkipUninterestingInstructions(MDefinition* ins) {
6135 // Drop the MToNumberInt32 added by the TypePolicy for double and float
6136 // values.
6137 if (ins->isToNumberInt32()) {
6138 return SkipUninterestingInstructions(ins->toToNumberInt32()->input());
6139 }
6140
6141 // Ignore the bounds check, which don't modify the index.
6142 if (ins->isBoundsCheck()) {
6143 return SkipUninterestingInstructions(ins->toBoundsCheck()->index());
6144 }
6145
6146 // Masking the index for Spectre-mitigation is not observable.
6147 if (ins->isSpectreMaskIndex()) {
6148 return SkipUninterestingInstructions(ins->toSpectreMaskIndex()->index());
6149 }
6150
6151 return ins;
6152 }
6153
6154 static bool DefinitelyDifferentValue(MDefinition* ins1, MDefinition* ins2) {
6155 ins1 = SkipUninterestingInstructions(ins1);
6156 ins2 = SkipUninterestingInstructions(ins2);
6157
6158 if (ins1 == ins2) {
6159 return false;
6160 }
6161
6162 // For constants check they are not equal.
6163 if (ins1->isConstant() && ins2->isConstant()) {
6164 MConstant* cst1 = ins1->toConstant();
6165 MConstant* cst2 = ins2->toConstant();
6166
6167 if (!cst1->isTypeRepresentableAsDouble() ||
6168 !cst2->isTypeRepresentableAsDouble()) {
6169 return false;
6170 }
6171
6172 // Be conservative and only allow values that fit into int32.
6173 int32_t n1, n2;
6174 if (!mozilla::NumberIsInt32(cst1->numberToDouble(), &n1) ||
6175 !mozilla::NumberIsInt32(cst2->numberToDouble(), &n2)) {
6176 return false;
6177 }
6178
6179 return n1 != n2;
6180 }
6181
6182 // Check if "ins1 = ins2 + cte", which would make both instructions
6183 // have different values.
6184 if (ins1->isAdd()) {
6185 if (AddIsANonZeroAdditionOf(ins1->toAdd(), ins2)) {
6186 return true;
6187 }
6188 }
6189 if (ins2->isAdd()) {
6190 if (AddIsANonZeroAdditionOf(ins2->toAdd(), ins1)) {
6191 return true;
6192 }
6193 }
6194
6195 return false;
6196 }
6197
6198 MDefinition::AliasType MLoadElement::mightAlias(const MDefinition* def) const {
6199 if (def->isStoreElement()) {
6200 const MStoreElement* store = def->toStoreElement();
6201 if (store->index() != index()) {
6202 if (DefinitelyDifferentValue(store->index(), index())) {
6203 return AliasType::NoAlias;
6204 }
6205 return AliasType::MayAlias;
6206 }
6207
6208 if (store->elements() != elements()) {
6209 return AliasType::MayAlias;
6210 }
6211
6212 return AliasType::MustAlias;
6213 }
6214 return AliasType::MayAlias;
6215 }
6216
6217 MDefinition* MLoadElement::foldsTo(TempAllocator& alloc) {
6218 if (MDefinition* def = foldsToStore(alloc)) {
6219 return def;
6220 }
6221
6222 return this;
6223 }
6224
6225 void MSqrt::trySpecializeFloat32(TempAllocator& alloc) {
6226 if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
6227 setResultType(MIRType::Float32);
6228 specialization_ = MIRType::Float32;
6229 }
6230 }
6231
6232 MDefinition* MClz::foldsTo(TempAllocator& alloc) {
6233 if (num()->isConstant()) {
6234 MConstant* c = num()->toConstant();
6235 if (type() == MIRType::Int32) {
6236 int32_t n = c->toInt32();
6237 if (n == 0) {
6238 return MConstant::New(alloc, Int32Value(32));
6239 }
6240 return MConstant::New(alloc,
6241 Int32Value(mozilla::CountLeadingZeroes32(n)));
6242 }
6243 int64_t n = c->toInt64();
6244 if (n == 0) {
6245 return MConstant::NewInt64(alloc, int64_t(64));
6246 }
6247 return MConstant::NewInt64(alloc,
6248 int64_t(mozilla::CountLeadingZeroes64(n)));
6249 }
6250
6251 return this;
6252 }
6253
6254 MDefinition* MCtz::foldsTo(TempAllocator& alloc) {
6255 if (num()->isConstant()) {
6256 MConstant* c = num()->toConstant();
6257 if (type() == MIRType::Int32) {
6258 int32_t n = num()->toConstant()->toInt32();
6259 if (n == 0) {
6260 return MConstant::New(alloc, Int32Value(32));
6261 }
6262 return MConstant::New(alloc,
6263 Int32Value(mozilla::CountTrailingZeroes32(n)));
6264 }
6265 int64_t n = c->toInt64();
6266 if (n == 0) {
6267 return MConstant::NewInt64(alloc, int64_t(64));
6268 }
6269 return MConstant::NewInt64(alloc,
6270 int64_t(mozilla::CountTrailingZeroes64(n)));
6271 }
6272
6273 return this;
6274 }
6275
6276 MDefinition* MPopcnt::foldsTo(TempAllocator& alloc) {
6277 if (num()->isConstant()) {
6278 MConstant* c = num()->toConstant();
6279 if (type() == MIRType::Int32) {
6280 int32_t n = num()->toConstant()->toInt32();
6281 return MConstant::New(alloc, Int32Value(mozilla::CountPopulation32(n)));
6282 }
6283 int64_t n = c->toInt64();
6284 return MConstant::NewInt64(alloc, int64_t(mozilla::CountPopulation64(n)));
6285 }
6286
6287 return this;
6288 }
6289
6290 MDefinition* MBoundsCheck::foldsTo(TempAllocator& alloc) {
6291 if (type() == MIRType::Int32 && index()->isConstant() &&
6292 length()->isConstant()) {
6293 uint32_t len = length()->toConstant()->toInt32();
6294 uint32_t idx = index()->toConstant()->toInt32();
6295 if (idx + uint32_t(minimum()) < len && idx + uint32_t(maximum()) < len) {
6296 return index();
6297 }
6298 }
6299
6300 return this;
6301 }
6302
6303 MDefinition* MTableSwitch::foldsTo(TempAllocator& alloc) {
6304 MDefinition* op = getOperand(0);
6305
6306 // If we only have one successor, convert to a plain goto to the only
6307 // successor. TableSwitch indices are numeric; other types will always go to
6308 // the only successor.
6309 if (numSuccessors() == 1 ||
6310 (op->type() != MIRType::Value && !IsNumberType(op->type()))) {
6311 return MGoto::New(alloc, getDefault());
6312 }
6313
6314 if (MConstant* opConst = op->maybeConstantValue()) {
6315 if (op->type() == MIRType::Int32) {
6316 int32_t i = opConst->toInt32() - low_;
6317 MBasicBlock* target;
6318 if (size_t(i) < numCases()) {
6319 target = getCase(size_t(i));
6320 } else {
6321 target = getDefault();
6322 }
6323 MOZ_ASSERT(target);
6324 return MGoto::New(alloc, target);
6325 }
6326 }
6327
6328 return this;
6329 }
6330
6331 MDefinition* MArrayJoin::foldsTo(TempAllocator& alloc) {
6332 MDefinition* arr = array();
6333
6334 if (!arr->isStringSplit()) {
6335 return this;
6336 }
6337
6338 setRecoveredOnBailout();
6339 if (arr->hasLiveDefUses()) {
6340 setNotRecoveredOnBailout();
6341 return this;
6342 }
6343
6344 // The MStringSplit won't generate any code.
6345 arr->setRecoveredOnBailout();
6346
6347 // We're replacing foo.split(bar).join(baz) by
6348 // foo.replace(bar, baz). MStringSplit could be recovered by
6349 // a bailout. As we are removing its last use, and its result
6350 // could be captured by a resume point, this MStringSplit will
6351 // be executed on the bailout path.
6352 MDefinition* string = arr->toStringSplit()->string();
6353 MDefinition* pattern = arr->toStringSplit()->separator();
6354 MDefinition* replacement = separator();
6355
6356 MStringReplace* substr =
6357 MStringReplace::New(alloc, string, pattern, replacement);
6358 substr->setFlatReplacement();
6359 return substr;
6360 }
6361
6362 MDefinition* MGetFirstDollarIndex::foldsTo(TempAllocator& alloc) {
6363 MDefinition* strArg = str();
6364 if (!strArg->isConstant()) {
6365 return this;
6366 }
6367
6368 JSLinearString* str = &strArg->toConstant()->toString()->asLinear();
6369 int32_t index = GetFirstDollarIndexRawFlat(str);
6370 return MConstant::New(alloc, Int32Value(index));
6371 }
6372
6373 AliasSet MThrowRuntimeLexicalError::getAliasSet() const {
6374 return AliasSet::Store(AliasSet::ExceptionState);
6375 }
6376
6377 AliasSet MSlots::getAliasSet() const {
6378 return AliasSet::Load(AliasSet::ObjectFields);
6379 }
6380
6381 MDefinition::AliasType MSlots::mightAlias(const MDefinition* store) const {
6382 // ArrayPush only modifies object elements, but not object slots.
6383 if (store->isArrayPush()) {
6384 return AliasType::NoAlias;
6385 }
6386 return MInstruction::mightAlias(store);
6387 }
6388
6389 AliasSet MElements::getAliasSet() const {
6390 return AliasSet::Load(AliasSet::ObjectFields);
6391 }
6392
6393 AliasSet MInitializedLength::getAliasSet() const {
6394 return AliasSet::Load(AliasSet::ObjectFields);
6395 }
6396
6397 AliasSet MSetInitializedLength::getAliasSet() const {
6398 return AliasSet::Store(AliasSet::ObjectFields);
6399 }
6400
6401 AliasSet MObjectKeysLength::getAliasSet() const {
6402 return AliasSet::Load(AliasSet::ObjectFields);
6403 }
6404
6405 AliasSet MArrayLength::getAliasSet() const {
6406 return AliasSet::Load(AliasSet::ObjectFields);
6407 }
6408
6409 AliasSet MSetArrayLength::getAliasSet() const {
6410 return AliasSet::Store(AliasSet::ObjectFields);
6411 }
6412
6413 AliasSet MFunctionLength::getAliasSet() const {
6414 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6415 AliasSet::DynamicSlot);
6416 }
6417
6418 AliasSet MFunctionName::getAliasSet() const {
6419 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6420 AliasSet::DynamicSlot);
6421 }
6422
6423 AliasSet MArrayBufferByteLength::getAliasSet() const {
6424 return AliasSet::Load(AliasSet::FixedSlot);
6425 }
6426
6427 AliasSet MArrayBufferViewLength::getAliasSet() const {
6428 return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
6429 }
6430
6431 AliasSet MArrayBufferViewByteOffset::getAliasSet() const {
6432 return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
6433 }
6434
6435 AliasSet MArrayBufferViewElements::getAliasSet() const {
6436 return AliasSet::Load(AliasSet::ObjectFields);
6437 }
6438
6439 AliasSet MGuardHasAttachedArrayBuffer::getAliasSet() const {
6440 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot);
6441 }
6442
6443 AliasSet MResizableTypedArrayByteOffsetMaybeOutOfBounds::getAliasSet() const {
6444 // Loads the byteOffset and additionally checks for detached buffers, so the
6445 // alias set also has to include |ObjectFields| and |FixedSlot|.
6446 return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset |
6447 AliasSet::ObjectFields | AliasSet::FixedSlot);
6448 }
6449
6450 AliasSet MResizableTypedArrayLength::getAliasSet() const {
6451 // Loads the length and byteOffset slots, the shared-elements flag, the
6452 // auto-length fixed slot, and the shared raw-buffer length.
6453 auto flags = AliasSet::ArrayBufferViewLengthOrOffset |
6454 AliasSet::ObjectFields | AliasSet::FixedSlot |
6455 AliasSet::SharedArrayRawBufferLength;
6456
6457 // When a barrier is needed make the instruction effectful by giving it a
6458 // "store" effect. Also prevent reordering LoadUnboxedScalar before this
6459 // instruction by including |UnboxedElement| in the alias set.
6460 if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
6461 return AliasSet::Store(flags | AliasSet::UnboxedElement);
6462 }
6463 return AliasSet::Load(flags);
6464 }
6465
6466 bool MResizableTypedArrayLength::congruentTo(const MDefinition* ins) const {
6467 if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
6468 return false;
6469 }
6470 return congruentIfOperandsEqual(ins);
6471 }
6472
6473 AliasSet MResizableDataViewByteLength::getAliasSet() const {
6474 // Loads the length and byteOffset slots, the shared-elements flag, the
6475 // auto-length fixed slot, and the shared raw-buffer length.
6476 auto flags = AliasSet::ArrayBufferViewLengthOrOffset |
6477 AliasSet::ObjectFields | AliasSet::FixedSlot |
6478 AliasSet::SharedArrayRawBufferLength;
6479
6480 // When a barrier is needed make the instruction effectful by giving it a
6481 // "store" effect. Also prevent reordering LoadUnboxedScalar before this
6482 // instruction by including |UnboxedElement| in the alias set.
6483 if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
6484 return AliasSet::Store(flags | AliasSet::UnboxedElement);
6485 }
6486 return AliasSet::Load(flags);
6487 }
6488
6489 bool MResizableDataViewByteLength::congruentTo(const MDefinition* ins) const {
6490 if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
6491 return false;
6492 }
6493 return congruentIfOperandsEqual(ins);
6494 }
6495
6496 AliasSet MGrowableSharedArrayBufferByteLength::getAliasSet() const {
6497 // Requires a barrier, so make the instruction effectful by giving it a
6498 // "store" effect. Also prevent reordering LoadUnboxedScalar before this
6499 // instruction by including |UnboxedElement| in the alias set.
6500 return AliasSet::Store(AliasSet::FixedSlot |
6501 AliasSet::SharedArrayRawBufferLength |
6502 AliasSet::UnboxedElement);
6503 }
6504
6505 AliasSet MGuardResizableArrayBufferViewInBounds::getAliasSet() const {
6506 // Additionally reads the |initialLength| and |initialByteOffset| slots, but
6507 // since these can't change after construction, we don't need to track them.
6508 return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
6509 }
6510
6511 AliasSet MGuardResizableArrayBufferViewInBoundsOrDetached::getAliasSet() const {
6512 // Loads the byteOffset and additionally checks for detached buffers, so the
6513 // alias set also has to include |ObjectFields| and |FixedSlot|.
6514 return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset |
6515 AliasSet::ObjectFields | AliasSet::FixedSlot);
6516 }
6517
6518 AliasSet MArrayPush::getAliasSet() const {
6519 return AliasSet::Store(AliasSet::ObjectFields | AliasSet::Element);
6520 }
6521
6522 MDefinition* MGuardNumberToIntPtrIndex::foldsTo(TempAllocator& alloc) {
6523 MDefinition* input = this->input();
6524
6525 if (input->isToDouble() && input->getOperand(0)->type() == MIRType::Int32) {
6526 return MInt32ToIntPtr::New(alloc, input->getOperand(0));
6527 }
6528
6529 if (!input->isConstant()) {
6530 return this;
6531 }
6532
6533 // Fold constant double representable as intptr to intptr.
6534 int64_t ival;
6535 if (!mozilla::NumberEqualsInt64(input->toConstant()->toDouble(), &ival)) {
6536 // If not representable as an int64, this access is equal to an OOB access.
6537 // So replace it with a known int64/intptr value which also produces an OOB
6538 // access. If we don't support OOB accesses we have to bail out.
6539 if (!supportOOB()) {
6540 return this;
6541 }
6542 ival = -1;
6543 }
6544
6545 if (ival < INTPTR_MIN || ival > INTPTR_MAX) {
6546 return this;
6547 }
6548
6549 return MConstant::NewIntPtr(alloc, intptr_t(ival));
6550 }
6551
6552 AliasSet MLoadScriptedProxyHandler::getAliasSet() const {
6553 return AliasSet::Load(AliasSet::ObjectFields);
6554 }
6555
6556 AliasSet MGuardIsNativeObject::getAliasSet() const {
6557 return AliasSet::Load(AliasSet::ObjectFields);
6558 }
6559
6560 AliasSet MGuardIsProxy::getAliasSet() const {
6561 return AliasSet::Load(AliasSet::ObjectFields);
6562 }
6563
6564 AliasSet MGuardIsNotProxy::getAliasSet() const {
6565 return AliasSet::Load(AliasSet::ObjectFields);
6566 }
6567
6568 AliasSet MGuardIsNotDOMProxy::getAliasSet() const {
6569 return AliasSet::Load(AliasSet::ObjectFields);
6570 }
6571
6572 AliasSet MGuardHasProxyHandler::getAliasSet() const {
6573 return AliasSet::Load(AliasSet::ObjectFields);
6574 }
6575
6576 AliasSet MIsConstructor::getAliasSet() const {
6577 return AliasSet::Load(AliasSet::ObjectFields);
6578 }
6579
6580 MDefinition* MIsObject::foldsTo(TempAllocator& alloc) {
6581 MDefinition* input = object();
6582 if (!input->isBox()) {
6583 return this;
6584 }
6585
6586 MDefinition* unboxed = input->toBox()->input();
6587 return MConstant::New(alloc,
6588 BooleanValue(unboxed->type() == MIRType::Object));
6589 }
6590
6591 MDefinition* MIsNullOrUndefined::foldsTo(TempAllocator& alloc) {
6592 MDefinition* input = value();
6593 if (!input->isBox()) {
6594 return this;
6595 }
6596
6597 MDefinition* unboxed = input->toBox()->input();
6598 return MConstant::New(alloc,
6599 BooleanValue(IsNullOrUndefined(unboxed->type())));
6600 }
6601
6602 AliasSet MHomeObjectSuperBase::getAliasSet() const {
6603 return AliasSet::Load(AliasSet::ObjectFields);
6604 }
6605
6606 MDefinition* MGuardValue::foldsTo(TempAllocator& alloc) {
6607 if (MConstant* cst = value()->maybeConstantValue()) {
6608 if (cst->toJSValue() == expected()) {
6609 return value();
6610 }
6611 }
6612
6613 return this;
6614 }
6615
6616 MDefinition* MGuardNullOrUndefined::foldsTo(TempAllocator& alloc) {
6617 MDefinition* input = value();
6618 if (!input->isBox()) {
6619 return this;
6620 }
6621
6622 MDefinition* unboxed = input->toBox()->input();
6623 if (IsNullOrUndefined(unboxed->type())) {
6624 return input;
6625 }
6626
6627 return this;
6628 }
6629
6630 MDefinition* MGuardIsNotObject::foldsTo(TempAllocator& alloc) {
6631 MDefinition* input = value();
6632 if (!input->isBox()) {
6633 return this;
6634 }
6635
6636 MDefinition* unboxed = input->toBox()->input();
6637 if (unboxed->type() == MIRType::Object) {
6638 return this;
6639 }
6640
6641 return input;
6642 }
6643
6644 MDefinition* MGuardObjectIdentity::foldsTo(TempAllocator& alloc) {
6645 if (object()->isConstant() && expected()->isConstant()) {
6646 JSObject* obj = &object()->toConstant()->toObject();
6647 JSObject* other = &expected()->toConstant()->toObject();
6648 if (!bailOnEquality()) {
6649 if (obj == other) {
6650 return object();
6651 }
6652 } else {
6653 if (obj != other) {
6654 return object();
6655 }
6656 }
6657 }
6658
6659 if (!bailOnEquality() && object()->isNurseryObject() &&
6660 expected()->isNurseryObject()) {
6661 uint32_t objIndex = object()->toNurseryObject()->nurseryIndex();
6662 uint32_t otherIndex = expected()->toNurseryObject()->nurseryIndex();
6663 if (objIndex == otherIndex) {
6664 return object();
6665 }
6666 }
6667
6668 return this;
6669 }
6670
6671 MDefinition* MGuardSpecificFunction::foldsTo(TempAllocator& alloc) {
6672 if (function()->isConstant() && expected()->isConstant()) {
6673 JSObject* fun = &function()->toConstant()->toObject();
6674 JSObject* other = &expected()->toConstant()->toObject();
6675 if (fun == other) {
6676 return function();
6677 }
6678 }
6679
6680 if (function()->isNurseryObject() && expected()->isNurseryObject()) {
6681 uint32_t funIndex = function()->toNurseryObject()->nurseryIndex();
6682 uint32_t otherIndex = expected()->toNurseryObject()->nurseryIndex();
6683 if (funIndex == otherIndex) {
6684 return function();
6685 }
6686 }
6687
6688 return this;
6689 }
6690
6691 MDefinition* MGuardSpecificAtom::foldsTo(TempAllocator& alloc) {
6692 if (str()->isConstant()) {
6693 JSString* s = str()->toConstant()->toString();
6694 if (s->isAtom()) {
6695 JSAtom* cstAtom = &s->asAtom();
6696 if (cstAtom == atom()) {
6697 return str();
6698 }
6699 }
6700 }
6701
6702 return this;
6703 }
6704
6705 MDefinition* MGuardSpecificSymbol::foldsTo(TempAllocator& alloc) {
6706 if (symbol()->isConstant()) {
6707 if (symbol()->toConstant()->toSymbol() == expected()) {
6708 return symbol();
6709 }
6710 }
6711
6712 return this;
6713 }
6714
6715 MDefinition* MGuardSpecificInt32::foldsTo(TempAllocator& alloc) {
6716 if (num()->isConstant() && num()->toConstant()->isInt32(expected())) {
6717 return num();
6718 }
6719 return this;
6720 }
6721
6722 bool MCallBindVar::congruentTo(const MDefinition* ins) const {
6723 if (!ins->isCallBindVar()) {
6724 return false;
6725 }
6726 return congruentIfOperandsEqual(ins);
6727 }
6728
6729 bool MGuardShape::congruentTo(const MDefinition* ins) const {
6730 if (!ins->isGuardShape()) {
6731 return false;
6732 }
6733 if (shape() != ins->toGuardShape()->shape()) {
6734 return false;
6735 }
6736 return congruentIfOperandsEqual(ins);
6737 }
6738
6739 AliasSet MGuardShape::getAliasSet() const {
6740 return AliasSet::Load(AliasSet::ObjectFields);
6741 }
6742
6743 bool MHasShape::congruentTo(const MDefinition* ins) const {
6744 if (!ins->isHasShape()) {
6745 return false;
6746 }
6747 if (shape() != ins->toHasShape()->shape()) {
6748 return false;
6749 }
6750 return congruentIfOperandsEqual(ins);
6751 }
6752
6753 AliasSet MHasShape::getAliasSet() const {
6754 return AliasSet::Load(AliasSet::ObjectFields);
6755 }
6756
6757 MDefinition::AliasType MGuardShape::mightAlias(const MDefinition* store) const {
6758 // These instructions only modify object elements, but not the shape.
6759 if (store->isStoreElementHole() || store->isArrayPush()) {
6760 return AliasType::NoAlias;
6761 }
6762 if (object()->isConstantProto()) {
6763 const MDefinition* receiverObject =
6764 object()->toConstantProto()->getReceiverObject();
6765 switch (store->op()) {
6766 case MDefinition::Opcode::StoreFixedSlot:
6767 if (store->toStoreFixedSlot()->object()->skipObjectGuards() ==
6768 receiverObject) {
6769 return AliasType::NoAlias;
6770 }
6771 break;
6772 case MDefinition::Opcode::StoreDynamicSlot:
6773 if (store->toStoreDynamicSlot()
6774 ->slots()
6775 ->toSlots()
6776 ->object()
6777 ->skipObjectGuards() == receiverObject) {
6778 return AliasType::NoAlias;
6779 }
6780 break;
6781 case MDefinition::Opcode::AddAndStoreSlot:
6782 if (store->toAddAndStoreSlot()->object()->skipObjectGuards() ==
6783 receiverObject) {
6784 return AliasType::NoAlias;
6785 }
6786 break;
6787 case MDefinition::Opcode::AllocateAndStoreSlot:
6788 if (store->toAllocateAndStoreSlot()->object()->skipObjectGuards() ==
6789 receiverObject) {
6790 return AliasType::NoAlias;
6791 }
6792 break;
6793 default:
6794 break;
6795 }
6796 }
6797 return MInstruction::mightAlias(store);
6798 }
6799
6800 bool MGuardFuse::congruentTo(const MDefinition* ins) const {
6801 if (!ins->isGuardFuse()) {
6802 return false;
6803 }
6804 if (fuseIndex() != ins->toGuardFuse()->fuseIndex()) {
6805 return false;
6806 }
6807 return congruentIfOperandsEqual(ins);
6808 }
6809
6810 AliasSet MGuardFuse::getAliasSet() const {
6811 // The alias set below reflects the set of operations which could cause a fuse
6812 // to be popped, and therefore MGuardFuse aliases with.
6813 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::DynamicSlot |
6814 AliasSet::FixedSlot |
6815 AliasSet::GlobalGenerationCounter);
6816 }
6817
6818 AliasSet MGuardMultipleShapes::getAliasSet() const {
6819 // Note: This instruction loads the elements of the ListObject used to
6820 // store the list of shapes, but that object is internal and not exposed
6821 // to script, so it doesn't have to be in the alias set.
6822 return AliasSet::Load(AliasSet::ObjectFields);
6823 }
6824
6825 AliasSet MGuardGlobalGeneration::getAliasSet() const {
6826 return AliasSet::Load(AliasSet::GlobalGenerationCounter);
6827 }
6828
6829 bool MGuardGlobalGeneration::congruentTo(const MDefinition* ins) const {
6830 return ins->isGuardGlobalGeneration() &&
6831 ins->toGuardGlobalGeneration()->expected() == expected() &&
6832 ins->toGuardGlobalGeneration()->generationAddr() == generationAddr();
6833 }
6834
6835 MDefinition* MGuardIsNotProxy::foldsTo(TempAllocator& alloc) {
6836 KnownClass known = GetObjectKnownClass(object());
6837 if (known == KnownClass::None) {
6838 return this;
6839 }
6840
6841 MOZ_ASSERT(!GetObjectKnownJSClass(object())->isProxyObject());
6842 AssertKnownClass(alloc, this, object());
6843 return object();
6844 }
6845
6846 AliasSet MMegamorphicLoadSlotByValue::getAliasSet() const {
6847 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6848 AliasSet::DynamicSlot);
6849 }
6850
6851 static PropertyKey ToNonIntPropertyKey(MDefinition* idval) {
6852 MConstant* constant = idval->maybeConstantValue();
6853 if (!constant) {
6854 return PropertyKey::Void();
6855 }
6856 if (constant->type() == MIRType::String) {
6857 JSString* str = constant->toString();
6858 if (!str->isAtom() || str->asAtom().isIndex()) {
6859 return PropertyKey::Void();
6860 }
6861 return PropertyKey::NonIntAtom(str);
6862 }
6863 if (constant->type() == MIRType::Symbol) {
6864 return PropertyKey::Symbol(constant->toSymbol());
6865 }
6866 return PropertyKey::Void();
6867 }
6868
6869 MDefinition* MMegamorphicLoadSlotByValue::foldsTo(TempAllocator& alloc) {
6870 PropertyKey id = ToNonIntPropertyKey(idVal());
6871 if (id.isVoid()) {
6872 return this;
6873 }
6874
6875 auto* result = MMegamorphicLoadSlot::New(alloc, object(), id);
6876 result->setDependency(dependency());
6877 return result;
6878 }
6879
6880 MDefinition* MMegamorphicLoadSlotByValuePermissive::foldsTo(
6881 TempAllocator& alloc) {
6882 PropertyKey id = ToNonIntPropertyKey(idVal());
6883 if (id.isVoid()) {
6884 return this;
6885 }
6886
6887 auto* result = MMegamorphicLoadSlotPermissive::New(alloc, object(), id);
6888 result->stealResumePoint(this);
6889 return result;
6890 }
6891
6892 bool MMegamorphicLoadSlot::congruentTo(const MDefinition* ins) const {
6893 if (!ins->isMegamorphicLoadSlot()) {
6894 return false;
6895 }
6896 if (ins->toMegamorphicLoadSlot()->name() != name()) {
6897 return false;
6898 }
6899 return congruentIfOperandsEqual(ins);
6900 }
6901
6902 AliasSet MMegamorphicLoadSlot::getAliasSet() const {
6903 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6904 AliasSet::DynamicSlot);
6905 }
6906
6907 bool MSmallObjectVariableKeyHasProp::congruentTo(const MDefinition* ins) const {
6908 if (!ins->isSmallObjectVariableKeyHasProp()) {
6909 return false;
6910 }
6911 if (ins->toSmallObjectVariableKeyHasProp()->shape() != shape()) {
6912 return false;
6913 }
6914 return congruentIfOperandsEqual(ins);
6915 }
6916
6917 AliasSet MSmallObjectVariableKeyHasProp::getAliasSet() const {
6918 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6919 AliasSet::DynamicSlot);
6920 }
6921
6922 bool MMegamorphicHasProp::congruentTo(const MDefinition* ins) const {
6923 if (!ins->isMegamorphicHasProp()) {
6924 return false;
6925 }
6926 if (ins->toMegamorphicHasProp()->hasOwn() != hasOwn()) {
6927 return false;
6928 }
6929 return congruentIfOperandsEqual(ins);
6930 }
6931
6932 AliasSet MMegamorphicHasProp::getAliasSet() const {
6933 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
6934 AliasSet::DynamicSlot);
6935 }
6936
6937 bool MNurseryObject::congruentTo(const MDefinition* ins) const {
6938 if (!ins->isNurseryObject()) {
6939 return false;
6940 }
6941 return nurseryIndex() == ins->toNurseryObject()->nurseryIndex();
6942 }
6943
6944 AliasSet MGuardFunctionIsNonBuiltinCtor::getAliasSet() const {
6945 return AliasSet::Load(AliasSet::ObjectFields);
6946 }
6947
6948 bool MGuardFunctionKind::congruentTo(const MDefinition* ins) const {
6949 if (!ins->isGuardFunctionKind()) {
6950 return false;
6951 }
6952 if (expected() != ins->toGuardFunctionKind()->expected()) {
6953 return false;
6954 }
6955 if (bailOnEquality() != ins->toGuardFunctionKind()->bailOnEquality()) {
6956 return false;
6957 }
6958 return congruentIfOperandsEqual(ins);
6959 }
6960
6961 AliasSet MGuardFunctionKind::getAliasSet() const {
6962 return AliasSet::Load(AliasSet::ObjectFields);
6963 }
6964
6965 bool MGuardFunctionScript::congruentTo(const MDefinition* ins) const {
6966 if (!ins->isGuardFunctionScript()) {
6967 return false;
6968 }
6969 if (expected() != ins->toGuardFunctionScript()->expected()) {
6970 return false;
6971 }
6972 return congruentIfOperandsEqual(ins);
6973 }
6974
6975 AliasSet MGuardFunctionScript::getAliasSet() const {
6976 // A JSFunction's BaseScript pointer is immutable. Relazification of
6977 // top-level/named self-hosted functions is an exception to this, but we don't
6978 // use this guard for those self-hosted functions.
6979 // See IRGenerator::emitCalleeGuard.
6980 MOZ_ASSERT_IF(flags_.isSelfHostedOrIntrinsic(), flags_.isLambda());
6981 return AliasSet::None();
6982 }
6983
6984 bool MGuardSpecificAtom::congruentTo(const MDefinition* ins) const {
6985 if (!ins->isGuardSpecificAtom()) {
6986 return false;
6987 }
6988 if (atom() != ins->toGuardSpecificAtom()->atom()) {
6989 return false;
6990 }
6991 return congruentIfOperandsEqual(ins);
6992 }
6993
6994 MDefinition* MGuardStringToIndex::foldsTo(TempAllocator& alloc) {
6995 if (!string()->isConstant()) {
6996 return this;
6997 }
6998
6999 JSString* str = string()->toConstant()->toString();
7000
7001 int32_t index = GetIndexFromString(str);
7002 if (index < 0) {
7003 return this;
7004 }
7005
7006 return MConstant::New(alloc, Int32Value(index));
7007 }
7008
7009 MDefinition* MGuardStringToInt32::foldsTo(TempAllocator& alloc) {
7010 if (!string()->isConstant()) {
7011 return this;
7012 }
7013
7014 JSLinearString* str = &string()->toConstant()->toString()->asLinear();
7015 double number = LinearStringToNumber(str);
7016
7017 int32_t n;
7018 if (!mozilla::NumberIsInt32(number, &n)) {
7019 return this;
7020 }
7021
7022 return MConstant::New(alloc, Int32Value(n));
7023 }
7024
7025 MDefinition* MGuardStringToDouble::foldsTo(TempAllocator& alloc) {
7026 if (!string()->isConstant()) {
7027 return this;
7028 }
7029
7030 JSLinearString* str = &string()->toConstant()->toString()->asLinear();
7031 double number = LinearStringToNumber(str);
7032 return MConstant::New(alloc, DoubleValue(number));
7033 }
7034
7035 AliasSet MGuardNoDenseElements::getAliasSet() const {
7036 return AliasSet::Load(AliasSet::ObjectFields);
7037 }
7038
7039 AliasSet MIteratorHasIndices::getAliasSet() const {
7040 return AliasSet::Load(AliasSet::ObjectFields);
7041 }
7042
7043 AliasSet MAllocateAndStoreSlot::getAliasSet() const {
7044 return AliasSet::Store(AliasSet::ObjectFields | AliasSet::DynamicSlot);
7045 }
7046
7047 AliasSet MLoadDOMExpandoValue::getAliasSet() const {
7048 return AliasSet::Load(AliasSet::DOMProxyExpando);
7049 }
7050
7051 AliasSet MLoadDOMExpandoValueIgnoreGeneration::getAliasSet() const {
7052 return AliasSet::Load(AliasSet::DOMProxyExpando);
7053 }
7054
7055 bool MGuardDOMExpandoMissingOrGuardShape::congruentTo(
7056 const MDefinition* ins) const {
7057 if (!ins->isGuardDOMExpandoMissingOrGuardShape()) {
7058 return false;
7059 }
7060 if (shape() != ins->toGuardDOMExpandoMissingOrGuardShape()->shape()) {
7061 return false;
7062 }
7063 return congruentIfOperandsEqual(ins);
7064 }
7065
7066 AliasSet MGuardDOMExpandoMissingOrGuardShape::getAliasSet() const {
7067 return AliasSet::Load(AliasSet::ObjectFields);
7068 }
7069
7070 MDefinition* MGuardToClass::foldsTo(TempAllocator& alloc) {
7071 const JSClass* clasp = GetObjectKnownJSClass(object());
7072 if (!clasp || getClass() != clasp) {
7073 return this;
7074 }
7075
7076 AssertKnownClass(alloc, this, object());
7077 return object();
7078 }
7079
7080 MDefinition* MGuardToEitherClass::foldsTo(TempAllocator& alloc) {
7081 const JSClass* clasp = GetObjectKnownJSClass(object());
7082 if (!clasp || (getClass1() != clasp && getClass2() != clasp)) {
7083 return this;
7084 }
7085
7086 AssertKnownClass(alloc, this, object());
7087 return object();
7088 }
7089
7090 MDefinition* MGuardToFunction::foldsTo(TempAllocator& alloc) {
7091 if (GetObjectKnownClass(object()) != KnownClass::Function) {
7092 return this;
7093 }
7094
7095 AssertKnownClass(alloc, this, object());
7096 return object();
7097 }
7098
7099 MDefinition* MHasClass::foldsTo(TempAllocator& alloc) {
7100 const JSClass* clasp = GetObjectKnownJSClass(object());
7101 if (!clasp) {
7102 return this;
7103 }
7104
7105 AssertKnownClass(alloc, this, object());
7106 return MConstant::New(alloc, BooleanValue(getClass() == clasp));
7107 }
7108
7109 MDefinition* MIsCallable::foldsTo(TempAllocator& alloc) {
7110 if (input()->type() != MIRType::Object) {
7111 return this;
7112 }
7113
7114 KnownClass known = GetObjectKnownClass(input());
7115 if (known == KnownClass::None) {
7116 return this;
7117 }
7118
7119 AssertKnownClass(alloc, this, input());
7120 return MConstant::New(alloc, BooleanValue(known == KnownClass::Function));
7121 }
7122
7123 MDefinition* MIsArray::foldsTo(TempAllocator& alloc) {
7124 if (input()->type() != MIRType::Object) {
7125 return this;
7126 }
7127
7128 KnownClass known = GetObjectKnownClass(input());
7129 if (known == KnownClass::None) {
7130 return this;
7131 }
7132
7133 AssertKnownClass(alloc, this, input());
7134 return MConstant::New(alloc, BooleanValue(known == KnownClass::Array));
7135 }
7136
7137 AliasSet MObjectClassToString::getAliasSet() const {
7138 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
7139 AliasSet::DynamicSlot);
7140 }
7141
7142 MDefinition* MGuardIsNotArrayBufferMaybeShared::foldsTo(TempAllocator& alloc) {
7143 switch (GetObjectKnownClass(object())) {
7144 case KnownClass::PlainObject:
7145 case KnownClass::Array:
7146 case KnownClass::Function:
7147 case KnownClass::RegExp:
7148 case KnownClass::ArrayIterator:
7149 case KnownClass::StringIterator:
7150 case KnownClass::RegExpStringIterator: {
7151 AssertKnownClass(alloc, this, object());
7152 return object();
7153 }
7154 case KnownClass::None:
7155 break;
7156 }
7157
7158 return this;
7159 }
7160
7161 MDefinition* MCheckIsObj::foldsTo(TempAllocator& alloc) {
7162 if (!input()->isBox()) {
7163 return this;
7164 }
7165
7166 MDefinition* unboxed = input()->toBox()->input();
7167 if (unboxed->type() == MIRType::Object) {
7168 return unboxed;
7169 }
7170
7171 return this;
7172 }
7173
7174 AliasSet MCheckIsObj::getAliasSet() const {
7175 return AliasSet::Store(AliasSet::ExceptionState);
7176 }
7177
7178 #ifdef JS_PUNBOX64
7179 AliasSet MCheckScriptedProxyGetResult::getAliasSet() const {
7180 return AliasSet::Store(AliasSet::ExceptionState);
7181 }
7182 #endif
7183
7184 static bool IsBoxedObject(MDefinition* def) {
7185 MOZ_ASSERT(def->type() == MIRType::Value);
7186
7187 if (def->isBox()) {
7188 return def->toBox()->input()->type() == MIRType::Object;
7189 }
7190
7191 // Construct calls are always returning a boxed object.
7192 //
7193 // TODO: We should consider encoding this directly in the graph instead of
7194 // having to special case it here.
7195 if (def->isCall()) {
7196 return def->toCall()->isConstructing();
7197 }
7198 if (def->isConstructArray()) {
7199 return true;
7200 }
7201 if (def->isConstructArgs()) {
7202 return true;
7203 }
7204
7205 return false;
7206 }
7207
7208 MDefinition* MCheckReturn::foldsTo(TempAllocator& alloc) {
7209 auto* returnVal = returnValue();
7210 if (!returnVal->isBox()) {
7211 return this;
7212 }
7213
7214 auto* unboxedReturnVal = returnVal->toBox()->input();
7215 if (unboxedReturnVal->type() == MIRType::Object) {
7216 return returnVal;
7217 }
7218
7219 if (unboxedReturnVal->type() != MIRType::Undefined) {
7220 return this;
7221 }
7222
7223 auto* thisVal = thisValue();
7224 if (IsBoxedObject(thisVal)) {
7225 return thisVal;
7226 }
7227
7228 return this;
7229 }
7230
7231 MDefinition* MCheckThis::foldsTo(TempAllocator& alloc) {
7232 MDefinition* input = thisValue();
7233 if (!input->isBox()) {
7234 return this;
7235 }
7236
7237 MDefinition* unboxed = input->toBox()->input();
7238 if (IsMagicType(unboxed->type())) {
7239 return this;
7240 }
7241
7242 return input;
7243 }
7244
7245 MDefinition* MCheckThisReinit::foldsTo(TempAllocator& alloc) {
7246 MDefinition* input = thisValue();
7247 if (!input->isBox()) {
7248 return this;
7249 }
7250
7251 MDefinition* unboxed = input->toBox()->input();
7252 if (unboxed->type() != MIRType::MagicUninitializedLexical) {
7253 return this;
7254 }
7255
7256 return input;
7257 }
7258
7259 MDefinition* MCheckObjCoercible::foldsTo(TempAllocator& alloc) {
7260 MDefinition* input = checkValue();
7261 if (!input->isBox()) {
7262 return this;
7263 }
7264
7265 MDefinition* unboxed = input->toBox()->input();
7266 if (IsNullOrUndefined(unboxed->type())) {
7267 return this;
7268 }
7269
7270 return input;
7271 }
7272
7273 AliasSet MCheckObjCoercible::getAliasSet() const {
7274 return AliasSet::Store(AliasSet::ExceptionState);
7275 }
7276
7277 AliasSet MCheckReturn::getAliasSet() const {
7278 return AliasSet::Store(AliasSet::ExceptionState);
7279 }
7280
7281 AliasSet MCheckThis::getAliasSet() const {
7282 return AliasSet::Store(AliasSet::ExceptionState);
7283 }
7284
7285 AliasSet MCheckThisReinit::getAliasSet() const {
7286 return AliasSet::Store(AliasSet::ExceptionState);
7287 }
7288
7289 AliasSet MIsPackedArray::getAliasSet() const {
7290 return AliasSet::Load(AliasSet::ObjectFields);
7291 }
7292
7293 AliasSet MGuardArrayIsPacked::getAliasSet() const {
7294 return AliasSet::Load(AliasSet::ObjectFields);
7295 }
7296
7297 AliasSet MSuperFunction::getAliasSet() const {
7298 return AliasSet::Load(AliasSet::ObjectFields);
7299 }
7300
7301 AliasSet MInitHomeObject::getAliasSet() const {
7302 return AliasSet::Store(AliasSet::ObjectFields);
7303 }
7304
7305 AliasSet MLoadWrapperTarget::getAliasSet() const {
7306 return AliasSet::Load(AliasSet::Any);
7307 }
7308
7309 bool MLoadWrapperTarget::congruentTo(const MDefinition* ins) const {
7310 if (!ins->isLoadWrapperTarget()) {
7311 return false;
7312 }
7313 if (ins->toLoadWrapperTarget()->fallible() != fallible()) {
7314 return false;
7315 }
7316 return congruentIfOperandsEqual(ins);
7317 }
7318
7319 AliasSet MGuardHasGetterSetter::getAliasSet() const {
7320 return AliasSet::Load(AliasSet::ObjectFields);
7321 }
7322
7323 bool MGuardHasGetterSetter::congruentTo(const MDefinition* ins) const {
7324 if (!ins->isGuardHasGetterSetter()) {
7325 return false;
7326 }
7327 if (ins->toGuardHasGetterSetter()->propId() != propId()) {
7328 return false;
7329 }
7330 if (ins->toGuardHasGetterSetter()->getterSetter() != getterSetter()) {
7331 return false;
7332 }
7333 return congruentIfOperandsEqual(ins);
7334 }
7335
7336 AliasSet MGuardIsExtensible::getAliasSet() const {
7337 return AliasSet::Load(AliasSet::ObjectFields);
7338 }
7339
7340 AliasSet MGuardIndexIsNotDenseElement::getAliasSet() const {
7341 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::Element);
7342 }
7343
7344 AliasSet MGuardIndexIsValidUpdateOrAdd::getAliasSet() const {
7345 return AliasSet::Load(AliasSet::ObjectFields);
7346 }
7347
7348 AliasSet MCallObjectHasSparseElement::getAliasSet() const {
7349 return AliasSet::Load(AliasSet::Element | AliasSet::ObjectFields |
7350 AliasSet::FixedSlot | AliasSet::DynamicSlot);
7351 }
7352
7353 AliasSet MLoadSlotByIteratorIndex::getAliasSet() const {
7354 return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
7355 AliasSet::DynamicSlot | AliasSet::Element);
7356 }
7357
7358 AliasSet MStoreSlotByIteratorIndex::getAliasSet() const {
7359 return AliasSet::Store(AliasSet::ObjectFields | AliasSet::FixedSlot |
7360 AliasSet::DynamicSlot | AliasSet::Element);
7361 }
7362
7363 MDefinition* MGuardInt32IsNonNegative::foldsTo(TempAllocator& alloc) {
7364 MOZ_ASSERT(index()->type() == MIRType::Int32);
7365
7366 MDefinition* input = index();
7367 if (!input->isConstant() || input->toConstant()->toInt32() < 0) {
7368 return this;
7369 }
7370 return input;
7371 }
7372
7373 MDefinition* MGuardInt32Range::foldsTo(TempAllocator& alloc) {
7374 MOZ_ASSERT(input()->type() == MIRType::Int32);
7375 MOZ_ASSERT(minimum() <= maximum());
7376
7377 MDefinition* in = input();
7378 if (!in->isConstant()) {
7379 return this;
7380 }
7381 int32_t cst = in->toConstant()->toInt32();
7382 if (cst < minimum() || cst > maximum()) {
7383 return this;
7384 }
7385 return in;
7386 }
7387
7388 MDefinition* MGuardNonGCThing::foldsTo(TempAllocator& alloc) {
7389 if (!input()->isBox()) {
7390 return this;
7391 }
7392
7393 MDefinition* unboxed = input()->toBox()->input();
7394 if (!IsNonGCThing(unboxed->type())) {
7395 return this;
7396 }
7397 return input();
7398 }
7399
7400 AliasSet MSetObjectHasNonBigInt::getAliasSet() const {
7401 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7402 }
7403
7404 AliasSet MSetObjectHasBigInt::getAliasSet() const {
7405 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7406 }
7407
7408 AliasSet MSetObjectHasValue::getAliasSet() const {
7409 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7410 }
7411
7412 AliasSet MSetObjectHasValueVMCall::getAliasSet() const {
7413 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7414 }
7415
7416 AliasSet MSetObjectSize::getAliasSet() const {
7417 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7418 }
7419
7420 AliasSet MMapObjectHasNonBigInt::getAliasSet() const {
7421 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7422 }
7423
7424 AliasSet MMapObjectHasBigInt::getAliasSet() const {
7425 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7426 }
7427
7428 AliasSet MMapObjectHasValue::getAliasSet() const {
7429 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7430 }
7431
7432 AliasSet MMapObjectHasValueVMCall::getAliasSet() const {
7433 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7434 }
7435
7436 AliasSet MMapObjectGetNonBigInt::getAliasSet() const {
7437 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7438 }
7439
7440 AliasSet MMapObjectGetBigInt::getAliasSet() const {
7441 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7442 }
7443
7444 AliasSet MMapObjectGetValue::getAliasSet() const {
7445 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7446 }
7447
7448 AliasSet MMapObjectGetValueVMCall::getAliasSet() const {
7449 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7450 }
7451
7452 AliasSet MMapObjectSize::getAliasSet() const {
7453 return AliasSet::Load(AliasSet::MapOrSetHashTable);
7454 }
7455
7456 AliasSet MDateFillLocalTimeSlots::getAliasSet() const {
7457 // Reads and stores fixed slots. Additional reads from DateTimeInfo don't need
7458 // to be tracked, because they don't interact with other alias set states.
7459 return AliasSet::Store(AliasSet::FixedSlot);
7460 }
7461
7462 MBindFunction* MBindFunction::New(TempAllocator& alloc, MDefinition* target,
7463 uint32_t argc, JSObject* templateObj) {
7464 auto* ins = new (alloc) MBindFunction(templateObj);
7465 if (!ins->init(alloc, NumNonArgumentOperands + argc)) {
7466 return nullptr;
7467 }
7468 ins->initOperand(0, target);
7469 return ins;
7470 }
7471
7472 MCreateInlinedArgumentsObject* MCreateInlinedArgumentsObject::New(
7473 TempAllocator& alloc, MDefinition* callObj, MDefinition* callee,
7474 MDefinitionVector& args, ArgumentsObject* templateObj) {
7475 MCreateInlinedArgumentsObject* ins =
7476 new (alloc) MCreateInlinedArgumentsObject(templateObj);
7477
7478 uint32_t argc = args.length();
7479 MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
7480
7481 if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
7482 return nullptr;
7483 }
7484
7485 ins->initOperand(0, callObj);
7486 ins->initOperand(1, callee);
7487 for (uint32_t i = 0; i < argc; i++) {
7488 ins->initOperand(i + NumNonArgumentOperands, args[i]);
7489 }
7490
7491 return ins;
7492 }
7493
7494 MGetInlinedArgument* MGetInlinedArgument::New(
7495 TempAllocator& alloc, MDefinition* index,
7496 MCreateInlinedArgumentsObject* args) {
7497 MGetInlinedArgument* ins = new (alloc) MGetInlinedArgument();
7498
7499 uint32_t argc = args->numActuals();
7500 MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
7501
7502 if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
7503 return nullptr;
7504 }
7505
7506 ins->initOperand(0, index);
7507 for (uint32_t i = 0; i < argc; i++) {
7508 ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
7509 }
7510
7511 return ins;
7512 }
7513
7514 MGetInlinedArgument* MGetInlinedArgument::New(TempAllocator& alloc,
7515 MDefinition* index,
7516 const CallInfo& callInfo) {
7517 MGetInlinedArgument* ins = new (alloc) MGetInlinedArgument();
7518
7519 uint32_t argc = callInfo.argc();
7520 MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
7521
7522 if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
7523 return nullptr;
7524 }
7525
7526 ins->initOperand(0, index);
7527 for (uint32_t i = 0; i < argc; i++) {
7528 ins->initOperand(i + NumNonArgumentOperands, callInfo.getArg(i));
7529 }
7530
7531 return ins;
7532 }
7533
7534 MDefinition* MGetInlinedArgument::foldsTo(TempAllocator& alloc) {
7535 MDefinition* indexDef = SkipUninterestingInstructions(index());
7536 if (!indexDef->isConstant() || indexDef->type() != MIRType::Int32) {
7537 return this;
7538 }
7539
7540 int32_t indexConst = indexDef->toConstant()->toInt32();
7541 if (indexConst < 0 || uint32_t(indexConst) >= numActuals()) {
7542 return this;
7543 }
7544
7545 MDefinition* arg = getArg(indexConst);
7546 if (arg->type() != MIRType::Value) {
7547 arg = MBox::New(alloc, arg);
7548 }
7549
7550 return arg;
7551 }
7552
7553 MGetInlinedArgumentHole* MGetInlinedArgumentHole::New(
7554 TempAllocator& alloc, MDefinition* index,
7555 MCreateInlinedArgumentsObject* args) {
7556 auto* ins = new (alloc) MGetInlinedArgumentHole();
7557
7558 uint32_t argc = args->numActuals();
7559 MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
7560
7561 if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
7562 return nullptr;
7563 }
7564
7565 ins->initOperand(0, index);
7566 for (uint32_t i = 0; i < argc; i++) {
7567 ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
7568 }
7569
7570 return ins;
7571 }
7572
7573 MDefinition* MGetInlinedArgumentHole::foldsTo(TempAllocator& alloc) {
7574 MDefinition* indexDef = SkipUninterestingInstructions(index());
7575 if (!indexDef->isConstant() || indexDef->type() != MIRType::Int32) {
7576 return this;
7577 }
7578
7579 int32_t indexConst = indexDef->toConstant()->toInt32();
7580 if (indexConst < 0) {
7581 return this;
7582 }
7583
7584 MDefinition* arg;
7585 if (uint32_t(indexConst) < numActuals()) {
7586 arg = getArg(indexConst);
7587
7588 if (arg->type() != MIRType::Value) {
7589 arg = MBox::New(alloc, arg);
7590 }
7591 } else {
7592 auto* undefined = MConstant::New(alloc, UndefinedValue());
7593 block()->insertBefore(this, undefined);
7594
7595 arg = MBox::New(alloc, undefined);
7596 }
7597
7598 return arg;
7599 }
7600
7601 MInlineArgumentsSlice* MInlineArgumentsSlice::New(
7602 TempAllocator& alloc, MDefinition* begin, MDefinition* count,
7603 MCreateInlinedArgumentsObject* args, JSObject* templateObj,
7604 gc::Heap initialHeap) {
7605 auto* ins = new (alloc) MInlineArgumentsSlice(templateObj, initialHeap);
7606
7607 uint32_t argc = args->numActuals();
7608 MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
7609
7610 if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
7611 return nullptr;
7612 }
7613
7614 ins->initOperand(0, begin);
7615 ins->initOperand(1, count);
7616 for (uint32_t i = 0; i < argc; i++) {
7617 ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
7618 }
7619
7620 return ins;
7621 }
7622
7623 MDefinition* MArrayLength::foldsTo(TempAllocator& alloc) {
7624 return this;
7625 }
7626
7627 MDefinition* MNormalizeSliceTerm::foldsTo(TempAllocator& alloc) {
7628 auto* length = this->length();
7629 if (!length->isConstant() && !length->isArgumentsLength()) {
7630 return this;
7631 }
7632
7633 if (length->isConstant()) {
7634 int32_t lengthConst = length->toConstant()->toInt32();
7635 MOZ_ASSERT(lengthConst >= 0);
7636
7637 // Result is always zero when |length| is zero.
7638 if (lengthConst == 0) {
7639 return length;
7640 }
7641
7642 auto* value = this->value();
7643 if (value->isConstant()) {
7644 int32_t valueConst = value->toConstant()->toInt32();
7645
7646 int32_t normalized;
7647 if (valueConst < 0) {
7648 normalized = std::max(valueConst + lengthConst, 0);
7649 } else {
7650 normalized = std::min(valueConst, lengthConst);
7651 }
7652
7653 if (normalized == valueConst) {
7654 return value;
7655 }
7656 if (normalized == lengthConst) {
7657 return length;
7658 }
7659 return MConstant::New(alloc, Int32Value(normalized));
7660 }
7661
7662 return this;
7663 }
7664
7665 auto* value = this->value();
7666 if (value->isConstant()) {
7667 int32_t valueConst = value->toConstant()->toInt32();
7668
7669 // Minimum of |value| and |length|.
7670 if (valueConst > 0) {
7671 bool isMax = false;
7672 return MMinMax::New(alloc, value, length, MIRType::Int32, isMax);
7673 }
7674
7675 // Maximum of |value + length| and zero.
7676 if (valueConst < 0) {
7677 // Safe to truncate because |length| is never negative.
7678 auto* add = MAdd::New(alloc, value, length, TruncateKind::Truncate);
7679 block()->insertBefore(this, add);
7680
7681 auto* zero = MConstant::New(alloc, Int32Value(0));
7682 block()->insertBefore(this, zero);
7683
7684 bool isMax = true;
7685 return MMinMax::New(alloc, add, zero, MIRType::Int32, isMax);
7686 }
7687
7688 // Directly return the value when it's zero.
7689 return value;
7690 }
7691
7692 // Normalizing MArgumentsLength is a no-op.
7693 if (value->isArgumentsLength()) {
7694 return value;
7695 }
7696
7697 return this;
7698 }
7699
7700 bool MInt32ToStringWithBase::congruentTo(const MDefinition* ins) const {
7701 if (!ins->isInt32ToStringWithBase()) {
7702 return false;
7703 }
7704 if (ins->toInt32ToStringWithBase()->lowerCase() != lowerCase()) {
7705 return false;
7706 }
7707 return congruentIfOperandsEqual(ins);
7708 }