Debian Codegraph @

js/src/jit/CacheIR.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/CacheIR.h"
8
9 #include "mozilla/CheckedInt.h"
10 #include "mozilla/DebugOnly.h"
11 #include "mozilla/FloatingPoint.h"
12
13 #include "jsapi.h"
14 #include "jsdate.h"
15 #include "jsmath.h"
16 #include "jsnum.h"
17
18 #include "builtin/DataViewObject.h"
19 #include "builtin/MapObject.h"
20 #include "builtin/ModuleObject.h"
21 #include "builtin/Object.h"
22 #include "jit/BaselineIC.h"
23 #include "jit/CacheIRCloner.h"
24 #include "jit/CacheIRCompiler.h"
25 #include "jit/CacheIRGenerator.h"
26 #include "jit/CacheIRSpewer.h"
27 #include "jit/CacheIRWriter.h"
28 #include "jit/InlinableNatives.h"
29 #include "jit/JitContext.h"
30 #include "jit/JitZone.h"
31 #include "js/experimental/JitInfo.h" // JSJitInfo
32 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
33 #include "js/friend/WindowProxy.h" // js::IsWindow, js::IsWindowProxy, js::ToWindowIfWindowProxy
34 #include "js/friend/XrayJitInfo.h" // js::jit::GetXrayJitInfo, JS::XrayJitInfo
35 #include "js/GCAPI.h" // JS::AutoSuppressGCAnalysis
36 #include "js/Prefs.h" // JS::Prefs
37 #include "js/RegExpFlags.h" // JS::RegExpFlags
38 #include "js/ScalarType.h" // js::Scalar::Type
39 #include "js/Utility.h" // JS::AutoEnterOOMUnsafeRegion
40 #include "js/Wrapper.h"
41 #include "proxy/DOMProxy.h" // js::GetDOMProxyHandlerFamily
42 #include "proxy/ScriptedProxyHandler.h"
43 #include "util/DifferentialTesting.h"
44 #include "util/Unicode.h"
45 #include "vm/ArrayBufferObject.h"
46 #include "vm/BoundFunctionObject.h"
47 #include "vm/BytecodeUtil.h"
48 #include "vm/Compartment.h"
49 #include "vm/DateObject.h"
50 #include "vm/Iteration.h"
51 #include "vm/PlainObject.h" // js::PlainObject
52 #include "vm/ProxyObject.h"
53 #include "vm/RegExpObject.h"
54 #include "vm/SelfHosting.h"
55 #include "vm/ThrowMsgKind.h" // ThrowCondition
56 #include "vm/TypeofEqOperand.h" // TypeofEqOperand
57 #include "vm/Watchtower.h"
58 #include "wasm/WasmInstance.h"
59
60 #include "jit/BaselineFrame-inl.h"
61 #include "jit/MacroAssembler-inl.h"
62 #include "vm/ArrayBufferObject-inl.h"
63 #include "vm/BytecodeUtil-inl.h"
64 #include "vm/EnvironmentObject-inl.h"
65 #include "vm/JSContext-inl.h"
66 #include "vm/JSFunction-inl.h"
67 #include "vm/JSObject-inl.h"
68 #include "vm/JSScript-inl.h"
69 #include "vm/List-inl.h"
70 #include "vm/NativeObject-inl.h"
71 #include "vm/PlainObject-inl.h"
72 #include "vm/StringObject-inl.h"
73 #include "wasm/WasmInstance-inl.h"
74
75 using namespace js;
76 using namespace js::jit;
77
78 using mozilla::DebugOnly;
79 using mozilla::Maybe;
80
81 using JS::DOMProxyShadowsResult;
82 using JS::ExpandoAndGeneration;
83
84 const char* const js::jit::CacheKindNames[] = {
85 #define DEFINE_KIND(kind) #kind,
86 CACHE_IR_KINDS(DEFINE_KIND)
87 #undef DEFINE_KIND
88 };
89
90 const char* const js::jit::CacheIROpNames[] = {
91 #define OPNAME(op, ...) #op,
92 CACHE_IR_OPS(OPNAME)
93 #undef OPNAME
94 };
95
96 const CacheIROpInfo js::jit::CacheIROpInfos[] = {
97 #define OPINFO(op, len, transpile, ...) {len, transpile},
98 CACHE_IR_OPS(OPINFO)
99 #undef OPINFO
100 };
101
102 const uint32_t js::jit::CacheIROpHealth[] = {
103 #define OPHEALTH(op, len, transpile, health) health,
104 CACHE_IR_OPS(OPHEALTH)
105 #undef OPHEALTH
106 };
107
108 size_t js::jit::NumInputsForCacheKind(CacheKind kind) {
109 switch (kind) {
110 case CacheKind::NewArray:
111 case CacheKind::NewObject:
112 case CacheKind::Lambda:
113 case CacheKind::LazyConstant:
114 case CacheKind::GetImport:
115 return 0;
116 case CacheKind::GetProp:
117 case CacheKind::TypeOf:
118 case CacheKind::TypeOfEq:
119 case CacheKind::ToPropertyKey:
120 case CacheKind::GetIterator:
121 case CacheKind::ToBool:
122 case CacheKind::UnaryArith:
123 case CacheKind::GetName:
124 case CacheKind::BindName:
125 case CacheKind::Call:
126 case CacheKind::OptimizeSpreadCall:
127 case CacheKind::CloseIter:
128 case CacheKind::OptimizeGetIterator:
129 return 1;
130 case CacheKind::Compare:
131 case CacheKind::GetElem:
132 case CacheKind::GetPropSuper:
133 case CacheKind::SetProp:
134 case CacheKind::In:
135 case CacheKind::HasOwn:
136 case CacheKind::CheckPrivateField:
137 case CacheKind::InstanceOf:
138 case CacheKind::BinaryArith:
139 return 2;
140 case CacheKind::GetElemSuper:
141 case CacheKind::SetElem:
142 return 3;
143 }
144 MOZ_CRASH("Invalid kind");
145 }
146
147 #ifdef DEBUG
148 void CacheIRWriter::assertSameCompartment(JSObject* obj) {
149 MOZ_ASSERT(cx_->compartment() == obj->compartment());
150 }
151 void CacheIRWriter::assertSameZone(Shape* shape) {
152 MOZ_ASSERT(cx_->zone() == shape->zone());
153 }
154 #endif
155
156 StubField CacheIRWriter::readStubField(uint32_t offset,
157 StubField::Type type) const {
158 size_t index = 0;
159 size_t currentOffset = 0;
160
161 // If we've seen an offset earlier than this before, we know we can start the
162 // search there at least, otherwise, we start the search from the beginning.
163 if (lastOffset_ < offset) {
164 currentOffset = lastOffset_;
165 index = lastIndex_;
166 }
167
168 while (currentOffset != offset) {
169 currentOffset += StubField::sizeInBytes(stubFields_[index].type());
170 index++;
171 MOZ_ASSERT(index < stubFields_.length());
172 }
173
174 MOZ_ASSERT(stubFields_[index].type() == type);
175
176 lastOffset_ = currentOffset;
177 lastIndex_ = index;
178
179 return stubFields_[index];
180 }
181
182 CacheIRCloner::CacheIRCloner(ICCacheIRStub* stub)
183 : stubInfo_(stub->stubInfo()), stubData_(stub->stubDataStart()) {}
184
185 void CacheIRCloner::cloneOp(CacheOp op, CacheIRReader& reader,
186 CacheIRWriter& writer) {
187 switch (op) {
188 #define DEFINE_OP(op, ...) \
189 case CacheOp::op: \
190 clone##op(reader, writer); \
191 break;
192 CACHE_IR_OPS(DEFINE_OP)
193 #undef DEFINE_OP
194 default:
195 MOZ_CRASH("Invalid op");
196 }
197 }
198
199 uintptr_t CacheIRCloner::readStubWord(uint32_t offset) {
200 return stubInfo_->getStubRawWord(stubData_, offset);
201 }
202 int64_t CacheIRCloner::readStubInt64(uint32_t offset) {
203 return stubInfo_->getStubRawInt64(stubData_, offset);
204 }
205
206 Shape* CacheIRCloner::getShapeField(uint32_t stubOffset) {
207 return reinterpret_cast<Shape*>(readStubWord(stubOffset));
208 }
209 Shape* CacheIRCloner::getWeakShapeField(uint32_t stubOffset) {
210 // No barrier is required to clone a weak pointer.
211 return reinterpret_cast<Shape*>(readStubWord(stubOffset));
212 }
213 GetterSetter* CacheIRCloner::getWeakGetterSetterField(uint32_t stubOffset) {
214 // No barrier is required to clone a weak pointer.
215 return reinterpret_cast<GetterSetter*>(readStubWord(stubOffset));
216 }
217 JSObject* CacheIRCloner::getObjectField(uint32_t stubOffset) {
218 return reinterpret_cast<JSObject*>(readStubWord(stubOffset));
219 }
220 JSObject* CacheIRCloner::getWeakObjectField(uint32_t stubOffset) {
221 // No barrier is required to clone a weak pointer.
222 return reinterpret_cast<JSObject*>(readStubWord(stubOffset));
223 }
224 JSString* CacheIRCloner::getStringField(uint32_t stubOffset) {
225 return reinterpret_cast<JSString*>(readStubWord(stubOffset));
226 }
227 JSAtom* CacheIRCloner::getAtomField(uint32_t stubOffset) {
228 return reinterpret_cast<JSAtom*>(readStubWord(stubOffset));
229 }
230 JS::Symbol* CacheIRCloner::getSymbolField(uint32_t stubOffset) {
231 return reinterpret_cast<JS::Symbol*>(readStubWord(stubOffset));
232 }
233 BaseScript* CacheIRCloner::getWeakBaseScriptField(uint32_t stubOffset) {
234 // No barrier is required to clone a weak pointer.
235 return reinterpret_cast<BaseScript*>(readStubWord(stubOffset));
236 }
237 JitCode* CacheIRCloner::getJitCodeField(uint32_t stubOffset) {
238 return reinterpret_cast<JitCode*>(readStubWord(stubOffset));
239 }
240 uint32_t CacheIRCloner::getRawInt32Field(uint32_t stubOffset) {
241 return uint32_t(reinterpret_cast<uintptr_t>(readStubWord(stubOffset)));
242 }
243 const void* CacheIRCloner::getRawPointerField(uint32_t stubOffset) {
244 return reinterpret_cast<const void*>(readStubWord(stubOffset));
245 }
246 const ICScript* CacheIRCloner::getICScriptField(uint32_t stubOffset) {
247 return reinterpret_cast<const ICScript*>(readStubWord(stubOffset));
248 }
249 uint64_t CacheIRCloner::getRawInt64Field(uint32_t stubOffset) {
250 return static_cast<uint64_t>(readStubInt64(stubOffset));
251 }
252 gc::AllocSite* CacheIRCloner::getAllocSiteField(uint32_t stubOffset) {
253 return reinterpret_cast<gc::AllocSite*>(readStubWord(stubOffset));
254 }
255
256 jsid CacheIRCloner::getIdField(uint32_t stubOffset) {
257 return jsid::fromRawBits(readStubWord(stubOffset));
258 }
259 const Value CacheIRCloner::getValueField(uint32_t stubOffset) {
260 return Value::fromRawBits(uint64_t(readStubInt64(stubOffset)));
261 }
262 double CacheIRCloner::getDoubleField(uint32_t stubOffset) {
263 uint64_t bits = uint64_t(readStubInt64(stubOffset));
264 return mozilla::BitwiseCast<double>(bits);
265 }
266
267 IRGenerator::IRGenerator(JSContext* cx, HandleScript script, jsbytecode* pc,
268 CacheKind cacheKind, ICState state,
269 BaselineFrame* maybeFrame)
270 : writer(cx),
271 cx_(cx),
272 script_(script),
273 pc_(pc),
274 maybeFrame_(maybeFrame),
275 cacheKind_(cacheKind),
276 mode_(state.mode()),
277 isFirstStub_(state.newStubIsFirstStub()),
278 numOptimizedStubs_(state.numOptimizedStubs()) {}
279
280 // Allocation sites are usually created during baseline compilation, but we also
281 // need to create them when an IC stub is added to a baseline compiled script
282 // and when trial inlining.
283 gc::AllocSite* IRGenerator::maybeCreateAllocSite() {
284 MOZ_ASSERT(BytecodeOpCanHaveAllocSite(JSOp(*pc_)));
285
286 BaselineFrame* frame = maybeFrame_;
287 MOZ_ASSERT(frame);
288
289 JSScript* outerScript = frame->outerScript();
290 bool hasBaselineScript = outerScript->hasBaselineScript();
291 bool isInlined = frame->icScript()->isInlined();
292 if (!hasBaselineScript && !isInlined) {
293 MOZ_ASSERT(frame->runningInInterpreter());
294 return outerScript->zone()->unknownAllocSite(JS::TraceKind::Object);
295 }
296
297 uint32_t pcOffset = frame->script()->pcToOffset(pc_);
298 return frame->icScript()->getOrCreateAllocSite(outerScript, pcOffset);
299 }
300
301 GetPropIRGenerator::GetPropIRGenerator(JSContext* cx, HandleScript script,
302 jsbytecode* pc, ICState state,
303 CacheKind cacheKind, HandleValue val,
304 HandleValue idVal)
305 : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {}
306
307 static void EmitLoadSlotResult(CacheIRWriter& writer, ObjOperandId holderId,
308 NativeObject* holder, PropertyInfo prop) {
309 if (holder->isFixedSlot(prop.slot())) {
310 writer.loadFixedSlotResult(holderId,
311 NativeObject::getFixedSlotOffset(prop.slot()));
312 } else {
313 size_t dynamicSlotOffset =
314 holder->dynamicSlotIndex(prop.slot()) * sizeof(Value);
315 writer.loadDynamicSlotResult(holderId, dynamicSlotOffset);
316 }
317 }
318
319 // DOM proxies
320 // -----------
321 //
322 // DOM proxies are proxies that are used to implement various DOM objects like
323 // HTMLDocument and NodeList. DOM proxies may have an expando object - a native
324 // object that stores extra properties added to the object. The following
325 // CacheIR instructions are only used with DOM proxies:
326 //
327 // * LoadDOMExpandoValue: returns the Value in the proxy's expando slot. This
328 // returns either an UndefinedValue (no expando), ObjectValue (the expando
329 // object), or PrivateValue(ExpandoAndGeneration*).
330 //
331 // * LoadDOMExpandoValueGuardGeneration: guards the Value in the proxy's expando
332 // slot is the same PrivateValue(ExpandoAndGeneration*), then guards on its
333 // generation, then returns expandoAndGeneration->expando. This Value is
334 // either an UndefinedValue or ObjectValue.
335 //
336 // * LoadDOMExpandoValueIgnoreGeneration: assumes the Value in the proxy's
337 // expando slot is a PrivateValue(ExpandoAndGeneration*), unboxes it, and
338 // returns the expandoAndGeneration->expando Value.
339 //
340 // * GuardDOMExpandoMissingOrGuardShape: takes an expando Value as input, then
341 // guards it's either UndefinedValue or an object with the expected shape.
342
343 enum class ProxyStubType {
344 None,
345 DOMExpando,
346 DOMShadowed,
347 DOMUnshadowed,
348 Generic
349 };
350
351 static bool IsCacheableDOMProxy(ProxyObject* obj) {
352 const BaseProxyHandler* handler = obj->handler();
353 if (handler->family() != GetDOMProxyHandlerFamily()) {
354 return false;
355 }
356
357 // Some DOM proxies have dynamic prototypes. We can't really cache those very
358 // well.
359 return obj->hasStaticPrototype();
360 }
361
362 static ProxyStubType GetProxyStubType(JSContext* cx, HandleObject obj,
363 HandleId id) {
364 if (!obj->is<ProxyObject>()) {
365 return ProxyStubType::None;
366 }
367 auto proxy = obj.as<ProxyObject>();
368
369 if (!IsCacheableDOMProxy(proxy)) {
370 return ProxyStubType::Generic;
371 }
372
373 // Private fields are defined on a separate expando object.
374 if (id.isPrivateName()) {
375 return ProxyStubType::Generic;
376 }
377
378 DOMProxyShadowsResult shadows = GetDOMProxyShadowsCheck()(cx, proxy, id);
379 if (shadows == DOMProxyShadowsResult::ShadowCheckFailed) {
380 cx->clearPendingException();
381 return ProxyStubType::None;
382 }
383
384 if (DOMProxyIsShadowing(shadows)) {
385 if (shadows == DOMProxyShadowsResult::ShadowsViaDirectExpando ||
386 shadows == DOMProxyShadowsResult::ShadowsViaIndirectExpando) {
387 return ProxyStubType::DOMExpando;
388 }
389 return ProxyStubType::DOMShadowed;
390 }
391
392 MOZ_ASSERT(shadows == DOMProxyShadowsResult::DoesntShadow ||
393 shadows == DOMProxyShadowsResult::DoesntShadowUnique);
394 return ProxyStubType::DOMUnshadowed;
395 }
396
397 static bool ValueToNameOrSymbolId(JSContext* cx, HandleValue idVal,
398 MutableHandleId id, bool* nameOrSymbol) {
399 *nameOrSymbol = false;
400
401 if (idVal.isObject() || idVal.isBigInt()) {
402 return true;
403 }
404
405 MOZ_ASSERT(idVal.isString() || idVal.isSymbol() || idVal.isBoolean() ||
406 idVal.isUndefined() || idVal.isNull() || idVal.isNumber());
407
408 if (IsNumberIndex(idVal)) {
409 return true;
410 }
411
412 if (!PrimitiveValueToId<CanGC>(cx, idVal, id)) {
413 return false;
414 }
415
416 if (!id.isAtom() && !id.isSymbol()) {
417 id.set(JS::PropertyKey::Void());
418 return true;
419 }
420
421 if (id.isAtom() && id.toAtom()->isIndex()) {
422 id.set(JS::PropertyKey::Void());
423 return true;
424 }
425
426 *nameOrSymbol = true;
427 return true;
428 }
429
430 AttachDecision GetPropIRGenerator::tryAttachStub() {
431 AutoAssertNoPendingException aanpe(cx_);
432
433 ValOperandId valId(writer.setInputOperandId(0));
434 if (cacheKind_ != CacheKind::GetProp) {
435 MOZ_ASSERT_IF(cacheKind_ == CacheKind::GetPropSuper,
436 getSuperReceiverValueId().id() == 1);
437 MOZ_ASSERT_IF(cacheKind_ != CacheKind::GetPropSuper,
438 getElemKeyValueId().id() == 1);
439 writer.setInputOperandId(1);
440 }
441 if (cacheKind_ == CacheKind::GetElemSuper) {
442 MOZ_ASSERT(getSuperReceiverValueId().id() == 2);
443 writer.setInputOperandId(2);
444 }
445
446 RootedId id(cx_);
447 bool nameOrSymbol;
448 if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
449 cx_->clearPendingException();
450 return AttachDecision::NoAction;
451 }
452
453 // |super.prop| getter calls use a |this| value that differs from lookup
454 // object.
455 ValOperandId receiverId = isSuper() ? getSuperReceiverValueId() : valId;
456
457 if (val_.isObject()) {
458 RootedObject obj(cx_, &val_.toObject());
459 ObjOperandId objId = writer.guardToObject(valId);
460
461 TRY_ATTACH(tryAttachTypedArrayElement(obj, objId));
462
463 if (nameOrSymbol) {
464 TRY_ATTACH(tryAttachObjectLength(obj, objId, id));
465 TRY_ATTACH(tryAttachTypedArray(obj, objId, id));
466 TRY_ATTACH(tryAttachDataView(obj, objId, id));
467 TRY_ATTACH(tryAttachArrayBufferMaybeShared(obj, objId, id));
468 TRY_ATTACH(tryAttachRegExp(obj, objId, id));
469 TRY_ATTACH(tryAttachMap(obj, objId, id));
470 TRY_ATTACH(tryAttachSet(obj, objId, id));
471 TRY_ATTACH(tryAttachNative(obj, objId, id, receiverId));
472 TRY_ATTACH(tryAttachModuleNamespace(obj, objId, id));
473 TRY_ATTACH(tryAttachWindowProxy(obj, objId, id));
474 TRY_ATTACH(tryAttachCrossCompartmentWrapper(obj, objId, id));
475 TRY_ATTACH(
476 tryAttachXrayCrossCompartmentWrapper(obj, objId, id, receiverId));
477 TRY_ATTACH(tryAttachFunction(obj, objId, id));
478 TRY_ATTACH(tryAttachArgumentsObjectIterator(obj, objId, id));
479 TRY_ATTACH(tryAttachArgumentsObjectCallee(obj, objId, id));
480 TRY_ATTACH(tryAttachProxy(obj, objId, id, receiverId));
481
482 if (!isSuper() && mode_ == ICState::Mode::Megamorphic &&
483 JSOp(*pc_) != JSOp::GetBoundName) {
484 attachMegamorphicNativeSlotPermissive(objId, id);
485 return AttachDecision::Attach;
486 }
487
488 trackAttached(IRGenerator::NotAttached);
489 return AttachDecision::NoAction;
490 }
491
492 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
493 cacheKind_ == CacheKind::GetElemSuper);
494
495 TRY_ATTACH(tryAttachProxyElement(obj, objId));
496
497 uint32_t index;
498 Int32OperandId indexId;
499 if (maybeGuardInt32Index(idVal_, getElemKeyValueId(), &index, &indexId)) {
500 TRY_ATTACH(tryAttachDenseElement(obj, objId, index, indexId));
501 TRY_ATTACH(tryAttachDenseElementHole(obj, objId, index, indexId));
502 TRY_ATTACH(tryAttachSparseElement(obj, objId, index, indexId));
503 TRY_ATTACH(tryAttachArgumentsObjectArg(obj, objId, index, indexId));
504 TRY_ATTACH(tryAttachArgumentsObjectArgHole(obj, objId, index, indexId));
505 TRY_ATTACH(
506 tryAttachGenericElement(obj, objId, index, indexId, receiverId));
507
508 trackAttached(IRGenerator::NotAttached);
509 return AttachDecision::NoAction;
510 }
511
512 trackAttached(IRGenerator::NotAttached);
513 return AttachDecision::NoAction;
514 }
515
516 if (nameOrSymbol) {
517 TRY_ATTACH(tryAttachPrimitive(valId, id));
518 TRY_ATTACH(tryAttachStringLength(valId, id));
519
520 trackAttached(IRGenerator::NotAttached);
521 return AttachDecision::NoAction;
522 }
523
524 if (idVal_.isInt32()) {
525 ValOperandId indexId = getElemKeyValueId();
526 TRY_ATTACH(tryAttachStringChar(valId, indexId));
527
528 trackAttached(IRGenerator::NotAttached);
529 return AttachDecision::NoAction;
530 }
531
532 trackAttached(IRGenerator::NotAttached);
533 return AttachDecision::NoAction;
534 }
535
536 #ifdef DEBUG
537 // Any property lookups performed when trying to attach ICs must be pure, i.e.
538 // must use LookupPropertyPure() or similar functions. Pure lookups are
539 // guaranteed to never modify the prototype chain. This ensures that the holder
540 // object can always be found on the prototype chain.
541 static bool IsCacheableProtoChain(NativeObject* obj, NativeObject* holder) {
542 while (obj != holder) {
543 JSObject* proto = obj->staticPrototype();
544 if (!proto || !proto->is<NativeObject>()) {
545 return false;
546 }
547 obj = &proto->as<NativeObject>();
548 }
549 return true;
550 }
551 #endif
552
553 static bool IsCacheableGetPropSlot(NativeObject* obj, NativeObject* holder,
554 PropertyInfo prop) {
555 MOZ_ASSERT(IsCacheableProtoChain(obj, holder));
556
557 return prop.isDataProperty();
558 }
559
560 enum class NativeGetPropKind {
561 None,
562 Missing,
563 Slot,
564 NativeGetter,
565 ScriptedGetter,
566 };
567
568 static NativeGetPropKind IsCacheableGetPropCall(NativeObject* obj,
569 NativeObject* holder,
570 PropertyInfo prop,
571 jsbytecode* pc = nullptr) {
572 MOZ_ASSERT(IsCacheableProtoChain(obj, holder));
573
574 if (pc && JSOp(*pc) == JSOp::GetBoundName) {
575 return NativeGetPropKind::None;
576 }
577
578 if (!prop.isAccessorProperty()) {
579 return NativeGetPropKind::None;
580 }
581
582 JSObject* getterObject = holder->getGetter(prop);
583 if (!getterObject || !getterObject->is<JSFunction>()) {
584 return NativeGetPropKind::None;
585 }
586
587 JSFunction& getter = getterObject->as<JSFunction>();
588
589 if (getter.isClassConstructor()) {
590 return NativeGetPropKind::None;
591 }
592
593 // Scripted functions and natives with JIT entry can use the scripted path.
594 if (getter.hasJitEntry()) {
595 return NativeGetPropKind::ScriptedGetter;
596 }
597
598 MOZ_ASSERT(getter.isNativeWithoutJitEntry());
599 return NativeGetPropKind::NativeGetter;
600 }
601
602 static bool CheckHasNoSuchOwnProperty(JSContext* cx, JSObject* obj, jsid id) {
603 if (!obj->is<NativeObject>()) {
604 return false;
605 }
606 // Don't handle objects with resolve hooks.
607 if (ClassMayResolveId(cx->names(), obj->getClass(), id, obj)) {
608 return false;
609 }
610 if (obj->as<NativeObject>().contains(cx, id)) {
611 return false;
612 }
613 if (obj->is<TypedArrayObject>() && ToTypedArrayIndex(id).isSome()) {
614 return false;
615 }
616 return true;
617 }
618
619 static bool CheckHasNoSuchProperty(JSContext* cx, JSObject* obj, jsid id) {
620 JSObject* curObj = obj;
621 do {
622 if (!CheckHasNoSuchOwnProperty(cx, curObj, id)) {
623 return false;
624 }
625
626 curObj = curObj->staticPrototype();
627 } while (curObj);
628
629 return true;
630 }
631
632 static bool IsCacheableNoProperty(JSContext* cx, NativeObject* obj,
633 NativeObject* holder, jsid id,
634 jsbytecode* pc) {
635 MOZ_ASSERT(!holder);
636
637 // If we're doing a name lookup, we have to throw a ReferenceError.
638 if (JSOp(*pc) == JSOp::GetBoundName) {
639 return false;
640 }
641
642 return CheckHasNoSuchProperty(cx, obj, id);
643 }
644
645 static NativeGetPropKind CanAttachNativeGetProp(JSContext* cx, JSObject* obj,
646 PropertyKey id,
647 NativeObject** holder,
648 Maybe<PropertyInfo>* propInfo,
649 jsbytecode* pc) {
650 MOZ_ASSERT(id.isString() || id.isSymbol());
651 MOZ_ASSERT(!*holder);
652
653 // The lookup needs to be universally pure, otherwise we risk calling hooks
654 // out of turn. We don't mind doing this even when purity isn't required,
655 // because we only miss out on shape hashification, which is only a temporary
656 // perf cost. The limits were arbitrarily set, anyways.
657 NativeObject* baseHolder = nullptr;
658 PropertyResult prop;
659 if (!LookupPropertyPure(cx, obj, id, &baseHolder, &prop)) {
660 return NativeGetPropKind::None;
661 }
662 auto* nobj = &obj->as<NativeObject>();
663
664 if (prop.isNativeProperty()) {
665 MOZ_ASSERT(baseHolder);
666 *holder = baseHolder;
667 *propInfo = mozilla::Some(prop.propertyInfo());
668
669 if (IsCacheableGetPropSlot(nobj, *holder, propInfo->ref())) {
670 return NativeGetPropKind::Slot;
671 }
672
673 return IsCacheableGetPropCall(nobj, *holder, propInfo->ref(), pc);
674 }
675
676 if (!prop.isFound()) {
677 if (IsCacheableNoProperty(cx, nobj, *holder, id, pc)) {
678 return NativeGetPropKind::Missing;
679 }
680 }
681
682 return NativeGetPropKind::None;
683 }
684
685 static void GuardReceiverProto(CacheIRWriter& writer, NativeObject* obj,
686 ObjOperandId objId) {
687 // Note: we guard on the actual prototype and not on the shape because this is
688 // used for sparse elements where we expect shape changes.
689
690 if (JSObject* proto = obj->staticPrototype()) {
691 writer.guardProto(objId, proto);
692 } else {
693 writer.guardNullProto(objId);
694 }
695 }
696
697 // Guard that a given object has same class and same OwnProperties (excluding
698 // dense elements and dynamic properties).
699 static void TestMatchingNativeReceiver(CacheIRWriter& writer, NativeObject* obj,
700 ObjOperandId objId) {
701 writer.guardShapeForOwnProperties(objId, obj->shape());
702 }
703
704 // Similar to |TestMatchingNativeReceiver|, but specialized for ProxyObject.
705 static void TestMatchingProxyReceiver(CacheIRWriter& writer, ProxyObject* obj,
706 ObjOperandId objId) {
707 writer.guardShapeForClass(objId, obj->shape());
708 }
709
710 static void GeneratePrototypeGuards(CacheIRWriter& writer, JSObject* obj,
711 NativeObject* holder, ObjOperandId objId) {
712 // Assuming target property is on |holder|, generate appropriate guards to
713 // ensure |holder| is still on the prototype chain of |obj| and we haven't
714 // introduced any shadowing definitions.
715 //
716 // For each item in the proto chain before holder, we must ensure that
717 // [[GetPrototypeOf]] still has the expected result, and that
718 // [[GetOwnProperty]] has no definition of the target property.
719 //
720 //
721 // [SMDOC] Shape Teleporting Optimization
722 // --------------------------------------
723 //
724 // Starting with the assumption (and guideline to developers) that mutating
725 // prototypes is an uncommon and fair-to-penalize operation we move cost
726 // from the access side to the mutation side.
727 //
728 // Consider the following proto chain, with B defining a property 'x':
729 //
730 // D -> C -> B{x: 3} -> A -> null
731 //
732 // When accessing |D.x| we refer to D as the "receiver", and B as the
733 // "holder". To optimize this access we need to ensure that neither D nor C
734 // has since defined a shadowing property 'x'. Since C is a prototype that
735 // we assume is rarely mutated we would like to avoid checking each time if
736 // new properties are added. To do this we require that whenever C starts
737 // shadowing a property on its proto chain, we invalidate (and opt out of) the
738 // teleporting optimization by setting the InvalidatedTeleporting flag on the
739 // object we're shadowing, triggering a shape change of that object. As a
740 // result, checking the shape of D and B is sufficient. Note that we do not
741 // care if the shape or properties of A change since the lookup of 'x' will
742 // stop at B.
743 //
744 // The second condition we must verify is that the prototype chain was not
745 // mutated. The same mechanism as above is used. When the prototype link is
746 // changed, we generate a new shape for the object. If the object whose
747 // link we are mutating is itself a prototype, we regenerate shapes down
748 // the chain by setting the InvalidatedTeleporting flag on them. This means
749 // the same two shape checks as above are sufficient.
750 //
751 // Once the InvalidatedTeleporting flag is set, it means the shape will no
752 // longer be changed by ReshapeForProtoMutation and ReshapeForShadowedProp.
753 // In this case we can no longer apply the optimization.
754 //
755 // See:
756 // - ReshapeForProtoMutation
757 // - ReshapeForShadowedProp
758
759 MOZ_ASSERT(holder);
760 MOZ_ASSERT(obj != holder);
761
762 // Receiver guards (see TestMatchingReceiver) ensure the receiver's proto is
763 // unchanged so peel off the receiver.
764 JSObject* pobj = obj->staticPrototype();
765 MOZ_ASSERT(pobj->isUsedAsPrototype());
766
767 // If teleporting is supported for this holder, we are done.
768 if (!holder->hasInvalidatedTeleporting()) {
769 return;
770 }
771
772 // If already at the holder, no further proto checks are needed.
773 if (pobj == holder) {
774 return;
775 }
776
777 // Synchronize pobj and protoId.
778 MOZ_ASSERT(pobj == obj->staticPrototype());
779 ObjOperandId protoId = writer.loadProto(objId);
780
781 // Shape guard each prototype object between receiver and holder. This guards
782 // against both proto changes and shadowing properties.
783 while (pobj != holder) {
784 writer.guardShape(protoId, pobj->shape());
785
786 pobj = pobj->staticPrototype();
787 protoId = writer.loadProto(protoId);
788 }
789 }
790
791 static void GeneratePrototypeHoleGuards(CacheIRWriter& writer,
792 NativeObject* obj, ObjOperandId objId,
793 bool alwaysGuardFirstProto) {
794 if (alwaysGuardFirstProto) {
795 GuardReceiverProto(writer, obj, objId);
796 }
797
798 JSObject* pobj = obj->staticPrototype();
799 while (pobj) {
800 ObjOperandId protoId = writer.loadObject(pobj);
801
802 // Make sure the shape matches, to ensure the proto is unchanged and to
803 // avoid non-dense elements or anything else that is being checked by
804 // CanAttachDenseElementHole.
805 MOZ_ASSERT(pobj->is<NativeObject>());
806 writer.guardShape(protoId, pobj->shape());
807
808 // Also make sure there are no dense elements.
809 writer.guardNoDenseElements(protoId);
810
811 pobj = pobj->staticPrototype();
812 }
813 }
814
815 // Similar to |TestMatchingReceiver|, but for the holder object (when it
816 // differs from the receiver). The holder may also be the expando of the
817 // receiver if it exists.
818 static void TestMatchingHolder(CacheIRWriter& writer, NativeObject* obj,
819 ObjOperandId objId) {
820 // The GeneratePrototypeGuards + TestMatchingHolder checks only support
821 // prototype chains composed of NativeObject (excluding the receiver
822 // itself).
823 writer.guardShapeForOwnProperties(objId, obj->shape());
824 }
825
826 enum class IsCrossCompartment { No, Yes };
827
828 // Emit a shape guard for all objects on the proto chain. This does NOT include
829 // the receiver; callers must ensure the receiver's proto is the first proto by
830 // either emitting a shape guard or a prototype guard for |objId|.
831 //
832 // Note: this relies on shape implying proto.
833 template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
834 static void ShapeGuardProtoChain(CacheIRWriter& writer, NativeObject* obj,
835 ObjOperandId objId) {
836 uint32_t depth = 0;
837 static const uint32_t MAX_CACHED_LOADS = 4;
838 ObjOperandId receiverObjId = objId;
839
840 while (true) {
841 JSObject* proto = obj->staticPrototype();
842 if (!proto) {
843 return;
844 }
845
846 obj = &proto->as<NativeObject>();
847
848 // After guarding the shape of an object, we can safely bake that
849 // object's proto into the stub data. Compared to LoadProto, this
850 // takes one load instead of three (object -> shape -> baseshape
851 // -> proto). We cap the depth to avoid bloating the size of the
852 // stub data. To avoid compartment mismatch, we skip this optimization
853 // in the cross-compartment case.
854 if (depth < MAX_CACHED_LOADS &&
855 MaybeCrossCompartment == IsCrossCompartment::No) {
856 objId = writer.loadProtoObject(obj, receiverObjId);
857 } else {
858 objId = writer.loadProto(objId);
859 }
860 depth++;
861
862 writer.guardShape(objId, obj->shape());
863 }
864 }
865
866 // For cross compartment guards we shape-guard the prototype chain to avoid
867 // referencing the holder object.
868 //
869 // This peels off the first layer because it's guarded against obj == holder.
870 //
871 // Returns the holder's OperandId.
872 static ObjOperandId ShapeGuardProtoChainForCrossCompartmentHolder(
873 CacheIRWriter& writer, NativeObject* obj, ObjOperandId objId,
874 NativeObject* holder) {
875 MOZ_ASSERT(obj != holder);
876 MOZ_ASSERT(holder);
877 while (true) {
878 MOZ_ASSERT(obj->staticPrototype());
879 obj = &obj->staticPrototype()->as<NativeObject>();
880
881 objId = writer.loadProto(objId);
882 if (obj == holder) {
883 TestMatchingHolder(writer, obj, objId);
884 return objId;
885 }
886 writer.guardShapeForOwnProperties(objId, obj->shape());
887 }
888 }
889
890 // Emit guards for reading a data property on |holder|. Returns the holder's
891 // OperandId.
892 template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
893 static ObjOperandId EmitReadSlotGuard(CacheIRWriter& writer, NativeObject* obj,
894 NativeObject* holder,
895 ObjOperandId objId) {
896 MOZ_ASSERT(holder);
897 TestMatchingNativeReceiver(writer, obj, objId);
898
899 if (obj == holder) {
900 return objId;
901 }
902
903 if (MaybeCrossCompartment == IsCrossCompartment::Yes) {
904 // Guard proto chain integrity.
905 // We use a variant of guards that avoid baking in any cross-compartment
906 // object pointers.
907 return ShapeGuardProtoChainForCrossCompartmentHolder(writer, obj, objId,
908 holder);
909 }
910
911 // Guard proto chain integrity.
912 GeneratePrototypeGuards(writer, obj, holder, objId);
913
914 // Guard on the holder's shape.
915 ObjOperandId holderId = writer.loadObject(holder);
916 TestMatchingHolder(writer, holder, holderId);
917 return holderId;
918 }
919
920 template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
921 static void EmitMissingPropGuard(CacheIRWriter& writer, NativeObject* obj,
922 ObjOperandId objId) {
923 TestMatchingNativeReceiver(writer, obj, objId);
924
925 // The property does not exist. Guard on everything in the prototype
926 // chain. This is guaranteed to see only Native objects because of
927 // CanAttachNativeGetProp().
928 ShapeGuardProtoChain<MaybeCrossCompartment>(writer, obj, objId);
929 }
930
931 template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
932 static void EmitReadSlotResult(CacheIRWriter& writer, NativeObject* obj,
933 NativeObject* holder, PropertyInfo prop,
934 ObjOperandId objId) {
935 MOZ_ASSERT(holder);
936
937 ObjOperandId holderId =
938 EmitReadSlotGuard<MaybeCrossCompartment>(writer, obj, holder, objId);
939
940 MOZ_ASSERT(holderId.valid());
941 EmitLoadSlotResult(writer, holderId, holder, prop);
942 }
943
944 template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
945 static void EmitMissingPropResult(CacheIRWriter& writer, NativeObject* obj,
946 ObjOperandId objId) {
947 EmitMissingPropGuard<MaybeCrossCompartment>(writer, obj, objId);
948 writer.loadUndefinedResult();
949 }
950
951 static void EmitCallGetterResultNoGuards(JSContext* cx, CacheIRWriter& writer,
952 NativeGetPropKind kind,
953 NativeObject* obj,
954 NativeObject* holder,
955 PropertyInfo prop,
956 ValOperandId receiverId) {
957 MOZ_ASSERT(IsCacheableGetPropCall(obj, holder, prop) == kind);
958
959 JSFunction* target = &holder->getGetter(prop)->as<JSFunction>();
960 bool sameRealm = cx->realm() == target->realm();
961
962 switch (kind) {
963 case NativeGetPropKind::NativeGetter: {
964 writer.callNativeGetterResult(receiverId, target, sameRealm);
965 writer.returnFromIC();
966 break;
967 }
968 case NativeGetPropKind::ScriptedGetter: {
969 writer.callScriptedGetterResult(receiverId, target, sameRealm);
970 writer.returnFromIC();
971 break;
972 }
973 default:
974 // CanAttachNativeGetProp guarantees that the getter is either a native or
975 // a scripted function.
976 MOZ_ASSERT_UNREACHABLE("Can't attach getter");
977 break;
978 }
979 }
980
981 // See the SMDOC comment in vm/GetterSetter.h for more info on Getter/Setter
982 // properties
983 static void EmitGuardGetterSetterSlot(CacheIRWriter& writer,
984 NativeObject* holder, PropertyInfo prop,
985 ObjOperandId holderId,
986 bool holderIsConstant = false) {
987 // If the holder is guaranteed to be the same object, and it never had a
988 // slot holding a GetterSetter mutated or deleted, its Shape will change when
989 // that does happen so we don't need to guard on the GetterSetter.
990 if (holderIsConstant && !holder->hadGetterSetterChange()) {
991 return;
992 }
993
994 size_t slot = prop.slot();
995 Value slotVal = holder->getSlot(slot);
996 MOZ_ASSERT(slotVal.isPrivateGCThing());
997
998 if (holder->isFixedSlot(slot)) {
999 size_t offset = NativeObject::getFixedSlotOffset(slot);
1000 writer.guardFixedSlotValue(holderId, offset, slotVal);
1001 } else {
1002 size_t offset = holder->dynamicSlotIndex(slot) * sizeof(Value);
1003 writer.guardDynamicSlotValue(holderId, offset, slotVal);
1004 }
1005 }
1006
1007 static void EmitCallGetterResultGuards(CacheIRWriter& writer, NativeObject* obj,
1008 NativeObject* holder, HandleId id,
1009 PropertyInfo prop, ObjOperandId objId,
1010 ICState::Mode mode) {
1011 // Use the megamorphic guard if we're in megamorphic mode, except if |obj|
1012 // is a Window as GuardHasGetterSetter doesn't support this yet (Window may
1013 // require outerizing).
1014
1015 MOZ_ASSERT(holder->containsPure(id, prop));
1016
1017 if (mode == ICState::Mode::Specialized || IsWindow(obj)) {
1018 TestMatchingNativeReceiver(writer, obj, objId);
1019
1020 if (obj != holder) {
1021 GeneratePrototypeGuards(writer, obj, holder, objId);
1022
1023 // Guard on the holder's shape.
1024 ObjOperandId holderId = writer.loadObject(holder);
1025 TestMatchingHolder(writer, holder, holderId);
1026
1027 EmitGuardGetterSetterSlot(writer, holder, prop, holderId,
1028 /* holderIsConstant = */ true);
1029 } else {
1030 EmitGuardGetterSetterSlot(writer, holder, prop, objId);
1031 }
1032 } else {
1033 GetterSetter* gs = holder->getGetterSetter(prop);
1034 writer.guardHasGetterSetter(objId, id, gs);
1035 }
1036 }
1037
1038 static void EmitCallGetterResult(JSContext* cx, CacheIRWriter& writer,
1039 NativeGetPropKind kind, NativeObject* obj,
1040 NativeObject* holder, HandleId id,
1041 PropertyInfo prop, ObjOperandId objId,
1042 ValOperandId receiverId, ICState::Mode mode) {
1043 EmitCallGetterResultGuards(writer, obj, holder, id, prop, objId, mode);
1044 EmitCallGetterResultNoGuards(cx, writer, kind, obj, holder, prop, receiverId);
1045 }
1046
1047 static bool CanAttachDOMCall(JSContext* cx, JSJitInfo::OpType type,
1048 JSObject* obj, JSFunction* fun,
1049 ICState::Mode mode) {
1050 MOZ_ASSERT(type == JSJitInfo::Getter || type == JSJitInfo::Setter ||
1051 type == JSJitInfo::Method);
1052
1053 if (mode != ICState::Mode::Specialized) {
1054 return false;
1055 }
1056
1057 if (!fun->hasJitInfo()) {
1058 return false;
1059 }
1060
1061 if (cx->realm() != fun->realm()) {
1062 return false;
1063 }
1064
1065 const JSJitInfo* jitInfo = fun->jitInfo();
1066 if (jitInfo->type() != type) {
1067 return false;
1068 }
1069
1070 MOZ_ASSERT_IF(IsWindow(obj), !jitInfo->needsOuterizedThisObject());
1071
1072 const JSClass* clasp = obj->getClass();
1073 if (!clasp->isDOMClass()) {
1074 return false;
1075 }
1076
1077 if (type != JSJitInfo::Method && clasp->isProxyObject()) {
1078 return false;
1079 }
1080
1081 // Ion codegen expects DOM_OBJECT_SLOT to be a fixed slot in LoadDOMPrivate.
1082 // It can be a dynamic slot if we transplanted this reflector object with a
1083 // proxy.
1084 if (obj->is<NativeObject>() && obj->as<NativeObject>().numFixedSlots() == 0) {
1085 return false;
1086 }
1087
1088 // Tell the analysis the |DOMInstanceClassHasProtoAtDepth| hook can't GC.
1089 JS::AutoSuppressGCAnalysis nogc;
1090
1091 DOMInstanceClassHasProtoAtDepth instanceChecker =
1092 cx->runtime()->DOMcallbacks->instanceClassMatchesProto;
1093 return instanceChecker(clasp, jitInfo->protoID, jitInfo->depth);
1094 }
1095
1096 static bool CanAttachDOMGetterSetter(JSContext* cx, JSJitInfo::OpType type,
1097 NativeObject* obj, NativeObject* holder,
1098 PropertyInfo prop, ICState::Mode mode) {
1099 MOZ_ASSERT(type == JSJitInfo::Getter || type == JSJitInfo::Setter);
1100
1101 JSObject* accessor = type == JSJitInfo::Getter ? holder->getGetter(prop)
1102 : holder->getSetter(prop);
1103 JSFunction* fun = &accessor->as<JSFunction>();
1104
1105 return CanAttachDOMCall(cx, type, obj, fun, mode);
1106 }
1107
1108 static void EmitCallDOMGetterResultNoGuards(CacheIRWriter& writer,
1109 NativeObject* holder,
1110 PropertyInfo prop,
1111 ObjOperandId objId) {
1112 JSFunction* getter = &holder->getGetter(prop)->as<JSFunction>();
1113 writer.callDOMGetterResult(objId, getter->jitInfo());
1114 writer.returnFromIC();
1115 }
1116
1117 static void EmitCallDOMGetterResult(JSContext* cx, CacheIRWriter& writer,
1118 NativeObject* obj, NativeObject* holder,
1119 HandleId id, PropertyInfo prop,
1120 ObjOperandId objId) {
1121 // Note: this relies on EmitCallGetterResultGuards emitting a shape guard
1122 // for specialized stubs.
1123 // The shape guard ensures the receiver's Class is valid for this DOM getter.
1124 EmitCallGetterResultGuards(writer, obj, holder, id, prop, objId,
1125 ICState::Mode::Specialized);
1126 EmitCallDOMGetterResultNoGuards(writer, holder, prop, objId);
1127 }
1128
1129 static ValOperandId EmitLoadSlot(CacheIRWriter& writer, NativeObject* holder,
1130 ObjOperandId holderId, uint32_t slot) {
1131 if (holder->isFixedSlot(slot)) {
1132 return writer.loadFixedSlot(holderId,
1133 NativeObject::getFixedSlotOffset(slot));
1134 }
1135 size_t dynamicSlotIndex = holder->dynamicSlotIndex(slot);
1136 return writer.loadDynamicSlot(holderId, dynamicSlotIndex);
1137 }
1138
1139 void GetPropIRGenerator::attachMegamorphicNativeSlot(ObjOperandId objId,
1140 jsid id) {
1141 MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
1142
1143 // We don't support GetBoundName because environment objects have
1144 // lookupProperty hooks and GetBoundName is usually not megamorphic.
1145 MOZ_ASSERT(JSOp(*pc_) != JSOp::GetBoundName);
1146
1147 if (cacheKind_ == CacheKind::GetProp ||
1148 cacheKind_ == CacheKind::GetPropSuper) {
1149 writer.megamorphicLoadSlotResult(objId, id);
1150 } else {
1151 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
1152 cacheKind_ == CacheKind::GetElemSuper);
1153 writer.megamorphicLoadSlotByValueResult(objId, getElemKeyValueId());
1154 }
1155 writer.returnFromIC();
1156
1157 trackAttached("GetProp.MegamorphicNativeSlot");
1158 }
1159
1160 void GetPropIRGenerator::attachMegamorphicNativeSlotPermissive(
1161 ObjOperandId objId, jsid id) {
1162 MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
1163
1164 // We don't support GetBoundName because environment objects have
1165 // lookupProperty hooks and GetBoundName is usually not megamorphic.
1166 MOZ_ASSERT(JSOp(*pc_) != JSOp::GetBoundName);
1167 // It is not worth the complexity to support super here because we'd have
1168 // to plumb the receiver through everywhere, so we just skip it.
1169 MOZ_ASSERT(!isSuper());
1170
1171 if (cacheKind_ == CacheKind::GetProp) {
1172 writer.megamorphicLoadSlotPermissiveResult(objId, id);
1173 } else {
1174 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem);
1175 writer.megamorphicLoadSlotByValuePermissiveResult(objId,
1176 getElemKeyValueId());
1177 }
1178 writer.returnFromIC();
1179
1180 trackAttached("GetProp.MegamorphicNativeSlotPermissive");
1181 }
1182
1183 AttachDecision GetPropIRGenerator::tryAttachNative(HandleObject obj,
1184 ObjOperandId objId,
1185 HandleId id,
1186 ValOperandId receiverId) {
1187 Maybe<PropertyInfo> prop;
1188 NativeObject* holder = nullptr;
1189
1190 NativeGetPropKind kind =
1191 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
1192 switch (kind) {
1193 case NativeGetPropKind::None:
1194 return AttachDecision::NoAction;
1195 case NativeGetPropKind::Missing:
1196 case NativeGetPropKind::Slot: {
1197 auto* nobj = &obj->as<NativeObject>();
1198
1199 if (mode_ == ICState::Mode::Megamorphic &&
1200 JSOp(*pc_) != JSOp::GetBoundName) {
1201 attachMegamorphicNativeSlot(objId, id);
1202 return AttachDecision::Attach;
1203 }
1204
1205 maybeEmitIdGuard(id);
1206 if (kind == NativeGetPropKind::Slot) {
1207 EmitReadSlotResult(writer, nobj, holder, *prop, objId);
1208 writer.returnFromIC();
1209 trackAttached("GetProp.NativeSlot");
1210 } else {
1211 EmitMissingPropResult(writer, nobj, objId);
1212 writer.returnFromIC();
1213 trackAttached("GetProp.Missing");
1214 }
1215 return AttachDecision::Attach;
1216 }
1217 case NativeGetPropKind::ScriptedGetter:
1218 case NativeGetPropKind::NativeGetter: {
1219 auto* nobj = &obj->as<NativeObject>();
1220 MOZ_ASSERT(!IsWindow(nobj));
1221
1222 // If we're in megamorphic mode, we assume that a specialized
1223 // getter call is just going to end up failing later, so we let this
1224 // get handled further down the chain by
1225 // attachMegamorphicNativeSlotPermissive
1226 if (!isSuper() && mode_ == ICState::Mode::Megamorphic) {
1227 return AttachDecision::NoAction;
1228 }
1229
1230 maybeEmitIdGuard(id);
1231
1232 if (!isSuper() && CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, nobj,
1233 holder, *prop, mode_)) {
1234 EmitCallDOMGetterResult(cx_, writer, nobj, holder, id, *prop, objId);
1235
1236 trackAttached("GetProp.DOMGetter");
1237 return AttachDecision::Attach;
1238 }
1239
1240 EmitCallGetterResult(cx_, writer, kind, nobj, holder, id, *prop, objId,
1241 receiverId, mode_);
1242
1243 trackAttached("GetProp.NativeGetter");
1244 return AttachDecision::Attach;
1245 }
1246 }
1247
1248 MOZ_CRASH("Bad NativeGetPropKind");
1249 }
1250
1251 // Returns whether obj is a WindowProxy wrapping the script's global.
1252 static bool IsWindowProxyForScriptGlobal(JSScript* script, JSObject* obj) {
1253 if (!IsWindowProxy(obj)) {
1254 return false;
1255 }
1256
1257 MOZ_ASSERT(obj->getClass() ==
1258 script->runtimeFromMainThread()->maybeWindowProxyClass());
1259
1260 JSObject* window = ToWindowIfWindowProxy(obj);
1261
1262 // Ion relies on the WindowProxy's group changing (and the group getting
1263 // marked as having unknown properties) on navigation. If we ever stop
1264 // transplanting same-compartment WindowProxies, this assert will fail and we
1265 // need to fix that code.
1266 MOZ_ASSERT(window == &obj->nonCCWGlobal());
1267
1268 // This must be a WindowProxy for a global in this compartment. Else it would
1269 // be a cross-compartment wrapper and IsWindowProxy returns false for
1270 // those.
1271 MOZ_ASSERT(script->compartment() == obj->compartment());
1272
1273 // Only optimize lookups on the WindowProxy for the current global. Other
1274 // WindowProxies in the compartment may require security checks (based on
1275 // mutable document.domain). See bug 1516775.
1276 return window == &script->global();
1277 }
1278
1279 // Guards objId is a WindowProxy for windowObj. Returns the window's operand id.
1280 static ObjOperandId GuardAndLoadWindowProxyWindow(CacheIRWriter& writer,
1281 ObjOperandId objId,
1282 GlobalObject* windowObj) {
1283 writer.guardClass(objId, GuardClassKind::WindowProxy);
1284 ObjOperandId windowObjId = writer.loadWrapperTarget(objId,
1285 /*fallible = */ false);
1286 writer.guardSpecificObject(windowObjId, windowObj);
1287 return windowObjId;
1288 }
1289
1290 // Whether a getter/setter on the global should have the WindowProxy as |this|
1291 // value instead of the Window (the global object). This always returns true for
1292 // scripted functions.
1293 static bool GetterNeedsWindowProxyThis(NativeObject* holder,
1294 PropertyInfo prop) {
1295 JSFunction* callee = &holder->getGetter(prop)->as<JSFunction>();
1296 return !callee->hasJitInfo() || callee->jitInfo()->needsOuterizedThisObject();
1297 }
1298 static bool SetterNeedsWindowProxyThis(NativeObject* holder,
1299 PropertyInfo prop) {
1300 JSFunction* callee = &holder->getSetter(prop)->as<JSFunction>();
1301 return !callee->hasJitInfo() || callee->jitInfo()->needsOuterizedThisObject();
1302 }
1303
1304 AttachDecision GetPropIRGenerator::tryAttachWindowProxy(HandleObject obj,
1305 ObjOperandId objId,
1306 HandleId id) {
1307 // Attach a stub when the receiver is a WindowProxy and we can do the lookup
1308 // on the Window (the global object).
1309
1310 if (!IsWindowProxyForScriptGlobal(script_, obj)) {
1311 return AttachDecision::NoAction;
1312 }
1313
1314 // If we're megamorphic prefer a generic proxy stub that handles a lot more
1315 // cases.
1316 if (mode_ == ICState::Mode::Megamorphic) {
1317 return AttachDecision::NoAction;
1318 }
1319
1320 // Now try to do the lookup on the Window (the current global).
1321 GlobalObject* windowObj = cx_->global();
1322 NativeObject* holder = nullptr;
1323 Maybe<PropertyInfo> prop;
1324 NativeGetPropKind kind =
1325 CanAttachNativeGetProp(cx_, windowObj, id, &holder, &prop, pc_);
1326 switch (kind) {
1327 case NativeGetPropKind::None:
1328 return AttachDecision::NoAction;
1329
1330 case NativeGetPropKind::Slot: {
1331 maybeEmitIdGuard(id);
1332 ObjOperandId windowObjId =
1333 GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
1334 EmitReadSlotResult(writer, windowObj, holder, *prop, windowObjId);
1335 writer.returnFromIC();
1336
1337 trackAttached("GetProp.WindowProxySlot");
1338 return AttachDecision::Attach;
1339 }
1340
1341 case NativeGetPropKind::Missing: {
1342 maybeEmitIdGuard(id);
1343 ObjOperandId windowObjId =
1344 GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
1345 EmitMissingPropResult(writer, windowObj, windowObjId);
1346 writer.returnFromIC();
1347
1348 trackAttached("GetProp.WindowProxyMissing");
1349 return AttachDecision::Attach;
1350 }
1351
1352 case NativeGetPropKind::NativeGetter:
1353 case NativeGetPropKind::ScriptedGetter: {
1354 // If a |super| access, it is not worth the complexity to attach an IC.
1355 if (isSuper()) {
1356 return AttachDecision::NoAction;
1357 }
1358
1359 bool needsWindowProxy = GetterNeedsWindowProxyThis(holder, *prop);
1360
1361 // Guard the incoming object is a WindowProxy and inline a getter call
1362 // based on the Window object.
1363 maybeEmitIdGuard(id);
1364 ObjOperandId windowObjId =
1365 GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
1366
1367 if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, windowObj, holder,
1368 *prop, mode_)) {
1369 MOZ_ASSERT(!needsWindowProxy);
1370 EmitCallDOMGetterResult(cx_, writer, windowObj, holder, id, *prop,
1371 windowObjId);
1372 trackAttached("GetProp.WindowProxyDOMGetter");
1373 } else {
1374 ValOperandId receiverId =
1375 writer.boxObject(needsWindowProxy ? objId : windowObjId);
1376 EmitCallGetterResult(cx_, writer, kind, windowObj, holder, id, *prop,
1377 windowObjId, receiverId, mode_);
1378 trackAttached("GetProp.WindowProxyGetter");
1379 }
1380
1381 return AttachDecision::Attach;
1382 }
1383 }
1384
1385 MOZ_CRASH("Unreachable");
1386 }
1387
1388 AttachDecision GetPropIRGenerator::tryAttachCrossCompartmentWrapper(
1389 HandleObject obj, ObjOperandId objId, HandleId id) {
1390 // We can only optimize this very wrapper-handler, because others might
1391 // have a security policy.
1392 if (!IsWrapper(obj) ||
1393 Wrapper::wrapperHandler(obj) != &CrossCompartmentWrapper::singleton) {
1394 return AttachDecision::NoAction;
1395 }
1396
1397 // If we're megamorphic prefer a generic proxy stub that handles a lot more
1398 // cases.
1399 if (mode_ == ICState::Mode::Megamorphic) {
1400 return AttachDecision::NoAction;
1401 }
1402
1403 RootedObject unwrapped(cx_, Wrapper::wrappedObject(obj));
1404 MOZ_ASSERT(unwrapped == UnwrapOneCheckedStatic(obj));
1405 MOZ_ASSERT(!IsCrossCompartmentWrapper(unwrapped),
1406 "CCWs must not wrap other CCWs");
1407
1408 // If we allowed different zones we would have to wrap strings.
1409 if (unwrapped->compartment()->zone() != cx_->compartment()->zone()) {
1410 return AttachDecision::NoAction;
1411 }
1412
1413 // Take the unwrapped object's global, and wrap in a
1414 // this-compartment wrapper. This is what will be stored in the IC
1415 // keep the compartment alive.
1416 RootedObject wrappedTargetGlobal(cx_, &unwrapped->nonCCWGlobal());
1417 if (!cx_->compartment()->wrap(cx_, &wrappedTargetGlobal)) {
1418 cx_->clearPendingException();
1419 return AttachDecision::NoAction;
1420 }
1421
1422 NativeObject* holder = nullptr;
1423 Maybe<PropertyInfo> prop;
1424
1425 // Enter realm of target to prevent failing compartment assertions when doing
1426 // the lookup.
1427 {
1428 AutoRealm ar(cx_, unwrapped);
1429
1430 NativeGetPropKind kind =
1431 CanAttachNativeGetProp(cx_, unwrapped, id, &holder, &prop, pc_);
1432 if (kind != NativeGetPropKind::Slot && kind != NativeGetPropKind::Missing) {
1433 return AttachDecision::NoAction;
1434 }
1435 }
1436 auto* unwrappedNative = &unwrapped->as<NativeObject>();
1437
1438 maybeEmitIdGuard(id);
1439 writer.guardIsProxy(objId);
1440 writer.guardHasProxyHandler(objId, Wrapper::wrapperHandler(obj));
1441
1442 // Load the object wrapped by the CCW
1443 ObjOperandId wrapperTargetId =
1444 writer.loadWrapperTarget(objId, /*fallible = */ false);
1445
1446 // If the compartment of the wrapped object is different we should fail.
1447 writer.guardCompartment(wrapperTargetId, wrappedTargetGlobal,
1448 unwrappedNative->compartment());
1449
1450 ObjOperandId unwrappedId = wrapperTargetId;
1451 if (holder) {
1452 EmitReadSlotResult<IsCrossCompartment::Yes>(writer, unwrappedNative, holder,
1453 *prop, unwrappedId);
1454 writer.wrapResult();
1455 writer.returnFromIC();
1456 trackAttached("GetProp.CCWSlot");
1457 } else {
1458 EmitMissingPropResult<IsCrossCompartment::Yes>(writer, unwrappedNative,
1459 unwrappedId);
1460 writer.returnFromIC();
1461 trackAttached("GetProp.CCWMissing");
1462 }
1463 return AttachDecision::Attach;
1464 }
1465
1466 static JSObject* NewWrapperWithObjectShape(JSContext* cx,
1467 Handle<NativeObject*> obj);
1468
1469 static bool GetXrayExpandoShapeWrapper(JSContext* cx, HandleObject xray,
1470 MutableHandleObject wrapper) {
1471 Value v = GetProxyReservedSlot(xray, GetXrayJitInfo()->xrayHolderSlot);
1472 if (v.isObject()) {
1473 NativeObject* holder = &v.toObject().as<NativeObject>();
1474 v = holder->getFixedSlot(GetXrayJitInfo()->holderExpandoSlot);
1475 if (v.isObject()) {
1476 Rooted<NativeObject*> expando(
1477 cx, &UncheckedUnwrap(&v.toObject())->as<NativeObject>());
1478 wrapper.set(NewWrapperWithObjectShape(cx, expando));
1479 return wrapper != nullptr;
1480 }
1481 }
1482 wrapper.set(nullptr);
1483 return true;
1484 }
1485
1486 AttachDecision GetPropIRGenerator::tryAttachXrayCrossCompartmentWrapper(
1487 HandleObject obj, ObjOperandId objId, HandleId id,
1488 ValOperandId receiverId) {
1489 if (!obj->is<ProxyObject>()) {
1490 return AttachDecision::NoAction;
1491 }
1492
1493 JS::XrayJitInfo* info = GetXrayJitInfo();
1494 if (!info || !info->isCrossCompartmentXray(GetProxyHandler(obj))) {
1495 return AttachDecision::NoAction;
1496 }
1497
1498 if (!info->compartmentHasExclusiveExpandos(obj)) {
1499 return AttachDecision::NoAction;
1500 }
1501
1502 RootedObject target(cx_, UncheckedUnwrap(obj));
1503
1504 RootedObject expandoShapeWrapper(cx_);
1505 if (!GetXrayExpandoShapeWrapper(cx_, obj, &expandoShapeWrapper)) {
1506 cx_->recoverFromOutOfMemory();
1507 return AttachDecision::NoAction;
1508 }
1509
1510 // Look for a getter we can call on the xray or its prototype chain.
1511 Rooted<Maybe<PropertyDescriptor>> desc(cx_);
1512 RootedObject holder(cx_, obj);
1513 RootedObjectVector prototypes(cx_);
1514 RootedObjectVector prototypeExpandoShapeWrappers(cx_);
1515 while (true) {
1516 if (!GetOwnPropertyDescriptor(cx_, holder, id, &desc)) {
1517 cx_->clearPendingException();
1518 return AttachDecision::NoAction;
1519 }
1520 if (desc.isSome()) {
1521 break;
1522 }
1523 if (!GetPrototype(cx_, holder, &holder)) {
1524 cx_->clearPendingException();
1525 return AttachDecision::NoAction;
1526 }
1527 if (!holder || !holder->is<ProxyObject>() ||
1528 !info->isCrossCompartmentXray(GetProxyHandler(holder))) {
1529 return AttachDecision::NoAction;
1530 }
1531 RootedObject prototypeExpandoShapeWrapper(cx_);
1532 if (!GetXrayExpandoShapeWrapper(cx_, holder,
1533 &prototypeExpandoShapeWrapper) ||
1534 !prototypes.append(holder) ||
1535 !prototypeExpandoShapeWrappers.append(prototypeExpandoShapeWrapper)) {
1536 cx_->recoverFromOutOfMemory();
1537 return AttachDecision::NoAction;
1538 }
1539 }
1540 if (!desc->isAccessorDescriptor()) {
1541 return AttachDecision::NoAction;
1542 }
1543
1544 RootedObject getter(cx_, desc->getter());
1545 if (!getter || !getter->is<JSFunction>() ||
1546 !getter->as<JSFunction>().isNativeWithoutJitEntry()) {
1547 return AttachDecision::NoAction;
1548 }
1549
1550 maybeEmitIdGuard(id);
1551 writer.guardIsProxy(objId);
1552 writer.guardHasProxyHandler(objId, GetProxyHandler(obj));
1553
1554 // Load the object wrapped by the CCW
1555 ObjOperandId wrapperTargetId =
1556 writer.loadWrapperTarget(objId, /*fallible = */ false);
1557
1558 // Test the wrapped object's class. The properties held by xrays or their
1559 // prototypes will be invariant for objects of a given class, except for
1560 // changes due to xray expandos or xray prototype mutations.
1561 writer.guardAnyClass(wrapperTargetId, target->getClass());
1562
1563 // Make sure the expandos on the xray and its prototype chain match up with
1564 // what we expect. The expando shape needs to be consistent, to ensure it
1565 // has not had any shadowing properties added, and the expando cannot have
1566 // any custom prototype (xray prototypes are stable otherwise).
1567 //
1568 // We can only do this for xrays with exclusive access to their expandos
1569 // (as we checked earlier), which store a pointer to their expando
1570 // directly. Xrays in other compartments may share their expandos with each
1571 // other and a VM call is needed just to find the expando.
1572 if (expandoShapeWrapper) {
1573 writer.guardXrayExpandoShapeAndDefaultProto(objId, expandoShapeWrapper);
1574 } else {
1575 writer.guardXrayNoExpando(objId);
1576 }
1577 for (size_t i = 0; i < prototypes.length(); i++) {
1578 JSObject* proto = prototypes[i];
1579 ObjOperandId protoId = writer.loadObject(proto);
1580 if (JSObject* protoShapeWrapper = prototypeExpandoShapeWrappers[i]) {
1581 writer.guardXrayExpandoShapeAndDefaultProto(protoId, protoShapeWrapper);
1582 } else {
1583 writer.guardXrayNoExpando(protoId);
1584 }
1585 }
1586
1587 bool sameRealm = cx_->realm() == getter->as<JSFunction>().realm();
1588 writer.callNativeGetterResult(receiverId, &getter->as<JSFunction>(),
1589 sameRealm);
1590 writer.returnFromIC();
1591
1592 trackAttached("GetProp.XrayCCW");
1593 return AttachDecision::Attach;
1594 }
1595
1596 #ifdef JS_PUNBOX64
1597 AttachDecision GetPropIRGenerator::tryAttachScriptedProxy(
1598 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id) {
1599 if (cacheKind_ != CacheKind::GetProp && cacheKind_ != CacheKind::GetElem) {
1600 return AttachDecision::NoAction;
1601 }
1602 if (cacheKind_ == CacheKind::GetElem) {
1603 if (!idVal_.isString() && !idVal_.isInt32() && !idVal_.isSymbol()) {
1604 return AttachDecision::NoAction;
1605 }
1606 }
1607
1608 JSObject* handlerObj = ScriptedProxyHandler::handlerObject(obj);
1609 if (!handlerObj) {
1610 return AttachDecision::NoAction;
1611 }
1612
1613 NativeObject* trapHolder = nullptr;
1614 Maybe<PropertyInfo> trapProp;
1615 // We call with pc_ even though that's not the actual corresponding pc. It
1616 // should, however, be fine, because it's just used to check if this is a
1617 // GetBoundName, which it's not.
1618 NativeGetPropKind trapKind = CanAttachNativeGetProp(
1619 cx_, handlerObj, NameToId(cx_->names().get), &trapHolder, &trapProp, pc_);
1620
1621 if (trapKind != NativeGetPropKind::Missing &&
1622 trapKind != NativeGetPropKind::Slot) {
1623 return AttachDecision::NoAction;
1624 }
1625
1626 if (trapKind != NativeGetPropKind::Missing) {
1627 uint32_t trapSlot = trapProp->slot();
1628 const Value& trapVal = trapHolder->getSlot(trapSlot);
1629 if (!trapVal.isObject()) {
1630 return AttachDecision::NoAction;
1631 }
1632
1633 JSObject* trapObj = &trapVal.toObject();
1634 if (!trapObj->is<JSFunction>()) {
1635 return AttachDecision::NoAction;
1636 }
1637
1638 JSFunction* trapFn = &trapObj->as<JSFunction>();
1639 if (trapFn->isClassConstructor()) {
1640 return AttachDecision::NoAction;
1641 }
1642
1643 if (!trapFn->hasJitEntry()) {
1644 return AttachDecision::NoAction;
1645 }
1646
1647 if (cx_->realm() != trapFn->realm()) {
1648 return AttachDecision::NoAction;
1649 }
1650 }
1651
1652 NativeObject* nHandlerObj = &handlerObj->as<NativeObject>();
1653 JSObject* targetObj = obj->target();
1654 MOZ_ASSERT(targetObj, "Guaranteed by the scripted Proxy constructor");
1655
1656 // We just require that the target is a NativeObject to make our lives
1657 // easier. There's too much nonsense we might have to handle otherwise and
1658 // we're not set up to recursively call GetPropIRGenerator::tryAttachStub
1659 // for the target object.
1660 if (!targetObj->is<NativeObject>()) {
1661 return AttachDecision::NoAction;
1662 }
1663
1664 writer.guardIsProxy(objId);
1665 writer.guardHasProxyHandler(objId, &ScriptedProxyHandler::singleton);
1666 ObjOperandId handlerObjId = writer.loadScriptedProxyHandler(objId);
1667 ObjOperandId targetObjId =
1668 writer.loadWrapperTarget(objId, /*fallible =*/true);
1669
1670 writer.guardIsNativeObject(targetObjId);
1671
1672 if (trapKind == NativeGetPropKind::Missing) {
1673 EmitMissingPropGuard(writer, nHandlerObj, handlerObjId);
1674 if (cacheKind_ == CacheKind::GetProp) {
1675 writer.megamorphicLoadSlotResult(targetObjId, id);
1676 } else {
1677 writer.megamorphicLoadSlotByValueResult(objId, getElemKeyValueId());
1678 }
1679 } else {
1680 uint32_t trapSlot = trapProp->slot();
1681 const Value& trapVal = trapHolder->getSlot(trapSlot);
1682 JSObject* trapObj = &trapVal.toObject();
1683 JSFunction* trapFn = &trapObj->as<JSFunction>();
1684 ObjOperandId trapHolderId =
1685 EmitReadSlotGuard(writer, nHandlerObj, trapHolder, handlerObjId);
1686
1687 ValOperandId fnValId =
1688 EmitLoadSlot(writer, trapHolder, trapHolderId, trapSlot);
1689 ObjOperandId fnObjId = writer.guardToObject(fnValId);
1690 emitCalleeGuard(fnObjId, trapFn);
1691 ValOperandId targetValId = writer.boxObject(targetObjId);
1692 if (cacheKind_ == CacheKind::GetProp) {
1693 writer.callScriptedProxyGetResult(targetValId, objId, handlerObjId,
1694 fnObjId, trapFn, id);
1695 } else {
1696 ValOperandId idId = getElemKeyValueId();
1697 ValOperandId stringIdId = writer.idToStringOrSymbol(idId);
1698 writer.callScriptedProxyGetByValueResult(targetValId, objId, handlerObjId,
1699 stringIdId, fnObjId, trapFn);
1700 }
1701 }
1702 writer.returnFromIC();
1703
1704 trackAttached("GetScriptedProxy");
1705 return AttachDecision::Attach;
1706 }
1707 #endif
1708
1709 AttachDecision GetPropIRGenerator::tryAttachGenericProxy(
1710 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
1711 bool handleDOMProxies) {
1712 writer.guardIsProxy(objId);
1713
1714 if (!handleDOMProxies) {
1715 // Ensure that the incoming object is not a DOM proxy, so that we can get to
1716 // the specialized stubs
1717 writer.guardIsNotDOMProxy(objId);
1718 }
1719
1720 if (cacheKind_ == CacheKind::GetProp || mode_ == ICState::Mode::Specialized) {
1721 MOZ_ASSERT(!isSuper());
1722 maybeEmitIdGuard(id);
1723 writer.proxyGetResult(objId, id);
1724 } else {
1725 // Attach a stub that handles every id.
1726 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem);
1727 MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
1728 MOZ_ASSERT(!isSuper());
1729 writer.proxyGetByValueResult(objId, getElemKeyValueId());
1730 }
1731
1732 writer.returnFromIC();
1733
1734 trackAttached("GetProp.GenericProxy");
1735 return AttachDecision::Attach;
1736 }
1737
1738 static bool ValueIsInt64Index(const Value& val, int64_t* index) {
1739 // Try to convert the Value to a TypedArray index or DataView offset.
1740
1741 if (val.isInt32()) {
1742 *index = val.toInt32();
1743 return true;
1744 }
1745
1746 if (val.isDouble()) {
1747 // Use NumberEqualsInt64 because ToPropertyKey(-0) is 0.
1748 return mozilla::NumberEqualsInt64(val.toDouble(), index);
1749 }
1750
1751 return false;
1752 }
1753
1754 IntPtrOperandId IRGenerator::guardToIntPtrIndex(const Value& index,
1755 ValOperandId indexId,
1756 bool supportOOB) {
1757 #ifdef DEBUG
1758 int64_t indexInt64;
1759 MOZ_ASSERT_IF(!supportOOB, ValueIsInt64Index(index, &indexInt64));
1760 #endif
1761
1762 if (index.isInt32()) {
1763 Int32OperandId int32IndexId = writer.guardToInt32(indexId);
1764 return writer.int32ToIntPtr(int32IndexId);
1765 }
1766
1767 MOZ_ASSERT(index.isNumber());
1768 NumberOperandId numberIndexId = writer.guardIsNumber(indexId);
1769 return writer.guardNumberToIntPtrIndex(numberIndexId, supportOOB);
1770 }
1771
1772 ObjOperandId IRGenerator::guardDOMProxyExpandoObjectAndShape(
1773 ProxyObject* obj, ObjOperandId objId, const Value& expandoVal,
1774 NativeObject* expandoObj) {
1775 MOZ_ASSERT(IsCacheableDOMProxy(obj));
1776
1777 TestMatchingProxyReceiver(writer, obj, objId);
1778
1779 // Shape determines Class, so now it must be a DOM proxy.
1780 ValOperandId expandoValId;
1781 if (expandoVal.isObject()) {
1782 expandoValId = writer.loadDOMExpandoValue(objId);
1783 } else {
1784 expandoValId = writer.loadDOMExpandoValueIgnoreGeneration(objId);
1785 }
1786
1787 // Guard the expando is an object and shape guard.
1788 ObjOperandId expandoObjId = writer.guardToObject(expandoValId);
1789 TestMatchingHolder(writer, expandoObj, expandoObjId);
1790 return expandoObjId;
1791 }
1792
1793 AttachDecision GetPropIRGenerator::tryAttachDOMProxyExpando(
1794 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
1795 ValOperandId receiverId) {
1796 MOZ_ASSERT(IsCacheableDOMProxy(obj));
1797
1798 Value expandoVal = GetProxyPrivate(obj);
1799 JSObject* expandoObj;
1800 if (expandoVal.isObject()) {
1801 expandoObj = &expandoVal.toObject();
1802 } else {
1803 MOZ_ASSERT(!expandoVal.isUndefined(),
1804 "How did a missing expando manage to shadow things?");
1805 auto expandoAndGeneration =
1806 static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
1807 MOZ_ASSERT(expandoAndGeneration);
1808 expandoObj = &expandoAndGeneration->expando.toObject();
1809 }
1810
1811 // Try to do the lookup on the expando object.
1812 NativeObject* holder = nullptr;
1813 Maybe<PropertyInfo> prop;
1814 NativeGetPropKind kind =
1815 CanAttachNativeGetProp(cx_, expandoObj, id, &holder, &prop, pc_);
1816 if (kind == NativeGetPropKind::None) {
1817 return AttachDecision::NoAction;
1818 }
1819 if (!holder) {
1820 return AttachDecision::NoAction;
1821 }
1822 auto* nativeExpandoObj = &expandoObj->as<NativeObject>();
1823
1824 MOZ_ASSERT(holder == nativeExpandoObj);
1825
1826 maybeEmitIdGuard(id);
1827 ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
1828 obj, objId, expandoVal, nativeExpandoObj);
1829
1830 if (kind == NativeGetPropKind::Slot) {
1831 // Load from the expando's slots.
1832 EmitLoadSlotResult(writer, expandoObjId, nativeExpandoObj, *prop);
1833 writer.returnFromIC();
1834 } else {
1835 // Call the getter. Note that we pass objId, the DOM proxy, as |this|
1836 // and not the expando object.
1837 MOZ_ASSERT(kind == NativeGetPropKind::NativeGetter ||
1838 kind == NativeGetPropKind::ScriptedGetter);
1839 EmitGuardGetterSetterSlot(writer, nativeExpandoObj, *prop, expandoObjId);
1840 EmitCallGetterResultNoGuards(cx_, writer, kind, nativeExpandoObj,
1841 nativeExpandoObj, *prop, receiverId);
1842 }
1843
1844 trackAttached("GetProp.DOMProxyExpando");
1845 return AttachDecision::Attach;
1846 }
1847
1848 AttachDecision GetPropIRGenerator::tryAttachDOMProxyShadowed(
1849 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id) {
1850 MOZ_ASSERT(!isSuper());
1851 MOZ_ASSERT(IsCacheableDOMProxy(obj));
1852
1853 maybeEmitIdGuard(id);
1854 TestMatchingProxyReceiver(writer, obj, objId);
1855 writer.proxyGetResult(objId, id);
1856 writer.returnFromIC();
1857
1858 trackAttached("GetProp.DOMProxyShadowed");
1859 return AttachDecision::Attach;
1860 }
1861
1862 // Emit CacheIR to guard the DOM proxy doesn't shadow |id|. There are two types
1863 // of DOM proxies:
1864 //
1865 // (a) DOM proxies marked LegacyOverrideBuiltIns in WebIDL, for example
1866 // HTMLDocument or HTMLFormElement. These proxies look up properties in this
1867 // order:
1868 //
1869 // (1) The expando object.
1870 // (2) The proxy's named-property handler.
1871 // (3) The prototype chain.
1872 //
1873 // To optimize properties on the prototype chain, we have to guard that (1)
1874 // and (2) don't shadow (3). We handle (1) by either emitting a shape guard
1875 // for the expando object or by guarding the proxy has no expando object. To
1876 // efficiently handle (2), the proxy must have an ExpandoAndGeneration*
1877 // stored as PrivateValue. We guard on its generation field to ensure the
1878 // set of names hasn't changed.
1879 //
1880 // Missing properties can be optimized in a similar way by emitting shape
1881 // guards for the prototype chain.
1882 //
1883 // (b) Other DOM proxies. These proxies look up properties in this
1884 // order:
1885 //
1886 // (1) The expando object.
1887 // (2) The prototype chain.
1888 // (3) The proxy's named-property handler.
1889 //
1890 // To optimize properties on the prototype chain, we only have to guard the
1891 // expando object doesn't shadow it.
1892 //
1893 // Missing properties can't be optimized in this case because we don't have
1894 // an efficient way to guard against the proxy handler shadowing the
1895 // property (there's no ExpandoAndGeneration*).
1896 //
1897 // See also:
1898 // * DOMProxyShadows in DOMJSProxyHandler.cpp
1899 // * https://webidl.spec.whatwg.org/#dfn-named-property-visibility (the Note at
1900 // the end)
1901 //
1902 // Callers are expected to have already guarded on the shape of the
1903 // object, which guarantees the object is a DOM proxy.
1904 static void CheckDOMProxyDoesNotShadow(CacheIRWriter& writer, ProxyObject* obj,
1905 jsid id, ObjOperandId objId,
1906 bool* canOptimizeMissing) {
1907 MOZ_ASSERT(IsCacheableDOMProxy(obj));
1908
1909 Value expandoVal = GetProxyPrivate(obj);
1910
1911 ValOperandId expandoId;
1912 if (!expandoVal.isObject() && !expandoVal.isUndefined()) {
1913 // Case (a).
1914 auto expandoAndGeneration =
1915 static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
1916 uint64_t generation = expandoAndGeneration->generation;
1917 expandoId = writer.loadDOMExpandoValueGuardGeneration(
1918 objId, expandoAndGeneration, generation);
1919 expandoVal = expandoAndGeneration->expando;
1920 *canOptimizeMissing = true;
1921 } else {
1922 // Case (b).
1923 expandoId = writer.loadDOMExpandoValue(objId);
1924 *canOptimizeMissing = false;
1925 }
1926
1927 if (expandoVal.isUndefined()) {
1928 // Guard there's no expando object.
1929 writer.guardNonDoubleType(expandoId, ValueType::Undefined);
1930 } else if (expandoVal.isObject()) {
1931 // Guard the proxy either has no expando object or, if it has one, that
1932 // the shape matches the current expando object.
1933 NativeObject& expandoObj = expandoVal.toObject().as<NativeObject>();
1934 MOZ_ASSERT(!expandoObj.containsPure(id));
1935 writer.guardDOMExpandoMissingOrGuardShape(expandoId, expandoObj.shape());
1936 } else {
1937 MOZ_CRASH("Invalid expando value");
1938 }
1939 }
1940
1941 AttachDecision GetPropIRGenerator::tryAttachDOMProxyUnshadowed(
1942 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
1943 ValOperandId receiverId) {
1944 MOZ_ASSERT(IsCacheableDOMProxy(obj));
1945
1946 JSObject* protoObj = obj->staticPrototype();
1947 if (!protoObj) {
1948 return AttachDecision::NoAction;
1949 }
1950
1951 NativeObject* holder = nullptr;
1952 Maybe<PropertyInfo> prop;
1953 NativeGetPropKind kind =
1954 CanAttachNativeGetProp(cx_, protoObj, id, &holder, &prop, pc_);
1955 if (kind == NativeGetPropKind::None) {
1956 return AttachDecision::NoAction;
1957 }
1958 auto* nativeProtoObj = &protoObj->as<NativeObject>();
1959
1960 maybeEmitIdGuard(id);
1961
1962 // Guard that our proxy (expando) object hasn't started shadowing this
1963 // property.
1964 TestMatchingProxyReceiver(writer, obj, objId);
1965 bool canOptimizeMissing = false;
1966 CheckDOMProxyDoesNotShadow(writer, obj, id, objId, &canOptimizeMissing);
1967
1968 if (holder) {
1969 // Found the property on the prototype chain. Treat it like a native
1970 // getprop.
1971 GeneratePrototypeGuards(writer, obj, holder, objId);
1972
1973 // Guard on the holder of the property.
1974 ObjOperandId holderId = writer.loadObject(holder);
1975 TestMatchingHolder(writer, holder, holderId);
1976
1977 if (kind == NativeGetPropKind::Slot) {
1978 EmitLoadSlotResult(writer, holderId, holder, *prop);
1979 writer.returnFromIC();
1980 } else {
1981 // EmitCallGetterResultNoGuards expects |obj| to be the object the
1982 // property is on to do some checks. Since we actually looked at
1983 // checkObj, and no extra guards will be generated, we can just
1984 // pass that instead.
1985 MOZ_ASSERT(kind == NativeGetPropKind::NativeGetter ||
1986 kind == NativeGetPropKind::ScriptedGetter);
1987 MOZ_ASSERT(!isSuper());
1988 EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
1989 /* holderIsConstant = */ true);
1990 EmitCallGetterResultNoGuards(cx_, writer, kind, nativeProtoObj, holder,
1991 *prop, receiverId);
1992 }
1993 } else {
1994 // Property was not found on the prototype chain.
1995 MOZ_ASSERT(kind == NativeGetPropKind::Missing);
1996 if (canOptimizeMissing) {
1997 // We already guarded on the proxy's shape, so now shape guard the proto
1998 // chain.
1999 ObjOperandId protoId = writer.loadObject(nativeProtoObj);
2000 EmitMissingPropResult(writer, nativeProtoObj, protoId);
2001 } else {
2002 MOZ_ASSERT(!isSuper());
2003 writer.proxyGetResult(objId, id);
2004 }
2005 writer.returnFromIC();
2006 }
2007
2008 trackAttached("GetProp.DOMProxyUnshadowed");
2009 return AttachDecision::Attach;
2010 }
2011
2012 AttachDecision GetPropIRGenerator::tryAttachProxy(HandleObject obj,
2013 ObjOperandId objId,
2014 HandleId id,
2015 ValOperandId receiverId) {
2016 // The proxy stubs don't currently support |super| access.
2017 if (isSuper()) {
2018 return AttachDecision::NoAction;
2019 }
2020
2021 // Always try to attach scripted proxy get even if we're megamorphic.
2022 // In Speedometer 3 we'll often run into cases where we're megamorphic
2023 // overall, but monomorphic for the proxy case. This is because there
2024 // are functions which lazily turn various differently-shaped objects
2025 // into proxies. So the un-proxified objects are megamorphic, but the
2026 // proxy handlers are actually monomorphic. There is room for a bit
2027 // more sophistication here, but this should do for now.
2028 if (!obj->is<ProxyObject>()) {
2029 return AttachDecision::NoAction;
2030 }
2031 auto proxy = obj.as<ProxyObject>();
2032 #ifdef JS_PUNBOX64
2033 if (proxy->handler()->isScripted()) {
2034 TRY_ATTACH(tryAttachScriptedProxy(proxy, objId, id));
2035 }
2036 #endif
2037
2038 ProxyStubType type = GetProxyStubType(cx_, obj, id);
2039 if (type == ProxyStubType::None) {
2040 return AttachDecision::NoAction;
2041 }
2042
2043 if (mode_ == ICState::Mode::Megamorphic) {
2044 return tryAttachGenericProxy(proxy, objId, id,
2045 /* handleDOMProxies = */ true);
2046 }
2047
2048 switch (type) {
2049 case ProxyStubType::None:
2050 break;
2051 case ProxyStubType::DOMExpando:
2052 TRY_ATTACH(tryAttachDOMProxyExpando(proxy, objId, id, receiverId));
2053 [[fallthrough]]; // Fall through to the generic shadowed case.
2054 case ProxyStubType::DOMShadowed:
2055 return tryAttachDOMProxyShadowed(proxy, objId, id);
2056 case ProxyStubType::DOMUnshadowed:
2057 TRY_ATTACH(tryAttachDOMProxyUnshadowed(proxy, objId, id, receiverId));
2058 return tryAttachGenericProxy(proxy, objId, id,
2059 /* handleDOMProxies = */ true);
2060 case ProxyStubType::Generic:
2061 return tryAttachGenericProxy(proxy, objId, id,
2062 /* handleDOMProxies = */ false);
2063 }
2064
2065 MOZ_CRASH("Unexpected ProxyStubType");
2066 }
2067
2068 const JSClass* js::jit::ClassFor(GuardClassKind kind) {
2069 switch (kind) {
2070 case GuardClassKind::Array:
2071 return &ArrayObject::class_;
2072 case GuardClassKind::PlainObject:
2073 return &PlainObject::class_;
2074 case GuardClassKind::FixedLengthArrayBuffer:
2075 return &FixedLengthArrayBufferObject::class_;
2076 case GuardClassKind::ResizableArrayBuffer:
2077 return &ResizableArrayBufferObject::class_;
2078 case GuardClassKind::FixedLengthSharedArrayBuffer:
2079 return &FixedLengthSharedArrayBufferObject::class_;
2080 case GuardClassKind::GrowableSharedArrayBuffer:
2081 return &GrowableSharedArrayBufferObject::class_;
2082 case GuardClassKind::FixedLengthDataView:
2083 return &FixedLengthDataViewObject::class_;
2084 case GuardClassKind::ResizableDataView:
2085 return &ResizableDataViewObject::class_;
2086 case GuardClassKind::MappedArguments:
2087 return &MappedArgumentsObject::class_;
2088 case GuardClassKind::UnmappedArguments:
2089 return &UnmappedArgumentsObject::class_;
2090 case GuardClassKind::WindowProxy:
2091 // Caller needs to handle this case, see
2092 // JSRuntime::maybeWindowProxyClass().
2093 break;
2094 case GuardClassKind::JSFunction:
2095 // Caller needs to handle this case. Can be either |js::FunctionClass| or
2096 // |js::ExtendedFunctionClass|.
2097 break;
2098 case GuardClassKind::BoundFunction:
2099 return &BoundFunctionObject::class_;
2100 case GuardClassKind::Set:
2101 return &SetObject::class_;
2102 case GuardClassKind::Map:
2103 return &MapObject::class_;
2104 case GuardClassKind::Date:
2105 return &DateObject::class_;
2106 }
2107 MOZ_CRASH("unexpected kind");
2108 }
2109
2110 // Guards the class of an object. Because shape implies class, and a shape guard
2111 // is faster than a class guard, if this is our first time attaching a stub, we
2112 // instead generate a shape guard.
2113 void IRGenerator::emitOptimisticClassGuard(ObjOperandId objId, JSObject* obj,
2114 GuardClassKind kind) {
2115 #ifdef DEBUG
2116 switch (kind) {
2117 case GuardClassKind::Array:
2118 case GuardClassKind::PlainObject:
2119 case GuardClassKind::FixedLengthArrayBuffer:
2120 case GuardClassKind::ResizableArrayBuffer:
2121 case GuardClassKind::FixedLengthSharedArrayBuffer:
2122 case GuardClassKind::GrowableSharedArrayBuffer:
2123 case GuardClassKind::FixedLengthDataView:
2124 case GuardClassKind::ResizableDataView:
2125 case GuardClassKind::Set:
2126 case GuardClassKind::Map:
2127 case GuardClassKind::Date:
2128 MOZ_ASSERT(obj->hasClass(ClassFor(kind)));
2129 break;
2130
2131 case GuardClassKind::MappedArguments:
2132 case GuardClassKind::UnmappedArguments:
2133 case GuardClassKind::JSFunction:
2134 case GuardClassKind::BoundFunction:
2135 case GuardClassKind::WindowProxy:
2136 // Arguments, functions, and the global object have
2137 // less consistent shapes.
2138 MOZ_CRASH("GuardClassKind not supported");
2139 }
2140 #endif
2141
2142 if (isFirstStub_) {
2143 writer.guardShapeForClass(objId, obj->shape());
2144 } else {
2145 writer.guardClass(objId, kind);
2146 }
2147 }
2148
2149 static void AssertArgumentsCustomDataProp(ArgumentsObject* obj,
2150 PropertyKey key) {
2151 #ifdef DEBUG
2152 // The property must still be a custom data property if it has been resolved.
2153 // If this assertion fails, we're probably missing a call to mark this
2154 // property overridden.
2155 Maybe<PropertyInfo> prop = obj->lookupPure(key);
2156 MOZ_ASSERT_IF(prop, prop->isCustomDataProperty());
2157 #endif
2158 }
2159
2160 AttachDecision GetPropIRGenerator::tryAttachObjectLength(HandleObject obj,
2161 ObjOperandId objId,
2162 HandleId id) {
2163 if (!id.isAtom(cx_->names().length)) {
2164 return AttachDecision::NoAction;
2165 }
2166
2167 if (obj->is<ArrayObject>()) {
2168 if (obj->as<ArrayObject>().length() > INT32_MAX) {
2169 return AttachDecision::NoAction;
2170 }
2171
2172 maybeEmitIdGuard(id);
2173 emitOptimisticClassGuard(objId, obj, GuardClassKind::Array);
2174 writer.loadInt32ArrayLengthResult(objId);
2175 writer.returnFromIC();
2176
2177 trackAttached("GetProp.ArrayLength");
2178 return AttachDecision::Attach;
2179 }
2180
2181 if (obj->is<ArgumentsObject>() &&
2182 !obj->as<ArgumentsObject>().hasOverriddenLength()) {
2183 AssertArgumentsCustomDataProp(&obj->as<ArgumentsObject>(), id);
2184 maybeEmitIdGuard(id);
2185 if (obj->is<MappedArgumentsObject>()) {
2186 writer.guardClass(objId, GuardClassKind::MappedArguments);
2187 } else {
2188 MOZ_ASSERT(obj->is<UnmappedArgumentsObject>());
2189 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
2190 }
2191 writer.loadArgumentsObjectLengthResult(objId);
2192 writer.returnFromIC();
2193
2194 trackAttached("GetProp.ArgumentsObjectLength");
2195 return AttachDecision::Attach;
2196 }
2197
2198 return AttachDecision::NoAction;
2199 }
2200
2201 AttachDecision GetPropIRGenerator::tryAttachTypedArray(HandleObject obj,
2202 ObjOperandId objId,
2203 HandleId id) {
2204 if (!obj->is<TypedArrayObject>()) {
2205 return AttachDecision::NoAction;
2206 }
2207
2208 if (mode_ != ICState::Mode::Specialized) {
2209 return AttachDecision::NoAction;
2210 }
2211
2212 // Receiver should be the object.
2213 if (isSuper()) {
2214 return AttachDecision::NoAction;
2215 }
2216
2217 bool isLength = id.isAtom(cx_->names().length);
2218 bool isByteOffset = id.isAtom(cx_->names().byteOffset);
2219 if (!isLength && !isByteOffset && !id.isAtom(cx_->names().byteLength)) {
2220 return AttachDecision::NoAction;
2221 }
2222
2223 NativeObject* holder = nullptr;
2224 Maybe<PropertyInfo> prop;
2225 NativeGetPropKind kind =
2226 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2227 if (kind != NativeGetPropKind::NativeGetter) {
2228 return AttachDecision::NoAction;
2229 }
2230
2231 JSFunction& fun = holder->getGetter(*prop)->as<JSFunction>();
2232 if (isLength) {
2233 if (!TypedArrayObject::isOriginalLengthGetter(fun.native())) {
2234 return AttachDecision::NoAction;
2235 }
2236 } else if (isByteOffset) {
2237 if (!TypedArrayObject::isOriginalByteOffsetGetter(fun.native())) {
2238 return AttachDecision::NoAction;
2239 }
2240 } else {
2241 if (!TypedArrayObject::isOriginalByteLengthGetter(fun.native())) {
2242 return AttachDecision::NoAction;
2243 }
2244 }
2245
2246 auto* tarr = &obj->as<TypedArrayObject>();
2247
2248 maybeEmitIdGuard(id);
2249 // Emit all the normal guards for calling this native, but specialize
2250 // callNativeGetterResult.
2251 EmitCallGetterResultGuards(writer, tarr, holder, id, *prop, objId, mode_);
2252 if (isLength) {
2253 size_t length = tarr->length().valueOr(0);
2254 if (tarr->is<FixedLengthTypedArrayObject>()) {
2255 if (length <= INT32_MAX) {
2256 writer.loadArrayBufferViewLengthInt32Result(objId);
2257 } else {
2258 writer.loadArrayBufferViewLengthDoubleResult(objId);
2259 }
2260 } else {
2261 if (length <= INT32_MAX) {
2262 writer.resizableTypedArrayLengthInt32Result(objId);
2263 } else {
2264 writer.resizableTypedArrayLengthDoubleResult(objId);
2265 }
2266 }
2267 trackAttached("GetProp.TypedArrayLength");
2268 } else if (isByteOffset) {
2269 // byteOffset doesn't need to use different code paths for fixed-length and
2270 // resizable TypedArrays.
2271 size_t byteOffset = tarr->byteOffset().valueOr(0);
2272 if (byteOffset <= INT32_MAX) {
2273 writer.arrayBufferViewByteOffsetInt32Result(objId);
2274 } else {
2275 writer.arrayBufferViewByteOffsetDoubleResult(objId);
2276 }
2277 trackAttached("GetProp.TypedArrayByteOffset");
2278 } else {
2279 size_t byteLength = tarr->byteLength().valueOr(0);
2280 if (tarr->is<FixedLengthTypedArrayObject>()) {
2281 if (byteLength <= INT32_MAX) {
2282 writer.typedArrayByteLengthInt32Result(objId);
2283 } else {
2284 writer.typedArrayByteLengthDoubleResult(objId);
2285 }
2286 } else {
2287 if (byteLength <= INT32_MAX) {
2288 writer.resizableTypedArrayByteLengthInt32Result(objId);
2289 } else {
2290 writer.resizableTypedArrayByteLengthDoubleResult(objId);
2291 }
2292 }
2293 trackAttached("GetProp.TypedArrayByteLength");
2294 }
2295 writer.returnFromIC();
2296
2297 return AttachDecision::Attach;
2298 }
2299
2300 AttachDecision GetPropIRGenerator::tryAttachDataView(HandleObject obj,
2301 ObjOperandId objId,
2302 HandleId id) {
2303 if (!obj->is<DataViewObject>()) {
2304 return AttachDecision::NoAction;
2305 }
2306 auto* dv = &obj->as<DataViewObject>();
2307
2308 if (mode_ != ICState::Mode::Specialized) {
2309 return AttachDecision::NoAction;
2310 }
2311
2312 // Receiver should be the object.
2313 if (isSuper()) {
2314 return AttachDecision::NoAction;
2315 }
2316
2317 bool isByteOffset = id.isAtom(cx_->names().byteOffset);
2318 if (!isByteOffset && !id.isAtom(cx_->names().byteLength)) {
2319 return AttachDecision::NoAction;
2320 }
2321
2322 // byteOffset and byteLength both throw when the ArrayBuffer is detached.
2323 if (dv->hasDetachedBuffer()) {
2324 return AttachDecision::NoAction;
2325 }
2326
2327 // byteOffset and byteLength both throw when the ArrayBuffer is out-of-bounds.
2328 if (dv->is<ResizableDataViewObject>() &&
2329 dv->as<ResizableDataViewObject>().isOutOfBounds()) {
2330 return AttachDecision::NoAction;
2331 }
2332
2333 NativeObject* holder = nullptr;
2334 Maybe<PropertyInfo> prop;
2335 NativeGetPropKind kind =
2336 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2337 if (kind != NativeGetPropKind::NativeGetter) {
2338 return AttachDecision::NoAction;
2339 }
2340
2341 auto& fun = holder->getGetter(*prop)->as<JSFunction>();
2342 if (isByteOffset) {
2343 if (!DataViewObject::isOriginalByteOffsetGetter(fun.native())) {
2344 return AttachDecision::NoAction;
2345 }
2346 } else {
2347 if (!DataViewObject::isOriginalByteLengthGetter(fun.native())) {
2348 return AttachDecision::NoAction;
2349 }
2350 }
2351
2352 maybeEmitIdGuard(id);
2353 // Emit all the normal guards for calling this native, but specialize
2354 // callNativeGetterResult.
2355 EmitCallGetterResultGuards(writer, dv, holder, id, *prop, objId, mode_);
2356 writer.guardHasAttachedArrayBuffer(objId);
2357 if (dv->is<ResizableDataViewObject>()) {
2358 writer.guardResizableArrayBufferViewInBounds(objId);
2359 }
2360 if (isByteOffset) {
2361 // byteOffset doesn't need to use different code paths for fixed-length and
2362 // resizable DataViews.
2363 size_t byteOffset = dv->byteOffset().valueOr(0);
2364 if (byteOffset <= INT32_MAX) {
2365 writer.arrayBufferViewByteOffsetInt32Result(objId);
2366 } else {
2367 writer.arrayBufferViewByteOffsetDoubleResult(objId);
2368 }
2369 trackAttached("GetProp.DataViewByteOffset");
2370 } else {
2371 size_t byteLength = dv->byteLength().valueOr(0);
2372 if (dv->is<FixedLengthDataViewObject>()) {
2373 if (byteLength <= INT32_MAX) {
2374 writer.loadArrayBufferViewLengthInt32Result(objId);
2375 } else {
2376 writer.loadArrayBufferViewLengthDoubleResult(objId);
2377 }
2378 } else {
2379 if (byteLength <= INT32_MAX) {
2380 writer.resizableDataViewByteLengthInt32Result(objId);
2381 } else {
2382 writer.resizableDataViewByteLengthDoubleResult(objId);
2383 }
2384 }
2385 trackAttached("GetProp.DataViewByteLength");
2386 }
2387 writer.returnFromIC();
2388
2389 return AttachDecision::Attach;
2390 }
2391
2392 AttachDecision GetPropIRGenerator::tryAttachArrayBufferMaybeShared(
2393 HandleObject obj, ObjOperandId objId, HandleId id) {
2394 if (!obj->is<ArrayBufferObjectMaybeShared>()) {
2395 return AttachDecision::NoAction;
2396 }
2397 auto* buf = &obj->as<ArrayBufferObjectMaybeShared>();
2398
2399 if (mode_ != ICState::Mode::Specialized) {
2400 return AttachDecision::NoAction;
2401 }
2402
2403 // Receiver should be the object.
2404 if (isSuper()) {
2405 return AttachDecision::NoAction;
2406 }
2407
2408 if (!id.isAtom(cx_->names().byteLength)) {
2409 return AttachDecision::NoAction;
2410 }
2411
2412 NativeObject* holder = nullptr;
2413 Maybe<PropertyInfo> prop;
2414 NativeGetPropKind kind =
2415 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2416 if (kind != NativeGetPropKind::NativeGetter) {
2417 return AttachDecision::NoAction;
2418 }
2419
2420 auto& fun = holder->getGetter(*prop)->as<JSFunction>();
2421 if (buf->is<ArrayBufferObject>()) {
2422 if (!ArrayBufferObject::isOriginalByteLengthGetter(fun.native())) {
2423 return AttachDecision::NoAction;
2424 }
2425 } else {
2426 if (!SharedArrayBufferObject::isOriginalByteLengthGetter(fun.native())) {
2427 return AttachDecision::NoAction;
2428 }
2429 }
2430
2431 maybeEmitIdGuard(id);
2432 // Emit all the normal guards for calling this native, but specialize
2433 // callNativeGetterResult.
2434 EmitCallGetterResultGuards(writer, buf, holder, id, *prop, objId, mode_);
2435 if (!buf->is<GrowableSharedArrayBufferObject>()) {
2436 if (buf->byteLength() <= INT32_MAX) {
2437 writer.loadArrayBufferByteLengthInt32Result(objId);
2438 } else {
2439 writer.loadArrayBufferByteLengthDoubleResult(objId);
2440 }
2441 } else {
2442 if (buf->byteLength() <= INT32_MAX) {
2443 writer.growableSharedArrayBufferByteLengthInt32Result(objId);
2444 } else {
2445 writer.growableSharedArrayBufferByteLengthDoubleResult(objId);
2446 }
2447 }
2448 writer.returnFromIC();
2449
2450 trackAttached("GetProp.ArrayBufferMaybeSharedByteLength");
2451 return AttachDecision::Attach;
2452 }
2453
2454 AttachDecision GetPropIRGenerator::tryAttachRegExp(HandleObject obj,
2455 ObjOperandId objId,
2456 HandleId id) {
2457 if (!obj->is<RegExpObject>()) {
2458 return AttachDecision::NoAction;
2459 }
2460 auto* regExp = &obj->as<RegExpObject>();
2461
2462 if (mode_ != ICState::Mode::Specialized) {
2463 return AttachDecision::NoAction;
2464 }
2465
2466 // Receiver should be the object.
2467 if (isSuper()) {
2468 return AttachDecision::NoAction;
2469 }
2470
2471 NativeObject* holder = nullptr;
2472 Maybe<PropertyInfo> prop;
2473 NativeGetPropKind kind =
2474 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2475 if (kind != NativeGetPropKind::NativeGetter) {
2476 return AttachDecision::NoAction;
2477 }
2478
2479 auto& fun = holder->getGetter(*prop)->as<JSFunction>();
2480 JS::RegExpFlags flags = JS::RegExpFlag::NoFlags;
2481 if (!RegExpObject::isOriginalFlagGetter(fun.native(), &flags)) {
2482 return AttachDecision::NoAction;
2483 }
2484
2485 maybeEmitIdGuard(id);
2486 // Emit all the normal guards for calling this native, but specialize
2487 // callNativeGetterResult.
2488 EmitCallGetterResultGuards(writer, regExp, holder, id, *prop, objId, mode_);
2489
2490 writer.regExpFlagResult(objId, flags.value());
2491 writer.returnFromIC();
2492
2493 trackAttached("GetProp.RegExpFlag");
2494 return AttachDecision::Attach;
2495 }
2496
2497 AttachDecision GetPropIRGenerator::tryAttachMap(HandleObject obj,
2498 ObjOperandId objId,
2499 HandleId id) {
2500 if (!obj->is<MapObject>()) {
2501 return AttachDecision::NoAction;
2502 }
2503 auto* mapObj = &obj->as<MapObject>();
2504
2505 if (mode_ != ICState::Mode::Specialized) {
2506 return AttachDecision::NoAction;
2507 }
2508
2509 // Receiver should be the object.
2510 if (isSuper()) {
2511 return AttachDecision::NoAction;
2512 }
2513
2514 if (!id.isAtom(cx_->names().size)) {
2515 return AttachDecision::NoAction;
2516 }
2517
2518 NativeObject* holder = nullptr;
2519 Maybe<PropertyInfo> prop;
2520 NativeGetPropKind kind =
2521 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2522 if (kind != NativeGetPropKind::NativeGetter) {
2523 return AttachDecision::NoAction;
2524 }
2525
2526 auto& fun = holder->getGetter(*prop)->as<JSFunction>();
2527 if (!MapObject::isOriginalSizeGetter(fun.native())) {
2528 return AttachDecision::NoAction;
2529 }
2530
2531 maybeEmitIdGuard(id);
2532
2533 // Emit all the normal guards for calling this native, but specialize
2534 // callNativeGetterResult.
2535 EmitCallGetterResultGuards(writer, mapObj, holder, id, *prop, objId, mode_);
2536
2537 writer.mapSizeResult(objId);
2538 writer.returnFromIC();
2539
2540 trackAttached("GetProp.MapSize");
2541 return AttachDecision::Attach;
2542 }
2543
2544 AttachDecision GetPropIRGenerator::tryAttachSet(HandleObject obj,
2545 ObjOperandId objId,
2546 HandleId id) {
2547 if (!obj->is<SetObject>()) {
2548 return AttachDecision::NoAction;
2549 }
2550 auto* setObj = &obj->as<SetObject>();
2551
2552 if (mode_ != ICState::Mode::Specialized) {
2553 return AttachDecision::NoAction;
2554 }
2555
2556 // Receiver should be the object.
2557 if (isSuper()) {
2558 return AttachDecision::NoAction;
2559 }
2560
2561 if (!id.isAtom(cx_->names().size)) {
2562 return AttachDecision::NoAction;
2563 }
2564
2565 NativeObject* holder = nullptr;
2566 Maybe<PropertyInfo> prop;
2567 NativeGetPropKind kind =
2568 CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
2569 if (kind != NativeGetPropKind::NativeGetter) {
2570 return AttachDecision::NoAction;
2571 }
2572
2573 auto& fun = holder->getGetter(*prop)->as<JSFunction>();
2574 if (!SetObject::isOriginalSizeGetter(fun.native())) {
2575 return AttachDecision::NoAction;
2576 }
2577
2578 maybeEmitIdGuard(id);
2579
2580 // Emit all the normal guards for calling this native, but specialize
2581 // callNativeGetterResult.
2582 EmitCallGetterResultGuards(writer, setObj, holder, id, *prop, objId, mode_);
2583
2584 writer.setSizeResult(objId);
2585 writer.returnFromIC();
2586
2587 trackAttached("GetProp.SetSize");
2588 return AttachDecision::Attach;
2589 }
2590
2591 AttachDecision GetPropIRGenerator::tryAttachFunction(HandleObject obj,
2592 ObjOperandId objId,
2593 HandleId id) {
2594 // Function properties are lazily resolved so they might not be defined yet.
2595 // And we might end up in a situation where we always have a fresh function
2596 // object during the IC generation.
2597 if (!obj->is<JSFunction>()) {
2598 return AttachDecision::NoAction;
2599 }
2600
2601 bool isLength = id.isAtom(cx_->names().length);
2602 if (!isLength && !id.isAtom(cx_->names().name)) {
2603 return AttachDecision::NoAction;
2604 }
2605
2606 NativeObject* holder = nullptr;
2607 PropertyResult prop;
2608 // If this property exists already, don't attach the stub.
2609 if (LookupPropertyPure(cx_, obj, id, &holder, &prop)) {
2610 return AttachDecision::NoAction;
2611 }
2612
2613 JSFunction* fun = &obj->as<JSFunction>();
2614
2615 if (isLength) {
2616 // length was probably deleted from the function.
2617 if (fun->hasResolvedLength()) {
2618 return AttachDecision::NoAction;
2619 }
2620
2621 // Lazy functions don't store the length.
2622 if (!fun->hasBytecode()) {
2623 return AttachDecision::NoAction;
2624 }
2625 } else {
2626 // name was probably deleted from the function.
2627 if (fun->hasResolvedName()) {
2628 return AttachDecision::NoAction;
2629 }
2630 }
2631
2632 maybeEmitIdGuard(id);
2633 writer.guardClass(objId, GuardClassKind::JSFunction);
2634 if (isLength) {
2635 writer.loadFunctionLengthResult(objId);
2636 writer.returnFromIC();
2637 trackAttached("GetProp.FunctionLength");
2638 } else {
2639 writer.loadFunctionNameResult(objId);
2640 writer.returnFromIC();
2641 trackAttached("GetProp.FunctionName");
2642 }
2643 return AttachDecision::Attach;
2644 }
2645
2646 AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectIterator(
2647 HandleObject obj, ObjOperandId objId, HandleId id) {
2648 if (!obj->is<ArgumentsObject>()) {
2649 return AttachDecision::NoAction;
2650 }
2651
2652 if (!id.isWellKnownSymbol(JS::SymbolCode::iterator)) {
2653 return AttachDecision::NoAction;
2654 }
2655
2656 Handle<ArgumentsObject*> args = obj.as<ArgumentsObject>();
2657 if (args->hasOverriddenIterator()) {
2658 return AttachDecision::NoAction;
2659 }
2660 if (cx_->realm() != args->realm()) {
2661 return AttachDecision::NoAction;
2662 }
2663
2664 AssertArgumentsCustomDataProp(args, id);
2665
2666 RootedValue iterator(cx_);
2667 if (!ArgumentsObject::getArgumentsIterator(cx_, &iterator)) {
2668 cx_->recoverFromOutOfMemory();
2669 return AttachDecision::NoAction;
2670 }
2671 MOZ_ASSERT(iterator.isObject());
2672
2673 maybeEmitIdGuard(id);
2674 if (args->is<MappedArgumentsObject>()) {
2675 writer.guardClass(objId, GuardClassKind::MappedArguments);
2676 } else {
2677 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
2678 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
2679 }
2680 uint32_t flags = ArgumentsObject::ITERATOR_OVERRIDDEN_BIT;
2681 writer.guardArgumentsObjectFlags(objId, flags);
2682 writer.guardObjectHasSameRealm(objId);
2683
2684 ObjOperandId iterId = writer.loadObject(&iterator.toObject());
2685 writer.loadObjectResult(iterId);
2686 writer.returnFromIC();
2687
2688 trackAttached("GetProp.ArgumentsObjectIterator");
2689 return AttachDecision::Attach;
2690 }
2691
2692 AttachDecision GetPropIRGenerator::tryAttachModuleNamespace(HandleObject obj,
2693 ObjOperandId objId,
2694 HandleId id) {
2695 if (!obj->is<ModuleNamespaceObject>()) {
2696 return AttachDecision::NoAction;
2697 }
2698
2699 auto* ns = &obj->as<ModuleNamespaceObject>();
2700 ModuleEnvironmentObject* env = nullptr;
2701 Maybe<PropertyInfo> prop;
2702 if (!ns->bindings().lookup(id, &env, &prop)) {
2703 return AttachDecision::NoAction;
2704 }
2705
2706 // Don't emit a stub until the target binding has been initialized.
2707 if (env->getSlot(prop->slot()).isMagic(JS_UNINITIALIZED_LEXICAL)) {
2708 return AttachDecision::NoAction;
2709 }
2710
2711 // Check for the specific namespace object.
2712 maybeEmitIdGuard(id);
2713 writer.guardSpecificObject(objId, ns);
2714
2715 ObjOperandId envId = writer.loadObject(env);
2716 EmitLoadSlotResult(writer, envId, env, *prop);
2717 writer.returnFromIC();
2718
2719 trackAttached("GetProp.ModuleNamespace");
2720 return AttachDecision::Attach;
2721 }
2722
2723 AttachDecision GetPropIRGenerator::tryAttachPrimitive(ValOperandId valId,
2724 HandleId id) {
2725 MOZ_ASSERT(!isSuper(), "SuperBase is guaranteed to be an object");
2726
2727 JSProtoKey protoKey;
2728 switch (val_.type()) {
2729 case ValueType::String:
2730 if (id.isAtom(cx_->names().length)) {
2731 // String length is special-cased, see js::GetProperty.
2732 return AttachDecision::NoAction;
2733 }
2734 protoKey = JSProto_String;
2735 break;
2736 case ValueType::Int32:
2737 case ValueType::Double:
2738 protoKey = JSProto_Number;
2739 break;
2740 case ValueType::Boolean:
2741 protoKey = JSProto_Boolean;
2742 break;
2743 case ValueType::Symbol:
2744 protoKey = JSProto_Symbol;
2745 break;
2746 case ValueType::BigInt:
2747 protoKey = JSProto_BigInt;
2748 break;
2749 case ValueType::Null:
2750 case ValueType::Undefined:
2751 case ValueType::Magic:
2752 return AttachDecision::NoAction;
2753 case ValueType::Object:
2754 case ValueType::PrivateGCThing:
2755 MOZ_CRASH("unexpected type");
2756 }
2757
2758 JSObject* proto = GlobalObject::getOrCreatePrototype(cx_, protoKey);
2759 if (!proto) {
2760 cx_->recoverFromOutOfMemory();
2761 return AttachDecision::NoAction;
2762 }
2763
2764 NativeObject* holder = nullptr;
2765 Maybe<PropertyInfo> prop;
2766 NativeGetPropKind kind =
2767 CanAttachNativeGetProp(cx_, proto, id, &holder, &prop, pc_);
2768 switch (kind) {
2769 case NativeGetPropKind::None:
2770 return AttachDecision::NoAction;
2771 case NativeGetPropKind::Missing:
2772 case NativeGetPropKind::Slot: {
2773 auto* nproto = &proto->as<NativeObject>();
2774
2775 if (val_.isNumber()) {
2776 writer.guardIsNumber(valId);
2777 } else {
2778 writer.guardNonDoubleType(valId, val_.type());
2779 }
2780 maybeEmitIdGuard(id);
2781
2782 ObjOperandId protoId = writer.loadObject(nproto);
2783 if (kind == NativeGetPropKind::Slot) {
2784 EmitReadSlotResult(writer, nproto, holder, *prop, protoId);
2785 writer.returnFromIC();
2786 trackAttached("GetProp.PrimitiveSlot");
2787 } else {
2788 EmitMissingPropResult(writer, nproto, protoId);
2789 writer.returnFromIC();
2790 trackAttached("GetProp.PrimitiveMissing");
2791 }
2792 return AttachDecision::Attach;
2793 }
2794 case NativeGetPropKind::ScriptedGetter:
2795 case NativeGetPropKind::NativeGetter: {
2796 auto* nproto = &proto->as<NativeObject>();
2797
2798 if (val_.isNumber()) {
2799 writer.guardIsNumber(valId);
2800 } else {
2801 writer.guardNonDoubleType(valId, val_.type());
2802 }
2803 maybeEmitIdGuard(id);
2804
2805 ObjOperandId protoId = writer.loadObject(nproto);
2806 EmitCallGetterResult(cx_, writer, kind, nproto, holder, id, *prop,
2807 protoId, valId, mode_);
2808
2809 trackAttached("GetProp.PrimitiveGetter");
2810 return AttachDecision::Attach;
2811 }
2812 }
2813
2814 MOZ_CRASH("Bad NativeGetPropKind");
2815 }
2816
2817 AttachDecision GetPropIRGenerator::tryAttachStringLength(ValOperandId valId,
2818 HandleId id) {
2819 if (!val_.isString() || !id.isAtom(cx_->names().length)) {
2820 return AttachDecision::NoAction;
2821 }
2822
2823 StringOperandId strId = writer.guardToString(valId);
2824 maybeEmitIdGuard(id);
2825 writer.loadStringLengthResult(strId);
2826 writer.returnFromIC();
2827
2828 trackAttached("GetProp.StringLength");
2829 return AttachDecision::Attach;
2830 }
2831
2832 enum class AttachStringChar { No, Yes, Linearize, OutOfBounds };
2833
2834 static AttachStringChar CanAttachStringChar(const Value& val,
2835 const Value& idVal,
2836 StringChar kind) {
2837 if (!val.isString() || !idVal.isInt32()) {
2838 return AttachStringChar::No;
2839 }
2840
2841 JSString* str = val.toString();
2842 int32_t index = idVal.toInt32();
2843
2844 if (index < 0 && kind == StringChar::At) {
2845 static_assert(JSString::MAX_LENGTH <= INT32_MAX,
2846 "string length fits in int32");
2847 index += int32_t(str->length());
2848 }
2849
2850 if (index < 0 || size_t(index) >= str->length()) {
2851 return AttachStringChar::OutOfBounds;
2852 }
2853
2854 // This follows JSString::getChar and MacroAssembler::loadStringChar.
2855 if (str->isRope()) {
2856 JSRope* rope = &str->asRope();
2857 if (size_t(index) < rope->leftChild()->length()) {
2858 str = rope->leftChild();
2859
2860 // MacroAssembler::loadStringChar doesn't support surrogate pairs which
2861 // are split between the left and right child of a rope.
2862 if (kind == StringChar::CodePointAt &&
2863 size_t(index) + 1 == str->length() && str->isLinear()) {
2864 // Linearize the string when the last character of the left child is a
2865 // a lead surrogate.
2866 char16_t ch = str->asLinear().latin1OrTwoByteChar(index);
2867 if (unicode::IsLeadSurrogate(ch)) {
2868 return AttachStringChar::Linearize;
2869 }
2870 }
2871 } else {
2872 str = rope->rightChild();
2873 }
2874 }
2875
2876 if (!str->isLinear()) {
2877 return AttachStringChar::Linearize;
2878 }
2879
2880 return AttachStringChar::Yes;
2881 }
2882
2883 static Int32OperandId EmitGuardToInt32Index(CacheIRWriter& writer,
2884 const Value& index,
2885 ValOperandId indexId) {
2886 if (index.isInt32()) {
2887 return writer.guardToInt32(indexId);
2888 }
2889 MOZ_ASSERT(index.isDouble());
2890 return writer.guardToInt32Index(indexId);
2891 }
2892
2893 AttachDecision GetPropIRGenerator::tryAttachStringChar(ValOperandId valId,
2894 ValOperandId indexId) {
2895 MOZ_ASSERT(idVal_.isInt32());
2896
2897 auto attach = CanAttachStringChar(val_, idVal_, StringChar::CharAt);
2898 if (attach == AttachStringChar::No) {
2899 return AttachDecision::NoAction;
2900 }
2901
2902 // Can't attach for out-of-bounds access without guarding that indexed
2903 // properties aren't present along the prototype chain of |String.prototype|.
2904 if (attach == AttachStringChar::OutOfBounds) {
2905 return AttachDecision::NoAction;
2906 }
2907
2908 StringOperandId strId = writer.guardToString(valId);
2909 Int32OperandId int32IndexId = EmitGuardToInt32Index(writer, idVal_, indexId);
2910 if (attach == AttachStringChar::Linearize) {
2911 strId = writer.linearizeForCharAccess(strId, int32IndexId);
2912 }
2913 writer.loadStringCharResult(strId, int32IndexId, /* handleOOB = */ false);
2914 writer.returnFromIC();
2915
2916 trackAttached("GetProp.StringChar");
2917 return AttachDecision::Attach;
2918 }
2919
2920 static bool ClassCanHaveExtraProperties(const JSClass* clasp) {
2921 return clasp->getResolve() || clasp->getOpsLookupProperty() ||
2922 clasp->getOpsGetProperty() || IsTypedArrayClass(clasp);
2923 }
2924
2925 enum class OwnProperty : bool { No, Yes };
2926 enum class AllowIndexedReceiver : bool { No, Yes };
2927 enum class AllowExtraReceiverProperties : bool { No, Yes };
2928
2929 static bool CanAttachDenseElementHole(
2930 NativeObject* obj, OwnProperty ownProp,
2931 AllowIndexedReceiver allowIndexedReceiver = AllowIndexedReceiver::No,
2932 AllowExtraReceiverProperties allowExtraReceiverProperties =
2933 AllowExtraReceiverProperties::No) {
2934 // Make sure the objects on the prototype don't have any indexed properties
2935 // or that such properties can't appear without a shape change.
2936 // Otherwise returning undefined for holes would obviously be incorrect,
2937 // because we would have to lookup a property on the prototype instead.
2938 do {
2939 // The first two checks are also relevant to the receiver object.
2940 if (allowIndexedReceiver == AllowIndexedReceiver::No && obj->isIndexed()) {
2941 return false;
2942 }
2943 allowIndexedReceiver = AllowIndexedReceiver::No;
2944
2945 if (allowExtraReceiverProperties == AllowExtraReceiverProperties::No &&
2946 ClassCanHaveExtraProperties(obj->getClass())) {
2947 return false;
2948 }
2949 allowExtraReceiverProperties = AllowExtraReceiverProperties::No;
2950
2951 // Don't need to check prototype for OwnProperty checks
2952 if (ownProp == OwnProperty::Yes) {
2953 return true;
2954 }
2955
2956 JSObject* proto = obj->staticPrototype();
2957 if (!proto) {
2958 break;
2959 }
2960
2961 if (!proto->is<NativeObject>()) {
2962 return false;
2963 }
2964
2965 // Make sure objects on the prototype don't have dense elements.
2966 if (proto->as<NativeObject>().getDenseInitializedLength() != 0) {
2967 return false;
2968 }
2969
2970 obj = &proto->as<NativeObject>();
2971 } while (true);
2972
2973 return true;
2974 }
2975
2976 AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectArg(
2977 HandleObject obj, ObjOperandId objId, uint32_t index,
2978 Int32OperandId indexId) {
2979 if (!obj->is<ArgumentsObject>()) {
2980 return AttachDecision::NoAction;
2981 }
2982 auto* args = &obj->as<ArgumentsObject>();
2983
2984 // No elements must have been overridden or deleted.
2985 if (args->hasOverriddenElement()) {
2986 return AttachDecision::NoAction;
2987 }
2988
2989 // Check bounds.
2990 if (index >= args->initialLength()) {
2991 return AttachDecision::NoAction;
2992 }
2993
2994 AssertArgumentsCustomDataProp(args, PropertyKey::Int(index));
2995
2996 // And finally also check that the argument isn't forwarded.
2997 if (args->argIsForwarded(index)) {
2998 return AttachDecision::NoAction;
2999 }
3000
3001 if (args->is<MappedArgumentsObject>()) {
3002 writer.guardClass(objId, GuardClassKind::MappedArguments);
3003 } else {
3004 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
3005 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
3006 }
3007
3008 writer.loadArgumentsObjectArgResult(objId, indexId);
3009 writer.returnFromIC();
3010
3011 trackAttached("GetProp.ArgumentsObjectArg");
3012 return AttachDecision::Attach;
3013 }
3014
3015 AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectArgHole(
3016 HandleObject obj, ObjOperandId objId, uint32_t index,
3017 Int32OperandId indexId) {
3018 if (!obj->is<ArgumentsObject>()) {
3019 return AttachDecision::NoAction;
3020 }
3021 auto* args = &obj->as<ArgumentsObject>();
3022
3023 // No elements must have been overridden or deleted.
3024 if (args->hasOverriddenElement()) {
3025 return AttachDecision::NoAction;
3026 }
3027
3028 // And also check that the argument isn't forwarded.
3029 if (index < args->initialLength() && args->argIsForwarded(index)) {
3030 return AttachDecision::NoAction;
3031 }
3032
3033 if (!CanAttachDenseElementHole(args, OwnProperty::No,
3034 AllowIndexedReceiver::Yes,
3035 AllowExtraReceiverProperties::Yes)) {
3036 return AttachDecision::NoAction;
3037 }
3038
3039 // We don't need to guard on the shape, because we check if any element is
3040 // overridden. Elements are marked as overridden iff any element is defined,
3041 // irrespective of whether the element is in-bounds or out-of-bounds. So when
3042 // that flag isn't set, we can guarantee that the arguments object doesn't
3043 // have any additional own elements.
3044
3045 if (args->is<MappedArgumentsObject>()) {
3046 writer.guardClass(objId, GuardClassKind::MappedArguments);
3047 } else {
3048 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
3049 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
3050 }
3051
3052 GeneratePrototypeHoleGuards(writer, args, objId,
3053 /* alwaysGuardFirstProto = */ true);
3054
3055 writer.loadArgumentsObjectArgHoleResult(objId, indexId);
3056 writer.returnFromIC();
3057
3058 trackAttached("GetProp.ArgumentsObjectArgHole");
3059 return AttachDecision::Attach;
3060 }
3061
3062 AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectCallee(
3063 HandleObject obj, ObjOperandId objId, HandleId id) {
3064 // Only mapped arguments objects have a `callee` property.
3065 if (!obj->is<MappedArgumentsObject>()) {
3066 return AttachDecision::NoAction;
3067 }
3068
3069 if (!id.isAtom(cx_->names().callee)) {
3070 return AttachDecision::NoAction;
3071 }
3072
3073 // The callee must not have been overridden or deleted.
3074 MappedArgumentsObject* args = &obj->as<MappedArgumentsObject>();
3075 if (args->hasOverriddenCallee()) {
3076 return AttachDecision::NoAction;
3077 }
3078
3079 AssertArgumentsCustomDataProp(args, id);
3080
3081 maybeEmitIdGuard(id);
3082 writer.guardClass(objId, GuardClassKind::MappedArguments);
3083
3084 uint32_t flags = ArgumentsObject::CALLEE_OVERRIDDEN_BIT;
3085 writer.guardArgumentsObjectFlags(objId, flags);
3086
3087 writer.loadFixedSlotResult(objId,
3088 MappedArgumentsObject::getCalleeSlotOffset());
3089 writer.returnFromIC();
3090
3091 trackAttached("GetProp.ArgumentsObjectCallee");
3092 return AttachDecision::Attach;
3093 }
3094
3095 AttachDecision GetPropIRGenerator::tryAttachDenseElement(
3096 HandleObject obj, ObjOperandId objId, uint32_t index,
3097 Int32OperandId indexId) {
3098 if (!obj->is<NativeObject>()) {
3099 return AttachDecision::NoAction;
3100 }
3101
3102 NativeObject* nobj = &obj->as<NativeObject>();
3103 if (!nobj->containsDenseElement(index)) {
3104 return AttachDecision::NoAction;
3105 }
3106
3107 if (mode_ == ICState::Mode::Megamorphic) {
3108 writer.guardIsNativeObject(objId);
3109 } else {
3110 TestMatchingNativeReceiver(writer, nobj, objId);
3111 }
3112 writer.loadDenseElementResult(objId, indexId);
3113 writer.returnFromIC();
3114
3115 trackAttached("GetProp.DenseElement");
3116 return AttachDecision::Attach;
3117 }
3118
3119 AttachDecision GetPropIRGenerator::tryAttachDenseElementHole(
3120 HandleObject obj, ObjOperandId objId, uint32_t index,
3121 Int32OperandId indexId) {
3122 if (!obj->is<NativeObject>()) {
3123 return AttachDecision::NoAction;
3124 }
3125
3126 NativeObject* nobj = &obj->as<NativeObject>();
3127 if (nobj->containsDenseElement(index)) {
3128 return AttachDecision::NoAction;
3129 }
3130 if (!CanAttachDenseElementHole(nobj, OwnProperty::No)) {
3131 return AttachDecision::NoAction;
3132 }
3133
3134 // Guard on the shape, to prevent non-dense elements from appearing.
3135 TestMatchingNativeReceiver(writer, nobj, objId);
3136 GeneratePrototypeHoleGuards(writer, nobj, objId,
3137 /* alwaysGuardFirstProto = */ false);
3138 writer.loadDenseElementHoleResult(objId, indexId);
3139 writer.returnFromIC();
3140
3141 trackAttached("GetProp.DenseElementHole");
3142 return AttachDecision::Attach;
3143 }
3144
3145 AttachDecision GetPropIRGenerator::tryAttachSparseElement(
3146 HandleObject obj, ObjOperandId objId, uint32_t index,
3147 Int32OperandId indexId) {
3148 if (!obj->is<NativeObject>()) {
3149 return AttachDecision::NoAction;
3150 }
3151 NativeObject* nobj = &obj->as<NativeObject>();
3152
3153 // Stub doesn't handle negative indices.
3154 if (index > INT32_MAX) {
3155 return AttachDecision::NoAction;
3156 }
3157
3158 // The object must have sparse elements.
3159 if (!nobj->isIndexed()) {
3160 return AttachDecision::NoAction;
3161 }
3162
3163 // The index must not be for a dense element.
3164 if (nobj->containsDenseElement(index)) {
3165 return AttachDecision::NoAction;
3166 }
3167
3168 // Only handle ArrayObject and PlainObject in this stub.
3169 if (!nobj->is<ArrayObject>() && !nobj->is<PlainObject>()) {
3170 return AttachDecision::NoAction;
3171 }
3172
3173 // GetSparseElementHelper assumes that the target and the receiver
3174 // are the same.
3175 if (isSuper()) {
3176 return AttachDecision::NoAction;
3177 }
3178
3179 // Here, we ensure that the prototype chain does not define any sparse
3180 // indexed properties on the shape lineage. This allows us to guard on
3181 // the shapes up the prototype chain to ensure that no indexed properties
3182 // exist outside of the dense elements.
3183 //
3184 // The `GeneratePrototypeHoleGuards` call below will guard on the shapes,
3185 // as well as ensure that no prototypes contain dense elements, allowing
3186 // us to perform a pure shape-search for out-of-bounds integer-indexed
3187 // properties on the receiver object.
3188 if (PrototypeMayHaveIndexedProperties(nobj)) {
3189 return AttachDecision::NoAction;
3190 }
3191
3192 // Ensure that obj is an ArrayObject or PlainObject.
3193 if (nobj->is<ArrayObject>()) {
3194 writer.guardClass(objId, GuardClassKind::Array);
3195 } else {
3196 MOZ_ASSERT(nobj->is<PlainObject>());
3197 writer.guardClass(objId, GuardClassKind::PlainObject);
3198 }
3199
3200 // The helper we are going to call only applies to non-dense elements.
3201 writer.guardIndexIsNotDenseElement(objId, indexId);
3202
3203 // Ensures we are able to efficiently able to map to an integral jsid.
3204 writer.guardInt32IsNonNegative(indexId);
3205
3206 // Shape guard the prototype chain to avoid shadowing indexes from appearing.
3207 // The helper function also ensures that the index does not appear within the
3208 // dense element set of the prototypes.
3209 GeneratePrototypeHoleGuards(writer, nobj, objId,
3210 /* alwaysGuardFirstProto = */ true);
3211
3212 // At this point, we are guaranteed that the indexed property will not
3213 // be found on one of the prototypes. We are assured that we only have
3214 // to check that the receiving object has the property.
3215
3216 writer.callGetSparseElementResult(objId, indexId);
3217 writer.returnFromIC();
3218
3219 trackAttached("GetProp.SparseElement");
3220 return AttachDecision::Attach;
3221 }
3222
3223 // For Uint32Array we let the stub return an Int32 if we have not seen a
3224 // double, to allow better codegen in Warp while avoiding bailout loops.
3225 static bool ForceDoubleForUint32Array(TypedArrayObject* tarr, uint64_t index) {
3226 MOZ_ASSERT(index < tarr->length().valueOr(0));
3227
3228 if (tarr->type() != Scalar::Type::Uint32) {
3229 // Return value is only relevant for Uint32Array.
3230 return false;
3231 }
3232
3233 Value res;
3234 MOZ_ALWAYS_TRUE(tarr->getElementPure(index, &res));
3235 MOZ_ASSERT(res.isNumber());
3236 return res.isDouble();
3237 }
3238
3239 static ArrayBufferViewKind ToArrayBufferViewKind(const TypedArrayObject* obj) {
3240 if (obj->is<FixedLengthTypedArrayObject>()) {
3241 return ArrayBufferViewKind::FixedLength;
3242 }
3243
3244 MOZ_ASSERT(obj->is<ResizableTypedArrayObject>());
3245 return ArrayBufferViewKind::Resizable;
3246 }
3247
3248 static ArrayBufferViewKind ToArrayBufferViewKind(const DataViewObject* obj) {
3249 if (obj->is<FixedLengthDataViewObject>()) {
3250 return ArrayBufferViewKind::FixedLength;
3251 }
3252
3253 MOZ_ASSERT(obj->is<ResizableDataViewObject>());
3254 return ArrayBufferViewKind::Resizable;
3255 }
3256
3257 AttachDecision GetPropIRGenerator::tryAttachTypedArrayElement(
3258 HandleObject obj, ObjOperandId objId) {
3259 if (!obj->is<TypedArrayObject>()) {
3260 return AttachDecision::NoAction;
3261 }
3262
3263 if (!idVal_.isNumber()) {
3264 return AttachDecision::NoAction;
3265 }
3266
3267 auto* tarr = &obj->as<TypedArrayObject>();
3268
3269 bool handleOOB = false;
3270 int64_t indexInt64;
3271 if (!ValueIsInt64Index(idVal_, &indexInt64) || indexInt64 < 0 ||
3272 uint64_t(indexInt64) >= tarr->length().valueOr(0)) {
3273 handleOOB = true;
3274 }
3275
3276 // If the number is not representable as an integer the result will be
3277 // |undefined| so we leave |forceDoubleForUint32| as false.
3278 bool forceDoubleForUint32 = false;
3279 if (!handleOOB) {
3280 uint64_t index = uint64_t(indexInt64);
3281 forceDoubleForUint32 = ForceDoubleForUint32Array(tarr, index);
3282 }
3283
3284 writer.guardShapeForClass(objId, tarr->shape());
3285
3286 ValOperandId keyId = getElemKeyValueId();
3287 IntPtrOperandId intPtrIndexId = guardToIntPtrIndex(idVal_, keyId, handleOOB);
3288
3289 auto viewKind = ToArrayBufferViewKind(tarr);
3290 writer.loadTypedArrayElementResult(objId, intPtrIndexId, tarr->type(),
3291 handleOOB, forceDoubleForUint32, viewKind);
3292 writer.returnFromIC();
3293
3294 trackAttached("GetProp.TypedElement");
3295 return AttachDecision::Attach;
3296 }
3297
3298 AttachDecision GetPropIRGenerator::tryAttachGenericElement(
3299 HandleObject obj, ObjOperandId objId, uint32_t index,
3300 Int32OperandId indexId, ValOperandId receiverId) {
3301 if (!obj->is<NativeObject>()) {
3302 return AttachDecision::NoAction;
3303 }
3304
3305 #ifdef JS_CODEGEN_X86
3306 if (isSuper()) {
3307 // There aren't enough registers available on x86.
3308 return AttachDecision::NoAction;
3309 }
3310 #endif
3311
3312 // To allow other types to attach in the non-megamorphic case we test the
3313 // specific matching native receiver; however, once megamorphic we can attach
3314 // for any native
3315 if (mode_ == ICState::Mode::Megamorphic) {
3316 writer.guardIsNativeObject(objId);
3317 } else {
3318 NativeObject* nobj = &obj->as<NativeObject>();
3319 TestMatchingNativeReceiver(writer, nobj, objId);
3320 }
3321 writer.guardIndexIsNotDenseElement(objId, indexId);
3322 if (isSuper()) {
3323 writer.callNativeGetElementSuperResult(objId, indexId, receiverId);
3324 } else {
3325 writer.callNativeGetElementResult(objId, indexId);
3326 }
3327 writer.returnFromIC();
3328
3329 trackAttached(mode_ == ICState::Mode::Megamorphic
3330 ? "GenericElementMegamorphic"
3331 : "GenericElement");
3332 return AttachDecision::Attach;
3333 }
3334
3335 AttachDecision GetPropIRGenerator::tryAttachProxyElement(HandleObject obj,
3336 ObjOperandId objId) {
3337 if (!obj->is<ProxyObject>()) {
3338 return AttachDecision::NoAction;
3339 }
3340
3341 // The proxy stubs don't currently support |super| access.
3342 if (isSuper()) {
3343 return AttachDecision::NoAction;
3344 }
3345
3346 #ifdef JS_PUNBOX64
3347 auto proxy = obj.as<ProxyObject>();
3348 if (proxy->handler()->isScripted()) {
3349 TRY_ATTACH(tryAttachScriptedProxy(proxy, objId, JS::VoidHandlePropertyKey));
3350 }
3351 #endif
3352
3353 writer.guardIsProxy(objId);
3354
3355 // We are not guarding against DOM proxies here, because there is no other
3356 // specialized DOM IC we could attach.
3357 // We could call maybeEmitIdGuard here and then emit ProxyGetResult,
3358 // but for GetElem we prefer to attach a stub that can handle any Value
3359 // so we don't attach a new stub for every id.
3360 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem);
3361 MOZ_ASSERT(!isSuper());
3362 writer.proxyGetByValueResult(objId, getElemKeyValueId());
3363 writer.returnFromIC();
3364
3365 trackAttached("GetProp.ProxyElement");
3366 return AttachDecision::Attach;
3367 }
3368
3369 void GetPropIRGenerator::trackAttached(const char* name) {
3370 stubName_ = name ? name : "NotAttached";
3371 #ifdef JS_CACHEIR_SPEW
3372 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
3373 sp.valueProperty("base", val_);
3374 sp.valueProperty("property", idVal_);
3375 }
3376 #endif
3377 }
3378
3379 void IRGenerator::emitIdGuard(ValOperandId valId, const Value& idVal, jsid id) {
3380 if (id.isSymbol()) {
3381 MOZ_ASSERT(idVal.toSymbol() == id.toSymbol());
3382 SymbolOperandId symId = writer.guardToSymbol(valId);
3383 writer.guardSpecificSymbol(symId, id.toSymbol());
3384 return;
3385 }
3386
3387 MOZ_ASSERT(id.isAtom());
3388 switch (idVal.type()) {
3389 case ValueType::String: {
3390 StringOperandId strId = writer.guardToString(valId);
3391 writer.guardSpecificAtom(strId, id.toAtom());
3392 break;
3393 }
3394 case ValueType::Null:
3395 MOZ_ASSERT(id.isAtom(cx_->names().null));
3396 writer.guardIsNull(valId);
3397 break;
3398 case ValueType::Undefined:
3399 MOZ_ASSERT(id.isAtom(cx_->names().undefined));
3400 writer.guardIsUndefined(valId);
3401 break;
3402 case ValueType::Boolean:
3403 MOZ_ASSERT(id.isAtom(cx_->names().true_) ||
3404 id.isAtom(cx_->names().false_));
3405 writer.guardSpecificValue(valId, idVal);
3406 break;
3407 case ValueType::Int32:
3408 case ValueType::Double:
3409 MOZ_ASSERT(!IsNumberIndex(idVal));
3410 writer.guardSpecificValue(valId, idVal);
3411 break;
3412 default:
3413 MOZ_CRASH("Unexpected type in emitIdGuard");
3414 }
3415 }
3416
3417 void GetPropIRGenerator::maybeEmitIdGuard(jsid id) {
3418 if (cacheKind_ == CacheKind::GetProp ||
3419 cacheKind_ == CacheKind::GetPropSuper) {
3420 // Constant PropertyName, no guards necessary.
3421 MOZ_ASSERT(&idVal_.toString()->asAtom() == id.toAtom());
3422 return;
3423 }
3424
3425 MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
3426 cacheKind_ == CacheKind::GetElemSuper);
3427 emitIdGuard(getElemKeyValueId(), idVal_, id);
3428 }
3429
3430 void SetPropIRGenerator::maybeEmitIdGuard(jsid id) {
3431 if (cacheKind_ == CacheKind::SetProp) {
3432 // Constant PropertyName, no guards necessary.
3433 MOZ_ASSERT(&idVal_.toString()->asAtom() == id.toAtom());
3434 return;
3435 }
3436
3437 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
3438 emitIdGuard(setElemKeyValueId(), idVal_, id);
3439 }
3440
3441 GetNameIRGenerator::GetNameIRGenerator(JSContext* cx, HandleScript script,
3442 jsbytecode* pc, ICState state,
3443 HandleObject env,
3444 Handle<PropertyName*> name)
3445 : IRGenerator(cx, script, pc, CacheKind::GetName, state),
3446 env_(env),
3447 name_(name) {}
3448
3449 AttachDecision GetNameIRGenerator::tryAttachStub() {
3450 MOZ_ASSERT(cacheKind_ == CacheKind::GetName);
3451
3452 AutoAssertNoPendingException aanpe(cx_);
3453
3454 ObjOperandId envId(writer.setInputOperandId(0));
3455 RootedId id(cx_, NameToId(name_));
3456
3457 TRY_ATTACH(tryAttachGlobalNameValue(envId, id));
3458 TRY_ATTACH(tryAttachGlobalNameGetter(envId, id));
3459 TRY_ATTACH(tryAttachEnvironmentName(envId, id));
3460
3461 trackAttached(IRGenerator::NotAttached);
3462 return AttachDecision::NoAction;
3463 }
3464
3465 static bool CanAttachGlobalName(JSContext* cx,
3466 GlobalLexicalEnvironmentObject* globalLexical,
3467 PropertyKey id, NativeObject** holder,
3468 Maybe<PropertyInfo>* prop) {
3469 // The property must be found, and it must be found as a normal data property.
3470 NativeObject* current = globalLexical;
3471 while (true) {
3472 *prop = current->lookup(cx, id);
3473 if (prop->isSome()) {
3474 break;
3475 }
3476
3477 if (current == globalLexical) {
3478 current = &globalLexical->global();
3479 } else {
3480 // In the browser the global prototype chain should be immutable.
3481 if (!current->staticPrototypeIsImmutable()) {
3482 return false;
3483 }
3484
3485 JSObject* proto = current->staticPrototype();
3486 if (!proto || !proto->is<NativeObject>()) {
3487 return false;
3488 }
3489
3490 current = &proto->as<NativeObject>();
3491 }
3492 }
3493
3494 *holder = current;
3495 return true;
3496 }
3497
3498 AttachDecision GetNameIRGenerator::tryAttachGlobalNameValue(ObjOperandId objId,
3499 HandleId id) {
3500 if (!IsGlobalOp(JSOp(*pc_))) {
3501 return AttachDecision::NoAction;
3502 }
3503 MOZ_ASSERT(!script_->hasNonSyntacticScope());
3504
3505 auto* globalLexical = &env_->as<GlobalLexicalEnvironmentObject>();
3506
3507 NativeObject* holder = nullptr;
3508 Maybe<PropertyInfo> prop;
3509 if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &prop)) {
3510 return AttachDecision::NoAction;
3511 }
3512
3513 // The property must be found, and it must be found as a normal data property.
3514 if (!prop->isDataProperty()) {
3515 return AttachDecision::NoAction;
3516 }
3517
3518 // This might still be an uninitialized lexical.
3519 if (holder->getSlot(prop->slot()).isMagic()) {
3520 return AttachDecision::NoAction;
3521 }
3522
3523 if (holder == globalLexical) {
3524 // There is no need to guard on the shape. Lexical bindings are
3525 // non-configurable, and this stub cannot be shared across globals.
3526 size_t dynamicSlotOffset =
3527 holder->dynamicSlotIndex(prop->slot()) * sizeof(Value);
3528 writer.loadDynamicSlotResult(objId, dynamicSlotOffset);
3529 } else if (holder == &globalLexical->global()) {
3530 MOZ_ASSERT(globalLexical->global().isGenerationCountedGlobal());
3531 writer.guardGlobalGeneration(
3532 globalLexical->global().generationCount(),
3533 globalLexical->global().addressOfGenerationCount());
3534 ObjOperandId holderId = writer.loadObject(holder);
3535 #ifdef DEBUG
3536 writer.assertPropertyLookup(holderId, id, prop->slot());
3537 #endif
3538 EmitLoadSlotResult(writer, holderId, holder, *prop);
3539 } else {
3540 // Check the prototype chain from the global to the holder
3541 // prototype. Ignore the global lexical scope as it doesn't figure
3542 // into the prototype chain. We guard on the global lexical
3543 // scope's shape independently.
3544 if (!IsCacheableGetPropSlot(&globalLexical->global(), holder, *prop)) {
3545 return AttachDecision::NoAction;
3546 }
3547
3548 // Shape guard for global lexical.
3549 writer.guardShape(objId, globalLexical->shape());
3550
3551 // Guard on the shape of the GlobalObject.
3552 ObjOperandId globalId = writer.loadObject(&globalLexical->global());
3553 writer.guardShape(globalId, globalLexical->global().shape());
3554
3555 // Shape guard holder.
3556 ObjOperandId holderId = writer.loadObject(holder);
3557 writer.guardShape(holderId, holder->shape());
3558
3559 EmitLoadSlotResult(writer, holderId, holder, *prop);
3560 }
3561
3562 writer.returnFromIC();
3563
3564 trackAttached("GetName.GlobalNameValue");
3565 return AttachDecision::Attach;
3566 }
3567
3568 AttachDecision GetNameIRGenerator::tryAttachGlobalNameGetter(ObjOperandId objId,
3569 HandleId id) {
3570 if (!IsGlobalOp(JSOp(*pc_))) {
3571 return AttachDecision::NoAction;
3572 }
3573 MOZ_ASSERT(!script_->hasNonSyntacticScope());
3574
3575 Handle<GlobalLexicalEnvironmentObject*> globalLexical =
3576 env_.as<GlobalLexicalEnvironmentObject>();
3577 MOZ_ASSERT(globalLexical->isGlobal());
3578
3579 NativeObject* holder = nullptr;
3580 Maybe<PropertyInfo> prop;
3581 if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &prop)) {
3582 return AttachDecision::NoAction;
3583 }
3584
3585 if (holder == globalLexical) {
3586 return AttachDecision::NoAction;
3587 }
3588
3589 GlobalObject* global = &globalLexical->global();
3590
3591 NativeGetPropKind kind = IsCacheableGetPropCall(global, holder, *prop, pc_);
3592 if (kind != NativeGetPropKind::NativeGetter &&
3593 kind != NativeGetPropKind::ScriptedGetter) {
3594 return AttachDecision::NoAction;
3595 }
3596
3597 bool needsWindowProxy =
3598 IsWindow(global) && GetterNeedsWindowProxyThis(holder, *prop);
3599
3600 // Shape guard for global lexical.
3601 writer.guardShape(objId, globalLexical->shape());
3602
3603 // Guard on the shape of the GlobalObject.
3604 ObjOperandId globalId = writer.loadEnclosingEnvironment(objId);
3605 writer.guardShape(globalId, global->shape());
3606
3607 if (holder != global) {
3608 // Shape guard holder.
3609 ObjOperandId holderId = writer.loadObject(holder);
3610 writer.guardShape(holderId, holder->shape());
3611 EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
3612 /* holderIsConstant = */ true);
3613 } else {
3614 // Note: pass true for |holderIsConstant| because the holder must be the
3615 // current global object.
3616 EmitGuardGetterSetterSlot(writer, holder, *prop, globalId,
3617 /* holderIsConstant = */ true);
3618 }
3619
3620 if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, global, holder, *prop,
3621 mode_)) {
3622 // The global shape guard above ensures the instance JSClass is correct.
3623 MOZ_ASSERT(!needsWindowProxy);
3624 EmitCallDOMGetterResultNoGuards(writer, holder, *prop, globalId);
3625 trackAttached("GetName.GlobalNameDOMGetter");
3626 } else {
3627 ObjOperandId receiverObjId;
3628 if (needsWindowProxy) {
3629 MOZ_ASSERT(cx_->global()->maybeWindowProxy());
3630 receiverObjId = writer.loadObject(cx_->global()->maybeWindowProxy());
3631 } else {
3632 receiverObjId = globalId;
3633 }
3634 ValOperandId receiverId = writer.boxObject(receiverObjId);
3635 EmitCallGetterResultNoGuards(cx_, writer, kind, global, holder, *prop,
3636 receiverId);
3637 trackAttached("GetName.GlobalNameGetter");
3638 }
3639
3640 return AttachDecision::Attach;
3641 }
3642
3643 static bool NeedEnvironmentShapeGuard(JSContext* cx, JSObject* envObj) {
3644 // We can skip a guard on the call object if the script's bindings are
3645 // guaranteed to be immutable (and thus cannot introduce shadowing variables).
3646 // If the function is a relazified self-hosted function it has no BaseScript
3647 // and we pessimistically create the guard.
3648 if (envObj->is<CallObject>()) {
3649 auto* callObj = &envObj->as<CallObject>();
3650 JSFunction* fun = &callObj->callee();
3651 return !fun->hasBaseScript() ||
3652 fun->baseScript()->funHasExtensibleScope() ||
3653 DebugEnvironments::hasDebugEnvironment(cx, *callObj);
3654 }
3655
3656 // Similar to the call object case, we can also skip a guard if the lexical
3657 // environment's bindings are immutable.
3658 if (envObj->is<LexicalEnvironmentObject>()) {
3659 return envObj->as<LexicalEnvironmentObject>().isExtensible();
3660 }
3661
3662 // Use a shape guard for all other environment objects.
3663 return true;
3664 }
3665
3666 AttachDecision GetNameIRGenerator::tryAttachEnvironmentName(ObjOperandId objId,
3667 HandleId id) {
3668 if (IsGlobalOp(JSOp(*pc_)) || script_->hasNonSyntacticScope()) {
3669 return AttachDecision::NoAction;
3670 }
3671
3672 JSObject* env = env_;
3673 Maybe<PropertyInfo> prop;
3674 NativeObject* holder = nullptr;
3675
3676 while (env) {
3677 if (env->is<GlobalObject>()) {
3678 prop = env->as<GlobalObject>().lookup(cx_, id);
3679 if (prop.isSome()) {
3680 break;
3681 }
3682 return AttachDecision::NoAction;
3683 }
3684
3685 if (!env->is<EnvironmentObject>() || env->is<WithEnvironmentObject>()) {
3686 return AttachDecision::NoAction;
3687 }
3688
3689 // Check for an 'own' property on the env. There is no need to
3690 // check the prototype as non-with scopes do not inherit properties
3691 // from any prototype.
3692 prop = env->as<NativeObject>().lookup(cx_, id);
3693 if (prop.isSome()) {
3694 break;
3695 }
3696
3697 env = env->enclosingEnvironment();
3698 }
3699
3700 holder = &env->as<NativeObject>();
3701 if (!IsCacheableGetPropSlot(holder, holder, *prop)) {
3702 return AttachDecision::NoAction;
3703 }
3704 if (holder->getSlot(prop->slot()).isMagic()) {
3705 MOZ_ASSERT(holder->is<EnvironmentObject>());
3706 return AttachDecision::NoAction;
3707 }
3708
3709 ObjOperandId lastObjId = objId;
3710 env = env_;
3711 while (env) {
3712 if (NeedEnvironmentShapeGuard(cx_, env)) {
3713 writer.guardShape(lastObjId, env->shape());
3714 }
3715
3716 if (env == holder) {
3717 break;
3718 }
3719
3720 lastObjId = writer.loadEnclosingEnvironment(lastObjId);
3721 env = env->enclosingEnvironment();
3722 }
3723
3724 ValOperandId resId = EmitLoadSlot(writer, holder, lastObjId, prop->slot());
3725 if (holder->is<EnvironmentObject>()) {
3726 writer.guardIsNotUninitializedLexical(resId);
3727 }
3728 writer.loadOperandResult(resId);
3729 writer.returnFromIC();
3730
3731 trackAttached("GetName.EnvironmentName");
3732 return AttachDecision::Attach;
3733 }
3734
3735 void GetNameIRGenerator::trackAttached(const char* name) {
3736 stubName_ = name ? name : "NotAttached";
3737 #ifdef JS_CACHEIR_SPEW
3738 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
3739 sp.valueProperty("base", ObjectValue(*env_));
3740 sp.valueProperty("property", StringValue(name_));
3741 }
3742 #endif
3743 }
3744
3745 BindNameIRGenerator::BindNameIRGenerator(JSContext* cx, HandleScript script,
3746 jsbytecode* pc, ICState state,
3747 HandleObject env,
3748 Handle<PropertyName*> name)
3749 : IRGenerator(cx, script, pc, CacheKind::BindName, state),
3750 env_(env),
3751 name_(name) {}
3752
3753 AttachDecision BindNameIRGenerator::tryAttachStub() {
3754 MOZ_ASSERT(cacheKind_ == CacheKind::BindName);
3755
3756 AutoAssertNoPendingException aanpe(cx_);
3757
3758 ObjOperandId envId(writer.setInputOperandId(0));
3759 RootedId id(cx_, NameToId(name_));
3760
3761 TRY_ATTACH(tryAttachGlobalName(envId, id));
3762 TRY_ATTACH(tryAttachEnvironmentName(envId, id));
3763
3764 trackAttached(IRGenerator::NotAttached);
3765 return AttachDecision::NoAction;
3766 }
3767
3768 AttachDecision BindNameIRGenerator::tryAttachGlobalName(ObjOperandId objId,
3769 HandleId id) {
3770 if (!IsGlobalOp(JSOp(*pc_))) {
3771 return AttachDecision::NoAction;
3772 }
3773 MOZ_ASSERT(!script_->hasNonSyntacticScope());
3774
3775 Handle<GlobalLexicalEnvironmentObject*> globalLexical =
3776 env_.as<GlobalLexicalEnvironmentObject>();
3777 MOZ_ASSERT(globalLexical->isGlobal());
3778
3779 JSObject* result = nullptr;
3780 if (Maybe<PropertyInfo> prop = globalLexical->lookup(cx_, id)) {
3781 // If this is an uninitialized lexical or a const, we need to return a
3782 // RuntimeLexicalErrorObject.
3783 if (globalLexical->getSlot(prop->slot()).isMagic() || !prop->writable()) {
3784 return AttachDecision::NoAction;
3785 }
3786 result = globalLexical;
3787 } else {
3788 result = &globalLexical->global();
3789 }
3790
3791 if (result == globalLexical) {
3792 // Lexical bindings are non-configurable so we can just return the
3793 // global lexical.
3794 writer.loadObjectResult(objId);
3795 } else {
3796 // If the property exists on the global and is non-configurable, it cannot
3797 // be shadowed by the lexical scope so we can just return the global without
3798 // a shape guard.
3799 Maybe<PropertyInfo> prop = result->as<GlobalObject>().lookup(cx_, id);
3800 if (prop.isNothing() || prop->configurable()) {
3801 writer.guardShape(objId, globalLexical->shape());
3802 }
3803 ObjOperandId globalId = writer.loadEnclosingEnvironment(objId);
3804 writer.loadObjectResult(globalId);
3805 }
3806 writer.returnFromIC();
3807
3808 trackAttached("BindName.GlobalName");
3809 return AttachDecision::Attach;
3810 }
3811
3812 AttachDecision BindNameIRGenerator::tryAttachEnvironmentName(ObjOperandId objId,
3813 HandleId id) {
3814 if (IsGlobalOp(JSOp(*pc_)) || script_->hasNonSyntacticScope()) {
3815 return AttachDecision::NoAction;
3816 }
3817
3818 // JSOp::BindUnqualifiedName when writing to a dynamic environment binding.
3819 // JSOp::BindName when reading from a dynamic environment binding.
3820 bool unqualifiedLookup = JSOp(*pc_) == JSOp::BindUnqualifiedName;
3821
3822 JSObject* env = env_;
3823 Maybe<PropertyInfo> prop;
3824 while (true) {
3825 // Stop when we've reached the global object.
3826 if (env->is<GlobalObject>()) {
3827 break;
3828 }
3829
3830 if (!env->is<EnvironmentObject>() || env->is<WithEnvironmentObject>()) {
3831 return AttachDecision::NoAction;
3832 }
3833
3834 // When we reach an unqualified variables object (like the global) we
3835 // have to stop looking and return that object.
3836 if (unqualifiedLookup && env->isUnqualifiedVarObj()) {
3837 break;
3838 }
3839
3840 // Check for an 'own' property on the env. There is no need to
3841 // check the prototype as non-with scopes do not inherit properties
3842 // from any prototype.
3843 prop = env->as<NativeObject>().lookup(cx_, id);
3844 if (prop.isSome()) {
3845 break;
3846 }
3847
3848 env = env->enclosingEnvironment();
3849 }
3850
3851 // If this is an uninitialized lexical or a const, we need to return a
3852 // RuntimeLexicalErrorObject.
3853 auto* holder = &env->as<NativeObject>();
3854 if (prop.isSome() && holder->is<EnvironmentObject>()) {
3855 // Uninitialized lexical binding.
3856 if (holder->getSlot(prop->slot()).isMagic()) {
3857 return AttachDecision::NoAction;
3858 }
3859
3860 // Attempt to write to a const binding.
3861 if (unqualifiedLookup && !prop->writable()) {
3862 return AttachDecision::NoAction;
3863 }
3864 }
3865
3866 ObjOperandId lastObjId = objId;
3867 env = env_;
3868 while (env) {
3869 if (NeedEnvironmentShapeGuard(cx_, env) && !env->is<GlobalObject>()) {
3870 writer.guardShape(lastObjId, env->shape());
3871 }
3872
3873 if (env == holder) {
3874 break;
3875 }
3876
3877 lastObjId = writer.loadEnclosingEnvironment(lastObjId);
3878 env = env->enclosingEnvironment();
3879 }
3880
3881 if (prop.isSome() && holder->is<EnvironmentObject>()) {
3882 ValOperandId valId = EmitLoadSlot(writer, holder, lastObjId, prop->slot());
3883 writer.guardIsNotUninitializedLexical(valId);
3884 }
3885
3886 writer.loadObjectResult(lastObjId);
3887 writer.returnFromIC();
3888
3889 trackAttached("BindName.EnvironmentName");
3890 return AttachDecision::Attach;
3891 }
3892
3893 void BindNameIRGenerator::trackAttached(const char* name) {
3894 stubName_ = name ? name : "NotAttached";
3895 #ifdef JS_CACHEIR_SPEW
3896 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
3897 sp.valueProperty("base", ObjectValue(*env_));
3898 sp.valueProperty("property", StringValue(name_));
3899 }
3900 #endif
3901 }
3902
3903 HasPropIRGenerator::HasPropIRGenerator(JSContext* cx, HandleScript script,
3904 jsbytecode* pc, ICState state,
3905 CacheKind cacheKind, HandleValue idVal,
3906 HandleValue val)
3907 : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {}
3908
3909 AttachDecision HasPropIRGenerator::tryAttachDense(HandleObject obj,
3910 ObjOperandId objId,
3911 uint32_t index,
3912 Int32OperandId indexId) {
3913 if (!obj->is<NativeObject>()) {
3914 return AttachDecision::NoAction;
3915 }
3916
3917 NativeObject* nobj = &obj->as<NativeObject>();
3918 if (!nobj->containsDenseElement(index)) {
3919 return AttachDecision::NoAction;
3920 }
3921
3922 if (mode_ == ICState::Mode::Megamorphic) {
3923 writer.guardIsNativeObject(objId);
3924 } else {
3925 // Guard shape to ensure object class is NativeObject.
3926 TestMatchingNativeReceiver(writer, nobj, objId);
3927 }
3928 writer.loadDenseElementExistsResult(objId, indexId);
3929 writer.returnFromIC();
3930
3931 trackAttached("HasProp.Dense");
3932 return AttachDecision::Attach;
3933 }
3934
3935 AttachDecision HasPropIRGenerator::tryAttachDenseHole(HandleObject obj,
3936 ObjOperandId objId,
3937 uint32_t index,
3938 Int32OperandId indexId) {
3939 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
3940 OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;
3941
3942 if (!obj->is<NativeObject>()) {
3943 return AttachDecision::NoAction;
3944 }
3945
3946 NativeObject* nobj = &obj->as<NativeObject>();
3947 if (nobj->containsDenseElement(index)) {
3948 return AttachDecision::NoAction;
3949 }
3950 if (!CanAttachDenseElementHole(nobj, ownProp)) {
3951 return AttachDecision::NoAction;
3952 }
3953
3954 // Guard shape to ensure class is NativeObject and to prevent non-dense
3955 // elements being added. Also ensures prototype doesn't change if dynamic
3956 // checks aren't emitted.
3957 TestMatchingNativeReceiver(writer, nobj, objId);
3958
3959 // Generate prototype guards if needed. This includes monitoring that
3960 // properties were not added in the chain.
3961 if (!hasOwn) {
3962 GeneratePrototypeHoleGuards(writer, nobj, objId,
3963 /* alwaysGuardFirstProto = */ false);
3964 }
3965
3966 writer.loadDenseElementHoleExistsResult(objId, indexId);
3967 writer.returnFromIC();
3968
3969 trackAttached("HasProp.DenseHole");
3970 return AttachDecision::Attach;
3971 }
3972
3973 AttachDecision HasPropIRGenerator::tryAttachSparse(HandleObject obj,
3974 ObjOperandId objId,
3975 Int32OperandId indexId) {
3976 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
3977 OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;
3978
3979 if (!obj->is<NativeObject>()) {
3980 return AttachDecision::NoAction;
3981 }
3982 auto* nobj = &obj->as<NativeObject>();
3983
3984 if (!nobj->isIndexed()) {
3985 return AttachDecision::NoAction;
3986 }
3987 if (!CanAttachDenseElementHole(nobj, ownProp, AllowIndexedReceiver::Yes)) {
3988 return AttachDecision::NoAction;
3989 }
3990
3991 // Guard that this is a native object.
3992 writer.guardIsNativeObject(objId);
3993
3994 // Generate prototype guards if needed. This includes monitoring that
3995 // properties were not added in the chain.
3996 if (!hasOwn) {
3997 GeneratePrototypeHoleGuards(writer, nobj, objId,
3998 /* alwaysGuardFirstProto = */ true);
3999 }
4000
4001 // Because of the prototype guard we know that the prototype chain
4002 // does not include any dense or sparse (i.e indexed) properties.
4003 writer.callObjectHasSparseElementResult(objId, indexId);
4004 writer.returnFromIC();
4005
4006 trackAttached("HasProp.Sparse");
4007 return AttachDecision::Attach;
4008 }
4009
4010 AttachDecision HasPropIRGenerator::tryAttachArgumentsObjectArg(
4011 HandleObject obj, ObjOperandId objId, Int32OperandId indexId) {
4012 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4013 OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;
4014
4015 if (!obj->is<ArgumentsObject>()) {
4016 return AttachDecision::NoAction;
4017 }
4018 auto* args = &obj->as<ArgumentsObject>();
4019
4020 // No elements must have been overridden or deleted.
4021 if (args->hasOverriddenElement()) {
4022 return AttachDecision::NoAction;
4023 }
4024
4025 if (!CanAttachDenseElementHole(args, ownProp, AllowIndexedReceiver::Yes,
4026 AllowExtraReceiverProperties::Yes)) {
4027 return AttachDecision::NoAction;
4028 }
4029
4030 if (args->is<MappedArgumentsObject>()) {
4031 writer.guardClass(objId, GuardClassKind::MappedArguments);
4032 } else {
4033 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
4034 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
4035 }
4036
4037 if (!hasOwn) {
4038 GeneratePrototypeHoleGuards(writer, args, objId,
4039 /* alwaysGuardFirstProto = */ true);
4040 }
4041
4042 writer.loadArgumentsObjectArgExistsResult(objId, indexId);
4043 writer.returnFromIC();
4044
4045 trackAttached("HasProp.ArgumentsObjectArg");
4046 return AttachDecision::Attach;
4047 }
4048
4049 AttachDecision HasPropIRGenerator::tryAttachNamedProp(HandleObject obj,
4050 ObjOperandId objId,
4051 HandleId key,
4052 ValOperandId keyId) {
4053 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4054
4055 Rooted<NativeObject*> holder(cx_);
4056 PropertyResult prop;
4057
4058 if (hasOwn) {
4059 if (!LookupOwnPropertyPure(cx_, obj, key, &prop)) {
4060 return AttachDecision::NoAction;
4061 }
4062
4063 holder.set(&obj->as<NativeObject>());
4064 } else {
4065 NativeObject* nHolder = nullptr;
4066 if (!LookupPropertyPure(cx_, obj, key, &nHolder, &prop)) {
4067 return AttachDecision::NoAction;
4068 }
4069 holder.set(nHolder);
4070 }
4071 if (prop.isNotFound()) {
4072 return AttachDecision::NoAction;
4073 }
4074
4075 TRY_ATTACH(tryAttachSmallObjectVariableKey(obj, objId, key, keyId));
4076 TRY_ATTACH(tryAttachMegamorphic(objId, keyId));
4077 TRY_ATTACH(tryAttachNative(&obj->as<NativeObject>(), objId, key, keyId, prop,
4078 holder.get()));
4079
4080 return AttachDecision::NoAction;
4081 }
4082
4083 AttachDecision HasPropIRGenerator::tryAttachSmallObjectVariableKey(
4084 HandleObject obj, ObjOperandId objId, jsid key, ValOperandId keyId) {
4085 MOZ_ASSERT(obj->is<NativeObject>());
4086
4087 if (cacheKind_ != CacheKind::HasOwn) {
4088 return AttachDecision::NoAction;
4089 }
4090
4091 if (mode_ != ICState::Mode::Megamorphic) {
4092 return AttachDecision::NoAction;
4093 }
4094
4095 if (numOptimizedStubs_ != 0) {
4096 return AttachDecision::NoAction;
4097 }
4098
4099 if (!idVal_.isString()) {
4100 return AttachDecision::NoAction;
4101 }
4102
4103 if (!obj->as<NativeObject>().hasEmptyElements()) {
4104 return AttachDecision::NoAction;
4105 }
4106
4107 if (ClassCanHaveExtraProperties(obj->getClass())) {
4108 return AttachDecision::NoAction;
4109 }
4110
4111 if (!obj->shape()->isShared()) {
4112 return AttachDecision::NoAction;
4113 }
4114
4115 static constexpr size_t SMALL_OBJECT_SIZE = 5;
4116
4117 if (obj->shape()->asShared().slotSpan() > SMALL_OBJECT_SIZE) {
4118 return AttachDecision::NoAction;
4119 }
4120
4121 Rooted<ListObject*> keyListObj(cx_, ListObject::create(cx_));
4122 if (!keyListObj) {
4123 cx_->recoverFromOutOfMemory();
4124 return AttachDecision::NoAction;
4125 }
4126
4127 for (SharedShapePropertyIter<CanGC> iter(cx_, &obj->shape()->asShared());
4128 !iter.done(); iter++) {
4129 if (!iter->key().isAtom()) {
4130 return AttachDecision::NoAction;
4131 }
4132
4133 if (keyListObj->length() == SMALL_OBJECT_SIZE) {
4134 return AttachDecision::NoAction;
4135 }
4136
4137 RootedValue key(cx_, StringValue(iter->key().toAtom()));
4138 if (!keyListObj->append(cx_, key)) {
4139 cx_->recoverFromOutOfMemory();
4140 return AttachDecision::NoAction;
4141 }
4142 }
4143
4144 writer.guardShape(objId, obj->shape());
4145 writer.guardNoDenseElements(objId);
4146 StringOperandId keyStrId = writer.guardToString(keyId);
4147 StringOperandId keyAtomId = writer.stringToAtom(keyStrId);
4148 writer.smallObjectVariableKeyHasOwnResult(keyAtomId, keyListObj,
4149 obj->shape());
4150 writer.returnFromIC();
4151 trackAttached("HasProp.SmallObjectVariableKey");
4152 return AttachDecision::Attach;
4153 }
4154
4155 AttachDecision HasPropIRGenerator::tryAttachMegamorphic(ObjOperandId objId,
4156 ValOperandId keyId) {
4157 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4158
4159 if (mode_ != ICState::Mode::Megamorphic) {
4160 return AttachDecision::NoAction;
4161 }
4162
4163 writer.megamorphicHasPropResult(objId, keyId, hasOwn);
4164 writer.returnFromIC();
4165 trackAttached("HasProp.Megamorphic");
4166 return AttachDecision::Attach;
4167 }
4168
4169 AttachDecision HasPropIRGenerator::tryAttachNative(NativeObject* obj,
4170 ObjOperandId objId, jsid key,
4171 ValOperandId keyId,
4172 PropertyResult prop,
4173 NativeObject* holder) {
4174 MOZ_ASSERT(IsCacheableProtoChain(obj, holder));
4175
4176 if (!prop.isNativeProperty()) {
4177 return AttachDecision::NoAction;
4178 }
4179
4180 emitIdGuard(keyId, idVal_, key);
4181 EmitReadSlotGuard(writer, obj, holder, objId);
4182 writer.loadBooleanResult(true);
4183 writer.returnFromIC();
4184
4185 trackAttached("HasProp.Native");
4186 return AttachDecision::Attach;
4187 }
4188
4189 static void EmitGuardTypedArray(CacheIRWriter& writer, TypedArrayObject* obj,
4190 ObjOperandId objId) {
4191 if (obj->is<FixedLengthTypedArrayObject>()) {
4192 writer.guardIsFixedLengthTypedArray(objId);
4193 } else {
4194 writer.guardIsResizableTypedArray(objId);
4195 }
4196 }
4197
4198 AttachDecision HasPropIRGenerator::tryAttachTypedArray(HandleObject obj,
4199 ObjOperandId objId,
4200 ValOperandId keyId) {
4201 if (!obj->is<TypedArrayObject>()) {
4202 return AttachDecision::NoAction;
4203 }
4204
4205 if (!idVal_.isNumber()) {
4206 return AttachDecision::NoAction;
4207 }
4208
4209 auto* tarr = &obj->as<TypedArrayObject>();
4210 EmitGuardTypedArray(writer, tarr, objId);
4211
4212 IntPtrOperandId intPtrIndexId =
4213 guardToIntPtrIndex(idVal_, keyId, /* supportOOB = */ true);
4214
4215 auto viewKind = ToArrayBufferViewKind(tarr);
4216 writer.loadTypedArrayElementExistsResult(objId, intPtrIndexId, viewKind);
4217 writer.returnFromIC();
4218
4219 trackAttached("HasProp.TypedArrayObject");
4220 return AttachDecision::Attach;
4221 }
4222
4223 AttachDecision HasPropIRGenerator::tryAttachSlotDoesNotExist(
4224 NativeObject* obj, ObjOperandId objId, jsid key, ValOperandId keyId) {
4225 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4226
4227 emitIdGuard(keyId, idVal_, key);
4228 if (hasOwn) {
4229 TestMatchingNativeReceiver(writer, obj, objId);
4230 } else {
4231 EmitMissingPropGuard(writer, obj, objId);
4232 }
4233 writer.loadBooleanResult(false);
4234 writer.returnFromIC();
4235
4236 trackAttached("HasProp.DoesNotExist");
4237 return AttachDecision::Attach;
4238 }
4239
4240 AttachDecision HasPropIRGenerator::tryAttachDoesNotExist(HandleObject obj,
4241 ObjOperandId objId,
4242 HandleId key,
4243 ValOperandId keyId) {
4244 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4245
4246 // Check that property doesn't exist on |obj| or it's prototype chain. These
4247 // checks allow NativeObjects with a NativeObject prototype chain. They return
4248 // NoAction if unknown such as resolve hooks or proxies.
4249 if (hasOwn) {
4250 if (!CheckHasNoSuchOwnProperty(cx_, obj, key)) {
4251 return AttachDecision::NoAction;
4252 }
4253 } else {
4254 if (!CheckHasNoSuchProperty(cx_, obj, key)) {
4255 return AttachDecision::NoAction;
4256 }
4257 }
4258
4259 TRY_ATTACH(tryAttachSmallObjectVariableKey(obj, objId, key, keyId));
4260 TRY_ATTACH(tryAttachMegamorphic(objId, keyId));
4261 TRY_ATTACH(
4262 tryAttachSlotDoesNotExist(&obj->as<NativeObject>(), objId, key, keyId));
4263
4264 return AttachDecision::NoAction;
4265 }
4266
4267 AttachDecision HasPropIRGenerator::tryAttachProxyElement(HandleObject obj,
4268 ObjOperandId objId,
4269 ValOperandId keyId) {
4270 bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
4271
4272 if (!obj->is<ProxyObject>()) {
4273 return AttachDecision::NoAction;
4274 }
4275
4276 writer.guardIsProxy(objId);
4277 writer.proxyHasPropResult(objId, keyId, hasOwn);
4278 writer.returnFromIC();
4279
4280 trackAttached("HasProp.ProxyElement");
4281 return AttachDecision::Attach;
4282 }
4283
4284 AttachDecision HasPropIRGenerator::tryAttachStub() {
4285 MOZ_ASSERT(cacheKind_ == CacheKind::In || cacheKind_ == CacheKind::HasOwn);
4286
4287 AutoAssertNoPendingException aanpe(cx_);
4288
4289 // NOTE: Argument order is PROPERTY, OBJECT
4290 ValOperandId keyId(writer.setInputOperandId(0));
4291 ValOperandId valId(writer.setInputOperandId(1));
4292
4293 if (!val_.isObject()) {
4294 trackAttached(IRGenerator::NotAttached);
4295 return AttachDecision::NoAction;
4296 }
4297 RootedObject obj(cx_, &val_.toObject());
4298 ObjOperandId objId = writer.guardToObject(valId);
4299
4300 // Optimize Proxies
4301 TRY_ATTACH(tryAttachProxyElement(obj, objId, keyId));
4302
4303 RootedId id(cx_);
4304 bool nameOrSymbol;
4305 if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
4306 cx_->clearPendingException();
4307 return AttachDecision::NoAction;
4308 }
4309
4310 TRY_ATTACH(tryAttachTypedArray(obj, objId, keyId));
4311
4312 if (nameOrSymbol) {
4313 TRY_ATTACH(tryAttachNamedProp(obj, objId, id, keyId));
4314 TRY_ATTACH(tryAttachDoesNotExist(obj, objId, id, keyId));
4315
4316 trackAttached(IRGenerator::NotAttached);
4317 return AttachDecision::NoAction;
4318 }
4319
4320 uint32_t index;
4321 Int32OperandId indexId;
4322 if (maybeGuardInt32Index(idVal_, keyId, &index, &indexId)) {
4323 TRY_ATTACH(tryAttachDense(obj, objId, index, indexId));
4324 TRY_ATTACH(tryAttachDenseHole(obj, objId, index, indexId));
4325 TRY_ATTACH(tryAttachSparse(obj, objId, indexId));
4326 TRY_ATTACH(tryAttachArgumentsObjectArg(obj, objId, indexId));
4327
4328 trackAttached(IRGenerator::NotAttached);
4329 return AttachDecision::NoAction;
4330 }
4331
4332 trackAttached(IRGenerator::NotAttached);
4333 return AttachDecision::NoAction;
4334 }
4335
4336 void HasPropIRGenerator::trackAttached(const char* name) {
4337 stubName_ = name ? name : "NotAttached";
4338 #ifdef JS_CACHEIR_SPEW
4339 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
4340 sp.valueProperty("base", val_);
4341 sp.valueProperty("property", idVal_);
4342 }
4343 #endif
4344 }
4345
4346 CheckPrivateFieldIRGenerator::CheckPrivateFieldIRGenerator(
4347 JSContext* cx, HandleScript script, jsbytecode* pc, ICState state,
4348 CacheKind cacheKind, HandleValue idVal, HandleValue val)
4349 : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {
4350 MOZ_ASSERT(idVal.isSymbol() && idVal.toSymbol()->isPrivateName());
4351 }
4352
4353 AttachDecision CheckPrivateFieldIRGenerator::tryAttachStub() {
4354 AutoAssertNoPendingException aanpe(cx_);
4355
4356 ValOperandId valId(writer.setInputOperandId(0));
4357 ValOperandId keyId(writer.setInputOperandId(1));
4358
4359 if (!val_.isObject()) {
4360 trackAttached(IRGenerator::NotAttached);
4361 return AttachDecision::NoAction;
4362 }
4363 JSObject* obj = &val_.toObject();
4364 ObjOperandId objId = writer.guardToObject(valId);
4365 PropertyKey key = PropertyKey::Symbol(idVal_.toSymbol());
4366
4367 ThrowCondition condition;
4368 ThrowMsgKind msgKind;
4369 GetCheckPrivateFieldOperands(pc_, &condition, &msgKind);
4370
4371 PropertyResult prop;
4372 if (!LookupOwnPropertyPure(cx_, obj, key, &prop)) {
4373 return AttachDecision::NoAction;
4374 }
4375
4376 if (CheckPrivateFieldWillThrow(condition, prop.isFound())) {
4377 // Don't attach a stub if the operation will throw.
4378 return AttachDecision::NoAction;
4379 }
4380
4381 auto* nobj = &obj->as<NativeObject>();
4382
4383 TRY_ATTACH(tryAttachNative(nobj, objId, key, keyId, prop));
4384
4385 return AttachDecision::NoAction;
4386 }
4387
4388 AttachDecision CheckPrivateFieldIRGenerator::tryAttachNative(
4389 NativeObject* obj, ObjOperandId objId, jsid key, ValOperandId keyId,
4390 PropertyResult prop) {
4391 MOZ_ASSERT(prop.isNativeProperty() || prop.isNotFound());
4392
4393 emitIdGuard(keyId, idVal_, key);
4394 TestMatchingNativeReceiver(writer, obj, objId);
4395 writer.loadBooleanResult(prop.isFound());
4396 writer.returnFromIC();
4397
4398 trackAttached("CheckPrivateField.Native");
4399 return AttachDecision::Attach;
4400 }
4401
4402 void CheckPrivateFieldIRGenerator::trackAttached(const char* name) {
4403 stubName_ = name ? name : "NotAttached";
4404 #ifdef JS_CACHEIR_SPEW
4405 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
4406 sp.valueProperty("base", val_);
4407 sp.valueProperty("property", idVal_);
4408 }
4409 #endif
4410 }
4411
4412 bool IRGenerator::maybeGuardInt32Index(const Value& index, ValOperandId indexId,
4413 uint32_t* int32Index,
4414 Int32OperandId* int32IndexId) {
4415 if (index.isNumber()) {
4416 int32_t indexSigned;
4417 if (index.isInt32()) {
4418 indexSigned = index.toInt32();
4419 } else {
4420 // We allow negative zero here.
4421 if (!mozilla::NumberEqualsInt32(index.toDouble(), &indexSigned)) {
4422 return false;
4423 }
4424 }
4425
4426 if (indexSigned < 0) {
4427 return false;
4428 }
4429
4430 *int32Index = uint32_t(indexSigned);
4431 *int32IndexId = EmitGuardToInt32Index(writer, index, indexId);
4432 return true;
4433 }
4434
4435 if (index.isString()) {
4436 int32_t indexSigned = GetIndexFromString(index.toString());
4437 if (indexSigned < 0) {
4438 return false;
4439 }
4440
4441 StringOperandId strId = writer.guardToString(indexId);
4442 *int32Index = uint32_t(indexSigned);
4443 *int32IndexId = writer.guardStringToIndex(strId);
4444 return true;
4445 }
4446
4447 return false;
4448 }
4449
4450 SetPropIRGenerator::SetPropIRGenerator(JSContext* cx, HandleScript script,
4451 jsbytecode* pc, CacheKind cacheKind,
4452 ICState state, HandleValue lhsVal,
4453 HandleValue idVal, HandleValue rhsVal)
4454 : IRGenerator(cx, script, pc, cacheKind, state),
4455 lhsVal_(lhsVal),
4456 idVal_(idVal),
4457 rhsVal_(rhsVal) {}
4458
4459 AttachDecision SetPropIRGenerator::tryAttachStub() {
4460 AutoAssertNoPendingException aanpe(cx_);
4461
4462 ValOperandId objValId(writer.setInputOperandId(0));
4463 ValOperandId rhsValId;
4464 if (cacheKind_ == CacheKind::SetProp) {
4465 rhsValId = ValOperandId(writer.setInputOperandId(1));
4466 } else {
4467 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
4468 MOZ_ASSERT(setElemKeyValueId().id() == 1);
4469 writer.setInputOperandId(1);
4470 rhsValId = ValOperandId(writer.setInputOperandId(2));
4471 }
4472
4473 RootedId id(cx_);
4474 bool nameOrSymbol;
4475 if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
4476 cx_->clearPendingException();
4477 return AttachDecision::NoAction;
4478 }
4479
4480 if (lhsVal_.isObject()) {
4481 RootedObject obj(cx_, &lhsVal_.toObject());
4482
4483 ObjOperandId objId = writer.guardToObject(objValId);
4484 TRY_ATTACH(tryAttachSetTypedArrayElement(obj, objId, rhsValId));
4485 if (IsPropertySetOp(JSOp(*pc_))) {
4486 TRY_ATTACH(tryAttachMegamorphicSetElement(obj, objId, rhsValId));
4487 }
4488 if (nameOrSymbol) {
4489 TRY_ATTACH(tryAttachNativeSetSlot(obj, objId, id, rhsValId));
4490 if (IsPropertySetOp(JSOp(*pc_))) {
4491 TRY_ATTACH(tryAttachSetArrayLength(obj, objId, id, rhsValId));
4492 TRY_ATTACH(tryAttachSetter(obj, objId, id, rhsValId));
4493 TRY_ATTACH(tryAttachWindowProxy(obj, objId, id, rhsValId));
4494 TRY_ATTACH(tryAttachProxy(obj, objId, id, rhsValId));
4495 TRY_ATTACH(tryAttachMegamorphicSetSlot(obj, objId, id, rhsValId));
4496 }
4497 if (canAttachAddSlotStub(obj, id)) {
4498 deferType_ = DeferType::AddSlot;
4499 return AttachDecision::Deferred;
4500 }
4501 return AttachDecision::NoAction;
4502 }
4503
4504 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
4505
4506 if (IsPropertySetOp(JSOp(*pc_))) {
4507 TRY_ATTACH(tryAttachProxyElement(obj, objId, rhsValId));
4508 }
4509
4510 uint32_t index;
4511 Int32OperandId indexId;
4512 if (maybeGuardInt32Index(idVal_, setElemKeyValueId(), &index, &indexId)) {
4513 TRY_ATTACH(
4514 tryAttachSetDenseElement(obj, objId, index, indexId, rhsValId));
4515 TRY_ATTACH(
4516 tryAttachSetDenseElementHole(obj, objId, index, indexId, rhsValId));
4517 TRY_ATTACH(tryAttachAddOrUpdateSparseElement(obj, objId, index, indexId,
4518 rhsValId));
4519 return AttachDecision::NoAction;
4520 }
4521 }
4522 return AttachDecision::NoAction;
4523 }
4524
4525 static void EmitStoreSlotAndReturn(CacheIRWriter& writer, ObjOperandId objId,
4526 NativeObject* nobj, PropertyInfo prop,
4527 ValOperandId rhsId) {
4528 if (nobj->isFixedSlot(prop.slot())) {
4529 size_t offset = NativeObject::getFixedSlotOffset(prop.slot());
4530 writer.storeFixedSlot(objId, offset, rhsId);
4531 } else {
4532 size_t offset = nobj->dynamicSlotIndex(prop.slot()) * sizeof(Value);
4533 writer.storeDynamicSlot(objId, offset, rhsId);
4534 }
4535 writer.returnFromIC();
4536 }
4537
4538 static Maybe<PropertyInfo> LookupShapeForSetSlot(JSOp op, NativeObject* obj,
4539 jsid id) {
4540 Maybe<PropertyInfo> prop = obj->lookupPure(id);
4541 if (prop.isNothing() || !prop->isDataProperty() || !prop->writable()) {
4542 return mozilla::Nothing();
4543 }
4544
4545 // If this is a property init operation, the property's attributes may have to
4546 // be changed too, so make sure the current flags match.
4547 if (IsPropertyInitOp(op)) {
4548 // Don't support locked init operations.
4549 if (IsLockedInitOp(op)) {
4550 return mozilla::Nothing();
4551 }
4552
4553 // Can't redefine a non-configurable property.
4554 if (!prop->configurable()) {
4555 return mozilla::Nothing();
4556 }
4557
4558 // Make sure the enumerable flag matches the init operation.
4559 if (IsHiddenInitOp(op) == prop->enumerable()) {
4560 return mozilla::Nothing();
4561 }
4562 }
4563
4564 return prop;
4565 }
4566
4567 static bool CanAttachNativeSetSlot(JSOp op, JSObject* obj, PropertyKey id,
4568 Maybe<PropertyInfo>* prop) {
4569 if (!obj->is<NativeObject>()) {
4570 return false;
4571 }
4572
4573 if (Watchtower::watchesPropertyValueChange(&obj->as<NativeObject>())) {
4574 return false;
4575 }
4576
4577 *prop = LookupShapeForSetSlot(op, &obj->as<NativeObject>(), id);
4578 return prop->isSome();
4579 }
4580
4581 // There is no need to guard on the shape. Global lexical bindings are
4582 // non-configurable and can not be shadowed.
4583 static bool IsGlobalLexicalSetGName(JSOp op, NativeObject* obj,
4584 PropertyInfo prop) {
4585 // Ensure that the env can't change.
4586 if (op != JSOp::SetGName && op != JSOp::StrictSetGName) {
4587 return false;
4588 }
4589
4590 if (!obj->is<GlobalLexicalEnvironmentObject>()) {
4591 return false;
4592 }
4593
4594 // Uninitialized let bindings use a RuntimeLexicalErrorObject.
4595 MOZ_ASSERT(!obj->getSlot(prop.slot()).isMagic());
4596 MOZ_ASSERT(prop.writable());
4597 MOZ_ASSERT(!prop.configurable());
4598 return true;
4599 }
4600
4601 AttachDecision SetPropIRGenerator::tryAttachNativeSetSlot(HandleObject obj,
4602 ObjOperandId objId,
4603 HandleId id,
4604 ValOperandId rhsId) {
4605 Maybe<PropertyInfo> prop;
4606 if (!CanAttachNativeSetSlot(JSOp(*pc_), obj, id, &prop)) {
4607 return AttachDecision::NoAction;
4608 }
4609
4610 if (mode_ == ICState::Mode::Megamorphic && cacheKind_ == CacheKind::SetProp &&
4611 IsPropertySetOp(JSOp(*pc_))) {
4612 return AttachDecision::NoAction;
4613 }
4614
4615 maybeEmitIdGuard(id);
4616
4617 NativeObject* nobj = &obj->as<NativeObject>();
4618 if (!IsGlobalLexicalSetGName(JSOp(*pc_), nobj, *prop)) {
4619 TestMatchingNativeReceiver(writer, nobj, objId);
4620 }
4621 EmitStoreSlotAndReturn(writer, objId, nobj, *prop, rhsId);
4622
4623 trackAttached("SetProp.NativeSlot");
4624 return AttachDecision::Attach;
4625 }
4626
4627 static bool ValueCanConvertToNumeric(Scalar::Type type, const Value& val) {
4628 if (Scalar::isBigIntType(type)) {
4629 return val.isBigInt();
4630 }
4631 return val.isNumber() || val.isNullOrUndefined() || val.isBoolean() ||
4632 val.isString();
4633 }
4634
4635 OperandId IRGenerator::emitNumericGuard(ValOperandId valId, const Value& v,
4636 Scalar::Type type) {
4637 MOZ_ASSERT(ValueCanConvertToNumeric(type, v));
4638 switch (type) {
4639 case Scalar::Int8:
4640 case Scalar::Uint8:
4641 case Scalar::Int16:
4642 case Scalar::Uint16:
4643 case Scalar::Int32:
4644 case Scalar::Uint32: {
4645 if (v.isNumber()) {
4646 return writer.guardToInt32ModUint32(valId);
4647 }
4648 if (v.isNullOrUndefined()) {
4649 writer.guardIsNullOrUndefined(valId);
4650 return writer.loadInt32Constant(0);
4651 }
4652 if (v.isBoolean()) {
4653 return writer.guardBooleanToInt32(valId);
4654 }
4655 MOZ_ASSERT(v.isString());
4656 StringOperandId strId = writer.guardToString(valId);
4657 NumberOperandId numId = writer.guardStringToNumber(strId);
4658 return writer.truncateDoubleToUInt32(numId);
4659 }
4660
4661 case Scalar::Float16:
4662 case Scalar::Float32:
4663 case Scalar::Float64: {
4664 if (v.isNumber()) {
4665 return writer.guardIsNumber(valId);
4666 }
4667 if (v.isNull()) {
4668 writer.guardIsNull(valId);
4669 return writer.loadDoubleConstant(0.0);
4670 }
4671 if (v.isUndefined()) {
4672 writer.guardIsUndefined(valId);
4673 return writer.loadDoubleConstant(JS::GenericNaN());
4674 }
4675 if (v.isBoolean()) {
4676 BooleanOperandId boolId = writer.guardToBoolean(valId);
4677 return writer.booleanToNumber(boolId);
4678 }
4679 MOZ_ASSERT(v.isString());
4680 StringOperandId strId = writer.guardToString(valId);
4681 return writer.guardStringToNumber(strId);
4682 }
4683
4684 case Scalar::Uint8Clamped: {
4685 if (v.isNumber()) {
4686 return writer.guardToUint8Clamped(valId);
4687 }
4688 if (v.isNullOrUndefined()) {
4689 writer.guardIsNullOrUndefined(valId);
4690 return writer.loadInt32Constant(0);
4691 }
4692 if (v.isBoolean()) {
4693 return writer.guardBooleanToInt32(valId);
4694 }
4695 MOZ_ASSERT(v.isString());
4696 StringOperandId strId = writer.guardToString(valId);
4697 NumberOperandId numId = writer.guardStringToNumber(strId);
4698 return writer.doubleToUint8Clamped(numId);
4699 }
4700
4701 case Scalar::BigInt64:
4702 case Scalar::BigUint64:
4703 MOZ_ASSERT(v.isBigInt());
4704 return writer.guardToBigInt(valId);
4705
4706 case Scalar::MaxTypedArrayViewType:
4707 case Scalar::Int64:
4708 case Scalar::Simd128:
4709 break;
4710 }
4711 MOZ_CRASH("Unsupported TypedArray type");
4712 }
4713
4714 void SetPropIRGenerator::trackAttached(const char* name) {
4715 stubName_ = name ? name : "NotAttached";
4716 #ifdef JS_CACHEIR_SPEW
4717 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
4718 sp.opcodeProperty("op", JSOp(*pc_));
4719 sp.valueProperty("base", lhsVal_);
4720 sp.valueProperty("property", idVal_);
4721 sp.valueProperty("value", rhsVal_);
4722 }
4723 #endif
4724 }
4725
4726 static bool IsCacheableSetPropCallNative(NativeObject* obj,
4727 NativeObject* holder,
4728 PropertyInfo prop) {
4729 MOZ_ASSERT(IsCacheableProtoChain(obj, holder));
4730
4731 if (!prop.isAccessorProperty()) {
4732 return false;
4733 }
4734
4735 JSObject* setterObject = holder->getSetter(prop);
4736 if (!setterObject || !setterObject->is<JSFunction>()) {
4737 return false;
4738 }
4739
4740 JSFunction& setter = setterObject->as<JSFunction>();
4741 if (!setter.isNativeWithoutJitEntry()) {
4742 return false;
4743 }
4744
4745 if (setter.isClassConstructor()) {
4746 return false;
4747 }
4748
4749 return true;
4750 }
4751
4752 static bool IsCacheableSetPropCallScripted(NativeObject* obj,
4753 NativeObject* holder,
4754 PropertyInfo prop) {
4755 MOZ_ASSERT(IsCacheableProtoChain(obj, holder));
4756
4757 if (!prop.isAccessorProperty()) {
4758 return false;
4759 }
4760
4761 JSObject* setterObject = holder->getSetter(prop);
4762 if (!setterObject || !setterObject->is<JSFunction>()) {
4763 return false;
4764 }
4765
4766 JSFunction& setter = setterObject->as<JSFunction>();
4767 if (setter.isClassConstructor()) {
4768 return false;
4769 }
4770
4771 // Scripted functions and natives with JIT entry can use the scripted path.
4772 return setter.hasJitEntry();
4773 }
4774
4775 static bool CanAttachSetter(JSContext* cx, jsbytecode* pc, JSObject* obj,
4776 PropertyKey id, NativeObject** holder,
4777 Maybe<PropertyInfo>* propInfo) {
4778 // Don't attach a setter stub for ops like JSOp::InitElem.
4779 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc)));
4780
4781 PropertyResult prop;
4782 if (!LookupPropertyPure(cx, obj, id, holder, &prop)) {
4783 return false;
4784 }
4785 auto* nobj = &obj->as<NativeObject>();
4786
4787 if (!prop.isNativeProperty()) {
4788 return false;
4789 }
4790
4791 if (!IsCacheableSetPropCallScripted(nobj, *holder, prop.propertyInfo()) &&
4792 !IsCacheableSetPropCallNative(nobj, *holder, prop.propertyInfo())) {
4793 return false;
4794 }
4795
4796 *propInfo = mozilla::Some(prop.propertyInfo());
4797 return true;
4798 }
4799
4800 static void EmitCallSetterNoGuards(JSContext* cx, CacheIRWriter& writer,
4801 NativeObject* obj, NativeObject* holder,
4802 PropertyInfo prop, ObjOperandId receiverId,
4803 ValOperandId rhsId) {
4804 JSFunction* target = &holder->getSetter(prop)->as<JSFunction>();
4805 bool sameRealm = cx->realm() == target->realm();
4806
4807 if (target->isNativeWithoutJitEntry()) {
4808 MOZ_ASSERT(IsCacheableSetPropCallNative(obj, holder, prop));
4809 writer.callNativeSetter(receiverId, target, rhsId, sameRealm);
4810 writer.returnFromIC();
4811 return;
4812 }
4813
4814 MOZ_ASSERT(IsCacheableSetPropCallScripted(obj, holder, prop));
4815 writer.callScriptedSetter(receiverId, target, rhsId, sameRealm);
4816 writer.returnFromIC();
4817 }
4818
4819 static void EmitCallDOMSetterNoGuards(JSContext* cx, CacheIRWriter& writer,
4820 NativeObject* holder, PropertyInfo prop,
4821 ObjOperandId objId, ValOperandId rhsId) {
4822 JSFunction* setter = &holder->getSetter(prop)->as<JSFunction>();
4823 MOZ_ASSERT(cx->realm() == setter->realm());
4824
4825 writer.callDOMSetter(objId, setter->jitInfo(), rhsId);
4826 writer.returnFromIC();
4827 }
4828
4829 AttachDecision SetPropIRGenerator::tryAttachSetter(HandleObject obj,
4830 ObjOperandId objId,
4831 HandleId id,
4832 ValOperandId rhsId) {
4833 // Don't attach a setter stub for ops like JSOp::InitElem.
4834 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
4835
4836 NativeObject* holder = nullptr;
4837 Maybe<PropertyInfo> prop;
4838 if (!CanAttachSetter(cx_, pc_, obj, id, &holder, &prop)) {
4839 return AttachDecision::NoAction;
4840 }
4841 auto* nobj = &obj->as<NativeObject>();
4842
4843 bool needsWindowProxy =
4844 IsWindow(nobj) && SetterNeedsWindowProxyThis(holder, *prop);
4845
4846 maybeEmitIdGuard(id);
4847
4848 // Use the megamorphic guard if we're in megamorphic mode, except if |obj|
4849 // is a Window as GuardHasGetterSetter doesn't support this yet (Window may
4850 // require outerizing).
4851 if (mode_ == ICState::Mode::Specialized || IsWindow(nobj)) {
4852 TestMatchingNativeReceiver(writer, nobj, objId);
4853
4854 if (nobj != holder) {
4855 GeneratePrototypeGuards(writer, nobj, holder, objId);
4856
4857 // Guard on the holder's shape.
4858 ObjOperandId holderId = writer.loadObject(holder);
4859 TestMatchingHolder(writer, holder, holderId);
4860
4861 EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
4862 /* holderIsConstant = */ true);
4863 } else {
4864 EmitGuardGetterSetterSlot(writer, holder, *prop, objId);
4865 }
4866 } else {
4867 GetterSetter* gs = holder->getGetterSetter(*prop);
4868 writer.guardHasGetterSetter(objId, id, gs);
4869 }
4870
4871 if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Setter, nobj, holder, *prop,
4872 mode_)) {
4873 MOZ_ASSERT(!needsWindowProxy);
4874 EmitCallDOMSetterNoGuards(cx_, writer, holder, *prop, objId, rhsId);
4875
4876 trackAttached("SetProp.DOMSetter");
4877 return AttachDecision::Attach;
4878 }
4879
4880 ObjOperandId receiverId;
4881 if (needsWindowProxy) {
4882 MOZ_ASSERT(cx_->global()->maybeWindowProxy());
4883 receiverId = writer.loadObject(cx_->global()->maybeWindowProxy());
4884 } else {
4885 receiverId = objId;
4886 }
4887 EmitCallSetterNoGuards(cx_, writer, nobj, holder, *prop, receiverId, rhsId);
4888
4889 trackAttached("SetProp.Setter");
4890 return AttachDecision::Attach;
4891 }
4892
4893 AttachDecision SetPropIRGenerator::tryAttachSetArrayLength(HandleObject obj,
4894 ObjOperandId objId,
4895 HandleId id,
4896 ValOperandId rhsId) {
4897 // Don't attach an array length stub for ops like JSOp::InitElem.
4898 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
4899
4900 if (!obj->is<ArrayObject>() || !id.isAtom(cx_->names().length) ||
4901 !obj->as<ArrayObject>().lengthIsWritable()) {
4902 return AttachDecision::NoAction;
4903 }
4904
4905 maybeEmitIdGuard(id);
4906 emitOptimisticClassGuard(objId, obj, GuardClassKind::Array);
4907 writer.callSetArrayLength(objId, IsStrictSetPC(pc_), rhsId);
4908 writer.returnFromIC();
4909
4910 trackAttached("SetProp.ArrayLength");
4911 return AttachDecision::Attach;
4912 }
4913
4914 AttachDecision SetPropIRGenerator::tryAttachSetDenseElement(
4915 HandleObject obj, ObjOperandId objId, uint32_t index,
4916 Int32OperandId indexId, ValOperandId rhsId) {
4917 if (!obj->is<NativeObject>()) {
4918 return AttachDecision::NoAction;
4919 }
4920
4921 NativeObject* nobj = &obj->as<NativeObject>();
4922 if (!nobj->containsDenseElement(index) || nobj->denseElementsAreFrozen()) {
4923 return AttachDecision::NoAction;
4924 }
4925
4926 // Setting holes requires extra code for marking the elements non-packed.
4927 MOZ_ASSERT(!rhsVal_.isMagic(JS_ELEMENTS_HOLE));
4928
4929 JSOp op = JSOp(*pc_);
4930
4931 // We don't currently emit locked init for any indexed properties.
4932 MOZ_ASSERT(!IsLockedInitOp(op));
4933
4934 // We don't currently emit hidden init for any existing indexed properties.
4935 MOZ_ASSERT(!IsHiddenInitOp(op));
4936
4937 // Don't optimize InitElem (DefineProperty) on non-extensible objects: when
4938 // the elements are sealed, we have to throw an exception. Note that we have
4939 // to check !isExtensible instead of denseElementsAreSealed because sealing
4940 // a (non-extensible) object does not necessarily trigger a Shape change.
4941 if (IsPropertyInitOp(op) && !nobj->isExtensible()) {
4942 return AttachDecision::NoAction;
4943 }
4944
4945 TestMatchingNativeReceiver(writer, nobj, objId);
4946
4947 writer.storeDenseElement(objId, indexId, rhsId);
4948 writer.returnFromIC();
4949
4950 trackAttached("SetProp.DenseElement");
4951 return AttachDecision::Attach;
4952 }
4953
4954 static bool CanAttachAddElement(NativeObject* obj, bool isInit,
4955 AllowIndexedReceiver allowIndexedReceiver) {
4956 MOZ_ASSERT(!obj->is<TypedArrayObject>());
4957
4958 // Make sure the receiver doesn't have any indexed properties and that such
4959 // properties can't appear without a shape change.
4960 if (allowIndexedReceiver == AllowIndexedReceiver::No && obj->isIndexed()) {
4961 return false;
4962 }
4963
4964 do {
4965 // This check is also relevant for the receiver object.
4966 const JSClass* clasp = obj->getClass();
4967 if (clasp != &ArrayObject::class_ &&
4968 (clasp->getAddProperty() || clasp->getResolve() ||
4969 clasp->getOpsLookupProperty() || clasp->getOpsSetProperty())) {
4970 return false;
4971 }
4972
4973 // If we're initializing a property instead of setting one, the objects
4974 // on the prototype are not relevant.
4975 if (isInit) {
4976 break;
4977 }
4978
4979 JSObject* proto = obj->staticPrototype();
4980 if (!proto) {
4981 break;
4982 }
4983
4984 if (!proto->is<NativeObject>()) {
4985 return false;
4986 }
4987
4988 // We shouldn't add an element if the index is OOB for a typed array on the
4989 // prototype chain.
4990 if (proto->is<TypedArrayObject>()) {
4991 return false;
4992 }
4993
4994 NativeObject* nproto = &proto->as<NativeObject>();
4995 if (nproto->isIndexed()) {
4996 return false;
4997 }
4998
4999 // We have to make sure the proto has no non-writable (frozen) elements
5000 // because we're not allowed to shadow them.
5001 if (nproto->denseElementsAreFrozen() &&
5002 nproto->getDenseInitializedLength() > 0) {
5003 return false;
5004 }
5005
5006 obj = nproto;
5007 } while (true);
5008
5009 return true;
5010 }
5011
5012 AttachDecision SetPropIRGenerator::tryAttachSetDenseElementHole(
5013 HandleObject obj, ObjOperandId objId, uint32_t index,
5014 Int32OperandId indexId, ValOperandId rhsId) {
5015 if (!obj->is<NativeObject>()) {
5016 return AttachDecision::NoAction;
5017 }
5018
5019 // Setting holes requires extra code for marking the elements non-packed.
5020 if (rhsVal_.isMagic(JS_ELEMENTS_HOLE)) {
5021 return AttachDecision::NoAction;
5022 }
5023
5024 JSOp op = JSOp(*pc_);
5025 MOZ_ASSERT(IsPropertySetOp(op) || IsPropertyInitOp(op));
5026
5027 // We don't currently emit locked init for any indexed properties.
5028 MOZ_ASSERT(!IsLockedInitOp(op));
5029
5030 // Hidden init can be emitted for absent indexed properties.
5031 if (IsHiddenInitOp(op)) {
5032 MOZ_ASSERT(op == JSOp::InitHiddenElem);
5033 return AttachDecision::NoAction;
5034 }
5035
5036 NativeObject* nobj = &obj->as<NativeObject>();
5037 if (!nobj->isExtensible()) {
5038 return AttachDecision::NoAction;
5039 }
5040
5041 MOZ_ASSERT(!nobj->denseElementsAreFrozen(),
5042 "Extensible objects should not have frozen elements");
5043
5044 uint32_t initLength = nobj->getDenseInitializedLength();
5045 uint32_t capacity = nobj->getDenseCapacity();
5046
5047 // Optimize if:
5048 // a) we're adding an element inside capacity, or one element past.
5049 // b) we're writing to a hole inside initLength.
5050 bool isAdd = index >= initLength && index <= capacity;
5051 bool isHoleInBounds =
5052 index < initLength && !nobj->containsDenseElement(index);
5053 if (!isAdd && !isHoleInBounds) {
5054 return AttachDecision::NoAction;
5055 }
5056
5057 // Can't add new elements to arrays with non-writable length.
5058 if (isAdd && nobj->is<ArrayObject>() &&
5059 !nobj->as<ArrayObject>().lengthIsWritable()) {
5060 return AttachDecision::NoAction;
5061 }
5062
5063 // Typed arrays don't have dense elements.
5064 if (nobj->is<TypedArrayObject>()) {
5065 return AttachDecision::NoAction;
5066 }
5067
5068 // Check for other indexed properties or class hooks.
5069 if (!CanAttachAddElement(nobj, IsPropertyInitOp(op),
5070 AllowIndexedReceiver::No)) {
5071 return AttachDecision::NoAction;
5072 }
5073
5074 TestMatchingNativeReceiver(writer, nobj, objId);
5075
5076 // Also shape guard the proto chain, unless this is an InitElem.
5077 if (IsPropertySetOp(op)) {
5078 ShapeGuardProtoChain(writer, nobj, objId);
5079 }
5080
5081 writer.storeDenseElementHole(objId, indexId, rhsId, isAdd);
5082 writer.returnFromIC();
5083
5084 trackAttached(isAdd ? "AddDenseElement" : "StoreDenseElementHole");
5085 return AttachDecision::Attach;
5086 }
5087
5088 // Add an IC for adding or updating a sparse element.
5089 AttachDecision SetPropIRGenerator::tryAttachAddOrUpdateSparseElement(
5090 HandleObject obj, ObjOperandId objId, uint32_t index,
5091 Int32OperandId indexId, ValOperandId rhsId) {
5092 JSOp op = JSOp(*pc_);
5093 MOZ_ASSERT(IsPropertySetOp(op) || IsPropertyInitOp(op));
5094
5095 if (op != JSOp::SetElem && op != JSOp::StrictSetElem) {
5096 return AttachDecision::NoAction;
5097 }
5098
5099 if (!obj->is<NativeObject>()) {
5100 return AttachDecision::NoAction;
5101 }
5102 NativeObject* nobj = &obj->as<NativeObject>();
5103
5104 // We cannot attach a stub to a non-extensible object
5105 if (!nobj->isExtensible()) {
5106 return AttachDecision::NoAction;
5107 }
5108
5109 // Stub doesn't handle negative indices.
5110 if (index > INT32_MAX) {
5111 return AttachDecision::NoAction;
5112 }
5113
5114 // The index must not be for a dense element.
5115 if (nobj->containsDenseElement(index)) {
5116 return AttachDecision::NoAction;
5117 }
5118
5119 // Only handle ArrayObject and PlainObject in this stub.
5120 if (!nobj->is<ArrayObject>() && !nobj->is<PlainObject>()) {
5121 return AttachDecision::NoAction;
5122 }
5123
5124 // Don't attach if we're adding to an array with non-writable length.
5125 if (nobj->is<ArrayObject>()) {
5126 ArrayObject* aobj = &nobj->as<ArrayObject>();
5127 bool isAdd = (index >= aobj->length());
5128 if (isAdd && !aobj->lengthIsWritable()) {
5129 return AttachDecision::NoAction;
5130 }
5131 }
5132
5133 // Check for class hooks or indexed properties on the prototype chain that
5134 // we're not allowed to shadow.
5135 if (!CanAttachAddElement(nobj, /* isInit = */ false,
5136 AllowIndexedReceiver::Yes)) {
5137 return AttachDecision::NoAction;
5138 }
5139
5140 // Ensure that obj is an ArrayObject or PlainObject.
5141 if (nobj->is<ArrayObject>()) {
5142 writer.guardClass(objId, GuardClassKind::Array);
5143 } else {
5144 MOZ_ASSERT(nobj->is<PlainObject>());
5145 writer.guardClass(objId, GuardClassKind::PlainObject);
5146 }
5147
5148 // The helper we are going to call only applies to non-dense elements.
5149 writer.guardIndexIsNotDenseElement(objId, indexId);
5150
5151 // Guard extensible: We may be trying to add a new element, and so we'd best
5152 // be able to do so safely.
5153 writer.guardIsExtensible(objId);
5154
5155 // Ensures we are able to efficiently able to map to an integral jsid.
5156 writer.guardInt32IsNonNegative(indexId);
5157
5158 // Shape guard the prototype chain to avoid shadowing indexes from appearing.
5159 // Guard the prototype of the receiver explicitly, because the receiver's
5160 // shape is not being guarded as a proxy for that.
5161 GuardReceiverProto(writer, nobj, objId);
5162
5163 // Dense elements may appear on the prototype chain (and prototypes may
5164 // have a different notion of which elements are dense), but they can
5165 // only be data properties, so our specialized Set handler is ok to bind
5166 // to them.
5167 if (IsPropertySetOp(op)) {
5168 ShapeGuardProtoChain(writer, nobj, objId);
5169 }
5170
5171 // Ensure that if we're adding an element to the object, the object's
5172 // length is writable.
5173 if (nobj->is<ArrayObject>()) {
5174 writer.guardIndexIsValidUpdateOrAdd(objId, indexId);
5175 }
5176
5177 writer.callAddOrUpdateSparseElementHelper(
5178 objId, indexId, rhsId,
5179 /* strict = */ op == JSOp::StrictSetElem);
5180 writer.returnFromIC();
5181
5182 trackAttached("SetProp.AddOrUpdateSparseElement");
5183 return AttachDecision::Attach;
5184 }
5185
5186 AttachDecision SetPropIRGenerator::tryAttachSetTypedArrayElement(
5187 HandleObject obj, ObjOperandId objId, ValOperandId rhsId) {
5188 if (!obj->is<TypedArrayObject>()) {
5189 return AttachDecision::NoAction;
5190 }
5191 if (!idVal_.isNumber()) {
5192 return AttachDecision::NoAction;
5193 }
5194
5195 auto* tarr = &obj->as<TypedArrayObject>();
5196 Scalar::Type elementType = tarr->type();
5197
5198 // Don't attach if the input type doesn't match the guard added below.
5199 if (!ValueCanConvertToNumeric(elementType, rhsVal_)) {
5200 return AttachDecision::NoAction;
5201 }
5202
5203 bool handleOOB = false;
5204 int64_t indexInt64;
5205 if (!ValueIsInt64Index(idVal_, &indexInt64) || indexInt64 < 0 ||
5206 uint64_t(indexInt64) >= tarr->length().valueOr(0)) {
5207 handleOOB = true;
5208 }
5209
5210 JSOp op = JSOp(*pc_);
5211
5212 // The only expected property init operation is InitElem.
5213 MOZ_ASSERT_IF(IsPropertyInitOp(op), op == JSOp::InitElem);
5214
5215 // InitElem (DefineProperty) has to throw an exception on out-of-bounds.
5216 if (handleOOB && IsPropertyInitOp(op)) {
5217 return AttachDecision::NoAction;
5218 }
5219
5220 writer.guardShapeForClass(objId, tarr->shape());
5221
5222 OperandId rhsValId = emitNumericGuard(rhsId, rhsVal_, elementType);
5223
5224 ValOperandId keyId = setElemKeyValueId();
5225 IntPtrOperandId indexId = guardToIntPtrIndex(idVal_, keyId, handleOOB);
5226
5227 auto viewKind = ToArrayBufferViewKind(tarr);
5228 writer.storeTypedArrayElement(objId, elementType, indexId, rhsValId,
5229 handleOOB, viewKind);
5230 writer.returnFromIC();
5231
5232 trackAttached(handleOOB ? "SetTypedElementOOB" : "SetTypedElement");
5233 return AttachDecision::Attach;
5234 }
5235
5236 AttachDecision SetPropIRGenerator::tryAttachGenericProxy(
5237 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
5238 ValOperandId rhsId, bool handleDOMProxies) {
5239 // Don't attach a proxy stub for ops like JSOp::InitElem.
5240 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5241
5242 writer.guardIsProxy(objId);
5243
5244 if (!handleDOMProxies) {
5245 // Ensure that the incoming object is not a DOM proxy, so that we can
5246 // get to the specialized stubs. If handleDOMProxies is true, we were
5247 // unable to attach a specialized DOM stub, so we just handle all
5248 // proxies here.
5249 writer.guardIsNotDOMProxy(objId);
5250 }
5251
5252 if (cacheKind_ == CacheKind::SetProp || mode_ == ICState::Mode::Specialized) {
5253 maybeEmitIdGuard(id);
5254 writer.proxySet(objId, id, rhsId, IsStrictSetPC(pc_));
5255 } else {
5256 // Attach a stub that handles every id.
5257 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
5258 MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
5259 writer.proxySetByValue(objId, setElemKeyValueId(), rhsId,
5260 IsStrictSetPC(pc_));
5261 }
5262
5263 writer.returnFromIC();
5264
5265 trackAttached("SetProp.GenericProxy");
5266 return AttachDecision::Attach;
5267 }
5268
5269 AttachDecision SetPropIRGenerator::tryAttachDOMProxyShadowed(
5270 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
5271 ValOperandId rhsId) {
5272 // Don't attach a proxy stub for ops like JSOp::InitElem.
5273 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5274
5275 MOZ_ASSERT(IsCacheableDOMProxy(obj));
5276
5277 maybeEmitIdGuard(id);
5278 TestMatchingProxyReceiver(writer, obj, objId);
5279 writer.proxySet(objId, id, rhsId, IsStrictSetPC(pc_));
5280 writer.returnFromIC();
5281
5282 trackAttached("SetProp.DOMProxyShadowed");
5283 return AttachDecision::Attach;
5284 }
5285
5286 AttachDecision SetPropIRGenerator::tryAttachDOMProxyUnshadowed(
5287 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
5288 ValOperandId rhsId) {
5289 // Don't attach a proxy stub for ops like JSOp::InitElem.
5290 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5291
5292 MOZ_ASSERT(IsCacheableDOMProxy(obj));
5293
5294 JSObject* proto = obj->staticPrototype();
5295 if (!proto) {
5296 return AttachDecision::NoAction;
5297 }
5298
5299 NativeObject* holder = nullptr;
5300 Maybe<PropertyInfo> prop;
5301 if (!CanAttachSetter(cx_, pc_, proto, id, &holder, &prop)) {
5302 return AttachDecision::NoAction;
5303 }
5304 auto* nproto = &proto->as<NativeObject>();
5305
5306 maybeEmitIdGuard(id);
5307
5308 // Guard that our proxy (expando) object hasn't started shadowing this
5309 // property.
5310 TestMatchingProxyReceiver(writer, obj, objId);
5311 bool canOptimizeMissing = false;
5312 CheckDOMProxyDoesNotShadow(writer, obj, id, objId, &canOptimizeMissing);
5313
5314 GeneratePrototypeGuards(writer, obj, holder, objId);
5315
5316 // Guard on the holder of the property.
5317 ObjOperandId holderId = writer.loadObject(holder);
5318 TestMatchingHolder(writer, holder, holderId);
5319
5320 EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
5321 /* holderIsConstant = */ true);
5322
5323 // EmitCallSetterNoGuards expects |obj| to be the object the property is
5324 // on to do some checks. Since we actually looked at proto, and no extra
5325 // guards will be generated, we can just pass that instead.
5326 EmitCallSetterNoGuards(cx_, writer, nproto, holder, *prop, objId, rhsId);
5327
5328 trackAttached("SetProp.DOMProxyUnshadowed");
5329 return AttachDecision::Attach;
5330 }
5331
5332 AttachDecision SetPropIRGenerator::tryAttachDOMProxyExpando(
5333 Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
5334 ValOperandId rhsId) {
5335 // Don't attach a proxy stub for ops like JSOp::InitElem.
5336 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5337
5338 MOZ_ASSERT(IsCacheableDOMProxy(obj));
5339
5340 Value expandoVal = GetProxyPrivate(obj);
5341 JSObject* expandoObj;
5342 if (expandoVal.isObject()) {
5343 expandoObj = &expandoVal.toObject();
5344 } else {
5345 MOZ_ASSERT(!expandoVal.isUndefined(),
5346 "How did a missing expando manage to shadow things?");
5347 auto expandoAndGeneration =
5348 static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
5349 MOZ_ASSERT(expandoAndGeneration);
5350 expandoObj = &expandoAndGeneration->expando.toObject();
5351 }
5352
5353 Maybe<PropertyInfo> prop;
5354 if (CanAttachNativeSetSlot(JSOp(*pc_), expandoObj, id, &prop)) {
5355 auto* nativeExpandoObj = &expandoObj->as<NativeObject>();
5356
5357 maybeEmitIdGuard(id);
5358 ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
5359 obj, objId, expandoVal, nativeExpandoObj);
5360
5361 EmitStoreSlotAndReturn(writer, expandoObjId, nativeExpandoObj, *prop,
5362 rhsId);
5363 trackAttached("SetProp.DOMProxyExpandoSlot");
5364 return AttachDecision::Attach;
5365 }
5366
5367 NativeObject* holder = nullptr;
5368 if (CanAttachSetter(cx_, pc_, expandoObj, id, &holder, &prop)) {
5369 auto* nativeExpandoObj = &expandoObj->as<NativeObject>();
5370
5371 // Call the setter. Note that we pass objId, the DOM proxy, as |this|
5372 // and not the expando object.
5373 maybeEmitIdGuard(id);
5374 ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
5375 obj, objId, expandoVal, nativeExpandoObj);
5376
5377 MOZ_ASSERT(holder == nativeExpandoObj);
5378 EmitGuardGetterSetterSlot(writer, nativeExpandoObj, *prop, expandoObjId);
5379 EmitCallSetterNoGuards(cx_, writer, nativeExpandoObj, nativeExpandoObj,
5380 *prop, objId, rhsId);
5381 trackAttached("SetProp.DOMProxyExpandoSetter");
5382 return AttachDecision::Attach;
5383 }
5384
5385 return AttachDecision::NoAction;
5386 }
5387
5388 AttachDecision SetPropIRGenerator::tryAttachProxy(HandleObject obj,
5389 ObjOperandId objId,
5390 HandleId id,
5391 ValOperandId rhsId) {
5392 // Don't attach a proxy stub for ops like JSOp::InitElem.
5393 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5394
5395 ProxyStubType type = GetProxyStubType(cx_, obj, id);
5396 if (type == ProxyStubType::None) {
5397 return AttachDecision::NoAction;
5398 }
5399 auto proxy = obj.as<ProxyObject>();
5400
5401 if (mode_ == ICState::Mode::Megamorphic) {
5402 return tryAttachGenericProxy(proxy, objId, id, rhsId,
5403 /* handleDOMProxies = */ true);
5404 }
5405
5406 switch (type) {
5407 case ProxyStubType::None:
5408 break;
5409 case ProxyStubType::DOMExpando:
5410 TRY_ATTACH(tryAttachDOMProxyExpando(proxy, objId, id, rhsId));
5411 [[fallthrough]]; // Fall through to the generic shadowed case.
5412 case ProxyStubType::DOMShadowed:
5413 return tryAttachDOMProxyShadowed(proxy, objId, id, rhsId);
5414 case ProxyStubType::DOMUnshadowed:
5415 TRY_ATTACH(tryAttachDOMProxyUnshadowed(proxy, objId, id, rhsId));
5416 return tryAttachGenericProxy(proxy, objId, id, rhsId,
5417 /* handleDOMProxies = */ true);
5418 case ProxyStubType::Generic:
5419 return tryAttachGenericProxy(proxy, objId, id, rhsId,
5420 /* handleDOMProxies = */ false);
5421 }
5422
5423 MOZ_CRASH("Unexpected ProxyStubType");
5424 }
5425
5426 AttachDecision SetPropIRGenerator::tryAttachProxyElement(HandleObject obj,
5427 ObjOperandId objId,
5428 ValOperandId rhsId) {
5429 // Don't attach a proxy stub for ops like JSOp::InitElem.
5430 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5431
5432 if (!obj->is<ProxyObject>()) {
5433 return AttachDecision::NoAction;
5434 }
5435
5436 writer.guardIsProxy(objId);
5437
5438 // Like GetPropIRGenerator::tryAttachProxyElement, don't check for DOM
5439 // proxies here as we don't have specialized DOM stubs for this.
5440 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
5441 writer.proxySetByValue(objId, setElemKeyValueId(), rhsId, IsStrictSetPC(pc_));
5442 writer.returnFromIC();
5443
5444 trackAttached("SetProp.ProxyElement");
5445 return AttachDecision::Attach;
5446 }
5447
5448 AttachDecision SetPropIRGenerator::tryAttachMegamorphicSetElement(
5449 HandleObject obj, ObjOperandId objId, ValOperandId rhsId) {
5450 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5451
5452 if (mode_ != ICState::Mode::Megamorphic || cacheKind_ != CacheKind::SetElem) {
5453 return AttachDecision::NoAction;
5454 }
5455
5456 // The generic proxy stubs are faster.
5457 if (obj->is<ProxyObject>()) {
5458 return AttachDecision::NoAction;
5459 }
5460
5461 writer.megamorphicSetElement(objId, setElemKeyValueId(), rhsId,
5462 IsStrictSetPC(pc_));
5463 writer.returnFromIC();
5464
5465 trackAttached("SetProp.MegamorphicSetElement");
5466 return AttachDecision::Attach;
5467 }
5468
5469 AttachDecision SetPropIRGenerator::tryAttachMegamorphicSetSlot(
5470 HandleObject obj, ObjOperandId objId, HandleId id, ValOperandId rhsId) {
5471 if (mode_ != ICState::Mode::Megamorphic || cacheKind_ != CacheKind::SetProp) {
5472 return AttachDecision::NoAction;
5473 }
5474
5475 writer.megamorphicStoreSlot(objId, id, rhsId, IsStrictSetPC(pc_));
5476 writer.returnFromIC();
5477 trackAttached("SetProp.MegamorphicNativeSlot");
5478 return AttachDecision::Attach;
5479 }
5480
5481 AttachDecision SetPropIRGenerator::tryAttachWindowProxy(HandleObject obj,
5482 ObjOperandId objId,
5483 HandleId id,
5484 ValOperandId rhsId) {
5485 // Don't attach a window proxy stub for ops like JSOp::InitElem.
5486 MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));
5487
5488 // Attach a stub when the receiver is a WindowProxy and we can do the set
5489 // on the Window (the global object).
5490
5491 if (!IsWindowProxyForScriptGlobal(script_, obj)) {
5492 return AttachDecision::NoAction;
5493 }
5494
5495 // If we're megamorphic prefer a generic proxy stub that handles a lot more
5496 // cases.
5497 if (mode_ == ICState::Mode::Megamorphic) {
5498 return AttachDecision::NoAction;
5499 }
5500
5501 // Now try to do the set on the Window (the current global).
5502 GlobalObject* windowObj = cx_->global();
5503
5504 Maybe<PropertyInfo> prop;
5505 if (!CanAttachNativeSetSlot(JSOp(*pc_), windowObj, id, &prop)) {
5506 return AttachDecision::NoAction;
5507 }
5508
5509 maybeEmitIdGuard(id);
5510
5511 ObjOperandId windowObjId =
5512 GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
5513 writer.guardShape(windowObjId, windowObj->shape());
5514
5515 EmitStoreSlotAndReturn(writer, windowObjId, windowObj, *prop, rhsId);
5516
5517 trackAttached("SetProp.WindowProxySlot");
5518 return AttachDecision::Attach;
5519 }
5520
5521 // Detect if |id| refers to the 'prototype' property of a function object. This
5522 // property is special-cased in canAttachAddSlotStub().
5523 static bool IsFunctionPrototype(const JSAtomState& names, JSObject* obj,
5524 PropertyKey id) {
5525 return obj->is<JSFunction>() && id.isAtom(names.prototype);
5526 }
5527
5528 bool SetPropIRGenerator::canAttachAddSlotStub(HandleObject obj, HandleId id) {
5529 if (!obj->is<NativeObject>()) {
5530 return false;
5531 }
5532 auto* nobj = &obj->as<NativeObject>();
5533
5534 // Special-case JSFunction resolve hook to allow redefining the 'prototype'
5535 // property without triggering lazy expansion of property and object
5536 // allocation.
5537 if (IsFunctionPrototype(cx_->names(), nobj, id)) {
5538 MOZ_ASSERT(ClassMayResolveId(cx_->names(), nobj->getClass(), id, nobj));
5539
5540 // We're only interested in functions that have a builtin .prototype
5541 // property (needsPrototypeProperty). The stub will guard on this because
5542 // the builtin .prototype property is non-configurable/non-enumerable and it
5543 // would be wrong to add a property with those attributes to a function that
5544 // doesn't have a builtin .prototype.
5545 //
5546 // Inlining needsPrototypeProperty in JIT code is complicated so we use
5547 // isNonBuiltinConstructor as a stronger condition that's easier to check
5548 // from JIT code.
5549 JSFunction* fun = &nobj->as<JSFunction>();
5550 if (!fun->isNonBuiltinConstructor()) {
5551 return false;
5552 }
5553 MOZ_ASSERT(fun->needsPrototypeProperty());
5554
5555 // If property exists this isn't an "add".
5556 if (fun->lookupPure(id)) {
5557 return false;
5558 }
5559 } else {
5560 // Normal Case: If property exists or is an OOB typed array index, this
5561 // isn't an "add".
5562 PropertyResult prop;
5563 if (!LookupOwnPropertyPure(cx_, nobj, id, &prop)) {
5564 return false;
5565 }
5566 if (prop.isFound() || prop.isTypedArrayOutOfRange()) {
5567 return false;
5568 }
5569 }
5570
5571 // For now we don't optimize Watchtower-monitored objects.
5572 if (Watchtower::watchesPropertyAdd(nobj)) {
5573 return false;
5574 }
5575
5576 // Object must be extensible, or we must be initializing a private
5577 // elem.
5578 bool canAddNewProperty = nobj->isExtensible() || id.isPrivateName();
5579 if (!canAddNewProperty) {
5580 return false;
5581 }
5582
5583 JSOp op = JSOp(*pc_);
5584 if (IsPropertyInitOp(op)) {
5585 return true;
5586 }
5587
5588 MOZ_ASSERT(IsPropertySetOp(op));
5589
5590 // Walk up the object prototype chain and ensure that all prototypes are
5591 // native, and that all prototypes have no setter defined on the property.
5592 for (JSObject* proto = nobj->staticPrototype(); proto;
5593 proto = proto->staticPrototype()) {
5594 if (!proto->is<NativeObject>()) {
5595 return false;
5596 }
5597
5598 // If prototype defines this property in a non-plain way, don't optimize.
5599 Maybe<PropertyInfo> protoProp = proto->as<NativeObject>().lookup(cx_, id);
5600 if (protoProp.isSome() && !protoProp->isDataProperty()) {
5601 return false;
5602 }
5603
5604 // Otherwise, if there's no such property, watch out for a resolve hook
5605 // that would need to be invoked and thus prevent inlining of property
5606 // addition. Allow the JSFunction resolve hook as it only defines plain
5607 // data properties and we don't need to invoke it for objects on the
5608 // proto chain.
5609 if (ClassMayResolveId(cx_->names(), proto->getClass(), id, proto) &&
5610 !proto->is<JSFunction>()) {
5611 return false;
5612 }
5613 }
5614
5615 return true;
5616 }
5617
5618 static PropertyFlags SetPropertyFlags(JSOp op, bool isFunctionPrototype) {
5619 // Locked properties are non-writable, non-enumerable, and non-configurable.
5620 if (IsLockedInitOp(op)) {
5621 return {};
5622 }
5623
5624 // Hidden properties are writable, non-enumerable, and configurable.
5625 if (IsHiddenInitOp(op)) {
5626 return {
5627 PropertyFlag::Writable,
5628 PropertyFlag::Configurable,
5629 };
5630 }
5631
5632 // This is a special case to overwrite an unresolved function.prototype
5633 // property. The initial property flags of this property are writable,
5634 // non-enumerable, and non-configurable. See canAttachAddSlotStub.
5635 if (isFunctionPrototype) {
5636 return {
5637 PropertyFlag::Writable,
5638 };
5639 }
5640
5641 // Other properties are writable, enumerable, and configurable.
5642 return PropertyFlags::defaultDataPropFlags;
5643 }
5644
5645 AttachDecision SetPropIRGenerator::tryAttachAddSlotStub(
5646 Handle<Shape*> oldShape) {
5647 ValOperandId objValId(writer.setInputOperandId(0));
5648 ValOperandId rhsValId;
5649 if (cacheKind_ == CacheKind::SetProp) {
5650 rhsValId = ValOperandId(writer.setInputOperandId(1));
5651 } else {
5652 MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
5653 MOZ_ASSERT(setElemKeyValueId().id() == 1);
5654 writer.setInputOperandId(1);
5655 rhsValId = ValOperandId(writer.setInputOperandId(2));
5656 }
5657
5658 RootedId id(cx_);
5659 bool nameOrSymbol;
5660 if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
5661 cx_->clearPendingException();
5662 return AttachDecision::NoAction;
5663 }
5664
5665 if (!lhsVal_.isObject() || !nameOrSymbol) {
5666 return AttachDecision::NoAction;
5667 }
5668
5669 JSObject* obj = &lhsVal_.toObject();
5670 if (!obj->is<NativeObject>()) {
5671 return AttachDecision::NoAction;
5672 }
5673 NativeObject* nobj = &obj->as<NativeObject>();
5674
5675 PropertyResult prop;
5676 if (!LookupOwnPropertyPure(cx_, obj, id, &prop)) {
5677 return AttachDecision::NoAction;
5678 }
5679 if (prop.isNotFound()) {
5680 return AttachDecision::NoAction;
5681 }
5682
5683 MOZ_RELEASE_ASSERT(prop.isNativeProperty());
5684 PropertyInfo propInfo = prop.propertyInfo();
5685 NativeObject* holder = nobj;
5686
5687 if (holder->inDictionaryMode()) {
5688 return AttachDecision::NoAction;
5689 }
5690
5691 SharedShape* oldSharedShape = &oldShape->asShared();
5692
5693 // The property must be the last added property of the object.
5694 SharedShape* newShape = holder->sharedShape();
5695 MOZ_RELEASE_ASSERT(oldShape != newShape);
5696 MOZ_RELEASE_ASSERT(newShape->lastProperty() == propInfo);
5697
5698 #ifdef DEBUG
5699 // Verify exactly one property was added by comparing the property map
5700 // lengths.
5701 if (oldSharedShape->propMapLength() == PropMap::Capacity) {
5702 MOZ_ASSERT(newShape->propMapLength() == 1);
5703 } else {
5704 MOZ_ASSERT(newShape->propMapLength() ==
5705 oldSharedShape->propMapLength() + 1);
5706 }
5707 #endif
5708
5709 bool isFunctionPrototype = IsFunctionPrototype(cx_->names(), nobj, id);
5710
5711 JSOp op = JSOp(*pc_);
5712 PropertyFlags flags = SetPropertyFlags(op, isFunctionPrototype);
5713
5714 // Basic property checks.
5715 if (!propInfo.isDataProperty() || propInfo.flags() != flags) {
5716 return AttachDecision::NoAction;
5717 }
5718
5719 ObjOperandId objId = writer.guardToObject(objValId);
5720 maybeEmitIdGuard(id);
5721
5722 // Shape guard the object.
5723 writer.guardShape(objId, oldShape);
5724
5725 // If this is the special function.prototype case, we need to guard the
5726 // function is a non-builtin constructor. See canAttachAddSlotStub.
5727 if (isFunctionPrototype) {
5728 MOZ_ASSERT(nobj->as<JSFunction>().isNonBuiltinConstructor());
5729 writer.guardFunctionIsNonBuiltinCtor(objId);
5730 }
5731
5732 // Also shape guard the proto chain, unless this is an InitElem.
5733 if (IsPropertySetOp(op)) {
5734 ShapeGuardProtoChain(writer, nobj, objId);
5735 }
5736
5737 // If the JSClass has an addProperty hook, we need to call a VM function to
5738 // invoke this hook. Ignore the Array addProperty hook, because it doesn't do
5739 // anything for non-index properties.
5740 DebugOnly<uint32_t> index;
5741 MOZ_ASSERT_IF(obj->is<ArrayObject>(), !IdIsIndex(id, &index));
5742 bool mustCallAddPropertyHook =
5743 obj->getClass()->getAddProperty() && !obj->is<ArrayObject>();
5744
5745 if (mustCallAddPropertyHook) {
5746 writer.addSlotAndCallAddPropHook(objId, rhsValId, newShape);
5747 trackAttached("SetProp.AddSlotWithAddPropertyHook");
5748 } else if (holder->isFixedSlot(propInfo.slot())) {
5749 size_t offset = NativeObject::getFixedSlotOffset(propInfo.slot());
5750 writer.addAndStoreFixedSlot(objId, offset, rhsValId, newShape);
5751 trackAttached("SetProp.AddSlotFixed");
5752 } else {
5753 size_t offset = holder->dynamicSlotIndex(propInfo.slot()) * sizeof(Value);
5754 uint32_t numOldSlots = NativeObject::calculateDynamicSlots(oldSharedShape);
5755 uint32_t numNewSlots = holder->numDynamicSlots();
5756 if (numOldSlots == numNewSlots) {
5757 writer.addAndStoreDynamicSlot(objId, offset, rhsValId, newShape);
5758 trackAttached("SetProp.AddSlotDynamic");
5759 } else {
5760 MOZ_ASSERT(numNewSlots > numOldSlots);
5761 writer.allocateAndStoreDynamicSlot(objId, offset, rhsValId, newShape,
5762 numNewSlots);
5763 trackAttached("SetProp.AllocateSlot");
5764 }
5765 }
5766 writer.returnFromIC();
5767
5768 return AttachDecision::Attach;
5769 }
5770
5771 InstanceOfIRGenerator::InstanceOfIRGenerator(JSContext* cx, HandleScript script,
5772 jsbytecode* pc, ICState state,
5773 HandleValue lhs, HandleObject rhs)
5774 : IRGenerator(cx, script, pc, CacheKind::InstanceOf, state),
5775 lhsVal_(lhs),
5776 rhsObj_(rhs) {}
5777
5778 AttachDecision InstanceOfIRGenerator::tryAttachStub() {
5779 MOZ_ASSERT(cacheKind_ == CacheKind::InstanceOf);
5780 AutoAssertNoPendingException aanpe(cx_);
5781
5782 // Ensure RHS is a function -- could be a Proxy, which the IC isn't prepared
5783 // to handle.
5784 if (!rhsObj_->is<JSFunction>()) {
5785 trackAttached(IRGenerator::NotAttached);
5786 return AttachDecision::NoAction;
5787 }
5788
5789 HandleFunction fun = rhsObj_.as<JSFunction>();
5790
5791 // Look up the @@hasInstance property, and check that Function.__proto__ is
5792 // the property holder, and that no object further down the prototype chain
5793 // (including this function) has shadowed it; together with the fact that
5794 // Function.__proto__[@@hasInstance] is immutable, this ensures that the
5795 // hasInstance hook will not change without the need to guard on the actual
5796 // property value.
5797 PropertyResult hasInstanceProp;
5798 NativeObject* hasInstanceHolder = nullptr;
5799 jsid hasInstanceID = PropertyKey::Symbol(cx_->wellKnownSymbols().hasInstance);
5800 if (!LookupPropertyPure(cx_, fun, hasInstanceID, &hasInstanceHolder,
5801 &hasInstanceProp) ||
5802 !hasInstanceProp.isNativeProperty()) {
5803 trackAttached(IRGenerator::NotAttached);
5804 return AttachDecision::NoAction;
5805 }
5806
5807 JSObject& funProto = cx_->global()->getPrototype(JSProto_Function);
5808 if (hasInstanceHolder != &funProto) {
5809 trackAttached(IRGenerator::NotAttached);
5810 return AttachDecision::NoAction;
5811 }
5812
5813 // If the above succeeded, then these should be true about @@hasInstance,
5814 // because the property on Function.__proto__ is an immutable data property:
5815 MOZ_ASSERT(hasInstanceProp.propertyInfo().isDataProperty());
5816 MOZ_ASSERT(!hasInstanceProp.propertyInfo().configurable());
5817 MOZ_ASSERT(!hasInstanceProp.propertyInfo().writable());
5818
5819 MOZ_ASSERT(IsCacheableProtoChain(fun, hasInstanceHolder));
5820
5821 // Ensure that the function's prototype slot is the same.
5822 Maybe<PropertyInfo> prop = fun->lookupPure(cx_->names().prototype);
5823 if (prop.isNothing() || !prop->isDataProperty()) {
5824 trackAttached(IRGenerator::NotAttached);
5825 return AttachDecision::NoAction;
5826 }
5827
5828 uint32_t slot = prop->slot();
5829 MOZ_ASSERT(slot >= fun->numFixedSlots(), "Stub code relies on this");
5830 if (!fun->getSlot(slot).isObject()) {
5831 trackAttached(IRGenerator::NotAttached);
5832 return AttachDecision::NoAction;
5833 }
5834
5835 // Abstract Objects
5836 ValOperandId lhs(writer.setInputOperandId(0));
5837 ValOperandId rhs(writer.setInputOperandId(1));
5838
5839 ObjOperandId rhsId = writer.guardToObject(rhs);
5840 writer.guardShape(rhsId, fun->shape());
5841
5842 // Ensure that the shapes up the prototype chain for the RHS remain the same
5843 // so that @@hasInstance is not shadowed by some intermediate prototype
5844 // object.
5845 if (hasInstanceHolder != fun) {
5846 GeneratePrototypeGuards(writer, fun, hasInstanceHolder, rhsId);
5847 ObjOperandId holderId = writer.loadObject(hasInstanceHolder);
5848 TestMatchingHolder(writer, hasInstanceHolder, holderId);
5849 }
5850
5851 // Load the .prototype value and ensure it's an object.
5852 ValOperandId protoValId =
5853 writer.loadDynamicSlot(rhsId, slot - fun->numFixedSlots());
5854 ObjOperandId protoId = writer.guardToObject(protoValId);
5855
5856 // Needn't guard LHS is object, because the actual stub can handle that
5857 // and correctly return false.
5858 writer.loadInstanceOfObjectResult(lhs, protoId);
5859 writer.returnFromIC();
5860 trackAttached("InstanceOf");
5861 return AttachDecision::Attach;
5862 }
5863
5864 void InstanceOfIRGenerator::trackAttached(const char* name) {
5865 stubName_ = name ? name : "NotAttached";
5866 #ifdef JS_CACHEIR_SPEW
5867 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
5868 sp.valueProperty("lhs", lhsVal_);
5869 sp.valueProperty("rhs", ObjectValue(*rhsObj_));
5870 }
5871 #else
5872 // Silence Clang -Wunused-private-field warning.
5873 (void)lhsVal_;
5874 #endif
5875 }
5876
5877 TypeOfIRGenerator::TypeOfIRGenerator(JSContext* cx, HandleScript script,
5878 jsbytecode* pc, ICState state,
5879 HandleValue value)
5880 : IRGenerator(cx, script, pc, CacheKind::TypeOf, state), val_(value) {}
5881
5882 void TypeOfIRGenerator::trackAttached(const char* name) {
5883 stubName_ = name ? name : "NotAttached";
5884 #ifdef JS_CACHEIR_SPEW
5885 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
5886 sp.valueProperty("val", val_);
5887 }
5888 #endif
5889 }
5890
5891 AttachDecision TypeOfIRGenerator::tryAttachStub() {
5892 MOZ_ASSERT(cacheKind_ == CacheKind::TypeOf);
5893
5894 AutoAssertNoPendingException aanpe(cx_);
5895
5896 ValOperandId valId(writer.setInputOperandId(0));
5897
5898 TRY_ATTACH(tryAttachPrimitive(valId));
5899 TRY_ATTACH(tryAttachObject(valId));
5900
5901 MOZ_ASSERT_UNREACHABLE("Failed to attach TypeOf");
5902 return AttachDecision::NoAction;
5903 }
5904
5905 AttachDecision TypeOfIRGenerator::tryAttachPrimitive(ValOperandId valId) {
5906 if (!val_.isPrimitive()) {
5907 return AttachDecision::NoAction;
5908 }
5909
5910 // Note: we don't use GuardIsNumber for int32 values because it's less
5911 // efficient in Warp (unboxing to double instead of int32).
5912 if (val_.isDouble()) {
5913 writer.guardIsNumber(valId);
5914 } else {
5915 writer.guardNonDoubleType(valId, val_.type());
5916 }
5917
5918 writer.loadConstantStringResult(
5919 TypeName(js::TypeOfValue(val_), cx_->names()));
5920 writer.returnFromIC();
5921 writer.setTypeData(TypeData(JSValueType(val_.type())));
5922 trackAttached("TypeOf.Primitive");
5923 return AttachDecision::Attach;
5924 }
5925
5926 AttachDecision TypeOfIRGenerator::tryAttachObject(ValOperandId valId) {
5927 if (!val_.isObject()) {
5928 return AttachDecision::NoAction;
5929 }
5930
5931 ObjOperandId objId = writer.guardToObject(valId);
5932 writer.loadTypeOfObjectResult(objId);
5933 writer.returnFromIC();
5934 writer.setTypeData(TypeData(JSValueType(val_.type())));
5935 trackAttached("TypeOf.Object");
5936 return AttachDecision::Attach;
5937 }
5938
5939 TypeOfEqIRGenerator::TypeOfEqIRGenerator(JSContext* cx, HandleScript script,
5940 jsbytecode* pc, ICState state,
5941 HandleValue value, JSType type,
5942 JSOp compareOp)
5943 : IRGenerator(cx, script, pc, CacheKind::TypeOfEq, state),
5944 val_(value),
5945 type_(type),
5946 compareOp_(compareOp) {}
5947
5948 void TypeOfEqIRGenerator::trackAttached(const char* name) {
5949 stubName_ = name ? name : "NotAttached";
5950 #ifdef JS_CACHEIR_SPEW
5951 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
5952 sp.valueProperty("val", val_);
5953 sp.jstypeProperty("type", type_);
5954 sp.opcodeProperty("compareOp", compareOp_);
5955 }
5956 #endif
5957 }
5958
5959 AttachDecision TypeOfEqIRGenerator::tryAttachStub() {
5960 MOZ_ASSERT(cacheKind_ == CacheKind::TypeOfEq);
5961
5962 AutoAssertNoPendingException aanpe(cx_);
5963
5964 ValOperandId valId(writer.setInputOperandId(0));
5965
5966 TRY_ATTACH(tryAttachPrimitive(valId));
5967 TRY_ATTACH(tryAttachObject(valId));
5968
5969 MOZ_ASSERT_UNREACHABLE("Failed to attach TypeOfEq");
5970 return AttachDecision::NoAction;
5971 }
5972
5973 AttachDecision TypeOfEqIRGenerator::tryAttachPrimitive(ValOperandId valId) {
5974 if (!val_.isPrimitive()) {
5975 return AttachDecision::NoAction;
5976 }
5977
5978 // Note: we don't use GuardIsNumber for int32 values because it's less
5979 // efficient in Warp (unboxing to double instead of int32).
5980 if (val_.isDouble()) {
5981 writer.guardIsNumber(valId);
5982 } else {
5983 writer.guardNonDoubleType(valId, val_.type());
5984 }
5985
5986 bool result = js::TypeOfValue(val_) == type_;
5987 if (compareOp_ == JSOp::Ne) {
5988 result = !result;
5989 }
5990 writer.loadBooleanResult(result);
5991 writer.returnFromIC();
5992 writer.setTypeData(TypeData(JSValueType(val_.type())));
5993 trackAttached("TypeOfEq.Primitive");
5994 return AttachDecision::Attach;
5995 }
5996
5997 AttachDecision TypeOfEqIRGenerator::tryAttachObject(ValOperandId valId) {
5998 if (!val_.isObject()) {
5999 return AttachDecision::NoAction;
6000 }
6001
6002 ObjOperandId objId = writer.guardToObject(valId);
6003 writer.loadTypeOfEqObjectResult(objId, TypeofEqOperand(type_, compareOp_));
6004 writer.returnFromIC();
6005 writer.setTypeData(TypeData(JSValueType(val_.type())));
6006 trackAttached("TypeOfEq.Object");
6007 return AttachDecision::Attach;
6008 }
6009
6010 GetIteratorIRGenerator::GetIteratorIRGenerator(JSContext* cx,
6011 HandleScript script,
6012 jsbytecode* pc, ICState state,
6013 HandleValue value)
6014 : IRGenerator(cx, script, pc, CacheKind::GetIterator, state), val_(value) {}
6015
6016 AttachDecision GetIteratorIRGenerator::tryAttachStub() {
6017 MOZ_ASSERT(cacheKind_ == CacheKind::GetIterator);
6018
6019 AutoAssertNoPendingException aanpe(cx_);
6020
6021 ValOperandId valId(writer.setInputOperandId(0));
6022
6023 TRY_ATTACH(tryAttachObject(valId));
6024 TRY_ATTACH(tryAttachNullOrUndefined(valId));
6025 TRY_ATTACH(tryAttachGeneric(valId));
6026
6027 trackAttached(IRGenerator::NotAttached);
6028 return AttachDecision::NoAction;
6029 }
6030
6031 AttachDecision GetIteratorIRGenerator::tryAttachObject(ValOperandId valId) {
6032 if (!val_.isObject()) {
6033 return AttachDecision::NoAction;
6034 }
6035
6036 MOZ_ASSERT(val_.toObject().compartment() == cx_->compartment());
6037
6038 ObjOperandId objId = writer.guardToObject(valId);
6039 writer.objectToIteratorResult(objId, cx_->compartment()->enumeratorsAddr());
6040 writer.returnFromIC();
6041
6042 trackAttached("GetIterator.Object");
6043 return AttachDecision::Attach;
6044 }
6045
6046 AttachDecision GetIteratorIRGenerator::tryAttachNullOrUndefined(
6047 ValOperandId valId) {
6048 MOZ_ASSERT(JSOp(*pc_) == JSOp::Iter);
6049
6050 // For null/undefined we can simply return the empty iterator singleton. This
6051 // works because this iterator is unlinked and immutable.
6052
6053 if (!val_.isNullOrUndefined()) {
6054 return AttachDecision::NoAction;
6055 }
6056
6057 PropertyIteratorObject* emptyIter =
6058 GlobalObject::getOrCreateEmptyIterator(cx_);
6059 if (!emptyIter) {
6060 cx_->recoverFromOutOfMemory();
6061 return AttachDecision::NoAction;
6062 }
6063
6064 writer.guardIsNullOrUndefined(valId);
6065
6066 ObjOperandId iterId = writer.loadObject(emptyIter);
6067 writer.loadObjectResult(iterId);
6068 writer.returnFromIC();
6069
6070 trackAttached("GetIterator.NullOrUndefined");
6071 return AttachDecision::Attach;
6072 }
6073
6074 AttachDecision GetIteratorIRGenerator::tryAttachGeneric(ValOperandId valId) {
6075 writer.valueToIteratorResult(valId);
6076 writer.returnFromIC();
6077
6078 trackAttached("GetIterator.Generic");
6079 return AttachDecision::Attach;
6080 }
6081
6082 void GetIteratorIRGenerator::trackAttached(const char* name) {
6083 stubName_ = name ? name : "NotAttached";
6084 #ifdef JS_CACHEIR_SPEW
6085 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
6086 sp.valueProperty("val", val_);
6087 }
6088 #endif
6089 }
6090
6091 OptimizeSpreadCallIRGenerator::OptimizeSpreadCallIRGenerator(
6092 JSContext* cx, HandleScript script, jsbytecode* pc, ICState state,
6093 HandleValue value)
6094 : IRGenerator(cx, script, pc, CacheKind::OptimizeSpreadCall, state),
6095 val_(value) {}
6096
6097 AttachDecision OptimizeSpreadCallIRGenerator::tryAttachStub() {
6098 MOZ_ASSERT(cacheKind_ == CacheKind::OptimizeSpreadCall);
6099
6100 AutoAssertNoPendingException aanpe(cx_);
6101
6102 TRY_ATTACH(tryAttachArray());
6103 TRY_ATTACH(tryAttachArguments());
6104 TRY_ATTACH(tryAttachNotOptimizable());
6105
6106 trackAttached(IRGenerator::NotAttached);
6107 return AttachDecision::NoAction;
6108 }
6109
6110 AttachDecision OptimizeSpreadCallIRGenerator::tryAttachArray() {
6111 if (!isFirstStub_) {
6112 return AttachDecision::NoAction;
6113 }
6114
6115 // The value must be a packed array.
6116 if (!val_.isObject()) {
6117 return AttachDecision::NoAction;
6118 }
6119 Rooted<JSObject*> obj(cx_, &val_.toObject());
6120 if (!IsArrayWithDefaultIterator<MustBePacked::Yes>(obj, cx_)) {
6121 return AttachDecision::NoAction;
6122 }
6123
6124 ValOperandId valId(writer.setInputOperandId(0));
6125 ObjOperandId objId = writer.guardToObject(valId);
6126
6127 // Guard the object is a packed array with Array.prototype as proto.
6128 MOZ_ASSERT(obj->is<ArrayObject>());
6129 writer.guardShape(objId, obj->shape());
6130 writer.guardArrayIsPacked(objId);
6131
6132 // Ensure Array.prototype[@@iterator] and %ArrayIteratorPrototype%.next
6133 // haven't been mutated.
6134 writer.guardFuse(RealmFuses::FuseIndex::OptimizeGetIteratorFuse);
6135
6136 writer.loadObjectResult(objId);
6137 writer.returnFromIC();
6138
6139 trackAttached("OptimizeSpreadCall.Array");
6140 return AttachDecision::Attach;
6141 }
6142
6143 AttachDecision OptimizeSpreadCallIRGenerator::tryAttachArguments() {
6144 // The value must be an arguments object.
6145 if (!val_.isObject()) {
6146 return AttachDecision::NoAction;
6147 }
6148 RootedObject obj(cx_, &val_.toObject());
6149 if (!obj->is<ArgumentsObject>()) {
6150 return AttachDecision::NoAction;
6151 }
6152 auto args = obj.as<ArgumentsObject>();
6153
6154 // Ensure neither elements, nor the length, nor the iterator has been
6155 // overridden. Also ensure no args are forwarded to allow reading them
6156 // directly from the frame.
6157 if (args->hasOverriddenElement() || args->hasOverriddenLength() ||
6158 args->hasOverriddenIterator() || args->anyArgIsForwarded()) {
6159 return AttachDecision::NoAction;
6160 }
6161
6162 // Don't optimize arguments objects from a different realm because in this
6163 // case we have to use the other realm's %ArrayIteratorPrototype% object.
6164 if (cx_->realm() != args->realm()) {
6165 return AttachDecision::NoAction;
6166 }
6167
6168 if (!HasOptimizableArrayIteratorPrototype(cx_)) {
6169 return AttachDecision::NoAction;
6170 }
6171
6172 Rooted<Shape*> shape(cx_, GlobalObject::getArrayShapeWithDefaultProto(cx_));
6173 if (!shape) {
6174 cx_->clearPendingException();
6175 return AttachDecision::NoAction;
6176 }
6177
6178 ValOperandId valId(writer.setInputOperandId(0));
6179 ObjOperandId objId = writer.guardToObject(valId);
6180
6181 if (args->is<MappedArgumentsObject>()) {
6182 writer.guardClass(objId, GuardClassKind::MappedArguments);
6183 } else {
6184 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
6185 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
6186 }
6187 uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
6188 ArgumentsObject::LENGTH_OVERRIDDEN_BIT |
6189 ArgumentsObject::ITERATOR_OVERRIDDEN_BIT |
6190 ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
6191 writer.guardArgumentsObjectFlags(objId, flags);
6192 writer.guardObjectHasSameRealm(objId);
6193
6194 writer.guardFuse(RealmFuses::FuseIndex::OptimizeArrayIteratorPrototypeFuse);
6195
6196 writer.arrayFromArgumentsObjectResult(objId, shape);
6197 writer.returnFromIC();
6198
6199 trackAttached("OptimizeSpreadCall.Arguments");
6200 return AttachDecision::Attach;
6201 }
6202
6203 AttachDecision OptimizeSpreadCallIRGenerator::tryAttachNotOptimizable() {
6204 ValOperandId valId(writer.setInputOperandId(0));
6205
6206 writer.loadUndefinedResult();
6207 writer.returnFromIC();
6208
6209 trackAttached("OptimizeSpreadCall.NotOptimizable");
6210 return AttachDecision::Attach;
6211 }
6212
6213 void OptimizeSpreadCallIRGenerator::trackAttached(const char* name) {
6214 stubName_ = name ? name : "NotAttached";
6215 #ifdef JS_CACHEIR_SPEW
6216 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
6217 sp.valueProperty("val", val_);
6218 }
6219 #endif
6220 }
6221
6222 CallIRGenerator::CallIRGenerator(JSContext* cx, HandleScript script,
6223 jsbytecode* pc, JSOp op, ICState state,
6224 BaselineFrame* frame, uint32_t argc,
6225 HandleValue callee, HandleValue thisval,
6226 HandleValue newTarget, HandleValueArray args)
6227 : IRGenerator(cx, script, pc, CacheKind::Call, state, frame),
6228 op_(op),
6229 argc_(argc),
6230 callee_(callee),
6231 thisval_(thisval),
6232 newTarget_(newTarget),
6233 args_(args) {}
6234
6235 bool InlinableNativeIRGenerator::isCalleeBoundFunction() const {
6236 return callee()->is<BoundFunctionObject>();
6237 }
6238
6239 BoundFunctionObject* InlinableNativeIRGenerator::boundCallee() const {
6240 MOZ_ASSERT(isCalleeBoundFunction());
6241 return &callee()->as<BoundFunctionObject>();
6242 }
6243
6244 bool InlinableNativeIRGenerator::isTargetBoundFunction() const {
6245 switch (flags_.getArgFormat()) {
6246 case CallFlags::Standard:
6247 case CallFlags::Spread:
6248 return false;
6249 case CallFlags::FunCall:
6250 case CallFlags::FunApplyArgsObj:
6251 case CallFlags::FunApplyArray:
6252 case CallFlags::FunApplyNullUndefined:
6253 if (callee()->is<JSFunction>()) {
6254 MOZ_ASSERT(generator_.thisval_.isObject());
6255 return generator_.thisval_.toObject().is<BoundFunctionObject>();
6256 }
6257 return false;
6258 case CallFlags::Unknown:
6259 break;
6260 }
6261 MOZ_CRASH("Unsupported arg format");
6262 }
6263
6264 BoundFunctionObject* InlinableNativeIRGenerator::boundTarget() const {
6265 MOZ_ASSERT(isTargetBoundFunction());
6266 return &generator_.thisval_.toObject().as<BoundFunctionObject>();
6267 }
6268
6269 ObjOperandId InlinableNativeIRGenerator::emitNativeCalleeGuard(
6270 Int32OperandId argcId) {
6271 // Note: we rely on GuardSpecificFunction to also guard against the same
6272 // native from a different realm.
6273 MOZ_ASSERT(target_->isNativeWithoutJitEntry());
6274
6275 ValOperandId calleeValId;
6276 switch (flags_.getArgFormat()) {
6277 case CallFlags::Standard:
6278 case CallFlags::Spread:
6279 calleeValId = writer.loadArgumentFixedSlot(ArgumentKind::Callee,
6280 stackArgc(), flags_);
6281 break;
6282 case CallFlags::FunCall:
6283 case CallFlags::FunApplyArray:
6284 case CallFlags::FunApplyNullUndefined:
6285 calleeValId = writer.loadArgumentFixedSlot(
6286 ArgumentKind::Callee, stackArgc(), CallFlags(CallFlags::Standard));
6287 break;
6288 case CallFlags::Unknown:
6289 case CallFlags::FunApplyArgsObj:
6290 MOZ_CRASH("Unsupported arg format");
6291 }
6292
6293 // Guard that |callee| is an object.
6294 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
6295 ObjOperandId targetId = calleeObjId;
6296
6297 // The callee is a bound function whose bound target is |target_|.
6298 //
6299 // Example:
6300 // ```
6301 // var boundPush = Array.prototype.push.bind(arr);
6302 // boundPush(1);
6303 // ```
6304 //
6305 // Relevant generator members:
6306 // - |CallIRGenerator::callee_| is `boundPush`
6307 // - |InlinableNativeIRGenerator::target_| is `Array.prototype.push`
6308 //
6309 // Also see tryAttachBound{Native,FunCall,FunApply}.
6310 if (isCalleeBoundFunction()) {
6311 // Ensure the callee is a bound function.
6312 writer.guardClass(calleeObjId, GuardClassKind::BoundFunction);
6313
6314 // Ensure numBoundArgs matches.
6315 size_t numBoundArgs = boundCallee()->numBoundArgs();
6316 Int32OperandId numBoundArgsId =
6317 writer.loadBoundFunctionNumArgs(calleeObjId);
6318 writer.guardSpecificInt32(numBoundArgsId, numBoundArgs);
6319
6320 // Load the bound function target.
6321 targetId = writer.loadBoundFunctionTarget(calleeObjId);
6322 }
6323
6324 if (flags_.getArgFormat() == CallFlags::FunCall ||
6325 flags_.getArgFormat() == CallFlags::FunApplyArray ||
6326 flags_.getArgFormat() == CallFlags::FunApplyNullUndefined) {
6327 JSFunction* funCallOrApply;
6328 ValOperandId thisValId;
6329 if (isCalleeBoundFunction()) {
6330 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::FunCall ||
6331 flags_.getArgFormat() == CallFlags::FunApplyNullUndefined,
6332 "unexpected bound function");
6333
6334 funCallOrApply = &boundCallee()->getTarget()->as<JSFunction>();
6335 thisValId = writer.loadFixedSlot(
6336 calleeObjId, BoundFunctionObject::offsetOfBoundThisSlot());
6337 } else {
6338 funCallOrApply = &callee()->as<JSFunction>();
6339 thisValId = writer.loadArgumentFixedSlot(ArgumentKind::This, stackArgc(),
6340 CallFlags(CallFlags::Standard));
6341 }
6342 MOZ_ASSERT(funCallOrApply->native() == fun_call ||
6343 funCallOrApply->native() == fun_apply);
6344
6345 // Guard that |target| is the |fun_call| or |fun_apply| native function.
6346 writer.guardSpecificFunction(targetId, funCallOrApply);
6347
6348 // Guard that |this| is an object.
6349 targetId = writer.guardToObject(thisValId);
6350 }
6351
6352 // The callee calls a bound function whose bound target is |target_|.
6353 //
6354 // For example:
6355 // ```
6356 // var boundPush = Array.prototype.push.bind(arr);
6357 // boundPush.call(null, 1);
6358 // ```
6359 //
6360 // Relevant generator members:
6361 // - |CallIRGenerator::callee_| is `Function.prototype.call`
6362 // - |CallIRGenerator::thisval_| is `boundPush`
6363 // - |InlinableNativeIRGenerator::target_| is `Array.prototype.push`
6364 //
6365 // Also see tryAttach{FunCall,FunApply}Bound.
6366 if (isTargetBoundFunction()) {
6367 MOZ_ASSERT(!isCalleeBoundFunction(), "unexpected nested bound functions");
6368 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::FunCall ||
6369 flags_.getArgFormat() == CallFlags::FunApplyNullUndefined,
6370 "unsupported arg-format for bound target");
6371
6372 // Ensure that |target| is a bound function.
6373 writer.guardClass(targetId, GuardClassKind::BoundFunction);
6374
6375 // Ensure numBoundArgs matches.
6376 size_t numBoundArgs = boundTarget()->numBoundArgs();
6377 Int32OperandId numBoundArgsId = writer.loadBoundFunctionNumArgs(targetId);
6378 writer.guardSpecificInt32(numBoundArgsId, numBoundArgs);
6379
6380 // Return the bound function as callee to support loading bound arguments.
6381 calleeObjId = targetId;
6382
6383 // Load the bound function target.
6384 targetId = writer.loadBoundFunctionTarget(targetId);
6385 }
6386
6387 writer.guardSpecificFunction(targetId, target_);
6388
6389 // If we're constructing we also need to guard newTarget == callee.
6390 if (flags_.isConstructing()) {
6391 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard);
6392 MOZ_ASSERT(&newTarget_.toObject() == callee());
6393
6394 ValOperandId newTargetValId = writer.loadArgumentFixedSlot(
6395 ArgumentKind::NewTarget, stackArgc(), flags_);
6396 ObjOperandId newTargetObjId = writer.guardToObject(newTargetValId);
6397
6398 if (isCalleeBoundFunction()) {
6399 writer.guardObjectIdentity(newTargetObjId, calleeObjId);
6400 } else {
6401 writer.guardSpecificFunction(newTargetObjId, target_);
6402 }
6403 }
6404
6405 // Guard the second argument is null or undefined.
6406 if (flags_.getArgFormat() == CallFlags::FunApplyNullUndefined) {
6407 constexpr size_t argIndex = 1;
6408
6409 size_t numBoundArgs = 0;
6410 if (isCalleeBoundFunction()) {
6411 numBoundArgs = boundCallee()->numBoundArgs();
6412 }
6413 MOZ_ASSERT(numBoundArgs <= 2);
6414
6415 ValOperandId argValId;
6416 if (argIndex < numBoundArgs) {
6417 argValId = loadBoundArgument(calleeObjId, argIndex);
6418 } else {
6419 auto argKind = ArgumentKindForArgIndex(argIndex - numBoundArgs);
6420 argValId = writer.loadArgumentFixedSlot(argKind, stackArgc(),
6421 CallFlags(CallFlags::Standard));
6422 }
6423
6424 writer.guardIsNullOrUndefined(argValId);
6425 }
6426
6427 return calleeObjId;
6428 }
6429
6430 ObjOperandId InlinableNativeIRGenerator::emitLoadArgsArray() {
6431 MOZ_ASSERT(!hasBoundArguments());
6432
6433 if (flags_.getArgFormat() == CallFlags::Spread) {
6434 return writer.loadSpreadArgs();
6435 }
6436
6437 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::FunApplyArray);
6438 return generator_.emitFunApplyArgsGuard(flags_.getArgFormat()).ref();
6439 }
6440
6441 ValOperandId InlinableNativeIRGenerator::loadBoundArgument(
6442 ObjOperandId calleeId, size_t argIndex) {
6443 MOZ_ASSERT(isCalleeBoundFunction() || isTargetBoundFunction());
6444
6445 auto* bound = isCalleeBoundFunction() ? boundCallee() : boundTarget();
6446 size_t numBoundArgs = bound->numBoundArgs();
6447 MOZ_ASSERT(argIndex < numBoundArgs);
6448
6449 if (numBoundArgs <= BoundFunctionObject::MaxInlineBoundArgs) {
6450 constexpr size_t inlineArgsOffset =
6451 BoundFunctionObject::offsetOfFirstInlineBoundArg();
6452
6453 size_t argSlot = inlineArgsOffset + argIndex * sizeof(Value);
6454 return writer.loadFixedSlot(calleeId, argSlot);
6455 }
6456 return writer.loadBoundFunctionArgument(calleeId, argIndex);
6457 }
6458
6459 ValOperandId InlinableNativeIRGenerator::loadThis(ObjOperandId calleeId) {
6460 switch (flags_.getArgFormat()) {
6461 case CallFlags::Standard:
6462 case CallFlags::Spread:
6463 MOZ_ASSERT(!isTargetBoundFunction());
6464 if (isCalleeBoundFunction()) {
6465 return writer.loadFixedSlot(
6466 calleeId, BoundFunctionObject::offsetOfBoundThisSlot());
6467 }
6468 return writer.loadArgumentFixedSlot(ArgumentKind::This, stackArgc(),
6469 flags_);
6470 case CallFlags::FunCall:
6471 case CallFlags::FunApplyNullUndefined:
6472 // Load |this| from bound this.
6473 if (isTargetBoundFunction()) {
6474 return writer.loadFixedSlot(
6475 calleeId, BoundFunctionObject::offsetOfBoundThisSlot());
6476 }
6477
6478 // Load |this| from bound arguments, if present.
6479 if (hasBoundArguments()) {
6480 MOZ_ASSERT(isCalleeBoundFunction());
6481 return loadBoundArgument(calleeId, 0);
6482 }
6483
6484 // The stack layout is already in the correct form for calls with at least
6485 // one argument.
6486 //
6487 // clang-format off
6488 //
6489 // *** STACK LAYOUT (bottom to top) *** *** INDEX ***
6490 // Callee <-- argc+1
6491 // ThisValue <-- argc
6492 // Args: | Arg0 | <-- argc-1
6493 // | Arg1 | <-- argc-2
6494 // | ... | <-- ...
6495 // | ArgN | <-- 0
6496 //
6497 // When passing |argc-1| as the number of arguments, we get:
6498 //
6499 // *** STACK LAYOUT (bottom to top) *** *** INDEX ***
6500 // Callee <-- (argc-1)+1 = argc = ThisValue
6501 // ThisValue <-- (argc-1) = argc-1 = Arg0
6502 // Args: | Arg0 | <-- (argc-1)-1 = argc-2 = Arg1
6503 // | Arg1 | <-- (argc-1)-2 = argc-3 = Arg2
6504 // | ... | <-- ...
6505 //
6506 // clang-format on
6507 //
6508 // This allows to call |loadArgumentFixedSlot(ArgumentKind::This)| and we
6509 // still load the correct argument index from |ArgumentKind::Arg0|.
6510 //
6511 // When no arguments are passed, i.e. |argc==0|, we have to replace
6512 // |ArgumentKind::Arg0| with the undefined value.
6513 if (stackArgc() == 0) {
6514 return writer.loadUndefined();
6515 }
6516 return writer.loadArgumentFixedSlot(ArgumentKind::This, stackArgc() - 1,
6517 CallFlags(CallFlags::Standard));
6518 case CallFlags::FunApplyArray:
6519 case CallFlags::FunApplyArgsObj:
6520 MOZ_ASSERT(stackArgc() > 0);
6521 MOZ_ASSERT(!isCalleeBoundFunction());
6522 MOZ_ASSERT(!isTargetBoundFunction());
6523 return writer.loadArgumentFixedSlot(ArgumentKind::This, stackArgc() - 1,
6524 CallFlags(CallFlags::Standard));
6525 case CallFlags::Unknown:
6526 break;
6527 }
6528 MOZ_CRASH("Unsupported arg format");
6529 }
6530
6531 ValOperandId InlinableNativeIRGenerator::loadArgument(ObjOperandId calleeId,
6532 ArgumentKind kind) {
6533 MOZ_ASSERT(kind >= ArgumentKind::Arg0);
6534 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard ||
6535 flags_.getArgFormat() == CallFlags::FunCall ||
6536 flags_.getArgFormat() == CallFlags::FunApplyNullUndefined);
6537 MOZ_ASSERT_IF(flags_.getArgFormat() == CallFlags::FunApplyNullUndefined,
6538 isTargetBoundFunction() && hasBoundArguments());
6539
6540 // Check if the |this| value is stored in the bound arguments.
6541 bool thisFromBoundArgs = flags_.getArgFormat() == CallFlags::FunCall &&
6542 isCalleeBoundFunction() && hasBoundArguments();
6543
6544 if (hasBoundArguments()) {
6545 auto* bound = isCalleeBoundFunction() ? boundCallee() : boundTarget();
6546 size_t numBoundArgs = bound->numBoundArgs();
6547 size_t argIndex = uint8_t(kind) - uint8_t(ArgumentKind::Arg0);
6548
6549 // Skip over the first bound argument, which stores the |this| value for
6550 // bound FunCall.
6551 if (thisFromBoundArgs) {
6552 argIndex += 1;
6553 }
6554
6555 // Load from bound args.
6556 if (argIndex < numBoundArgs) {
6557 return loadBoundArgument(calleeId, argIndex);
6558 }
6559
6560 // Load from stack arguments.
6561 kind = ArgumentKindForArgIndex(argIndex - numBoundArgs);
6562 }
6563
6564 switch (flags_.getArgFormat()) {
6565 case CallFlags::Standard:
6566 return writer.loadArgumentFixedSlot(kind, stackArgc(), flags_);
6567 case CallFlags::FunCall:
6568 if (thisFromBoundArgs) {
6569 return writer.loadArgumentFixedSlot(kind, stackArgc(),
6570 CallFlags(CallFlags::Standard));
6571 }
6572 MOZ_ASSERT(stackArgc() > 1);
6573 // See |loadThis| for why we subtract |argc - 1| here.
6574 return writer.loadArgumentFixedSlot(kind, stackArgc() - 1,
6575 CallFlags(CallFlags::Standard));
6576 case CallFlags::Spread:
6577 case CallFlags::FunApplyArray:
6578 case CallFlags::FunApplyArgsObj:
6579 case CallFlags::FunApplyNullUndefined:
6580 case CallFlags::Unknown:
6581 break;
6582 }
6583 MOZ_CRASH("Unsupported arg format");
6584 }
6585
6586 bool InlinableNativeIRGenerator::hasBoundArguments() const {
6587 if (isCalleeBoundFunction()) {
6588 return boundCallee()->numBoundArgs() != 0;
6589 }
6590 if (isTargetBoundFunction()) {
6591 return boundTarget()->numBoundArgs() != 0;
6592 }
6593 return false;
6594 }
6595
6596 void IRGenerator::emitCalleeGuard(ObjOperandId calleeId, JSFunction* callee) {
6597 // Guarding on the callee JSFunction* is most efficient, but doesn't work well
6598 // for lambda clones (multiple functions with the same BaseScript). We guard
6599 // on the function's BaseScript if the callee is scripted and this isn't the
6600 // first IC stub.
6601 //
6602 // Self-hosted functions are more complicated: top-level functions can be
6603 // relazified using SelfHostedLazyScript and this means they don't have a
6604 // stable BaseScript pointer. These functions are never lambda clones, though,
6605 // so we can just always guard on the JSFunction*. Self-hosted lambdas are
6606 // never relazified so there we use the normal heuristics.
6607 if (isFirstStub_ || !callee->hasBaseScript() ||
6608 (callee->isSelfHostedBuiltin() && !callee->isLambda())) {
6609 writer.guardSpecificFunction(calleeId, callee);
6610 } else {
6611 MOZ_ASSERT_IF(callee->isSelfHostedBuiltin(),
6612 !callee->baseScript()->allowRelazify());
6613 writer.guardClass(calleeId, GuardClassKind::JSFunction);
6614 writer.guardFunctionScript(calleeId, callee->baseScript());
6615 }
6616 }
6617
6618 ObjOperandId CallIRGenerator::emitFunCallOrApplyGuard(Int32OperandId argcId) {
6619 JSFunction* callee = &callee_.toObject().as<JSFunction>();
6620 MOZ_ASSERT(callee->native() == fun_call || callee->native() == fun_apply);
6621
6622 // |GetIndexOfArgument| doesn't yet support FunCall/FunApply.
6623 CallFlags flags(CallFlags::Standard);
6624
6625 // Guard that callee is the |fun_call| or |fun_apply| native function.
6626 ValOperandId calleeValId =
6627 writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
6628 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
6629 writer.guardSpecificFunction(calleeObjId, callee);
6630
6631 // Guard that |this| is an object.
6632 ValOperandId thisValId =
6633 writer.loadArgumentDynamicSlot(ArgumentKind::This, argcId, flags);
6634 return writer.guardToObject(thisValId);
6635 }
6636
6637 ObjOperandId CallIRGenerator::emitFunCallGuard(Int32OperandId argcId) {
6638 MOZ_ASSERT(callee_.toObject().as<JSFunction>().native() == fun_call);
6639
6640 return emitFunCallOrApplyGuard(argcId);
6641 }
6642
6643 ObjOperandId CallIRGenerator::emitFunApplyGuard(Int32OperandId argcId) {
6644 MOZ_ASSERT(callee_.toObject().as<JSFunction>().native() == fun_apply);
6645
6646 return emitFunCallOrApplyGuard(argcId);
6647 }
6648
6649 Maybe<ObjOperandId> CallIRGenerator::emitFunApplyArgsGuard(
6650 CallFlags::ArgFormat format) {
6651 MOZ_ASSERT(argc_ == 2);
6652
6653 // |GetIndexOfArgument| doesn't yet support FunCall/FunApply.
6654 CallFlags flags(CallFlags::Standard);
6655
6656 ValOperandId argValId =
6657 writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_, flags);
6658
6659 if (format == CallFlags::FunApplyArgsObj) {
6660 ObjOperandId argObjId = writer.guardToObject(argValId);
6661 if (args_[1].toObject().is<MappedArgumentsObject>()) {
6662 writer.guardClass(argObjId, GuardClassKind::MappedArguments);
6663 } else {
6664 MOZ_ASSERT(args_[1].toObject().is<UnmappedArgumentsObject>());
6665 writer.guardClass(argObjId, GuardClassKind::UnmappedArguments);
6666 }
6667 uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
6668 ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
6669 writer.guardArgumentsObjectFlags(argObjId, flags);
6670 return mozilla::Some(argObjId);
6671 }
6672
6673 if (format == CallFlags::FunApplyArray) {
6674 ObjOperandId argObjId = writer.guardToObject(argValId);
6675 emitOptimisticClassGuard(argObjId, &args_[1].toObject(),
6676 GuardClassKind::Array);
6677 writer.guardArrayIsPacked(argObjId);
6678 return mozilla::Some(argObjId);
6679 }
6680
6681 MOZ_ASSERT(format == CallFlags::FunApplyNullUndefined);
6682 writer.guardIsNullOrUndefined(argValId);
6683 return mozilla::Nothing();
6684 }
6685
6686 AttachDecision InlinableNativeIRGenerator::tryAttachArrayPush() {
6687 // Only optimize on obj.push(val);
6688 if (args_.length() != 1 || !thisval_.isObject()) {
6689 return AttachDecision::NoAction;
6690 }
6691
6692 // Where |obj| is a native array.
6693 JSObject* thisobj = &thisval_.toObject();
6694 if (!thisobj->is<ArrayObject>()) {
6695 return AttachDecision::NoAction;
6696 }
6697
6698 auto* thisarray = &thisobj->as<ArrayObject>();
6699
6700 // Check for other indexed properties or class hooks.
6701 if (!CanAttachAddElement(thisarray, /* isInit = */ false,
6702 AllowIndexedReceiver::No)) {
6703 return AttachDecision::NoAction;
6704 }
6705
6706 // Can't add new elements to arrays with non-writable length.
6707 if (!thisarray->lengthIsWritable()) {
6708 return AttachDecision::NoAction;
6709 }
6710
6711 // Check that array is extensible.
6712 if (!thisarray->isExtensible()) {
6713 return AttachDecision::NoAction;
6714 }
6715
6716 // Check that the array is completely initialized (no holes).
6717 if (thisarray->getDenseInitializedLength() != thisarray->length()) {
6718 return AttachDecision::NoAction;
6719 }
6720
6721 MOZ_ASSERT(!thisarray->denseElementsAreFrozen(),
6722 "Extensible arrays should not have frozen elements");
6723
6724 // After this point, we can generate code fine.
6725
6726 // Initialize the input operand.
6727 Int32OperandId argcId = initializeInputOperand();
6728
6729 // Guard callee is the 'push' native function.
6730 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
6731
6732 // Guard this is an array object.
6733 ValOperandId thisValId = loadThis(calleeId);
6734 ObjOperandId thisObjId = writer.guardToObject(thisValId);
6735
6736 // Guard that the shape matches.
6737 TestMatchingNativeReceiver(writer, thisarray, thisObjId);
6738
6739 // Guard proto chain shapes.
6740 ShapeGuardProtoChain(writer, thisarray, thisObjId);
6741
6742 // arr.push(x) is equivalent to arr[arr.length] = x for regular arrays.
6743 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
6744 writer.arrayPush(thisObjId, argId);
6745
6746 writer.returnFromIC();
6747
6748 trackAttached("ArrayPush");
6749 return AttachDecision::Attach;
6750 }
6751
6752 AttachDecision InlinableNativeIRGenerator::tryAttachArrayPopShift(
6753 InlinableNative native) {
6754 // Expecting no arguments.
6755 if (args_.length() != 0) {
6756 return AttachDecision::NoAction;
6757 }
6758
6759 // Only optimize if |this| is a packed array.
6760 if (!thisval_.isObject() || !IsPackedArray(&thisval_.toObject())) {
6761 return AttachDecision::NoAction;
6762 }
6763
6764 // Other conditions:
6765 //
6766 // * The array length needs to be writable because we're changing it.
6767 // * The array must be extensible. Non-extensible arrays require preserving
6768 // the |initializedLength == capacity| invariant on ObjectElements.
6769 // See NativeObject::shrinkCapacityToInitializedLength.
6770 // This also ensures the elements aren't sealed/frozen.
6771 // * There must not be a for-in iterator for the elements because the IC stub
6772 // does not suppress deleted properties.
6773 ArrayObject* arr = &thisval_.toObject().as<ArrayObject>();
6774 if (!arr->lengthIsWritable() || !arr->isExtensible() ||
6775 arr->denseElementsHaveMaybeInIterationFlag()) {
6776 return AttachDecision::NoAction;
6777 }
6778
6779 // Initialize the input operand.
6780 Int32OperandId argcId = initializeInputOperand();
6781
6782 // Guard callee is the 'pop' or 'shift' native function.
6783 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
6784
6785 ValOperandId thisValId = loadThis(calleeId);
6786 ObjOperandId objId = writer.guardToObject(thisValId);
6787 emitOptimisticClassGuard(objId, arr, GuardClassKind::Array);
6788
6789 if (native == InlinableNative::ArrayPop) {
6790 writer.packedArrayPopResult(objId);
6791 } else {
6792 MOZ_ASSERT(native == InlinableNative::ArrayShift);
6793 writer.packedArrayShiftResult(objId);
6794 }
6795
6796 writer.returnFromIC();
6797
6798 trackAttached("ArrayPopShift");
6799 return AttachDecision::Attach;
6800 }
6801
6802 AttachDecision InlinableNativeIRGenerator::tryAttachArrayJoin() {
6803 // Only handle argc <= 1.
6804 if (args_.length() > 1) {
6805 return AttachDecision::NoAction;
6806 }
6807
6808 // Only optimize if |this| is an array.
6809 if (!thisval_.isObject() || !thisval_.toObject().is<ArrayObject>()) {
6810 return AttachDecision::NoAction;
6811 }
6812
6813 // The separator argument must be a string, if present.
6814 if (args_.length() > 0 && !args_[0].isString()) {
6815 return AttachDecision::NoAction;
6816 }
6817
6818 // IC stub code can handle non-packed array.
6819
6820 // Initialize the input operand.
6821 Int32OperandId argcId = initializeInputOperand();
6822
6823 // Guard callee is the 'join' native function.
6824 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
6825
6826 // Guard this is an array object.
6827 ValOperandId thisValId = loadThis(calleeId);
6828 ObjOperandId thisObjId = writer.guardToObject(thisValId);
6829 emitOptimisticClassGuard(thisObjId, &thisval_.toObject(),
6830 GuardClassKind::Array);
6831
6832 StringOperandId sepId;
6833 if (args_.length() == 1) {
6834 // If argcount is 1, guard that the argument is a string.
6835 ValOperandId argValId = loadArgument(calleeId, ArgumentKind::Arg0);
6836 sepId = writer.guardToString(argValId);
6837 } else {
6838 sepId = writer.loadConstantString(cx_->names().comma_);
6839 }
6840
6841 // Do the join.
6842 writer.arrayJoinResult(thisObjId, sepId);
6843
6844 writer.returnFromIC();
6845
6846 trackAttached("ArrayJoin");
6847 return AttachDecision::Attach;
6848 }
6849
6850 AttachDecision InlinableNativeIRGenerator::tryAttachArraySlice() {
6851 // Only handle argc <= 2.
6852 if (args_.length() > 2) {
6853 return AttachDecision::NoAction;
6854 }
6855
6856 // Only optimize if |this| is a packed array or an arguments object.
6857 if (!thisval_.isObject()) {
6858 return AttachDecision::NoAction;
6859 }
6860
6861 bool isPackedArray = IsPackedArray(&thisval_.toObject());
6862 if (!isPackedArray) {
6863 if (!thisval_.toObject().is<ArgumentsObject>()) {
6864 return AttachDecision::NoAction;
6865 }
6866 auto* args = &thisval_.toObject().as<ArgumentsObject>();
6867
6868 // No elements must have been overridden or deleted.
6869 if (args->hasOverriddenElement()) {
6870 return AttachDecision::NoAction;
6871 }
6872
6873 // The length property mustn't be overridden.
6874 if (args->hasOverriddenLength()) {
6875 return AttachDecision::NoAction;
6876 }
6877
6878 // And finally also check that no argument is forwarded.
6879 if (args->anyArgIsForwarded()) {
6880 return AttachDecision::NoAction;
6881 }
6882 }
6883
6884 // Arguments for the sliced region must be integers.
6885 if (args_.length() > 0 && !args_[0].isInt32()) {
6886 return AttachDecision::NoAction;
6887 }
6888 if (args_.length() > 1 && !args_[1].isInt32()) {
6889 return AttachDecision::NoAction;
6890 }
6891
6892 JSObject* templateObj = NewDenseFullyAllocatedArray(cx_, 0, TenuredObject);
6893 if (!templateObj) {
6894 cx_->recoverFromOutOfMemory();
6895 return AttachDecision::NoAction;
6896 }
6897
6898 // Initialize the input operand.
6899 Int32OperandId argcId = initializeInputOperand();
6900
6901 // Guard callee is the 'slice' native function.
6902 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
6903
6904 ValOperandId thisValId = loadThis(calleeId);
6905 ObjOperandId objId = writer.guardToObject(thisValId);
6906
6907 if (isPackedArray) {
6908 emitOptimisticClassGuard(objId, &thisval_.toObject(),
6909 GuardClassKind::Array);
6910 } else {
6911 auto* args = &thisval_.toObject().as<ArgumentsObject>();
6912
6913 if (args->is<MappedArgumentsObject>()) {
6914 writer.guardClass(objId, GuardClassKind::MappedArguments);
6915 } else {
6916 MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
6917 writer.guardClass(objId, GuardClassKind::UnmappedArguments);
6918 }
6919
6920 uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
6921 ArgumentsObject::LENGTH_OVERRIDDEN_BIT |
6922 ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
6923 writer.guardArgumentsObjectFlags(objId, flags);
6924 }
6925
6926 Int32OperandId int32BeginId;
6927 if (args_.length() > 0) {
6928 ValOperandId beginId = loadArgument(calleeId, ArgumentKind::Arg0);
6929 int32BeginId = writer.guardToInt32(beginId);
6930 } else {
6931 int32BeginId = writer.loadInt32Constant(0);
6932 }
6933
6934 Int32OperandId int32EndId;
6935 if (args_.length() > 1) {
6936 ValOperandId endId = loadArgument(calleeId, ArgumentKind::Arg1);
6937 int32EndId = writer.guardToInt32(endId);
6938 } else if (isPackedArray) {
6939 int32EndId = writer.loadInt32ArrayLength(objId);
6940 } else {
6941 int32EndId = writer.loadArgumentsObjectLength(objId);
6942 }
6943
6944 if (isPackedArray) {
6945 writer.packedArraySliceResult(templateObj, objId, int32BeginId, int32EndId);
6946 } else {
6947 writer.argumentsSliceResult(templateObj, objId, int32BeginId, int32EndId);
6948 }
6949 writer.returnFromIC();
6950
6951 trackAttached(isPackedArray ? "ArraySlice" : "ArgumentsSlice");
6952 return AttachDecision::Attach;
6953 }
6954
6955 AttachDecision InlinableNativeIRGenerator::tryAttachArrayIsArray() {
6956 // Need a single argument.
6957 if (args_.length() != 1) {
6958 return AttachDecision::NoAction;
6959 }
6960
6961 // Initialize the input operand.
6962 Int32OperandId argcId = initializeInputOperand();
6963
6964 // Guard callee is the 'isArray' native function.
6965 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
6966
6967 // Check if the argument is an Array and return result.
6968 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
6969 writer.isArrayResult(argId);
6970 writer.returnFromIC();
6971
6972 trackAttached("ArrayIsArray");
6973 return AttachDecision::Attach;
6974 }
6975
6976 AttachDecision InlinableNativeIRGenerator::tryAttachDataViewGet(
6977 Scalar::Type type) {
6978 // Ensure |this| is a DataViewObject.
6979 if (!thisval_.isObject() || !thisval_.toObject().is<DataViewObject>()) {
6980 return AttachDecision::NoAction;
6981 }
6982
6983 // Expected arguments: offset (number), optional littleEndian (boolean).
6984 if (args_.length() < 1 || args_.length() > 2) {
6985 return AttachDecision::NoAction;
6986 }
6987 int64_t offsetInt64;
6988 if (!ValueIsInt64Index(args_[0], &offsetInt64)) {
6989 return AttachDecision::NoAction;
6990 }
6991 if (args_.length() > 1 && !args_[1].isBoolean()) {
6992 return AttachDecision::NoAction;
6993 }
6994
6995 auto* dv = &thisval_.toObject().as<DataViewObject>();
6996
6997 // Bounds check the offset.
6998 size_t byteLength = dv->byteLength().valueOr(0);
6999 if (offsetInt64 < 0 || !DataViewObject::offsetIsInBounds(
7000 Scalar::byteSize(type), offsetInt64, byteLength)) {
7001 return AttachDecision::NoAction;
7002 }
7003
7004 // For getUint32 we let the stub return an Int32 if we have not seen a
7005 // double, to allow better codegen in Warp while avoiding bailout loops.
7006 bool forceDoubleForUint32 = false;
7007 if (type == Scalar::Uint32) {
7008 bool isLittleEndian = args_.length() > 1 && args_[1].toBoolean();
7009 uint32_t res = dv->read<uint32_t>(offsetInt64, byteLength, isLittleEndian);
7010 forceDoubleForUint32 = res >= INT32_MAX;
7011 }
7012
7013 // Initialize the input operand.
7014 Int32OperandId argcId = initializeInputOperand();
7015
7016 // Guard callee is this DataView native function.
7017 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
7018
7019 // Guard |this| is a DataViewObject.
7020 ValOperandId thisValId = loadThis(calleeId);
7021 ObjOperandId objId = writer.guardToObject(thisValId);
7022
7023 if (dv->is<FixedLengthDataViewObject>()) {
7024 emitOptimisticClassGuard(objId, &thisval_.toObject(),
7025 GuardClassKind::FixedLengthDataView);
7026 } else {
7027 emitOptimisticClassGuard(objId, &thisval_.toObject(),
7028 GuardClassKind::ResizableDataView);
7029 }
7030
7031 // Convert offset to intPtr.
7032 ValOperandId offsetId = loadArgument(calleeId, ArgumentKind::Arg0);
7033 IntPtrOperandId intPtrOffsetId =
7034 guardToIntPtrIndex(args_[0], offsetId, /* supportOOB = */ false);
7035
7036 BooleanOperandId boolLittleEndianId;
7037 if (args_.length() > 1) {
7038 ValOperandId littleEndianId = loadArgument(calleeId, ArgumentKind::Arg1);
7039 boolLittleEndianId = writer.guardToBoolean(littleEndianId);
7040 } else {
7041 boolLittleEndianId = writer.loadBooleanConstant(false);
7042 }
7043
7044 auto viewKind = ToArrayBufferViewKind(dv);
7045 writer.loadDataViewValueResult(objId, intPtrOffsetId, boolLittleEndianId,
7046 type, forceDoubleForUint32, viewKind);
7047
7048 writer.returnFromIC();
7049
7050 trackAttached("DataViewGet");
7051 return AttachDecision::Attach;
7052 }
7053
7054 AttachDecision InlinableNativeIRGenerator::tryAttachDataViewSet(
7055 Scalar::Type type) {
7056 // Ensure |this| is a DataViewObject.
7057 if (!thisval_.isObject() || !thisval_.toObject().is<DataViewObject>()) {
7058 return AttachDecision::NoAction;
7059 }
7060
7061 // Expected arguments: offset (number), value, optional littleEndian (boolean)
7062 if (args_.length() < 2 || args_.length() > 3) {
7063 return AttachDecision::NoAction;
7064 }
7065 int64_t offsetInt64;
7066 if (!ValueIsInt64Index(args_[0], &offsetInt64)) {
7067 return AttachDecision::NoAction;
7068 }
7069 if (!ValueCanConvertToNumeric(type, args_[1])) {
7070 return AttachDecision::NoAction;
7071 }
7072 if (args_.length() > 2 && !args_[2].isBoolean()) {
7073 return AttachDecision::NoAction;
7074 }
7075
7076 auto* dv = &thisval_.toObject().as<DataViewObject>();
7077
7078 // Bounds check the offset.
7079 size_t byteLength = dv->byteLength().valueOr(0);
7080 if (offsetInt64 < 0 || !DataViewObject::offsetIsInBounds(
7081 Scalar::byteSize(type), offsetInt64, byteLength)) {
7082 return AttachDecision::NoAction;
7083 }
7084
7085 // Initialize the input operand.
7086 Int32OperandId argcId = initializeInputOperand();
7087
7088 // Guard callee is this DataView native function.
7089 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
7090
7091 // Guard |this| is a DataViewObject.
7092 ValOperandId thisValId = loadThis(calleeId);
7093 ObjOperandId objId = writer.guardToObject(thisValId);
7094
7095 if (dv->is<FixedLengthDataViewObject>()) {
7096 emitOptimisticClassGuard(objId, &thisval_.toObject(),
7097 GuardClassKind::FixedLengthDataView);
7098 } else {
7099 emitOptimisticClassGuard(objId, &thisval_.toObject(),
7100 GuardClassKind::ResizableDataView);
7101 }
7102
7103 // Convert offset to intPtr.
7104 ValOperandId offsetId = loadArgument(calleeId, ArgumentKind::Arg0);
7105 IntPtrOperandId intPtrOffsetId =
7106 guardToIntPtrIndex(args_[0], offsetId, /* supportOOB = */ false);
7107
7108 // Convert value to number or BigInt.
7109 ValOperandId valueId = loadArgument(calleeId, ArgumentKind::Arg1);
7110 OperandId numericValueId = emitNumericGuard(valueId, args_[1], type);
7111
7112 BooleanOperandId boolLittleEndianId;
7113 if (args_.length() > 2) {
7114 ValOperandId littleEndianId = loadArgument(calleeId, ArgumentKind::Arg2);
7115 boolLittleEndianId = writer.guardToBoolean(littleEndianId);
7116 } else {
7117 boolLittleEndianId = writer.loadBooleanConstant(false);
7118 }
7119
7120 auto viewKind = ToArrayBufferViewKind(dv);
7121 writer.storeDataViewValueResult(objId, intPtrOffsetId, numericValueId,
7122 boolLittleEndianId, type, viewKind);
7123
7124 writer.returnFromIC();
7125
7126 trackAttached("DataViewSet");
7127 return AttachDecision::Attach;
7128 }
7129
7130 AttachDecision InlinableNativeIRGenerator::tryAttachUnsafeGetReservedSlot(
7131 InlinableNative native) {
7132 // Self-hosted code calls this with (object, int32) arguments.
7133 MOZ_ASSERT(args_.length() == 2);
7134 MOZ_ASSERT(args_[0].isObject());
7135 MOZ_ASSERT(args_[1].isInt32());
7136 MOZ_ASSERT(args_[1].toInt32() >= 0);
7137
7138 uint32_t slot = uint32_t(args_[1].toInt32());
7139 if (slot >= NativeObject::MAX_FIXED_SLOTS) {
7140 return AttachDecision::NoAction;
7141 }
7142 size_t offset = NativeObject::getFixedSlotOffset(slot);
7143
7144 // Initialize the input operand.
7145 initializeInputOperand();
7146
7147 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7148
7149 // Guard that the first argument is an object.
7150 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7151 ObjOperandId objId = writer.guardToObject(arg0Id);
7152
7153 // BytecodeEmitter::assertSelfHostedUnsafeGetReservedSlot ensures that the
7154 // slot argument is constant. (At least for direct calls)
7155
7156 switch (native) {
7157 case InlinableNative::IntrinsicUnsafeGetReservedSlot:
7158 writer.loadFixedSlotResult(objId, offset);
7159 break;
7160 case InlinableNative::IntrinsicUnsafeGetObjectFromReservedSlot:
7161 writer.loadFixedSlotTypedResult(objId, offset, ValueType::Object);
7162 break;
7163 case InlinableNative::IntrinsicUnsafeGetInt32FromReservedSlot:
7164 writer.loadFixedSlotTypedResult(objId, offset, ValueType::Int32);
7165 break;
7166 case InlinableNative::IntrinsicUnsafeGetStringFromReservedSlot:
7167 writer.loadFixedSlotTypedResult(objId, offset, ValueType::String);
7168 break;
7169 default:
7170 MOZ_CRASH("unexpected native");
7171 }
7172
7173 writer.returnFromIC();
7174
7175 trackAttached("UnsafeGetReservedSlot");
7176 return AttachDecision::Attach;
7177 }
7178
7179 AttachDecision InlinableNativeIRGenerator::tryAttachUnsafeSetReservedSlot() {
7180 // Self-hosted code calls this with (object, int32, value) arguments.
7181 MOZ_ASSERT(args_.length() == 3);
7182 MOZ_ASSERT(args_[0].isObject());
7183 MOZ_ASSERT(args_[1].isInt32());
7184 MOZ_ASSERT(args_[1].toInt32() >= 0);
7185
7186 uint32_t slot = uint32_t(args_[1].toInt32());
7187 if (slot >= NativeObject::MAX_FIXED_SLOTS) {
7188 return AttachDecision::NoAction;
7189 }
7190 size_t offset = NativeObject::getFixedSlotOffset(slot);
7191
7192 // Initialize the input operand.
7193 initializeInputOperand();
7194
7195 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7196
7197 // Guard that the first argument is an object.
7198 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7199 ObjOperandId objId = writer.guardToObject(arg0Id);
7200
7201 // BytecodeEmitter::assertSelfHostedUnsafeSetReservedSlot ensures that the
7202 // slot argument is constant. (At least for direct calls)
7203
7204 // Get the value to set.
7205 ValOperandId valId = loadArgumentIntrinsic(ArgumentKind::Arg2);
7206
7207 // Set the fixed slot and return undefined.
7208 writer.storeFixedSlotUndefinedResult(objId, offset, valId);
7209
7210 // This stub always returns undefined.
7211 writer.returnFromIC();
7212
7213 trackAttached("UnsafeSetReservedSlot");
7214 return AttachDecision::Attach;
7215 }
7216
7217 AttachDecision InlinableNativeIRGenerator::tryAttachIsSuspendedGenerator() {
7218 // The IsSuspendedGenerator intrinsic is only called in
7219 // self-hosted code, so it's safe to assume we have a single
7220 // argument and the callee is our intrinsic.
7221
7222 MOZ_ASSERT(args_.length() == 1);
7223
7224 initializeInputOperand();
7225
7226 // Stack layout here is (bottom to top):
7227 // 2: Callee
7228 // 1: ThisValue
7229 // 0: Arg <-- Top of stack.
7230 // We only care about the argument.
7231 ValOperandId valId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7232
7233 // Check whether the argument is a suspended generator.
7234 // We don't need guards, because IsSuspendedGenerator returns
7235 // false for values that are not generator objects.
7236 writer.callIsSuspendedGeneratorResult(valId);
7237 writer.returnFromIC();
7238
7239 trackAttached("IsSuspendedGenerator");
7240 return AttachDecision::Attach;
7241 }
7242
7243 AttachDecision InlinableNativeIRGenerator::tryAttachToObject() {
7244 // Self-hosted code calls this with a single argument.
7245 MOZ_ASSERT(args_.length() == 1);
7246
7247 // Need a single object argument.
7248 // TODO(Warp): Support all or more conversions to object.
7249 if (!args_[0].isObject()) {
7250 return AttachDecision::NoAction;
7251 }
7252
7253 // Initialize the input operand.
7254 initializeInputOperand();
7255
7256 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7257
7258 // Guard that the argument is an object.
7259 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7260 ObjOperandId objId = writer.guardToObject(argId);
7261
7262 // Return the object.
7263 writer.loadObjectResult(objId);
7264 writer.returnFromIC();
7265
7266 trackAttached("ToObject");
7267 return AttachDecision::Attach;
7268 }
7269
7270 AttachDecision InlinableNativeIRGenerator::tryAttachToInteger() {
7271 // Self-hosted code calls this with a single argument.
7272 MOZ_ASSERT(args_.length() == 1);
7273
7274 // Need a single int32 argument.
7275 // TODO(Warp): Support all or more conversions to integer.
7276 // Make sure to update this code correctly if we ever start
7277 // returning non-int32 integers.
7278 if (!args_[0].isInt32()) {
7279 return AttachDecision::NoAction;
7280 }
7281
7282 // Initialize the input operand.
7283 initializeInputOperand();
7284
7285 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7286
7287 // Guard that the argument is an int32.
7288 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7289 Int32OperandId int32Id = writer.guardToInt32(argId);
7290
7291 // Return the int32.
7292 writer.loadInt32Result(int32Id);
7293 writer.returnFromIC();
7294
7295 trackAttached("ToInteger");
7296 return AttachDecision::Attach;
7297 }
7298
7299 AttachDecision InlinableNativeIRGenerator::tryAttachToLength() {
7300 // Self-hosted code calls this with a single argument.
7301 MOZ_ASSERT(args_.length() == 1);
7302
7303 // Need a single int32 argument.
7304 if (!args_[0].isInt32()) {
7305 return AttachDecision::NoAction;
7306 }
7307
7308 // Initialize the input operand.
7309 initializeInputOperand();
7310
7311 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7312
7313 // ToLength(int32) is equivalent to max(int32, 0).
7314 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7315 Int32OperandId int32ArgId = writer.guardToInt32(argId);
7316 Int32OperandId zeroId = writer.loadInt32Constant(0);
7317 bool isMax = true;
7318 Int32OperandId maxId = writer.int32MinMax(isMax, int32ArgId, zeroId);
7319 writer.loadInt32Result(maxId);
7320 writer.returnFromIC();
7321
7322 trackAttached("ToLength");
7323 return AttachDecision::Attach;
7324 }
7325
7326 AttachDecision InlinableNativeIRGenerator::tryAttachIsObject() {
7327 // Self-hosted code calls this with a single argument.
7328 MOZ_ASSERT(args_.length() == 1);
7329
7330 // Initialize the input operand.
7331 initializeInputOperand();
7332
7333 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7334
7335 // Type check the argument and return result.
7336 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7337 writer.isObjectResult(argId);
7338 writer.returnFromIC();
7339
7340 trackAttached("IsObject");
7341 return AttachDecision::Attach;
7342 }
7343
7344 AttachDecision InlinableNativeIRGenerator::tryAttachIsPackedArray() {
7345 // Self-hosted code calls this with a single object argument.
7346 MOZ_ASSERT(args_.length() == 1);
7347 MOZ_ASSERT(args_[0].isObject());
7348
7349 // Initialize the input operand.
7350 initializeInputOperand();
7351
7352 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7353
7354 // Check if the argument is packed and return result.
7355 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7356 ObjOperandId objArgId = writer.guardToObject(argId);
7357 writer.isPackedArrayResult(objArgId);
7358 writer.returnFromIC();
7359
7360 trackAttached("IsPackedArray");
7361 return AttachDecision::Attach;
7362 }
7363
7364 AttachDecision InlinableNativeIRGenerator::tryAttachIsCallable() {
7365 // Self-hosted code calls this with a single argument.
7366 MOZ_ASSERT(args_.length() == 1);
7367
7368 // Initialize the input operand.
7369 initializeInputOperand();
7370
7371 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7372
7373 // Check if the argument is callable and return result.
7374 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7375 writer.isCallableResult(argId);
7376 writer.returnFromIC();
7377
7378 trackAttached("IsCallable");
7379 return AttachDecision::Attach;
7380 }
7381
7382 AttachDecision InlinableNativeIRGenerator::tryAttachIsConstructor() {
7383 // Self-hosted code calls this with a single argument.
7384 MOZ_ASSERT(args_.length() == 1);
7385
7386 // Need a single object argument.
7387 if (!args_[0].isObject()) {
7388 return AttachDecision::NoAction;
7389 }
7390
7391 // Initialize the input operand.
7392 initializeInputOperand();
7393
7394 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7395
7396 // Guard that the argument is an object.
7397 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7398 ObjOperandId objId = writer.guardToObject(argId);
7399
7400 // Check if the argument is a constructor and return result.
7401 writer.isConstructorResult(objId);
7402 writer.returnFromIC();
7403
7404 trackAttached("IsConstructor");
7405 return AttachDecision::Attach;
7406 }
7407
7408 AttachDecision
7409 InlinableNativeIRGenerator::tryAttachIsCrossRealmArrayConstructor() {
7410 // Self-hosted code calls this with an object argument.
7411 MOZ_ASSERT(args_.length() == 1);
7412 MOZ_ASSERT(args_[0].isObject());
7413
7414 if (args_[0].toObject().is<ProxyObject>()) {
7415 return AttachDecision::NoAction;
7416 }
7417
7418 // Initialize the input operand.
7419 initializeInputOperand();
7420
7421 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7422
7423 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7424 ObjOperandId objId = writer.guardToObject(argId);
7425 writer.guardIsNotProxy(objId);
7426 writer.isCrossRealmArrayConstructorResult(objId);
7427 writer.returnFromIC();
7428
7429 trackAttached("IsCrossRealmArrayConstructor");
7430 return AttachDecision::Attach;
7431 }
7432
7433 AttachDecision InlinableNativeIRGenerator::tryAttachCanOptimizeArraySpecies() {
7434 // Self-hosted code calls this with an object argument.
7435 MOZ_ASSERT(args_.length() == 1);
7436 MOZ_ASSERT(args_[0].isObject());
7437
7438 SharedShape* shape = GlobalObject::getArrayShapeWithDefaultProto(cx_);
7439 if (!shape) {
7440 cx_->recoverFromOutOfMemory();
7441 return AttachDecision::NoAction;
7442 }
7443
7444 // Initialize the input operand.
7445 initializeInputOperand();
7446
7447 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7448
7449 if (cx_->realm()->realmFuses.optimizeArraySpeciesFuse.intact()) {
7450 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7451 ObjOperandId objId = writer.guardToObject(argId);
7452 writer.guardFuse(RealmFuses::FuseIndex::OptimizeArraySpeciesFuse);
7453 writer.hasShapeResult(objId, shape);
7454 writer.returnFromIC();
7455 trackAttached("CanOptimizeArraySpecies.Optimized");
7456 } else {
7457 writer.loadBooleanResult(false);
7458 writer.returnFromIC();
7459 trackAttached("CanOptimizeArraySpecies.Deoptimized");
7460 }
7461
7462 return AttachDecision::Attach;
7463 }
7464
7465 AttachDecision
7466 InlinableNativeIRGenerator::tryAttachCanOptimizeStringProtoSymbolLookup() {
7467 // Self-hosted code calls this with no arguments.
7468 MOZ_ASSERT(args_.length() == 0);
7469
7470 // Initialize the input operand.
7471 initializeInputOperand();
7472
7473 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7474
7475 if (cx_->realm()->realmFuses.optimizeStringPrototypeSymbolsFuse.intact()) {
7476 writer.guardFuse(RealmFuses::FuseIndex::OptimizeStringPrototypeSymbolsFuse);
7477 writer.loadBooleanResult(true);
7478 writer.returnFromIC();
7479 trackAttached("CanOptimizeStringProtoSymbolLookup.Optimized");
7480 } else {
7481 writer.loadBooleanResult(false);
7482 writer.returnFromIC();
7483 trackAttached("CanOptimizeStringProtoSymbolLookup.Deoptimized");
7484 }
7485
7486 return AttachDecision::Attach;
7487 }
7488
7489 AttachDecision InlinableNativeIRGenerator::tryAttachGuardToClass(
7490 InlinableNative native) {
7491 // Self-hosted code calls this with an object argument.
7492 MOZ_ASSERT(args_.length() == 1);
7493 MOZ_ASSERT(args_[0].isObject());
7494
7495 // Class must match.
7496 const JSClass* clasp = InlinableNativeGuardToClass(native);
7497 if (args_[0].toObject().getClass() != clasp) {
7498 return AttachDecision::NoAction;
7499 }
7500
7501 // Initialize the input operand.
7502 initializeInputOperand();
7503
7504 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7505
7506 // Guard that the argument is an object.
7507 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7508 ObjOperandId objId = writer.guardToObject(argId);
7509
7510 // Guard that the object has the correct class.
7511 writer.guardAnyClass(objId, clasp);
7512
7513 // Return the object.
7514 writer.loadObjectResult(objId);
7515 writer.returnFromIC();
7516
7517 trackAttached("GuardToClass");
7518 return AttachDecision::Attach;
7519 }
7520
7521 AttachDecision InlinableNativeIRGenerator::tryAttachGuardToClass(
7522 GuardClassKind kind) {
7523 // Self-hosted code calls this with an object argument.
7524 MOZ_ASSERT(args_.length() == 1);
7525 MOZ_ASSERT(args_[0].isObject());
7526
7527 // Class must match.
7528 const JSClass* clasp = ClassFor(kind);
7529 if (args_[0].toObject().getClass() != clasp) {
7530 return AttachDecision::NoAction;
7531 }
7532
7533 // Initialize the input operand.
7534 initializeInputOperand();
7535
7536 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7537
7538 // Guard that the argument is an object.
7539 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7540 ObjOperandId objId = writer.guardToObject(argId);
7541
7542 // Guard that the object has the correct class.
7543 writer.guardClass(objId, kind);
7544
7545 // Return the object.
7546 writer.loadObjectResult(objId);
7547 writer.returnFromIC();
7548
7549 trackAttached("GuardToClass");
7550 return AttachDecision::Attach;
7551 }
7552
7553 AttachDecision InlinableNativeIRGenerator::tryAttachGuardToEitherClass(
7554 GuardClassKind kind1, GuardClassKind kind2) {
7555 MOZ_ASSERT(kind1 != kind2,
7556 "prefer tryAttachGuardToClass for the same class case");
7557
7558 // Self-hosted code calls this with an object argument.
7559 MOZ_ASSERT(args_.length() == 1);
7560 MOZ_ASSERT(args_[0].isObject());
7561
7562 // Class must match.
7563 const JSClass* clasp1 = ClassFor(kind1);
7564 const JSClass* clasp2 = ClassFor(kind2);
7565 const JSClass* objClass = args_[0].toObject().getClass();
7566 if (objClass != clasp1 && objClass != clasp2) {
7567 return AttachDecision::NoAction;
7568 }
7569
7570 // Initialize the input operand.
7571 initializeInputOperand();
7572
7573 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7574
7575 // Guard that the argument is an object.
7576 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7577 ObjOperandId objId = writer.guardToObject(argId);
7578
7579 // Guard that the object has the correct class.
7580 writer.guardEitherClass(objId, kind1, kind2);
7581
7582 // Return the object.
7583 writer.loadObjectResult(objId);
7584 writer.returnFromIC();
7585
7586 trackAttached("GuardToEitherClass");
7587 return AttachDecision::Attach;
7588 }
7589
7590 AttachDecision InlinableNativeIRGenerator::tryAttachGuardToArrayBuffer() {
7591 return tryAttachGuardToEitherClass(GuardClassKind::FixedLengthArrayBuffer,
7592 GuardClassKind::ResizableArrayBuffer);
7593 }
7594
7595 AttachDecision InlinableNativeIRGenerator::tryAttachGuardToSharedArrayBuffer() {
7596 return tryAttachGuardToEitherClass(
7597 GuardClassKind::FixedLengthSharedArrayBuffer,
7598 GuardClassKind::GrowableSharedArrayBuffer);
7599 }
7600
7601 AttachDecision InlinableNativeIRGenerator::tryAttachHasClass(
7602 const JSClass* clasp, bool isPossiblyWrapped) {
7603 // Self-hosted code calls this with an object argument.
7604 MOZ_ASSERT(args_.length() == 1);
7605 MOZ_ASSERT(args_[0].isObject());
7606
7607 // Only optimize when the object isn't a proxy.
7608 if (isPossiblyWrapped && args_[0].toObject().is<ProxyObject>()) {
7609 return AttachDecision::NoAction;
7610 }
7611
7612 // Initialize the input operand.
7613 initializeInputOperand();
7614
7615 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7616
7617 // Perform the Class check.
7618 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7619 ObjOperandId objId = writer.guardToObject(argId);
7620
7621 if (isPossiblyWrapped) {
7622 writer.guardIsNotProxy(objId);
7623 }
7624
7625 writer.hasClassResult(objId, clasp);
7626 writer.returnFromIC();
7627
7628 trackAttached("HasClass");
7629 return AttachDecision::Attach;
7630 }
7631
7632 // Returns whether the .lastIndex property is a non-negative int32 value and is
7633 // still writable.
7634 static bool HasOptimizableLastIndexSlot(RegExpObject* regexp, JSContext* cx) {
7635 auto lastIndexProp = regexp->lookupPure(cx->names().lastIndex);
7636 MOZ_ASSERT(lastIndexProp->isDataProperty());
7637 if (!lastIndexProp->writable()) {
7638 return false;
7639 }
7640 Value lastIndex = regexp->getLastIndex();
7641 if (!lastIndex.isInt32() || lastIndex.toInt32() < 0) {
7642 return false;
7643 }
7644 return true;
7645 }
7646
7647 // Returns the RegExp stub used by the optimized code path for this intrinsic.
7648 // We store a pointer to this in the IC stub to ensure GC doesn't discard it.
7649 static JitCode* GetOrCreateRegExpStub(JSContext* cx, InlinableNative native) {
7650 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
7651 return nullptr;
7652 #else
7653 // The stubs assume the global has non-null RegExpStatics and match result
7654 // shape.
7655 if (!GlobalObject::getRegExpStatics(cx, cx->global()) ||
7656 !cx->global()->regExpRealm().getOrCreateMatchResultShape(cx)) {
7657 MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
7658 cx->clearPendingException();
7659 return nullptr;
7660 }
7661 JitZone::StubKind kind;
7662 switch (native) {
7663 case InlinableNative::IntrinsicRegExpBuiltinExecForTest:
7664 case InlinableNative::IntrinsicRegExpExecForTest:
7665 kind = JitZone::StubKind::RegExpExecTest;
7666 break;
7667 case InlinableNative::IntrinsicRegExpBuiltinExec:
7668 case InlinableNative::IntrinsicRegExpExec:
7669 kind = JitZone::StubKind::RegExpExecMatch;
7670 break;
7671 case InlinableNative::RegExpMatcher:
7672 kind = JitZone::StubKind::RegExpMatcher;
7673 break;
7674 case InlinableNative::RegExpSearcher:
7675 kind = JitZone::StubKind::RegExpSearcher;
7676 break;
7677 default:
7678 MOZ_CRASH("Unexpected native");
7679 }
7680 JitCode* code = cx->zone()->jitZone()->ensureStubExists(cx, kind);
7681 if (!code) {
7682 MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
7683 cx->clearPendingException();
7684 return nullptr;
7685 }
7686 return code;
7687 #endif
7688 }
7689
7690 static void EmitGuardLastIndexIsNonNegativeInt32(CacheIRWriter& writer,
7691 ObjOperandId regExpId) {
7692 size_t offset =
7693 NativeObject::getFixedSlotOffset(RegExpObject::lastIndexSlot());
7694 ValOperandId lastIndexValId = writer.loadFixedSlot(regExpId, offset);
7695 Int32OperandId lastIndexId = writer.guardToInt32(lastIndexValId);
7696 writer.guardInt32IsNonNegative(lastIndexId);
7697 }
7698
7699 AttachDecision InlinableNativeIRGenerator::tryAttachIntrinsicRegExpBuiltinExec(
7700 InlinableNative native) {
7701 // Self-hosted code calls this with (regexp, string) arguments.
7702 MOZ_ASSERT(args_.length() == 2);
7703 MOZ_ASSERT(args_[0].isObject());
7704 MOZ_ASSERT(args_[1].isString());
7705
7706 JitCode* stub = GetOrCreateRegExpStub(cx_, native);
7707 if (!stub) {
7708 return AttachDecision::NoAction;
7709 }
7710
7711 RegExpObject* re = &args_[0].toObject().as<RegExpObject>();
7712 if (!HasOptimizableLastIndexSlot(re, cx_)) {
7713 return AttachDecision::NoAction;
7714 }
7715
7716 // Initialize the input operand.
7717 initializeInputOperand();
7718
7719 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7720
7721 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7722 ObjOperandId regExpId = writer.guardToObject(arg0Id);
7723 writer.guardShape(regExpId, re->shape());
7724 EmitGuardLastIndexIsNonNegativeInt32(writer, regExpId);
7725
7726 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
7727 StringOperandId inputId = writer.guardToString(arg1Id);
7728
7729 if (native == InlinableNative::IntrinsicRegExpBuiltinExecForTest) {
7730 writer.regExpBuiltinExecTestResult(regExpId, inputId, stub);
7731 } else {
7732 writer.regExpBuiltinExecMatchResult(regExpId, inputId, stub);
7733 }
7734 writer.returnFromIC();
7735
7736 trackAttached("IntrinsicRegExpBuiltinExec");
7737 return AttachDecision::Attach;
7738 }
7739
7740 AttachDecision InlinableNativeIRGenerator::tryAttachIntrinsicRegExpExec(
7741 InlinableNative native) {
7742 // Self-hosted code calls this with (object, string) arguments.
7743 MOZ_ASSERT(args_.length() == 2);
7744 MOZ_ASSERT(args_[0].isObject());
7745 MOZ_ASSERT(args_[1].isString());
7746
7747 // Ensure the object is a RegExpObject with the builtin RegExp.prototype.exec
7748 // function.
7749 if (!IsOptimizableRegExpObject(&args_[0].toObject(), cx_)) {
7750 return AttachDecision::NoAction;
7751 }
7752
7753 JitCode* stub = GetOrCreateRegExpStub(cx_, native);
7754 if (!stub) {
7755 return AttachDecision::NoAction;
7756 }
7757
7758 RegExpObject* re = &args_[0].toObject().as<RegExpObject>();
7759 if (!HasOptimizableLastIndexSlot(re, cx_)) {
7760 return AttachDecision::NoAction;
7761 }
7762
7763 // Initialize the input operand.
7764 initializeInputOperand();
7765
7766 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7767
7768 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7769 ObjOperandId regExpId = writer.guardToObject(arg0Id);
7770 writer.guardShape(regExpId, re->shape());
7771 writer.guardFuse(RealmFuses::FuseIndex::OptimizeRegExpPrototypeFuse);
7772 EmitGuardLastIndexIsNonNegativeInt32(writer, regExpId);
7773
7774 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
7775 StringOperandId inputId = writer.guardToString(arg1Id);
7776
7777 if (native == InlinableNative::IntrinsicRegExpExecForTest) {
7778 writer.regExpBuiltinExecTestResult(regExpId, inputId, stub);
7779 } else {
7780 writer.regExpBuiltinExecMatchResult(regExpId, inputId, stub);
7781 }
7782 writer.returnFromIC();
7783
7784 trackAttached("IntrinsicRegExpExec");
7785 return AttachDecision::Attach;
7786 }
7787
7788 AttachDecision InlinableNativeIRGenerator::tryAttachRegExpMatcherSearcher(
7789 InlinableNative native) {
7790 // Self-hosted code calls this with (object, string, number) arguments.
7791 MOZ_ASSERT(args_.length() == 3);
7792 MOZ_ASSERT(args_[0].isObject());
7793 MOZ_ASSERT(args_[1].isString());
7794 MOZ_ASSERT(args_[2].isNumber());
7795
7796 // It's not guaranteed that the JITs have typed |lastIndex| as an Int32.
7797 if (!args_[2].isInt32()) {
7798 return AttachDecision::NoAction;
7799 }
7800
7801 JitCode* stub = GetOrCreateRegExpStub(cx_, native);
7802 if (!stub) {
7803 return AttachDecision::NoAction;
7804 }
7805
7806 // Initialize the input operand.
7807 initializeInputOperand();
7808
7809 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7810
7811 // Guard argument types.
7812 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7813 ObjOperandId reId = writer.guardToObject(arg0Id);
7814
7815 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
7816 StringOperandId inputId = writer.guardToString(arg1Id);
7817
7818 ValOperandId arg2Id = loadArgumentIntrinsic(ArgumentKind::Arg2);
7819 Int32OperandId lastIndexId = writer.guardToInt32(arg2Id);
7820
7821 switch (native) {
7822 case InlinableNative::RegExpMatcher:
7823 writer.callRegExpMatcherResult(reId, inputId, lastIndexId, stub);
7824 writer.returnFromIC();
7825 trackAttached("RegExpMatcher");
7826 break;
7827
7828 case InlinableNative::RegExpSearcher:
7829 writer.callRegExpSearcherResult(reId, inputId, lastIndexId, stub);
7830 writer.returnFromIC();
7831 trackAttached("RegExpSearcher");
7832 break;
7833
7834 default:
7835 MOZ_CRASH("Unexpected native");
7836 }
7837
7838 return AttachDecision::Attach;
7839 }
7840
7841 AttachDecision InlinableNativeIRGenerator::tryAttachRegExpSearcherLastLimit() {
7842 // Self-hosted code calls this with a string argument that's only used for an
7843 // assertion.
7844 MOZ_ASSERT(args_.length() == 1);
7845 MOZ_ASSERT(args_[0].isString());
7846
7847 // Initialize the input operand.
7848 initializeInputOperand();
7849
7850 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7851
7852 writer.regExpSearcherLastLimitResult();
7853 writer.returnFromIC();
7854
7855 trackAttached("RegExpSearcherLastLimit");
7856 return AttachDecision::Attach;
7857 }
7858
7859 AttachDecision InlinableNativeIRGenerator::tryAttachRegExpHasCaptureGroups() {
7860 // Self-hosted code calls this with object and string arguments.
7861 MOZ_ASSERT(args_.length() == 2);
7862 MOZ_ASSERT(args_[0].toObject().is<RegExpObject>());
7863 MOZ_ASSERT(args_[1].isString());
7864
7865 // Initialize the input operand.
7866 initializeInputOperand();
7867
7868 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7869
7870 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7871 ObjOperandId objId = writer.guardToObject(arg0Id);
7872
7873 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
7874 StringOperandId inputId = writer.guardToString(arg1Id);
7875
7876 writer.regExpHasCaptureGroupsResult(objId, inputId);
7877 writer.returnFromIC();
7878
7879 trackAttached("RegExpHasCaptureGroups");
7880 return AttachDecision::Attach;
7881 }
7882
7883 AttachDecision
7884 InlinableNativeIRGenerator::tryAttachIsRegExpPrototypeOptimizable() {
7885 // Self-hosted code calls this with no arguments.
7886 MOZ_ASSERT(args_.length() == 0);
7887
7888 // Initialize the input operand.
7889 initializeInputOperand();
7890
7891 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7892
7893 if (cx_->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact()) {
7894 writer.guardFuse(RealmFuses::FuseIndex::OptimizeRegExpPrototypeFuse);
7895 writer.loadBooleanResult(true);
7896 writer.returnFromIC();
7897 trackAttached("IsRegExpPrototypeOptimizable.Optimized");
7898 } else {
7899 writer.loadBooleanResult(false);
7900 writer.returnFromIC();
7901 trackAttached("IsRegExpPrototypeOptimizable.Deoptimized");
7902 }
7903
7904 return AttachDecision::Attach;
7905 }
7906
7907 AttachDecision
7908 InlinableNativeIRGenerator::tryAttachIsOptimizableRegExpObject() {
7909 // Self-hosted code calls this with a single object argument.
7910 MOZ_ASSERT(args_.length() == 1);
7911 MOZ_ASSERT(args_[0].isObject());
7912
7913 Shape* optimizableShape = cx_->global()->maybeRegExpShapeWithDefaultProto();
7914 if (!optimizableShape) {
7915 return AttachDecision::NoAction;
7916 }
7917
7918 // Initialize the input operand.
7919 initializeInputOperand();
7920
7921 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7922
7923 if (cx_->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact()) {
7924 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
7925 ObjOperandId objId = writer.guardToObject(argId);
7926 writer.guardFuse(RealmFuses::FuseIndex::OptimizeRegExpPrototypeFuse);
7927 writer.hasShapeResult(objId, optimizableShape);
7928 writer.returnFromIC();
7929 trackAttached("IsOptimizableRegExpObject.Optimized");
7930 } else {
7931 writer.loadBooleanResult(false);
7932 writer.returnFromIC();
7933 trackAttached("IsOptimizableRegExpObject.Deoptimized");
7934 }
7935
7936 return AttachDecision::Attach;
7937 }
7938
7939 AttachDecision InlinableNativeIRGenerator::tryAttachGetFirstDollarIndex() {
7940 // Self-hosted code calls this with a single string argument.
7941 MOZ_ASSERT(args_.length() == 1);
7942 MOZ_ASSERT(args_[0].isString());
7943
7944 // Initialize the input operand.
7945 initializeInputOperand();
7946
7947 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7948
7949 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7950 StringOperandId strId = writer.guardToString(arg0Id);
7951
7952 writer.getFirstDollarIndexResult(strId);
7953 writer.returnFromIC();
7954
7955 trackAttached("GetFirstDollarIndex");
7956 return AttachDecision::Attach;
7957 }
7958
7959 AttachDecision InlinableNativeIRGenerator::tryAttachSubstringKernel() {
7960 // Self-hosted code calls this with (string, int32, int32) arguments.
7961 MOZ_ASSERT(args_.length() == 3);
7962 MOZ_ASSERT(args_[0].isString());
7963 MOZ_ASSERT(args_[1].isInt32());
7964 MOZ_ASSERT(args_[2].isInt32());
7965
7966 // Initialize the input operand.
7967 initializeInputOperand();
7968
7969 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
7970
7971 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
7972 StringOperandId strId = writer.guardToString(arg0Id);
7973
7974 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
7975 Int32OperandId beginId = writer.guardToInt32(arg1Id);
7976
7977 ValOperandId arg2Id = loadArgumentIntrinsic(ArgumentKind::Arg2);
7978 Int32OperandId lengthId = writer.guardToInt32(arg2Id);
7979
7980 writer.callSubstringKernelResult(strId, beginId, lengthId);
7981 writer.returnFromIC();
7982
7983 trackAttached("SubstringKernel");
7984 return AttachDecision::Attach;
7985 }
7986
7987 static bool CanConvertToString(const Value& v) {
7988 return v.isString() || v.isNumber() || v.isBoolean() || v.isNullOrUndefined();
7989 }
7990
7991 AttachDecision InlinableNativeIRGenerator::tryAttachString() {
7992 // Need a single argument that is or can be converted to a string.
7993 if (args_.length() != 1 || !CanConvertToString(args_[0])) {
7994 return AttachDecision::NoAction;
7995 }
7996
7997 // Initialize the input operand.
7998 Int32OperandId argcId = initializeInputOperand();
7999
8000 // Guard callee is the 'String' function.
8001 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8002
8003 // Guard that the argument is a string or can be converted to one.
8004 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8005 StringOperandId strId = emitToStringGuard(argId, args_[0]);
8006
8007 // Return the string.
8008 writer.loadStringResult(strId);
8009 writer.returnFromIC();
8010
8011 trackAttached("String");
8012 return AttachDecision::Attach;
8013 }
8014
8015 AttachDecision InlinableNativeIRGenerator::tryAttachStringConstructor() {
8016 // Need a single argument that is or can be converted to a string.
8017 if (args_.length() != 1 || !CanConvertToString(args_[0])) {
8018 return AttachDecision::NoAction;
8019 }
8020
8021 RootedString emptyString(cx_, cx_->runtime()->emptyString);
8022 JSObject* templateObj = StringObject::create(
8023 cx_, emptyString, /* proto = */ nullptr, TenuredObject);
8024 if (!templateObj) {
8025 cx_->recoverFromOutOfMemory();
8026 return AttachDecision::NoAction;
8027 }
8028
8029 // Initialize the input operand.
8030 Int32OperandId argcId = initializeInputOperand();
8031
8032 // Guard callee is the 'String' function.
8033 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8034
8035 // Guard on number and convert to string.
8036 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8037 StringOperandId strId = emitToStringGuard(argId, args_[0]);
8038
8039 writer.newStringObjectResult(templateObj, strId);
8040 writer.returnFromIC();
8041
8042 trackAttached("StringConstructor");
8043 return AttachDecision::Attach;
8044 }
8045
8046 AttachDecision InlinableNativeIRGenerator::tryAttachStringToStringValueOf() {
8047 // Expecting no arguments.
8048 if (args_.length() != 0) {
8049 return AttachDecision::NoAction;
8050 }
8051
8052 // Ensure |this| is a primitive string value.
8053 if (!thisval_.isString()) {
8054 return AttachDecision::NoAction;
8055 }
8056
8057 // Initialize the input operand.
8058 Int32OperandId argcId = initializeInputOperand();
8059
8060 // Guard callee is the 'toString' OR 'valueOf' native function.
8061 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8062
8063 // Guard |this| is a string.
8064 ValOperandId thisValId = loadThis(calleeId);
8065 StringOperandId strId = writer.guardToString(thisValId);
8066
8067 // Return the string
8068 writer.loadStringResult(strId);
8069 writer.returnFromIC();
8070
8071 trackAttached("StringToStringValueOf");
8072 return AttachDecision::Attach;
8073 }
8074
8075 AttachDecision InlinableNativeIRGenerator::tryAttachStringReplaceString() {
8076 // Self-hosted code calls this with (string, string, string) arguments.
8077 MOZ_ASSERT(args_.length() == 3);
8078 MOZ_ASSERT(args_[0].isString());
8079 MOZ_ASSERT(args_[1].isString());
8080 MOZ_ASSERT(args_[2].isString());
8081
8082 // Initialize the input operand.
8083 initializeInputOperand();
8084
8085 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
8086
8087 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
8088 StringOperandId strId = writer.guardToString(arg0Id);
8089
8090 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
8091 StringOperandId patternId = writer.guardToString(arg1Id);
8092
8093 ValOperandId arg2Id = loadArgumentIntrinsic(ArgumentKind::Arg2);
8094 StringOperandId replacementId = writer.guardToString(arg2Id);
8095
8096 writer.stringReplaceStringResult(strId, patternId, replacementId);
8097 writer.returnFromIC();
8098
8099 trackAttached("StringReplaceString");
8100 return AttachDecision::Attach;
8101 }
8102
8103 AttachDecision InlinableNativeIRGenerator::tryAttachStringSplitString() {
8104 // Self-hosted code calls this with (string, string) arguments.
8105 MOZ_ASSERT(args_.length() == 2);
8106 MOZ_ASSERT(args_[0].isString());
8107 MOZ_ASSERT(args_[1].isString());
8108
8109 // Initialize the input operand.
8110 initializeInputOperand();
8111
8112 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
8113
8114 ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
8115 StringOperandId strId = writer.guardToString(arg0Id);
8116
8117 ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
8118 StringOperandId separatorId = writer.guardToString(arg1Id);
8119
8120 writer.stringSplitStringResult(strId, separatorId);
8121 writer.returnFromIC();
8122
8123 trackAttached("StringSplitString");
8124 return AttachDecision::Attach;
8125 }
8126
8127 AttachDecision InlinableNativeIRGenerator::tryAttachStringChar(
8128 StringChar kind) {
8129 // Need one argument.
8130 if (args_.length() != 1) {
8131 return AttachDecision::NoAction;
8132 }
8133
8134 auto attach = CanAttachStringChar(thisval_, args_[0], kind);
8135 if (attach == AttachStringChar::No) {
8136 return AttachDecision::NoAction;
8137 }
8138
8139 bool handleOOB = attach == AttachStringChar::OutOfBounds;
8140
8141 // Initialize the input operand.
8142 Int32OperandId argcId = initializeInputOperand();
8143
8144 // Guard callee is the 'charCodeAt', 'codePointAt', 'charAt', or 'at' native
8145 // function.
8146 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8147
8148 // Guard this is a string.
8149 ValOperandId thisValId = loadThis(calleeId);
8150 StringOperandId strId = writer.guardToString(thisValId);
8151
8152 // Guard int32 index.
8153 ValOperandId indexId = loadArgument(calleeId, ArgumentKind::Arg0);
8154 Int32OperandId int32IndexId =
8155 EmitGuardToInt32Index(writer, args_[0], indexId);
8156
8157 // Handle relative string indices, if necessary.
8158 if (kind == StringChar::At) {
8159 int32IndexId = writer.toRelativeStringIndex(int32IndexId, strId);
8160 }
8161
8162 // Linearize the string.
8163 //
8164 // AttachStringChar doesn't have a separate state when OOB access happens on
8165 // a string which needs to be linearized, so just linearize unconditionally
8166 // for out-of-bounds accesses.
8167 if (attach == AttachStringChar::Linearize ||
8168 attach == AttachStringChar::OutOfBounds) {
8169 switch (kind) {
8170 case StringChar::CharCodeAt:
8171 case StringChar::CharAt:
8172 case StringChar::At:
8173 strId = writer.linearizeForCharAccess(strId, int32IndexId);
8174 break;
8175 case StringChar::CodePointAt:
8176 strId = writer.linearizeForCodePointAccess(strId, int32IndexId);
8177 break;
8178 }
8179 }
8180
8181 // Load string char or code.
8182 switch (kind) {
8183 case StringChar::CharCodeAt:
8184 writer.loadStringCharCodeResult(strId, int32IndexId, handleOOB);
8185 break;
8186 case StringChar::CodePointAt:
8187 writer.loadStringCodePointResult(strId, int32IndexId, handleOOB);
8188 break;
8189 case StringChar::CharAt:
8190 writer.loadStringCharResult(strId, int32IndexId, handleOOB);
8191 break;
8192 case StringChar::At:
8193 writer.loadStringAtResult(strId, int32IndexId, handleOOB);
8194 break;
8195 }
8196
8197 writer.returnFromIC();
8198
8199 switch (kind) {
8200 case StringChar::CharCodeAt:
8201 trackAttached("StringCharCodeAt");
8202 break;
8203 case StringChar::CodePointAt:
8204 trackAttached("StringCodePointAt");
8205 break;
8206 case StringChar::CharAt:
8207 trackAttached("StringCharAt");
8208 break;
8209 case StringChar::At:
8210 trackAttached("StringAt");
8211 break;
8212 }
8213
8214 return AttachDecision::Attach;
8215 }
8216
8217 AttachDecision InlinableNativeIRGenerator::tryAttachStringCharCodeAt() {
8218 return tryAttachStringChar(StringChar::CharCodeAt);
8219 }
8220
8221 AttachDecision InlinableNativeIRGenerator::tryAttachStringCodePointAt() {
8222 return tryAttachStringChar(StringChar::CodePointAt);
8223 }
8224
8225 AttachDecision InlinableNativeIRGenerator::tryAttachStringCharAt() {
8226 return tryAttachStringChar(StringChar::CharAt);
8227 }
8228
8229 AttachDecision InlinableNativeIRGenerator::tryAttachStringAt() {
8230 return tryAttachStringChar(StringChar::At);
8231 }
8232
8233 AttachDecision InlinableNativeIRGenerator::tryAttachStringFromCharCode() {
8234 // Need one number argument.
8235 if (args_.length() != 1 || !args_[0].isNumber()) {
8236 return AttachDecision::NoAction;
8237 }
8238
8239 // Initialize the input operand.
8240 Int32OperandId argcId = initializeInputOperand();
8241
8242 // Guard callee is the 'fromCharCode' native function.
8243 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8244
8245 // Guard int32 argument.
8246 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8247 Int32OperandId codeId;
8248 if (args_[0].isInt32()) {
8249 codeId = writer.guardToInt32(argId);
8250 } else {
8251 // 'fromCharCode' performs ToUint16 on its input. We can use Uint32
8252 // semantics, because ToUint16(ToUint32(v)) == ToUint16(v).
8253 codeId = writer.guardToInt32ModUint32(argId);
8254 }
8255
8256 // Return string created from code.
8257 writer.stringFromCharCodeResult(codeId);
8258 writer.returnFromIC();
8259
8260 trackAttached("StringFromCharCode");
8261 return AttachDecision::Attach;
8262 }
8263
8264 AttachDecision InlinableNativeIRGenerator::tryAttachStringFromCodePoint() {
8265 // Need one int32 argument.
8266 if (args_.length() != 1 || !args_[0].isInt32()) {
8267 return AttachDecision::NoAction;
8268 }
8269
8270 // String.fromCodePoint throws for invalid code points.
8271 int32_t codePoint = args_[0].toInt32();
8272 if (codePoint < 0 || codePoint > int32_t(unicode::NonBMPMax)) {
8273 return AttachDecision::NoAction;
8274 }
8275
8276 // Initialize the input operand.
8277 Int32OperandId argcId = initializeInputOperand();
8278
8279 // Guard callee is the 'fromCodePoint' native function.
8280 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8281
8282 // Guard int32 argument.
8283 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8284 Int32OperandId codeId = writer.guardToInt32(argId);
8285
8286 // Return string created from code point.
8287 writer.stringFromCodePointResult(codeId);
8288 writer.returnFromIC();
8289
8290 trackAttached("StringFromCodePoint");
8291 return AttachDecision::Attach;
8292 }
8293
8294 AttachDecision InlinableNativeIRGenerator::tryAttachStringIncludes() {
8295 // Need one string argument.
8296 if (args_.length() != 1 || !args_[0].isString()) {
8297 return AttachDecision::NoAction;
8298 }
8299
8300 // Ensure |this| is a primitive string value.
8301 if (!thisval_.isString()) {
8302 return AttachDecision::NoAction;
8303 }
8304
8305 // Initialize the input operand.
8306 Int32OperandId argcId = initializeInputOperand();
8307
8308 // Guard callee is the 'includes' native function.
8309 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8310
8311 // Guard this is a string.
8312 ValOperandId thisValId = loadThis(calleeId);
8313 StringOperandId strId = writer.guardToString(thisValId);
8314
8315 // Guard string argument.
8316 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8317 StringOperandId searchStrId = writer.guardToString(argId);
8318
8319 writer.stringIncludesResult(strId, searchStrId);
8320 writer.returnFromIC();
8321
8322 trackAttached("StringIncludes");
8323 return AttachDecision::Attach;
8324 }
8325
8326 AttachDecision InlinableNativeIRGenerator::tryAttachStringIndexOf() {
8327 // Need one string argument.
8328 if (args_.length() != 1 || !args_[0].isString()) {
8329 return AttachDecision::NoAction;
8330 }
8331
8332 // Ensure |this| is a primitive string value.
8333 if (!thisval_.isString()) {
8334 return AttachDecision::NoAction;
8335 }
8336
8337 // Initialize the input operand.
8338 Int32OperandId argcId = initializeInputOperand();
8339
8340 // Guard callee is the 'indexOf' native function.
8341 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8342
8343 // Guard this is a string.
8344 ValOperandId thisValId = loadThis(calleeId);
8345 StringOperandId strId = writer.guardToString(thisValId);
8346
8347 // Guard string argument.
8348 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8349 StringOperandId searchStrId = writer.guardToString(argId);
8350
8351 writer.stringIndexOfResult(strId, searchStrId);
8352 writer.returnFromIC();
8353
8354 trackAttached("StringIndexOf");
8355 return AttachDecision::Attach;
8356 }
8357
8358 AttachDecision InlinableNativeIRGenerator::tryAttachStringLastIndexOf() {
8359 // Need one string argument.
8360 if (args_.length() != 1 || !args_[0].isString()) {
8361 return AttachDecision::NoAction;
8362 }
8363
8364 // Ensure |this| is a primitive string value.
8365 if (!thisval_.isString()) {
8366 return AttachDecision::NoAction;
8367 }
8368
8369 // Initialize the input operand.
8370 Int32OperandId argcId = initializeInputOperand();
8371
8372 // Guard callee is the 'lastIndexOf' native function.
8373 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8374
8375 // Guard this is a string.
8376 ValOperandId thisValId = loadThis(calleeId);
8377 StringOperandId strId = writer.guardToString(thisValId);
8378
8379 // Guard string argument.
8380 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8381 StringOperandId searchStrId = writer.guardToString(argId);
8382
8383 writer.stringLastIndexOfResult(strId, searchStrId);
8384 writer.returnFromIC();
8385
8386 trackAttached("StringLastIndexOf");
8387 return AttachDecision::Attach;
8388 }
8389
8390 AttachDecision InlinableNativeIRGenerator::tryAttachStringStartsWith() {
8391 // Need one string argument.
8392 if (args_.length() != 1 || !args_[0].isString()) {
8393 return AttachDecision::NoAction;
8394 }
8395
8396 // Ensure |this| is a primitive string value.
8397 if (!thisval_.isString()) {
8398 return AttachDecision::NoAction;
8399 }
8400
8401 // Initialize the input operand.
8402 Int32OperandId argcId = initializeInputOperand();
8403
8404 // Guard callee is the 'startsWith' native function.
8405 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8406
8407 // Guard this is a string.
8408 ValOperandId thisValId = loadThis(calleeId);
8409 StringOperandId strId = writer.guardToString(thisValId);
8410
8411 // Guard string argument.
8412 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8413 StringOperandId searchStrId = writer.guardToString(argId);
8414
8415 writer.stringStartsWithResult(strId, searchStrId);
8416 writer.returnFromIC();
8417
8418 trackAttached("StringStartsWith");
8419 return AttachDecision::Attach;
8420 }
8421
8422 AttachDecision InlinableNativeIRGenerator::tryAttachStringEndsWith() {
8423 // Need one string argument.
8424 if (args_.length() != 1 || !args_[0].isString()) {
8425 return AttachDecision::NoAction;
8426 }
8427
8428 // Ensure |this| is a primitive string value.
8429 if (!thisval_.isString()) {
8430 return AttachDecision::NoAction;
8431 }
8432
8433 // Initialize the input operand.
8434 Int32OperandId argcId = initializeInputOperand();
8435
8436 // Guard callee is the 'endsWith' native function.
8437 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8438
8439 // Guard this is a string.
8440 ValOperandId thisValId = loadThis(calleeId);
8441 StringOperandId strId = writer.guardToString(thisValId);
8442
8443 // Guard string argument.
8444 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8445 StringOperandId searchStrId = writer.guardToString(argId);
8446
8447 writer.stringEndsWithResult(strId, searchStrId);
8448 writer.returnFromIC();
8449
8450 trackAttached("StringEndsWith");
8451 return AttachDecision::Attach;
8452 }
8453
8454 AttachDecision InlinableNativeIRGenerator::tryAttachStringToLowerCase() {
8455 // Expecting no arguments.
8456 if (args_.length() != 0) {
8457 return AttachDecision::NoAction;
8458 }
8459
8460 // Ensure |this| is a primitive string value.
8461 if (!thisval_.isString()) {
8462 return AttachDecision::NoAction;
8463 }
8464
8465 // Initialize the input operand.
8466 Int32OperandId argcId = initializeInputOperand();
8467
8468 // Guard callee is the 'toLowerCase' native function.
8469 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8470
8471 // Guard this is a string.
8472 ValOperandId thisValId = loadThis(calleeId);
8473 StringOperandId strId = writer.guardToString(thisValId);
8474
8475 // Return string converted to lower-case.
8476 writer.stringToLowerCaseResult(strId);
8477 writer.returnFromIC();
8478
8479 trackAttached("StringToLowerCase");
8480 return AttachDecision::Attach;
8481 }
8482
8483 AttachDecision InlinableNativeIRGenerator::tryAttachStringToUpperCase() {
8484 // Expecting no arguments.
8485 if (args_.length() != 0) {
8486 return AttachDecision::NoAction;
8487 }
8488
8489 // Ensure |this| is a primitive string value.
8490 if (!thisval_.isString()) {
8491 return AttachDecision::NoAction;
8492 }
8493
8494 // Initialize the input operand.
8495 Int32OperandId argcId = initializeInputOperand();
8496
8497 // Guard callee is the 'toUpperCase' native function.
8498 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8499
8500 // Guard this is a string.
8501 ValOperandId thisValId = loadThis(calleeId);
8502 StringOperandId strId = writer.guardToString(thisValId);
8503
8504 // Return string converted to upper-case.
8505 writer.stringToUpperCaseResult(strId);
8506 writer.returnFromIC();
8507
8508 trackAttached("StringToUpperCase");
8509 return AttachDecision::Attach;
8510 }
8511
8512 AttachDecision InlinableNativeIRGenerator::tryAttachStringTrim() {
8513 // Expecting no arguments.
8514 if (args_.length() != 0) {
8515 return AttachDecision::NoAction;
8516 }
8517
8518 // Ensure |this| is a primitive string value.
8519 if (!thisval_.isString()) {
8520 return AttachDecision::NoAction;
8521 }
8522
8523 // Initialize the input operand.
8524 Int32OperandId argcId = initializeInputOperand();
8525
8526 // Guard callee is the 'trim' native function.
8527 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8528
8529 // Guard this is a string.
8530 ValOperandId thisValId = loadThis(calleeId);
8531 StringOperandId strId = writer.guardToString(thisValId);
8532
8533 writer.stringTrimResult(strId);
8534 writer.returnFromIC();
8535
8536 trackAttached("StringTrim");
8537 return AttachDecision::Attach;
8538 }
8539
8540 AttachDecision InlinableNativeIRGenerator::tryAttachStringTrimStart() {
8541 // Expecting no arguments.
8542 if (args_.length() != 0) {
8543 return AttachDecision::NoAction;
8544 }
8545
8546 // Ensure |this| is a primitive string value.
8547 if (!thisval_.isString()) {
8548 return AttachDecision::NoAction;
8549 }
8550
8551 // Initialize the input operand.
8552 Int32OperandId argcId = initializeInputOperand();
8553
8554 // Guard callee is the 'trimStart' native function.
8555 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8556
8557 // Guard this is a string.
8558 ValOperandId thisValId = loadThis(calleeId);
8559 StringOperandId strId = writer.guardToString(thisValId);
8560
8561 writer.stringTrimStartResult(strId);
8562 writer.returnFromIC();
8563
8564 trackAttached("StringTrimStart");
8565 return AttachDecision::Attach;
8566 }
8567
8568 AttachDecision InlinableNativeIRGenerator::tryAttachStringTrimEnd() {
8569 // Expecting no arguments.
8570 if (args_.length() != 0) {
8571 return AttachDecision::NoAction;
8572 }
8573
8574 // Ensure |this| is a primitive string value.
8575 if (!thisval_.isString()) {
8576 return AttachDecision::NoAction;
8577 }
8578
8579 // Initialize the input operand.
8580 Int32OperandId argcId = initializeInputOperand();
8581
8582 // Guard callee is the 'trimEnd' native function.
8583 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8584
8585 // Guard this is a string.
8586 ValOperandId thisValId = loadThis(calleeId);
8587 StringOperandId strId = writer.guardToString(thisValId);
8588
8589 writer.stringTrimEndResult(strId);
8590 writer.returnFromIC();
8591
8592 trackAttached("StringTrimEnd");
8593 return AttachDecision::Attach;
8594 }
8595
8596 AttachDecision InlinableNativeIRGenerator::tryAttachMathRandom() {
8597 // Expecting no arguments.
8598 if (args_.length() != 0) {
8599 return AttachDecision::NoAction;
8600 }
8601
8602 MOZ_ASSERT(cx_->realm() == target_->realm(),
8603 "Shouldn't inline cross-realm Math.random because per-realm RNG");
8604
8605 // Initialize the input operand.
8606 Int32OperandId argcId = initializeInputOperand();
8607
8608 // Guard callee is the 'random' native function.
8609 emitNativeCalleeGuard(argcId);
8610
8611 mozilla::non_crypto::XorShift128PlusRNG* rng =
8612 &cx_->realm()->getOrCreateRandomNumberGenerator();
8613 writer.mathRandomResult(rng);
8614
8615 writer.returnFromIC();
8616
8617 trackAttached("MathRandom");
8618 return AttachDecision::Attach;
8619 }
8620
8621 AttachDecision InlinableNativeIRGenerator::tryAttachMathAbs() {
8622 // Need one argument.
8623 if (args_.length() != 1) {
8624 return AttachDecision::NoAction;
8625 }
8626
8627 if (!args_[0].isNumber()) {
8628 return AttachDecision::NoAction;
8629 }
8630
8631 // Initialize the input operand.
8632 Int32OperandId argcId = initializeInputOperand();
8633
8634 // Guard callee is the 'abs' native function.
8635 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8636
8637 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8638
8639 // abs(INT_MIN) is a double.
8640 if (args_[0].isInt32() && args_[0].toInt32() != INT_MIN) {
8641 Int32OperandId int32Id = writer.guardToInt32(argumentId);
8642 writer.mathAbsInt32Result(int32Id);
8643 } else {
8644 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8645 writer.mathAbsNumberResult(numberId);
8646 }
8647
8648 writer.returnFromIC();
8649
8650 trackAttached("MathAbs");
8651 return AttachDecision::Attach;
8652 }
8653
8654 AttachDecision InlinableNativeIRGenerator::tryAttachMathClz32() {
8655 // Need one (number) argument.
8656 if (args_.length() != 1 || !args_[0].isNumber()) {
8657 return AttachDecision::NoAction;
8658 }
8659
8660 // Initialize the input operand.
8661 Int32OperandId argcId = initializeInputOperand();
8662
8663 // Guard callee is the 'clz32' native function.
8664 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8665
8666 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8667
8668 Int32OperandId int32Id;
8669 if (args_[0].isInt32()) {
8670 int32Id = writer.guardToInt32(argId);
8671 } else {
8672 MOZ_ASSERT(args_[0].isDouble());
8673 NumberOperandId numId = writer.guardIsNumber(argId);
8674 int32Id = writer.truncateDoubleToUInt32(numId);
8675 }
8676 writer.mathClz32Result(int32Id);
8677 writer.returnFromIC();
8678
8679 trackAttached("MathClz32");
8680 return AttachDecision::Attach;
8681 }
8682
8683 AttachDecision InlinableNativeIRGenerator::tryAttachMathSign() {
8684 // Need one (number) argument.
8685 if (args_.length() != 1 || !args_[0].isNumber()) {
8686 return AttachDecision::NoAction;
8687 }
8688
8689 // Initialize the input operand.
8690 Int32OperandId argcId = initializeInputOperand();
8691
8692 // Guard callee is the 'sign' native function.
8693 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8694
8695 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
8696
8697 if (args_[0].isInt32()) {
8698 Int32OperandId int32Id = writer.guardToInt32(argId);
8699 writer.mathSignInt32Result(int32Id);
8700 } else {
8701 // Math.sign returns a double only if the input is -0 or NaN so try to
8702 // optimize the common Number => Int32 case.
8703 double d = math_sign_impl(args_[0].toDouble());
8704 int32_t unused;
8705 bool resultIsInt32 = mozilla::NumberIsInt32(d, &unused);
8706
8707 NumberOperandId numId = writer.guardIsNumber(argId);
8708 if (resultIsInt32) {
8709 writer.mathSignNumberToInt32Result(numId);
8710 } else {
8711 writer.mathSignNumberResult(numId);
8712 }
8713 }
8714
8715 writer.returnFromIC();
8716
8717 trackAttached("MathSign");
8718 return AttachDecision::Attach;
8719 }
8720
8721 AttachDecision InlinableNativeIRGenerator::tryAttachMathImul() {
8722 // Need two (number) arguments.
8723 if (args_.length() != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
8724 return AttachDecision::NoAction;
8725 }
8726
8727 // Initialize the input operand.
8728 Int32OperandId argcId = initializeInputOperand();
8729
8730 // Guard callee is the 'imul' native function.
8731 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8732
8733 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
8734 ValOperandId arg1Id = loadArgument(calleeId, ArgumentKind::Arg1);
8735
8736 Int32OperandId int32Arg0Id, int32Arg1Id;
8737 if (args_[0].isInt32() && args_[1].isInt32()) {
8738 int32Arg0Id = writer.guardToInt32(arg0Id);
8739 int32Arg1Id = writer.guardToInt32(arg1Id);
8740 } else {
8741 // Treat both arguments as numbers if at least one of them is non-int32.
8742 NumberOperandId numArg0Id = writer.guardIsNumber(arg0Id);
8743 NumberOperandId numArg1Id = writer.guardIsNumber(arg1Id);
8744 int32Arg0Id = writer.truncateDoubleToUInt32(numArg0Id);
8745 int32Arg1Id = writer.truncateDoubleToUInt32(numArg1Id);
8746 }
8747 writer.mathImulResult(int32Arg0Id, int32Arg1Id);
8748 writer.returnFromIC();
8749
8750 trackAttached("MathImul");
8751 return AttachDecision::Attach;
8752 }
8753
8754 AttachDecision InlinableNativeIRGenerator::tryAttachMathFloor() {
8755 // Need one (number) argument.
8756 if (args_.length() != 1 || !args_[0].isNumber()) {
8757 return AttachDecision::NoAction;
8758 }
8759
8760 // Check if the result fits in int32.
8761 double res = math_floor_impl(args_[0].toNumber());
8762 int32_t unused;
8763 bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);
8764
8765 // Initialize the input operand.
8766 Int32OperandId argcId = initializeInputOperand();
8767
8768 // Guard callee is the 'floor' native function.
8769 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8770
8771 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8772
8773 if (args_[0].isInt32()) {
8774 MOZ_ASSERT(resultIsInt32);
8775
8776 // Use an indirect truncation to inform the optimizer it needs to preserve
8777 // a bailout when the input can't be represented as an int32, even if the
8778 // final result is fully truncated.
8779 Int32OperandId intId = writer.guardToInt32(argumentId);
8780 writer.indirectTruncateInt32Result(intId);
8781 } else {
8782 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8783
8784 if (resultIsInt32) {
8785 writer.mathFloorToInt32Result(numberId);
8786 } else {
8787 writer.mathFloorNumberResult(numberId);
8788 }
8789 }
8790
8791 writer.returnFromIC();
8792
8793 trackAttached("MathFloor");
8794 return AttachDecision::Attach;
8795 }
8796
8797 AttachDecision InlinableNativeIRGenerator::tryAttachMathCeil() {
8798 // Need one (number) argument.
8799 if (args_.length() != 1 || !args_[0].isNumber()) {
8800 return AttachDecision::NoAction;
8801 }
8802
8803 // Check if the result fits in int32.
8804 double res = math_ceil_impl(args_[0].toNumber());
8805 int32_t unused;
8806 bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);
8807
8808 // Initialize the input operand.
8809 Int32OperandId argcId = initializeInputOperand();
8810
8811 // Guard callee is the 'ceil' native function.
8812 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8813
8814 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8815
8816 if (args_[0].isInt32()) {
8817 MOZ_ASSERT(resultIsInt32);
8818
8819 // Use an indirect truncation to inform the optimizer it needs to preserve
8820 // a bailout when the input can't be represented as an int32, even if the
8821 // final result is fully truncated.
8822 Int32OperandId intId = writer.guardToInt32(argumentId);
8823 writer.indirectTruncateInt32Result(intId);
8824 } else {
8825 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8826
8827 if (resultIsInt32) {
8828 writer.mathCeilToInt32Result(numberId);
8829 } else {
8830 writer.mathCeilNumberResult(numberId);
8831 }
8832 }
8833
8834 writer.returnFromIC();
8835
8836 trackAttached("MathCeil");
8837 return AttachDecision::Attach;
8838 }
8839
8840 AttachDecision InlinableNativeIRGenerator::tryAttachMathTrunc() {
8841 // Need one (number) argument.
8842 if (args_.length() != 1 || !args_[0].isNumber()) {
8843 return AttachDecision::NoAction;
8844 }
8845
8846 // Check if the result fits in int32.
8847 double res = math_trunc_impl(args_[0].toNumber());
8848 int32_t unused;
8849 bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);
8850
8851 // Initialize the input operand.
8852 Int32OperandId argcId = initializeInputOperand();
8853
8854 // Guard callee is the 'trunc' native function.
8855 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8856
8857 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8858
8859 if (args_[0].isInt32()) {
8860 MOZ_ASSERT(resultIsInt32);
8861
8862 // We don't need an indirect truncation barrier here, because Math.trunc
8863 // always truncates, but never rounds its input away from zero.
8864 Int32OperandId intId = writer.guardToInt32(argumentId);
8865 writer.loadInt32Result(intId);
8866 } else {
8867 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8868
8869 if (resultIsInt32) {
8870 writer.mathTruncToInt32Result(numberId);
8871 } else {
8872 writer.mathTruncNumberResult(numberId);
8873 }
8874 }
8875
8876 writer.returnFromIC();
8877
8878 trackAttached("MathTrunc");
8879 return AttachDecision::Attach;
8880 }
8881
8882 AttachDecision InlinableNativeIRGenerator::tryAttachMathRound() {
8883 // Need one (number) argument.
8884 if (args_.length() != 1 || !args_[0].isNumber()) {
8885 return AttachDecision::NoAction;
8886 }
8887
8888 // Check if the result fits in int32.
8889 double res = math_round_impl(args_[0].toNumber());
8890 int32_t unused;
8891 bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);
8892
8893 // Initialize the input operand.
8894 Int32OperandId argcId = initializeInputOperand();
8895
8896 // Guard callee is the 'round' native function.
8897 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8898
8899 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8900
8901 if (args_[0].isInt32()) {
8902 MOZ_ASSERT(resultIsInt32);
8903
8904 // Use an indirect truncation to inform the optimizer it needs to preserve
8905 // a bailout when the input can't be represented as an int32, even if the
8906 // final result is fully truncated.
8907 Int32OperandId intId = writer.guardToInt32(argumentId);
8908 writer.indirectTruncateInt32Result(intId);
8909 } else {
8910 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8911
8912 if (resultIsInt32) {
8913 writer.mathRoundToInt32Result(numberId);
8914 } else {
8915 writer.mathFunctionNumberResult(numberId, UnaryMathFunction::Round);
8916 }
8917 }
8918
8919 writer.returnFromIC();
8920
8921 trackAttached("MathRound");
8922 return AttachDecision::Attach;
8923 }
8924
8925 AttachDecision InlinableNativeIRGenerator::tryAttachMathSqrt() {
8926 // Need one (number) argument.
8927 if (args_.length() != 1 || !args_[0].isNumber()) {
8928 return AttachDecision::NoAction;
8929 }
8930
8931 // Initialize the input operand.
8932 Int32OperandId argcId = initializeInputOperand();
8933
8934 // Guard callee is the 'sqrt' native function.
8935 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8936
8937 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8938 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8939 writer.mathSqrtNumberResult(numberId);
8940 writer.returnFromIC();
8941
8942 trackAttached("MathSqrt");
8943 return AttachDecision::Attach;
8944 }
8945
8946 AttachDecision InlinableNativeIRGenerator::tryAttachMathFRound() {
8947 // Need one (number) argument.
8948 if (args_.length() != 1 || !args_[0].isNumber()) {
8949 return AttachDecision::NoAction;
8950 }
8951
8952 // Initialize the input operand.
8953 Int32OperandId argcId = initializeInputOperand();
8954
8955 // Guard callee is the 'fround' native function.
8956 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8957
8958 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8959 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8960 writer.mathFRoundNumberResult(numberId);
8961 writer.returnFromIC();
8962
8963 trackAttached("MathFRound");
8964 return AttachDecision::Attach;
8965 }
8966
8967 AttachDecision InlinableNativeIRGenerator::tryAttachMathF16Round() {
8968 // Need one (number) argument.
8969 if (args_.length() != 1 || !args_[0].isNumber()) {
8970 return AttachDecision::NoAction;
8971 }
8972
8973 // Initialize the input operand.
8974 Int32OperandId argcId = initializeInputOperand();
8975
8976 // Guard callee is the 'f16round' native function.
8977 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
8978
8979 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
8980 NumberOperandId numberId = writer.guardIsNumber(argumentId);
8981 writer.mathF16RoundNumberResult(numberId);
8982 writer.returnFromIC();
8983
8984 trackAttached("MathF16Round");
8985 return AttachDecision::Attach;
8986 }
8987
8988 static bool CanAttachInt32Pow(const Value& baseVal, const Value& powerVal) {
8989 auto valToInt32 = [](const Value& v) {
8990 if (v.isInt32()) {
8991 return v.toInt32();
8992 }
8993 if (v.isBoolean()) {
8994 return int32_t(v.toBoolean());
8995 }
8996 MOZ_ASSERT(v.isNull());
8997 return 0;
8998 };
8999 int32_t base = valToInt32(baseVal);
9000 int32_t power = valToInt32(powerVal);
9001
9002 // x^y where y < 0 is most of the time not an int32, except when x is 1 or y
9003 // gets large enough. It's hard to determine when exactly y is "large enough",
9004 // so we don't use Int32PowResult when x != 1 and y < 0.
9005 // Note: it's important for this condition to match the code generated by
9006 // MacroAssembler::pow32 to prevent failure loops.
9007 if (power < 0) {
9008 return base == 1;
9009 }
9010
9011 double res = powi(base, power);
9012 int32_t unused;
9013 return mozilla::NumberIsInt32(res, &unused);
9014 }
9015
9016 AttachDecision InlinableNativeIRGenerator::tryAttachMathPow() {
9017 // Need two number arguments.
9018 if (args_.length() != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
9019 return AttachDecision::NoAction;
9020 }
9021
9022 // Initialize the input operand.
9023 Int32OperandId argcId = initializeInputOperand();
9024
9025 // Guard callee is the 'pow' function.
9026 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9027
9028 ValOperandId baseId = loadArgument(calleeId, ArgumentKind::Arg0);
9029 ValOperandId exponentId = loadArgument(calleeId, ArgumentKind::Arg1);
9030
9031 if (args_[0].isInt32() && args_[1].isInt32() &&
9032 CanAttachInt32Pow(args_[0], args_[1])) {
9033 Int32OperandId baseInt32Id = writer.guardToInt32(baseId);
9034 Int32OperandId exponentInt32Id = writer.guardToInt32(exponentId);
9035 writer.int32PowResult(baseInt32Id, exponentInt32Id);
9036 } else {
9037 NumberOperandId baseNumberId = writer.guardIsNumber(baseId);
9038 NumberOperandId exponentNumberId = writer.guardIsNumber(exponentId);
9039 writer.doublePowResult(baseNumberId, exponentNumberId);
9040 }
9041
9042 writer.returnFromIC();
9043
9044 trackAttached("MathPow");
9045 return AttachDecision::Attach;
9046 }
9047
9048 AttachDecision InlinableNativeIRGenerator::tryAttachMathHypot() {
9049 // Only optimize if there are 2-4 arguments.
9050 if (args_.length() < 2 || args_.length() > 4) {
9051 return AttachDecision::NoAction;
9052 }
9053
9054 for (size_t i = 0; i < args_.length(); i++) {
9055 if (!args_[i].isNumber()) {
9056 return AttachDecision::NoAction;
9057 }
9058 }
9059
9060 // Initialize the input operand.
9061 Int32OperandId argcId = initializeInputOperand();
9062
9063 // Guard callee is the 'hypot' native function.
9064 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9065
9066 ValOperandId firstId = loadArgument(calleeId, ArgumentKind::Arg0);
9067 ValOperandId secondId = loadArgument(calleeId, ArgumentKind::Arg1);
9068
9069 NumberOperandId firstNumId = writer.guardIsNumber(firstId);
9070 NumberOperandId secondNumId = writer.guardIsNumber(secondId);
9071
9072 ValOperandId thirdId;
9073 ValOperandId fourthId;
9074 NumberOperandId thirdNumId;
9075 NumberOperandId fourthNumId;
9076
9077 switch (args_.length()) {
9078 case 2:
9079 writer.mathHypot2NumberResult(firstNumId, secondNumId);
9080 break;
9081 case 3:
9082 thirdId = loadArgument(calleeId, ArgumentKind::Arg2);
9083 thirdNumId = writer.guardIsNumber(thirdId);
9084 writer.mathHypot3NumberResult(firstNumId, secondNumId, thirdNumId);
9085 break;
9086 case 4:
9087 thirdId = loadArgument(calleeId, ArgumentKind::Arg2);
9088 fourthId = loadArgument(calleeId, ArgumentKind::Arg3);
9089 thirdNumId = writer.guardIsNumber(thirdId);
9090 fourthNumId = writer.guardIsNumber(fourthId);
9091 writer.mathHypot4NumberResult(firstNumId, secondNumId, thirdNumId,
9092 fourthNumId);
9093 break;
9094 default:
9095 MOZ_CRASH("Unexpected number of arguments to hypot function.");
9096 }
9097
9098 writer.returnFromIC();
9099
9100 trackAttached("MathHypot");
9101 return AttachDecision::Attach;
9102 }
9103
9104 AttachDecision InlinableNativeIRGenerator::tryAttachMathATan2() {
9105 // Requires two numbers as arguments.
9106 if (args_.length() != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
9107 return AttachDecision::NoAction;
9108 }
9109
9110 // Initialize the input operand.
9111 Int32OperandId argcId = initializeInputOperand();
9112
9113 // Guard callee is the 'atan2' native function.
9114 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9115
9116 ValOperandId yId = loadArgument(calleeId, ArgumentKind::Arg0);
9117 ValOperandId xId = loadArgument(calleeId, ArgumentKind::Arg1);
9118
9119 NumberOperandId yNumberId = writer.guardIsNumber(yId);
9120 NumberOperandId xNumberId = writer.guardIsNumber(xId);
9121
9122 writer.mathAtan2NumberResult(yNumberId, xNumberId);
9123 writer.returnFromIC();
9124
9125 trackAttached("MathAtan2");
9126 return AttachDecision::Attach;
9127 }
9128
9129 AttachDecision InlinableNativeIRGenerator::tryAttachMathMinMax(bool isMax) {
9130 // For now only optimize if there are 1-4 arguments.
9131 if (args_.length() < 1 || args_.length() > 4) {
9132 return AttachDecision::NoAction;
9133 }
9134
9135 // Ensure all arguments are numbers.
9136 bool allInt32 = true;
9137 for (size_t i = 0; i < args_.length(); i++) {
9138 if (!args_[i].isNumber()) {
9139 return AttachDecision::NoAction;
9140 }
9141 if (!args_[i].isInt32()) {
9142 allInt32 = false;
9143 }
9144 }
9145
9146 // Initialize the input operand.
9147 Int32OperandId argcId = initializeInputOperand();
9148
9149 // Guard callee is this Math function.
9150 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9151
9152 if (allInt32) {
9153 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg0);
9154 Int32OperandId resId = writer.guardToInt32(valId);
9155 for (size_t i = 1; i < args_.length(); i++) {
9156 ValOperandId argId = loadArgument(calleeId, ArgumentKindForArgIndex(i));
9157 Int32OperandId argInt32Id = writer.guardToInt32(argId);
9158 resId = writer.int32MinMax(isMax, resId, argInt32Id);
9159 }
9160 writer.loadInt32Result(resId);
9161 } else {
9162 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg0);
9163 NumberOperandId resId = writer.guardIsNumber(valId);
9164 for (size_t i = 1; i < args_.length(); i++) {
9165 ValOperandId argId = loadArgument(calleeId, ArgumentKindForArgIndex(i));
9166 NumberOperandId argNumId = writer.guardIsNumber(argId);
9167 resId = writer.numberMinMax(isMax, resId, argNumId);
9168 }
9169 writer.loadDoubleResult(resId);
9170 }
9171
9172 writer.returnFromIC();
9173
9174 trackAttached(isMax ? "MathMax" : "MathMin");
9175 return AttachDecision::Attach;
9176 }
9177
9178 AttachDecision InlinableNativeIRGenerator::tryAttachSpreadMathMinMax(
9179 bool isMax) {
9180 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Spread ||
9181 flags_.getArgFormat() == CallFlags::FunApplyArray);
9182
9183 // The result will be an int32 if there is at least one argument,
9184 // and all the arguments are int32.
9185 bool int32Result = args_.length() > 0;
9186 for (size_t i = 0; i < args_.length(); i++) {
9187 if (!args_[i].isNumber()) {
9188 return AttachDecision::NoAction;
9189 }
9190 if (!args_[i].isInt32()) {
9191 int32Result = false;
9192 }
9193 }
9194
9195 // Initialize the input operand.
9196 Int32OperandId argcId = initializeInputOperand();
9197
9198 // Guard callee is this Math function.
9199 emitNativeCalleeGuard(argcId);
9200
9201 // Load the argument array.
9202 ObjOperandId argsId = emitLoadArgsArray();
9203
9204 if (int32Result) {
9205 writer.int32MinMaxArrayResult(argsId, isMax);
9206 } else {
9207 writer.numberMinMaxArrayResult(argsId, isMax);
9208 }
9209
9210 writer.returnFromIC();
9211
9212 trackAttached(isMax ? "MathMaxArray" : "MathMinArray");
9213 return AttachDecision::Attach;
9214 }
9215
9216 AttachDecision InlinableNativeIRGenerator::tryAttachMathFunction(
9217 UnaryMathFunction fun) {
9218 // Need one argument.
9219 if (args_.length() != 1) {
9220 return AttachDecision::NoAction;
9221 }
9222
9223 if (!args_[0].isNumber()) {
9224 return AttachDecision::NoAction;
9225 }
9226
9227 if (math_use_fdlibm_for_sin_cos_tan() ||
9228 target_->realm()->creationOptions().alwaysUseFdlibm()) {
9229 switch (fun) {
9230 case UnaryMathFunction::SinNative:
9231 fun = UnaryMathFunction::SinFdlibm;
9232 break;
9233 case UnaryMathFunction::CosNative:
9234 fun = UnaryMathFunction::CosFdlibm;
9235 break;
9236 case UnaryMathFunction::TanNative:
9237 fun = UnaryMathFunction::TanFdlibm;
9238 break;
9239 default:
9240 break;
9241 }
9242 }
9243
9244 // Initialize the input operand.
9245 Int32OperandId argcId = initializeInputOperand();
9246
9247 // Guard callee is this Math function.
9248 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9249
9250 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
9251 NumberOperandId numberId = writer.guardIsNumber(argumentId);
9252 writer.mathFunctionNumberResult(numberId, fun);
9253 writer.returnFromIC();
9254
9255 trackAttached("MathFunction");
9256 return AttachDecision::Attach;
9257 }
9258
9259 AttachDecision InlinableNativeIRGenerator::tryAttachNumber() {
9260 // Expect a single string argument.
9261 if (args_.length() != 1 || !args_[0].isString()) {
9262 return AttachDecision::NoAction;
9263 }
9264
9265 double num;
9266 if (!StringToNumber(cx_, args_[0].toString(), &num)) {
9267 cx_->recoverFromOutOfMemory();
9268 return AttachDecision::NoAction;
9269 }
9270
9271 // Initialize the input operand.
9272 Int32OperandId argcId = initializeInputOperand();
9273
9274 // Guard callee is the `Number` function.
9275 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9276
9277 // Guard that the argument is a string.
9278 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
9279 StringOperandId strId = writer.guardToString(argId);
9280
9281 // Return either an Int32 or Double result.
9282 int32_t unused;
9283 if (mozilla::NumberIsInt32(num, &unused)) {
9284 Int32OperandId resultId = writer.guardStringToInt32(strId);
9285 writer.loadInt32Result(resultId);
9286 } else {
9287 NumberOperandId resultId = writer.guardStringToNumber(strId);
9288 writer.loadDoubleResult(resultId);
9289 }
9290 writer.returnFromIC();
9291
9292 trackAttached("Number");
9293 return AttachDecision::Attach;
9294 }
9295
9296 AttachDecision InlinableNativeIRGenerator::tryAttachNumberParseInt() {
9297 // Expected arguments: input (string or number), optional radix (int32).
9298 if (args_.length() < 1 || args_.length() > 2) {
9299 return AttachDecision::NoAction;
9300 }
9301 if (!args_[0].isString() && !args_[0].isNumber()) {
9302 return AttachDecision::NoAction;
9303 }
9304 if (args_[0].isDouble()) {
9305 double d = args_[0].toDouble();
9306
9307 // See num_parseInt for why we have to reject numbers smaller than 1.0e-6.
9308 // Negative numbers in the exclusive range (-1, -0) return -0.
9309 bool canTruncateToInt32 =
9310 (DOUBLE_DECIMAL_IN_SHORTEST_LOW <= d && d <= double(INT32_MAX)) ||
9311 (double(INT32_MIN) <= d && d <= -1.0) || (d == 0.0);
9312 if (!canTruncateToInt32) {
9313 return AttachDecision::NoAction;
9314 }
9315 }
9316 if (args_.length() > 1 && !args_[1].isInt32(10)) {
9317 return AttachDecision::NoAction;
9318 }
9319
9320 // Initialize the input operand.
9321 Int32OperandId argcId = initializeInputOperand();
9322
9323 // Guard callee is the 'parseInt' native function.
9324 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9325
9326 auto guardRadix = [&]() {
9327 ValOperandId radixId = loadArgument(calleeId, ArgumentKind::Arg1);
9328 Int32OperandId intRadixId = writer.guardToInt32(radixId);
9329 writer.guardSpecificInt32(intRadixId, 10);
9330 return intRadixId;
9331 };
9332
9333 ValOperandId inputId = loadArgument(calleeId, ArgumentKind::Arg0);
9334
9335 if (args_[0].isString()) {
9336 StringOperandId strId = writer.guardToString(inputId);
9337
9338 Int32OperandId intRadixId;
9339 if (args_.length() > 1) {
9340 intRadixId = guardRadix();
9341 } else {
9342 intRadixId = writer.loadInt32Constant(0);
9343 }
9344
9345 writer.numberParseIntResult(strId, intRadixId);
9346 } else if (args_[0].isInt32()) {
9347 Int32OperandId intId = writer.guardToInt32(inputId);
9348 if (args_.length() > 1) {
9349 guardRadix();
9350 }
9351 writer.loadInt32Result(intId);
9352 } else {
9353 MOZ_ASSERT(args_[0].isDouble());
9354
9355 NumberOperandId numId = writer.guardIsNumber(inputId);
9356 if (args_.length() > 1) {
9357 guardRadix();
9358 }
9359 writer.doubleParseIntResult(numId);
9360 }
9361
9362 writer.returnFromIC();
9363
9364 trackAttached("NumberParseInt");
9365 return AttachDecision::Attach;
9366 }
9367
9368 StringOperandId IRGenerator::emitToStringGuard(ValOperandId id,
9369 const Value& v) {
9370 MOZ_ASSERT(CanConvertToString(v));
9371 if (v.isString()) {
9372 return writer.guardToString(id);
9373 }
9374 if (v.isBoolean()) {
9375 BooleanOperandId boolId = writer.guardToBoolean(id);
9376 return writer.booleanToString(boolId);
9377 }
9378 if (v.isNull()) {
9379 writer.guardIsNull(id);
9380 return writer.loadConstantString(cx_->names().null);
9381 }
9382 if (v.isUndefined()) {
9383 writer.guardIsUndefined(id);
9384 return writer.loadConstantString(cx_->names().undefined);
9385 }
9386 if (v.isInt32()) {
9387 Int32OperandId intId = writer.guardToInt32(id);
9388 return writer.callInt32ToString(intId);
9389 }
9390 // At this point we are creating an IC that will handle
9391 // both Int32 and Double cases.
9392 MOZ_ASSERT(v.isNumber());
9393 NumberOperandId numId = writer.guardIsNumber(id);
9394 return writer.callNumberToString(numId);
9395 }
9396
9397 AttachDecision InlinableNativeIRGenerator::tryAttachNumberToString() {
9398 // Expecting no arguments or a single int32 argument.
9399 if (args_.length() > 1) {
9400 return AttachDecision::NoAction;
9401 }
9402 if (args_.length() == 1 && !args_[0].isInt32()) {
9403 return AttachDecision::NoAction;
9404 }
9405
9406 // Ensure |this| is a primitive number value.
9407 if (!thisval_.isNumber()) {
9408 return AttachDecision::NoAction;
9409 }
9410
9411 // No arguments means base 10.
9412 int32_t base = 10;
9413 if (args_.length() > 0) {
9414 base = args_[0].toInt32();
9415 if (base < 2 || base > 36) {
9416 return AttachDecision::NoAction;
9417 }
9418
9419 // Non-decimal bases currently only support int32 inputs.
9420 if (base != 10 && !thisval_.isInt32()) {
9421 return AttachDecision::NoAction;
9422 }
9423 }
9424 MOZ_ASSERT(2 <= base && base <= 36);
9425
9426 // Initialize the input operand.
9427 Int32OperandId argcId = initializeInputOperand();
9428
9429 // Guard callee is the 'toString' native function.
9430 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9431
9432 // Initialize the |this| operand.
9433 ValOperandId thisValId = loadThis(calleeId);
9434
9435 // Guard on number and convert to string.
9436 if (base == 10) {
9437 // If an explicit base was passed, guard its value.
9438 if (args_.length() > 0) {
9439 // Guard the `base` argument is an int32.
9440 ValOperandId baseId = loadArgument(calleeId, ArgumentKind::Arg0);
9441 Int32OperandId intBaseId = writer.guardToInt32(baseId);
9442
9443 // Guard `base` is 10 for decimal toString representation.
9444 writer.guardSpecificInt32(intBaseId, 10);
9445 }
9446
9447 StringOperandId strId = emitToStringGuard(thisValId, thisval_);
9448
9449 // Return the string.
9450 writer.loadStringResult(strId);
9451 } else {
9452 MOZ_ASSERT(args_.length() > 0);
9453
9454 // Guard the |this| value is an int32.
9455 Int32OperandId thisIntId = writer.guardToInt32(thisValId);
9456
9457 // Guard the `base` argument is an int32.
9458 ValOperandId baseId = loadArgument(calleeId, ArgumentKind::Arg0);
9459 Int32OperandId intBaseId = writer.guardToInt32(baseId);
9460
9461 // Return the string.
9462 writer.int32ToStringWithBaseResult(thisIntId, intBaseId);
9463 }
9464
9465 writer.returnFromIC();
9466
9467 trackAttached("NumberToString");
9468 return AttachDecision::Attach;
9469 }
9470
9471 AttachDecision InlinableNativeIRGenerator::tryAttachReflectGetPrototypeOf() {
9472 // Need one argument.
9473 if (args_.length() != 1) {
9474 return AttachDecision::NoAction;
9475 }
9476
9477 if (!args_[0].isObject()) {
9478 return AttachDecision::NoAction;
9479 }
9480
9481 // Initialize the input operand.
9482 Int32OperandId argcId = initializeInputOperand();
9483
9484 // Guard callee is the 'getPrototypeOf' native function.
9485 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9486
9487 ValOperandId argumentId = loadArgument(calleeId, ArgumentKind::Arg0);
9488 ObjOperandId objId = writer.guardToObject(argumentId);
9489
9490 writer.reflectGetPrototypeOfResult(objId);
9491 writer.returnFromIC();
9492
9493 trackAttached("ReflectGetPrototypeOf");
9494 return AttachDecision::Attach;
9495 }
9496
9497 static bool AtomicsMeetsPreconditions(TypedArrayObject* typedArray,
9498 const Value& index) {
9499 switch (typedArray->type()) {
9500 case Scalar::Int8:
9501 case Scalar::Uint8:
9502 case Scalar::Int16:
9503 case Scalar::Uint16:
9504 case Scalar::Int32:
9505 case Scalar::Uint32:
9506 case Scalar::BigInt64:
9507 case Scalar::BigUint64:
9508 break;
9509
9510 case Scalar::Float16:
9511 case Scalar::Float32:
9512 case Scalar::Float64:
9513 case Scalar::Uint8Clamped:
9514 // Exclude floating types and Uint8Clamped.
9515 return false;
9516
9517 case Scalar::MaxTypedArrayViewType:
9518 case Scalar::Int64:
9519 case Scalar::Simd128:
9520 MOZ_CRASH("Unsupported TypedArray type");
9521 }
9522
9523 // Bounds check the index argument.
9524 int64_t indexInt64;
9525 if (!ValueIsInt64Index(index, &indexInt64)) {
9526 return false;
9527 }
9528 if (indexInt64 < 0 ||
9529 uint64_t(indexInt64) >= typedArray->length().valueOr(0)) {
9530 return false;
9531 }
9532
9533 return true;
9534 }
9535
9536 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsCompareExchange() {
9537 if (!JitSupportsAtomics()) {
9538 return AttachDecision::NoAction;
9539 }
9540
9541 // Need four arguments.
9542 if (args_.length() != 4) {
9543 return AttachDecision::NoAction;
9544 }
9545
9546 // Arguments: typedArray, index (number), expected, replacement.
9547 if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
9548 return AttachDecision::NoAction;
9549 }
9550 if (!args_[1].isNumber()) {
9551 return AttachDecision::NoAction;
9552 }
9553
9554 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9555 if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
9556 return AttachDecision::NoAction;
9557 }
9558
9559 Scalar::Type elementType = typedArray->type();
9560 if (!ValueCanConvertToNumeric(elementType, args_[2])) {
9561 return AttachDecision::NoAction;
9562 }
9563 if (!ValueCanConvertToNumeric(elementType, args_[3])) {
9564 return AttachDecision::NoAction;
9565 }
9566
9567 // Initialize the input operand.
9568 Int32OperandId argcId = initializeInputOperand();
9569
9570 // Guard callee is the `compareExchange` native function.
9571 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9572
9573 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
9574 ObjOperandId objId = writer.guardToObject(arg0Id);
9575 writer.guardShapeForClass(objId, typedArray->shape());
9576
9577 // Convert index to intPtr.
9578 ValOperandId indexId = loadArgument(calleeId, ArgumentKind::Arg1);
9579 IntPtrOperandId intPtrIndexId =
9580 guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);
9581
9582 // Convert expected value to int32/BigInt.
9583 ValOperandId expectedId = loadArgument(calleeId, ArgumentKind::Arg2);
9584 OperandId numericExpectedId =
9585 emitNumericGuard(expectedId, args_[2], elementType);
9586
9587 // Convert replacement value to int32/BigInt.
9588 ValOperandId replacementId = loadArgument(calleeId, ArgumentKind::Arg3);
9589 OperandId numericReplacementId =
9590 emitNumericGuard(replacementId, args_[3], elementType);
9591
9592 auto viewKind = ToArrayBufferViewKind(typedArray);
9593 writer.atomicsCompareExchangeResult(objId, intPtrIndexId, numericExpectedId,
9594 numericReplacementId, typedArray->type(),
9595 viewKind);
9596 writer.returnFromIC();
9597
9598 trackAttached("AtomicsCompareExchange");
9599 return AttachDecision::Attach;
9600 }
9601
9602 bool InlinableNativeIRGenerator::canAttachAtomicsReadWriteModify() {
9603 if (!JitSupportsAtomics()) {
9604 return false;
9605 }
9606
9607 // Need three arguments.
9608 if (args_.length() != 3) {
9609 return false;
9610 }
9611
9612 // Arguments: typedArray, index (number), value.
9613 if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
9614 return false;
9615 }
9616 if (!args_[1].isNumber()) {
9617 return false;
9618 }
9619
9620 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9621 if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
9622 return false;
9623 }
9624 if (!ValueCanConvertToNumeric(typedArray->type(), args_[2])) {
9625 return false;
9626 }
9627 return true;
9628 }
9629
9630 InlinableNativeIRGenerator::AtomicsReadWriteModifyOperands
9631 InlinableNativeIRGenerator::emitAtomicsReadWriteModifyOperands() {
9632 MOZ_ASSERT(canAttachAtomicsReadWriteModify());
9633
9634 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9635
9636 // Initialize the input operand.
9637 Int32OperandId argcId = initializeInputOperand();
9638
9639 // Guard callee is this Atomics function.
9640 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9641
9642 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
9643 ObjOperandId objId = writer.guardToObject(arg0Id);
9644 writer.guardShapeForClass(objId, typedArray->shape());
9645
9646 // Convert index to intPtr.
9647 ValOperandId indexId = loadArgument(calleeId, ArgumentKind::Arg1);
9648 IntPtrOperandId intPtrIndexId =
9649 guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);
9650
9651 // Convert value to int32/BigInt.
9652 ValOperandId valueId = loadArgument(calleeId, ArgumentKind::Arg2);
9653 OperandId numericValueId =
9654 emitNumericGuard(valueId, args_[2], typedArray->type());
9655
9656 return {objId, intPtrIndexId, numericValueId};
9657 }
9658
9659 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsExchange() {
9660 if (!canAttachAtomicsReadWriteModify()) {
9661 return AttachDecision::NoAction;
9662 }
9663
9664 auto [objId, intPtrIndexId, numericValueId] =
9665 emitAtomicsReadWriteModifyOperands();
9666
9667 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9668 auto viewKind = ToArrayBufferViewKind(typedArray);
9669
9670 writer.atomicsExchangeResult(objId, intPtrIndexId, numericValueId,
9671 typedArray->type(), viewKind);
9672 writer.returnFromIC();
9673
9674 trackAttached("AtomicsExchange");
9675 return AttachDecision::Attach;
9676 }
9677
9678 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsAdd() {
9679 if (!canAttachAtomicsReadWriteModify()) {
9680 return AttachDecision::NoAction;
9681 }
9682
9683 auto [objId, intPtrIndexId, numericValueId] =
9684 emitAtomicsReadWriteModifyOperands();
9685
9686 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9687 bool forEffect = ignoresResult();
9688 auto viewKind = ToArrayBufferViewKind(typedArray);
9689
9690 writer.atomicsAddResult(objId, intPtrIndexId, numericValueId,
9691 typedArray->type(), forEffect, viewKind);
9692 writer.returnFromIC();
9693
9694 trackAttached("AtomicsAdd");
9695 return AttachDecision::Attach;
9696 }
9697
9698 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsSub() {
9699 if (!canAttachAtomicsReadWriteModify()) {
9700 return AttachDecision::NoAction;
9701 }
9702
9703 auto [objId, intPtrIndexId, numericValueId] =
9704 emitAtomicsReadWriteModifyOperands();
9705
9706 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9707 bool forEffect = ignoresResult();
9708 auto viewKind = ToArrayBufferViewKind(typedArray);
9709
9710 writer.atomicsSubResult(objId, intPtrIndexId, numericValueId,
9711 typedArray->type(), forEffect, viewKind);
9712 writer.returnFromIC();
9713
9714 trackAttached("AtomicsSub");
9715 return AttachDecision::Attach;
9716 }
9717
9718 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsAnd() {
9719 if (!canAttachAtomicsReadWriteModify()) {
9720 return AttachDecision::NoAction;
9721 }
9722
9723 auto [objId, intPtrIndexId, numericValueId] =
9724 emitAtomicsReadWriteModifyOperands();
9725
9726 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9727 bool forEffect = ignoresResult();
9728 auto viewKind = ToArrayBufferViewKind(typedArray);
9729
9730 writer.atomicsAndResult(objId, intPtrIndexId, numericValueId,
9731 typedArray->type(), forEffect, viewKind);
9732 writer.returnFromIC();
9733
9734 trackAttached("AtomicsAnd");
9735 return AttachDecision::Attach;
9736 }
9737
9738 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsOr() {
9739 if (!canAttachAtomicsReadWriteModify()) {
9740 return AttachDecision::NoAction;
9741 }
9742
9743 auto [objId, intPtrIndexId, numericValueId] =
9744 emitAtomicsReadWriteModifyOperands();
9745
9746 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9747 bool forEffect = ignoresResult();
9748 auto viewKind = ToArrayBufferViewKind(typedArray);
9749
9750 writer.atomicsOrResult(objId, intPtrIndexId, numericValueId,
9751 typedArray->type(), forEffect, viewKind);
9752 writer.returnFromIC();
9753
9754 trackAttached("AtomicsOr");
9755 return AttachDecision::Attach;
9756 }
9757
9758 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsXor() {
9759 if (!canAttachAtomicsReadWriteModify()) {
9760 return AttachDecision::NoAction;
9761 }
9762
9763 auto [objId, intPtrIndexId, numericValueId] =
9764 emitAtomicsReadWriteModifyOperands();
9765
9766 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9767 bool forEffect = ignoresResult();
9768 auto viewKind = ToArrayBufferViewKind(typedArray);
9769
9770 writer.atomicsXorResult(objId, intPtrIndexId, numericValueId,
9771 typedArray->type(), forEffect, viewKind);
9772 writer.returnFromIC();
9773
9774 trackAttached("AtomicsXor");
9775 return AttachDecision::Attach;
9776 }
9777
9778 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsLoad() {
9779 if (!JitSupportsAtomics()) {
9780 return AttachDecision::NoAction;
9781 }
9782
9783 // Need two arguments.
9784 if (args_.length() != 2) {
9785 return AttachDecision::NoAction;
9786 }
9787
9788 // Arguments: typedArray, index (number).
9789 if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
9790 return AttachDecision::NoAction;
9791 }
9792 if (!args_[1].isNumber()) {
9793 return AttachDecision::NoAction;
9794 }
9795
9796 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9797 if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
9798 return AttachDecision::NoAction;
9799 }
9800
9801 // Initialize the input operand.
9802 Int32OperandId argcId = initializeInputOperand();
9803
9804 // Guard callee is the `load` native function.
9805 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9806
9807 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
9808 ObjOperandId objId = writer.guardToObject(arg0Id);
9809 writer.guardShapeForClass(objId, typedArray->shape());
9810
9811 // Convert index to intPtr.
9812 ValOperandId indexId = loadArgument(calleeId, ArgumentKind::Arg1);
9813 IntPtrOperandId intPtrIndexId =
9814 guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);
9815
9816 auto viewKind = ToArrayBufferViewKind(typedArray);
9817 writer.atomicsLoadResult(objId, intPtrIndexId, typedArray->type(), viewKind);
9818 writer.returnFromIC();
9819
9820 trackAttached("AtomicsLoad");
9821 return AttachDecision::Attach;
9822 }
9823
9824 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsStore() {
9825 if (!JitSupportsAtomics()) {
9826 return AttachDecision::NoAction;
9827 }
9828
9829 // Need three arguments.
9830 if (args_.length() != 3) {
9831 return AttachDecision::NoAction;
9832 }
9833
9834 // Atomics.store() is annoying because it returns the result of converting the
9835 // value by ToInteger(), not the input value, nor the result of converting the
9836 // value by ToInt32(). It is especially annoying because almost nobody uses
9837 // the result value.
9838 //
9839 // As an expedient compromise, therefore, we inline only if the result is
9840 // obviously unused or if the argument is already Int32 and thus requires no
9841 // conversion.
9842
9843 // Arguments: typedArray, index (number), value.
9844 if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
9845 return AttachDecision::NoAction;
9846 }
9847 if (!args_[1].isNumber()) {
9848 return AttachDecision::NoAction;
9849 }
9850
9851 auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
9852 if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
9853 return AttachDecision::NoAction;
9854 }
9855
9856 Scalar::Type elementType = typedArray->type();
9857 if (!ValueCanConvertToNumeric(elementType, args_[2])) {
9858 return AttachDecision::NoAction;
9859 }
9860
9861 bool guardIsInt32 = !Scalar::isBigIntType(elementType) && !ignoresResult();
9862
9863 if (guardIsInt32 && !args_[2].isInt32()) {
9864 return AttachDecision::NoAction;
9865 }
9866
9867 // Initialize the input operand.
9868 Int32OperandId argcId = initializeInputOperand();
9869
9870 // Guard callee is the `store` native function.
9871 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9872
9873 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
9874 ObjOperandId objId = writer.guardToObject(arg0Id);
9875 writer.guardShapeForClass(objId, typedArray->shape());
9876
9877 // Convert index to intPtr.
9878 ValOperandId indexId = loadArgument(calleeId, ArgumentKind::Arg1);
9879 IntPtrOperandId intPtrIndexId =
9880 guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);
9881
9882 // Ensure value is int32 or BigInt.
9883 ValOperandId valueId = loadArgument(calleeId, ArgumentKind::Arg2);
9884 OperandId numericValueId;
9885 if (guardIsInt32) {
9886 numericValueId = writer.guardToInt32(valueId);
9887 } else {
9888 numericValueId = emitNumericGuard(valueId, args_[2], elementType);
9889 }
9890
9891 auto viewKind = ToArrayBufferViewKind(typedArray);
9892 writer.atomicsStoreResult(objId, intPtrIndexId, numericValueId,
9893 typedArray->type(), viewKind);
9894 writer.returnFromIC();
9895
9896 trackAttached("AtomicsStore");
9897 return AttachDecision::Attach;
9898 }
9899
9900 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsIsLockFree() {
9901 // Need one argument.
9902 if (args_.length() != 1) {
9903 return AttachDecision::NoAction;
9904 }
9905
9906 if (!args_[0].isInt32()) {
9907 return AttachDecision::NoAction;
9908 }
9909
9910 // Initialize the input operand.
9911 Int32OperandId argcId = initializeInputOperand();
9912
9913 // Guard callee is the `isLockFree` native function.
9914 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9915
9916 // Ensure value is int32.
9917 ValOperandId valueId = loadArgument(calleeId, ArgumentKind::Arg0);
9918 Int32OperandId int32ValueId = writer.guardToInt32(valueId);
9919
9920 writer.atomicsIsLockFreeResult(int32ValueId);
9921 writer.returnFromIC();
9922
9923 trackAttached("AtomicsIsLockFree");
9924 return AttachDecision::Attach;
9925 }
9926
9927 AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsPause() {
9928 // We don't yet support inlining when the iteration count argument is present.
9929 if (args_.length() != 0) {
9930 return AttachDecision::NoAction;
9931 }
9932
9933 // Initialize the input operand.
9934 Int32OperandId argcId = initializeInputOperand();
9935
9936 // Guard callee is the `pause` native function.
9937 emitNativeCalleeGuard(argcId);
9938
9939 writer.atomicsPauseResult();
9940 writer.returnFromIC();
9941
9942 trackAttached("AtomicsPause");
9943 return AttachDecision::Attach;
9944 }
9945
9946 AttachDecision InlinableNativeIRGenerator::tryAttachBoolean() {
9947 // Need zero or one argument.
9948 if (args_.length() > 1) {
9949 return AttachDecision::NoAction;
9950 }
9951
9952 // Initialize the input operand.
9953 Int32OperandId argcId = initializeInputOperand();
9954
9955 // Guard callee is the 'Boolean' native function.
9956 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
9957
9958 if (args_.length() == 0) {
9959 writer.loadBooleanResult(false);
9960 } else {
9961 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg0);
9962
9963 writer.loadValueTruthyResult(valId);
9964 }
9965
9966 writer.returnFromIC();
9967
9968 trackAttached("Boolean");
9969 return AttachDecision::Attach;
9970 }
9971
9972 AttachDecision InlinableNativeIRGenerator::tryAttachBailout() {
9973 // Expecting no arguments.
9974 if (args_.length() != 0) {
9975 return AttachDecision::NoAction;
9976 }
9977
9978 // Initialize the input operand.
9979 Int32OperandId argcId = initializeInputOperand();
9980
9981 // Guard callee is the 'bailout' native function.
9982 emitNativeCalleeGuard(argcId);
9983
9984 writer.bailout();
9985 writer.loadUndefinedResult();
9986 writer.returnFromIC();
9987
9988 trackAttached("Bailout");
9989 return AttachDecision::Attach;
9990 }
9991
9992 AttachDecision InlinableNativeIRGenerator::tryAttachAssertFloat32() {
9993 // Expecting two arguments.
9994 if (args_.length() != 2) {
9995 return AttachDecision::NoAction;
9996 }
9997
9998 // (Fuzzing unsafe) testing function which must be called with a constant
9999 // boolean as its second argument.
10000 bool mustBeFloat32 = args_[1].toBoolean();
10001
10002 // Initialize the input operand.
10003 Int32OperandId argcId = initializeInputOperand();
10004
10005 // Guard callee is the 'assertFloat32' native function.
10006 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10007
10008 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg0);
10009
10010 writer.assertFloat32Result(valId, mustBeFloat32);
10011 writer.returnFromIC();
10012
10013 trackAttached("AssertFloat32");
10014 return AttachDecision::Attach;
10015 }
10016
10017 AttachDecision InlinableNativeIRGenerator::tryAttachAssertRecoveredOnBailout() {
10018 // Expecting two arguments.
10019 if (args_.length() != 2) {
10020 return AttachDecision::NoAction;
10021 }
10022
10023 // (Fuzzing unsafe) testing function which must be called with a constant
10024 // boolean as its second argument.
10025 bool mustBeRecovered = args_[1].toBoolean();
10026
10027 // Initialize the input operand.
10028 Int32OperandId argcId = initializeInputOperand();
10029
10030 // Guard callee is the 'assertRecoveredOnBailout' native function.
10031 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10032
10033 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg0);
10034
10035 writer.assertRecoveredOnBailoutResult(valId, mustBeRecovered);
10036 writer.returnFromIC();
10037
10038 trackAttached("AssertRecoveredOnBailout");
10039 return AttachDecision::Attach;
10040 }
10041
10042 AttachDecision InlinableNativeIRGenerator::tryAttachObjectIs() {
10043 // Need two arguments.
10044 if (args_.length() != 2) {
10045 return AttachDecision::NoAction;
10046 }
10047
10048 // Initialize the input operand.
10049 Int32OperandId argcId = initializeInputOperand();
10050
10051 // Guard callee is the `is` native function.
10052 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10053
10054 ValOperandId lhsId = loadArgument(calleeId, ArgumentKind::Arg0);
10055 ValOperandId rhsId = loadArgument(calleeId, ArgumentKind::Arg1);
10056
10057 HandleValue lhs = args_[0];
10058 HandleValue rhs = args_[1];
10059
10060 if (!isFirstStub()) {
10061 writer.sameValueResult(lhsId, rhsId);
10062 } else if (lhs.isNumber() && rhs.isNumber() &&
10063 !(lhs.isInt32() && rhs.isInt32())) {
10064 NumberOperandId lhsNumId = writer.guardIsNumber(lhsId);
10065 NumberOperandId rhsNumId = writer.guardIsNumber(rhsId);
10066 writer.compareDoubleSameValueResult(lhsNumId, rhsNumId);
10067 } else if (!SameType(lhs, rhs)) {
10068 // Compare tags for strictly different types.
10069 ValueTagOperandId lhsTypeId = writer.loadValueTag(lhsId);
10070 ValueTagOperandId rhsTypeId = writer.loadValueTag(rhsId);
10071 writer.guardTagNotEqual(lhsTypeId, rhsTypeId);
10072 writer.loadBooleanResult(false);
10073 } else {
10074 MOZ_ASSERT(lhs.type() == rhs.type());
10075 MOZ_ASSERT(lhs.type() != JS::ValueType::Double);
10076
10077 switch (lhs.type()) {
10078 case JS::ValueType::Int32: {
10079 Int32OperandId lhsIntId = writer.guardToInt32(lhsId);
10080 Int32OperandId rhsIntId = writer.guardToInt32(rhsId);
10081 writer.compareInt32Result(JSOp::StrictEq, lhsIntId, rhsIntId);
10082 break;
10083 }
10084 case JS::ValueType::Boolean: {
10085 Int32OperandId lhsIntId = writer.guardBooleanToInt32(lhsId);
10086 Int32OperandId rhsIntId = writer.guardBooleanToInt32(rhsId);
10087 writer.compareInt32Result(JSOp::StrictEq, lhsIntId, rhsIntId);
10088 break;
10089 }
10090 case JS::ValueType::Undefined: {
10091 writer.guardIsUndefined(lhsId);
10092 writer.guardIsUndefined(rhsId);
10093 writer.loadBooleanResult(true);
10094 break;
10095 }
10096 case JS::ValueType::Null: {
10097 writer.guardIsNull(lhsId);
10098 writer.guardIsNull(rhsId);
10099 writer.loadBooleanResult(true);
10100 break;
10101 }
10102 case JS::ValueType::String: {
10103 StringOperandId lhsStrId = writer.guardToString(lhsId);
10104 StringOperandId rhsStrId = writer.guardToString(rhsId);
10105 writer.compareStringResult(JSOp::StrictEq, lhsStrId, rhsStrId);
10106 break;
10107 }
10108 case JS::ValueType::Symbol: {
10109 SymbolOperandId lhsSymId = writer.guardToSymbol(lhsId);
10110 SymbolOperandId rhsSymId = writer.guardToSymbol(rhsId);
10111 writer.compareSymbolResult(JSOp::StrictEq, lhsSymId, rhsSymId);
10112 break;
10113 }
10114 case JS::ValueType::BigInt: {
10115 BigIntOperandId lhsBigIntId = writer.guardToBigInt(lhsId);
10116 BigIntOperandId rhsBigIntId = writer.guardToBigInt(rhsId);
10117 writer.compareBigIntResult(JSOp::StrictEq, lhsBigIntId, rhsBigIntId);
10118 break;
10119 }
10120 case JS::ValueType::Object: {
10121 ObjOperandId lhsObjId = writer.guardToObject(lhsId);
10122 ObjOperandId rhsObjId = writer.guardToObject(rhsId);
10123 writer.compareObjectResult(JSOp::StrictEq, lhsObjId, rhsObjId);
10124 break;
10125 }
10126
10127 case JS::ValueType::Double:
10128 case JS::ValueType::Magic:
10129 case JS::ValueType::PrivateGCThing:
10130 MOZ_CRASH("Unexpected type");
10131 }
10132 }
10133
10134 writer.returnFromIC();
10135
10136 trackAttached("ObjectIs");
10137 return AttachDecision::Attach;
10138 }
10139
10140 AttachDecision InlinableNativeIRGenerator::tryAttachObjectIsPrototypeOf() {
10141 // Ensure |this| is an object.
10142 if (!thisval_.isObject()) {
10143 return AttachDecision::NoAction;
10144 }
10145
10146 // Need a single argument.
10147 if (args_.length() != 1) {
10148 return AttachDecision::NoAction;
10149 }
10150
10151 // Initialize the input operand.
10152 Int32OperandId argcId = initializeInputOperand();
10153
10154 // Guard callee is the `isPrototypeOf` native function.
10155 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10156
10157 // Guard that |this| is an object.
10158 ValOperandId thisValId = loadThis(calleeId);
10159 ObjOperandId thisObjId = writer.guardToObject(thisValId);
10160
10161 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10162
10163 writer.loadInstanceOfObjectResult(argId, thisObjId);
10164 writer.returnFromIC();
10165
10166 trackAttached("ObjectIsPrototypeOf");
10167 return AttachDecision::Attach;
10168 }
10169
10170 AttachDecision InlinableNativeIRGenerator::tryAttachObjectKeys() {
10171 // Only handle argc <= 1.
10172 if (args_.length() != 1) {
10173 return AttachDecision::NoAction;
10174 }
10175
10176 // Do not attach any IC if the argument is not an object.
10177 if (!args_[0].isObject()) {
10178 return AttachDecision::NoAction;
10179 }
10180 // Do not attach any IC if the argument is a Proxy. While implementation could
10181 // work with proxies the goal of this implementation is to provide an
10182 // optimization for calls of `Object.keys(obj)` where there is no side-effect,
10183 // and where the computation of the array of property name can be moved.
10184 const JSClass* clasp = args_[0].toObject().getClass();
10185 if (clasp->isProxyObject()) {
10186 return AttachDecision::NoAction;
10187 }
10188
10189 // Generate cache IR code to attach a new inline cache which will delegate the
10190 // call to Object.keys to the native function.
10191 Int32OperandId argcId = initializeInputOperand();
10192
10193 // Guard callee is the 'keys' native function.
10194 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10195
10196 // Implicit: Note `Object.keys` is a property of the `Object` global. The fact
10197 // that we are in this function implies that we already identify the function
10198 // as being the proper one. Thus there should not be any need to validate that
10199 // this is the proper function. (test: ion/object-keys-05)
10200
10201 // Guard `arg0` is an object.
10202 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10203 ObjOperandId argObjId = writer.guardToObject(argId);
10204
10205 // Guard against proxies.
10206 writer.guardIsNotProxy(argObjId);
10207
10208 // Compute the keys array.
10209 writer.objectKeysResult(argObjId);
10210
10211 writer.returnFromIC();
10212
10213 trackAttached("ObjectKeys");
10214 return AttachDecision::Attach;
10215 }
10216
10217 AttachDecision InlinableNativeIRGenerator::tryAttachObjectToString() {
10218 // Expecting no arguments.
10219 if (args_.length() != 0) {
10220 return AttachDecision::NoAction;
10221 }
10222
10223 // Ensure |this| is an object.
10224 if (!thisval_.isObject()) {
10225 return AttachDecision::NoAction;
10226 }
10227
10228 // Don't attach if the object has @@toStringTag or is a proxy.
10229 if (!ObjectClassToString(cx_, &thisval_.toObject())) {
10230 return AttachDecision::NoAction;
10231 }
10232
10233 // Initialize the input operand.
10234 Int32OperandId argcId = initializeInputOperand();
10235
10236 // Guard callee is the 'toString' native function.
10237 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10238
10239 // Guard that |this| is an object.
10240 ValOperandId thisValId = loadThis(calleeId);
10241 ObjOperandId thisObjId = writer.guardToObject(thisValId);
10242
10243 writer.objectToStringResult(thisObjId);
10244 writer.returnFromIC();
10245
10246 trackAttached("ObjectToString");
10247 return AttachDecision::Attach;
10248 }
10249
10250 AttachDecision InlinableNativeIRGenerator::tryAttachBigInt() {
10251 // Need a single argument (Int32).
10252 if (args_.length() != 1 || !args_[0].isInt32()) {
10253 return AttachDecision::NoAction;
10254 }
10255
10256 // Initialize the input operand.
10257 Int32OperandId argcId = initializeInputOperand();
10258
10259 // Guard callee is the 'BigInt' native function.
10260 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10261
10262 // Guard that the argument is an Int32.
10263 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10264 Int32OperandId int32Id = writer.guardToInt32(argId);
10265
10266 // Convert Int32 to BigInt.
10267 IntPtrOperandId intptrId = writer.int32ToIntPtr(int32Id);
10268 writer.intPtrToBigIntResult(intptrId);
10269 writer.returnFromIC();
10270
10271 trackAttached("BigInt");
10272 return AttachDecision::Attach;
10273 }
10274
10275 AttachDecision InlinableNativeIRGenerator::tryAttachBigIntAsIntN() {
10276 // Need two arguments (Int32, BigInt).
10277 if (args_.length() != 2 || !args_[0].isInt32() || !args_[1].isBigInt()) {
10278 return AttachDecision::NoAction;
10279 }
10280
10281 // Negative bits throws an error.
10282 if (args_[0].toInt32() < 0) {
10283 return AttachDecision::NoAction;
10284 }
10285
10286 // Initialize the input operand.
10287 Int32OperandId argcId = initializeInputOperand();
10288
10289 // Guard callee is the 'BigInt.asIntN' native function.
10290 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10291
10292 // Convert bits to int32.
10293 ValOperandId bitsId = loadArgument(calleeId, ArgumentKind::Arg0);
10294 Int32OperandId int32BitsId = EmitGuardToInt32Index(writer, args_[0], bitsId);
10295
10296 // Number of bits mustn't be negative.
10297 writer.guardInt32IsNonNegative(int32BitsId);
10298
10299 ValOperandId arg1Id = loadArgument(calleeId, ArgumentKind::Arg1);
10300 BigIntOperandId bigIntId = writer.guardToBigInt(arg1Id);
10301
10302 writer.bigIntAsIntNResult(int32BitsId, bigIntId);
10303 writer.returnFromIC();
10304
10305 trackAttached("BigIntAsIntN");
10306 return AttachDecision::Attach;
10307 }
10308
10309 AttachDecision InlinableNativeIRGenerator::tryAttachBigIntAsUintN() {
10310 // Need two arguments (Int32, BigInt).
10311 if (args_.length() != 2 || !args_[0].isInt32() || !args_[1].isBigInt()) {
10312 return AttachDecision::NoAction;
10313 }
10314
10315 // Negative bits throws an error.
10316 if (args_[0].toInt32() < 0) {
10317 return AttachDecision::NoAction;
10318 }
10319
10320 // Initialize the input operand.
10321 Int32OperandId argcId = initializeInputOperand();
10322
10323 // Guard callee is the 'BigInt.asUintN' native function.
10324 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10325
10326 // Convert bits to int32.
10327 ValOperandId bitsId = loadArgument(calleeId, ArgumentKind::Arg0);
10328 Int32OperandId int32BitsId = EmitGuardToInt32Index(writer, args_[0], bitsId);
10329
10330 // Number of bits mustn't be negative.
10331 writer.guardInt32IsNonNegative(int32BitsId);
10332
10333 ValOperandId arg1Id = loadArgument(calleeId, ArgumentKind::Arg1);
10334 BigIntOperandId bigIntId = writer.guardToBigInt(arg1Id);
10335
10336 writer.bigIntAsUintNResult(int32BitsId, bigIntId);
10337 writer.returnFromIC();
10338
10339 trackAttached("BigIntAsUintN");
10340 return AttachDecision::Attach;
10341 }
10342
10343 AttachDecision InlinableNativeIRGenerator::tryAttachSetHas() {
10344 // Ensure |this| is a SetObject.
10345 if (!thisval_.isObject() || !thisval_.toObject().is<SetObject>()) {
10346 return AttachDecision::NoAction;
10347 }
10348
10349 // Need a single argument.
10350 if (args_.length() != 1) {
10351 return AttachDecision::NoAction;
10352 }
10353
10354 // Initialize the input operand.
10355 Int32OperandId argcId = initializeInputOperand();
10356
10357 // Guard callee is the 'has' native function.
10358 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10359
10360 // Guard |this| is a SetObject.
10361 ValOperandId thisValId = loadThis(calleeId);
10362 ObjOperandId objId = writer.guardToObject(thisValId);
10363 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Set);
10364
10365 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10366
10367 #ifndef JS_CODEGEN_X86
10368 // Assume the hash key will likely always have the same type when attaching
10369 // the first stub. If the call is polymorphic on the hash key, attach a stub
10370 // which handles any value.
10371 if (isFirstStub()) {
10372 switch (args_[0].type()) {
10373 case ValueType::Double:
10374 case ValueType::Int32:
10375 case ValueType::Boolean:
10376 case ValueType::Undefined:
10377 case ValueType::Null: {
10378 writer.guardToNonGCThing(argId);
10379 writer.setHasNonGCThingResult(objId, argId);
10380 break;
10381 }
10382 case ValueType::String: {
10383 StringOperandId strId = writer.guardToString(argId);
10384 writer.setHasStringResult(objId, strId);
10385 break;
10386 }
10387 case ValueType::Symbol: {
10388 SymbolOperandId symId = writer.guardToSymbol(argId);
10389 writer.setHasSymbolResult(objId, symId);
10390 break;
10391 }
10392 case ValueType::BigInt: {
10393 BigIntOperandId bigIntId = writer.guardToBigInt(argId);
10394 writer.setHasBigIntResult(objId, bigIntId);
10395 break;
10396 }
10397 case ValueType::Object: {
10398 // Currently only supported on 64-bit platforms.
10399 # ifdef JS_PUNBOX64
10400 ObjOperandId valId = writer.guardToObject(argId);
10401 writer.setHasObjectResult(objId, valId);
10402 # else
10403 writer.setHasResult(objId, argId);
10404 # endif
10405 break;
10406 }
10407
10408 case ValueType::Magic:
10409 case ValueType::PrivateGCThing:
10410 MOZ_CRASH("Unexpected type");
10411 }
10412 } else {
10413 writer.setHasResult(objId, argId);
10414 }
10415 #else
10416 // The optimized versions require too many registers on x86.
10417 writer.setHasResult(objId, argId);
10418 #endif
10419
10420 writer.returnFromIC();
10421
10422 trackAttached("SetHas");
10423 return AttachDecision::Attach;
10424 }
10425
10426 AttachDecision InlinableNativeIRGenerator::tryAttachSetDelete() {
10427 // Ensure |this| is a SetObject.
10428 if (!thisval_.isObject() || !thisval_.toObject().is<SetObject>()) {
10429 return AttachDecision::NoAction;
10430 }
10431
10432 // Need a single argument.
10433 if (args_.length() != 1) {
10434 return AttachDecision::NoAction;
10435 }
10436
10437 // Initialize the input operand.
10438 Int32OperandId argcId = initializeInputOperand();
10439
10440 // Guard callee is the 'delete' native function.
10441 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10442
10443 // Guard |this| is a SetObject.
10444 ValOperandId thisValId = loadThis(calleeId);
10445 ObjOperandId objId = writer.guardToObject(thisValId);
10446 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Set);
10447
10448 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10449 writer.setDeleteResult(objId, argId);
10450 writer.returnFromIC();
10451
10452 trackAttached("SetDelete");
10453 return AttachDecision::Attach;
10454 }
10455
10456 AttachDecision InlinableNativeIRGenerator::tryAttachSetAdd() {
10457 // Ensure |this| is a SetObject.
10458 if (!thisval_.isObject() || !thisval_.toObject().is<SetObject>()) {
10459 return AttachDecision::NoAction;
10460 }
10461
10462 // Need one argument.
10463 if (args_.length() != 1) {
10464 return AttachDecision::NoAction;
10465 }
10466
10467 // Initialize the input operand.
10468 Int32OperandId argcId = initializeInputOperand();
10469
10470 // Guard callee is the 'add' native function.
10471 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10472
10473 // Guard |this| is a SetObject.
10474 ValOperandId thisValId = loadThis(calleeId);
10475 ObjOperandId objId = writer.guardToObject(thisValId);
10476 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Set);
10477
10478 ValOperandId keyId = loadArgument(calleeId, ArgumentKind::Arg0);
10479 writer.setAddResult(objId, keyId);
10480 writer.returnFromIC();
10481
10482 trackAttached("SetAdd");
10483 return AttachDecision::Attach;
10484 }
10485
10486 AttachDecision InlinableNativeIRGenerator::tryAttachSetSize() {
10487 // Ensure |this| is a SetObject.
10488 if (!thisval_.isObject() || !thisval_.toObject().is<SetObject>()) {
10489 return AttachDecision::NoAction;
10490 }
10491
10492 // Expecting no arguments.
10493 if (args_.length() != 0) {
10494 return AttachDecision::NoAction;
10495 }
10496
10497 // Initialize the input operand.
10498 Int32OperandId argcId = initializeInputOperand();
10499
10500 // Guard callee is the 'size' native function.
10501 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10502
10503 // Guard |this| is a SetObject.
10504 ValOperandId thisValId = loadThis(calleeId);
10505 ObjOperandId objId = writer.guardToObject(thisValId);
10506 writer.guardClass(objId, GuardClassKind::Set);
10507
10508 writer.setSizeResult(objId);
10509 writer.returnFromIC();
10510
10511 trackAttached("SetSize");
10512 return AttachDecision::Attach;
10513 }
10514
10515 AttachDecision InlinableNativeIRGenerator::tryAttachMapHas() {
10516 // Ensure |this| is a MapObject.
10517 if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
10518 return AttachDecision::NoAction;
10519 }
10520
10521 // Need a single argument.
10522 if (args_.length() != 1) {
10523 return AttachDecision::NoAction;
10524 }
10525
10526 // Initialize the input operand.
10527 Int32OperandId argcId = initializeInputOperand();
10528
10529 // Guard callee is the 'has' native function.
10530 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10531
10532 // Guard |this| is a MapObject.
10533 ValOperandId thisValId = loadThis(calleeId);
10534 ObjOperandId objId = writer.guardToObject(thisValId);
10535 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);
10536
10537 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10538
10539 #ifndef JS_CODEGEN_X86
10540 // Assume the hash key will likely always have the same type when attaching
10541 // the first stub. If the call is polymorphic on the hash key, attach a stub
10542 // which handles any value.
10543 if (isFirstStub()) {
10544 switch (args_[0].type()) {
10545 case ValueType::Double:
10546 case ValueType::Int32:
10547 case ValueType::Boolean:
10548 case ValueType::Undefined:
10549 case ValueType::Null: {
10550 writer.guardToNonGCThing(argId);
10551 writer.mapHasNonGCThingResult(objId, argId);
10552 break;
10553 }
10554 case ValueType::String: {
10555 StringOperandId strId = writer.guardToString(argId);
10556 writer.mapHasStringResult(objId, strId);
10557 break;
10558 }
10559 case ValueType::Symbol: {
10560 SymbolOperandId symId = writer.guardToSymbol(argId);
10561 writer.mapHasSymbolResult(objId, symId);
10562 break;
10563 }
10564 case ValueType::BigInt: {
10565 BigIntOperandId bigIntId = writer.guardToBigInt(argId);
10566 writer.mapHasBigIntResult(objId, bigIntId);
10567 break;
10568 }
10569 case ValueType::Object: {
10570 // Currently only supported on 64-bit platforms.
10571 # ifdef JS_PUNBOX64
10572 ObjOperandId valId = writer.guardToObject(argId);
10573 writer.mapHasObjectResult(objId, valId);
10574 # else
10575 writer.mapHasResult(objId, argId);
10576 # endif
10577 break;
10578 }
10579
10580 case ValueType::Magic:
10581 case ValueType::PrivateGCThing:
10582 MOZ_CRASH("Unexpected type");
10583 }
10584 } else {
10585 writer.mapHasResult(objId, argId);
10586 }
10587 #else
10588 // The optimized versions require too many registers on x86.
10589 writer.mapHasResult(objId, argId);
10590 #endif
10591
10592 writer.returnFromIC();
10593
10594 trackAttached("MapHas");
10595 return AttachDecision::Attach;
10596 }
10597
10598 AttachDecision InlinableNativeIRGenerator::tryAttachMapGet() {
10599 // Ensure |this| is a MapObject.
10600 if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
10601 return AttachDecision::NoAction;
10602 }
10603
10604 // Need a single argument.
10605 if (args_.length() != 1) {
10606 return AttachDecision::NoAction;
10607 }
10608
10609 // Initialize the input operand.
10610 Int32OperandId argcId = initializeInputOperand();
10611
10612 // Guard callee is the 'get' native function.
10613 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10614
10615 // Guard |this| is a MapObject.
10616 ValOperandId thisValId = loadThis(calleeId);
10617 ObjOperandId objId = writer.guardToObject(thisValId);
10618 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);
10619
10620 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10621
10622 #ifndef JS_CODEGEN_X86
10623 // Assume the hash key will likely always have the same type when attaching
10624 // the first stub. If the call is polymorphic on the hash key, attach a stub
10625 // which handles any value.
10626 if (isFirstStub()) {
10627 switch (args_[0].type()) {
10628 case ValueType::Double:
10629 case ValueType::Int32:
10630 case ValueType::Boolean:
10631 case ValueType::Undefined:
10632 case ValueType::Null: {
10633 writer.guardToNonGCThing(argId);
10634 writer.mapGetNonGCThingResult(objId, argId);
10635 break;
10636 }
10637 case ValueType::String: {
10638 StringOperandId strId = writer.guardToString(argId);
10639 writer.mapGetStringResult(objId, strId);
10640 break;
10641 }
10642 case ValueType::Symbol: {
10643 SymbolOperandId symId = writer.guardToSymbol(argId);
10644 writer.mapGetSymbolResult(objId, symId);
10645 break;
10646 }
10647 case ValueType::BigInt: {
10648 BigIntOperandId bigIntId = writer.guardToBigInt(argId);
10649 writer.mapGetBigIntResult(objId, bigIntId);
10650 break;
10651 }
10652 case ValueType::Object: {
10653 // Currently only supported on 64-bit platforms.
10654 # ifdef JS_PUNBOX64
10655 ObjOperandId valId = writer.guardToObject(argId);
10656 writer.mapGetObjectResult(objId, valId);
10657 # else
10658 writer.mapGetResult(objId, argId);
10659 # endif
10660 break;
10661 }
10662
10663 case ValueType::Magic:
10664 case ValueType::PrivateGCThing:
10665 MOZ_CRASH("Unexpected type");
10666 }
10667 } else {
10668 writer.mapGetResult(objId, argId);
10669 }
10670 #else
10671 // The optimized versions require too many registers on x86.
10672 writer.mapGetResult(objId, argId);
10673 #endif
10674
10675 writer.returnFromIC();
10676
10677 trackAttached("MapGet");
10678 return AttachDecision::Attach;
10679 }
10680
10681 AttachDecision InlinableNativeIRGenerator::tryAttachMapDelete() {
10682 // Ensure |this| is a MapObject.
10683 if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
10684 return AttachDecision::NoAction;
10685 }
10686
10687 // Need a single argument.
10688 if (args_.length() != 1) {
10689 return AttachDecision::NoAction;
10690 }
10691
10692 // Initialize the input operand.
10693 Int32OperandId argcId = initializeInputOperand();
10694
10695 // Guard callee is the 'delete' native function.
10696 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10697
10698 // Guard |this| is a MapObject.
10699 ValOperandId thisValId = loadThis(calleeId);
10700 ObjOperandId objId = writer.guardToObject(thisValId);
10701 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);
10702
10703 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
10704 writer.mapDeleteResult(objId, argId);
10705 writer.returnFromIC();
10706
10707 trackAttached("MapDelete");
10708 return AttachDecision::Attach;
10709 }
10710
10711 AttachDecision InlinableNativeIRGenerator::tryAttachMapSet() {
10712 #ifdef JS_CODEGEN_X86
10713 // 32-bit x86 does not have enough registers for the AutoCallVM output, the
10714 // MapObject*, and two Values.
10715 return AttachDecision::NoAction;
10716 #endif
10717
10718 // Ensure |this| is a MapObject.
10719 if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
10720 return AttachDecision::NoAction;
10721 }
10722
10723 // Need two arguments.
10724 if (args_.length() != 2) {
10725 return AttachDecision::NoAction;
10726 }
10727
10728 // Initialize the input operand.
10729 Int32OperandId argcId = initializeInputOperand();
10730
10731 // Guard callee is the 'set' native function.
10732 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10733
10734 // Guard |this| is a MapObject.
10735 ValOperandId thisValId = loadThis(calleeId);
10736 ObjOperandId objId = writer.guardToObject(thisValId);
10737 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);
10738
10739 ValOperandId keyId = loadArgument(calleeId, ArgumentKind::Arg0);
10740 ValOperandId valId = loadArgument(calleeId, ArgumentKind::Arg1);
10741 writer.mapSetResult(objId, keyId, valId);
10742 writer.returnFromIC();
10743
10744 trackAttached("MapSet");
10745 return AttachDecision::Attach;
10746 }
10747
10748 AttachDecision InlinableNativeIRGenerator::tryAttachDateGetTime(
10749 InlinableNative native) {
10750 // Ensure |this| is a DateObject.
10751 if (!thisval_.isObject() || !thisval_.toObject().is<DateObject>()) {
10752 return AttachDecision::NoAction;
10753 }
10754
10755 if (native == InlinableNative::DateGetTime) {
10756 // Expecting no arguments.
10757 if (args_.length() != 0) {
10758 return AttachDecision::NoAction;
10759 }
10760 } else {
10761 MOZ_ASSERT(args_.length() == 1 && args_[0].isInt32());
10762 }
10763
10764 // Initialize the input operand.
10765 Int32OperandId argcId = initializeInputOperand();
10766
10767 ObjOperandId calleeId;
10768 if (native == InlinableNative::DateGetTime) {
10769 // Guard callee is the 'getTime' (or 'valueOf') native function.
10770 calleeId = emitNativeCalleeGuard(argcId);
10771 } else {
10772 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
10773 MOZ_ASSERT(native == InlinableNative::IntrinsicThisTimeValue);
10774 }
10775
10776 // Guard |this| is a DateObject.
10777 ValOperandId thisValId = loadThis(calleeId);
10778 ObjOperandId objId = writer.guardToObject(thisValId);
10779 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Date);
10780
10781 writer.loadFixedSlotTypedResult(objId, DateObject::offsetOfUTCTimeSlot(),
10782 ValueType::Double);
10783
10784 writer.returnFromIC();
10785
10786 trackAttached(native == InlinableNative::DateGetTime ? "DateGetTime"
10787 : "ThisTimeValue");
10788 return AttachDecision::Attach;
10789 }
10790
10791 AttachDecision InlinableNativeIRGenerator::tryAttachDateGet(
10792 DateComponent component) {
10793 // Ensure |this| is a DateObject.
10794 if (!thisval_.isObject() || !thisval_.toObject().is<DateObject>()) {
10795 return AttachDecision::NoAction;
10796 }
10797
10798 // Expecting no arguments.
10799 if (args_.length() != 0) {
10800 return AttachDecision::NoAction;
10801 }
10802
10803 // Can't check DateTime cache when time zone is forced to UTC.
10804 if (cx_->realm()->creationOptions().forceUTC()) {
10805 return AttachDecision::NoAction;
10806 }
10807
10808 // Initialize the input operand.
10809 Int32OperandId argcId = initializeInputOperand();
10810
10811 // Guard callee is the Date native function.
10812 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
10813
10814 // Guard |this| is a DateObject.
10815 ValOperandId thisValId = loadThis(calleeId);
10816 ObjOperandId objId = writer.guardToObject(thisValId);
10817 emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Date);
10818
10819 // Fill in the local time slots.
10820 writer.dateFillLocalTimeSlots(objId);
10821
10822 switch (component) {
10823 case DateComponent::FullYear:
10824 writer.loadFixedSlotResult(objId, DateObject::offsetOfLocalYearSlot());
10825 break;
10826 case DateComponent::Month:
10827 writer.loadFixedSlotResult(objId, DateObject::offsetOfLocalMonthSlot());
10828 break;
10829 case DateComponent::Date:
10830 writer.loadFixedSlotResult(objId, DateObject::offsetOfLocalDateSlot());
10831 break;
10832 case DateComponent::Day:
10833 writer.loadFixedSlotResult(objId, DateObject::offsetOfLocalDaySlot());
10834 break;
10835 case DateComponent::Hours: {
10836 ValOperandId secondsIntoYearValId = writer.loadFixedSlot(
10837 objId, DateObject::offsetOfLocalSecondsIntoYearSlot());
10838 writer.dateHoursFromSecondsIntoYearResult(secondsIntoYearValId);
10839 break;
10840 }
10841 case DateComponent::Minutes: {
10842 ValOperandId secondsIntoYearValId = writer.loadFixedSlot(
10843 objId, DateObject::offsetOfLocalSecondsIntoYearSlot());
10844 writer.dateMinutesFromSecondsIntoYearResult(secondsIntoYearValId);
10845 break;
10846 }
10847 case DateComponent::Seconds: {
10848 ValOperandId secondsIntoYearValId = writer.loadFixedSlot(
10849 objId, DateObject::offsetOfLocalSecondsIntoYearSlot());
10850 writer.dateSecondsFromSecondsIntoYearResult(secondsIntoYearValId);
10851 break;
10852 }
10853 }
10854
10855 writer.returnFromIC();
10856
10857 switch (component) {
10858 case DateComponent::FullYear:
10859 trackAttached("DateGetFullYear");
10860 break;
10861 case DateComponent::Month:
10862 trackAttached("DateGetMonth");
10863 break;
10864 case DateComponent::Date:
10865 trackAttached("DateGetDate");
10866 break;
10867 case DateComponent::Day:
10868 trackAttached("DateGetDay");
10869 break;
10870 case DateComponent::Hours:
10871 trackAttached("DateGetHours");
10872 break;
10873 case DateComponent::Minutes:
10874 trackAttached("DateGetMinutes");
10875 break;
10876 case DateComponent::Seconds:
10877 trackAttached("DateGetSeconds");
10878 break;
10879 }
10880 return AttachDecision::Attach;
10881 }
10882
10883 AttachDecision CallIRGenerator::tryAttachFunCall(HandleFunction callee) {
10884 MOZ_ASSERT(callee->isNativeWithoutJitEntry());
10885
10886 if (callee->native() != fun_call) {
10887 return AttachDecision::NoAction;
10888 }
10889
10890 if (!thisval_.isObject() || !thisval_.toObject().is<JSFunction>()) {
10891 return AttachDecision::NoAction;
10892 }
10893 RootedFunction target(cx_, &thisval_.toObject().as<JSFunction>());
10894
10895 bool isScripted = target->hasJitEntry();
10896 MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());
10897
10898 if (target->isClassConstructor()) {
10899 return AttachDecision::NoAction;
10900 }
10901
10902 CallFlags targetFlags(CallFlags::FunCall);
10903 if (mode_ == ICState::Mode::Specialized) {
10904 if (cx_->realm() == target->realm()) {
10905 targetFlags.setIsSameRealm();
10906 }
10907 }
10908
10909 if (mode_ == ICState::Mode::Specialized && !isScripted) {
10910 HandleValue newTarget = NullHandleValue;
10911 HandleValue thisValue = argc_ > 0 ? args_[0] : UndefinedHandleValue;
10912 HandleValueArray args =
10913 argc_ > 0 ? HandleValueArray::subarray(args_, 1, args_.length() - 1)
10914 : HandleValueArray::empty();
10915
10916 // Check for specific native-function optimizations.
10917 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
10918 args, targetFlags);
10919 TRY_ATTACH(nativeGen.tryAttachStub());
10920 }
10921
10922 Int32OperandId argcId(writer.setInputOperandId(0));
10923 ObjOperandId thisObjId = emitFunCallGuard(argcId);
10924
10925 if (mode_ == ICState::Mode::Specialized) {
10926 // Ensure that |this| is the expected target function.
10927 emitCalleeGuard(thisObjId, target);
10928
10929 if (isScripted) {
10930 writer.callScriptedFunction(thisObjId, argcId, targetFlags,
10931 ClampFixedArgc(argc_));
10932 } else {
10933 writer.callNativeFunction(thisObjId, argcId, op_, target, targetFlags,
10934 ClampFixedArgc(argc_));
10935 }
10936 } else {
10937 // Guard that |this| is a function.
10938 writer.guardClass(thisObjId, GuardClassKind::JSFunction);
10939
10940 // Guard that function is not a class constructor.
10941 writer.guardNotClassConstructor(thisObjId);
10942
10943 if (isScripted) {
10944 writer.guardFunctionHasJitEntry(thisObjId);
10945 writer.callScriptedFunction(thisObjId, argcId, targetFlags,
10946 ClampFixedArgc(argc_));
10947 } else {
10948 writer.guardFunctionHasNoJitEntry(thisObjId);
10949 writer.callAnyNativeFunction(thisObjId, argcId, targetFlags,
10950 ClampFixedArgc(argc_));
10951 }
10952 }
10953
10954 writer.returnFromIC();
10955
10956 if (isScripted) {
10957 trackAttached("Scripted fun_call");
10958 } else {
10959 trackAttached("Native fun_call");
10960 }
10961
10962 return AttachDecision::Attach;
10963 }
10964
10965 AttachDecision InlinableNativeIRGenerator::tryAttachIsTypedArray(
10966 bool isPossiblyWrapped) {
10967 // Self-hosted code calls this with a single object argument.
10968 MOZ_ASSERT(args_.length() == 1);
10969 MOZ_ASSERT(args_[0].isObject());
10970
10971 // Initialize the input operand.
10972 initializeInputOperand();
10973
10974 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
10975
10976 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
10977 ObjOperandId objArgId = writer.guardToObject(argId);
10978 writer.isTypedArrayResult(objArgId, isPossiblyWrapped);
10979 writer.returnFromIC();
10980
10981 trackAttached(isPossiblyWrapped ? "IsPossiblyWrappedTypedArray"
10982 : "IsTypedArray");
10983 return AttachDecision::Attach;
10984 }
10985
10986 AttachDecision InlinableNativeIRGenerator::tryAttachIsTypedArrayConstructor() {
10987 // Self-hosted code calls this with a single object argument.
10988 MOZ_ASSERT(args_.length() == 1);
10989 MOZ_ASSERT(args_[0].isObject());
10990
10991 // Initialize the input operand.
10992 initializeInputOperand();
10993
10994 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
10995
10996 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
10997 ObjOperandId objArgId = writer.guardToObject(argId);
10998 writer.isTypedArrayConstructorResult(objArgId);
10999 writer.returnFromIC();
11000
11001 trackAttached("IsTypedArrayConstructor");
11002 return AttachDecision::Attach;
11003 }
11004
11005 AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayByteOffset() {
11006 // Self-hosted code calls this with a single TypedArrayObject argument.
11007 MOZ_ASSERT(args_.length() == 1);
11008 MOZ_ASSERT(args_[0].isObject());
11009 MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());
11010
11011 auto* tarr = &args_[0].toObject().as<TypedArrayObject>();
11012
11013 // Initialize the input operand.
11014 initializeInputOperand();
11015
11016 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11017
11018 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
11019 ObjOperandId objArgId = writer.guardToObject(argId);
11020
11021 EmitGuardTypedArray(writer, tarr, objArgId);
11022
11023 size_t byteOffset = tarr->byteOffsetMaybeOutOfBounds();
11024 if (tarr->is<FixedLengthTypedArrayObject>()) {
11025 if (byteOffset <= INT32_MAX) {
11026 writer.arrayBufferViewByteOffsetInt32Result(objArgId);
11027 } else {
11028 writer.arrayBufferViewByteOffsetDoubleResult(objArgId);
11029 }
11030 } else {
11031 if (byteOffset <= INT32_MAX) {
11032 writer.resizableTypedArrayByteOffsetMaybeOutOfBoundsInt32Result(objArgId);
11033 } else {
11034 writer.resizableTypedArrayByteOffsetMaybeOutOfBoundsDoubleResult(
11035 objArgId);
11036 }
11037 }
11038
11039 writer.returnFromIC();
11040
11041 trackAttached("IntrinsicTypedArrayByteOffset");
11042 return AttachDecision::Attach;
11043 }
11044
11045 AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayElementSize() {
11046 // Self-hosted code calls this with a single TypedArrayObject argument.
11047 MOZ_ASSERT(args_.length() == 1);
11048 MOZ_ASSERT(args_[0].isObject());
11049 MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());
11050
11051 // Initialize the input operand.
11052 initializeInputOperand();
11053
11054 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11055
11056 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
11057 ObjOperandId objArgId = writer.guardToObject(argId);
11058 writer.typedArrayElementSizeResult(objArgId);
11059 writer.returnFromIC();
11060
11061 trackAttached("TypedArrayElementSize");
11062 return AttachDecision::Attach;
11063 }
11064
11065 AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayLength(
11066 bool isPossiblyWrapped, bool allowOutOfBounds) {
11067 // Self-hosted code calls this with a single, possibly wrapped,
11068 // TypedArrayObject argument.
11069 MOZ_ASSERT(args_.length() == 1);
11070 MOZ_ASSERT(args_[0].isObject());
11071
11072 // Only optimize when the object isn't a wrapper.
11073 if (isPossiblyWrapped && IsWrapper(&args_[0].toObject())) {
11074 return AttachDecision::NoAction;
11075 }
11076
11077 MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());
11078
11079 auto* tarr = &args_[0].toObject().as<TypedArrayObject>();
11080
11081 // Don't optimize when a resizable TypedArray is out-of-bounds and
11082 // out-of-bounds isn't allowed.
11083 auto length = tarr->length();
11084 if (length.isNothing() && !tarr->hasDetachedBuffer()) {
11085 MOZ_ASSERT(tarr->is<ResizableTypedArrayObject>());
11086 MOZ_ASSERT(tarr->isOutOfBounds());
11087
11088 if (!allowOutOfBounds) {
11089 return AttachDecision::NoAction;
11090 }
11091 }
11092
11093 // Initialize the input operand.
11094 initializeInputOperand();
11095
11096 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11097
11098 ValOperandId argId = loadArgumentIntrinsic(ArgumentKind::Arg0);
11099 ObjOperandId objArgId = writer.guardToObject(argId);
11100
11101 if (isPossiblyWrapped) {
11102 writer.guardIsNotProxy(objArgId);
11103 }
11104
11105 EmitGuardTypedArray(writer, tarr, objArgId);
11106
11107 if (tarr->is<FixedLengthTypedArrayObject>()) {
11108 if (length.valueOr(0) <= INT32_MAX) {
11109 writer.loadArrayBufferViewLengthInt32Result(objArgId);
11110 } else {
11111 writer.loadArrayBufferViewLengthDoubleResult(objArgId);
11112 }
11113 } else {
11114 if (!allowOutOfBounds) {
11115 writer.guardResizableArrayBufferViewInBoundsOrDetached(objArgId);
11116 }
11117
11118 if (length.valueOr(0) <= INT32_MAX) {
11119 writer.resizableTypedArrayLengthInt32Result(objArgId);
11120 } else {
11121 writer.resizableTypedArrayLengthDoubleResult(objArgId);
11122 }
11123 }
11124 writer.returnFromIC();
11125
11126 trackAttached("IntrinsicTypedArrayLength");
11127 return AttachDecision::Attach;
11128 }
11129
11130 AttachDecision InlinableNativeIRGenerator::tryAttachIsConstructing() {
11131 // Self-hosted code calls this with no arguments in function scripts.
11132 MOZ_ASSERT(args_.length() == 0);
11133 MOZ_ASSERT(script()->isFunction());
11134
11135 // Initialize the input operand.
11136 initializeInputOperand();
11137
11138 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11139
11140 writer.frameIsConstructingResult();
11141 writer.returnFromIC();
11142
11143 trackAttached("IsConstructing");
11144 return AttachDecision::Attach;
11145 }
11146
11147 AttachDecision
11148 InlinableNativeIRGenerator::tryAttachGetNextMapSetEntryForIterator(bool isMap) {
11149 // Self-hosted code calls this with two objects.
11150 MOZ_ASSERT(args_.length() == 2);
11151 if (isMap) {
11152 MOZ_ASSERT(args_[0].toObject().is<MapIteratorObject>());
11153 } else {
11154 MOZ_ASSERT(args_[0].toObject().is<SetIteratorObject>());
11155 }
11156 MOZ_ASSERT(args_[1].toObject().is<ArrayObject>());
11157
11158 // Initialize the input operand.
11159 initializeInputOperand();
11160
11161 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11162
11163 ValOperandId iterId = loadArgumentIntrinsic(ArgumentKind::Arg0);
11164 ObjOperandId objIterId = writer.guardToObject(iterId);
11165
11166 ValOperandId resultArrId = loadArgumentIntrinsic(ArgumentKind::Arg1);
11167 ObjOperandId objResultArrId = writer.guardToObject(resultArrId);
11168
11169 writer.getNextMapSetEntryForIteratorResult(objIterId, objResultArrId, isMap);
11170 writer.returnFromIC();
11171
11172 trackAttached("GetNextMapSetEntryForIterator");
11173 return AttachDecision::Attach;
11174 }
11175
11176 AttachDecision InlinableNativeIRGenerator::tryAttachNewArrayIterator() {
11177 // Self-hosted code calls this without any arguments
11178 MOZ_ASSERT(args_.length() == 0);
11179
11180 JSObject* templateObj = NewArrayIteratorTemplate(cx_);
11181 if (!templateObj) {
11182 cx_->recoverFromOutOfMemory();
11183 return AttachDecision::NoAction;
11184 }
11185
11186 // Initialize the input operand.
11187 initializeInputOperand();
11188
11189 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11190
11191 writer.newArrayIteratorResult(templateObj);
11192 writer.returnFromIC();
11193
11194 trackAttached("NewArrayIterator");
11195 return AttachDecision::Attach;
11196 }
11197
11198 AttachDecision InlinableNativeIRGenerator::tryAttachNewStringIterator() {
11199 // Self-hosted code calls this without any arguments
11200 MOZ_ASSERT(args_.length() == 0);
11201
11202 JSObject* templateObj = NewStringIteratorTemplate(cx_);
11203 if (!templateObj) {
11204 cx_->recoverFromOutOfMemory();
11205 return AttachDecision::NoAction;
11206 }
11207
11208 // Initialize the input operand.
11209 initializeInputOperand();
11210
11211 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11212
11213 writer.newStringIteratorResult(templateObj);
11214 writer.returnFromIC();
11215
11216 trackAttached("NewStringIterator");
11217 return AttachDecision::Attach;
11218 }
11219
11220 AttachDecision InlinableNativeIRGenerator::tryAttachNewRegExpStringIterator() {
11221 // Self-hosted code calls this without any arguments
11222 MOZ_ASSERT(args_.length() == 0);
11223
11224 JSObject* templateObj = NewRegExpStringIteratorTemplate(cx_);
11225 if (!templateObj) {
11226 cx_->recoverFromOutOfMemory();
11227 return AttachDecision::NoAction;
11228 }
11229
11230 // Initialize the input operand.
11231 initializeInputOperand();
11232
11233 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11234
11235 writer.newRegExpStringIteratorResult(templateObj);
11236 writer.returnFromIC();
11237
11238 trackAttached("NewRegExpStringIterator");
11239 return AttachDecision::Attach;
11240 }
11241
11242 AttachDecision
11243 InlinableNativeIRGenerator::tryAttachArrayIteratorPrototypeOptimizable() {
11244 // Self-hosted code calls this without any arguments
11245 MOZ_ASSERT(args_.length() == 0);
11246
11247 if (!isFirstStub()) {
11248 // Attach only once to prevent slowdowns for polymorphic calls.
11249 return AttachDecision::NoAction;
11250 }
11251
11252 if (!HasOptimizableArrayIteratorPrototype(cx_)) {
11253 return AttachDecision::NoAction;
11254 }
11255
11256 // Initialize the input operand.
11257 initializeInputOperand();
11258
11259 // Note: we don't need to call emitNativeCalleeGuard for intrinsics.
11260
11261 writer.guardFuse(RealmFuses::FuseIndex::OptimizeArrayIteratorPrototypeFuse);
11262 writer.loadBooleanResult(true);
11263 writer.returnFromIC();
11264
11265 trackAttached("ArrayIteratorPrototypeOptimizable");
11266 return AttachDecision::Attach;
11267 }
11268
11269 AttachDecision InlinableNativeIRGenerator::tryAttachObjectCreate() {
11270 // Need a single object-or-null argument.
11271 if (args_.length() != 1 || !args_[0].isObjectOrNull()) {
11272 return AttachDecision::NoAction;
11273 }
11274
11275 if (!isFirstStub()) {
11276 // Attach only once to prevent slowdowns for polymorphic calls.
11277 return AttachDecision::NoAction;
11278 }
11279
11280 RootedObject proto(cx_, args_[0].toObjectOrNull());
11281 JSObject* templateObj = ObjectCreateImpl(cx_, proto, TenuredObject);
11282 if (!templateObj) {
11283 cx_->recoverFromOutOfMemory();
11284 return AttachDecision::NoAction;
11285 }
11286
11287 // Initialize the input operand.
11288 Int32OperandId argcId = initializeInputOperand();
11289
11290 // Guard callee is the 'create' native function.
11291 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11292
11293 // Guard on the proto argument.
11294 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
11295 if (proto) {
11296 ObjOperandId protoId = writer.guardToObject(argId);
11297 writer.guardSpecificObject(protoId, proto);
11298 } else {
11299 writer.guardIsNull(argId);
11300 }
11301
11302 writer.objectCreateResult(templateObj);
11303 writer.returnFromIC();
11304
11305 trackAttached("ObjectCreate");
11306 return AttachDecision::Attach;
11307 }
11308
11309 AttachDecision InlinableNativeIRGenerator::tryAttachObjectConstructor() {
11310 // Expecting no arguments or a single object argument.
11311 // TODO(Warp): Support all or more conversions to object.
11312 if (args_.length() > 1) {
11313 return AttachDecision::NoAction;
11314 }
11315 if (args_.length() == 1 && !args_[0].isObject()) {
11316 return AttachDecision::NoAction;
11317 }
11318
11319 gc::AllocSite* site = nullptr;
11320 PlainObject* templateObj = nullptr;
11321 if (args_.length() == 0) {
11322 // Stub doesn't support metadata builder
11323 if (cx_->realm()->hasAllocationMetadataBuilder()) {
11324 return AttachDecision::NoAction;
11325 }
11326
11327 site = generator_.maybeCreateAllocSite();
11328 if (!site) {
11329 return AttachDecision::NoAction;
11330 }
11331
11332 // Create a temporary object to act as the template object.
11333 templateObj = NewPlainObjectWithAllocKind(cx_, NewObjectGCKind());
11334 if (!templateObj) {
11335 cx_->recoverFromOutOfMemory();
11336 return AttachDecision::NoAction;
11337 }
11338 }
11339
11340 // Initialize the input operand.
11341 Int32OperandId argcId = initializeInputOperand();
11342
11343 // Guard callee and newTarget (if constructing) are this Object constructor
11344 // function.
11345 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11346
11347 if (args_.length() == 0) {
11348 uint32_t numFixedSlots = templateObj->numUsedFixedSlots();
11349 uint32_t numDynamicSlots = templateObj->numDynamicSlots();
11350 gc::AllocKind allocKind = templateObj->allocKindForTenure();
11351 Shape* shape = templateObj->shape();
11352
11353 writer.guardNoAllocationMetadataBuilder(
11354 cx_->realm()->addressOfMetadataBuilder());
11355 writer.newPlainObjectResult(numFixedSlots, numDynamicSlots, allocKind,
11356 shape, site);
11357 } else {
11358 // Guard that the argument is an object.
11359 ValOperandId argId = loadArgument(calleeId, ArgumentKind::Arg0);
11360 ObjOperandId objId = writer.guardToObject(argId);
11361
11362 // Return the object.
11363 writer.loadObjectResult(objId);
11364 }
11365
11366 writer.returnFromIC();
11367
11368 trackAttached("ObjectConstructor");
11369 return AttachDecision::Attach;
11370 }
11371
11372 AttachDecision InlinableNativeIRGenerator::tryAttachArrayConstructor() {
11373 // Only optimize the |Array()| and |Array(n)| cases (with or without |new|)
11374 // for now. Note that self-hosted code calls this without |new| via std_Array.
11375 if (args_.length() > 1) {
11376 return AttachDecision::NoAction;
11377 }
11378 if (args_.length() == 1 && !args_[0].isInt32()) {
11379 return AttachDecision::NoAction;
11380 }
11381
11382 int32_t length = (args_.length() == 1) ? args_[0].toInt32() : 0;
11383 if (length < 0 || uint32_t(length) > ArrayObject::EagerAllocationMaxLength) {
11384 return AttachDecision::NoAction;
11385 }
11386
11387 // We allow inlining this function across realms so make sure the template
11388 // object is allocated in that realm. See CanInlineNativeCrossRealm.
11389 JSObject* templateObj;
11390 {
11391 AutoRealm ar(cx_, target_);
11392 templateObj = NewDenseFullyAllocatedArray(cx_, length, TenuredObject);
11393 if (!templateObj) {
11394 cx_->clearPendingException();
11395 return AttachDecision::NoAction;
11396 }
11397 }
11398
11399 gc::AllocSite* site = generator_.maybeCreateAllocSite();
11400 if (!site) {
11401 return AttachDecision::NoAction;
11402 }
11403
11404 // Initialize the input operand.
11405 Int32OperandId argcId = initializeInputOperand();
11406
11407 // Guard callee and newTarget (if constructing) are this Array constructor
11408 // function.
11409 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11410
11411 Int32OperandId lengthId;
11412 if (args_.length() == 1) {
11413 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
11414 lengthId = writer.guardToInt32(arg0Id);
11415 } else {
11416 MOZ_ASSERT(args_.length() == 0);
11417 lengthId = writer.loadInt32Constant(0);
11418 }
11419
11420 writer.newArrayFromLengthResult(templateObj, lengthId, site);
11421 writer.returnFromIC();
11422
11423 trackAttached("ArrayConstructor");
11424 return AttachDecision::Attach;
11425 }
11426
11427 AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayConstructor() {
11428 MOZ_ASSERT(flags_.isConstructing());
11429
11430 if (args_.length() == 0 || args_.length() > 3) {
11431 return AttachDecision::NoAction;
11432 }
11433
11434 if (!isFirstStub()) {
11435 // Attach only once to prevent slowdowns for polymorphic calls.
11436 return AttachDecision::NoAction;
11437 }
11438
11439 // The first argument must be int32 or a non-proxy object.
11440 if (!args_[0].isInt32() && !args_[0].isObject()) {
11441 return AttachDecision::NoAction;
11442 }
11443 if (args_[0].isObject() && args_[0].toObject().is<ProxyObject>()) {
11444 return AttachDecision::NoAction;
11445 }
11446
11447 #ifdef JS_CODEGEN_X86
11448 // Unfortunately NewTypedArrayFromArrayBufferResult needs more registers than
11449 // we can easily support on 32-bit x86 for now.
11450 if (args_[0].isObject() &&
11451 args_[0].toObject().is<ArrayBufferObjectMaybeShared>()) {
11452 return AttachDecision::NoAction;
11453 }
11454 #endif
11455
11456 RootedObject templateObj(cx_);
11457 if (!TypedArrayObject::GetTemplateObjectForNative(cx_, target_->native(),
11458 args_, &templateObj)) {
11459 cx_->recoverFromOutOfMemory();
11460 return AttachDecision::NoAction;
11461 }
11462
11463 if (!templateObj) {
11464 // This can happen for large length values.
11465 MOZ_ASSERT(args_[0].isInt32());
11466 return AttachDecision::NoAction;
11467 }
11468
11469 // Initialize the input operand.
11470 Int32OperandId argcId = initializeInputOperand();
11471
11472 // Guard callee and newTarget are this TypedArray constructor function.
11473 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11474
11475 ValOperandId arg0Id = loadArgument(calleeId, ArgumentKind::Arg0);
11476
11477 if (args_[0].isInt32()) {
11478 // From length.
11479 Int32OperandId lengthId = writer.guardToInt32(arg0Id);
11480 writer.newTypedArrayFromLengthResult(templateObj, lengthId);
11481 } else {
11482 JSObject* obj = &args_[0].toObject();
11483 ObjOperandId objId = writer.guardToObject(arg0Id);
11484
11485 if (obj->is<ArrayBufferObjectMaybeShared>()) {
11486 // From ArrayBuffer.
11487 if (obj->is<FixedLengthArrayBufferObject>()) {
11488 writer.guardClass(objId, GuardClassKind::FixedLengthArrayBuffer);
11489 } else if (obj->is<FixedLengthSharedArrayBufferObject>()) {
11490 writer.guardClass(objId, GuardClassKind::FixedLengthSharedArrayBuffer);
11491 } else if (obj->is<ResizableArrayBufferObject>()) {
11492 writer.guardClass(objId, GuardClassKind::ResizableArrayBuffer);
11493 } else {
11494 MOZ_ASSERT(obj->is<GrowableSharedArrayBufferObject>());
11495 writer.guardClass(objId, GuardClassKind::GrowableSharedArrayBuffer);
11496 }
11497 ValOperandId byteOffsetId;
11498 if (args_.length() > 1) {
11499 byteOffsetId = loadArgument(calleeId, ArgumentKind::Arg1);
11500 } else {
11501 byteOffsetId = writer.loadUndefined();
11502 }
11503 ValOperandId lengthId;
11504 if (args_.length() > 2) {
11505 lengthId = loadArgument(calleeId, ArgumentKind::Arg2);
11506 } else {
11507 lengthId = writer.loadUndefined();
11508 }
11509 writer.newTypedArrayFromArrayBufferResult(templateObj, objId,
11510 byteOffsetId, lengthId);
11511 } else {
11512 // From Array-like.
11513 writer.guardIsNotArrayBufferMaybeShared(objId);
11514 writer.guardIsNotProxy(objId);
11515 writer.newTypedArrayFromArrayResult(templateObj, objId);
11516 }
11517 }
11518
11519 writer.returnFromIC();
11520
11521 trackAttached("TypedArrayConstructor");
11522 return AttachDecision::Attach;
11523 }
11524
11525 AttachDecision InlinableNativeIRGenerator::tryAttachMapSetConstructor(
11526 InlinableNative native) {
11527 MOZ_ASSERT(native == InlinableNative::MapConstructor ||
11528 native == InlinableNative::SetConstructor);
11529 MOZ_ASSERT(flags_.isConstructing());
11530
11531 // Must have either no arguments or a single (iterable) argument.
11532 if (args_.length() > 1) {
11533 return AttachDecision::NoAction;
11534 }
11535
11536 if (!isFirstStub()) {
11537 // Attach only once to prevent slowdowns for polymorphic calls.
11538 return AttachDecision::NoAction;
11539 }
11540
11541 JSObject* templateObj;
11542 if (native == InlinableNative::MapConstructor) {
11543 templateObj = GlobalObject::getOrCreateMapTemplateObject(cx_);
11544 } else {
11545 templateObj = GlobalObject::getOrCreateSetTemplateObject(cx_);
11546 }
11547 if (!templateObj) {
11548 cx_->recoverFromOutOfMemory();
11549 return AttachDecision::NoAction;
11550 }
11551
11552 // Initialize the input operand.
11553 Int32OperandId argcId = initializeInputOperand();
11554
11555 // Guard callee and newTarget are this Map/Set constructor function.
11556 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11557
11558 if (args_.length() == 1) {
11559 ValOperandId iterableId = loadArgument(calleeId, ArgumentKind::Arg0);
11560 if (native == InlinableNative::MapConstructor) {
11561 writer.newMapObjectFromIterableResult(templateObj, iterableId);
11562 } else {
11563 writer.newSetObjectFromIterableResult(templateObj, iterableId);
11564 }
11565 } else {
11566 if (native == InlinableNative::MapConstructor) {
11567 writer.newMapObjectResult(templateObj);
11568 } else {
11569 writer.newSetObjectResult(templateObj);
11570 }
11571 }
11572 writer.returnFromIC();
11573
11574 if (native == InlinableNative::MapConstructor) {
11575 trackAttached("MapConstructor");
11576 } else {
11577 trackAttached("SetConstructor");
11578 }
11579 return AttachDecision::Attach;
11580 }
11581
11582 AttachDecision InlinableNativeIRGenerator::tryAttachSpecializedFunctionBind(
11583 Handle<JSObject*> target, Handle<BoundFunctionObject*> templateObj) {
11584 // Try to attach a faster stub that's more specialized than what we emit in
11585 // tryAttachFunctionBind. This lets us allocate and initialize a bound
11586 // function object in Ion without calling into C++.
11587 //
11588 // We can do this if:
11589 //
11590 // * The target's prototype is Function.prototype, because that's the proto we
11591 // use for the template object.
11592 // * All bound arguments can be stored inline.
11593 // * The `.name`, `.length`, and `IsConstructor` values match `target`.
11594 //
11595 // We initialize the template object with the bound function's name, length,
11596 // and flags. At runtime we then only have to clone the template object and
11597 // initialize the slots for the target, the bound `this` and the bound
11598 // arguments.
11599
11600 if (!isFirstStub()) {
11601 return AttachDecision::NoAction;
11602 }
11603 if (!target->is<JSFunction>() && !target->is<BoundFunctionObject>()) {
11604 return AttachDecision::NoAction;
11605 }
11606 if (target->staticPrototype() != &cx_->global()->getFunctionPrototype()) {
11607 return AttachDecision::NoAction;
11608 }
11609 size_t numBoundArgs = args_.length() > 0 ? args_.length() - 1 : 0;
11610 if (numBoundArgs > BoundFunctionObject::MaxInlineBoundArgs) {
11611 return AttachDecision::NoAction;
11612 }
11613
11614 const bool targetIsConstructor = target->isConstructor();
11615 Rooted<JSAtom*> targetName(cx_);
11616 uint32_t targetLength = 0;
11617
11618 if (target->is<JSFunction>()) {
11619 Rooted<JSFunction*> fun(cx_, &target->as<JSFunction>());
11620 if (fun->isNativeFun()) {
11621 return AttachDecision::NoAction;
11622 }
11623 if (fun->hasResolvedLength() || fun->hasResolvedName()) {
11624 return AttachDecision::NoAction;
11625 }
11626 uint16_t len;
11627 if (!JSFunction::getUnresolvedLength(cx_, fun, &len)) {
11628 cx_->clearPendingException();
11629 return AttachDecision::NoAction;
11630 }
11631 targetName = fun->getUnresolvedName(cx_);
11632 if (!targetName) {
11633 cx_->clearPendingException();
11634 return AttachDecision::NoAction;
11635 }
11636
11637 targetLength = len;
11638 } else {
11639 BoundFunctionObject* bound = &target->as<BoundFunctionObject>();
11640 if (!targetIsConstructor) {
11641 // Only support constructors for now. This lets us use
11642 // GuardBoundFunctionIsConstructor.
11643 return AttachDecision::NoAction;
11644 }
11645 Shape* initialShape =
11646 cx_->global()->maybeBoundFunctionShapeWithDefaultProto();
11647 if (bound->shape() != initialShape) {
11648 return AttachDecision::NoAction;
11649 }
11650 Value lenVal = bound->getLengthForInitialShape();
11651 Value nameVal = bound->getNameForInitialShape();
11652 if (!lenVal.isInt32() || lenVal.toInt32() < 0 || !nameVal.isString() ||
11653 !nameVal.toString()->isAtom()) {
11654 return AttachDecision::NoAction;
11655 }
11656 targetName = &nameVal.toString()->asAtom();
11657 targetLength = uint32_t(lenVal.toInt32());
11658 }
11659
11660 if (!templateObj->initTemplateSlotsForSpecializedBind(
11661 cx_, numBoundArgs, targetIsConstructor, targetLength, targetName)) {
11662 cx_->recoverFromOutOfMemory();
11663 return AttachDecision::NoAction;
11664 }
11665
11666 Int32OperandId argcId = initializeInputOperand();
11667 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11668
11669 ValOperandId thisValId = loadThis(calleeId);
11670 ObjOperandId targetId = writer.guardToObject(thisValId);
11671
11672 // Ensure the JSClass and proto match, and that the `length` and `name`
11673 // properties haven't been redefined.
11674 writer.guardShape(targetId, target->shape());
11675
11676 // Emit guards for the `IsConstructor`, `.length`, and `.name` values.
11677 if (target->is<JSFunction>()) {
11678 // Guard on:
11679 // * The BaseScript (because that's what JSFunction uses for the `length`).
11680 // Because MGuardFunctionScript doesn't support self-hosted functions yet,
11681 // we use GuardSpecificFunction instead in this case.
11682 // See assertion in MGuardFunctionScript::getAliasSet.
11683 // * The flags slot (for the CONSTRUCTOR, RESOLVED_NAME, RESOLVED_LENGTH,
11684 // HAS_INFERRED_NAME, and HAS_GUESSED_ATOM flags).
11685 // * The atom slot.
11686 JSFunction* fun = &target->as<JSFunction>();
11687 if (fun->isSelfHostedBuiltin()) {
11688 writer.guardSpecificFunction(targetId, fun);
11689 } else {
11690 writer.guardFunctionScript(targetId, fun->baseScript());
11691 }
11692 writer.guardFixedSlotValue(
11693 targetId, JSFunction::offsetOfFlagsAndArgCount(),
11694 fun->getReservedSlot(JSFunction::FlagsAndArgCountSlot));
11695 writer.guardFixedSlotValue(targetId, JSFunction::offsetOfAtom(),
11696 fun->getReservedSlot(JSFunction::AtomSlot));
11697 } else {
11698 BoundFunctionObject* bound = &target->as<BoundFunctionObject>();
11699 writer.guardBoundFunctionIsConstructor(targetId);
11700 writer.guardFixedSlotValue(targetId,
11701 BoundFunctionObject::offsetOfLengthSlot(),
11702 bound->getLengthForInitialShape());
11703 writer.guardFixedSlotValue(targetId,
11704 BoundFunctionObject::offsetOfNameSlot(),
11705 bound->getNameForInitialShape());
11706 }
11707
11708 writer.specializedBindFunctionResult(targetId, args_.length(), templateObj);
11709 writer.returnFromIC();
11710
11711 trackAttached("SpecializedFunctionBind");
11712 return AttachDecision::Attach;
11713 }
11714
11715 AttachDecision InlinableNativeIRGenerator::tryAttachFunctionBind() {
11716 // Ensure |this| (the target) is a function object or a bound function object.
11717 // We could support other callables too, but note that we rely on the target
11718 // having a static prototype in BoundFunctionObject::functionBindImpl.
11719 if (!thisval_.isObject()) {
11720 return AttachDecision::NoAction;
11721 }
11722 Rooted<JSObject*> target(cx_, &thisval_.toObject());
11723 if (!target->is<JSFunction>() && !target->is<BoundFunctionObject>()) {
11724 return AttachDecision::NoAction;
11725 }
11726
11727 // Only support standard, non-spread calls.
11728 if (flags_.getArgFormat() != CallFlags::Standard) {
11729 return AttachDecision::NoAction;
11730 }
11731
11732 // Only support when no additional bound arguments are present.
11733 if (hasBoundArguments()) {
11734 return AttachDecision::NoAction;
11735 }
11736 MOZ_ASSERT(stackArgc() == args_.length(), "argc matches number of arguments");
11737
11738 // Only optimize if the number of arguments is small. This ensures we don't
11739 // compile a lot of different stubs (because we bake in argc) and that we
11740 // don't get anywhere near ARGS_LENGTH_MAX.
11741 static constexpr size_t MaxArguments = 6;
11742 if (args_.length() > MaxArguments) {
11743 return AttachDecision::NoAction;
11744 }
11745
11746 Rooted<BoundFunctionObject*> templateObj(
11747 cx_, BoundFunctionObject::createTemplateObject(cx_));
11748 if (!templateObj) {
11749 cx_->recoverFromOutOfMemory();
11750 return AttachDecision::NoAction;
11751 }
11752
11753 TRY_ATTACH(tryAttachSpecializedFunctionBind(target, templateObj));
11754
11755 Int32OperandId argcId = initializeInputOperand();
11756
11757 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
11758
11759 // Guard |this| is a function object or a bound function object.
11760 ValOperandId thisValId = loadThis(calleeId);
11761 ObjOperandId targetId = writer.guardToObject(thisValId);
11762 if (target->is<JSFunction>()) {
11763 writer.guardClass(targetId, GuardClassKind::JSFunction);
11764 } else {
11765 MOZ_ASSERT(target->is<BoundFunctionObject>());
11766 writer.guardClass(targetId, GuardClassKind::BoundFunction);
11767 }
11768
11769 writer.bindFunctionResult(targetId, args_.length(), templateObj);
11770 writer.returnFromIC();
11771
11772 trackAttached("FunctionBind");
11773 return AttachDecision::Attach;
11774 }
11775
11776 AttachDecision CallIRGenerator::tryAttachFunApply(HandleFunction calleeFunc) {
11777 MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());
11778
11779 if (calleeFunc->native() != fun_apply) {
11780 return AttachDecision::NoAction;
11781 }
11782
11783 if (argc_ > 2) {
11784 return AttachDecision::NoAction;
11785 }
11786
11787 if (!thisval_.isObject() || !thisval_.toObject().is<JSFunction>()) {
11788 return AttachDecision::NoAction;
11789 }
11790 Rooted<JSFunction*> target(cx_, &thisval_.toObject().as<JSFunction>());
11791
11792 bool isScripted = target->hasJitEntry();
11793 MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());
11794
11795 if (target->isClassConstructor()) {
11796 return AttachDecision::NoAction;
11797 }
11798
11799 CallFlags::ArgFormat format = CallFlags::Standard;
11800 if (argc_ < 2) {
11801 // |fun.apply()| and |fun.apply(thisValue)| are equivalent to |fun.call()|
11802 // resp. |fun.call(thisValue)|.
11803 format = CallFlags::FunCall;
11804 } else if (args_[1].isNullOrUndefined()) {
11805 // |fun.apply(thisValue, null)| and |fun.apply(thisValue, undefined)| are
11806 // also equivalent to |fun.call(thisValue)|, but we can't use FunCall
11807 // because we have to discard the second argument.
11808 format = CallFlags::FunApplyNullUndefined;
11809 } else if (args_[1].isObject() && args_[1].toObject().is<ArgumentsObject>()) {
11810 auto* argsObj = &args_[1].toObject().as<ArgumentsObject>();
11811 if (argsObj->hasOverriddenElement() || argsObj->anyArgIsForwarded() ||
11812 argsObj->hasOverriddenLength() ||
11813 argsObj->initialLength() > JIT_ARGS_LENGTH_MAX) {
11814 return AttachDecision::NoAction;
11815 }
11816 format = CallFlags::FunApplyArgsObj;
11817 } else if (args_[1].isObject() && args_[1].toObject().is<ArrayObject>() &&
11818 args_[1].toObject().as<ArrayObject>().length() <=
11819 JIT_ARGS_LENGTH_MAX &&
11820 IsPackedArray(&args_[1].toObject())) {
11821 format = CallFlags::FunApplyArray;
11822 } else {
11823 return AttachDecision::NoAction;
11824 }
11825
11826 CallFlags targetFlags(format);
11827 if (mode_ == ICState::Mode::Specialized) {
11828 if (cx_->realm() == target->realm()) {
11829 targetFlags.setIsSameRealm();
11830 }
11831 }
11832
11833 if (mode_ == ICState::Mode::Specialized && !isScripted &&
11834 format == CallFlags::FunApplyArray) {
11835 HandleValue newTarget = NullHandleValue;
11836 HandleValue thisValue = args_[0];
11837 Rooted<ArrayObject*> aobj(cx_, &args_[1].toObject().as<ArrayObject>());
11838 HandleValueArray args = HandleValueArray::fromMarkedLocation(
11839 aobj->length(), aobj->getDenseElements());
11840
11841 // Check for specific native-function optimizations.
11842 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
11843 args, targetFlags);
11844 TRY_ATTACH(nativeGen.tryAttachStub());
11845 }
11846
11847 if (mode_ == ICState::Mode::Specialized && !isScripted &&
11848 (format == CallFlags::FunCall ||
11849 format == CallFlags::FunApplyNullUndefined)) {
11850 HandleValue newTarget = NullHandleValue;
11851 HandleValue thisValue = argc_ > 0 ? args_[0] : UndefinedHandleValue;
11852 HandleValueArray args = HandleValueArray::empty();
11853
11854 // Check for specific native-function optimizations.
11855 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
11856 args, targetFlags);
11857 TRY_ATTACH(nativeGen.tryAttachStub());
11858 }
11859
11860 Int32OperandId argcId(writer.setInputOperandId(0));
11861 ObjOperandId thisObjId = emitFunApplyGuard(argcId);
11862
11863 uint32_t fixedArgc;
11864 if (format == CallFlags::FunApplyArray ||
11865 format == CallFlags::FunApplyArgsObj ||
11866 format == CallFlags::FunApplyNullUndefined) {
11867 emitFunApplyArgsGuard(format);
11868
11869 // We always use MaxUnrolledArgCopy here because the fixed argc is
11870 // meaningless in a FunApply case.
11871 fixedArgc = MaxUnrolledArgCopy;
11872 } else {
11873 MOZ_ASSERT(format == CallFlags::FunCall);
11874
11875 // Whereas for the FunCall case we need to use the actual fixed argc value.
11876 fixedArgc = ClampFixedArgc(argc_);
11877 }
11878
11879 if (mode_ == ICState::Mode::Specialized) {
11880 // Ensure that |this| is the expected target function.
11881 emitCalleeGuard(thisObjId, target);
11882
11883 if (isScripted) {
11884 writer.callScriptedFunction(thisObjId, argcId, targetFlags, fixedArgc);
11885 } else {
11886 writer.callNativeFunction(thisObjId, argcId, op_, target, targetFlags,
11887 fixedArgc);
11888 }
11889 } else {
11890 // Guard that |this| is a function.
11891 writer.guardClass(thisObjId, GuardClassKind::JSFunction);
11892
11893 // Guard that function is not a class constructor.
11894 writer.guardNotClassConstructor(thisObjId);
11895
11896 if (isScripted) {
11897 // Guard that function is scripted.
11898 writer.guardFunctionHasJitEntry(thisObjId);
11899 writer.callScriptedFunction(thisObjId, argcId, targetFlags, fixedArgc);
11900 } else {
11901 // Guard that function is native.
11902 writer.guardFunctionHasNoJitEntry(thisObjId);
11903 writer.callAnyNativeFunction(thisObjId, argcId, targetFlags, fixedArgc);
11904 }
11905 }
11906
11907 writer.returnFromIC();
11908
11909 if (isScripted) {
11910 trackAttached("Call.ScriptedFunApply");
11911 } else {
11912 trackAttached("Call.NativeFunApply");
11913 }
11914
11915 return AttachDecision::Attach;
11916 }
11917
11918 AttachDecision CallIRGenerator::tryAttachWasmCall(HandleFunction calleeFunc) {
11919 // Try to optimize calls into Wasm code by emitting the CallWasmFunction
11920 // CacheIR op. Baseline ICs currently treat this as a CallScriptedFunction op
11921 // (calling Wasm's JitEntry stub) but Warp transpiles it to a more direct call
11922 // into Wasm code.
11923 //
11924 // Note: some code refers to these optimized Wasm calls as "inlined" calls.
11925
11926 MOZ_ASSERT(calleeFunc->isWasmWithJitEntry());
11927
11928 if (!JitOptions.enableWasmIonFastCalls) {
11929 return AttachDecision::NoAction;
11930 }
11931 if (!isFirstStub_) {
11932 return AttachDecision::NoAction;
11933 }
11934 JSOp op = JSOp(*pc_);
11935 if (op != JSOp::Call && op != JSOp::CallContent &&
11936 op != JSOp::CallIgnoresRv) {
11937 return AttachDecision::NoAction;
11938 }
11939 if (cx_->realm() != calleeFunc->realm()) {
11940 return AttachDecision::NoAction;
11941 }
11942
11943 wasm::Instance& inst = calleeFunc->wasmInstance();
11944 uint32_t funcIndex = calleeFunc->wasmFuncIndex();
11945 const wasm::CodeBlock& codeBlock = inst.code().funcCodeBlock(funcIndex);
11946 const wasm::FuncExport& funcExport = codeBlock.lookupFuncExport(funcIndex);
11947 const wasm::FuncType& sig = calleeFunc->wasmTypeDef()->funcType();
11948
11949 MOZ_ASSERT(!IsInsideNursery(inst.object()));
11950 MOZ_ASSERT(sig.canHaveJitEntry(), "Function should allow a Wasm JitEntry");
11951
11952 // If there are too many arguments, don't optimize (we won't be able to store
11953 // the arguments in the LIR node).
11954 static_assert(wasm::MaxArgsForJitInlineCall <= ArgumentKindArgIndexLimit);
11955 if (sig.args().length() > wasm::MaxArgsForJitInlineCall ||
11956 argc_ > ArgumentKindArgIndexLimit) {
11957 return AttachDecision::NoAction;
11958 }
11959
11960 // If there are too many results, don't optimize as Warp currently doesn't
11961 // have code to handle this.
11962 if (sig.results().length() > wasm::MaxResultsForJitInlineCall) {
11963 return AttachDecision::NoAction;
11964 }
11965
11966 // Bug 1631656 - Don't try to optimize with I64 args on 32-bit platforms
11967 // because it is more difficult (because it requires multiple LIR arguments
11968 // per I64).
11969 //
11970 // Bug 1631650 - On 64-bit platforms, we also give up optimizing for I64 args
11971 // spilled to the stack because it causes problems with register allocation.
11972 #ifdef JS_64BIT
11973 constexpr bool optimizeWithI64 = true;
11974 #else
11975 constexpr bool optimizeWithI64 = false;
11976 #endif
11977 ABIArgGenerator abi;
11978 for (const auto& valType : sig.args()) {
11979 MIRType mirType = valType.toMIRType();
11980 ABIArg abiArg = abi.next(mirType);
11981 if (mirType != MIRType::Int64) {
11982 continue;
11983 }
11984 if (!optimizeWithI64 || abiArg.kind() == ABIArg::Stack) {
11985 return AttachDecision::NoAction;
11986 }
11987 }
11988
11989 // Check that all arguments can be converted to the Wasm type in Warp code
11990 // without bailing out.
11991 for (size_t i = 0; i < sig.args().length(); i++) {
11992 Value argVal = i < argc_ ? args_[i] : UndefinedValue();
11993 switch (sig.args()[i].kind()) {
11994 case wasm::ValType::I32:
11995 case wasm::ValType::F32:
11996 case wasm::ValType::F64:
11997 if (!argVal.isNumber() && !argVal.isBoolean() &&
11998 !argVal.isUndefined()) {
11999 return AttachDecision::NoAction;
12000 }
12001 break;
12002 case wasm::ValType::I64:
12003 if (!argVal.isBigInt() && !argVal.isBoolean() && !argVal.isString()) {
12004 return AttachDecision::NoAction;
12005 }
12006 break;
12007 case wasm::ValType::V128:
12008 MOZ_CRASH("Function should not have a Wasm JitEntry");
12009 case wasm::ValType::Ref:
12010 // canHaveJitEntry restricts args to externref, where all JS values are
12011 // valid and can be boxed.
12012 MOZ_ASSERT(sig.args()[i].refType().isExtern(),
12013 "Unexpected type for Wasm JitEntry");
12014 break;
12015 }
12016 }
12017
12018 CallFlags flags(/* isConstructing = */ false, /* isSpread = */ false,
12019 /* isSameRealm = */ true);
12020
12021 // Load argc.
12022 Int32OperandId argcId(writer.setInputOperandId(0));
12023
12024 // Load the callee and ensure it is an object
12025 ValOperandId calleeValId =
12026 writer.loadArgumentFixedSlot(ArgumentKind::Callee, argc_, flags);
12027 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
12028
12029 // Ensure the callee is this Wasm function.
12030 emitCalleeGuard(calleeObjId, calleeFunc);
12031
12032 // Guard the argument types.
12033 uint32_t guardedArgs = std::min<uint32_t>(sig.args().length(), argc_);
12034 for (uint32_t i = 0; i < guardedArgs; i++) {
12035 ArgumentKind argKind = ArgumentKindForArgIndex(i);
12036 ValOperandId argId = writer.loadArgumentFixedSlot(argKind, argc_, flags);
12037 writer.guardWasmArg(argId, sig.args()[i].kind());
12038 }
12039
12040 writer.callWasmFunction(calleeObjId, argcId, flags, ClampFixedArgc(argc_),
12041 &funcExport, inst.object());
12042 writer.returnFromIC();
12043
12044 trackAttached("Call.WasmCall");
12045
12046 return AttachDecision::Attach;
12047 }
12048
12049 AttachDecision CallIRGenerator::tryAttachInlinableNative(HandleFunction callee,
12050 CallFlags flags) {
12051 MOZ_ASSERT(mode_ == ICState::Mode::Specialized);
12052 MOZ_ASSERT(callee->isNativeWithoutJitEntry());
12053 MOZ_ASSERT(flags.getArgFormat() == CallFlags::Standard ||
12054 flags.getArgFormat() == CallFlags::Spread);
12055
12056 InlinableNativeIRGenerator nativeGen(*this, callee, newTarget_, thisval_,
12057 args_, flags);
12058 return nativeGen.tryAttachStub();
12059 }
12060
12061 #ifdef FUZZING_JS_FUZZILLI
12062 AttachDecision InlinableNativeIRGenerator::tryAttachFuzzilliHash() {
12063 if (args_.length() != 1) {
12064 return AttachDecision::NoAction;
12065 }
12066
12067 // Initialize the input operand.
12068 Int32OperandId argcId = initializeInputOperand();
12069
12070 // Guard callee is the 'fuzzilli_hash' native function.
12071 ObjOperandId calleeId = emitNativeCalleeGuard(argcId);
12072
12073 ValOperandId argValId = loadArgument(calleeId, ArgumentKind::Arg0);
12074
12075 writer.fuzzilliHashResult(argValId);
12076 writer.returnFromIC();
12077
12078 trackAttached("FuzzilliHash");
12079 return AttachDecision::Attach;
12080 }
12081 #endif
12082
12083 AttachDecision InlinableNativeIRGenerator::tryAttachStub() {
12084 MOZ_ASSERT(generator_.mode_ == ICState::Mode::Specialized);
12085 MOZ_ASSERT(target_->isNativeWithoutJitEntry());
12086
12087 // Special case functions are only optimized for normal calls.
12088 if (!BytecodeCallOpCanHaveInlinableNative(op())) {
12089 return AttachDecision::NoAction;
12090 }
12091
12092 if (!target_->hasJitInfo() ||
12093 target_->jitInfo()->type() != JSJitInfo::InlinableNative) {
12094 return AttachDecision::NoAction;
12095 }
12096
12097 InlinableNative native = target_->jitInfo()->inlinableNative;
12098
12099 // Not all natives can be inlined cross-realm.
12100 if (cx_->realm() != target_->realm() && !CanInlineNativeCrossRealm(native)) {
12101 return AttachDecision::NoAction;
12102 }
12103
12104 // Check for special-cased native constructors.
12105 if (flags_.isConstructing()) {
12106 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard);
12107
12108 // newTarget must match the callee. CacheIR for this is emitted in
12109 // emitNativeCalleeGuard.
12110 if (ObjectValue(*callee()) != newTarget_) {
12111 return AttachDecision::NoAction;
12112 }
12113 switch (native) {
12114 case InlinableNative::Array:
12115 return tryAttachArrayConstructor();
12116 case InlinableNative::TypedArrayConstructor:
12117 return tryAttachTypedArrayConstructor();
12118 case InlinableNative::MapConstructor:
12119 case InlinableNative::SetConstructor:
12120 return tryAttachMapSetConstructor(native);
12121 case InlinableNative::String:
12122 return tryAttachStringConstructor();
12123 case InlinableNative::Object:
12124 return tryAttachObjectConstructor();
12125 default:
12126 break;
12127 }
12128 return AttachDecision::NoAction;
12129 }
12130
12131 // Check for special-cased native spread calls.
12132 if (flags_.getArgFormat() == CallFlags::Spread ||
12133 flags_.getArgFormat() == CallFlags::FunApplyArray) {
12134 // Can't inline spread calls when bound arguments are present.
12135 MOZ_ASSERT(!hasBoundArguments());
12136
12137 switch (native) {
12138 case InlinableNative::MathMin:
12139 return tryAttachSpreadMathMinMax(/*isMax = */ false);
12140 case InlinableNative::MathMax:
12141 return tryAttachSpreadMathMinMax(/*isMax = */ true);
12142 default:
12143 break;
12144 }
12145 return AttachDecision::NoAction;
12146 }
12147
12148 MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard ||
12149 flags_.getArgFormat() == CallFlags::FunCall ||
12150 flags_.getArgFormat() == CallFlags::FunApplyNullUndefined);
12151
12152 // Check for special-cased native functions.
12153 switch (native) {
12154 // Array natives.
12155 case InlinableNative::Array:
12156 return tryAttachArrayConstructor();
12157 case InlinableNative::ArrayPush:
12158 return tryAttachArrayPush();
12159 case InlinableNative::ArrayPop:
12160 case InlinableNative::ArrayShift:
12161 return tryAttachArrayPopShift(native);
12162 case InlinableNative::ArrayJoin:
12163 return tryAttachArrayJoin();
12164 case InlinableNative::ArraySlice:
12165 return tryAttachArraySlice();
12166 case InlinableNative::ArrayIsArray:
12167 return tryAttachArrayIsArray();
12168
12169 // DataView natives.
12170 case InlinableNative::DataViewGetInt8:
12171 return tryAttachDataViewGet(Scalar::Int8);
12172 case InlinableNative::DataViewGetUint8:
12173 return tryAttachDataViewGet(Scalar::Uint8);
12174 case InlinableNative::DataViewGetInt16:
12175 return tryAttachDataViewGet(Scalar::Int16);
12176 case InlinableNative::DataViewGetUint16:
12177 return tryAttachDataViewGet(Scalar::Uint16);
12178 case InlinableNative::DataViewGetInt32:
12179 return tryAttachDataViewGet(Scalar::Int32);
12180 case InlinableNative::DataViewGetUint32:
12181 return tryAttachDataViewGet(Scalar::Uint32);
12182 case InlinableNative::DataViewGetFloat16:
12183 return tryAttachDataViewGet(Scalar::Float16);
12184 case InlinableNative::DataViewGetFloat32:
12185 return tryAttachDataViewGet(Scalar::Float32);
12186 case InlinableNative::DataViewGetFloat64:
12187 return tryAttachDataViewGet(Scalar::Float64);
12188 case InlinableNative::DataViewGetBigInt64:
12189 return tryAttachDataViewGet(Scalar::BigInt64);
12190 case InlinableNative::DataViewGetBigUint64:
12191 return tryAttachDataViewGet(Scalar::BigUint64);
12192 case InlinableNative::DataViewSetInt8:
12193 return tryAttachDataViewSet(Scalar::Int8);
12194 case InlinableNative::DataViewSetUint8:
12195 return tryAttachDataViewSet(Scalar::Uint8);
12196 case InlinableNative::DataViewSetInt16:
12197 return tryAttachDataViewSet(Scalar::Int16);
12198 case InlinableNative::DataViewSetUint16:
12199 return tryAttachDataViewSet(Scalar::Uint16);
12200 case InlinableNative::DataViewSetInt32:
12201 return tryAttachDataViewSet(Scalar::Int32);
12202 case InlinableNative::DataViewSetUint32:
12203 return tryAttachDataViewSet(Scalar::Uint32);
12204 case InlinableNative::DataViewSetFloat16:
12205 return tryAttachDataViewSet(Scalar::Float16);
12206 case InlinableNative::DataViewSetFloat32:
12207 return tryAttachDataViewSet(Scalar::Float32);
12208 case InlinableNative::DataViewSetFloat64:
12209 return tryAttachDataViewSet(Scalar::Float64);
12210 case InlinableNative::DataViewSetBigInt64:
12211 return tryAttachDataViewSet(Scalar::BigInt64);
12212 case InlinableNative::DataViewSetBigUint64:
12213 return tryAttachDataViewSet(Scalar::BigUint64);
12214
12215 // Function natives.
12216 case InlinableNative::FunctionBind:
12217 return tryAttachFunctionBind();
12218
12219 // Intl natives.
12220 case InlinableNative::IntlGuardToCollator:
12221 case InlinableNative::IntlGuardToDateTimeFormat:
12222 case InlinableNative::IntlGuardToDisplayNames:
12223 case InlinableNative::IntlGuardToDurationFormat:
12224 case InlinableNative::IntlGuardToListFormat:
12225 case InlinableNative::IntlGuardToNumberFormat:
12226 case InlinableNative::IntlGuardToPluralRules:
12227 case InlinableNative::IntlGuardToRelativeTimeFormat:
12228 case InlinableNative::IntlGuardToSegmenter:
12229 case InlinableNative::IntlGuardToSegments:
12230 case InlinableNative::IntlGuardToSegmentIterator:
12231 return tryAttachGuardToClass(native);
12232
12233 // Slot intrinsics.
12234 case InlinableNative::IntrinsicUnsafeGetReservedSlot:
12235 case InlinableNative::IntrinsicUnsafeGetObjectFromReservedSlot:
12236 case InlinableNative::IntrinsicUnsafeGetInt32FromReservedSlot:
12237 case InlinableNative::IntrinsicUnsafeGetStringFromReservedSlot:
12238 return tryAttachUnsafeGetReservedSlot(native);
12239 case InlinableNative::IntrinsicUnsafeSetReservedSlot:
12240 return tryAttachUnsafeSetReservedSlot();
12241
12242 // Intrinsics.
12243 case InlinableNative::IntrinsicIsSuspendedGenerator:
12244 return tryAttachIsSuspendedGenerator();
12245 case InlinableNative::IntrinsicToObject:
12246 return tryAttachToObject();
12247 case InlinableNative::IntrinsicToInteger:
12248 return tryAttachToInteger();
12249 case InlinableNative::IntrinsicToLength:
12250 return tryAttachToLength();
12251 case InlinableNative::IntrinsicIsObject:
12252 return tryAttachIsObject();
12253 case InlinableNative::IntrinsicIsPackedArray:
12254 return tryAttachIsPackedArray();
12255 case InlinableNative::IntrinsicIsCallable:
12256 return tryAttachIsCallable();
12257 case InlinableNative::IntrinsicIsConstructor:
12258 return tryAttachIsConstructor();
12259 case InlinableNative::IntrinsicIsCrossRealmArrayConstructor:
12260 return tryAttachIsCrossRealmArrayConstructor();
12261 case InlinableNative::IntrinsicCanOptimizeArraySpecies:
12262 return tryAttachCanOptimizeArraySpecies();
12263 case InlinableNative::IntrinsicCanOptimizeStringProtoSymbolLookup:
12264 return tryAttachCanOptimizeStringProtoSymbolLookup();
12265 case InlinableNative::IntrinsicGuardToArrayIterator:
12266 case InlinableNative::IntrinsicGuardToMapIterator:
12267 case InlinableNative::IntrinsicGuardToSetIterator:
12268 case InlinableNative::IntrinsicGuardToStringIterator:
12269 case InlinableNative::IntrinsicGuardToRegExpStringIterator:
12270 case InlinableNative::IntrinsicGuardToWrapForValidIterator:
12271 case InlinableNative::IntrinsicGuardToIteratorHelper:
12272 #ifdef NIGHTLY_BUILD
12273 case InlinableNative::IntrinsicGuardToIteratorRange:
12274 #endif
12275 case InlinableNative::IntrinsicGuardToAsyncIteratorHelper:
12276 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
12277 case InlinableNative::IntrinsicGuardToAsyncDisposableStack:
12278 case InlinableNative::IntrinsicGuardToDisposableStack:
12279 #endif
12280 return tryAttachGuardToClass(native);
12281 case InlinableNative::IntrinsicSubstringKernel:
12282 return tryAttachSubstringKernel();
12283 case InlinableNative::IntrinsicIsConstructing:
12284 return tryAttachIsConstructing();
12285 case InlinableNative::IntrinsicNewArrayIterator:
12286 return tryAttachNewArrayIterator();
12287 case InlinableNative::IntrinsicNewStringIterator:
12288 return tryAttachNewStringIterator();
12289 case InlinableNative::IntrinsicNewRegExpStringIterator:
12290 return tryAttachNewRegExpStringIterator();
12291 case InlinableNative::IntrinsicArrayIteratorPrototypeOptimizable:
12292 return tryAttachArrayIteratorPrototypeOptimizable();
12293
12294 // RegExp natives.
12295 case InlinableNative::IsRegExpObject:
12296 return tryAttachHasClass(&RegExpObject::class_,
12297 /* isPossiblyWrapped = */ false);
12298 case InlinableNative::IsPossiblyWrappedRegExpObject:
12299 return tryAttachHasClass(&RegExpObject::class_,
12300 /* isPossiblyWrapped = */ true);
12301 case InlinableNative::RegExpMatcher:
12302 case InlinableNative::RegExpSearcher:
12303 return tryAttachRegExpMatcherSearcher(native);
12304 case InlinableNative::RegExpSearcherLastLimit:
12305 return tryAttachRegExpSearcherLastLimit();
12306 case InlinableNative::RegExpHasCaptureGroups:
12307 return tryAttachRegExpHasCaptureGroups();
12308 case InlinableNative::IsRegExpPrototypeOptimizable:
12309 return tryAttachIsRegExpPrototypeOptimizable();
12310 case InlinableNative::IsOptimizableRegExpObject:
12311 return tryAttachIsOptimizableRegExpObject();
12312 case InlinableNative::GetFirstDollarIndex:
12313 return tryAttachGetFirstDollarIndex();
12314 case InlinableNative::IntrinsicRegExpBuiltinExec:
12315 case InlinableNative::IntrinsicRegExpBuiltinExecForTest:
12316 return tryAttachIntrinsicRegExpBuiltinExec(native);
12317 case InlinableNative::IntrinsicRegExpExec:
12318 case InlinableNative::IntrinsicRegExpExecForTest:
12319 return tryAttachIntrinsicRegExpExec(native);
12320
12321 // String natives.
12322 case InlinableNative::String:
12323 return tryAttachString();
12324 case InlinableNative::StringToString:
12325 case InlinableNative::StringValueOf:
12326 return tryAttachStringToStringValueOf();
12327 case InlinableNative::StringCharCodeAt:
12328 return tryAttachStringCharCodeAt();
12329 case InlinableNative::StringCodePointAt:
12330 return tryAttachStringCodePointAt();
12331 case InlinableNative::StringCharAt:
12332 return tryAttachStringCharAt();
12333 case InlinableNative::StringAt:
12334 return tryAttachStringAt();
12335 case InlinableNative::StringFromCharCode:
12336 return tryAttachStringFromCharCode();
12337 case InlinableNative::StringFromCodePoint:
12338 return tryAttachStringFromCodePoint();
12339 case InlinableNative::StringIncludes:
12340 return tryAttachStringIncludes();
12341 case InlinableNative::StringIndexOf:
12342 return tryAttachStringIndexOf();
12343 case InlinableNative::StringLastIndexOf:
12344 return tryAttachStringLastIndexOf();
12345 case InlinableNative::StringStartsWith:
12346 return tryAttachStringStartsWith();
12347 case InlinableNative::StringEndsWith:
12348 return tryAttachStringEndsWith();
12349 case InlinableNative::StringToLowerCase:
12350 return tryAttachStringToLowerCase();
12351 case InlinableNative::StringToUpperCase:
12352 return tryAttachStringToUpperCase();
12353 case InlinableNative::StringTrim:
12354 return tryAttachStringTrim();
12355 case InlinableNative::StringTrimStart:
12356 return tryAttachStringTrimStart();
12357 case InlinableNative::StringTrimEnd:
12358 return tryAttachStringTrimEnd();
12359 case InlinableNative::IntrinsicStringReplaceString:
12360 return tryAttachStringReplaceString();
12361 case InlinableNative::IntrinsicStringSplitString:
12362 return tryAttachStringSplitString();
12363
12364 // Math natives.
12365 case InlinableNative::MathRandom:
12366 return tryAttachMathRandom();
12367 case InlinableNative::MathAbs:
12368 return tryAttachMathAbs();
12369 case InlinableNative::MathClz32:
12370 return tryAttachMathClz32();
12371 case InlinableNative::MathSign:
12372 return tryAttachMathSign();
12373 case InlinableNative::MathImul:
12374 return tryAttachMathImul();
12375 case InlinableNative::MathFloor:
12376 return tryAttachMathFloor();
12377 case InlinableNative::MathCeil:
12378 return tryAttachMathCeil();
12379 case InlinableNative::MathTrunc:
12380 return tryAttachMathTrunc();
12381 case InlinableNative::MathRound:
12382 return tryAttachMathRound();
12383 case InlinableNative::MathSqrt:
12384 return tryAttachMathSqrt();
12385 case InlinableNative::MathFRound:
12386 return tryAttachMathFRound();
12387 case InlinableNative::MathF16Round:
12388 return tryAttachMathF16Round();
12389 case InlinableNative::MathHypot:
12390 return tryAttachMathHypot();
12391 case InlinableNative::MathATan2:
12392 return tryAttachMathATan2();
12393 case InlinableNative::MathSin:
12394 return tryAttachMathFunction(UnaryMathFunction::SinNative);
12395 case InlinableNative::MathTan:
12396 return tryAttachMathFunction(UnaryMathFunction::TanNative);
12397 case InlinableNative::MathCos:
12398 return tryAttachMathFunction(UnaryMathFunction::CosNative);
12399 case InlinableNative::MathExp:
12400 return tryAttachMathFunction(UnaryMathFunction::Exp);
12401 case InlinableNative::MathLog:
12402 return tryAttachMathFunction(UnaryMathFunction::Log);
12403 case InlinableNative::MathASin:
12404 return tryAttachMathFunction(UnaryMathFunction::ASin);
12405 case InlinableNative::MathATan:
12406 return tryAttachMathFunction(UnaryMathFunction::ATan);
12407 case InlinableNative::MathACos:
12408 return tryAttachMathFunction(UnaryMathFunction::ACos);
12409 case InlinableNative::MathLog10:
12410 return tryAttachMathFunction(UnaryMathFunction::Log10);
12411 case InlinableNative::MathLog2:
12412 return tryAttachMathFunction(UnaryMathFunction::Log2);
12413 case InlinableNative::MathLog1P:
12414 return tryAttachMathFunction(UnaryMathFunction::Log1P);
12415 case InlinableNative::MathExpM1:
12416 return tryAttachMathFunction(UnaryMathFunction::ExpM1);
12417 case InlinableNative::MathCosH:
12418 return tryAttachMathFunction(UnaryMathFunction::CosH);
12419 case InlinableNative::MathSinH:
12420 return tryAttachMathFunction(UnaryMathFunction::SinH);
12421 case InlinableNative::MathTanH:
12422 return tryAttachMathFunction(UnaryMathFunction::TanH);
12423 case InlinableNative::MathACosH:
12424 return tryAttachMathFunction(UnaryMathFunction::ACosH);
12425 case InlinableNative::MathASinH:
12426 return tryAttachMathFunction(UnaryMathFunction::ASinH);
12427 case InlinableNative::MathATanH:
12428 return tryAttachMathFunction(UnaryMathFunction::ATanH);
12429 case InlinableNative::MathCbrt:
12430 return tryAttachMathFunction(UnaryMathFunction::Cbrt);
12431 case InlinableNative::MathPow:
12432 return tryAttachMathPow();
12433 case InlinableNative::MathMin:
12434 return tryAttachMathMinMax(/* isMax = */ false);
12435 case InlinableNative::MathMax:
12436 return tryAttachMathMinMax(/* isMax = */ true);
12437
12438 // Map intrinsics.
12439 case InlinableNative::IntrinsicGuardToMapObject:
12440 return tryAttachGuardToClass(GuardClassKind::Map);
12441 case InlinableNative::IntrinsicGetNextMapEntryForIterator:
12442 return tryAttachGetNextMapSetEntryForIterator(/* isMap = */ true);
12443
12444 // Number natives.
12445 case InlinableNative::Number:
12446 return tryAttachNumber();
12447 case InlinableNative::NumberParseInt:
12448 return tryAttachNumberParseInt();
12449 case InlinableNative::NumberToString:
12450 return tryAttachNumberToString();
12451
12452 // Object natives.
12453 case InlinableNative::Object:
12454 return tryAttachObjectConstructor();
12455 case InlinableNative::ObjectCreate:
12456 return tryAttachObjectCreate();
12457 case InlinableNative::ObjectIs:
12458 return tryAttachObjectIs();
12459 case InlinableNative::ObjectIsPrototypeOf:
12460 return tryAttachObjectIsPrototypeOf();
12461 case InlinableNative::ObjectKeys:
12462 return tryAttachObjectKeys();
12463 case InlinableNative::ObjectToString:
12464 return tryAttachObjectToString();
12465
12466 // Set intrinsics.
12467 case InlinableNative::IntrinsicGuardToSetObject:
12468 return tryAttachGuardToClass(GuardClassKind::Set);
12469 case InlinableNative::IntrinsicGetNextSetEntryForIterator:
12470 return tryAttachGetNextMapSetEntryForIterator(/* isMap = */ false);
12471
12472 // ArrayBuffer intrinsics.
12473 case InlinableNative::IntrinsicGuardToArrayBuffer:
12474 return tryAttachGuardToArrayBuffer();
12475
12476 // SharedArrayBuffer intrinsics.
12477 case InlinableNative::IntrinsicGuardToSharedArrayBuffer:
12478 return tryAttachGuardToSharedArrayBuffer();
12479
12480 // TypedArray intrinsics.
12481 case InlinableNative::TypedArrayConstructor:
12482 return AttachDecision::NoAction; // Not callable.
12483 case InlinableNative::IntrinsicIsTypedArray:
12484 return tryAttachIsTypedArray(/* isPossiblyWrapped = */ false);
12485 case InlinableNative::IntrinsicIsPossiblyWrappedTypedArray:
12486 return tryAttachIsTypedArray(/* isPossiblyWrapped = */ true);
12487 case InlinableNative::IntrinsicIsTypedArrayConstructor:
12488 return tryAttachIsTypedArrayConstructor();
12489 case InlinableNative::IntrinsicTypedArrayByteOffset:
12490 return tryAttachTypedArrayByteOffset();
12491 case InlinableNative::IntrinsicTypedArrayElementSize:
12492 return tryAttachTypedArrayElementSize();
12493 case InlinableNative::IntrinsicTypedArrayLength:
12494 return tryAttachTypedArrayLength(/* isPossiblyWrapped = */ false,
12495 /* allowOutOfBounds = */ false);
12496 case InlinableNative::IntrinsicTypedArrayLengthZeroOnOutOfBounds:
12497 return tryAttachTypedArrayLength(/* isPossiblyWrapped = */ false,
12498 /* allowOutOfBounds = */ true);
12499 case InlinableNative::IntrinsicPossiblyWrappedTypedArrayLength:
12500 return tryAttachTypedArrayLength(/* isPossiblyWrapped = */ true,
12501 /* allowOutOfBounds = */ false);
12502
12503 // Reflect natives.
12504 case InlinableNative::ReflectGetPrototypeOf:
12505 return tryAttachReflectGetPrototypeOf();
12506
12507 // Atomics intrinsics:
12508 case InlinableNative::AtomicsCompareExchange:
12509 return tryAttachAtomicsCompareExchange();
12510 case InlinableNative::AtomicsExchange:
12511 return tryAttachAtomicsExchange();
12512 case InlinableNative::AtomicsAdd:
12513 return tryAttachAtomicsAdd();
12514 case InlinableNative::AtomicsSub:
12515 return tryAttachAtomicsSub();
12516 case InlinableNative::AtomicsAnd:
12517 return tryAttachAtomicsAnd();
12518 case InlinableNative::AtomicsOr:
12519 return tryAttachAtomicsOr();
12520 case InlinableNative::AtomicsXor:
12521 return tryAttachAtomicsXor();
12522 case InlinableNative::AtomicsLoad:
12523 return tryAttachAtomicsLoad();
12524 case InlinableNative::AtomicsStore:
12525 return tryAttachAtomicsStore();
12526 case InlinableNative::AtomicsIsLockFree:
12527 return tryAttachAtomicsIsLockFree();
12528 case InlinableNative::AtomicsPause:
12529 return tryAttachAtomicsPause();
12530
12531 // BigInt natives.
12532 case InlinableNative::BigInt:
12533 return tryAttachBigInt();
12534 case InlinableNative::BigIntAsIntN:
12535 return tryAttachBigIntAsIntN();
12536 case InlinableNative::BigIntAsUintN:
12537 return tryAttachBigIntAsUintN();
12538
12539 // Boolean natives.
12540 case InlinableNative::Boolean:
12541 return tryAttachBoolean();
12542
12543 // Set natives.
12544 case InlinableNative::SetConstructor:
12545 return AttachDecision::NoAction; // Not callable.
12546 case InlinableNative::SetHas:
12547 return tryAttachSetHas();
12548 case InlinableNative::SetDelete:
12549 return tryAttachSetDelete();
12550 case InlinableNative::SetAdd:
12551 return tryAttachSetAdd();
12552 case InlinableNative::SetSize:
12553 return tryAttachSetSize();
12554
12555 // Map natives.
12556 case InlinableNative::MapConstructor:
12557 return AttachDecision::NoAction; // Not callable.
12558 case InlinableNative::MapHas:
12559 return tryAttachMapHas();
12560 case InlinableNative::MapGet:
12561 return tryAttachMapGet();
12562 case InlinableNative::MapDelete:
12563 return tryAttachMapDelete();
12564 case InlinableNative::MapSet:
12565 return tryAttachMapSet();
12566
12567 // Date natives and intrinsics.
12568 case InlinableNative::DateGetTime:
12569 case InlinableNative::IntrinsicThisTimeValue:
12570 return tryAttachDateGetTime(native);
12571 case InlinableNative::DateGetFullYear:
12572 return tryAttachDateGet(DateComponent::FullYear);
12573 case InlinableNative::DateGetMonth:
12574 return tryAttachDateGet(DateComponent::Month);
12575 case InlinableNative::DateGetDate:
12576 return tryAttachDateGet(DateComponent::Date);
12577 case InlinableNative::DateGetDay:
12578 return tryAttachDateGet(DateComponent::Day);
12579 case InlinableNative::DateGetHours:
12580 return tryAttachDateGet(DateComponent::Hours);
12581 case InlinableNative::DateGetMinutes:
12582 return tryAttachDateGet(DateComponent::Minutes);
12583 case InlinableNative::DateGetSeconds:
12584 return tryAttachDateGet(DateComponent::Seconds);
12585
12586 // Testing functions.
12587 case InlinableNative::TestBailout:
12588 if (js::SupportDifferentialTesting()) {
12589 return AttachDecision::NoAction;
12590 }
12591 return tryAttachBailout();
12592 case InlinableNative::TestAssertFloat32:
12593 return tryAttachAssertFloat32();
12594 case InlinableNative::TestAssertRecoveredOnBailout:
12595 if (js::SupportDifferentialTesting()) {
12596 return AttachDecision::NoAction;
12597 }
12598 return tryAttachAssertRecoveredOnBailout();
12599
12600 #ifdef FUZZING_JS_FUZZILLI
12601 // Fuzzilli function
12602 case InlinableNative::FuzzilliHash:
12603 return tryAttachFuzzilliHash();
12604 #endif
12605
12606 case InlinableNative::Limit:
12607 break;
12608 }
12609
12610 MOZ_CRASH("Shouldn't get here");
12611 }
12612
12613 // Remember the shape of the this object for any script being called as a
12614 // constructor, for later use during Ion compilation.
12615 ScriptedThisResult CallIRGenerator::getThisShapeForScripted(
12616 HandleFunction calleeFunc, Handle<JSObject*> newTarget,
12617 MutableHandle<Shape*> result) {
12618 // Some constructors allocate their own |this| object.
12619 if (calleeFunc->constructorNeedsUninitializedThis()) {
12620 return ScriptedThisResult::UninitializedThis;
12621 }
12622
12623 // Only attach a stub if the newTarget is a function with a
12624 // nonconfigurable prototype.
12625 if (!newTarget->is<JSFunction>() ||
12626 !newTarget->as<JSFunction>().hasNonConfigurablePrototypeDataProperty()) {
12627 return ScriptedThisResult::NoAction;
12628 }
12629
12630 AutoRealm ar(cx_, calleeFunc);
12631 Shape* thisShape = ThisShapeForFunction(cx_, calleeFunc, newTarget);
12632 if (!thisShape) {
12633 cx_->clearPendingException();
12634 return ScriptedThisResult::NoAction;
12635 }
12636
12637 MOZ_ASSERT(thisShape->realm() == calleeFunc->realm());
12638 result.set(thisShape);
12639 return ScriptedThisResult::PlainObjectShape;
12640 }
12641
12642 static bool CanOptimizeScriptedCall(JSFunction* callee, bool isConstructing) {
12643 if (!callee->hasJitEntry()) {
12644 return false;
12645 }
12646
12647 // If callee is not an interpreted constructor, we have to throw.
12648 if (isConstructing && !callee->isConstructor()) {
12649 return false;
12650 }
12651
12652 // Likewise, if the callee is a class constructor, we have to throw.
12653 if (!isConstructing && callee->isClassConstructor()) {
12654 return false;
12655 }
12656
12657 return true;
12658 }
12659
12660 void CallIRGenerator::emitCallScriptedGuards(ObjOperandId calleeObjId,
12661 JSFunction* calleeFunc,
12662 Int32OperandId argcId,
12663 CallFlags flags, Shape* thisShape,
12664 bool isBoundFunction) {
12665 bool isConstructing = flags.isConstructing();
12666
12667 if (mode_ == ICState::Mode::Specialized) {
12668 MOZ_ASSERT_IF(isConstructing, thisShape || flags.needsUninitializedThis());
12669
12670 // Ensure callee matches this stub's callee
12671 emitCalleeGuard(calleeObjId, calleeFunc);
12672 if (thisShape) {
12673 // Emit guards to ensure the newTarget's .prototype property is what we
12674 // expect. Note that getThisForScripted checked newTarget is a function
12675 // with a non-configurable .prototype data property.
12676
12677 JSFunction* newTarget;
12678 ObjOperandId newTargetObjId;
12679 if (isBoundFunction) {
12680 newTarget = calleeFunc;
12681 newTargetObjId = calleeObjId;
12682 } else {
12683 newTarget = &newTarget_.toObject().as<JSFunction>();
12684 ValOperandId newTargetValId = writer.loadArgumentDynamicSlot(
12685 ArgumentKind::NewTarget, argcId, flags);
12686 newTargetObjId = writer.guardToObject(newTargetValId);
12687 }
12688
12689 Maybe<PropertyInfo> prop = newTarget->lookupPure(cx_->names().prototype);
12690 MOZ_ASSERT(prop.isSome());
12691 uint32_t slot = prop->slot();
12692 MOZ_ASSERT(slot >= newTarget->numFixedSlots(),
12693 "Stub code relies on this");
12694
12695 writer.guardShape(newTargetObjId, newTarget->shape());
12696
12697 const Value& value = newTarget->getSlot(slot);
12698 if (value.isObject()) {
12699 JSObject* prototypeObject = &value.toObject();
12700
12701 ObjOperandId protoId = writer.loadObject(prototypeObject);
12702 writer.guardDynamicSlotIsSpecificObject(
12703 newTargetObjId, protoId, slot - newTarget->numFixedSlots());
12704 } else {
12705 writer.guardDynamicSlotIsNotObject(newTargetObjId,
12706 slot - newTarget->numFixedSlots());
12707 }
12708
12709 // Call metaScriptedThisShape before emitting the call, so that Warp can
12710 // use the shape to create the |this| object before transpiling the call.
12711 writer.metaScriptedThisShape(thisShape);
12712 }
12713 } else {
12714 // Guard that object is a scripted function
12715 writer.guardClass(calleeObjId, GuardClassKind::JSFunction);
12716 writer.guardFunctionHasJitEntry(calleeObjId);
12717
12718 if (isConstructing) {
12719 // If callee is not a constructor, we have to throw.
12720 writer.guardFunctionIsConstructor(calleeObjId);
12721 } else {
12722 // If callee is a class constructor, we have to throw.
12723 writer.guardNotClassConstructor(calleeObjId);
12724 }
12725 }
12726 }
12727
12728 AttachDecision CallIRGenerator::tryAttachCallScripted(
12729 HandleFunction calleeFunc) {
12730 MOZ_ASSERT(calleeFunc->hasJitEntry());
12731
12732 if (calleeFunc->isWasmWithJitEntry()) {
12733 TRY_ATTACH(tryAttachWasmCall(calleeFunc));
12734 }
12735
12736 bool isSpecialized = mode_ == ICState::Mode::Specialized;
12737
12738 bool isConstructing = IsConstructPC(pc_);
12739 bool isSpread = IsSpreadPC(pc_);
12740 bool isSameRealm = isSpecialized && cx_->realm() == calleeFunc->realm();
12741 CallFlags flags(isConstructing, isSpread, isSameRealm);
12742
12743 if (!CanOptimizeScriptedCall(calleeFunc, isConstructing)) {
12744 return AttachDecision::NoAction;
12745 }
12746
12747 if (isConstructing && !calleeFunc->hasJitScript()) {
12748 // If we're constructing, require the callee to have a JitScript. This isn't
12749 // required for correctness but avoids allocating a template object below
12750 // for constructors that aren't hot. See bug 1419758.
12751 return AttachDecision::TemporarilyUnoptimizable;
12752 }
12753
12754 // Verify that spread calls have a reasonable number of arguments.
12755 if (isSpread && args_.length() > JIT_ARGS_LENGTH_MAX) {
12756 return AttachDecision::NoAction;
12757 }
12758
12759 Rooted<Shape*> thisShape(cx_);
12760 if (isConstructing && isSpecialized) {
12761 Rooted<JSObject*> newTarget(cx_, &newTarget_.toObject());
12762 switch (getThisShapeForScripted(calleeFunc, newTarget, &thisShape)) {
12763 case ScriptedThisResult::PlainObjectShape:
12764 break;
12765 case ScriptedThisResult::UninitializedThis:
12766 flags.setNeedsUninitializedThis();
12767 break;
12768 case ScriptedThisResult::NoAction:
12769 return AttachDecision::NoAction;
12770 }
12771 }
12772
12773 // Load argc.
12774 Int32OperandId argcId(writer.setInputOperandId(0));
12775
12776 // Load the callee and ensure it is an object
12777 ValOperandId calleeValId =
12778 writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
12779 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
12780
12781 emitCallScriptedGuards(calleeObjId, calleeFunc, argcId, flags, thisShape,
12782 /* isBoundFunction = */ false);
12783
12784 writer.callScriptedFunction(calleeObjId, argcId, flags,
12785 ClampFixedArgc(argc_));
12786 writer.returnFromIC();
12787
12788 if (isSpecialized) {
12789 trackAttached("Call.CallScripted");
12790 } else {
12791 trackAttached("Call.CallAnyScripted");
12792 }
12793
12794 return AttachDecision::Attach;
12795 }
12796
12797 AttachDecision CallIRGenerator::tryAttachCallNative(HandleFunction calleeFunc) {
12798 MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());
12799
12800 bool isSpecialized = mode_ == ICState::Mode::Specialized;
12801
12802 bool isSpread = IsSpreadPC(pc_);
12803 bool isSameRealm = isSpecialized && cx_->realm() == calleeFunc->realm();
12804 bool isConstructing = IsConstructPC(pc_);
12805 CallFlags flags(isConstructing, isSpread, isSameRealm);
12806
12807 if (isConstructing && !calleeFunc->isConstructor()) {
12808 return AttachDecision::NoAction;
12809 }
12810
12811 // Verify that spread calls have a reasonable number of arguments.
12812 if (isSpread && args_.length() > JIT_ARGS_LENGTH_MAX) {
12813 return AttachDecision::NoAction;
12814 }
12815
12816 // Check for specific native-function optimizations.
12817 if (isSpecialized) {
12818 TRY_ATTACH(tryAttachInlinableNative(calleeFunc, flags));
12819 }
12820
12821 // Load argc.
12822 Int32OperandId argcId(writer.setInputOperandId(0));
12823
12824 // Load the callee and ensure it is an object
12825 ValOperandId calleeValId =
12826 writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
12827 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
12828
12829 // DOM calls need an additional guard so only try optimizing the first stub.
12830 // Can only optimize normal (non-spread) calls.
12831 if (isFirstStub_ && !isSpread && thisval_.isObject() &&
12832 CanAttachDOMCall(cx_, JSJitInfo::Method, &thisval_.toObject(), calleeFunc,
12833 mode_)) {
12834 MOZ_ASSERT(!isConstructing, "DOM functions are not constructors");
12835
12836 gc::AllocSite* allocSite = nullptr;
12837 if (calleeFunc->jitInfo()->returnType() == JSVAL_TYPE_OBJECT &&
12838 JS::Prefs::dom_alloc_site()) {
12839 allocSite = maybeCreateAllocSite();
12840 if (!allocSite) {
12841 return AttachDecision::NoAction;
12842 }
12843 }
12844
12845 // Guard that |this| is an object.
12846 ValOperandId thisValId =
12847 writer.loadArgumentDynamicSlot(ArgumentKind::This, argcId, flags);
12848 ObjOperandId thisObjId = writer.guardToObject(thisValId);
12849
12850 // Guard on the |this| shape to make sure it's the right instance. This also
12851 // ensures DOM_OBJECT_SLOT is stored in a fixed slot. See CanAttachDOMCall.
12852 writer.guardShape(thisObjId, thisval_.toObject().shape());
12853
12854 // Ensure callee matches this stub's callee
12855 writer.guardSpecificFunction(calleeObjId, calleeFunc);
12856
12857 if (allocSite) {
12858 writer.callDOMFunctionWithAllocSite(calleeObjId, argcId, thisObjId,
12859 calleeFunc, flags,
12860 ClampFixedArgc(argc_), allocSite);
12861 } else {
12862 writer.callDOMFunction(calleeObjId, argcId, thisObjId, calleeFunc, flags,
12863 ClampFixedArgc(argc_));
12864 }
12865
12866 trackAttached("Call.CallDOM");
12867 } else if (isSpecialized) {
12868 // Ensure callee matches this stub's callee
12869 writer.guardSpecificFunction(calleeObjId, calleeFunc);
12870 writer.callNativeFunction(calleeObjId, argcId, op_, calleeFunc, flags,
12871 ClampFixedArgc(argc_));
12872
12873 trackAttached("Call.CallNative");
12874 } else {
12875 // Guard that object is a native function
12876 writer.guardClass(calleeObjId, GuardClassKind::JSFunction);
12877 writer.guardFunctionHasNoJitEntry(calleeObjId);
12878
12879 if (isConstructing) {
12880 // If callee is not a constructor, we have to throw.
12881 writer.guardFunctionIsConstructor(calleeObjId);
12882 } else {
12883 // If callee is a class constructor, we have to throw.
12884 writer.guardNotClassConstructor(calleeObjId);
12885 }
12886 writer.callAnyNativeFunction(calleeObjId, argcId, flags,
12887 ClampFixedArgc(argc_));
12888
12889 trackAttached("Call.CallAnyNative");
12890 }
12891
12892 writer.returnFromIC();
12893
12894 return AttachDecision::Attach;
12895 }
12896
12897 AttachDecision CallIRGenerator::tryAttachCallHook(HandleObject calleeObj) {
12898 if (mode_ != ICState::Mode::Specialized) {
12899 // We do not have megamorphic call hook stubs.
12900 // TODO: Should we attach specialized call hook stubs in
12901 // megamorphic mode to avoid going generic?
12902 return AttachDecision::NoAction;
12903 }
12904
12905 bool isSpread = IsSpreadPC(pc_);
12906 bool isConstructing = IsConstructPC(pc_);
12907 CallFlags flags(isConstructing, isSpread);
12908 JSNative hook =
12909 isConstructing ? calleeObj->constructHook() : calleeObj->callHook();
12910 if (!hook) {
12911 return AttachDecision::NoAction;
12912 }
12913
12914 // Bound functions have a JSClass construct hook but are not always
12915 // constructors.
12916 if (isConstructing && !calleeObj->isConstructor()) {
12917 return AttachDecision::NoAction;
12918 }
12919
12920 // We don't support spread calls in the transpiler yet.
12921 if (isSpread) {
12922 return AttachDecision::NoAction;
12923 }
12924
12925 // Load argc.
12926 Int32OperandId argcId(writer.setInputOperandId(0));
12927
12928 // Load the callee and ensure it is an object
12929 ValOperandId calleeValId =
12930 writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
12931 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
12932
12933 // Ensure the callee's class matches the one in this stub.
12934 writer.guardAnyClass(calleeObjId, calleeObj->getClass());
12935
12936 if (isConstructing && calleeObj->is<BoundFunctionObject>()) {
12937 writer.guardBoundFunctionIsConstructor(calleeObjId);
12938 }
12939
12940 writer.callClassHook(calleeObjId, argcId, hook, flags, ClampFixedArgc(argc_));
12941 writer.returnFromIC();
12942
12943 trackAttached("Call.CallHook");
12944
12945 return AttachDecision::Attach;
12946 }
12947
12948 AttachDecision CallIRGenerator::tryAttachBoundFunction(
12949 Handle<BoundFunctionObject*> calleeObj) {
12950 // The target must be a JSFunction with a JitEntry.
12951 if (!calleeObj->getTarget()->is<JSFunction>()) {
12952 return AttachDecision::NoAction;
12953 }
12954
12955 bool isSpread = IsSpreadPC(pc_);
12956 bool isConstructing = IsConstructPC(pc_);
12957
12958 // Spread calls are not supported yet.
12959 if (isSpread) {
12960 return AttachDecision::NoAction;
12961 }
12962
12963 Rooted<JSFunction*> target(cx_, &calleeObj->getTarget()->as<JSFunction>());
12964 if (!CanOptimizeScriptedCall(target, isConstructing)) {
12965 return AttachDecision::NoAction;
12966 }
12967
12968 // Limit the number of bound arguments to prevent us from compiling many
12969 // different stubs (we bake in numBoundArgs and it's usually very small).
12970 static constexpr size_t MaxBoundArgs = 10;
12971 size_t numBoundArgs = calleeObj->numBoundArgs();
12972 if (numBoundArgs > MaxBoundArgs) {
12973 return AttachDecision::NoAction;
12974 }
12975
12976 // Ensure we don't exceed JIT_ARGS_LENGTH_MAX.
12977 if (numBoundArgs + argc_ > JIT_ARGS_LENGTH_MAX) {
12978 return AttachDecision::NoAction;
12979 }
12980
12981 CallFlags flags(isConstructing, isSpread);
12982
12983 if (mode_ == ICState::Mode::Specialized) {
12984 if (cx_->realm() == target->realm()) {
12985 flags.setIsSameRealm();
12986 }
12987 }
12988
12989 Rooted<Shape*> thisShape(cx_);
12990 if (isConstructing) {
12991 // Only optimize if newTarget == callee. This is the common case and ensures
12992 // we can always pass the bound function's target as newTarget.
12993 if (newTarget_ != ObjectValue(*calleeObj)) {
12994 return AttachDecision::NoAction;
12995 }
12996
12997 if (mode_ == ICState::Mode::Specialized) {
12998 Handle<JSFunction*> newTarget = target;
12999 switch (getThisShapeForScripted(target, newTarget, &thisShape)) {
13000 case ScriptedThisResult::PlainObjectShape:
13001 break;
13002 case ScriptedThisResult::UninitializedThis:
13003 flags.setNeedsUninitializedThis();
13004 break;
13005 case ScriptedThisResult::NoAction:
13006 return AttachDecision::NoAction;
13007 }
13008 }
13009 }
13010
13011 // Load argc.
13012 Int32OperandId argcId(writer.setInputOperandId(0));
13013
13014 // Load the callee and ensure it's a bound function.
13015 ValOperandId calleeValId =
13016 writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
13017 ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
13018 writer.guardClass(calleeObjId, GuardClassKind::BoundFunction);
13019
13020 // Ensure numBoundArgs matches.
13021 Int32OperandId numBoundArgsId = writer.loadBoundFunctionNumArgs(calleeObjId);
13022 writer.guardSpecificInt32(numBoundArgsId, numBoundArgs);
13023
13024 if (isConstructing) {
13025 // Guard newTarget == callee. We depend on this in CallBoundScriptedFunction
13026 // and in emitCallScriptedGuards by using boundTarget as newTarget.
13027 ValOperandId newTargetValId =
13028 writer.loadArgumentDynamicSlot(ArgumentKind::NewTarget, argcId, flags);
13029 ObjOperandId newTargetObjId = writer.guardToObject(newTargetValId);
13030 writer.guardObjectIdentity(newTargetObjId, calleeObjId);
13031 }
13032
13033 ObjOperandId targetId = writer.loadBoundFunctionTarget(calleeObjId);
13034
13035 emitCallScriptedGuards(targetId, target, argcId, flags, thisShape,
13036 /* isBoundFunction = */ true);
13037
13038 writer.callBoundScriptedFunction(calleeObjId, targetId, argcId, flags,
13039 numBoundArgs);
13040 writer.returnFromIC();
13041
13042 trackAttached("Call.BoundFunction");
13043 return AttachDecision::Attach;
13044 }
13045
13046 AttachDecision CallIRGenerator::tryAttachBoundNative(
13047 Handle<BoundFunctionObject*> calleeObj) {
13048 // The target must be a native JSFunction without a JitEntry.
13049 Rooted<JSObject*> boundTarget(cx_, calleeObj->getTarget());
13050 if (!boundTarget->is<JSFunction>()) {
13051 return AttachDecision::NoAction;
13052 }
13053 auto target = boundTarget.as<JSFunction>();
13054
13055 bool isScripted = target->hasJitEntry();
13056 MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());
13057
13058 if (isScripted) {
13059 return AttachDecision::NoAction;
13060 }
13061
13062 // Limit the number of bound arguments to prevent us from compiling many
13063 // different stubs (we bake in numBoundArgs and it's usually very small).
13064 static constexpr size_t MaxBoundArgs = 10;
13065 size_t numBoundArgs = calleeObj->numBoundArgs();
13066 if (numBoundArgs > MaxBoundArgs) {
13067 return AttachDecision::NoAction;
13068 }
13069
13070 // Ensure we don't exceed JIT_ARGS_LENGTH_MAX.
13071 if (numBoundArgs + argc_ > JIT_ARGS_LENGTH_MAX) {
13072 return AttachDecision::NoAction;
13073 }
13074
13075 // Don't try to optimize when we're already megamorphic.
13076 if (mode_ != ICState::Mode::Specialized) {
13077 return AttachDecision::NoAction;
13078 }
13079
13080 bool isSpread = IsSpreadPC(pc_);
13081 bool isSameRealm = cx_->realm() == target->realm();
13082 bool isConstructing = IsConstructPC(pc_);
13083 CallFlags flags(isConstructing, isSpread, isSameRealm);
13084
13085 if (isConstructing && !target->isConstructor()) {
13086 return AttachDecision::NoAction;
13087 }
13088
13089 // Verify that spread calls have a reasonable number of arguments.
13090 if (isSpread && args_.length() > JIT_ARGS_LENGTH_MAX) {
13091 return AttachDecision::NoAction;
13092 }
13093
13094 // Spread calls are only supported when we don't have to insert bound args.
13095 if (isSpread && numBoundArgs != 0) {
13096 return AttachDecision::NoAction;
13097 }
13098
13099 // Use the bound |this| value.
13100 Rooted<Value> thisValue(cx_, calleeObj->getBoundThis());
13101
13102 // Concatenate the bound arguments and the stack arguments.
13103 JS::RootedVector<Value> concatenatedArgs(cx_);
13104 if (numBoundArgs != 0) {
13105 if (!concatenatedArgs.reserve(numBoundArgs + args_.length())) {
13106 cx_->recoverFromOutOfMemory();
13107 return AttachDecision::NoAction;
13108 }
13109
13110 for (size_t i = 0; i < numBoundArgs; i++) {
13111 concatenatedArgs.infallibleAppend(calleeObj->getBoundArg(i));
13112 }
13113 concatenatedArgs.infallibleAppend(args_.begin(), args_.length());
13114 }
13115 auto args = numBoundArgs != 0 ? concatenatedArgs : args_;
13116
13117 // Check for specific native-function optimizations.
13118 InlinableNativeIRGenerator nativeGen(*this, target, newTarget_, thisValue,
13119 args, flags);
13120 return nativeGen.tryAttachStub();
13121 }
13122
13123 AttachDecision CallIRGenerator::tryAttachBoundFunCall(
13124 Handle<BoundFunctionObject*> calleeObj) {
13125 // Only optimize fun_call for simple calls.
13126 if (op_ != JSOp::Call && op_ != JSOp::CallContent &&
13127 op_ != JSOp::CallIgnoresRv) {
13128 return AttachDecision::NoAction;
13129 }
13130
13131 // The target must be a native JSFunction to fun_call.
13132 JSObject* boundTarget = calleeObj->getTarget();
13133 if (!boundTarget->is<JSFunction>()) {
13134 return AttachDecision::NoAction;
13135 }
13136 auto* boundTargetFn = &boundTarget->as<JSFunction>();
13137
13138 bool isScripted = boundTargetFn->hasJitEntry();
13139 MOZ_ASSERT_IF(!isScripted, boundTargetFn->isNativeWithoutJitEntry());
13140
13141 if (isScripted || boundTargetFn->native() != fun_call) {
13142 return AttachDecision::NoAction;
13143 }
13144
13145 // Limit the number of bound arguments to prevent us from compiling many
13146 // different stubs (we bake in numBoundArgs and it's usually very small).
13147 static constexpr size_t MaxBoundArgs = 10;
13148 size_t numBoundArgs = calleeObj->numBoundArgs();
13149 if (numBoundArgs > MaxBoundArgs) {
13150 return AttachDecision::NoAction;
13151 }
13152
13153 // Ensure we don't exceed JIT_ARGS_LENGTH_MAX.
13154 if (numBoundArgs + argc_ > JIT_ARGS_LENGTH_MAX) {
13155 return AttachDecision::NoAction;
13156 }
13157
13158 // Don't try to optimize when we're already megamorphic.
13159 if (mode_ != ICState::Mode::Specialized) {
13160 return AttachDecision::NoAction;
13161 }
13162
13163 JSFunction* boundThis;
13164 if (!IsFunctionObject(calleeObj->getBoundThis(), &boundThis)) {
13165 return AttachDecision::NoAction;
13166 }
13167
13168 bool boundThisIsScripted = boundThis->hasJitEntry();
13169 MOZ_ASSERT_IF(!boundThisIsScripted, boundThis->isNativeWithoutJitEntry());
13170
13171 if (boundThisIsScripted) {
13172 return AttachDecision::NoAction;
13173 }
13174
13175 CallFlags targetFlags(CallFlags::FunCall);
13176 if (cx_->realm() == boundThis->realm()) {
13177 targetFlags.setIsSameRealm();
13178 }
13179
13180 Rooted<JSFunction*> target(cx_, boundThis);
13181 HandleValue newTarget = NullHandleValue;
13182
13183 Rooted<Value> thisValue(cx_);
13184 if (numBoundArgs > 0) {
13185 thisValue = calleeObj->getBoundArg(0);
13186 } else if (argc_ > 0) {
13187 thisValue = args_[0];
13188 } else {
13189 MOZ_ASSERT(thisValue.isUndefined());
13190 }
13191
13192 // Concatenate the bound arguments and the stack arguments.
13193 JS::RootedVector<Value> concatenatedArgs(cx_);
13194 if (numBoundArgs > 1) {
13195 if (!concatenatedArgs.reserve((numBoundArgs - 1) + args_.length())) {
13196 cx_->recoverFromOutOfMemory();
13197 return AttachDecision::NoAction;
13198 }
13199
13200 for (size_t i = 1; i < numBoundArgs; i++) {
13201 concatenatedArgs.infallibleAppend(calleeObj->getBoundArg(i));
13202 }
13203 concatenatedArgs.infallibleAppend(args_.begin(), args_.length());
13204 }
13205 auto args = ([&]() -> HandleValueArray {
13206 if (numBoundArgs > 1) {
13207 // Return |concatenatedArgs| if there are any bound arguments.
13208 return concatenatedArgs;
13209 }
13210 if (numBoundArgs > 0) {
13211 // Return |args_| if only the |this| value is bound.
13212 return args_;
13213 }
13214 if (argc_ > 0) {
13215 // Nothing bound at all, return stack arguments starting from |args[1]|.
13216 return HandleValueArray::subarray(args_, 1, args_.length() - 1);
13217 }
13218 // No arguments at all.
13219 return HandleValueArray::empty();
13220 })();
13221
13222 // Check for specific native-function optimizations.
13223 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
13224 args, targetFlags);
13225 return nativeGen.tryAttachStub();
13226 }
13227
13228 AttachDecision CallIRGenerator::tryAttachBoundFunApply(
13229 Handle<BoundFunctionObject*> calleeObj) {
13230 // Only optimize fun_apply for simple calls.
13231 if (op_ != JSOp::Call && op_ != JSOp::CallContent &&
13232 op_ != JSOp::CallIgnoresRv) {
13233 return AttachDecision::NoAction;
13234 }
13235
13236 // The target must be a native JSFunction to fun_apply.
13237 JSObject* boundTarget = calleeObj->getTarget();
13238 if (!boundTarget->is<JSFunction>()) {
13239 return AttachDecision::NoAction;
13240 }
13241 auto* boundTargetFn = &boundTarget->as<JSFunction>();
13242
13243 bool isScripted = boundTargetFn->hasJitEntry();
13244 MOZ_ASSERT_IF(!isScripted, boundTargetFn->isNativeWithoutJitEntry());
13245
13246 if (isScripted || boundTargetFn->native() != fun_apply) {
13247 return AttachDecision::NoAction;
13248 }
13249
13250 size_t numBoundArgs = calleeObj->numBoundArgs();
13251 if (numBoundArgs + argc_ > 2) {
13252 return AttachDecision::NoAction;
13253 }
13254
13255 // Don't try to optimize when we're already megamorphic.
13256 if (mode_ != ICState::Mode::Specialized) {
13257 return AttachDecision::NoAction;
13258 }
13259
13260 JSFunction* boundThis;
13261 if (!IsFunctionObject(calleeObj->getBoundThis(), &boundThis)) {
13262 return AttachDecision::NoAction;
13263 }
13264
13265 bool boundThisIsScripted = boundThis->hasJitEntry();
13266 MOZ_ASSERT_IF(!boundThisIsScripted, boundThis->isNativeWithoutJitEntry());
13267
13268 if (boundThisIsScripted) {
13269 return AttachDecision::NoAction;
13270 }
13271
13272 // The second argument must be |null| or |undefined|, because we only support
13273 // |CallFlags::FunCall| and |CallFlags::FunApplyNullUndefined|.
13274 CallFlags::ArgFormat format;
13275 if (numBoundArgs + argc_ < 2) {
13276 format = CallFlags::FunCall;
13277 } else {
13278 Value arg;
13279 if (numBoundArgs == 2) {
13280 arg = calleeObj->getBoundArg(1);
13281 } else if (numBoundArgs == 1) {
13282 arg = args_[0];
13283 } else {
13284 arg = args_[1];
13285 }
13286 if (!arg.isNullOrUndefined()) {
13287 return AttachDecision::NoAction;
13288 }
13289 format = CallFlags::FunApplyNullUndefined;
13290 }
13291
13292 CallFlags targetFlags(format);
13293 if (cx_->realm() == boundThis->realm()) {
13294 targetFlags.setIsSameRealm();
13295 }
13296
13297 Rooted<JSFunction*> target(cx_, boundThis);
13298 HandleValue newTarget = NullHandleValue;
13299
13300 Rooted<Value> thisValue(cx_);
13301 if (numBoundArgs > 0) {
13302 thisValue = calleeObj->getBoundArg(0);
13303 } else if (argc_ > 0) {
13304 thisValue = args_[0];
13305 } else {
13306 MOZ_ASSERT(thisValue.isUndefined());
13307 }
13308 HandleValueArray args = HandleValueArray::empty();
13309
13310 // Check for specific native-function optimizations.
13311 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
13312 args, targetFlags);
13313 return nativeGen.tryAttachStub();
13314 }
13315
13316 AttachDecision CallIRGenerator::tryAttachFunCallBound(
13317 Handle<JSFunction*> callee) {
13318 MOZ_ASSERT(callee->isNativeWithoutJitEntry());
13319
13320 if (callee->native() != fun_call) {
13321 return AttachDecision::NoAction;
13322 }
13323
13324 if (!thisval_.isObject() || !thisval_.toObject().is<BoundFunctionObject>()) {
13325 return AttachDecision::NoAction;
13326 }
13327 Rooted<BoundFunctionObject*> bound(
13328 cx_, &thisval_.toObject().as<BoundFunctionObject>());
13329
13330 // The target must be a native JSFunction without a JitEntry.
13331 Rooted<JSObject*> boundTarget(cx_, bound->getTarget());
13332 if (!boundTarget->is<JSFunction>()) {
13333 return AttachDecision::NoAction;
13334 }
13335 auto target = boundTarget.as<JSFunction>();
13336
13337 bool isScripted = target->hasJitEntry();
13338 MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());
13339
13340 // We don't yet supported scripted bound targets.
13341 if (isScripted) {
13342 return AttachDecision::NoAction;
13343 }
13344
13345 // Limit the number of bound arguments to prevent us from compiling many
13346 // different stubs (we bake in numBoundArgs and it's usually very small).
13347 static constexpr size_t MaxBoundArgs = 10;
13348 size_t numBoundArgs = bound->numBoundArgs();
13349 if (numBoundArgs > MaxBoundArgs) {
13350 return AttachDecision::NoAction;
13351 }
13352
13353 // Ensure we don't exceed JIT_ARGS_LENGTH_MAX.
13354 if (numBoundArgs + argc_ > JIT_ARGS_LENGTH_MAX) {
13355 return AttachDecision::NoAction;
13356 }
13357
13358 // Don't try to optimize when we're already megamorphic.
13359 if (mode_ != ICState::Mode::Specialized) {
13360 return AttachDecision::NoAction;
13361 }
13362
13363 CallFlags targetFlags(CallFlags::FunCall);
13364 if (cx_->realm() == target->realm()) {
13365 targetFlags.setIsSameRealm();
13366 }
13367
13368 HandleValue newTarget = NullHandleValue;
13369
13370 // Use the bound |this| value.
13371 Rooted<Value> thisValue(cx_, bound->getBoundThis());
13372
13373 auto callArgs = argc_ > 0
13374 ? HandleValueArray::subarray(args_, 1, args_.length() - 1)
13375 : HandleValueArray::empty();
13376
13377 // Concatenate the bound arguments and the stack arguments.
13378 JS::RootedVector<Value> concatenatedArgs(cx_);
13379 if (numBoundArgs != 0) {
13380 if (!concatenatedArgs.reserve(numBoundArgs + callArgs.length())) {
13381 cx_->recoverFromOutOfMemory();
13382 return AttachDecision::NoAction;
13383 }
13384
13385 for (size_t i = 0; i < numBoundArgs; i++) {
13386 concatenatedArgs.infallibleAppend(bound->getBoundArg(i));
13387 }
13388 concatenatedArgs.infallibleAppend(callArgs.begin(), callArgs.length());
13389 }
13390
13391 // Actual args.
13392 auto args = numBoundArgs != 0 ? concatenatedArgs : callArgs;
13393
13394 // Check for specific native-function optimizations.
13395 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
13396 args, targetFlags);
13397 return nativeGen.tryAttachStub();
13398 }
13399
13400 AttachDecision CallIRGenerator::tryAttachFunApplyBound(
13401 Handle<JSFunction*> callee) {
13402 MOZ_ASSERT(callee->isNativeWithoutJitEntry());
13403
13404 if (callee->native() != fun_apply) {
13405 return AttachDecision::NoAction;
13406 }
13407
13408 if (argc_ > 2) {
13409 return AttachDecision::NoAction;
13410 }
13411
13412 if (!thisval_.isObject() || !thisval_.toObject().is<BoundFunctionObject>()) {
13413 return AttachDecision::NoAction;
13414 }
13415 Rooted<BoundFunctionObject*> bound(
13416 cx_, &thisval_.toObject().as<BoundFunctionObject>());
13417
13418 // The target must be a native JSFunction without a JitEntry.
13419 Rooted<JSObject*> boundTarget(cx_, bound->getTarget());
13420 if (!boundTarget->is<JSFunction>()) {
13421 return AttachDecision::NoAction;
13422 }
13423 auto target = boundTarget.as<JSFunction>();
13424
13425 bool isScripted = target->hasJitEntry();
13426 MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());
13427
13428 // We don't yet supported scripted bound targets.
13429 if (isScripted) {
13430 return AttachDecision::NoAction;
13431 }
13432
13433 // Limit the number of bound arguments to prevent us from compiling many
13434 // different stubs (we bake in numBoundArgs and it's usually very small).
13435 static constexpr size_t MaxBoundArgs = 10;
13436 size_t numBoundArgs = bound->numBoundArgs();
13437 if (numBoundArgs > MaxBoundArgs) {
13438 return AttachDecision::NoAction;
13439 }
13440
13441 // The second argument must be |null| or |undefined|, because we only support
13442 // |CallFlags::FunCall| and |CallFlags::FunApplyNullUndefined|.
13443 CallFlags::ArgFormat format;
13444 if (argc_ < 2) {
13445 format = CallFlags::FunCall;
13446 } else if (args_[1].isNullOrUndefined()) {
13447 format = CallFlags::FunApplyNullUndefined;
13448 } else {
13449 return AttachDecision::NoAction;
13450 }
13451
13452 // Don't try to optimize when we're already megamorphic.
13453 if (mode_ != ICState::Mode::Specialized) {
13454 return AttachDecision::NoAction;
13455 }
13456
13457 CallFlags targetFlags(format);
13458 if (cx_->realm() == target->realm()) {
13459 targetFlags.setIsSameRealm();
13460 }
13461
13462 HandleValue newTarget = NullHandleValue;
13463
13464 // Use the bound |this| value.
13465 Rooted<Value> thisValue(cx_, bound->getBoundThis());
13466
13467 // Collect all bound arguments.
13468 JS::RootedVector<Value> args(cx_);
13469 if (numBoundArgs != 0) {
13470 if (!args.reserve(numBoundArgs)) {
13471 cx_->recoverFromOutOfMemory();
13472 return AttachDecision::NoAction;
13473 }
13474
13475 for (size_t i = 0; i < numBoundArgs; i++) {
13476 args.infallibleAppend(bound->getBoundArg(i));
13477 }
13478 }
13479
13480 // Check for specific native-function optimizations.
13481 InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
13482 args, targetFlags);
13483 return nativeGen.tryAttachStub();
13484 }
13485
13486 AttachDecision CallIRGenerator::tryAttachStub() {
13487 AutoAssertNoPendingException aanpe(cx_);
13488
13489 // Some opcodes are not yet supported.
13490 switch (op_) {
13491 case JSOp::Call:
13492 case JSOp::CallContent:
13493 case JSOp::CallIgnoresRv:
13494 case JSOp::CallIter:
13495 case JSOp::CallContentIter:
13496 case JSOp::SpreadCall:
13497 case JSOp::New:
13498 case JSOp::NewContent:
13499 case JSOp::SpreadNew:
13500 case JSOp::SuperCall:
13501 case JSOp::SpreadSuperCall:
13502 break;
13503 default:
13504 return AttachDecision::NoAction;
13505 }
13506
13507 MOZ_ASSERT(mode_ != ICState::Mode::Generic);
13508
13509 // Ensure callee is a function.
13510 if (!callee_.isObject()) {
13511 return AttachDecision::NoAction;
13512 }
13513
13514 RootedObject calleeObj(cx_, &callee_.toObject());
13515 if (calleeObj->is<BoundFunctionObject>()) {
13516 auto boundCalleeObj = calleeObj.as<BoundFunctionObject>();
13517
13518 TRY_ATTACH(tryAttachBoundFunction(boundCalleeObj));
13519 TRY_ATTACH(tryAttachBoundNative(boundCalleeObj));
13520 TRY_ATTACH(tryAttachBoundFunCall(boundCalleeObj));
13521 TRY_ATTACH(tryAttachBoundFunApply(boundCalleeObj));
13522 }
13523 if (!calleeObj->is<JSFunction>()) {
13524 return tryAttachCallHook(calleeObj);
13525 }
13526
13527 HandleFunction calleeFunc = calleeObj.as<JSFunction>();
13528
13529 // Check for scripted optimizations.
13530 if (calleeFunc->hasJitEntry()) {
13531 return tryAttachCallScripted(calleeFunc);
13532 }
13533
13534 // Check for native-function optimizations.
13535 MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());
13536
13537 // Try inlining Function.prototype.{call,apply}. We don't use the
13538 // InlinableNative mechanism for this because we want to optimize these more
13539 // aggressively than other natives.
13540 if (op_ == JSOp::Call || op_ == JSOp::CallContent ||
13541 op_ == JSOp::CallIgnoresRv) {
13542 TRY_ATTACH(tryAttachFunCall(calleeFunc));
13543 TRY_ATTACH(tryAttachFunApply(calleeFunc));
13544 TRY_ATTACH(tryAttachFunCallBound(calleeFunc));
13545 TRY_ATTACH(tryAttachFunApplyBound(calleeFunc));
13546 }
13547
13548 return tryAttachCallNative(calleeFunc);
13549 }
13550
13551 void CallIRGenerator::trackAttached(const char* name) {
13552 stubName_ = name ? name : "NotAttached";
13553 #ifdef JS_CACHEIR_SPEW
13554 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
13555 sp.valueProperty("callee", callee_);
13556 sp.valueProperty("thisval", thisval_);
13557 sp.valueProperty("argc", Int32Value(argc_));
13558
13559 // Try to log the first two arguments.
13560 if (args_.length() >= 1) {
13561 sp.valueProperty("arg0", args_[0]);
13562 }
13563 if (args_.length() >= 2) {
13564 sp.valueProperty("arg1", args_[1]);
13565 }
13566 }
13567 #endif
13568 }
13569
13570 // Class which holds a shape pointer for use when caches might reference data in
13571 // other zones.
13572 static const JSClass shapeContainerClass = {"ShapeContainer",
13573 JSCLASS_HAS_RESERVED_SLOTS(1)};
13574
13575 static const size_t SHAPE_CONTAINER_SLOT = 0;
13576
13577 static JSObject* NewWrapperWithObjectShape(JSContext* cx,
13578 Handle<NativeObject*> obj) {
13579 MOZ_ASSERT(cx->compartment() != obj->compartment());
13580
13581 RootedObject wrapper(cx);
13582 {
13583 AutoRealm ar(cx, obj);
13584 wrapper = NewBuiltinClassInstance(cx, &shapeContainerClass);
13585 if (!wrapper) {
13586 return nullptr;
13587 }
13588 wrapper->as<NativeObject>().setReservedSlot(
13589 SHAPE_CONTAINER_SLOT, PrivateGCThingValue(obj->shape()));
13590 }
13591 if (!JS_WrapObject(cx, &wrapper)) {
13592 return nullptr;
13593 }
13594 MOZ_ASSERT(IsWrapper(wrapper));
13595 return wrapper;
13596 }
13597
13598 void jit::LoadShapeWrapperContents(MacroAssembler& masm, Register obj,
13599 Register dst, Label* failure) {
13600 masm.loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()), dst);
13601 Address privateAddr(dst,
13602 js::detail::ProxyReservedSlots::offsetOfPrivateSlot());
13603 masm.fallibleUnboxObject(privateAddr, dst, failure);
13604 masm.unboxNonDouble(
13605 Address(dst, NativeObject::getFixedSlotOffset(SHAPE_CONTAINER_SLOT)), dst,
13606 JSVAL_TYPE_PRIVATE_GCTHING);
13607 }
13608
13609 static bool CanConvertToInt32ForToNumber(const Value& v) {
13610 return v.isInt32() || v.isBoolean() || v.isNull();
13611 }
13612
13613 static Int32OperandId EmitGuardToInt32ForToNumber(CacheIRWriter& writer,
13614 ValOperandId id,
13615 const Value& v) {
13616 if (v.isInt32()) {
13617 return writer.guardToInt32(id);
13618 }
13619 if (v.isNull()) {
13620 writer.guardIsNull(id);
13621 return writer.loadInt32Constant(0);
13622 }
13623 MOZ_ASSERT(v.isBoolean());
13624 return writer.guardBooleanToInt32(id);
13625 }
13626
13627 static bool CanConvertToDoubleForToNumber(const Value& v) {
13628 return v.isNumber() || v.isBoolean() || v.isNullOrUndefined();
13629 }
13630
13631 static NumberOperandId EmitGuardToDoubleForToNumber(CacheIRWriter& writer,
13632 ValOperandId id,
13633 const Value& v) {
13634 if (v.isNumber()) {
13635 return writer.guardIsNumber(id);
13636 }
13637 if (v.isBoolean()) {
13638 BooleanOperandId boolId = writer.guardToBoolean(id);
13639 return writer.booleanToNumber(boolId);
13640 }
13641 if (v.isNull()) {
13642 writer.guardIsNull(id);
13643 return writer.loadDoubleConstant(0.0);
13644 }
13645 MOZ_ASSERT(v.isUndefined());
13646 writer.guardIsUndefined(id);
13647 return writer.loadDoubleConstant(JS::GenericNaN());
13648 }
13649
13650 CompareIRGenerator::CompareIRGenerator(JSContext* cx, HandleScript script,
13651 jsbytecode* pc, ICState state, JSOp op,
13652 HandleValue lhsVal, HandleValue rhsVal)
13653 : IRGenerator(cx, script, pc, CacheKind::Compare, state),
13654 op_(op),
13655 lhsVal_(lhsVal),
13656 rhsVal_(rhsVal) {}
13657
13658 AttachDecision CompareIRGenerator::tryAttachString(ValOperandId lhsId,
13659 ValOperandId rhsId) {
13660 if (!lhsVal_.isString() || !rhsVal_.isString()) {
13661 return AttachDecision::NoAction;
13662 }
13663
13664 StringOperandId lhsStrId = writer.guardToString(lhsId);
13665 StringOperandId rhsStrId = writer.guardToString(rhsId);
13666 writer.compareStringResult(op_, lhsStrId, rhsStrId);
13667 writer.returnFromIC();
13668
13669 trackAttached("Compare.String");
13670 return AttachDecision::Attach;
13671 }
13672
13673 AttachDecision CompareIRGenerator::tryAttachObject(ValOperandId lhsId,
13674 ValOperandId rhsId) {
13675 MOZ_ASSERT(IsEqualityOp(op_));
13676
13677 if (!lhsVal_.isObject() || !rhsVal_.isObject()) {
13678 return AttachDecision::NoAction;
13679 }
13680
13681 ObjOperandId lhsObjId = writer.guardToObject(lhsId);
13682 ObjOperandId rhsObjId = writer.guardToObject(rhsId);
13683 writer.compareObjectResult(op_, lhsObjId, rhsObjId);
13684 writer.returnFromIC();
13685
13686 trackAttached("Compare.Object");
13687 return AttachDecision::Attach;
13688 }
13689
13690 AttachDecision CompareIRGenerator::tryAttachSymbol(ValOperandId lhsId,
13691 ValOperandId rhsId) {
13692 MOZ_ASSERT(IsEqualityOp(op_));
13693
13694 if (!lhsVal_.isSymbol() || !rhsVal_.isSymbol()) {
13695 return AttachDecision::NoAction;
13696 }
13697
13698 SymbolOperandId lhsSymId = writer.guardToSymbol(lhsId);
13699 SymbolOperandId rhsSymId = writer.guardToSymbol(rhsId);
13700 writer.compareSymbolResult(op_, lhsSymId, rhsSymId);
13701 writer.returnFromIC();
13702
13703 trackAttached("Compare.Symbol");
13704 return AttachDecision::Attach;
13705 }
13706
13707 AttachDecision CompareIRGenerator::tryAttachStrictDifferentTypes(
13708 ValOperandId lhsId, ValOperandId rhsId) {
13709 MOZ_ASSERT(IsEqualityOp(op_));
13710
13711 if (op_ != JSOp::StrictEq && op_ != JSOp::StrictNe) {
13712 return AttachDecision::NoAction;
13713 }
13714
13715 // Probably can't hit some of these.
13716 if (SameType(lhsVal_, rhsVal_) ||
13717 (lhsVal_.isNumber() && rhsVal_.isNumber())) {
13718 return AttachDecision::NoAction;
13719 }
13720
13721 // Compare tags
13722 ValueTagOperandId lhsTypeId = writer.loadValueTag(lhsId);
13723 ValueTagOperandId rhsTypeId = writer.loadValueTag(rhsId);
13724 writer.guardTagNotEqual(lhsTypeId, rhsTypeId);
13725
13726 // Now that we've passed the guard, we know differing types, so return the
13727 // bool result.
13728 writer.loadBooleanResult(op_ == JSOp::StrictNe ? true : false);
13729 writer.returnFromIC();
13730
13731 trackAttached("Compare.StrictDifferentTypes");
13732 return AttachDecision::Attach;
13733 }
13734
13735 AttachDecision CompareIRGenerator::tryAttachInt32(ValOperandId lhsId,
13736 ValOperandId rhsId) {
13737 if (!CanConvertToInt32ForToNumber(lhsVal_) ||
13738 !CanConvertToInt32ForToNumber(rhsVal_)) {
13739 return AttachDecision::NoAction;
13740 }
13741
13742 // Strictly different types should have been handed by
13743 // tryAttachStrictDifferentTypes.
13744 MOZ_ASSERT_IF(op_ == JSOp::StrictEq || op_ == JSOp::StrictNe,
13745 lhsVal_.type() == rhsVal_.type());
13746
13747 // Should have been handled by tryAttachAnyNullUndefined.
13748 MOZ_ASSERT_IF(lhsVal_.isNull() || rhsVal_.isNull(), !IsEqualityOp(op_));
13749
13750 Int32OperandId lhsIntId = EmitGuardToInt32ForToNumber(writer, lhsId, lhsVal_);
13751 Int32OperandId rhsIntId = EmitGuardToInt32ForToNumber(writer, rhsId, rhsVal_);
13752
13753 writer.compareInt32Result(op_, lhsIntId, rhsIntId);
13754 writer.returnFromIC();
13755
13756 trackAttached("Compare.Int32");
13757 return AttachDecision::Attach;
13758 }
13759
13760 AttachDecision CompareIRGenerator::tryAttachNumber(ValOperandId lhsId,
13761 ValOperandId rhsId) {
13762 if (!CanConvertToDoubleForToNumber(lhsVal_) ||
13763 !CanConvertToDoubleForToNumber(rhsVal_)) {
13764 return AttachDecision::NoAction;
13765 }
13766
13767 // Strictly different types should have been handed by
13768 // tryAttachStrictDifferentTypes.
13769 MOZ_ASSERT_IF(op_ == JSOp::StrictEq || op_ == JSOp::StrictNe,
13770 lhsVal_.type() == rhsVal_.type() ||
13771 (lhsVal_.isNumber() && rhsVal_.isNumber()));
13772
13773 // Should have been handled by tryAttachAnyNullUndefined.
13774 MOZ_ASSERT_IF(lhsVal_.isNullOrUndefined() || rhsVal_.isNullOrUndefined(),
13775 !IsEqualityOp(op_));
13776
13777 NumberOperandId lhs = EmitGuardToDoubleForToNumber(writer, lhsId, lhsVal_);
13778 NumberOperandId rhs = EmitGuardToDoubleForToNumber(writer, rhsId, rhsVal_);
13779 writer.compareDoubleResult(op_, lhs, rhs);
13780 writer.returnFromIC();
13781
13782 trackAttached("Compare.Number");
13783 return AttachDecision::Attach;
13784 }
13785
13786 AttachDecision CompareIRGenerator::tryAttachBigInt(ValOperandId lhsId,
13787 ValOperandId rhsId) {
13788 if (!lhsVal_.isBigInt() || !rhsVal_.isBigInt()) {
13789 return AttachDecision::NoAction;
13790 }
13791
13792 BigIntOperandId lhs = writer.guardToBigInt(lhsId);
13793 BigIntOperandId rhs = writer.guardToBigInt(rhsId);
13794
13795 writer.compareBigIntResult(op_, lhs, rhs);
13796 writer.returnFromIC();
13797
13798 trackAttached("Compare.BigInt");
13799 return AttachDecision::Attach;
13800 }
13801
13802 AttachDecision CompareIRGenerator::tryAttachAnyNullUndefined(
13803 ValOperandId lhsId, ValOperandId rhsId) {
13804 MOZ_ASSERT(IsEqualityOp(op_));
13805
13806 // Either RHS or LHS needs to be null/undefined.
13807 if (!lhsVal_.isNullOrUndefined() && !rhsVal_.isNullOrUndefined()) {
13808 return AttachDecision::NoAction;
13809 }
13810
13811 // We assume that the side with null/undefined is usually constant, in
13812 // code like `if (x === undefined) { x = {}; }`.
13813 // That is why we don't attach when both sides are undefined/null,
13814 // because we would basically need to decide by chance which side is
13815 // the likely constant.
13816 // The actual generated code however handles null/undefined of course.
13817 if (lhsVal_.isNullOrUndefined() && rhsVal_.isNullOrUndefined()) {
13818 return AttachDecision::NoAction;
13819 }
13820
13821 if (rhsVal_.isNullOrUndefined()) {
13822 if (rhsVal_.isNull()) {
13823 writer.guardIsNull(rhsId);
13824 writer.compareNullUndefinedResult(op_, /* isUndefined */ false, lhsId);
13825 trackAttached("Compare.AnyNull");
13826 } else {
13827 writer.guardIsUndefined(rhsId);
13828 writer.compareNullUndefinedResult(op_, /* isUndefined */ true, lhsId);
13829 trackAttached("Compare.AnyUndefined");
13830 }
13831 } else {
13832 if (lhsVal_.isNull()) {
13833 writer.guardIsNull(lhsId);
13834 writer.compareNullUndefinedResult(op_, /* isUndefined */ false, rhsId);
13835 trackAttached("Compare.NullAny");
13836 } else {
13837 writer.guardIsUndefined(lhsId);
13838 writer.compareNullUndefinedResult(op_, /* isUndefined */ true, rhsId);
13839 trackAttached("Compare.UndefinedAny");
13840 }
13841 }
13842
13843 writer.returnFromIC();
13844 return AttachDecision::Attach;
13845 }
13846
13847 // Handle {null/undefined} x {null,undefined} equality comparisons
13848 AttachDecision CompareIRGenerator::tryAttachNullUndefined(ValOperandId lhsId,
13849 ValOperandId rhsId) {
13850 if (!lhsVal_.isNullOrUndefined() || !rhsVal_.isNullOrUndefined()) {
13851 return AttachDecision::NoAction;
13852 }
13853
13854 if (op_ == JSOp::Eq || op_ == JSOp::Ne) {
13855 writer.guardIsNullOrUndefined(lhsId);
13856 writer.guardIsNullOrUndefined(rhsId);
13857 // Sloppy equality means we actually only care about the op:
13858 writer.loadBooleanResult(op_ == JSOp::Eq);
13859 trackAttached("Compare.SloppyNullUndefined");
13860 } else {
13861 // Strict equality only hits this branch, and only in the
13862 // undef {!,=}== undef and null {!,=}== null cases.
13863 // The other cases should have hit tryAttachStrictDifferentTypes.
13864 MOZ_ASSERT(lhsVal_.isNull() == rhsVal_.isNull());
13865 lhsVal_.isNull() ? writer.guardIsNull(lhsId)
13866 : writer.guardIsUndefined(lhsId);
13867 rhsVal_.isNull() ? writer.guardIsNull(rhsId)
13868 : writer.guardIsUndefined(rhsId);
13869 writer.loadBooleanResult(op_ == JSOp::StrictEq);
13870 trackAttached("Compare.StrictNullUndefinedEquality");
13871 }
13872
13873 writer.returnFromIC();
13874 return AttachDecision::Attach;
13875 }
13876
13877 AttachDecision CompareIRGenerator::tryAttachStringNumber(ValOperandId lhsId,
13878 ValOperandId rhsId) {
13879 // Ensure String x {Number, Boolean, Null, Undefined}
13880 if (!(lhsVal_.isString() && CanConvertToDoubleForToNumber(rhsVal_)) &&
13881 !(rhsVal_.isString() && CanConvertToDoubleForToNumber(lhsVal_))) {
13882 return AttachDecision::NoAction;
13883 }
13884
13885 // Case should have been handled by tryAttachStrictDifferentTypes
13886 MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);
13887
13888 auto createGuards = [&](const Value& v, ValOperandId vId) {
13889 if (v.isString()) {
13890 StringOperandId strId = writer.guardToString(vId);
13891 return writer.guardStringToNumber(strId);
13892 }
13893 return EmitGuardToDoubleForToNumber(writer, vId, v);
13894 };
13895
13896 NumberOperandId lhsGuardedId = createGuards(lhsVal_, lhsId);
13897 NumberOperandId rhsGuardedId = createGuards(rhsVal_, rhsId);
13898 writer.compareDoubleResult(op_, lhsGuardedId, rhsGuardedId);
13899 writer.returnFromIC();
13900
13901 trackAttached("Compare.StringNumber");
13902 return AttachDecision::Attach;
13903 }
13904
13905 AttachDecision CompareIRGenerator::tryAttachPrimitiveSymbol(
13906 ValOperandId lhsId, ValOperandId rhsId) {
13907 MOZ_ASSERT(IsEqualityOp(op_));
13908
13909 // The set of primitive cases we want to handle here (excluding null,
13910 // undefined, and symbol)
13911 auto isPrimitive = [](const Value& x) {
13912 return x.isString() || x.isBoolean() || x.isNumber() || x.isBigInt();
13913 };
13914
13915 // Ensure Symbol x {String, Bool, Number, BigInt}.
13916 if (!(lhsVal_.isSymbol() && isPrimitive(rhsVal_)) &&
13917 !(rhsVal_.isSymbol() && isPrimitive(lhsVal_))) {
13918 return AttachDecision::NoAction;
13919 }
13920
13921 auto guardPrimitive = [&](const Value& v, ValOperandId id) {
13922 MOZ_ASSERT(isPrimitive(v));
13923 if (v.isNumber()) {
13924 writer.guardIsNumber(id);
13925 return;
13926 }
13927 switch (v.extractNonDoubleType()) {
13928 case JSVAL_TYPE_STRING:
13929 writer.guardToString(id);
13930 return;
13931 case JSVAL_TYPE_BOOLEAN:
13932 writer.guardToBoolean(id);
13933 return;
13934 case JSVAL_TYPE_BIGINT:
13935 writer.guardToBigInt(id);
13936 return;
13937 default:
13938 MOZ_CRASH("unexpected type");
13939 return;
13940 }
13941 };
13942
13943 if (lhsVal_.isSymbol()) {
13944 writer.guardToSymbol(lhsId);
13945 guardPrimitive(rhsVal_, rhsId);
13946 } else {
13947 guardPrimitive(lhsVal_, lhsId);
13948 writer.guardToSymbol(rhsId);
13949 }
13950
13951 // Comparing a primitive with symbol will always be true for Ne/StrictNe, and
13952 // always be false for other compare ops.
13953 writer.loadBooleanResult(op_ == JSOp::Ne || op_ == JSOp::StrictNe);
13954 writer.returnFromIC();
13955
13956 trackAttached("Compare.PrimitiveSymbol");
13957 return AttachDecision::Attach;
13958 }
13959
13960 AttachDecision CompareIRGenerator::tryAttachBigIntInt32(ValOperandId lhsId,
13961 ValOperandId rhsId) {
13962 // Ensure BigInt x {Int32, Boolean, Null}.
13963 if (!(lhsVal_.isBigInt() && CanConvertToInt32ForToNumber(rhsVal_)) &&
13964 !(rhsVal_.isBigInt() && CanConvertToInt32ForToNumber(lhsVal_))) {
13965 return AttachDecision::NoAction;
13966 }
13967
13968 // Case should have been handled by tryAttachStrictDifferentTypes
13969 MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);
13970
13971 if (lhsVal_.isBigInt()) {
13972 BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
13973 Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, rhsId, rhsVal_);
13974
13975 writer.compareBigIntInt32Result(op_, bigIntId, intId);
13976 } else {
13977 Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, lhsId, lhsVal_);
13978 BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);
13979
13980 writer.compareBigIntInt32Result(ReverseCompareOp(op_), bigIntId, intId);
13981 }
13982 writer.returnFromIC();
13983
13984 trackAttached("Compare.BigIntInt32");
13985 return AttachDecision::Attach;
13986 }
13987
13988 AttachDecision CompareIRGenerator::tryAttachBigIntNumber(ValOperandId lhsId,
13989 ValOperandId rhsId) {
13990 // Ensure BigInt x {Number, Undefined}.
13991 if (!(lhsVal_.isBigInt() && CanConvertToDoubleForToNumber(rhsVal_)) &&
13992 !(rhsVal_.isBigInt() && CanConvertToDoubleForToNumber(lhsVal_))) {
13993 return AttachDecision::NoAction;
13994 }
13995
13996 // Case should have been handled by tryAttachStrictDifferentTypes
13997 MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);
13998
13999 // Case should have been handled by tryAttachBigIntInt32.
14000 MOZ_ASSERT(!CanConvertToInt32ForToNumber(lhsVal_));
14001 MOZ_ASSERT(!CanConvertToInt32ForToNumber(rhsVal_));
14002
14003 if (lhsVal_.isBigInt()) {
14004 BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
14005 NumberOperandId numId =
14006 EmitGuardToDoubleForToNumber(writer, rhsId, rhsVal_);
14007
14008 writer.compareBigIntNumberResult(op_, bigIntId, numId);
14009 } else {
14010 NumberOperandId numId =
14011 EmitGuardToDoubleForToNumber(writer, lhsId, lhsVal_);
14012 BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);
14013
14014 writer.compareBigIntNumberResult(ReverseCompareOp(op_), bigIntId, numId);
14015 }
14016 writer.returnFromIC();
14017
14018 trackAttached("Compare.BigIntNumber");
14019 return AttachDecision::Attach;
14020 }
14021
14022 AttachDecision CompareIRGenerator::tryAttachBigIntString(ValOperandId lhsId,
14023 ValOperandId rhsId) {
14024 // Ensure BigInt x String.
14025 if (!(lhsVal_.isBigInt() && rhsVal_.isString()) &&
14026 !(rhsVal_.isBigInt() && lhsVal_.isString())) {
14027 return AttachDecision::NoAction;
14028 }
14029
14030 // Case should have been handled by tryAttachStrictDifferentTypes
14031 MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);
14032
14033 if (lhsVal_.isBigInt()) {
14034 BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
14035 StringOperandId strId = writer.guardToString(rhsId);
14036
14037 writer.compareBigIntStringResult(op_, bigIntId, strId);
14038 } else {
14039 StringOperandId strId = writer.guardToString(lhsId);
14040 BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);
14041
14042 writer.compareBigIntStringResult(ReverseCompareOp(op_), bigIntId, strId);
14043 }
14044 writer.returnFromIC();
14045
14046 trackAttached("Compare.BigIntString");
14047 return AttachDecision::Attach;
14048 }
14049
14050 AttachDecision CompareIRGenerator::tryAttachStub() {
14051 MOZ_ASSERT(cacheKind_ == CacheKind::Compare);
14052 MOZ_ASSERT(IsEqualityOp(op_) || IsRelationalOp(op_));
14053
14054 AutoAssertNoPendingException aanpe(cx_);
14055
14056 constexpr uint8_t lhsIndex = 0;
14057 constexpr uint8_t rhsIndex = 1;
14058
14059 ValOperandId lhsId(writer.setInputOperandId(lhsIndex));
14060 ValOperandId rhsId(writer.setInputOperandId(rhsIndex));
14061
14062 // For sloppy equality ops, there are cases this IC does not handle:
14063 // - {Object} x {String, Symbol, Bool, Number, BigInt}.
14064 //
14065 // For relational comparison ops, these cases aren't handled:
14066 // - Object x {String, Bool, Number, BigInt, Object, Null, Undefined}.
14067 // Note: |Symbol x any| always throws, so it doesn't need to be handled.
14068 //
14069 // (The above lists omits the equivalent case {B} x {A} when {A} x {B} is
14070 // already present.)
14071
14072 if (IsEqualityOp(op_)) {
14073 TRY_ATTACH(tryAttachObject(lhsId, rhsId));
14074 TRY_ATTACH(tryAttachSymbol(lhsId, rhsId));
14075
14076 // Handles any (non null or undefined) comparison with null/undefined.
14077 TRY_ATTACH(tryAttachAnyNullUndefined(lhsId, rhsId));
14078
14079 // This covers -strict- equality/inequality using a type tag check, so
14080 // catches all different type pairs outside of Numbers, which cannot be
14081 // checked on tags alone.
14082 TRY_ATTACH(tryAttachStrictDifferentTypes(lhsId, rhsId));
14083
14084 TRY_ATTACH(tryAttachNullUndefined(lhsId, rhsId));
14085
14086 TRY_ATTACH(tryAttachPrimitiveSymbol(lhsId, rhsId));
14087 }
14088
14089 // We want these to be last, to allow us to bypass the
14090 // strictly-different-types cases in the below attachment code
14091 TRY_ATTACH(tryAttachInt32(lhsId, rhsId));
14092 TRY_ATTACH(tryAttachNumber(lhsId, rhsId));
14093 TRY_ATTACH(tryAttachBigInt(lhsId, rhsId));
14094 TRY_ATTACH(tryAttachString(lhsId, rhsId));
14095
14096 TRY_ATTACH(tryAttachStringNumber(lhsId, rhsId));
14097
14098 TRY_ATTACH(tryAttachBigIntInt32(lhsId, rhsId));
14099 TRY_ATTACH(tryAttachBigIntNumber(lhsId, rhsId));
14100 TRY_ATTACH(tryAttachBigIntString(lhsId, rhsId));
14101
14102 // Strict equality is always supported.
14103 MOZ_ASSERT(!IsStrictEqualityOp(op_));
14104
14105 // Other operations are unsupported iff at least one operand is an object.
14106 MOZ_ASSERT(lhsVal_.isObject() || rhsVal_.isObject());
14107
14108 trackAttached(IRGenerator::NotAttached);
14109 return AttachDecision::NoAction;
14110 }
14111
14112 void CompareIRGenerator::trackAttached(const char* name) {
14113 stubName_ = name ? name : "NotAttached";
14114 #ifdef JS_CACHEIR_SPEW
14115 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14116 sp.valueProperty("lhs", lhsVal_);
14117 sp.valueProperty("rhs", rhsVal_);
14118 sp.opcodeProperty("op", op_);
14119 }
14120 #endif
14121 }
14122
14123 ToBoolIRGenerator::ToBoolIRGenerator(JSContext* cx, HandleScript script,
14124 jsbytecode* pc, ICState state,
14125 HandleValue val)
14126 : IRGenerator(cx, script, pc, CacheKind::ToBool, state), val_(val) {}
14127
14128 void ToBoolIRGenerator::trackAttached(const char* name) {
14129 stubName_ = name ? name : "NotAttached";
14130 #ifdef JS_CACHEIR_SPEW
14131 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14132 sp.valueProperty("val", val_);
14133 }
14134 #endif
14135 }
14136
14137 AttachDecision ToBoolIRGenerator::tryAttachStub() {
14138 AutoAssertNoPendingException aanpe(cx_);
14139 writer.setTypeData(TypeData(JSValueType(val_.type())));
14140
14141 TRY_ATTACH(tryAttachBool());
14142 TRY_ATTACH(tryAttachInt32());
14143 TRY_ATTACH(tryAttachNumber());
14144 TRY_ATTACH(tryAttachString());
14145 TRY_ATTACH(tryAttachNullOrUndefined());
14146 TRY_ATTACH(tryAttachObject());
14147 TRY_ATTACH(tryAttachSymbol());
14148 TRY_ATTACH(tryAttachBigInt());
14149
14150 trackAttached(IRGenerator::NotAttached);
14151 return AttachDecision::NoAction;
14152 }
14153
14154 AttachDecision ToBoolIRGenerator::tryAttachBool() {
14155 if (!val_.isBoolean()) {
14156 return AttachDecision::NoAction;
14157 }
14158
14159 ValOperandId valId(writer.setInputOperandId(0));
14160 writer.guardNonDoubleType(valId, ValueType::Boolean);
14161 writer.loadOperandResult(valId);
14162 writer.returnFromIC();
14163 trackAttached("ToBool.Bool");
14164 return AttachDecision::Attach;
14165 }
14166
14167 AttachDecision ToBoolIRGenerator::tryAttachInt32() {
14168 if (!val_.isInt32()) {
14169 return AttachDecision::NoAction;
14170 }
14171
14172 ValOperandId valId(writer.setInputOperandId(0));
14173 writer.guardNonDoubleType(valId, ValueType::Int32);
14174 writer.loadInt32TruthyResult(valId);
14175 writer.returnFromIC();
14176 trackAttached("ToBool.Int32");
14177 return AttachDecision::Attach;
14178 }
14179
14180 AttachDecision ToBoolIRGenerator::tryAttachNumber() {
14181 if (!val_.isNumber()) {
14182 return AttachDecision::NoAction;
14183 }
14184
14185 ValOperandId valId(writer.setInputOperandId(0));
14186 NumberOperandId numId = writer.guardIsNumber(valId);
14187 writer.loadDoubleTruthyResult(numId);
14188 writer.returnFromIC();
14189 trackAttached("ToBool.Number");
14190 return AttachDecision::Attach;
14191 }
14192
14193 AttachDecision ToBoolIRGenerator::tryAttachSymbol() {
14194 if (!val_.isSymbol()) {
14195 return AttachDecision::NoAction;
14196 }
14197
14198 ValOperandId valId(writer.setInputOperandId(0));
14199 writer.guardNonDoubleType(valId, ValueType::Symbol);
14200 writer.loadBooleanResult(true);
14201 writer.returnFromIC();
14202 trackAttached("ToBool.Symbol");
14203 return AttachDecision::Attach;
14204 }
14205
14206 AttachDecision ToBoolIRGenerator::tryAttachString() {
14207 if (!val_.isString()) {
14208 return AttachDecision::NoAction;
14209 }
14210
14211 ValOperandId valId(writer.setInputOperandId(0));
14212 StringOperandId strId = writer.guardToString(valId);
14213 writer.loadStringTruthyResult(strId);
14214 writer.returnFromIC();
14215 trackAttached("ToBool.String");
14216 return AttachDecision::Attach;
14217 }
14218
14219 AttachDecision ToBoolIRGenerator::tryAttachNullOrUndefined() {
14220 if (!val_.isNullOrUndefined()) {
14221 return AttachDecision::NoAction;
14222 }
14223
14224 ValOperandId valId(writer.setInputOperandId(0));
14225 writer.guardIsNullOrUndefined(valId);
14226 writer.loadBooleanResult(false);
14227 writer.returnFromIC();
14228 trackAttached("ToBool.NullOrUndefined");
14229 return AttachDecision::Attach;
14230 }
14231
14232 AttachDecision ToBoolIRGenerator::tryAttachObject() {
14233 if (!val_.isObject()) {
14234 return AttachDecision::NoAction;
14235 }
14236
14237 ValOperandId valId(writer.setInputOperandId(0));
14238 ObjOperandId objId = writer.guardToObject(valId);
14239 writer.loadObjectTruthyResult(objId);
14240 writer.returnFromIC();
14241 trackAttached("ToBool.Object");
14242 return AttachDecision::Attach;
14243 }
14244
14245 AttachDecision ToBoolIRGenerator::tryAttachBigInt() {
14246 if (!val_.isBigInt()) {
14247 return AttachDecision::NoAction;
14248 }
14249
14250 ValOperandId valId(writer.setInputOperandId(0));
14251 BigIntOperandId bigIntId = writer.guardToBigInt(valId);
14252 writer.loadBigIntTruthyResult(bigIntId);
14253 writer.returnFromIC();
14254 trackAttached("ToBool.BigInt");
14255 return AttachDecision::Attach;
14256 }
14257
14258 LazyConstantIRGenerator::LazyConstantIRGenerator(JSContext* cx,
14259 HandleScript script,
14260 jsbytecode* pc, ICState state,
14261 HandleValue val)
14262 : IRGenerator(cx, script, pc, CacheKind::LazyConstant, state), val_(val) {}
14263
14264 void LazyConstantIRGenerator::trackAttached(const char* name) {
14265 stubName_ = name ? name : "NotAttached";
14266 #ifdef JS_CACHEIR_SPEW
14267 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14268 sp.valueProperty("val", val_);
14269 }
14270 #endif
14271 }
14272
14273 AttachDecision LazyConstantIRGenerator::tryAttachStub() {
14274 AutoAssertNoPendingException aanpe(cx_);
14275 writer.loadValueResult(val_);
14276 writer.returnFromIC();
14277 trackAttached("LazyConstant");
14278 return AttachDecision::Attach;
14279 }
14280
14281 UnaryArithIRGenerator::UnaryArithIRGenerator(JSContext* cx, HandleScript script,
14282 jsbytecode* pc, ICState state,
14283 JSOp op, HandleValue val,
14284 HandleValue res)
14285 : IRGenerator(cx, script, pc, CacheKind::UnaryArith, state),
14286 op_(op),
14287 val_(val),
14288 res_(res) {}
14289
14290 void UnaryArithIRGenerator::trackAttached(const char* name) {
14291 stubName_ = name ? name : "NotAttached";
14292 #ifdef JS_CACHEIR_SPEW
14293 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14294 sp.valueProperty("val", val_);
14295 sp.valueProperty("res", res_);
14296 }
14297 #endif
14298 }
14299
14300 AttachDecision UnaryArithIRGenerator::tryAttachStub() {
14301 AutoAssertNoPendingException aanpe(cx_);
14302 TRY_ATTACH(tryAttachInt32());
14303 TRY_ATTACH(tryAttachNumber());
14304 TRY_ATTACH(tryAttachBitwise());
14305 TRY_ATTACH(tryAttachBigIntPtr());
14306 TRY_ATTACH(tryAttachBigInt());
14307 TRY_ATTACH(tryAttachStringInt32());
14308 TRY_ATTACH(tryAttachStringNumber());
14309
14310 trackAttached(IRGenerator::NotAttached);
14311 return AttachDecision::NoAction;
14312 }
14313
14314 AttachDecision UnaryArithIRGenerator::tryAttachInt32() {
14315 if (op_ == JSOp::BitNot) {
14316 return AttachDecision::NoAction;
14317 }
14318 if (!CanConvertToInt32ForToNumber(val_) || !res_.isInt32()) {
14319 return AttachDecision::NoAction;
14320 }
14321
14322 ValOperandId valId(writer.setInputOperandId(0));
14323
14324 Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, valId, val_);
14325 switch (op_) {
14326 case JSOp::Pos:
14327 writer.loadInt32Result(intId);
14328 trackAttached("UnaryArith.Int32Pos");
14329 break;
14330 case JSOp::Neg:
14331 writer.int32NegationResult(intId);
14332 trackAttached("UnaryArith.Int32Neg");
14333 break;
14334 case JSOp::Inc:
14335 writer.int32IncResult(intId);
14336 trackAttached("UnaryArith.Int32Inc");
14337 break;
14338 case JSOp::Dec:
14339 writer.int32DecResult(intId);
14340 trackAttached("UnaryArith.Int32Dec");
14341 break;
14342 case JSOp::ToNumeric:
14343 writer.loadInt32Result(intId);
14344 trackAttached("UnaryArith.Int32ToNumeric");
14345 break;
14346 default:
14347 MOZ_CRASH("unexpected OP");
14348 }
14349
14350 writer.returnFromIC();
14351 return AttachDecision::Attach;
14352 }
14353
14354 AttachDecision UnaryArithIRGenerator::tryAttachNumber() {
14355 if (op_ == JSOp::BitNot) {
14356 return AttachDecision::NoAction;
14357 }
14358 if (!CanConvertToDoubleForToNumber(val_)) {
14359 return AttachDecision::NoAction;
14360 }
14361 MOZ_ASSERT(res_.isNumber());
14362
14363 ValOperandId valId(writer.setInputOperandId(0));
14364 NumberOperandId numId = EmitGuardToDoubleForToNumber(writer, valId, val_);
14365
14366 switch (op_) {
14367 case JSOp::Pos:
14368 writer.loadDoubleResult(numId);
14369 trackAttached("UnaryArith.DoublePos");
14370 break;
14371 case JSOp::Neg:
14372 writer.doubleNegationResult(numId);
14373 trackAttached("UnaryArith.DoubleNeg");
14374 break;
14375 case JSOp::Inc:
14376 writer.doubleIncResult(numId);
14377 trackAttached("UnaryArith.DoubleInc");
14378 break;
14379 case JSOp::Dec:
14380 writer.doubleDecResult(numId);
14381 trackAttached("UnaryArith.DoubleDec");
14382 break;
14383 case JSOp::ToNumeric:
14384 writer.loadDoubleResult(numId);
14385 trackAttached("UnaryArith.DoubleToNumeric");
14386 break;
14387 default:
14388 MOZ_CRASH("Unexpected OP");
14389 }
14390
14391 writer.returnFromIC();
14392 return AttachDecision::Attach;
14393 }
14394
14395 static bool CanTruncateToInt32(const Value& val) {
14396 return val.isNumber() || val.isBoolean() || val.isNullOrUndefined() ||
14397 val.isString();
14398 }
14399
14400 // Convert type into int32 for the bitwise/shift operands.
14401 static Int32OperandId EmitTruncateToInt32Guard(CacheIRWriter& writer,
14402 ValOperandId id,
14403 const Value& val) {
14404 MOZ_ASSERT(CanTruncateToInt32(val));
14405 if (val.isInt32()) {
14406 return writer.guardToInt32(id);
14407 }
14408 if (val.isBoolean()) {
14409 return writer.guardBooleanToInt32(id);
14410 }
14411 if (val.isNullOrUndefined()) {
14412 writer.guardIsNullOrUndefined(id);
14413 return writer.loadInt32Constant(0);
14414 }
14415 NumberOperandId numId;
14416 if (val.isString()) {
14417 StringOperandId strId = writer.guardToString(id);
14418 numId = writer.guardStringToNumber(strId);
14419 } else {
14420 MOZ_ASSERT(val.isDouble());
14421 numId = writer.guardIsNumber(id);
14422 }
14423 return writer.truncateDoubleToUInt32(numId);
14424 }
14425
14426 AttachDecision UnaryArithIRGenerator::tryAttachBitwise() {
14427 // Only bitwise operators.
14428 if (op_ != JSOp::BitNot) {
14429 return AttachDecision::NoAction;
14430 }
14431
14432 // Check guard conditions
14433 if (!CanTruncateToInt32(val_)) {
14434 return AttachDecision::NoAction;
14435 }
14436
14437 // Bitwise operators always produce Int32 values.
14438 MOZ_ASSERT(res_.isInt32());
14439
14440 ValOperandId valId(writer.setInputOperandId(0));
14441 Int32OperandId intId = EmitTruncateToInt32Guard(writer, valId, val_);
14442 writer.int32NotResult(intId);
14443 trackAttached("UnaryArith.BitwiseBitNot");
14444
14445 writer.returnFromIC();
14446 return AttachDecision::Attach;
14447 }
14448
14449 AttachDecision UnaryArithIRGenerator::tryAttachBigInt() {
14450 if (!val_.isBigInt()) {
14451 return AttachDecision::NoAction;
14452 }
14453 MOZ_ASSERT(res_.isBigInt());
14454
14455 MOZ_ASSERT(op_ != JSOp::Pos,
14456 "Applying the unary + operator on BigInt values throws an error");
14457
14458 ValOperandId valId(writer.setInputOperandId(0));
14459 BigIntOperandId bigIntId = writer.guardToBigInt(valId);
14460 switch (op_) {
14461 case JSOp::BitNot:
14462 writer.bigIntNotResult(bigIntId);
14463 trackAttached("UnaryArith.BigIntNot");
14464 break;
14465 case JSOp::Neg:
14466 writer.bigIntNegationResult(bigIntId);
14467 trackAttached("UnaryArith.BigIntNeg");
14468 break;
14469 case JSOp::Inc:
14470 writer.bigIntIncResult(bigIntId);
14471 trackAttached("UnaryArith.BigIntInc");
14472 break;
14473 case JSOp::Dec:
14474 writer.bigIntDecResult(bigIntId);
14475 trackAttached("UnaryArith.BigIntDec");
14476 break;
14477 case JSOp::ToNumeric:
14478 writer.loadBigIntResult(bigIntId);
14479 trackAttached("UnaryArith.BigIntToNumeric");
14480 break;
14481 default:
14482 MOZ_CRASH("Unexpected OP");
14483 }
14484
14485 writer.returnFromIC();
14486 return AttachDecision::Attach;
14487 }
14488
14489 AttachDecision UnaryArithIRGenerator::tryAttachBigIntPtr() {
14490 if (!val_.isBigInt()) {
14491 return AttachDecision::NoAction;
14492 }
14493 MOZ_ASSERT(res_.isBigInt());
14494
14495 MOZ_ASSERT(op_ != JSOp::Pos,
14496 "Applying the unary + operator on BigInt values throws an error");
14497
14498 switch (op_) {
14499 case JSOp::BitNot:
14500 case JSOp::Neg:
14501 case JSOp::Inc:
14502 case JSOp::Dec:
14503 break;
14504 case JSOp::ToNumeric:
14505 return AttachDecision::NoAction;
14506 default:
14507 MOZ_CRASH("Unexpected OP");
14508 }
14509
14510 intptr_t val;
14511 if (!BigInt::isIntPtr(val_.toBigInt(), &val)) {
14512 return AttachDecision::NoAction;
14513 }
14514
14515 using CheckedIntPtr = mozilla::CheckedInt<intptr_t>;
14516
14517 switch (op_) {
14518 case JSOp::BitNot: {
14519 // Bitwise operations always return an intptr-sized result.
14520 break;
14521 }
14522 case JSOp::Neg: {
14523 auto result = -CheckedIntPtr(val);
14524 if (result.isValid()) {
14525 break;
14526 }
14527 return AttachDecision::NoAction;
14528 }
14529 case JSOp::Inc: {
14530 auto result = CheckedIntPtr(val) + intptr_t(1);
14531 if (result.isValid()) {
14532 break;
14533 }
14534 return AttachDecision::NoAction;
14535 }
14536 case JSOp::Dec: {
14537 auto result = CheckedIntPtr(val) - intptr_t(1);
14538 if (result.isValid()) {
14539 break;
14540 }
14541 return AttachDecision::NoAction;
14542 }
14543 default:
14544 MOZ_CRASH("Unexpected OP");
14545 }
14546
14547 ValOperandId valId(writer.setInputOperandId(0));
14548 BigIntOperandId bigIntId = writer.guardToBigInt(valId);
14549 IntPtrOperandId intPtrId = writer.bigIntToIntPtr(bigIntId);
14550 IntPtrOperandId resultId;
14551 switch (op_) {
14552 case JSOp::BitNot:
14553 resultId = writer.bigIntPtrNot(intPtrId);
14554 trackAttached("UnaryArith.BigIntPtrNot");
14555 break;
14556 case JSOp::Neg:
14557 resultId = writer.bigIntPtrNegation(intPtrId);
14558 trackAttached("UnaryArith.BigIntPtrNeg");
14559 break;
14560 case JSOp::Inc:
14561 resultId = writer.bigIntPtrInc(intPtrId);
14562 trackAttached("UnaryArith.BigIntPtrInc");
14563 break;
14564 case JSOp::Dec:
14565 resultId = writer.bigIntPtrDec(intPtrId);
14566 trackAttached("UnaryArith.BigIntPtrDec");
14567 break;
14568 default:
14569 MOZ_CRASH("Unexpected OP");
14570 }
14571
14572 writer.intPtrToBigIntResult(resultId);
14573 writer.returnFromIC();
14574 return AttachDecision::Attach;
14575 }
14576
14577 AttachDecision UnaryArithIRGenerator::tryAttachStringInt32() {
14578 if (!val_.isString()) {
14579 return AttachDecision::NoAction;
14580 }
14581 MOZ_ASSERT(res_.isNumber());
14582
14583 // Case should have been handled by tryAttachBitwise.
14584 MOZ_ASSERT(op_ != JSOp::BitNot);
14585
14586 if (!res_.isInt32()) {
14587 return AttachDecision::NoAction;
14588 }
14589
14590 ValOperandId valId(writer.setInputOperandId(0));
14591 StringOperandId stringId = writer.guardToString(valId);
14592 Int32OperandId intId = writer.guardStringToInt32(stringId);
14593
14594 switch (op_) {
14595 case JSOp::Pos:
14596 writer.loadInt32Result(intId);
14597 trackAttached("UnaryArith.StringInt32Pos");
14598 break;
14599 case JSOp::Neg:
14600 writer.int32NegationResult(intId);
14601 trackAttached("UnaryArith.StringInt32Neg");
14602 break;
14603 case JSOp::Inc:
14604 writer.int32IncResult(intId);
14605 trackAttached("UnaryArith.StringInt32Inc");
14606 break;
14607 case JSOp::Dec:
14608 writer.int32DecResult(intId);
14609 trackAttached("UnaryArith.StringInt32Dec");
14610 break;
14611 case JSOp::ToNumeric:
14612 writer.loadInt32Result(intId);
14613 trackAttached("UnaryArith.StringInt32ToNumeric");
14614 break;
14615 default:
14616 MOZ_CRASH("Unexpected OP");
14617 }
14618
14619 writer.returnFromIC();
14620 return AttachDecision::Attach;
14621 }
14622
14623 AttachDecision UnaryArithIRGenerator::tryAttachStringNumber() {
14624 if (!val_.isString()) {
14625 return AttachDecision::NoAction;
14626 }
14627 MOZ_ASSERT(res_.isNumber());
14628
14629 // Case should have been handled by tryAttachBitwise.
14630 MOZ_ASSERT(op_ != JSOp::BitNot);
14631
14632 ValOperandId valId(writer.setInputOperandId(0));
14633 StringOperandId stringId = writer.guardToString(valId);
14634 NumberOperandId numId = writer.guardStringToNumber(stringId);
14635
14636 Int32OperandId truncatedId;
14637 switch (op_) {
14638 case JSOp::Pos:
14639 writer.loadDoubleResult(numId);
14640 trackAttached("UnaryArith.StringNumberPos");
14641 break;
14642 case JSOp::Neg:
14643 writer.doubleNegationResult(numId);
14644 trackAttached("UnaryArith.StringNumberNeg");
14645 break;
14646 case JSOp::Inc:
14647 writer.doubleIncResult(numId);
14648 trackAttached("UnaryArith.StringNumberInc");
14649 break;
14650 case JSOp::Dec:
14651 writer.doubleDecResult(numId);
14652 trackAttached("UnaryArith.StringNumberDec");
14653 break;
14654 case JSOp::ToNumeric:
14655 writer.loadDoubleResult(numId);
14656 trackAttached("UnaryArith.StringNumberToNumeric");
14657 break;
14658 default:
14659 MOZ_CRASH("Unexpected OP");
14660 }
14661
14662 writer.returnFromIC();
14663 return AttachDecision::Attach;
14664 }
14665
14666 ToPropertyKeyIRGenerator::ToPropertyKeyIRGenerator(JSContext* cx,
14667 HandleScript script,
14668 jsbytecode* pc,
14669 ICState state,
14670 HandleValue val)
14671 : IRGenerator(cx, script, pc, CacheKind::ToPropertyKey, state), val_(val) {}
14672
14673 void ToPropertyKeyIRGenerator::trackAttached(const char* name) {
14674 stubName_ = name ? name : "NotAttached";
14675 #ifdef JS_CACHEIR_SPEW
14676 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14677 sp.valueProperty("val", val_);
14678 }
14679 #endif
14680 }
14681
14682 AttachDecision ToPropertyKeyIRGenerator::tryAttachStub() {
14683 AutoAssertNoPendingException aanpe(cx_);
14684 TRY_ATTACH(tryAttachInt32());
14685 TRY_ATTACH(tryAttachNumber());
14686 TRY_ATTACH(tryAttachString());
14687 TRY_ATTACH(tryAttachSymbol());
14688
14689 trackAttached(IRGenerator::NotAttached);
14690 return AttachDecision::NoAction;
14691 }
14692
14693 AttachDecision ToPropertyKeyIRGenerator::tryAttachInt32() {
14694 if (!val_.isInt32()) {
14695 return AttachDecision::NoAction;
14696 }
14697
14698 ValOperandId valId(writer.setInputOperandId(0));
14699
14700 Int32OperandId intId = writer.guardToInt32(valId);
14701 writer.loadInt32Result(intId);
14702 writer.returnFromIC();
14703
14704 trackAttached("ToPropertyKey.Int32");
14705 return AttachDecision::Attach;
14706 }
14707
14708 AttachDecision ToPropertyKeyIRGenerator::tryAttachNumber() {
14709 if (!val_.isNumber()) {
14710 return AttachDecision::NoAction;
14711 }
14712
14713 // We allow negative zero here because ToPropertyKey(-0.0) is 0.
14714 int32_t unused;
14715 if (!mozilla::NumberEqualsInt32(val_.toNumber(), &unused)) {
14716 return AttachDecision::NoAction;
14717 }
14718
14719 ValOperandId valId(writer.setInputOperandId(0));
14720
14721 Int32OperandId intId = EmitGuardToInt32Index(writer, val_, valId);
14722 writer.loadInt32Result(intId);
14723 writer.returnFromIC();
14724
14725 trackAttached("ToPropertyKey.Number");
14726 return AttachDecision::Attach;
14727 }
14728
14729 AttachDecision ToPropertyKeyIRGenerator::tryAttachString() {
14730 if (!val_.isString()) {
14731 return AttachDecision::NoAction;
14732 }
14733
14734 ValOperandId valId(writer.setInputOperandId(0));
14735
14736 StringOperandId strId = writer.guardToString(valId);
14737 writer.loadStringResult(strId);
14738 writer.returnFromIC();
14739
14740 trackAttached("ToPropertyKey.String");
14741 return AttachDecision::Attach;
14742 }
14743
14744 AttachDecision ToPropertyKeyIRGenerator::tryAttachSymbol() {
14745 if (!val_.isSymbol()) {
14746 return AttachDecision::NoAction;
14747 }
14748
14749 ValOperandId valId(writer.setInputOperandId(0));
14750
14751 SymbolOperandId strId = writer.guardToSymbol(valId);
14752 writer.loadSymbolResult(strId);
14753 writer.returnFromIC();
14754
14755 trackAttached("ToPropertyKey.Symbol");
14756 return AttachDecision::Attach;
14757 }
14758
14759 BinaryArithIRGenerator::BinaryArithIRGenerator(JSContext* cx,
14760 HandleScript script,
14761 jsbytecode* pc, ICState state,
14762 JSOp op, HandleValue lhs,
14763 HandleValue rhs, HandleValue res)
14764 : IRGenerator(cx, script, pc, CacheKind::BinaryArith, state),
14765 op_(op),
14766 lhs_(lhs),
14767 rhs_(rhs),
14768 res_(res) {}
14769
14770 void BinaryArithIRGenerator::trackAttached(const char* name) {
14771 stubName_ = name ? name : "NotAttached";
14772 #ifdef JS_CACHEIR_SPEW
14773 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
14774 sp.opcodeProperty("op", op_);
14775 sp.valueProperty("rhs", rhs_);
14776 sp.valueProperty("lhs", lhs_);
14777 }
14778 #endif
14779 }
14780
14781 AttachDecision BinaryArithIRGenerator::tryAttachStub() {
14782 AutoAssertNoPendingException aanpe(cx_);
14783 // Arithmetic operations with Int32 operands
14784 TRY_ATTACH(tryAttachInt32());
14785
14786 // Bitwise operations with Int32/Double/Boolean/Null/Undefined/String
14787 // operands.
14788 TRY_ATTACH(tryAttachBitwise());
14789
14790 // Arithmetic operations with Double operands. This needs to come after
14791 // tryAttachInt32, as the guards overlap, and we'd prefer to attach the
14792 // more specialized Int32 IC if it is possible.
14793 TRY_ATTACH(tryAttachDouble());
14794
14795 // String x {String,Number,Boolean,Null,Undefined}
14796 TRY_ATTACH(tryAttachStringConcat());
14797
14798 // String x Object
14799 TRY_ATTACH(tryAttachStringObjectConcat());
14800
14801 // Arithmetic operations or bitwise operations with intptr-sized BigInt
14802 // operands.
14803 TRY_ATTACH(tryAttachBigIntPtr());
14804
14805 // Arithmetic operations or bitwise operations with BigInt operands
14806 TRY_ATTACH(tryAttachBigInt());
14807
14808 // Arithmetic operations (without addition) with String x Int32.
14809 TRY_ATTACH(tryAttachStringInt32Arith());
14810
14811 // Arithmetic operations (without addition) with String x Number. This needs
14812 // to come after tryAttachStringInt32Arith, as the guards overlap, and we'd
14813 // prefer to attach the more specialized Int32 IC if it is possible.
14814 TRY_ATTACH(tryAttachStringNumberArith());
14815
14816 TRY_ATTACH(tryAttachDateArith());
14817
14818 trackAttached(IRGenerator::NotAttached);
14819 return AttachDecision::NoAction;
14820 }
14821
14822 AttachDecision BinaryArithIRGenerator::tryAttachBitwise() {
14823 // Only bit-wise and shifts.
14824 if (op_ != JSOp::BitOr && op_ != JSOp::BitXor && op_ != JSOp::BitAnd &&
14825 op_ != JSOp::Lsh && op_ != JSOp::Rsh && op_ != JSOp::Ursh) {
14826 return AttachDecision::NoAction;
14827 }
14828
14829 // Check guard conditions
14830 if (!CanTruncateToInt32(lhs_) || !CanTruncateToInt32(rhs_)) {
14831 return AttachDecision::NoAction;
14832 }
14833
14834 // All ops, with the exception of Ursh, produce Int32 values.
14835 MOZ_ASSERT_IF(op_ != JSOp::Ursh, res_.isInt32());
14836
14837 ValOperandId lhsId(writer.setInputOperandId(0));
14838 ValOperandId rhsId(writer.setInputOperandId(1));
14839
14840 Int32OperandId lhsIntId = EmitTruncateToInt32Guard(writer, lhsId, lhs_);
14841 Int32OperandId rhsIntId = EmitTruncateToInt32Guard(writer, rhsId, rhs_);
14842
14843 switch (op_) {
14844 case JSOp::BitOr:
14845 writer.int32BitOrResult(lhsIntId, rhsIntId);
14846 trackAttached("BinaryArith.BitwiseBitOr");
14847 break;
14848 case JSOp::BitXor:
14849 writer.int32BitXorResult(lhsIntId, rhsIntId);
14850 trackAttached("BinaryArith.BitwiseBitXor");
14851 break;
14852 case JSOp::BitAnd:
14853 writer.int32BitAndResult(lhsIntId, rhsIntId);
14854 trackAttached("BinaryArith.BitwiseBitAnd");
14855 break;
14856 case JSOp::Lsh:
14857 writer.int32LeftShiftResult(lhsIntId, rhsIntId);
14858 trackAttached("BinaryArith.BitwiseLeftShift");
14859 break;
14860 case JSOp::Rsh:
14861 writer.int32RightShiftResult(lhsIntId, rhsIntId);
14862 trackAttached("BinaryArith.BitwiseRightShift");
14863 break;
14864 case JSOp::Ursh:
14865 writer.int32URightShiftResult(lhsIntId, rhsIntId, res_.isDouble());
14866 trackAttached("BinaryArith.BitwiseUnsignedRightShift");
14867 break;
14868 default:
14869 MOZ_CRASH("Unhandled op in tryAttachBitwise");
14870 }
14871
14872 writer.returnFromIC();
14873 return AttachDecision::Attach;
14874 }
14875
14876 AttachDecision BinaryArithIRGenerator::tryAttachDouble() {
14877 // Check valid opcodes
14878 if (op_ != JSOp::Add && op_ != JSOp::Sub && op_ != JSOp::Mul &&
14879 op_ != JSOp::Div && op_ != JSOp::Mod && op_ != JSOp::Pow) {
14880 return AttachDecision::NoAction;
14881 }
14882
14883 // Check guard conditions.
14884 if (!CanConvertToDoubleForToNumber(lhs_) ||
14885 !CanConvertToDoubleForToNumber(rhs_)) {
14886 return AttachDecision::NoAction;
14887 }
14888
14889 ValOperandId lhsId(writer.setInputOperandId(0));
14890 ValOperandId rhsId(writer.setInputOperandId(1));
14891
14892 NumberOperandId lhs = EmitGuardToDoubleForToNumber(writer, lhsId, lhs_);
14893 NumberOperandId rhs = EmitGuardToDoubleForToNumber(writer, rhsId, rhs_);
14894
14895 switch (op_) {
14896 case JSOp::Add:
14897 writer.doubleAddResult(lhs, rhs);
14898 trackAttached("BinaryArith.DoubleAdd");
14899 break;
14900 case JSOp::Sub:
14901 writer.doubleSubResult(lhs, rhs);
14902 trackAttached("BinaryArith.DoubleSub");
14903 break;
14904 case JSOp::Mul:
14905 writer.doubleMulResult(lhs, rhs);
14906 trackAttached("BinaryArith.DoubleMul");
14907 break;
14908 case JSOp::Div:
14909 writer.doubleDivResult(lhs, rhs);
14910 trackAttached("BinaryArith.DoubleDiv");
14911 break;
14912 case JSOp::Mod:
14913 writer.doubleModResult(lhs, rhs);
14914 trackAttached("BinaryArith.DoubleMod");
14915 break;
14916 case JSOp::Pow:
14917 writer.doublePowResult(lhs, rhs);
14918 trackAttached("BinaryArith.DoublePow");
14919 break;
14920 default:
14921 MOZ_CRASH("Unhandled Op");
14922 }
14923 writer.returnFromIC();
14924 return AttachDecision::Attach;
14925 }
14926
14927 AttachDecision BinaryArithIRGenerator::tryAttachInt32() {
14928 // Check guard conditions.
14929 if (!CanConvertToInt32ForToNumber(lhs_) ||
14930 !CanConvertToInt32ForToNumber(rhs_)) {
14931 return AttachDecision::NoAction;
14932 }
14933
14934 // These ICs will failure() if result can't be encoded in an Int32:
14935 // If sample result is not Int32, we should avoid IC.
14936 if (!res_.isInt32()) {
14937 return AttachDecision::NoAction;
14938 }
14939
14940 if (op_ != JSOp::Add && op_ != JSOp::Sub && op_ != JSOp::Mul &&
14941 op_ != JSOp::Div && op_ != JSOp::Mod && op_ != JSOp::Pow) {
14942 return AttachDecision::NoAction;
14943 }
14944
14945 if (op_ == JSOp::Pow && !CanAttachInt32Pow(lhs_, rhs_)) {
14946 return AttachDecision::NoAction;
14947 }
14948
14949 ValOperandId lhsId(writer.setInputOperandId(0));
14950 ValOperandId rhsId(writer.setInputOperandId(1));
14951
14952 Int32OperandId lhsIntId = EmitGuardToInt32ForToNumber(writer, lhsId, lhs_);
14953 Int32OperandId rhsIntId = EmitGuardToInt32ForToNumber(writer, rhsId, rhs_);
14954
14955 switch (op_) {
14956 case JSOp::Add:
14957 writer.int32AddResult(lhsIntId, rhsIntId);
14958 trackAttached("BinaryArith.Int32Add");
14959 break;
14960 case JSOp::Sub:
14961 writer.int32SubResult(lhsIntId, rhsIntId);
14962 trackAttached("BinaryArith.Int32Sub");
14963 break;
14964 case JSOp::Mul:
14965 writer.int32MulResult(lhsIntId, rhsIntId);
14966 trackAttached("BinaryArith.Int32Mul");
14967 break;
14968 case JSOp::Div:
14969 writer.int32DivResult(lhsIntId, rhsIntId);
14970 trackAttached("BinaryArith.Int32Div");
14971 break;
14972 case JSOp::Mod:
14973 writer.int32ModResult(lhsIntId, rhsIntId);
14974 trackAttached("BinaryArith.Int32Mod");
14975 break;
14976 case JSOp::Pow:
14977 writer.int32PowResult(lhsIntId, rhsIntId);
14978 trackAttached("BinaryArith.Int32Pow");
14979 break;
14980 default:
14981 MOZ_CRASH("Unhandled op in tryAttachInt32");
14982 }
14983
14984 writer.returnFromIC();
14985 return AttachDecision::Attach;
14986 }
14987
14988 AttachDecision BinaryArithIRGenerator::tryAttachStringConcat() {
14989 // Only Addition
14990 if (op_ != JSOp::Add) {
14991 return AttachDecision::NoAction;
14992 }
14993
14994 // One side must be a string, the other side a primitive value we can easily
14995 // convert to a string.
14996 if (!(lhs_.isString() && CanConvertToString(rhs_)) &&
14997 !(CanConvertToString(lhs_) && rhs_.isString())) {
14998 return AttachDecision::NoAction;
14999 }
15000
15001 JitCode* code = cx_->zone()->jitZone()->ensureStubExists(
15002 cx_, JitZone::StubKind::StringConcat);
15003 if (!code) {
15004 cx_->recoverFromOutOfMemory();
15005 return AttachDecision::NoAction;
15006 }
15007
15008 ValOperandId lhsId(writer.setInputOperandId(0));
15009 ValOperandId rhsId(writer.setInputOperandId(1));
15010
15011 StringOperandId lhsStrId = emitToStringGuard(lhsId, lhs_);
15012 StringOperandId rhsStrId = emitToStringGuard(rhsId, rhs_);
15013
15014 writer.concatStringsResult(lhsStrId, rhsStrId, code);
15015
15016 writer.returnFromIC();
15017 trackAttached("BinaryArith.StringConcat");
15018 return AttachDecision::Attach;
15019 }
15020
15021 AttachDecision BinaryArithIRGenerator::tryAttachStringObjectConcat() {
15022 // Only Addition
15023 if (op_ != JSOp::Add) {
15024 return AttachDecision::NoAction;
15025 }
15026
15027 // Check Guards
15028 if (!(lhs_.isObject() && rhs_.isString()) &&
15029 !(lhs_.isString() && rhs_.isObject()))
15030 return AttachDecision::NoAction;
15031
15032 ValOperandId lhsId(writer.setInputOperandId(0));
15033 ValOperandId rhsId(writer.setInputOperandId(1));
15034
15035 // This guard is actually overly tight, as the runtime
15036 // helper can handle lhs or rhs being a string, so long
15037 // as the other is an object.
15038 if (lhs_.isString()) {
15039 writer.guardToString(lhsId);
15040 writer.guardToObject(rhsId);
15041 } else {
15042 writer.guardToObject(lhsId);
15043 writer.guardToString(rhsId);
15044 }
15045
15046 writer.callStringObjectConcatResult(lhsId, rhsId);
15047
15048 writer.returnFromIC();
15049 trackAttached("BinaryArith.StringObjectConcat");
15050 return AttachDecision::Attach;
15051 }
15052
15053 AttachDecision BinaryArithIRGenerator::tryAttachBigInt() {
15054 // Check Guards
15055 if (!lhs_.isBigInt() || !rhs_.isBigInt()) {
15056 return AttachDecision::NoAction;
15057 }
15058
15059 switch (op_) {
15060 case JSOp::Add:
15061 case JSOp::Sub:
15062 case JSOp::Mul:
15063 case JSOp::Div:
15064 case JSOp::Mod:
15065 case JSOp::Pow:
15066 // Arithmetic operations.
15067 break;
15068
15069 case JSOp::BitOr:
15070 case JSOp::BitXor:
15071 case JSOp::BitAnd:
15072 case JSOp::Lsh:
15073 case JSOp::Rsh:
15074 // Bitwise operations.
15075 break;
15076
15077 default:
15078 return AttachDecision::NoAction;
15079 }
15080
15081 ValOperandId lhsId(writer.setInputOperandId(0));
15082 ValOperandId rhsId(writer.setInputOperandId(1));
15083
15084 BigIntOperandId lhsBigIntId = writer.guardToBigInt(lhsId);
15085 BigIntOperandId rhsBigIntId = writer.guardToBigInt(rhsId);
15086
15087 switch (op_) {
15088 case JSOp::Add:
15089 writer.bigIntAddResult(lhsBigIntId, rhsBigIntId);
15090 trackAttached("BinaryArith.BigIntAdd");
15091 break;
15092 case JSOp::Sub:
15093 writer.bigIntSubResult(lhsBigIntId, rhsBigIntId);
15094 trackAttached("BinaryArith.BigIntSub");
15095 break;
15096 case JSOp::Mul:
15097 writer.bigIntMulResult(lhsBigIntId, rhsBigIntId);
15098 trackAttached("BinaryArith.BigIntMul");
15099 break;
15100 case JSOp::Div:
15101 writer.bigIntDivResult(lhsBigIntId, rhsBigIntId);
15102 trackAttached("BinaryArith.BigIntDiv");
15103 break;
15104 case JSOp::Mod:
15105 writer.bigIntModResult(lhsBigIntId, rhsBigIntId);
15106 trackAttached("BinaryArith.BigIntMod");
15107 break;
15108 case JSOp::Pow:
15109 writer.bigIntPowResult(lhsBigIntId, rhsBigIntId);
15110 trackAttached("BinaryArith.BigIntPow");
15111 break;
15112 case JSOp::BitOr:
15113 writer.bigIntBitOrResult(lhsBigIntId, rhsBigIntId);
15114 trackAttached("BinaryArith.BigIntBitOr");
15115 break;
15116 case JSOp::BitXor:
15117 writer.bigIntBitXorResult(lhsBigIntId, rhsBigIntId);
15118 trackAttached("BinaryArith.BigIntBitXor");
15119 break;
15120 case JSOp::BitAnd:
15121 writer.bigIntBitAndResult(lhsBigIntId, rhsBigIntId);
15122 trackAttached("BinaryArith.BigIntBitAnd");
15123 break;
15124 case JSOp::Lsh:
15125 writer.bigIntLeftShiftResult(lhsBigIntId, rhsBigIntId);
15126 trackAttached("BinaryArith.BigIntLeftShift");
15127 break;
15128 case JSOp::Rsh:
15129 writer.bigIntRightShiftResult(lhsBigIntId, rhsBigIntId);
15130 trackAttached("BinaryArith.BigIntRightShift");
15131 break;
15132 default:
15133 MOZ_CRASH("Unhandled op in tryAttachBigInt");
15134 }
15135
15136 writer.returnFromIC();
15137 return AttachDecision::Attach;
15138 }
15139
15140 AttachDecision BinaryArithIRGenerator::tryAttachBigIntPtr() {
15141 // Check Guards
15142 if (!lhs_.isBigInt() || !rhs_.isBigInt()) {
15143 return AttachDecision::NoAction;
15144 }
15145
15146 switch (op_) {
15147 case JSOp::Add:
15148 case JSOp::Sub:
15149 case JSOp::Mul:
15150 case JSOp::Div:
15151 case JSOp::Mod:
15152 case JSOp::Pow:
15153 // Arithmetic operations.
15154 break;
15155
15156 case JSOp::BitOr:
15157 case JSOp::BitXor:
15158 case JSOp::BitAnd:
15159 case JSOp::Lsh:
15160 case JSOp::Rsh:
15161 // Bitwise operations.
15162 break;
15163
15164 default:
15165 return AttachDecision::NoAction;
15166 }
15167
15168 intptr_t lhs;
15169 intptr_t rhs;
15170 if (!BigInt::isIntPtr(lhs_.toBigInt(), &lhs) ||
15171 !BigInt::isIntPtr(rhs_.toBigInt(), &rhs)) {
15172 return AttachDecision::NoAction;
15173 }
15174
15175 using CheckedIntPtr = mozilla::CheckedInt<intptr_t>;
15176
15177 switch (op_) {
15178 case JSOp::Add: {
15179 auto result = CheckedIntPtr(lhs) + rhs;
15180 if (result.isValid()) {
15181 break;
15182 }
15183 return AttachDecision::NoAction;
15184 }
15185 case JSOp::Sub: {
15186 auto result = CheckedIntPtr(lhs) - rhs;
15187 if (result.isValid()) {
15188 break;
15189 }
15190 return AttachDecision::NoAction;
15191 }
15192 case JSOp::Mul: {
15193 auto result = CheckedIntPtr(lhs) * rhs;
15194 if (result.isValid()) {
15195 break;
15196 }
15197 return AttachDecision::NoAction;
15198 }
15199 case JSOp::Div: {
15200 auto result = CheckedIntPtr(lhs) / rhs;
15201 if (result.isValid()) {
15202 break;
15203 }
15204 return AttachDecision::NoAction;
15205 }
15206 case JSOp::Mod: {
15207 // We can't use mozilla::CheckedInt here, because it disallows negative
15208 // inputs.
15209 if (rhs != 0) {
15210 break;
15211 }
15212 return AttachDecision::NoAction;
15213 }
15214 case JSOp::Pow: {
15215 intptr_t result;
15216 if (BigInt::powIntPtr(lhs, rhs, &result)) {
15217 break;
15218 }
15219 return AttachDecision::NoAction;
15220 }
15221 case JSOp::BitOr:
15222 case JSOp::BitXor:
15223 case JSOp::BitAnd: {
15224 // Bitwise operations always return an intptr-sized result.
15225 break;
15226 }
15227 case JSOp::Lsh: {
15228 if (lhs == 0 || rhs <= 0) {
15229 break;
15230 }
15231 if (size_t(rhs) < BigInt::DigitBits) {
15232 intptr_t result = lhs << rhs;
15233 if ((result >> rhs) == lhs) {
15234 break;
15235 }
15236 }
15237 return AttachDecision::NoAction;
15238 }
15239 case JSOp::Rsh: {
15240 if (lhs == 0 || rhs >= 0) {
15241 break;
15242 }
15243 if (rhs > -intptr_t(BigInt::DigitBits)) {
15244 intptr_t result = lhs << -rhs;
15245 if ((result >> -rhs) == lhs) {
15246 break;
15247 }
15248 }
15249 return AttachDecision::NoAction;
15250 }
15251 default:
15252 MOZ_CRASH("Unexpected OP");
15253 }
15254
15255 ValOperandId lhsId(writer.setInputOperandId(0));
15256 ValOperandId rhsId(writer.setInputOperandId(1));
15257
15258 BigIntOperandId lhsBigIntId = writer.guardToBigInt(lhsId);
15259 BigIntOperandId rhsBigIntId = writer.guardToBigInt(rhsId);
15260
15261 IntPtrOperandId lhsIntPtrId = writer.bigIntToIntPtr(lhsBigIntId);
15262 IntPtrOperandId rhsIntPtrId = writer.bigIntToIntPtr(rhsBigIntId);
15263
15264 IntPtrOperandId resultId;
15265 switch (op_) {
15266 case JSOp::Add: {
15267 resultId = writer.bigIntPtrAdd(lhsIntPtrId, rhsIntPtrId);
15268 trackAttached("BinaryArith.BigIntPtr.Add");
15269 break;
15270 }
15271 case JSOp::Sub: {
15272 resultId = writer.bigIntPtrSub(lhsIntPtrId, rhsIntPtrId);
15273 trackAttached("BinaryArith.BigIntPtr.Sub");
15274 break;
15275 }
15276 case JSOp::Mul: {
15277 resultId = writer.bigIntPtrMul(lhsIntPtrId, rhsIntPtrId);
15278 trackAttached("BinaryArith.BigIntPtr.Mul");
15279 break;
15280 }
15281 case JSOp::Div: {
15282 resultId = writer.bigIntPtrDiv(lhsIntPtrId, rhsIntPtrId);
15283 trackAttached("BinaryArith.BigIntPtr.Div");
15284 break;
15285 }
15286 case JSOp::Mod: {
15287 resultId = writer.bigIntPtrMod(lhsIntPtrId, rhsIntPtrId);
15288 trackAttached("BinaryArith.BigIntPtr.Mod");
15289 break;
15290 }
15291 case JSOp::Pow: {
15292 resultId = writer.bigIntPtrPow(lhsIntPtrId, rhsIntPtrId);
15293 trackAttached("BinaryArith.BigIntPtr.Pow");
15294 break;
15295 }
15296 case JSOp::BitOr: {
15297 resultId = writer.bigIntPtrBitOr(lhsIntPtrId, rhsIntPtrId);
15298 trackAttached("BinaryArith.BigIntPtr.BitOr");
15299 break;
15300 }
15301 case JSOp::BitXor: {
15302 resultId = writer.bigIntPtrBitXor(lhsIntPtrId, rhsIntPtrId);
15303 trackAttached("BinaryArith.BigIntPtr.BitXor");
15304 break;
15305 }
15306 case JSOp::BitAnd: {
15307 resultId = writer.bigIntPtrBitAnd(lhsIntPtrId, rhsIntPtrId);
15308 trackAttached("BinaryArith.BigIntPtr.BitAnd");
15309 break;
15310 }
15311 case JSOp::Lsh: {
15312 resultId = writer.bigIntPtrLeftShift(lhsIntPtrId, rhsIntPtrId);
15313 trackAttached("BinaryArith.BigIntPtr.LeftShift");
15314 break;
15315 }
15316 case JSOp::Rsh: {
15317 resultId = writer.bigIntPtrRightShift(lhsIntPtrId, rhsIntPtrId);
15318 trackAttached("BinaryArith.BigIntPtr.RightShift");
15319 break;
15320 }
15321 default:
15322 MOZ_CRASH("Unexpected OP");
15323 }
15324
15325 writer.intPtrToBigIntResult(resultId);
15326 writer.returnFromIC();
15327 return AttachDecision::Attach;
15328 }
15329
15330 AttachDecision BinaryArithIRGenerator::tryAttachStringInt32Arith() {
15331 // Check for either int32 x string or string x int32.
15332 if (!(lhs_.isInt32() && rhs_.isString()) &&
15333 !(lhs_.isString() && rhs_.isInt32())) {
15334 return AttachDecision::NoAction;
15335 }
15336
15337 // The created ICs will fail if the result can't be encoded as as int32.
15338 // Thus skip this IC, if the sample result is not an int32.
15339 if (!res_.isInt32()) {
15340 return AttachDecision::NoAction;
15341 }
15342
15343 // Must _not_ support Add, because it would be string concatenation instead.
15344 // For Pow we can't easily determine the CanAttachInt32Pow conditions so we
15345 // reject that as well.
15346 if (op_ != JSOp::Sub && op_ != JSOp::Mul && op_ != JSOp::Div &&
15347 op_ != JSOp::Mod) {
15348 return AttachDecision::NoAction;
15349 }
15350
15351 // The string operand must be convertable to an int32 value.
15352 JSString* str = lhs_.isString() ? lhs_.toString() : rhs_.toString();
15353
15354 double num;
15355 if (!StringToNumber(cx_, str, &num)) {
15356 cx_->recoverFromOutOfMemory();
15357 return AttachDecision::NoAction;
15358 }
15359
15360 int32_t unused;
15361 if (!mozilla::NumberIsInt32(num, &unused)) {
15362 return AttachDecision::NoAction;
15363 }
15364
15365 ValOperandId lhsId(writer.setInputOperandId(0));
15366 ValOperandId rhsId(writer.setInputOperandId(1));
15367
15368 auto guardToInt32 = [&](ValOperandId id, const Value& v) {
15369 if (v.isInt32()) {
15370 return writer.guardToInt32(id);
15371 }
15372
15373 MOZ_ASSERT(v.isString());
15374 StringOperandId strId = writer.guardToString(id);
15375 return writer.guardStringToInt32(strId);
15376 };
15377
15378 Int32OperandId lhsIntId = guardToInt32(lhsId, lhs_);
15379 Int32OperandId rhsIntId = guardToInt32(rhsId, rhs_);
15380
15381 switch (op_) {
15382 case JSOp::Sub:
15383 writer.int32SubResult(lhsIntId, rhsIntId);
15384 trackAttached("BinaryArith.StringInt32Sub");
15385 break;
15386 case JSOp::Mul:
15387 writer.int32MulResult(lhsIntId, rhsIntId);
15388 trackAttached("BinaryArith.StringInt32Mul");
15389 break;
15390 case JSOp::Div:
15391 writer.int32DivResult(lhsIntId, rhsIntId);
15392 trackAttached("BinaryArith.StringInt32Div");
15393 break;
15394 case JSOp::Mod:
15395 writer.int32ModResult(lhsIntId, rhsIntId);
15396 trackAttached("BinaryArith.StringInt32Mod");
15397 break;
15398 default:
15399 MOZ_CRASH("Unhandled op in tryAttachStringInt32Arith");
15400 }
15401
15402 writer.returnFromIC();
15403 return AttachDecision::Attach;
15404 }
15405
15406 AttachDecision BinaryArithIRGenerator::tryAttachStringNumberArith() {
15407 // Check for either number x string or string x number.
15408 if (!(lhs_.isNumber() && rhs_.isString()) &&
15409 !(lhs_.isString() && rhs_.isNumber())) {
15410 return AttachDecision::NoAction;
15411 }
15412
15413 // Must _not_ support Add, because it would be string concatenation instead.
15414 if (op_ != JSOp::Sub && op_ != JSOp::Mul && op_ != JSOp::Div &&
15415 op_ != JSOp::Mod && op_ != JSOp::Pow) {
15416 return AttachDecision::NoAction;
15417 }
15418
15419 ValOperandId lhsId(writer.setInputOperandId(0));
15420 ValOperandId rhsId(writer.setInputOperandId(1));
15421
15422 auto guardToNumber = [&](ValOperandId id, const Value& v) {
15423 if (v.isNumber()) {
15424 return writer.guardIsNumber(id);
15425 }
15426
15427 MOZ_ASSERT(v.isString());
15428 StringOperandId strId = writer.guardToString(id);
15429 return writer.guardStringToNumber(strId);
15430 };
15431
15432 NumberOperandId lhsIntId = guardToNumber(lhsId, lhs_);
15433 NumberOperandId rhsIntId = guardToNumber(rhsId, rhs_);
15434
15435 switch (op_) {
15436 case JSOp::Sub:
15437 writer.doubleSubResult(lhsIntId, rhsIntId);
15438 trackAttached("BinaryArith.StringNumberSub");
15439 break;
15440 case JSOp::Mul:
15441 writer.doubleMulResult(lhsIntId, rhsIntId);
15442 trackAttached("BinaryArith.StringNumberMul");
15443 break;
15444 case JSOp::Div:
15445 writer.doubleDivResult(lhsIntId, rhsIntId);
15446 trackAttached("BinaryArith.StringNumberDiv");
15447 break;
15448 case JSOp::Mod:
15449 writer.doubleModResult(lhsIntId, rhsIntId);
15450 trackAttached("BinaryArith.StringNumberMod");
15451 break;
15452 case JSOp::Pow:
15453 writer.doublePowResult(lhsIntId, rhsIntId);
15454 trackAttached("BinaryArith.StringNumberPow");
15455 break;
15456 default:
15457 MOZ_CRASH("Unhandled op in tryAttachStringNumberArith");
15458 }
15459
15460 writer.returnFromIC();
15461 return AttachDecision::Attach;
15462 }
15463
15464 static bool CheckPropertyIsNativeFunction(JSContext* cx, JSObject* obj,
15465 jsbytecode* pc, PropertyKey propKey,
15466 JSNative nativeFn, JSFunction** fn,
15467 NativeObject** holder, size_t* slot) {
15468 Maybe<PropertyInfo> prop;
15469 NativeGetPropKind kind =
15470 CanAttachNativeGetProp(cx, obj, propKey, holder, &prop, pc);
15471 if (kind != NativeGetPropKind::Slot) {
15472 return false;
15473 }
15474
15475 MOZ_ASSERT(holder);
15476 MOZ_ASSERT(prop->isDataProperty());
15477
15478 *slot = prop->slot();
15479 Value calleeVal = (*holder)->getSlot(*slot);
15480 if (!calleeVal.isObject() || !calleeVal.toObject().is<JSFunction>()) {
15481 return false;
15482 }
15483
15484 if (!IsNativeFunction(calleeVal, nativeFn)) {
15485 return false;
15486 }
15487
15488 *fn = &calleeVal.toObject().as<JSFunction>();
15489 return true;
15490 }
15491
15492 static void EmitGuardPropertyIsNativeFunction(CacheIRWriter& writer,
15493 JSObject* dateObj, JSFunction* fn,
15494 NativeObject* holder, size_t slot,
15495 ObjOperandId objId) {
15496 MOZ_ASSERT(holder);
15497 ObjOperandId holderId =
15498 EmitReadSlotGuard(writer, &dateObj->as<NativeObject>(), holder, objId);
15499 ValOperandId calleeValId = EmitLoadSlot(writer, holder, holderId, slot);
15500 ObjOperandId calleeId = writer.guardToObject(calleeValId);
15501 writer.guardSpecificFunction(calleeId, fn);
15502 }
15503
15504 AttachDecision BinaryArithIRGenerator::tryAttachDateArith() {
15505 // Only support subtractions
15506 if (op_ != JSOp::Sub) {
15507 return AttachDecision::NoAction;
15508 }
15509
15510 // At least one side must be an object.
15511 if (!lhs_.isObject() && !rhs_.isObject()) {
15512 return AttachDecision::NoAction;
15513 }
15514
15515 // Must be either object or numbers.
15516 if (!lhs_.isObject() && !lhs_.isNumber()) {
15517 return AttachDecision::NoAction;
15518 }
15519
15520 if (!rhs_.isObject() && !rhs_.isNumber()) {
15521 return AttachDecision::NoAction;
15522 }
15523
15524 // We can only operate on Date objects.
15525 if (lhs_.isObject() && !lhs_.toObject().is<DateObject>()) {
15526 return AttachDecision::NoAction;
15527 }
15528
15529 if (rhs_.isObject() && !rhs_.toObject().is<DateObject>()) {
15530 return AttachDecision::NoAction;
15531 }
15532
15533 JSFunction* lhsDateValueOfFn = nullptr;
15534 NativeObject* lhsDateValueOfHolder = nullptr;
15535 size_t lhsDateValueOfSlot;
15536
15537 JSFunction* lhsToPrimitiveFn = nullptr;
15538 NativeObject* lhsToPrimitiveHolder = nullptr;
15539 size_t lhsToPrimitiveSlot;
15540
15541 if (lhs_.isObject()) {
15542 if (!CheckPropertyIsNativeFunction(
15543 cx_, &lhs_.toObject(), pc_, NameToId(cx_->names().valueOf),
15544 date_valueOf, &lhsDateValueOfFn, &lhsDateValueOfHolder,
15545 &lhsDateValueOfSlot)) {
15546 return AttachDecision::NoAction;
15547 }
15548
15549 if (!CheckPropertyIsNativeFunction(
15550 cx_, &lhs_.toObject(), pc_,
15551 PropertyKey::Symbol(cx_->wellKnownSymbols().toPrimitive),
15552 date_toPrimitive, &lhsToPrimitiveFn, &lhsToPrimitiveHolder,
15553 &lhsToPrimitiveSlot)) {
15554 return AttachDecision::NoAction;
15555 }
15556 }
15557
15558 JSFunction* rhsDateValueOfFn = nullptr;
15559 NativeObject* rhsDateValueOfHolder = nullptr;
15560 size_t rhsDateValueOfSlot;
15561
15562 JSFunction* rhsToPrimitiveFn = nullptr;
15563 NativeObject* rhsToPrimitiveHolder = nullptr;
15564 size_t rhsToPrimitiveSlot;
15565
15566 if (rhs_.isObject()) {
15567 if (!CheckPropertyIsNativeFunction(
15568 cx_, &rhs_.toObject(), pc_, NameToId(cx_->names().valueOf),
15569 date_valueOf, &rhsDateValueOfFn, &rhsDateValueOfHolder,
15570 &rhsDateValueOfSlot)) {
15571 return AttachDecision::NoAction;
15572 }
15573
15574 if (!CheckPropertyIsNativeFunction(
15575 cx_, &rhs_.toObject(), pc_,
15576 PropertyKey::Symbol(cx_->wellKnownSymbols().toPrimitive),
15577 date_toPrimitive, &rhsToPrimitiveFn, &rhsToPrimitiveHolder,
15578 &rhsToPrimitiveSlot)) {
15579 return AttachDecision::NoAction;
15580 }
15581 }
15582
15583 ValOperandId lhsId(writer.setInputOperandId(0));
15584 ValOperandId rhsId(writer.setInputOperandId(1));
15585
15586 NumberOperandId lhsNumId;
15587 NumberOperandId rhsNumId;
15588
15589 if (lhs_.isObject()) {
15590 ObjOperandId lhsObjId = writer.guardToObject(lhsId);
15591 // The shape guard in EmitGuardPropertyIsNativeFunction ensures the object
15592 // is a Date object.
15593 EmitGuardPropertyIsNativeFunction(writer, &lhs_.toObject(),
15594 lhsDateValueOfFn, lhsDateValueOfHolder,
15595 lhsDateValueOfSlot, lhsObjId);
15596 EmitGuardPropertyIsNativeFunction(writer, &lhs_.toObject(),
15597 lhsToPrimitiveFn, lhsToPrimitiveHolder,
15598 lhsToPrimitiveSlot, lhsObjId);
15599
15600 ValOperandId lhsUtcValId =
15601 writer.loadFixedSlot(lhsObjId, DateObject::offsetOfUTCTimeSlot());
15602 lhsNumId = writer.guardIsNumber(lhsUtcValId);
15603 } else {
15604 MOZ_ASSERT(lhs_.isNumber());
15605 lhsNumId = writer.guardIsNumber(lhsId);
15606 }
15607
15608 if (rhs_.isObject()) {
15609 ObjOperandId rhsObjId = writer.guardToObject(rhsId);
15610 EmitGuardPropertyIsNativeFunction(writer, &rhs_.toObject(),
15611 rhsDateValueOfFn, rhsDateValueOfHolder,
15612 rhsDateValueOfSlot, rhsObjId);
15613 EmitGuardPropertyIsNativeFunction(writer, &rhs_.toObject(),
15614 rhsToPrimitiveFn, rhsToPrimitiveHolder,
15615 rhsToPrimitiveSlot, rhsObjId);
15616
15617 ValOperandId rhsUtcValId =
15618 writer.loadFixedSlot(rhsObjId, DateObject::offsetOfUTCTimeSlot());
15619 rhsNumId = writer.guardIsNumber(rhsUtcValId);
15620 } else {
15621 MOZ_ASSERT(rhs_.isNumber());
15622 rhsNumId = writer.guardIsNumber(rhsId);
15623 }
15624
15625 writer.doubleSubResult(lhsNumId, rhsNumId);
15626 trackAttached("BinaryArith.DateSub");
15627
15628 writer.returnFromIC();
15629 return AttachDecision::Attach;
15630 }
15631
15632 NewArrayIRGenerator::NewArrayIRGenerator(JSContext* cx, HandleScript script,
15633 jsbytecode* pc, ICState state, JSOp op,
15634 HandleObject templateObj,
15635 BaselineFrame* frame)
15636 : IRGenerator(cx, script, pc, CacheKind::NewArray, state, frame),
15637 #ifdef JS_CACHEIR_SPEW
15638 op_(op),
15639 #endif
15640 templateObject_(templateObj) {
15641 MOZ_ASSERT(templateObject_);
15642 }
15643
15644 void NewArrayIRGenerator::trackAttached(const char* name) {
15645 stubName_ = name ? name : "NotAttached";
15646 #ifdef JS_CACHEIR_SPEW
15647 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
15648 sp.opcodeProperty("op", op_);
15649 }
15650 #endif
15651 }
15652
15653 AttachDecision NewArrayIRGenerator::tryAttachArrayObject() {
15654 ArrayObject* arrayObj = &templateObject_->as<ArrayObject>();
15655
15656 MOZ_ASSERT(arrayObj->numUsedFixedSlots() == 0);
15657 MOZ_ASSERT(arrayObj->numDynamicSlots() == 0);
15658 MOZ_ASSERT(!arrayObj->isSharedMemory());
15659
15660 // The macro assembler only supports creating arrays with fixed elements.
15661 if (arrayObj->hasDynamicElements()) {
15662 return AttachDecision::NoAction;
15663 }
15664
15665 // Stub doesn't support metadata builder
15666 if (cx_->realm()->hasAllocationMetadataBuilder()) {
15667 return AttachDecision::NoAction;
15668 }
15669
15670 writer.guardNoAllocationMetadataBuilder(
15671 cx_->realm()->addressOfMetadataBuilder());
15672
15673 gc::AllocSite* site = maybeCreateAllocSite();
15674 if (!site) {
15675 return AttachDecision::NoAction;
15676 }
15677
15678 Shape* shape = arrayObj->shape();
15679 uint32_t length = arrayObj->length();
15680
15681 writer.newArrayObjectResult(length, shape, site);
15682
15683 writer.returnFromIC();
15684
15685 trackAttached("NewArray.Object");
15686 return AttachDecision::Attach;
15687 }
15688
15689 AttachDecision NewArrayIRGenerator::tryAttachStub() {
15690 AutoAssertNoPendingException aanpe(cx_);
15691
15692 TRY_ATTACH(tryAttachArrayObject());
15693
15694 trackAttached(IRGenerator::NotAttached);
15695 return AttachDecision::NoAction;
15696 }
15697
15698 NewObjectIRGenerator::NewObjectIRGenerator(JSContext* cx, HandleScript script,
15699 jsbytecode* pc, ICState state,
15700 JSOp op, HandleObject templateObj,
15701 BaselineFrame* frame)
15702 : IRGenerator(cx, script, pc, CacheKind::NewObject, state, frame),
15703 #ifdef JS_CACHEIR_SPEW
15704 op_(op),
15705 #endif
15706 templateObject_(templateObj) {
15707 MOZ_ASSERT(templateObject_);
15708 }
15709
15710 void NewObjectIRGenerator::trackAttached(const char* name) {
15711 stubName_ = name ? name : "NotAttached";
15712 #ifdef JS_CACHEIR_SPEW
15713 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
15714 sp.opcodeProperty("op", op_);
15715 }
15716 #endif
15717 }
15718
15719 AttachDecision NewObjectIRGenerator::tryAttachPlainObject() {
15720 // Don't optimize allocations with too many dynamic slots. We use an unrolled
15721 // loop when initializing slots and this avoids generating too much code.
15722 static const uint32_t MaxDynamicSlotsToOptimize = 64;
15723
15724 NativeObject* nativeObj = &templateObject_->as<NativeObject>();
15725 MOZ_ASSERT(nativeObj->is<PlainObject>());
15726
15727 // Stub doesn't support metadata builder
15728 if (cx_->realm()->hasAllocationMetadataBuilder()) {
15729 return AttachDecision::NoAction;
15730 }
15731
15732 if (nativeObj->numDynamicSlots() > MaxDynamicSlotsToOptimize) {
15733 return AttachDecision::NoAction;
15734 }
15735
15736 MOZ_ASSERT(!nativeObj->hasDynamicElements());
15737 MOZ_ASSERT(!nativeObj->isSharedMemory());
15738
15739 gc::AllocSite* site = maybeCreateAllocSite();
15740 if (!site) {
15741 return AttachDecision::NoAction;
15742 }
15743
15744 uint32_t numFixedSlots = nativeObj->numUsedFixedSlots();
15745 uint32_t numDynamicSlots = nativeObj->numDynamicSlots();
15746 gc::AllocKind allocKind = nativeObj->allocKindForTenure();
15747 Shape* shape = nativeObj->shape();
15748
15749 writer.guardNoAllocationMetadataBuilder(
15750 cx_->realm()->addressOfMetadataBuilder());
15751 writer.newPlainObjectResult(numFixedSlots, numDynamicSlots, allocKind, shape,
15752 site);
15753
15754 writer.returnFromIC();
15755
15756 trackAttached("NewObject.PlainObject");
15757 return AttachDecision::Attach;
15758 }
15759
15760 AttachDecision NewObjectIRGenerator::tryAttachStub() {
15761 AutoAssertNoPendingException aanpe(cx_);
15762
15763 TRY_ATTACH(tryAttachPlainObject());
15764
15765 trackAttached(IRGenerator::NotAttached);
15766 return AttachDecision::NoAction;
15767 }
15768
15769 LambdaIRGenerator::LambdaIRGenerator(JSContext* cx, HandleScript script,
15770 jsbytecode* pc, ICState state, JSOp op,
15771 Handle<JSFunction*> canonicalFunction,
15772 BaselineFrame* frame)
15773 : IRGenerator(cx, script, pc, CacheKind::Lambda, state, frame),
15774 #ifdef JS_CACHEIR_SPEW
15775 op_(op),
15776 #endif
15777 canonicalFunction_(canonicalFunction) {
15778 MOZ_ASSERT(canonicalFunction_);
15779 }
15780
15781 void LambdaIRGenerator::trackAttached(const char* name) {
15782 stubName_ = name ? name : "NotAttached";
15783 #ifdef JS_CACHEIR_SPEW
15784 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
15785 sp.opcodeProperty("op", op_);
15786 }
15787 #endif
15788 }
15789
15790 AttachDecision LambdaIRGenerator::tryAttachFunctionClone() {
15791 // Don't optimize asm.js module functions.
15792 if (canonicalFunction_->isNativeFun()) {
15793 MOZ_ASSERT(IsAsmJSModule(canonicalFunction_));
15794 return AttachDecision::NoAction;
15795 }
15796
15797 // Stub doesn't support metadata builder.
15798 if (cx_->realm()->hasAllocationMetadataBuilder()) {
15799 return AttachDecision::NoAction;
15800 }
15801
15802 gc::AllocSite* site = maybeCreateAllocSite();
15803 if (!site) {
15804 return AttachDecision::NoAction;
15805 }
15806
15807 writer.guardNoAllocationMetadataBuilder(
15808 cx_->realm()->addressOfMetadataBuilder());
15809
15810 gc::AllocKind allocKind = canonicalFunction_->getAllocKind();
15811 MOZ_ASSERT(allocKind == gc::AllocKind::FUNCTION ||
15812 allocKind == gc::AllocKind::FUNCTION_EXTENDED);
15813 writer.newFunctionCloneResult(canonicalFunction_, allocKind, site);
15814 writer.returnFromIC();
15815
15816 trackAttached("Lambda.FunctionClone");
15817 return AttachDecision::Attach;
15818 }
15819
15820 AttachDecision LambdaIRGenerator::tryAttachStub() {
15821 AutoAssertNoPendingException aanpe(cx_);
15822
15823 TRY_ATTACH(tryAttachFunctionClone());
15824
15825 trackAttached(IRGenerator::NotAttached);
15826 return AttachDecision::NoAction;
15827 }
15828
15829 CloseIterIRGenerator::CloseIterIRGenerator(JSContext* cx, HandleScript script,
15830 jsbytecode* pc, ICState state,
15831 HandleObject iter,
15832 CompletionKind kind)
15833 : IRGenerator(cx, script, pc, CacheKind::CloseIter, state),
15834 iter_(iter),
15835 kind_(kind) {}
15836
15837 void CloseIterIRGenerator::trackAttached(const char* name) {
15838 #ifdef JS_CACHEIR_SPEW
15839 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
15840 sp.valueProperty("iter", ObjectValue(*iter_));
15841 }
15842 #endif
15843 }
15844
15845 AttachDecision CloseIterIRGenerator::tryAttachNoReturnMethod() {
15846 Maybe<PropertyInfo> prop;
15847 NativeObject* holder = nullptr;
15848
15849 // If we can guard that the iterator does not have a |return| method,
15850 // then this CloseIter is a no-op.
15851 NativeGetPropKind kind = CanAttachNativeGetProp(
15852 cx_, iter_, NameToId(cx_->names().return_), &holder, &prop, pc_);
15853 if (kind != NativeGetPropKind::Missing) {
15854 return AttachDecision::NoAction;
15855 }
15856 MOZ_ASSERT(!holder);
15857
15858 ObjOperandId objId(writer.setInputOperandId(0));
15859
15860 EmitMissingPropGuard(writer, &iter_->as<NativeObject>(), objId);
15861
15862 // There is no return method, so we don't have to do anything.
15863 writer.returnFromIC();
15864
15865 trackAttached("CloseIter.NoReturn");
15866 return AttachDecision::Attach;
15867 }
15868
15869 AttachDecision CloseIterIRGenerator::tryAttachScriptedReturn() {
15870 Maybe<PropertyInfo> prop;
15871 NativeObject* holder = nullptr;
15872
15873 NativeGetPropKind kind = CanAttachNativeGetProp(
15874 cx_, iter_, NameToId(cx_->names().return_), &holder, &prop, pc_);
15875 if (kind != NativeGetPropKind::Slot) {
15876 return AttachDecision::NoAction;
15877 }
15878 MOZ_ASSERT(holder);
15879 MOZ_ASSERT(prop->isDataProperty());
15880
15881 size_t slot = prop->slot();
15882 Value calleeVal = holder->getSlot(slot);
15883 if (!calleeVal.isObject() || !calleeVal.toObject().is<JSFunction>()) {
15884 return AttachDecision::NoAction;
15885 }
15886
15887 JSFunction* callee = &calleeVal.toObject().as<JSFunction>();
15888 if (!callee->hasJitEntry()) {
15889 return AttachDecision::NoAction;
15890 }
15891 if (callee->isClassConstructor()) {
15892 return AttachDecision::NoAction;
15893 }
15894
15895 // We don't support cross-realm |return|.
15896 if (cx_->realm() != callee->realm()) {
15897 return AttachDecision::NoAction;
15898 }
15899
15900 ObjOperandId objId(writer.setInputOperandId(0));
15901
15902 ObjOperandId holderId =
15903 EmitReadSlotGuard(writer, &iter_->as<NativeObject>(), holder, objId);
15904
15905 ValOperandId calleeValId = EmitLoadSlot(writer, holder, holderId, slot);
15906 ObjOperandId calleeId = writer.guardToObject(calleeValId);
15907 emitCalleeGuard(calleeId, callee);
15908
15909 writer.closeIterScriptedResult(objId, calleeId, kind_, callee->nargs());
15910
15911 writer.returnFromIC();
15912 trackAttached("CloseIter.ScriptedReturn");
15913
15914 return AttachDecision::Attach;
15915 }
15916
15917 AttachDecision CloseIterIRGenerator::tryAttachStub() {
15918 AutoAssertNoPendingException aanpe(cx_);
15919
15920 TRY_ATTACH(tryAttachNoReturnMethod());
15921 TRY_ATTACH(tryAttachScriptedReturn());
15922
15923 trackAttached(IRGenerator::NotAttached);
15924 return AttachDecision::NoAction;
15925 }
15926
15927 OptimizeGetIteratorIRGenerator::OptimizeGetIteratorIRGenerator(
15928 JSContext* cx, HandleScript script, jsbytecode* pc, ICState state,
15929 HandleValue value)
15930 : IRGenerator(cx, script, pc, CacheKind::OptimizeGetIterator, state),
15931 val_(value) {}
15932
15933 AttachDecision OptimizeGetIteratorIRGenerator::tryAttachStub() {
15934 MOZ_ASSERT(cacheKind_ == CacheKind::OptimizeGetIterator);
15935
15936 AutoAssertNoPendingException aanpe(cx_);
15937
15938 TRY_ATTACH(tryAttachArray());
15939 TRY_ATTACH(tryAttachNotOptimizable());
15940
15941 MOZ_CRASH("Failed to attach unoptimizable case.");
15942 }
15943
15944 AttachDecision OptimizeGetIteratorIRGenerator::tryAttachArray() {
15945 if (!isFirstStub_) {
15946 return AttachDecision::NoAction;
15947 }
15948
15949 // The value must be a packed array.
15950 if (!val_.isObject()) {
15951 return AttachDecision::NoAction;
15952 }
15953 Rooted<JSObject*> obj(cx_, &val_.toObject());
15954 if (!IsArrayWithDefaultIterator<MustBePacked::Yes>(obj, cx_)) {
15955 return AttachDecision::NoAction;
15956 }
15957
15958 ValOperandId valId(writer.setInputOperandId(0));
15959 ObjOperandId objId = writer.guardToObject(valId);
15960
15961 // Guard the object is a packed array with Array.prototype as proto.
15962 MOZ_ASSERT(obj->is<ArrayObject>());
15963 writer.guardShape(objId, obj->shape());
15964 writer.guardArrayIsPacked(objId);
15965
15966 // Guard on Array.prototype[@@iterator] and %ArrayIteratorPrototype%.next.
15967 // This fuse also ensures the prototype chain for Array Iterator is
15968 // maintained and that no return method is added.
15969 writer.guardFuse(RealmFuses::FuseIndex::OptimizeGetIteratorFuse);
15970
15971 writer.loadBooleanResult(true);
15972 writer.returnFromIC();
15973
15974 trackAttached("OptimizeGetIterator.Array.Fuse");
15975 return AttachDecision::Attach;
15976 }
15977
15978 AttachDecision OptimizeGetIteratorIRGenerator::tryAttachNotOptimizable() {
15979 ValOperandId valId(writer.setInputOperandId(0));
15980
15981 writer.loadBooleanResult(false);
15982 writer.returnFromIC();
15983
15984 trackAttached("OptimizeGetIterator.NotOptimizable");
15985 return AttachDecision::Attach;
15986 }
15987
15988 void OptimizeGetIteratorIRGenerator::trackAttached(const char* name) {
15989 stubName_ = name ? name : "NotAttached";
15990
15991 #ifdef JS_CACHEIR_SPEW
15992 if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
15993 sp.valueProperty("val", val_);
15994 }
15995 #endif
15996 }
15997
15998 GetImportIRGenerator::GetImportIRGenerator(JSContext* cx, HandleScript script,
15999 jsbytecode* pc, ICState state)
16000 : IRGenerator(cx, script, pc, CacheKind::GetImport, state) {}
16001
16002 void GetImportIRGenerator::trackAttached(const char* name) {
16003 #ifdef JS_CACHEIR_SPEW
16004 const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name);
16005 (void)sp; // Silence unused warning
16006 #endif
16007 }
16008
16009 AttachDecision GetImportIRGenerator::tryAttachInitialized() {
16010 ModuleEnvironmentObject* env = GetModuleEnvironmentForScript(script_);
16011 MOZ_ASSERT(env);
16012
16013 jsid id = NameToId(script_->getName(pc_));
16014 ModuleEnvironmentObject* holderEnv;
16015 Maybe<PropertyInfo> prop;
16016 MOZ_ALWAYS_TRUE(env->lookupImport(id, &holderEnv, &prop));
16017
16018 // Imports are initialized by this point except in rare circumstances.
16019 if (holderEnv->getSlot(prop->slot()).isMagic(JS_UNINITIALIZED_LEXICAL)) {
16020 return AttachDecision::NoAction;
16021 }
16022
16023 ObjOperandId holderEnvId = writer.loadObject(holderEnv);
16024 EmitLoadSlotResult(writer, holderEnvId, holderEnv, *prop);
16025 writer.returnFromIC();
16026
16027 trackAttached("GetImport.Initialized");
16028 return AttachDecision::Attach;
16029 }
16030
16031 AttachDecision GetImportIRGenerator::tryAttachStub() {
16032 AutoAssertNoPendingException aanpe(cx_);
16033
16034 TRY_ATTACH(tryAttachInitialized());
16035
16036 trackAttached(IRGenerator::NotAttached);
16037 return AttachDecision::NoAction;
16038 }
16039
16040 #ifdef JS_SIMULATOR
16041 bool js::jit::CallAnyNative(JSContext* cx, unsigned argc, Value* vp) {
16042 CallArgs args = CallArgsFromVp(argc, vp);
16043 JSObject* calleeObj = &args.callee();
16044
16045 MOZ_ASSERT(calleeObj->is<JSFunction>());
16046 auto* calleeFunc = &calleeObj->as<JSFunction>();
16047 MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());
16048
16049 JSNative native = calleeFunc->native();
16050 return native(cx, args.length(), args.base());
16051 }
16052
16053 const void* js::jit::RedirectedCallAnyNative() {
16054 // The simulator requires native calls to be redirected to a
16055 // special swi instruction. If we are calling an arbitrary native
16056 // function, we can't wrap the real target ahead of time, so we
16057 // call a wrapper function (CallAnyNative) that calls the target
16058 // itself, and redirect that wrapper.
16059 JSNative target = CallAnyNative;
16060 void* rawPtr = JS_FUNC_TO_DATA_PTR(void*, target);
16061 void* redirected = Simulator::RedirectNativeFunction(rawPtr, Args_General3);
16062 return redirected;
16063 }
16064 #endif