1/*
2 * Copyright (C) 2013-2018 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#pragma once
27
28#if ENABLE(DFG_JIT)
29
30#include "DFGGraph.h"
31
32namespace JSC { namespace DFG {
33
34template<typename AbstractStateType>
35class SafeToExecuteEdge {
36public:
37 SafeToExecuteEdge(AbstractStateType& state)
38 : m_state(state)
39 {
40 }
41
42 void operator()(Node*, Edge edge)
43 {
44 m_maySeeEmptyChild |= !!(m_state.forNode(edge).m_type & SpecEmpty);
45
46 switch (edge.useKind()) {
47 case UntypedUse:
48 case Int32Use:
49 case DoubleRepUse:
50 case DoubleRepRealUse:
51 case Int52RepUse:
52 case NumberUse:
53 case RealNumberUse:
54 case BooleanUse:
55 case CellUse:
56 case CellOrOtherUse:
57 case ObjectUse:
58 case ArrayUse:
59 case FunctionUse:
60 case FinalObjectUse:
61 case RegExpObjectUse:
62 case ProxyObjectUse:
63 case DerivedArrayUse:
64 case MapObjectUse:
65 case SetObjectUse:
66 case WeakMapObjectUse:
67 case WeakSetObjectUse:
68 case DataViewObjectUse:
69 case ObjectOrOtherUse:
70 case StringIdentUse:
71 case StringUse:
72 case StringOrOtherUse:
73 case SymbolUse:
74 case BigIntUse:
75 case StringObjectUse:
76 case StringOrStringObjectUse:
77 case NotStringVarUse:
78 case NotSymbolUse:
79 case NotCellUse:
80 case OtherUse:
81 case MiscUse:
82 case AnyIntUse:
83 case DoubleRepAnyIntUse:
84 return;
85
86 case KnownInt32Use:
87 if (m_state.forNode(edge).m_type & ~SpecInt32Only)
88 m_result = false;
89 return;
90
91 case KnownBooleanUse:
92 if (m_state.forNode(edge).m_type & ~SpecBoolean)
93 m_result = false;
94 return;
95
96 case KnownCellUse:
97 if (m_state.forNode(edge).m_type & ~SpecCell)
98 m_result = false;
99 return;
100
101 case KnownStringUse:
102 if (m_state.forNode(edge).m_type & ~SpecString)
103 m_result = false;
104 return;
105
106 case KnownPrimitiveUse:
107 if (m_state.forNode(edge).m_type & ~(SpecHeapTop & ~SpecObject))
108 m_result = false;
109 return;
110
111 case KnownOtherUse:
112 if (m_state.forNode(edge).m_type & ~SpecOther)
113 m_result = false;
114 return;
115
116 case LastUseKind:
117 RELEASE_ASSERT_NOT_REACHED();
118 break;
119 }
120 RELEASE_ASSERT_NOT_REACHED();
121 }
122
123 bool result() const { return m_result; }
124 bool maySeeEmptyChild() const { return m_maySeeEmptyChild; }
125private:
126 AbstractStateType& m_state;
127 bool m_result { true };
128 bool m_maySeeEmptyChild { false };
129};
130
131// Determines if it's safe to execute a node within the given abstract state. This may
132// return false conservatively. If it returns true, then you can hoist the given node
133// up to the given point and expect that it will not crash. It also guarantees that the
134// node will not produce a malformed JSValue or object pointer when executed in the
135// given state. But this doesn't guarantee that the node will produce the result you
136// wanted. For example, you may have a GetByOffset from a prototype that only makes
137// semantic sense if you've also checked that some nearer prototype doesn't also have
138// a property of the same name. This could still return true even if that check hadn't
139// been performed in the given abstract state. That's fine though: the load can still
140// safely execute before that check, so long as that check continues to guard any
141// user-observable things done to the loaded value.
142template<typename AbstractStateType>
143bool safeToExecute(AbstractStateType& state, Graph& graph, Node* node, bool ignoreEmptyChildren = false)
144{
145 SafeToExecuteEdge<AbstractStateType> safeToExecuteEdge(state);
146 DFG_NODE_DO_TO_CHILDREN(graph, node, safeToExecuteEdge);
147 if (!safeToExecuteEdge.result())
148 return false;
149
150 if (!ignoreEmptyChildren && safeToExecuteEdge.maySeeEmptyChild()) {
151 // We conservatively assume if the empty value flows into a node,
152 // it might not be able to handle it (e.g, crash). In general, the bytecode generator
153 // emits code in such a way that most node types don't need to worry about the empty value
154 // because they will never see it. However, code motion has to consider the empty
155 // value so it does not insert/move nodes to a place where they will crash. E.g, the
156 // type check hoisting phase needs to insert CheckStructureOrEmpty instead of CheckStructure
157 // for hoisted structure checks because it can not guarantee that a particular local is not
158 // the empty value.
159 switch (node->op()) {
160 case CheckNotEmpty:
161 case CheckStructureOrEmpty:
162 break;
163 default:
164 return false;
165 }
166 }
167
168 // NOTE: This tends to lie when it comes to effectful nodes, because it knows that they aren't going to
169 // get hoisted anyway.
170
171 switch (node->op()) {
172 case JSConstant:
173 case DoubleConstant:
174 case Int52Constant:
175 case LazyJSConstant:
176 case Identity:
177 case IdentityWithProfile:
178 case ToThis:
179 case CreateThis:
180 case ObjectCreate:
181 case ObjectKeys:
182 case GetCallee:
183 case SetCallee:
184 case GetArgumentCountIncludingThis:
185 case SetArgumentCountIncludingThis:
186 case GetRestLength:
187 case GetLocal:
188 case SetLocal:
189 case PutStack:
190 case KillStack:
191 case GetStack:
192 case MovHint:
193 case ZombieHint:
194 case ExitOK:
195 case Phantom:
196 case Upsilon:
197 case Phi:
198 case Flush:
199 case PhantomLocal:
200 case SetArgument:
201 case ArithBitNot:
202 case ArithBitAnd:
203 case ArithBitOr:
204 case ArithBitXor:
205 case BitLShift:
206 case BitRShift:
207 case BitURShift:
208 case ValueToInt32:
209 case UInt32ToNumber:
210 case DoubleAsInt32:
211 case ArithAdd:
212 case ArithClz32:
213 case ArithSub:
214 case ArithNegate:
215 case ArithMul:
216 case ArithIMul:
217 case ArithDiv:
218 case ArithMod:
219 case ArithAbs:
220 case ArithMin:
221 case ArithMax:
222 case ArithPow:
223 case ArithRandom:
224 case ArithSqrt:
225 case ArithFRound:
226 case ArithRound:
227 case ArithFloor:
228 case ArithCeil:
229 case ArithTrunc:
230 case ArithUnary:
231 case ValueBitAnd:
232 case ValueBitXor:
233 case ValueBitOr:
234 case ValueBitNot:
235 case ValueNegate:
236 case ValueAdd:
237 case ValueSub:
238 case ValueMul:
239 case ValueDiv:
240 case TryGetById:
241 case DeleteById:
242 case DeleteByVal:
243 case GetById:
244 case GetByIdWithThis:
245 case GetByValWithThis:
246 case GetByIdFlush:
247 case GetByIdDirect:
248 case GetByIdDirectFlush:
249 case PutById:
250 case PutByIdFlush:
251 case PutByIdWithThis:
252 case PutByValWithThis:
253 case PutByIdDirect:
254 case PutGetterById:
255 case PutSetterById:
256 case PutGetterSetterById:
257 case PutGetterByVal:
258 case PutSetterByVal:
259 case DefineDataProperty:
260 case DefineAccessorProperty:
261 case CheckStructure:
262 case CheckStructureOrEmpty:
263 case GetExecutable:
264 case GetButterfly:
265 case CallDOMGetter:
266 case CallDOM:
267 case CheckSubClass:
268 case CheckArray:
269 case Arrayify:
270 case ArrayifyToStructure:
271 case GetScope:
272 case SkipScope:
273 case GetGlobalObject:
274 case GetGlobalThis:
275 case GetClosureVar:
276 case PutClosureVar:
277 case GetGlobalVar:
278 case GetGlobalLexicalVariable:
279 case PutGlobalVariable:
280 case CheckCell:
281 case CheckBadCell:
282 case CheckNotEmpty:
283 case AssertNotEmpty:
284 case CheckStringIdent:
285 case RegExpExec:
286 case RegExpExecNonGlobalOrSticky:
287 case RegExpTest:
288 case RegExpMatchFast:
289 case RegExpMatchFastGlobal:
290 case CompareLess:
291 case CompareLessEq:
292 case CompareGreater:
293 case CompareGreaterEq:
294 case CompareBelow:
295 case CompareBelowEq:
296 case CompareEq:
297 case CompareStrictEq:
298 case CompareEqPtr:
299 case SameValue:
300 case Call:
301 case DirectCall:
302 case TailCallInlinedCaller:
303 case DirectTailCallInlinedCaller:
304 case Construct:
305 case DirectConstruct:
306 case CallVarargs:
307 case CallEval:
308 case TailCallVarargsInlinedCaller:
309 case TailCallForwardVarargsInlinedCaller:
310 case ConstructVarargs:
311 case LoadVarargs:
312 case CallForwardVarargs:
313 case ConstructForwardVarargs:
314 case NewObject:
315 case NewArray:
316 case NewArrayWithSize:
317 case NewArrayBuffer:
318 case NewArrayWithSpread:
319 case Spread:
320 case NewRegexp:
321 case NewSymbol:
322 case ProfileType:
323 case ProfileControlFlow:
324 case CheckTypeInfoFlags:
325 case ParseInt:
326 case OverridesHasInstance:
327 case InstanceOf:
328 case InstanceOfCustom:
329 case IsEmpty:
330 case IsUndefined:
331 case IsUndefinedOrNull:
332 case IsBoolean:
333 case IsNumber:
334 case NumberIsInteger:
335 case IsObject:
336 case IsObjectOrNull:
337 case IsFunction:
338 case IsCellWithType:
339 case IsTypedArrayView:
340 case TypeOf:
341 case LogicalNot:
342 case CallObjectConstructor:
343 case ToPrimitive:
344 case ToString:
345 case ToNumber:
346 case ToObject:
347 case NumberToStringWithRadix:
348 case NumberToStringWithValidRadixConstant:
349 case SetFunctionName:
350 case StrCat:
351 case CallStringConstructor:
352 case NewStringObject:
353 case MakeRope:
354 case InByVal:
355 case InById:
356 case HasOwnProperty:
357 case PushWithScope:
358 case CreateActivation:
359 case CreateDirectArguments:
360 case CreateScopedArguments:
361 case CreateClonedArguments:
362 case GetFromArguments:
363 case GetArgument:
364 case PutToArguments:
365 case NewFunction:
366 case NewGeneratorFunction:
367 case NewAsyncGeneratorFunction:
368 case NewAsyncFunction:
369 case Jump:
370 case Branch:
371 case Switch:
372 case EntrySwitch:
373 case Return:
374 case TailCall:
375 case DirectTailCall:
376 case TailCallVarargs:
377 case TailCallForwardVarargs:
378 case Throw:
379 case ThrowStaticError:
380 case CountExecution:
381 case SuperSamplerBegin:
382 case SuperSamplerEnd:
383 case ForceOSRExit:
384 case CPUIntrinsic:
385 case CheckTraps:
386 case LogShadowChickenPrologue:
387 case LogShadowChickenTail:
388 case StringFromCharCode:
389 case NewTypedArray:
390 case Unreachable:
391 case ExtractOSREntryLocal:
392 case ExtractCatchLocal:
393 case ClearCatchLocals:
394 case CheckTierUpInLoop:
395 case CheckTierUpAtReturn:
396 case CheckTierUpAndOSREnter:
397 case LoopHint:
398 case InvalidationPoint:
399 case NotifyWrite:
400 case CheckInBounds:
401 case ConstantStoragePointer:
402 case Check:
403 case CheckVarargs:
404 case MultiPutByOffset:
405 case ValueRep:
406 case DoubleRep:
407 case Int52Rep:
408 case BooleanToNumber:
409 case FiatInt52:
410 case GetGetter:
411 case GetSetter:
412 case GetEnumerableLength:
413 case HasGenericProperty:
414 case HasStructureProperty:
415 case HasIndexedProperty:
416 case GetDirectPname:
417 case GetPropertyEnumerator:
418 case GetEnumeratorStructurePname:
419 case GetEnumeratorGenericPname:
420 case ToIndexString:
421 case PhantomNewObject:
422 case PhantomNewFunction:
423 case PhantomNewGeneratorFunction:
424 case PhantomNewAsyncGeneratorFunction:
425 case PhantomNewAsyncFunction:
426 case PhantomCreateActivation:
427 case PhantomNewRegexp:
428 case PutHint:
429 case CheckStructureImmediate:
430 case MaterializeNewObject:
431 case MaterializeCreateActivation:
432 case PhantomDirectArguments:
433 case PhantomCreateRest:
434 case PhantomSpread:
435 case PhantomNewArrayWithSpread:
436 case PhantomNewArrayBuffer:
437 case PhantomClonedArguments:
438 case GetMyArgumentByVal:
439 case GetMyArgumentByValOutOfBounds:
440 case ForwardVarargs:
441 case CreateRest:
442 case GetPrototypeOf:
443 case StringReplace:
444 case StringReplaceRegExp:
445 case GetRegExpObjectLastIndex:
446 case SetRegExpObjectLastIndex:
447 case RecordRegExpCachedResult:
448 case GetDynamicVar:
449 case PutDynamicVar:
450 case ResolveScopeForHoistingFuncDeclInEval:
451 case ResolveScope:
452 case MapHash:
453 case NormalizeMapKey:
454 case StringValueOf:
455 case StringSlice:
456 case ToLowerCase:
457 case GetMapBucket:
458 case GetMapBucketHead:
459 case GetMapBucketNext:
460 case LoadKeyFromMapBucket:
461 case LoadValueFromMapBucket:
462 case ExtractValueFromWeakMapGet:
463 case WeakMapGet:
464 case WeakSetAdd:
465 case WeakMapSet:
466 case AtomicsAdd:
467 case AtomicsAnd:
468 case AtomicsCompareExchange:
469 case AtomicsExchange:
470 case AtomicsLoad:
471 case AtomicsOr:
472 case AtomicsStore:
473 case AtomicsSub:
474 case AtomicsXor:
475 case AtomicsIsLockFree:
476 case InitializeEntrypointArguments:
477 case MatchStructure:
478 case DataViewGetInt:
479 case DataViewGetFloat:
480 return true;
481
482 case ArraySlice:
483 case ArrayIndexOf: {
484 // You could plausibly move this code around as long as you proved the
485 // incoming array base structure is an original array at the hoisted location.
486 // Instead of doing that extra work, we just conservatively return false.
487 return false;
488 }
489
490 case BottomValue:
491 // If in doubt, assume that this isn't safe to execute, just because we have no way of
492 // compiling this node.
493 return false;
494
495 case StoreBarrier:
496 case FencedStoreBarrier:
497 case PutStructure:
498 case NukeStructureAndSetButterfly:
499 // We conservatively assume that these cannot be put anywhere, which forces the compiler to
500 // keep them exactly where they were. This is sort of overkill since the clobberize effects
501 // already force these things to be ordered precisely. I'm just not confident enough in my
502 // effect based memory model to rely solely on that right now.
503 return false;
504
505 case FilterCallLinkStatus:
506 case FilterGetByIdStatus:
507 case FilterPutByIdStatus:
508 case FilterInByIdStatus:
509 // We don't want these to be moved anywhere other than where we put them, since we want them
510 // to capture "profiling" at the point in control flow here the user put them.
511 return false;
512
513 case GetByVal:
514 case GetIndexedPropertyStorage:
515 case GetArrayLength:
516 case GetVectorLength:
517 case ArrayPop:
518 case StringCharAt:
519 case StringCharCodeAt:
520 return node->arrayMode().alreadyChecked(graph, node, state.forNode(graph.child(node, 0)));
521
522 case ArrayPush:
523 return node->arrayMode().alreadyChecked(graph, node, state.forNode(graph.varArgChild(node, 1)));
524
525 case GetTypedArrayByteOffset:
526 return !(state.forNode(node->child1()).m_type & ~(SpecTypedArrayView));
527
528 case PutByValDirect:
529 case PutByVal:
530 case PutByValAlias:
531 return node->arrayMode().modeForPut().alreadyChecked(
532 graph, node, state.forNode(graph.varArgChild(node, 0)));
533
534 case AllocatePropertyStorage:
535 case ReallocatePropertyStorage:
536 return state.forNode(node->child1()).m_structure.isSubsetOf(
537 RegisteredStructureSet(node->transition()->previous));
538
539 case GetByOffset:
540 case GetGetterSetterByOffset:
541 case PutByOffset: {
542 StorageAccessData& data = node->storageAccessData();
543 PropertyOffset offset = data.offset;
544 // Graph::isSafeToLoad() is all about proofs derived from PropertyConditions. Those don't
545 // know anything about inferred types. But if we have a proof derived from watching a
546 // structure that has a type proof, then the next case below will deal with it.
547 if (state.structureClobberState() == StructuresAreWatched) {
548 if (JSObject* knownBase = node->child1()->dynamicCastConstant<JSObject*>(graph.m_vm)) {
549 if (graph.isSafeToLoad(knownBase, offset))
550 return true;
551 }
552 }
553
554 StructureAbstractValue& value = state.forNode(node->child1()).m_structure;
555 if (value.isInfinite())
556 return false;
557 for (unsigned i = value.size(); i--;) {
558 Structure* thisStructure = value[i].get();
559 if (!thisStructure->isValidOffset(offset))
560 return false;
561 }
562 return true;
563 }
564
565 case MultiGetByOffset: {
566 // We can't always guarantee that the MultiGetByOffset is safe to execute if it
567 // contains loads from prototypes. If the load requires a check in IR, which is rare, then
568 // we currently claim that we don't know if it's safe to execute because finding that
569 // check in the abstract state would be hard. If the load requires watchpoints, we just
570 // check if we're not in a clobbered state (i.e. in between a side effect and an
571 // invalidation point).
572 for (const MultiGetByOffsetCase& getCase : node->multiGetByOffsetData().cases) {
573 GetByOffsetMethod method = getCase.method();
574 switch (method.kind()) {
575 case GetByOffsetMethod::Invalid:
576 RELEASE_ASSERT_NOT_REACHED();
577 break;
578 case GetByOffsetMethod::Constant: // OK because constants are always safe to execute.
579 case GetByOffsetMethod::Load: // OK because the MultiGetByOffset has its own checks for loading from self.
580 break;
581 case GetByOffsetMethod::LoadFromPrototype:
582 // Only OK if the state isn't clobbered. That's almost always the case.
583 if (state.structureClobberState() != StructuresAreWatched)
584 return false;
585 if (!graph.isSafeToLoad(method.prototype()->cast<JSObject*>(), method.offset()))
586 return false;
587 break;
588 }
589 }
590 return true;
591 }
592
593 case DataViewSet:
594 return false;
595
596 case SetAdd:
597 case MapSet:
598 return false;
599
600 case LastNodeType:
601 RELEASE_ASSERT_NOT_REACHED();
602 return false;
603 }
604
605 RELEASE_ASSERT_NOT_REACHED();
606 return false;
607}
608
609} } // namespace JSC::DFG
610
611#endif // ENABLE(DFG_JIT)
612