JIT-generated store barrier code should assume the buffer pointer and capacity to...
[WebKit-https.git] / Source / JavaScriptCore / jit / Repatch.cpp
1 /*
2  * Copyright (C) 2011-2015 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 #include "config.h"
27 #include "Repatch.h"
28
29 #if ENABLE(JIT)
30
31 #include "AccessorCallJITStubRoutine.h"
32 #include "BinarySwitch.h"
33 #include "CCallHelpers.h"
34 #include "DFGOperations.h"
35 #include "DFGSpeculativeJIT.h"
36 #include "FTLThunks.h"
37 #include "GCAwareJITStubRoutine.h"
38 #include "GetterSetter.h"
39 #include "JIT.h"
40 #include "JITInlines.h"
41 #include "LinkBuffer.h"
42 #include "JSCInlines.h"
43 #include "PolymorphicGetByIdList.h"
44 #include "PolymorphicPutByIdList.h"
45 #include "RegExpMatchesArray.h"
46 #include "RepatchBuffer.h"
47 #include "ScratchRegisterAllocator.h"
48 #include "StackAlignment.h"
49 #include "StructureRareDataInlines.h"
50 #include "StructureStubClearingWatchpoint.h"
51 #include "ThunkGenerators.h"
52 #include <wtf/CommaPrinter.h>
53 #include <wtf/ListDump.h>
54 #include <wtf/StringPrintStream.h>
55
56 namespace JSC {
57
58 // Beware: in this code, it is not safe to assume anything about the following registers
59 // that would ordinarily have well-known values:
60 // - tagTypeNumberRegister
61 // - tagMaskRegister
62
63 static FunctionPtr readCallTarget(RepatchBuffer& repatchBuffer, CodeLocationCall call)
64 {
65     FunctionPtr result = MacroAssembler::readCallTarget(call);
66 #if ENABLE(FTL_JIT)
67     CodeBlock* codeBlock = repatchBuffer.codeBlock();
68     if (codeBlock->jitType() == JITCode::FTLJIT) {
69         return FunctionPtr(codeBlock->vm()->ftlThunks->keyForSlowPathCallThunk(
70             MacroAssemblerCodePtr::createFromExecutableAddress(
71                 result.executableAddress())).callTarget());
72     }
73 #else
74     UNUSED_PARAM(repatchBuffer);
75 #endif // ENABLE(FTL_JIT)
76     return result;
77 }
78
79 static void repatchCall(RepatchBuffer& repatchBuffer, CodeLocationCall call, FunctionPtr newCalleeFunction)
80 {
81 #if ENABLE(FTL_JIT)
82     CodeBlock* codeBlock = repatchBuffer.codeBlock();
83     if (codeBlock->jitType() == JITCode::FTLJIT) {
84         VM& vm = *codeBlock->vm();
85         FTL::Thunks& thunks = *vm.ftlThunks;
86         FTL::SlowPathCallKey key = thunks.keyForSlowPathCallThunk(
87             MacroAssemblerCodePtr::createFromExecutableAddress(
88                 MacroAssembler::readCallTarget(call).executableAddress()));
89         key = key.withCallTarget(newCalleeFunction.executableAddress());
90         newCalleeFunction = FunctionPtr(
91             thunks.getSlowPathCallThunk(vm, key).code().executableAddress());
92     }
93 #endif // ENABLE(FTL_JIT)
94     repatchBuffer.relink(call, newCalleeFunction);
95 }
96
97 static void repatchCall(CodeBlock* codeblock, CodeLocationCall call, FunctionPtr newCalleeFunction)
98 {
99     RepatchBuffer repatchBuffer(codeblock);
100     repatchCall(repatchBuffer, call, newCalleeFunction);
101 }
102
103 static void repatchByIdSelfAccess(
104     VM& vm, CodeBlock* codeBlock, StructureStubInfo& stubInfo, Structure* structure,
105     const Identifier& propertyName, PropertyOffset offset, const FunctionPtr &slowPathFunction,
106     bool compact)
107 {
108     if (structure->typeInfo().newImpurePropertyFiresWatchpoints())
109         vm.registerWatchpointForImpureProperty(propertyName, stubInfo.addWatchpoint(codeBlock));
110     
111     RepatchBuffer repatchBuffer(codeBlock);
112
113     // Only optimize once!
114     repatchCall(repatchBuffer, stubInfo.callReturnLocation, slowPathFunction);
115
116     // Patch the structure check & the offset of the load.
117     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(-(intptr_t)stubInfo.patch.deltaCheckImmToCall), bitwise_cast<int32_t>(structure->id()));
118     repatchBuffer.setLoadInstructionIsActive(stubInfo.callReturnLocation.convertibleLoadAtOffset(stubInfo.patch.deltaCallToStorageLoad), isOutOfLineOffset(offset));
119 #if USE(JSVALUE64)
120     if (compact)
121         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToLoadOrStore), offsetRelativeToPatchedStorage(offset));
122     else
123         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToLoadOrStore), offsetRelativeToPatchedStorage(offset));
124 #elif USE(JSVALUE32_64)
125     if (compact) {
126         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToTagLoadOrStore), offsetRelativeToPatchedStorage(offset) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag));
127         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToPayloadLoadOrStore), offsetRelativeToPatchedStorage(offset) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload));
128     } else {
129         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToTagLoadOrStore), offsetRelativeToPatchedStorage(offset) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag));
130         repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToPayloadLoadOrStore), offsetRelativeToPatchedStorage(offset) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload));
131     }
132 #endif
133 }
134
135 static void addStructureTransitionCheck(
136     JSCell* object, Structure* structure, CodeBlock* codeBlock, StructureStubInfo& stubInfo,
137     MacroAssembler& jit, MacroAssembler::JumpList& failureCases, GPRReg scratchGPR)
138 {
139     if (object->structure() == structure && structure->transitionWatchpointSetIsStillValid()) {
140         structure->addTransitionWatchpoint(stubInfo.addWatchpoint(codeBlock));
141         if (!ASSERT_DISABLED) {
142             // If we execute this code, the object must have the structure we expect. Assert
143             // this in debug modes.
144             jit.move(MacroAssembler::TrustedImmPtr(object), scratchGPR);
145             MacroAssembler::Jump ok = branchStructure(
146                 jit,
147                 MacroAssembler::Equal,
148                 MacroAssembler::Address(scratchGPR, JSCell::structureIDOffset()),
149                 structure);
150             jit.abortWithReason(RepatchIneffectiveWatchpoint);
151             ok.link(&jit);
152         }
153         return;
154     }
155     
156     jit.move(MacroAssembler::TrustedImmPtr(object), scratchGPR);
157     failureCases.append(
158         branchStructure(jit,
159             MacroAssembler::NotEqual,
160             MacroAssembler::Address(scratchGPR, JSCell::structureIDOffset()),
161             structure));
162 }
163
164 static void addStructureTransitionCheck(
165     JSValue prototype, CodeBlock* codeBlock, StructureStubInfo& stubInfo,
166     MacroAssembler& jit, MacroAssembler::JumpList& failureCases, GPRReg scratchGPR)
167 {
168     if (prototype.isNull())
169         return;
170     
171     ASSERT(prototype.isCell());
172     
173     addStructureTransitionCheck(
174         prototype.asCell(), prototype.asCell()->structure(), codeBlock, stubInfo, jit,
175         failureCases, scratchGPR);
176 }
177
178 static void replaceWithJump(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo, const MacroAssemblerCodePtr target)
179 {
180     if (MacroAssembler::canJumpReplacePatchableBranch32WithPatch()) {
181         repatchBuffer.replaceWithJump(
182             RepatchBuffer::startOfPatchableBranch32WithPatchOnAddress(
183                 stubInfo.callReturnLocation.dataLabel32AtOffset(
184                     -(intptr_t)stubInfo.patch.deltaCheckImmToCall)),
185             CodeLocationLabel(target));
186         return;
187     }
188     
189     repatchBuffer.relink(
190         stubInfo.callReturnLocation.jumpAtOffset(
191             stubInfo.patch.deltaCallToJump),
192         CodeLocationLabel(target));
193 }
194
195 static void emitRestoreScratch(MacroAssembler& stubJit, bool needToRestoreScratch, GPRReg scratchGPR, MacroAssembler::Jump& success, MacroAssembler::Jump& fail, MacroAssembler::JumpList failureCases)
196 {
197     if (needToRestoreScratch) {
198         stubJit.popToRestore(scratchGPR);
199         
200         success = stubJit.jump();
201         
202         // link failure cases here, so we can pop scratchGPR, and then jump back.
203         failureCases.link(&stubJit);
204         
205         stubJit.popToRestore(scratchGPR);
206         
207         fail = stubJit.jump();
208         return;
209     }
210     
211     success = stubJit.jump();
212 }
213
214 static void linkRestoreScratch(LinkBuffer& patchBuffer, bool needToRestoreScratch, MacroAssembler::Jump success, MacroAssembler::Jump fail, MacroAssembler::JumpList failureCases, CodeLocationLabel successLabel, CodeLocationLabel slowCaseBegin)
215 {
216     patchBuffer.link(success, successLabel);
217         
218     if (needToRestoreScratch) {
219         patchBuffer.link(fail, slowCaseBegin);
220         return;
221     }
222     
223     // link failure cases directly back to normal path
224     patchBuffer.link(failureCases, slowCaseBegin);
225 }
226
227 static void linkRestoreScratch(LinkBuffer& patchBuffer, bool needToRestoreScratch, StructureStubInfo& stubInfo, MacroAssembler::Jump success, MacroAssembler::Jump fail, MacroAssembler::JumpList failureCases)
228 {
229     linkRestoreScratch(patchBuffer, needToRestoreScratch, success, fail, failureCases, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone), stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
230 }
231
232 enum ByIdStubKind {
233     GetValue,
234     GetUndefined,
235     CallGetter,
236     CallCustomGetter,
237     CallSetter,
238     CallCustomSetter
239 };
240
241 static const char* toString(ByIdStubKind kind)
242 {
243     switch (kind) {
244     case GetValue:
245         return "GetValue";
246     case GetUndefined:
247         return "GetUndefined";
248     case CallGetter:
249         return "CallGetter";
250     case CallCustomGetter:
251         return "CallCustomGetter";
252     case CallSetter:
253         return "CallSetter";
254     case CallCustomSetter:
255         return "CallCustomSetter";
256     default:
257         RELEASE_ASSERT_NOT_REACHED();
258         return nullptr;
259     }
260 }
261
262 static ByIdStubKind kindFor(const PropertySlot& slot)
263 {
264     if (slot.isCacheableValue())
265         return GetValue;
266     if (slot.isUnset())
267         return GetUndefined;
268     if (slot.isCacheableCustom())
269         return CallCustomGetter;
270     RELEASE_ASSERT(slot.isCacheableGetter());
271     return CallGetter;
272 }
273
274 static FunctionPtr customFor(const PropertySlot& slot)
275 {
276     if (!slot.isCacheableCustom())
277         return FunctionPtr();
278     return FunctionPtr(slot.customGetter());
279 }
280
281 static ByIdStubKind kindFor(const PutPropertySlot& slot)
282 {
283     RELEASE_ASSERT(!slot.isCacheablePut());
284     if (slot.isCacheableSetter())
285         return CallSetter;
286     RELEASE_ASSERT(slot.isCacheableCustom());
287     return CallCustomSetter;
288 }
289
290 static FunctionPtr customFor(const PutPropertySlot& slot)
291 {
292     if (!slot.isCacheableCustom())
293         return FunctionPtr();
294     return FunctionPtr(slot.customSetter());
295 }
296
297 static bool generateByIdStub(
298     ExecState* exec, ByIdStubKind kind, const Identifier& propertyName,
299     FunctionPtr custom, StructureStubInfo& stubInfo, StructureChain* chain, size_t count,
300     PropertyOffset offset, Structure* structure, bool loadTargetFromProxy, WatchpointSet* watchpointSet,
301     CodeLocationLabel successLabel, CodeLocationLabel slowCaseLabel, RefPtr<JITStubRoutine>& stubRoutine)
302 {
303
304     VM* vm = &exec->vm();
305     GPRReg baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
306     JSValueRegs valueRegs = JSValueRegs(
307 #if USE(JSVALUE32_64)
308         static_cast<GPRReg>(stubInfo.patch.valueTagGPR),
309 #endif
310         static_cast<GPRReg>(stubInfo.patch.valueGPR));
311     GPRReg scratchGPR = TempRegisterSet(stubInfo.patch.usedRegisters).getFreeGPR();
312     bool needToRestoreScratch = scratchGPR == InvalidGPRReg;
313     RELEASE_ASSERT(!needToRestoreScratch || (kind == GetValue || kind == GetUndefined));
314     
315     CCallHelpers stubJit(&exec->vm(), exec->codeBlock());
316     if (needToRestoreScratch) {
317         scratchGPR = AssemblyHelpers::selectScratchGPR(
318             baseGPR, valueRegs.tagGPR(), valueRegs.payloadGPR());
319         stubJit.pushToSave(scratchGPR);
320         needToRestoreScratch = true;
321     }
322     
323     MacroAssembler::JumpList failureCases;
324
325     GPRReg baseForGetGPR;
326     if (loadTargetFromProxy) {
327         baseForGetGPR = valueRegs.payloadGPR();
328         failureCases.append(stubJit.branch8(
329             MacroAssembler::NotEqual, 
330             MacroAssembler::Address(baseGPR, JSCell::typeInfoTypeOffset()), 
331             MacroAssembler::TrustedImm32(PureForwardingProxyType)));
332
333         stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSProxy::targetOffset()), scratchGPR);
334         
335         failureCases.append(branchStructure(stubJit,
336             MacroAssembler::NotEqual, 
337             MacroAssembler::Address(scratchGPR, JSCell::structureIDOffset()),
338             structure));
339     } else {
340         baseForGetGPR = baseGPR;
341
342         failureCases.append(branchStructure(stubJit,
343             MacroAssembler::NotEqual, 
344             MacroAssembler::Address(baseForGetGPR, JSCell::structureIDOffset()), 
345             structure));
346     }
347
348     CodeBlock* codeBlock = exec->codeBlock();
349     if (structure->typeInfo().newImpurePropertyFiresWatchpoints())
350         vm->registerWatchpointForImpureProperty(propertyName, stubInfo.addWatchpoint(codeBlock));
351
352     if (watchpointSet)
353         watchpointSet->add(stubInfo.addWatchpoint(codeBlock));
354
355     Structure* currStructure = structure; 
356     JSObject* protoObject = 0;
357     if (chain) {
358         WriteBarrier<Structure>* it = chain->head();
359         for (unsigned i = 0; i < count; ++i, ++it) {
360             protoObject = asObject(currStructure->prototypeForLookup(exec));
361             Structure* protoStructure = protoObject->structure();
362             if (protoStructure->typeInfo().newImpurePropertyFiresWatchpoints())
363                 vm->registerWatchpointForImpureProperty(propertyName, stubInfo.addWatchpoint(codeBlock));
364             addStructureTransitionCheck(
365                 protoObject, protoStructure, codeBlock, stubInfo, stubJit,
366                 failureCases, scratchGPR);
367             currStructure = it->get();
368         }
369         ASSERT(!protoObject || protoObject->structure() == currStructure);
370     }
371     
372     currStructure->startWatchingPropertyForReplacements(*vm, offset);
373     GPRReg baseForAccessGPR = InvalidGPRReg;
374     if (kind != GetUndefined) {
375         if (chain) {
376             // We could have clobbered scratchGPR earlier, so we have to reload from baseGPR to get the target.
377             if (loadTargetFromProxy)
378                 stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSProxy::targetOffset()), baseForGetGPR);
379             stubJit.move(MacroAssembler::TrustedImmPtr(protoObject), scratchGPR);
380             baseForAccessGPR = scratchGPR;
381         } else {
382             // For proxy objects, we need to do all the Structure checks before moving the baseGPR into
383             // baseForGetGPR because if we fail any of the checks then we would have the wrong value in baseGPR
384             // on the slow path.
385             if (loadTargetFromProxy)
386                 stubJit.move(scratchGPR, baseForGetGPR);
387             baseForAccessGPR = baseForGetGPR;
388         }
389     }
390
391     GPRReg loadedValueGPR = InvalidGPRReg;
392     if (kind == GetUndefined)
393         stubJit.moveTrustedValue(jsUndefined(), valueRegs);
394     else if (kind != CallCustomGetter && kind != CallCustomSetter) {
395         if (kind == GetValue)
396             loadedValueGPR = valueRegs.payloadGPR();
397         else
398             loadedValueGPR = scratchGPR;
399         
400         GPRReg storageGPR;
401         if (isInlineOffset(offset))
402             storageGPR = baseForAccessGPR;
403         else {
404             stubJit.loadPtr(MacroAssembler::Address(baseForAccessGPR, JSObject::butterflyOffset()), loadedValueGPR);
405             storageGPR = loadedValueGPR;
406         }
407         
408 #if USE(JSVALUE64)
409         stubJit.load64(MacroAssembler::Address(storageGPR, offsetRelativeToBase(offset)), loadedValueGPR);
410 #else
411         if (kind == GetValue)
412             stubJit.load32(MacroAssembler::Address(storageGPR, offsetRelativeToBase(offset) + TagOffset), valueRegs.tagGPR());
413         stubJit.load32(MacroAssembler::Address(storageGPR, offsetRelativeToBase(offset) + PayloadOffset), loadedValueGPR);
414 #endif
415     }
416
417     // Stuff for custom getters.
418     MacroAssembler::Call operationCall;
419     MacroAssembler::Call handlerCall;
420
421     // Stuff for JS getters.
422     MacroAssembler::DataLabelPtr addressOfLinkFunctionCheck;
423     MacroAssembler::Call fastPathCall;
424     MacroAssembler::Call slowPathCall;
425     std::unique_ptr<CallLinkInfo> callLinkInfo;
426
427     MacroAssembler::Jump success, fail;
428     if (kind != GetValue && kind != GetUndefined) {
429         // Need to make sure that whenever this call is made in the future, we remember the
430         // place that we made it from. It just so happens to be the place that we are at
431         // right now!
432         stubJit.store32(MacroAssembler::TrustedImm32(exec->locationAsRawBits()),
433             CCallHelpers::tagFor(static_cast<VirtualRegister>(JSStack::ArgumentCount)));
434
435         if (kind == CallGetter || kind == CallSetter) {
436             // Create a JS call using a JS call inline cache. Assume that:
437             //
438             // - SP is aligned and represents the extent of the calling compiler's stack usage.
439             //
440             // - FP is set correctly (i.e. it points to the caller's call frame header).
441             //
442             // - SP - FP is an aligned difference.
443             //
444             // - Any byte between FP (exclusive) and SP (inclusive) could be live in the calling
445             //   code.
446             //
447             // Therefore, we temporarily grow the stack for the purpose of the call and then
448             // shrink it after.
449             
450             callLinkInfo = std::make_unique<CallLinkInfo>();
451             callLinkInfo->callType = CallLinkInfo::Call;
452             callLinkInfo->codeOrigin = stubInfo.codeOrigin;
453             callLinkInfo->calleeGPR = loadedValueGPR;
454             
455             MacroAssembler::JumpList done;
456             
457             // There is a 'this' argument but nothing else.
458             unsigned numberOfParameters = 1;
459             // ... unless we're calling a setter.
460             if (kind == CallSetter)
461                 numberOfParameters++;
462             
463             // Get the accessor; if there ain't one then the result is jsUndefined().
464             if (kind == CallSetter) {
465                 stubJit.loadPtr(
466                     MacroAssembler::Address(loadedValueGPR, GetterSetter::offsetOfSetter()),
467                     loadedValueGPR);
468             } else {
469                 stubJit.loadPtr(
470                     MacroAssembler::Address(loadedValueGPR, GetterSetter::offsetOfGetter()),
471                     loadedValueGPR);
472             }
473             MacroAssembler::Jump returnUndefined = stubJit.branchTestPtr(
474                 MacroAssembler::Zero, loadedValueGPR);
475             
476             unsigned numberOfRegsForCall =
477                 JSStack::CallFrameHeaderSize + numberOfParameters;
478             
479             unsigned numberOfBytesForCall =
480                 numberOfRegsForCall * sizeof(Register) - sizeof(CallerFrameAndPC);
481             
482             unsigned alignedNumberOfBytesForCall =
483                 WTF::roundUpToMultipleOf(stackAlignmentBytes(), numberOfBytesForCall);
484             
485             stubJit.subPtr(
486                 MacroAssembler::TrustedImm32(alignedNumberOfBytesForCall),
487                 MacroAssembler::stackPointerRegister);
488             
489             MacroAssembler::Address calleeFrame = MacroAssembler::Address(
490                 MacroAssembler::stackPointerRegister,
491                 -static_cast<ptrdiff_t>(sizeof(CallerFrameAndPC)));
492             
493             stubJit.store32(
494                 MacroAssembler::TrustedImm32(numberOfParameters),
495                 calleeFrame.withOffset(
496                     JSStack::ArgumentCount * sizeof(Register) + PayloadOffset));
497             
498             stubJit.storeCell(
499                 loadedValueGPR, calleeFrame.withOffset(JSStack::Callee * sizeof(Register)));
500
501             stubJit.storeCell(
502                 baseForGetGPR,
503                 calleeFrame.withOffset(
504                     virtualRegisterForArgument(0).offset() * sizeof(Register)));
505             
506             if (kind == CallSetter) {
507                 stubJit.storeValue(
508                     valueRegs,
509                     calleeFrame.withOffset(
510                         virtualRegisterForArgument(1).offset() * sizeof(Register)));
511             }
512             
513             MacroAssembler::Jump slowCase = stubJit.branchPtrWithPatch(
514                 MacroAssembler::NotEqual, loadedValueGPR, addressOfLinkFunctionCheck,
515                 MacroAssembler::TrustedImmPtr(0));
516             
517             fastPathCall = stubJit.nearCall();
518             
519             stubJit.addPtr(
520                 MacroAssembler::TrustedImm32(alignedNumberOfBytesForCall),
521                 MacroAssembler::stackPointerRegister);
522             if (kind == CallGetter)
523                 stubJit.setupResults(valueRegs);
524             
525             done.append(stubJit.jump());
526             slowCase.link(&stubJit);
527             
528             stubJit.move(loadedValueGPR, GPRInfo::regT0);
529 #if USE(JSVALUE32_64)
530             stubJit.move(MacroAssembler::TrustedImm32(JSValue::CellTag), GPRInfo::regT1);
531 #endif
532             stubJit.move(MacroAssembler::TrustedImmPtr(callLinkInfo.get()), GPRInfo::regT2);
533             slowPathCall = stubJit.nearCall();
534             
535             stubJit.addPtr(
536                 MacroAssembler::TrustedImm32(alignedNumberOfBytesForCall),
537                 MacroAssembler::stackPointerRegister);
538             if (kind == CallGetter)
539                 stubJit.setupResults(valueRegs);
540             
541             done.append(stubJit.jump());
542             returnUndefined.link(&stubJit);
543             
544             if (kind == CallGetter)
545                 stubJit.moveTrustedValue(jsUndefined(), valueRegs);
546             
547             done.link(&stubJit);
548         } else {
549             // getter: EncodedJSValue (*GetValueFunc)(ExecState*, JSObject* slotBase, EncodedJSValue thisValue, PropertyName);
550             // setter: void (*PutValueFunc)(ExecState*, JSObject* base, EncodedJSValue thisObject, EncodedJSValue value);
551 #if USE(JSVALUE64)
552             if (kind == CallCustomGetter)
553                 stubJit.setupArgumentsWithExecState(baseForAccessGPR, baseForGetGPR, MacroAssembler::TrustedImmPtr(propertyName.impl()));
554             else
555                 stubJit.setupArgumentsWithExecState(baseForAccessGPR, baseForGetGPR, valueRegs.gpr());
556 #else
557             if (kind == CallCustomGetter)
558                 stubJit.setupArgumentsWithExecState(baseForAccessGPR, baseForGetGPR, MacroAssembler::TrustedImm32(JSValue::CellTag), MacroAssembler::TrustedImmPtr(propertyName.impl()));
559             else
560                 stubJit.setupArgumentsWithExecState(baseForAccessGPR, baseForGetGPR, MacroAssembler::TrustedImm32(JSValue::CellTag), valueRegs.payloadGPR(), valueRegs.tagGPR());
561 #endif
562             stubJit.storePtr(GPRInfo::callFrameRegister, &vm->topCallFrame);
563
564             operationCall = stubJit.call();
565             if (kind == CallCustomGetter)
566                 stubJit.setupResults(valueRegs);
567             MacroAssembler::Jump noException = stubJit.emitExceptionCheck(CCallHelpers::InvertedExceptionCheck);
568             
569             stubJit.setupArguments(CCallHelpers::TrustedImmPtr(vm), GPRInfo::callFrameRegister);
570             handlerCall = stubJit.call();
571             stubJit.jumpToExceptionHandler();
572             
573             noException.link(&stubJit);
574         }
575     }
576     emitRestoreScratch(stubJit, needToRestoreScratch, scratchGPR, success, fail, failureCases);
577     
578     LinkBuffer patchBuffer(*vm, stubJit, exec->codeBlock(), JITCompilationCanFail);
579     if (patchBuffer.didFailToAllocate())
580         return false;
581     
582     linkRestoreScratch(patchBuffer, needToRestoreScratch, success, fail, failureCases, successLabel, slowCaseLabel);
583     if (kind == CallCustomGetter || kind == CallCustomSetter) {
584         patchBuffer.link(operationCall, custom);
585         patchBuffer.link(handlerCall, lookupExceptionHandler);
586     } else if (kind == CallGetter || kind == CallSetter) {
587         callLinkInfo->hotPathOther = patchBuffer.locationOfNearCall(fastPathCall);
588         callLinkInfo->hotPathBegin = patchBuffer.locationOf(addressOfLinkFunctionCheck);
589         callLinkInfo->callReturnLocation = patchBuffer.locationOfNearCall(slowPathCall);
590
591         ThunkGenerator generator = linkThunkGeneratorFor(
592             CodeForCall, RegisterPreservationNotRequired);
593         patchBuffer.link(
594             slowPathCall, CodeLocationLabel(vm->getCTIStub(generator).code()));
595     }
596     
597     MacroAssemblerCodeRef code = FINALIZE_CODE_FOR(
598         exec->codeBlock(), patchBuffer,
599         ("%s access stub for %s, return point %p",
600             toString(kind), toCString(*exec->codeBlock()).data(),
601             successLabel.executableAddress()));
602     
603     if (kind == CallGetter || kind == CallSetter)
604         stubRoutine = adoptRef(new AccessorCallJITStubRoutine(code, *vm, WTF::move(callLinkInfo)));
605     else
606         stubRoutine = createJITStubRoutine(code, *vm, codeBlock->ownerExecutable(), true);
607     
608     return true;
609 }
610
611 enum InlineCacheAction {
612     GiveUpOnCache,
613     RetryCacheLater,
614     AttemptToCache
615 };
616
617 static InlineCacheAction actionForCell(VM& vm, JSCell* cell)
618 {
619     Structure* structure = cell->structure(vm);
620
621     TypeInfo typeInfo = structure->typeInfo();
622     if (typeInfo.prohibitsPropertyCaching())
623         return GiveUpOnCache;
624
625     if (structure->isUncacheableDictionary()) {
626         if (structure->hasBeenFlattenedBefore())
627             return GiveUpOnCache;
628         // Flattening could have changed the offset, so return early for another try.
629         asObject(cell)->flattenDictionaryObject(vm);
630         return RetryCacheLater;
631     }
632     ASSERT(!structure->isUncacheableDictionary());
633     
634     if (typeInfo.hasImpureGetOwnPropertySlot() && !typeInfo.newImpurePropertyFiresWatchpoints())
635         return GiveUpOnCache;
636
637     return AttemptToCache;
638 }
639
640 static InlineCacheAction tryCacheGetByID(ExecState* exec, JSValue baseValue, const Identifier& propertyName, const PropertySlot& slot, StructureStubInfo& stubInfo)
641 {
642     if (Options::forceICFailure())
643         return GiveUpOnCache;
644     
645     // FIXME: Write a test that proves we need to check for recursion here just
646     // like the interpreter does, then add a check for recursion.
647
648     CodeBlock* codeBlock = exec->codeBlock();
649     VM* vm = &exec->vm();
650
651     if ((isJSArray(baseValue) || isJSString(baseValue)) && propertyName == exec->propertyNames().length) {
652         GPRReg baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
653 #if USE(JSVALUE32_64)
654         GPRReg resultTagGPR = static_cast<GPRReg>(stubInfo.patch.valueTagGPR);
655 #endif
656         GPRReg resultGPR = static_cast<GPRReg>(stubInfo.patch.valueGPR);
657
658         MacroAssembler stubJit;
659
660         if (isJSArray(baseValue)) {
661             GPRReg scratchGPR = TempRegisterSet(stubInfo.patch.usedRegisters).getFreeGPR();
662             bool needToRestoreScratch = false;
663
664             if (scratchGPR == InvalidGPRReg) {
665 #if USE(JSVALUE64)
666                 scratchGPR = AssemblyHelpers::selectScratchGPR(baseGPR, resultGPR);
667 #else
668                 scratchGPR = AssemblyHelpers::selectScratchGPR(baseGPR, resultGPR, resultTagGPR);
669 #endif
670                 stubJit.pushToSave(scratchGPR);
671                 needToRestoreScratch = true;
672             }
673
674             MacroAssembler::JumpList failureCases;
675
676             stubJit.load8(MacroAssembler::Address(baseGPR, JSCell::indexingTypeOffset()), scratchGPR);
677             failureCases.append(stubJit.branchTest32(MacroAssembler::Zero, scratchGPR, MacroAssembler::TrustedImm32(IsArray)));
678             failureCases.append(stubJit.branchTest32(MacroAssembler::Zero, scratchGPR, MacroAssembler::TrustedImm32(IndexingShapeMask)));
679
680             stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR);
681             stubJit.load32(MacroAssembler::Address(scratchGPR, ArrayStorage::lengthOffset()), scratchGPR);
682             failureCases.append(stubJit.branch32(MacroAssembler::LessThan, scratchGPR, MacroAssembler::TrustedImm32(0)));
683
684             stubJit.move(scratchGPR, resultGPR);
685 #if USE(JSVALUE64)
686             stubJit.or64(AssemblyHelpers::TrustedImm64(TagTypeNumber), resultGPR);
687 #elif USE(JSVALUE32_64)
688             stubJit.move(AssemblyHelpers::TrustedImm32(JSValue::Int32Tag), resultTagGPR);
689 #endif
690
691             MacroAssembler::Jump success, fail;
692
693             emitRestoreScratch(stubJit, needToRestoreScratch, scratchGPR, success, fail, failureCases);
694             
695             LinkBuffer patchBuffer(*vm, stubJit, codeBlock, JITCompilationCanFail);
696             if (patchBuffer.didFailToAllocate())
697                 return GiveUpOnCache;
698
699             linkRestoreScratch(patchBuffer, needToRestoreScratch, stubInfo, success, fail, failureCases);
700
701             stubInfo.stubRoutine = FINALIZE_CODE_FOR_STUB(
702                 exec->codeBlock(), patchBuffer,
703                 ("GetById array length stub for %s, return point %p",
704                     toCString(*exec->codeBlock()).data(), stubInfo.callReturnLocation.labelAtOffset(
705                         stubInfo.patch.deltaCallToDone).executableAddress()));
706
707             RepatchBuffer repatchBuffer(codeBlock);
708             replaceWithJump(repatchBuffer, stubInfo, stubInfo.stubRoutine->code().code());
709             repatchCall(repatchBuffer, stubInfo.callReturnLocation, operationGetById);
710
711             return RetryCacheLater;
712         }
713
714         // String.length case
715         MacroAssembler::Jump failure = stubJit.branch8(MacroAssembler::NotEqual, MacroAssembler::Address(baseGPR, JSCell::typeInfoTypeOffset()), MacroAssembler::TrustedImm32(StringType));
716
717         stubJit.load32(MacroAssembler::Address(baseGPR, JSString::offsetOfLength()), resultGPR);
718
719 #if USE(JSVALUE64)
720         stubJit.or64(AssemblyHelpers::TrustedImm64(TagTypeNumber), resultGPR);
721 #elif USE(JSVALUE32_64)
722         stubJit.move(AssemblyHelpers::TrustedImm32(JSValue::Int32Tag), resultTagGPR);
723 #endif
724
725         MacroAssembler::Jump success = stubJit.jump();
726
727         LinkBuffer patchBuffer(*vm, stubJit, codeBlock, JITCompilationCanFail);
728         if (patchBuffer.didFailToAllocate())
729             return GiveUpOnCache;
730         
731         patchBuffer.link(success, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone));
732         patchBuffer.link(failure, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
733
734         stubInfo.stubRoutine = FINALIZE_CODE_FOR_STUB(
735             exec->codeBlock(), patchBuffer,
736             ("GetById string length stub for %s, return point %p",
737                 toCString(*exec->codeBlock()).data(), stubInfo.callReturnLocation.labelAtOffset(
738                     stubInfo.patch.deltaCallToDone).executableAddress()));
739
740         RepatchBuffer repatchBuffer(codeBlock);
741         replaceWithJump(repatchBuffer, stubInfo, stubInfo.stubRoutine->code().code());
742         repatchCall(repatchBuffer, stubInfo.callReturnLocation, operationGetById);
743
744         return RetryCacheLater;
745     }
746
747     // FIXME: Cache property access for immediates.
748     if (!baseValue.isCell())
749         return GiveUpOnCache;
750
751     if (!slot.isCacheable() && !slot.isUnset())
752         return GiveUpOnCache;
753
754     JSCell* baseCell = baseValue.asCell();
755     Structure* structure = baseCell->structure(*vm);
756
757     InlineCacheAction action = actionForCell(*vm, baseCell);
758     if (action != AttemptToCache)
759         return action;
760
761     // Optimize self access.
762     if (slot.isCacheableValue()
763         && slot.slotBase() == baseValue
764         && !slot.watchpointSet()
765         && MacroAssembler::isCompactPtrAlignedAddressOffset(maxOffsetRelativeToPatchedStorage(slot.cachedOffset()))) {
766         structure->startWatchingPropertyForReplacements(*vm, slot.cachedOffset());
767         repatchByIdSelfAccess(*vm, codeBlock, stubInfo, structure, propertyName, slot.cachedOffset(), operationGetByIdBuildList, true);
768         stubInfo.initGetByIdSelf(*vm, codeBlock->ownerExecutable(), structure);
769         return RetryCacheLater;
770     }
771
772     repatchCall(codeBlock, stubInfo.callReturnLocation, operationGetByIdBuildList);
773     return RetryCacheLater;
774 }
775
776 void repatchGetByID(ExecState* exec, JSValue baseValue, const Identifier& propertyName, const PropertySlot& slot, StructureStubInfo& stubInfo)
777 {
778     GCSafeConcurrentJITLocker locker(exec->codeBlock()->m_lock, exec->vm().heap);
779     
780     if (tryCacheGetByID(exec, baseValue, propertyName, slot, stubInfo) == GiveUpOnCache)
781         repatchCall(exec->codeBlock(), stubInfo.callReturnLocation, operationGetById);
782 }
783
784 static void patchJumpToGetByIdStub(CodeBlock* codeBlock, StructureStubInfo& stubInfo, JITStubRoutine* stubRoutine)
785 {
786     RELEASE_ASSERT(stubInfo.accessType == access_get_by_id_list);
787     RepatchBuffer repatchBuffer(codeBlock);
788     if (stubInfo.u.getByIdList.list->didSelfPatching()) {
789         repatchBuffer.relink(
790             stubInfo.callReturnLocation.jumpAtOffset(
791                 stubInfo.patch.deltaCallToJump),
792             CodeLocationLabel(stubRoutine->code().code()));
793         return;
794     }
795     
796     replaceWithJump(repatchBuffer, stubInfo, stubRoutine->code().code());
797 }
798
799 static InlineCacheAction tryBuildGetByIDList(ExecState* exec, JSValue baseValue, const Identifier& ident, const PropertySlot& slot, StructureStubInfo& stubInfo)
800 {
801     if (!baseValue.isCell()
802         || (!slot.isCacheable() && !slot.isUnset()))
803         return GiveUpOnCache;
804
805     JSCell* baseCell = baseValue.asCell();
806     bool loadTargetFromProxy = false;
807     if (baseCell->type() == PureForwardingProxyType) {
808         baseValue = jsCast<JSProxy*>(baseCell)->target();
809         baseCell = baseValue.asCell();
810         loadTargetFromProxy = true;
811     }
812
813     VM* vm = &exec->vm();
814     CodeBlock* codeBlock = exec->codeBlock();
815
816     InlineCacheAction action = actionForCell(*vm, baseCell);
817     if (action != AttemptToCache)
818         return action;
819
820     Structure* structure = baseCell->structure(*vm);
821     TypeInfo typeInfo = structure->typeInfo();
822
823     if (stubInfo.patch.spillMode == NeedToSpill) {
824         // We cannot do as much inline caching if the registers were not flushed prior to this GetById. In particular,
825         // non-Value cached properties require planting calls, which requires registers to have been flushed. Thus,
826         // if registers were not flushed, don't do non-Value caching.
827         if (!slot.isCacheableValue() && !slot.isUnset())
828             return GiveUpOnCache;
829     }
830
831     PropertyOffset offset = slot.isUnset() ? invalidOffset : slot.cachedOffset();
832     StructureChain* prototypeChain = 0;
833     size_t count = 0;
834     
835     if (slot.isUnset() || slot.slotBase() != baseValue) {
836         if (typeInfo.prohibitsPropertyCaching() || structure->isDictionary())
837             return GiveUpOnCache;
838
839         if (slot.isUnset())
840             count = normalizePrototypeChain(exec, structure);
841         else
842             count = normalizePrototypeChainForChainAccess(
843                 exec, structure, slot.slotBase(), ident, offset);
844         if (count == InvalidPrototypeChain)
845             return GiveUpOnCache;
846         prototypeChain = structure->prototypeChain(exec);
847     }
848     
849     PolymorphicGetByIdList* list = PolymorphicGetByIdList::from(stubInfo);
850     if (list->isFull()) {
851         // We need this extra check because of recursion.
852         return GiveUpOnCache;
853     }
854     
855     RefPtr<JITStubRoutine> stubRoutine;
856     bool result = generateByIdStub(
857         exec, kindFor(slot), ident, customFor(slot), stubInfo, prototypeChain, count, offset, 
858         structure, loadTargetFromProxy, slot.watchpointSet(), 
859         stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone),
860         CodeLocationLabel(list->currentSlowPathTarget(stubInfo)), stubRoutine);
861     if (!result)
862         return GiveUpOnCache;
863     
864     GetByIdAccess::AccessType accessType;
865     if (slot.isCacheableValue())
866         accessType = slot.watchpointSet() ? GetByIdAccess::WatchedStub : GetByIdAccess::SimpleStub;
867     else if (slot.isUnset())
868         accessType = GetByIdAccess::SimpleMiss;
869     else if (slot.isCacheableGetter())
870         accessType = GetByIdAccess::Getter;
871     else
872         accessType = GetByIdAccess::CustomGetter;
873     
874     list->addAccess(GetByIdAccess(
875         *vm, codeBlock->ownerExecutable(), accessType, stubRoutine, structure,
876         prototypeChain, count));
877     
878     patchJumpToGetByIdStub(codeBlock, stubInfo, stubRoutine.get());
879     
880     return list->isFull() ? GiveUpOnCache : RetryCacheLater;
881 }
882
883 void buildGetByIDList(ExecState* exec, JSValue baseValue, const Identifier& propertyName, const PropertySlot& slot, StructureStubInfo& stubInfo)
884 {
885     GCSafeConcurrentJITLocker locker(exec->codeBlock()->m_lock, exec->vm().heap);
886     
887     if (tryBuildGetByIDList(exec, baseValue, propertyName, slot, stubInfo) == GiveUpOnCache)
888         repatchCall(exec->codeBlock(), stubInfo.callReturnLocation, operationGetById);
889 }
890
891 static V_JITOperation_ESsiJJI appropriateGenericPutByIdFunction(const PutPropertySlot &slot, PutKind putKind)
892 {
893     if (slot.isStrictMode()) {
894         if (putKind == Direct)
895             return operationPutByIdDirectStrict;
896         return operationPutByIdStrict;
897     }
898     if (putKind == Direct)
899         return operationPutByIdDirectNonStrict;
900     return operationPutByIdNonStrict;
901 }
902
903 static V_JITOperation_ESsiJJI appropriateListBuildingPutByIdFunction(const PutPropertySlot &slot, PutKind putKind)
904 {
905     if (slot.isStrictMode()) {
906         if (putKind == Direct)
907             return operationPutByIdDirectStrictBuildList;
908         return operationPutByIdStrictBuildList;
909     }
910     if (putKind == Direct)
911         return operationPutByIdDirectNonStrictBuildList;
912     return operationPutByIdNonStrictBuildList;
913 }
914
915 static bool emitPutReplaceStub(
916     ExecState* exec,
917     const Identifier&,
918     const PutPropertySlot& slot,
919     StructureStubInfo& stubInfo,
920     Structure* structure,
921     CodeLocationLabel failureLabel,
922     RefPtr<JITStubRoutine>& stubRoutine)
923 {
924     VM* vm = &exec->vm();
925     GPRReg baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
926 #if USE(JSVALUE32_64)
927     GPRReg valueTagGPR = static_cast<GPRReg>(stubInfo.patch.valueTagGPR);
928 #endif
929     GPRReg valueGPR = static_cast<GPRReg>(stubInfo.patch.valueGPR);
930
931     ScratchRegisterAllocator allocator(stubInfo.patch.usedRegisters);
932     allocator.lock(baseGPR);
933 #if USE(JSVALUE32_64)
934     allocator.lock(valueTagGPR);
935 #endif
936     allocator.lock(valueGPR);
937     
938     GPRReg scratchGPR1 = allocator.allocateScratchGPR();
939
940     CCallHelpers stubJit(vm, exec->codeBlock());
941
942     allocator.preserveReusedRegistersByPushing(stubJit);
943
944     MacroAssembler::Jump badStructure = branchStructure(stubJit,
945         MacroAssembler::NotEqual,
946         MacroAssembler::Address(baseGPR, JSCell::structureIDOffset()),
947         structure);
948
949 #if USE(JSVALUE64)
950     if (isInlineOffset(slot.cachedOffset()))
951         stubJit.store64(valueGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue)));
952     else {
953         stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR1);
954         stubJit.store64(valueGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue)));
955     }
956 #elif USE(JSVALUE32_64)
957     if (isInlineOffset(slot.cachedOffset())) {
958         stubJit.store32(valueGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload)));
959         stubJit.store32(valueTagGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag)));
960     } else {
961         stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR1);
962         stubJit.store32(valueGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload)));
963         stubJit.store32(valueTagGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag)));
964     }
965 #endif
966     
967     MacroAssembler::Jump success;
968     MacroAssembler::Jump failure;
969     
970     if (allocator.didReuseRegisters()) {
971         allocator.restoreReusedRegistersByPopping(stubJit);
972         success = stubJit.jump();
973         
974         badStructure.link(&stubJit);
975         allocator.restoreReusedRegistersByPopping(stubJit);
976         failure = stubJit.jump();
977     } else {
978         success = stubJit.jump();
979         failure = badStructure;
980     }
981     
982     LinkBuffer patchBuffer(*vm, stubJit, exec->codeBlock(), JITCompilationCanFail);
983     if (patchBuffer.didFailToAllocate())
984         return false;
985     
986     patchBuffer.link(success, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone));
987     patchBuffer.link(failure, failureLabel);
988             
989     stubRoutine = FINALIZE_CODE_FOR_STUB(
990         exec->codeBlock(), patchBuffer,
991         ("PutById replace stub for %s, return point %p",
992             toCString(*exec->codeBlock()).data(), stubInfo.callReturnLocation.labelAtOffset(
993                 stubInfo.patch.deltaCallToDone).executableAddress()));
994     
995     return true;
996 }
997
998 static Structure* emitPutTransitionStubAndGetOldStructure(ExecState* exec, VM* vm, Structure*& structure, const Identifier& ident, 
999     const PutPropertySlot& slot, StructureStubInfo& stubInfo, PutKind putKind)
1000 {
1001     PropertyName pname(ident);
1002     Structure* oldStructure = structure;
1003     if (!oldStructure->isObject() || oldStructure->isDictionary() || parseIndex(pname))
1004         return nullptr;
1005
1006     PropertyOffset propertyOffset;
1007     structure = Structure::addPropertyTransitionToExistingStructureConcurrently(oldStructure, ident.impl(), 0, propertyOffset);
1008
1009     if (!structure || !structure->isObject() || structure->isDictionary() || !structure->propertyAccessesAreCacheable())
1010         return nullptr;
1011
1012     // Skip optimizing the case where we need a realloc, if we don't have
1013     // enough registers to make it happen.
1014     if (GPRInfo::numberOfRegisters < 6
1015         && oldStructure->outOfLineCapacity() != structure->outOfLineCapacity()
1016         && oldStructure->outOfLineCapacity()) {
1017         return nullptr;
1018     }
1019
1020     // Skip optimizing the case where we need realloc, and the structure has
1021     // indexing storage.
1022     // FIXME: We shouldn't skip this! Implement it!
1023     // https://bugs.webkit.org/show_bug.cgi?id=130914
1024     if (oldStructure->couldHaveIndexingHeader())
1025         return nullptr;
1026
1027     if (normalizePrototypeChain(exec, structure) == InvalidPrototypeChain)
1028         return nullptr;
1029
1030     StructureChain* prototypeChain = structure->prototypeChain(exec);
1031
1032     // emitPutTransitionStub
1033
1034     CodeLocationLabel failureLabel = stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase);
1035     RefPtr<JITStubRoutine>& stubRoutine = stubInfo.stubRoutine;
1036
1037     GPRReg baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
1038 #if USE(JSVALUE32_64)
1039     GPRReg valueTagGPR = static_cast<GPRReg>(stubInfo.patch.valueTagGPR);
1040 #endif
1041     GPRReg valueGPR = static_cast<GPRReg>(stubInfo.patch.valueGPR);
1042     
1043     ScratchRegisterAllocator allocator(stubInfo.patch.usedRegisters);
1044     allocator.lock(baseGPR);
1045 #if USE(JSVALUE32_64)
1046     allocator.lock(valueTagGPR);
1047 #endif
1048     allocator.lock(valueGPR);
1049     
1050     CCallHelpers stubJit(vm);
1051     
1052     bool needThirdScratch = false;
1053     if (structure->outOfLineCapacity() != oldStructure->outOfLineCapacity()
1054         && oldStructure->outOfLineCapacity()) {
1055         needThirdScratch = true;
1056     }
1057
1058     GPRReg scratchGPR1 = allocator.allocateScratchGPR();
1059     ASSERT(scratchGPR1 != baseGPR);
1060     ASSERT(scratchGPR1 != valueGPR);
1061     
1062     GPRReg scratchGPR2 = allocator.allocateScratchGPR();
1063     ASSERT(scratchGPR2 != baseGPR);
1064     ASSERT(scratchGPR2 != valueGPR);
1065     ASSERT(scratchGPR2 != scratchGPR1);
1066
1067     GPRReg scratchGPR3;
1068     if (needThirdScratch) {
1069         scratchGPR3 = allocator.allocateScratchGPR();
1070         ASSERT(scratchGPR3 != baseGPR);
1071         ASSERT(scratchGPR3 != valueGPR);
1072         ASSERT(scratchGPR3 != scratchGPR1);
1073         ASSERT(scratchGPR3 != scratchGPR2);
1074     } else
1075         scratchGPR3 = InvalidGPRReg;
1076     
1077     allocator.preserveReusedRegistersByPushing(stubJit);
1078
1079     MacroAssembler::JumpList failureCases;
1080             
1081     ASSERT(oldStructure->transitionWatchpointSetHasBeenInvalidated());
1082     
1083     failureCases.append(branchStructure(stubJit,
1084         MacroAssembler::NotEqual, 
1085         MacroAssembler::Address(baseGPR, JSCell::structureIDOffset()), 
1086         oldStructure));
1087     
1088     addStructureTransitionCheck(
1089         oldStructure->storedPrototype(), exec->codeBlock(), stubInfo, stubJit, failureCases,
1090         scratchGPR1);
1091             
1092     if (putKind == NotDirect) {
1093         for (WriteBarrier<Structure>* it = prototypeChain->head(); *it; ++it) {
1094             addStructureTransitionCheck(
1095                 (*it)->storedPrototype(), exec->codeBlock(), stubInfo, stubJit, failureCases,
1096                 scratchGPR1);
1097         }
1098     }
1099
1100     MacroAssembler::JumpList slowPath;
1101     
1102     bool scratchGPR1HasStorage = false;
1103     
1104     if (structure->outOfLineCapacity() != oldStructure->outOfLineCapacity()) {
1105         size_t newSize = structure->outOfLineCapacity() * sizeof(JSValue);
1106         CopiedAllocator* copiedAllocator = &vm->heap.storageAllocator();
1107         
1108         if (!oldStructure->outOfLineCapacity()) {
1109             stubJit.loadPtr(&copiedAllocator->m_currentRemaining, scratchGPR1);
1110             slowPath.append(stubJit.branchSubPtr(MacroAssembler::Signed, MacroAssembler::TrustedImm32(newSize), scratchGPR1));
1111             stubJit.storePtr(scratchGPR1, &copiedAllocator->m_currentRemaining);
1112             stubJit.negPtr(scratchGPR1);
1113             stubJit.addPtr(MacroAssembler::AbsoluteAddress(&copiedAllocator->m_currentPayloadEnd), scratchGPR1);
1114             stubJit.addPtr(MacroAssembler::TrustedImm32(sizeof(JSValue)), scratchGPR1);
1115         } else {
1116             size_t oldSize = oldStructure->outOfLineCapacity() * sizeof(JSValue);
1117             ASSERT(newSize > oldSize);
1118             
1119             stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR3);
1120             stubJit.loadPtr(&copiedAllocator->m_currentRemaining, scratchGPR1);
1121             slowPath.append(stubJit.branchSubPtr(MacroAssembler::Signed, MacroAssembler::TrustedImm32(newSize), scratchGPR1));
1122             stubJit.storePtr(scratchGPR1, &copiedAllocator->m_currentRemaining);
1123             stubJit.negPtr(scratchGPR1);
1124             stubJit.addPtr(MacroAssembler::AbsoluteAddress(&copiedAllocator->m_currentPayloadEnd), scratchGPR1);
1125             stubJit.addPtr(MacroAssembler::TrustedImm32(sizeof(JSValue)), scratchGPR1);
1126             // We have scratchGPR1 = new storage, scratchGPR3 = old storage, scratchGPR2 = available
1127             for (size_t offset = 0; offset < oldSize; offset += sizeof(void*)) {
1128                 stubJit.loadPtr(MacroAssembler::Address(scratchGPR3, -static_cast<ptrdiff_t>(offset + sizeof(JSValue) + sizeof(void*))), scratchGPR2);
1129                 stubJit.storePtr(scratchGPR2, MacroAssembler::Address(scratchGPR1, -static_cast<ptrdiff_t>(offset + sizeof(JSValue) + sizeof(void*))));
1130             }
1131         }
1132         
1133         stubJit.storePtr(scratchGPR1, MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()));
1134         scratchGPR1HasStorage = true;
1135     }
1136
1137     ASSERT(oldStructure->typeInfo().type() == structure->typeInfo().type());
1138     ASSERT(oldStructure->typeInfo().inlineTypeFlags() == structure->typeInfo().inlineTypeFlags());
1139     ASSERT(oldStructure->indexingType() == structure->indexingType());
1140 #if USE(JSVALUE64)
1141     uint32_t val = structure->id();
1142 #else
1143     uint32_t val = reinterpret_cast<uint32_t>(structure->id());
1144 #endif
1145     stubJit.store32(MacroAssembler::TrustedImm32(val), MacroAssembler::Address(baseGPR, JSCell::structureIDOffset()));
1146 #if USE(JSVALUE64)
1147     if (isInlineOffset(slot.cachedOffset()))
1148         stubJit.store64(valueGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue)));
1149     else {
1150         if (!scratchGPR1HasStorage)
1151             stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR1);
1152         stubJit.store64(valueGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue)));
1153     }
1154 #elif USE(JSVALUE32_64)
1155     if (isInlineOffset(slot.cachedOffset())) {
1156         stubJit.store32(valueGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload)));
1157         stubJit.store32(valueTagGPR, MacroAssembler::Address(baseGPR, JSObject::offsetOfInlineStorage() + offsetInInlineStorage(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag)));
1158     } else {
1159         if (!scratchGPR1HasStorage)
1160             stubJit.loadPtr(MacroAssembler::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR1);
1161         stubJit.store32(valueGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload)));
1162         stubJit.store32(valueTagGPR, MacroAssembler::Address(scratchGPR1, offsetInButterfly(slot.cachedOffset()) * sizeof(JSValue) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.tag)));
1163     }
1164 #endif
1165     
1166     ScratchBuffer* scratchBuffer = nullptr;
1167
1168 #if ENABLE(GGC)
1169     MacroAssembler::Call callFlushWriteBarrierBuffer;
1170     MacroAssembler::Jump ownerIsRememberedOrInEden = stubJit.jumpIfIsRememberedOrInEden(baseGPR);
1171     {
1172         WriteBarrierBuffer& writeBarrierBuffer = stubJit.vm()->heap.writeBarrierBuffer();
1173         stubJit.load32(writeBarrierBuffer.currentIndexAddress(), scratchGPR2);
1174         MacroAssembler::Jump needToFlush =
1175             stubJit.branch32(MacroAssembler::AboveOrEqual, scratchGPR2, MacroAssembler::TrustedImm32(writeBarrierBuffer.capacity()));
1176
1177         stubJit.add32(MacroAssembler::TrustedImm32(1), scratchGPR2);
1178         stubJit.store32(scratchGPR2, writeBarrierBuffer.currentIndexAddress());
1179
1180         stubJit.move(MacroAssembler::TrustedImmPtr(writeBarrierBuffer.buffer()), scratchGPR1);
1181         // We use an offset of -sizeof(void*) because we already added 1 to scratchGPR2.
1182         stubJit.storePtr(baseGPR, MacroAssembler::BaseIndex(scratchGPR1, scratchGPR2, MacroAssembler::ScalePtr, static_cast<int32_t>(-sizeof(void*))));
1183
1184         MacroAssembler::Jump doneWithBarrier = stubJit.jump();
1185         needToFlush.link(&stubJit);
1186
1187         scratchBuffer = vm->scratchBufferForSize(allocator.desiredScratchBufferSizeForCall());
1188         allocator.preserveUsedRegistersToScratchBufferForCall(stubJit, scratchBuffer, scratchGPR2);
1189         stubJit.setupArgumentsWithExecState(baseGPR);
1190         callFlushWriteBarrierBuffer = stubJit.call();
1191         allocator.restoreUsedRegistersFromScratchBufferForCall(stubJit, scratchBuffer, scratchGPR2);
1192
1193         doneWithBarrier.link(&stubJit);
1194     }
1195     ownerIsRememberedOrInEden.link(&stubJit);
1196 #endif
1197
1198     MacroAssembler::Jump success;
1199     MacroAssembler::Jump failure;
1200             
1201     if (allocator.didReuseRegisters()) {
1202         allocator.restoreReusedRegistersByPopping(stubJit);
1203         success = stubJit.jump();
1204
1205         failureCases.link(&stubJit);
1206         allocator.restoreReusedRegistersByPopping(stubJit);
1207         failure = stubJit.jump();
1208     } else
1209         success = stubJit.jump();
1210     
1211     MacroAssembler::Call operationCall;
1212     MacroAssembler::Jump successInSlowPath;
1213     
1214     if (structure->outOfLineCapacity() != oldStructure->outOfLineCapacity()) {
1215         slowPath.link(&stubJit);
1216         
1217         allocator.restoreReusedRegistersByPopping(stubJit);
1218         if (!scratchBuffer)
1219             scratchBuffer = vm->scratchBufferForSize(allocator.desiredScratchBufferSizeForCall());
1220         allocator.preserveUsedRegistersToScratchBufferForCall(stubJit, scratchBuffer, scratchGPR1);
1221 #if USE(JSVALUE64)
1222         stubJit.setupArgumentsWithExecState(baseGPR, MacroAssembler::TrustedImmPtr(structure), MacroAssembler::TrustedImm32(slot.cachedOffset()), valueGPR);
1223 #else
1224         stubJit.setupArgumentsWithExecState(baseGPR, MacroAssembler::TrustedImmPtr(structure), MacroAssembler::TrustedImm32(slot.cachedOffset()), valueGPR, valueTagGPR);
1225 #endif
1226         operationCall = stubJit.call();
1227         allocator.restoreUsedRegistersFromScratchBufferForCall(stubJit, scratchBuffer, scratchGPR1);
1228         successInSlowPath = stubJit.jump();
1229     }
1230     
1231     LinkBuffer patchBuffer(*vm, stubJit, exec->codeBlock(), JITCompilationCanFail);
1232     if (patchBuffer.didFailToAllocate())
1233         return nullptr;
1234     
1235     patchBuffer.link(success, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone));
1236     if (allocator.didReuseRegisters())
1237         patchBuffer.link(failure, failureLabel);
1238     else
1239         patchBuffer.link(failureCases, failureLabel);
1240 #if ENABLE(GGC)
1241     patchBuffer.link(callFlushWriteBarrierBuffer, operationFlushWriteBarrierBuffer);
1242 #endif
1243     if (structure->outOfLineCapacity() != oldStructure->outOfLineCapacity()) {
1244         patchBuffer.link(operationCall, operationReallocateStorageAndFinishPut);
1245         patchBuffer.link(successInSlowPath, stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone));
1246     }
1247     
1248     stubRoutine =
1249         createJITStubRoutine(
1250             FINALIZE_CODE_FOR(
1251                 exec->codeBlock(), patchBuffer,
1252                 ("PutById %stransition stub (%p -> %p) for %s, return point %p",
1253                     structure->outOfLineCapacity() != oldStructure->outOfLineCapacity() ? "reallocating " : "",
1254                     oldStructure, structure,
1255                     toCString(*exec->codeBlock()).data(), stubInfo.callReturnLocation.labelAtOffset(
1256                         stubInfo.patch.deltaCallToDone).executableAddress())),
1257             *vm,
1258             exec->codeBlock()->ownerExecutable(),
1259             structure->outOfLineCapacity() != oldStructure->outOfLineCapacity(),
1260             structure);
1261
1262     return oldStructure;
1263 }
1264
1265 static InlineCacheAction tryCachePutByID(ExecState* exec, JSValue baseValue, Structure* structure, const Identifier& ident, const PutPropertySlot& slot, StructureStubInfo& stubInfo, PutKind putKind)
1266 {
1267     if (Options::forceICFailure())
1268         return GiveUpOnCache;
1269     
1270     CodeBlock* codeBlock = exec->codeBlock();
1271     VM* vm = &exec->vm();
1272
1273     if (!baseValue.isCell())
1274         return GiveUpOnCache;
1275     
1276     if (!slot.isCacheablePut() && !slot.isCacheableCustom() && !slot.isCacheableSetter())
1277         return GiveUpOnCache;
1278
1279     if (!structure->propertyAccessesAreCacheable())
1280         return GiveUpOnCache;
1281
1282     // Optimize self access.
1283     if (slot.base() == baseValue && slot.isCacheablePut()) {
1284         if (slot.type() == PutPropertySlot::NewProperty) {
1285
1286             Structure* oldStructure = emitPutTransitionStubAndGetOldStructure(exec, vm, structure, ident, slot, stubInfo, putKind);
1287             if (!oldStructure)
1288                 return GiveUpOnCache;
1289             
1290             StructureChain* prototypeChain = structure->prototypeChain(exec);
1291             
1292             RepatchBuffer repatchBuffer(codeBlock);
1293             repatchBuffer.relink(
1294                 stubInfo.callReturnLocation.jumpAtOffset(
1295                     stubInfo.patch.deltaCallToJump),
1296                 CodeLocationLabel(stubInfo.stubRoutine->code().code()));
1297             repatchCall(repatchBuffer, stubInfo.callReturnLocation, appropriateListBuildingPutByIdFunction(slot, putKind));
1298             
1299             stubInfo.initPutByIdTransition(*vm, codeBlock->ownerExecutable(), oldStructure, structure, prototypeChain, putKind == Direct);
1300             
1301             return RetryCacheLater;
1302         }
1303
1304         if (!MacroAssembler::isPtrAlignedAddressOffset(offsetRelativeToPatchedStorage(slot.cachedOffset())))
1305             return GiveUpOnCache;
1306
1307         structure->didCachePropertyReplacement(*vm, slot.cachedOffset());
1308         repatchByIdSelfAccess(*vm, codeBlock, stubInfo, structure, ident, slot.cachedOffset(), appropriateListBuildingPutByIdFunction(slot, putKind), false);
1309         stubInfo.initPutByIdReplace(*vm, codeBlock->ownerExecutable(), structure);
1310         return RetryCacheLater;
1311     }
1312
1313     if ((slot.isCacheableCustom() || slot.isCacheableSetter())
1314         && stubInfo.patch.spillMode == DontSpill) {
1315         RefPtr<JITStubRoutine> stubRoutine;
1316
1317         StructureChain* prototypeChain = 0;
1318         PropertyOffset offset = slot.cachedOffset();
1319         size_t count = 0;
1320         if (baseValue != slot.base()) {
1321             count = normalizePrototypeChainForChainAccess(exec, structure, slot.base(), ident, offset);
1322             if (count == InvalidPrototypeChain)
1323                 return GiveUpOnCache;
1324             prototypeChain = structure->prototypeChain(exec);
1325         }
1326         PolymorphicPutByIdList* list;
1327         list = PolymorphicPutByIdList::from(putKind, stubInfo);
1328
1329         bool result = generateByIdStub(
1330             exec, kindFor(slot), ident, customFor(slot), stubInfo, prototypeChain, count,
1331             offset, structure, false, nullptr,
1332             stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone),
1333             stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase),
1334             stubRoutine);
1335         if (!result)
1336             return GiveUpOnCache;
1337         
1338         list->addAccess(PutByIdAccess::setter(
1339             *vm, codeBlock->ownerExecutable(),
1340             slot.isCacheableSetter() ? PutByIdAccess::Setter : PutByIdAccess::CustomSetter,
1341             structure, prototypeChain, count, slot.customSetter(), stubRoutine));
1342
1343         RepatchBuffer repatchBuffer(codeBlock);
1344         repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), CodeLocationLabel(stubRoutine->code().code()));
1345         repatchCall(repatchBuffer, stubInfo.callReturnLocation, appropriateListBuildingPutByIdFunction(slot, putKind));
1346         RELEASE_ASSERT(!list->isFull());
1347         return RetryCacheLater;
1348     }
1349
1350     return GiveUpOnCache;
1351 }
1352
1353 void repatchPutByID(ExecState* exec, JSValue baseValue, Structure* structure, const Identifier& propertyName, const PutPropertySlot& slot, StructureStubInfo& stubInfo, PutKind putKind)
1354 {
1355     GCSafeConcurrentJITLocker locker(exec->codeBlock()->m_lock, exec->vm().heap);
1356     
1357     if (tryCachePutByID(exec, baseValue, structure, propertyName, slot, stubInfo, putKind) == GiveUpOnCache)
1358         repatchCall(exec->codeBlock(), stubInfo.callReturnLocation, appropriateGenericPutByIdFunction(slot, putKind));
1359 }
1360
1361 static InlineCacheAction tryBuildPutByIdList(ExecState* exec, JSValue baseValue, Structure* structure, const Identifier& propertyName, const PutPropertySlot& slot, StructureStubInfo& stubInfo, PutKind putKind)
1362 {
1363     CodeBlock* codeBlock = exec->codeBlock();
1364     VM* vm = &exec->vm();
1365
1366     if (!baseValue.isCell())
1367         return GiveUpOnCache;
1368
1369     if (!slot.isCacheablePut() && !slot.isCacheableCustom() && !slot.isCacheableSetter())
1370         return GiveUpOnCache;
1371
1372     if (!structure->propertyAccessesAreCacheable())
1373         return GiveUpOnCache;
1374
1375     // Optimize self access.
1376     if (slot.base() == baseValue && slot.isCacheablePut()) {
1377         PolymorphicPutByIdList* list;
1378         RefPtr<JITStubRoutine> stubRoutine;
1379         
1380         if (slot.type() == PutPropertySlot::NewProperty) {
1381             list = PolymorphicPutByIdList::from(putKind, stubInfo);
1382             if (list->isFull())
1383                 return GiveUpOnCache; // Will get here due to recursion.
1384
1385             Structure* oldStructure = emitPutTransitionStubAndGetOldStructure(exec, vm, structure, propertyName, slot, stubInfo, putKind);
1386
1387             if (!oldStructure) 
1388                 return GiveUpOnCache;
1389
1390             StructureChain* prototypeChain = structure->prototypeChain(exec);
1391             stubRoutine = stubInfo.stubRoutine;
1392             list->addAccess(
1393                 PutByIdAccess::transition(
1394                     *vm, codeBlock->ownerExecutable(),
1395                     oldStructure, structure, prototypeChain,
1396                     stubRoutine));
1397
1398         } else {
1399             list = PolymorphicPutByIdList::from(putKind, stubInfo);
1400             if (list->isFull())
1401                 return GiveUpOnCache; // Will get here due to recursion.
1402             
1403             structure->didCachePropertyReplacement(*vm, slot.cachedOffset());
1404             
1405             // We're now committed to creating the stub. Mogrify the meta-data accordingly.
1406             bool result = emitPutReplaceStub(
1407                 exec, propertyName, slot, stubInfo, 
1408                 structure, CodeLocationLabel(list->currentSlowPathTarget()), stubRoutine);
1409             if (!result)
1410                 return GiveUpOnCache;
1411             
1412             list->addAccess(
1413                 PutByIdAccess::replace(
1414                     *vm, codeBlock->ownerExecutable(),
1415                     structure, stubRoutine));
1416         }
1417         RepatchBuffer repatchBuffer(codeBlock);
1418         repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), CodeLocationLabel(stubRoutine->code().code()));
1419         if (list->isFull())
1420             repatchCall(repatchBuffer, stubInfo.callReturnLocation, appropriateGenericPutByIdFunction(slot, putKind));
1421
1422         return RetryCacheLater;
1423     }
1424
1425     if ((slot.isCacheableCustom() || slot.isCacheableSetter())
1426         && stubInfo.patch.spillMode == DontSpill) {
1427         RefPtr<JITStubRoutine> stubRoutine;
1428         StructureChain* prototypeChain = 0;
1429         PropertyOffset offset = slot.cachedOffset();
1430         size_t count = 0;
1431         if (baseValue != slot.base()) {
1432             count = normalizePrototypeChainForChainAccess(exec, structure, slot.base(), propertyName, offset);
1433             if (count == InvalidPrototypeChain)
1434                 return GiveUpOnCache;
1435             prototypeChain = structure->prototypeChain(exec);
1436         }
1437         
1438         PolymorphicPutByIdList* list;
1439         list = PolymorphicPutByIdList::from(putKind, stubInfo);
1440
1441         bool result = generateByIdStub(
1442             exec, kindFor(slot), propertyName, customFor(slot), stubInfo, prototypeChain, count,
1443             offset, structure, false, nullptr,
1444             stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone),
1445             CodeLocationLabel(list->currentSlowPathTarget()),
1446             stubRoutine);
1447         if (!result)
1448             return GiveUpOnCache;
1449         
1450         list->addAccess(PutByIdAccess::setter(
1451             *vm, codeBlock->ownerExecutable(),
1452             slot.isCacheableSetter() ? PutByIdAccess::Setter : PutByIdAccess::CustomSetter,
1453             structure, prototypeChain, count, slot.customSetter(), stubRoutine));
1454
1455         RepatchBuffer repatchBuffer(codeBlock);
1456         repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), CodeLocationLabel(stubRoutine->code().code()));
1457         if (list->isFull())
1458             repatchCall(repatchBuffer, stubInfo.callReturnLocation, appropriateGenericPutByIdFunction(slot, putKind));
1459
1460         return RetryCacheLater;
1461     }
1462     return GiveUpOnCache;
1463 }
1464
1465 void buildPutByIdList(ExecState* exec, JSValue baseValue, Structure* structure, const Identifier& propertyName, const PutPropertySlot& slot, StructureStubInfo& stubInfo, PutKind putKind)
1466 {
1467     GCSafeConcurrentJITLocker locker(exec->codeBlock()->m_lock, exec->vm().heap);
1468     
1469     if (tryBuildPutByIdList(exec, baseValue, structure, propertyName, slot, stubInfo, putKind) == GiveUpOnCache)
1470         repatchCall(exec->codeBlock(), stubInfo.callReturnLocation, appropriateGenericPutByIdFunction(slot, putKind));
1471 }
1472
1473 static InlineCacheAction tryRepatchIn(
1474     ExecState* exec, JSCell* base, const Identifier& ident, bool wasFound,
1475     const PropertySlot& slot, StructureStubInfo& stubInfo)
1476 {
1477     if (Options::forceICFailure())
1478         return GiveUpOnCache;
1479     
1480     if (!base->structure()->propertyAccessesAreCacheable())
1481         return GiveUpOnCache;
1482     
1483     if (wasFound) {
1484         if (!slot.isCacheable())
1485             return GiveUpOnCache;
1486     }
1487     
1488     CodeBlock* codeBlock = exec->codeBlock();
1489     VM* vm = &exec->vm();
1490     Structure* structure = base->structure(*vm);
1491     
1492     PropertyOffset offsetIgnored;
1493     JSValue foundSlotBase = wasFound ? slot.slotBase() : JSValue();
1494     size_t count = !foundSlotBase || foundSlotBase != base ? 
1495         normalizePrototypeChainForChainAccess(exec, structure, foundSlotBase, ident, offsetIgnored) : 0;
1496     if (count == InvalidPrototypeChain)
1497         return GiveUpOnCache;
1498     
1499     PolymorphicAccessStructureList* polymorphicStructureList;
1500     int listIndex;
1501     
1502     CodeLocationLabel successLabel = stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone);
1503     CodeLocationLabel slowCaseLabel;
1504     
1505     if (stubInfo.accessType == access_unset) {
1506         polymorphicStructureList = new PolymorphicAccessStructureList();
1507         stubInfo.initInList(polymorphicStructureList, 0);
1508         slowCaseLabel = stubInfo.callReturnLocation.labelAtOffset(
1509             stubInfo.patch.deltaCallToSlowCase);
1510         listIndex = 0;
1511     } else {
1512         RELEASE_ASSERT(stubInfo.accessType == access_in_list);
1513         polymorphicStructureList = stubInfo.u.inList.structureList;
1514         listIndex = stubInfo.u.inList.listSize;
1515         slowCaseLabel = CodeLocationLabel(polymorphicStructureList->list[listIndex - 1].stubRoutine->code().code());
1516         
1517         if (listIndex == POLYMORPHIC_LIST_CACHE_SIZE)
1518             return GiveUpOnCache;
1519     }
1520     
1521     StructureChain* chain = structure->prototypeChain(exec);
1522     RefPtr<JITStubRoutine> stubRoutine;
1523     
1524     {
1525         GPRReg baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
1526         GPRReg resultGPR = static_cast<GPRReg>(stubInfo.patch.valueGPR);
1527         GPRReg scratchGPR = TempRegisterSet(stubInfo.patch.usedRegisters).getFreeGPR();
1528         
1529         CCallHelpers stubJit(vm);
1530         
1531         bool needToRestoreScratch;
1532         if (scratchGPR == InvalidGPRReg) {
1533             scratchGPR = AssemblyHelpers::selectScratchGPR(baseGPR, resultGPR);
1534             stubJit.pushToSave(scratchGPR);
1535             needToRestoreScratch = true;
1536         } else
1537             needToRestoreScratch = false;
1538         
1539         MacroAssembler::JumpList failureCases;
1540         failureCases.append(branchStructure(stubJit,
1541             MacroAssembler::NotEqual,
1542             MacroAssembler::Address(baseGPR, JSCell::structureIDOffset()),
1543             structure));
1544
1545         CodeBlock* codeBlock = exec->codeBlock();
1546         if (structure->typeInfo().newImpurePropertyFiresWatchpoints())
1547             vm->registerWatchpointForImpureProperty(ident, stubInfo.addWatchpoint(codeBlock));
1548
1549         if (slot.watchpointSet())
1550             slot.watchpointSet()->add(stubInfo.addWatchpoint(codeBlock));
1551
1552         Structure* currStructure = structure;
1553         WriteBarrier<Structure>* it = chain->head();
1554         for (unsigned i = 0; i < count; ++i, ++it) {
1555             JSObject* prototype = asObject(currStructure->prototypeForLookup(exec));
1556             Structure* protoStructure = prototype->structure();
1557             addStructureTransitionCheck(
1558                 prototype, protoStructure, exec->codeBlock(), stubInfo, stubJit,
1559                 failureCases, scratchGPR);
1560             if (protoStructure->typeInfo().newImpurePropertyFiresWatchpoints())
1561                 vm->registerWatchpointForImpureProperty(ident, stubInfo.addWatchpoint(codeBlock));
1562             currStructure = it->get();
1563         }
1564         
1565 #if USE(JSVALUE64)
1566         stubJit.move(MacroAssembler::TrustedImm64(JSValue::encode(jsBoolean(wasFound))), resultGPR);
1567 #else
1568         stubJit.move(MacroAssembler::TrustedImm32(wasFound), resultGPR);
1569 #endif
1570         
1571         MacroAssembler::Jump success, fail;
1572         
1573         emitRestoreScratch(stubJit, needToRestoreScratch, scratchGPR, success, fail, failureCases);
1574         
1575         LinkBuffer patchBuffer(*vm, stubJit, exec->codeBlock(), JITCompilationCanFail);
1576         if (patchBuffer.didFailToAllocate())
1577             return GiveUpOnCache;
1578         
1579         linkRestoreScratch(patchBuffer, needToRestoreScratch, success, fail, failureCases, successLabel, slowCaseLabel);
1580         
1581         stubRoutine = FINALIZE_CODE_FOR_STUB(
1582             exec->codeBlock(), patchBuffer,
1583             ("In (found = %s) stub for %s, return point %p",
1584                 wasFound ? "yes" : "no", toCString(*exec->codeBlock()).data(),
1585                 successLabel.executableAddress()));
1586     }
1587     
1588     polymorphicStructureList->list[listIndex].set(*vm, codeBlock->ownerExecutable(), stubRoutine, structure, true);
1589     stubInfo.u.inList.listSize++;
1590     
1591     RepatchBuffer repatchBuffer(codeBlock);
1592     repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), CodeLocationLabel(stubRoutine->code().code()));
1593     
1594     return listIndex < (POLYMORPHIC_LIST_CACHE_SIZE - 1) ? RetryCacheLater : GiveUpOnCache;
1595 }
1596
1597 void repatchIn(
1598     ExecState* exec, JSCell* base, const Identifier& ident, bool wasFound,
1599     const PropertySlot& slot, StructureStubInfo& stubInfo)
1600 {
1601     if (tryRepatchIn(exec, base, ident, wasFound, slot, stubInfo) == GiveUpOnCache)
1602         repatchCall(exec->codeBlock(), stubInfo.callReturnLocation, operationIn);
1603 }
1604
1605 static void linkSlowFor(
1606     RepatchBuffer& repatchBuffer, VM* vm, CallLinkInfo& callLinkInfo, ThunkGenerator generator)
1607 {
1608     repatchBuffer.relink(
1609         callLinkInfo.callReturnLocation, vm->getCTIStub(generator).code());
1610 }
1611
1612 static void linkSlowFor(
1613     RepatchBuffer& repatchBuffer, VM* vm, CallLinkInfo& callLinkInfo,
1614     CodeSpecializationKind kind, RegisterPreservationMode registers)
1615 {
1616     linkSlowFor(repatchBuffer, vm, callLinkInfo, virtualThunkGeneratorFor(kind, registers));
1617 }
1618
1619 void linkFor(
1620     ExecState* exec, CallLinkInfo& callLinkInfo, CodeBlock* calleeCodeBlock,
1621     JSFunction* callee, MacroAssemblerCodePtr codePtr, CodeSpecializationKind kind,
1622     RegisterPreservationMode registers)
1623 {
1624     ASSERT(!callLinkInfo.stub);
1625     
1626     CodeBlock* callerCodeBlock = exec->callerFrame()->codeBlock();
1627
1628     VM* vm = callerCodeBlock->vm();
1629     
1630     RepatchBuffer repatchBuffer(callerCodeBlock);
1631     
1632     ASSERT(!callLinkInfo.isLinked());
1633     callLinkInfo.callee.set(exec->callerFrame()->vm(), callLinkInfo.hotPathBegin, callerCodeBlock->ownerExecutable(), callee);
1634     callLinkInfo.lastSeenCallee.set(exec->callerFrame()->vm(), callerCodeBlock->ownerExecutable(), callee);
1635     if (shouldShowDisassemblyFor(callerCodeBlock))
1636         dataLog("Linking call in ", *callerCodeBlock, " at ", callLinkInfo.codeOrigin, " to ", pointerDump(calleeCodeBlock), ", entrypoint at ", codePtr, "\n");
1637     repatchBuffer.relink(callLinkInfo.hotPathOther, codePtr);
1638     
1639     if (calleeCodeBlock)
1640         calleeCodeBlock->linkIncomingCall(exec->callerFrame(), &callLinkInfo);
1641     
1642     if (kind == CodeForCall) {
1643         linkSlowFor(
1644             repatchBuffer, vm, callLinkInfo, linkPolymorphicCallThunkGeneratorFor(registers));
1645         return;
1646     }
1647     
1648     ASSERT(kind == CodeForConstruct);
1649     linkSlowFor(repatchBuffer, vm, callLinkInfo, CodeForConstruct, registers);
1650 }
1651
1652 void linkSlowFor(
1653     ExecState* exec, CallLinkInfo& callLinkInfo, CodeSpecializationKind kind,
1654     RegisterPreservationMode registers)
1655 {
1656     CodeBlock* callerCodeBlock = exec->callerFrame()->codeBlock();
1657     VM* vm = callerCodeBlock->vm();
1658     
1659     RepatchBuffer repatchBuffer(callerCodeBlock);
1660     
1661     linkSlowFor(repatchBuffer, vm, callLinkInfo, kind, registers);
1662 }
1663
1664 static void revertCall(
1665     RepatchBuffer& repatchBuffer, VM* vm, CallLinkInfo& callLinkInfo, ThunkGenerator generator)
1666 {
1667     repatchBuffer.revertJumpReplacementToBranchPtrWithPatch(
1668         RepatchBuffer::startOfBranchPtrWithPatchOnRegister(callLinkInfo.hotPathBegin),
1669         static_cast<MacroAssembler::RegisterID>(callLinkInfo.calleeGPR), 0);
1670     linkSlowFor(repatchBuffer, vm, callLinkInfo, generator);
1671     callLinkInfo.hasSeenShouldRepatch = false;
1672     callLinkInfo.callee.clear();
1673     callLinkInfo.stub.clear();
1674     if (callLinkInfo.isOnList())
1675         callLinkInfo.remove();
1676 }
1677
1678 void unlinkFor(
1679     RepatchBuffer& repatchBuffer, CallLinkInfo& callLinkInfo,
1680     CodeSpecializationKind kind, RegisterPreservationMode registers)
1681 {
1682     if (Options::showDisassembly())
1683         dataLog("Unlinking call from ", callLinkInfo.callReturnLocation, " in request from ", pointerDump(repatchBuffer.codeBlock()), "\n");
1684     
1685     revertCall(
1686         repatchBuffer, repatchBuffer.codeBlock()->vm(), callLinkInfo,
1687         linkThunkGeneratorFor(kind, registers));
1688 }
1689
1690 void linkVirtualFor(
1691     ExecState* exec, CallLinkInfo& callLinkInfo,
1692     CodeSpecializationKind kind, RegisterPreservationMode registers)
1693 {
1694     // FIXME: We could generate a virtual call stub here. This would lead to faster virtual calls
1695     // by eliminating the branch prediction bottleneck inside the shared virtual call thunk.
1696     
1697     CodeBlock* callerCodeBlock = exec->callerFrame()->codeBlock();
1698     VM* vm = callerCodeBlock->vm();
1699     
1700     if (shouldShowDisassemblyFor(callerCodeBlock))
1701         dataLog("Linking virtual call at ", *callerCodeBlock, " ", exec->callerFrame()->codeOrigin(), "\n");
1702     
1703     RepatchBuffer repatchBuffer(callerCodeBlock);
1704     revertCall(repatchBuffer, vm, callLinkInfo, virtualThunkGeneratorFor(kind, registers));
1705 }
1706
1707 namespace {
1708 struct CallToCodePtr {
1709     CCallHelpers::Call call;
1710     MacroAssemblerCodePtr codePtr;
1711 };
1712 } // annonymous namespace
1713
1714 void linkPolymorphicCall(
1715     ExecState* exec, CallLinkInfo& callLinkInfo, CallVariant newVariant,
1716     RegisterPreservationMode registers)
1717 {
1718     // Currently we can't do anything for non-function callees.
1719     // https://bugs.webkit.org/show_bug.cgi?id=140685
1720     if (!newVariant || !newVariant.executable()) {
1721         linkVirtualFor(exec, callLinkInfo, CodeForCall, registers);
1722         return;
1723     }
1724     
1725     CodeBlock* callerCodeBlock = exec->callerFrame()->codeBlock();
1726     VM* vm = callerCodeBlock->vm();
1727     
1728     CallVariantList list;
1729     if (PolymorphicCallStubRoutine* stub = callLinkInfo.stub.get())
1730         list = stub->variants();
1731     else if (JSFunction* oldCallee = callLinkInfo.callee.get())
1732         list = CallVariantList{ CallVariant(oldCallee) };
1733     
1734     list = variantListWithVariant(list, newVariant);
1735
1736     // If there are any closure calls then it makes sense to treat all of them as closure calls.
1737     // This makes switching on callee cheaper. It also produces profiling that's easier on the DFG;
1738     // the DFG doesn't really want to deal with a combination of closure and non-closure callees.
1739     bool isClosureCall = false;
1740     for (CallVariant variant : list)  {
1741         if (variant.isClosureCall()) {
1742             list = despecifiedVariantList(list);
1743             isClosureCall = true;
1744             break;
1745         }
1746     }
1747     
1748     Vector<PolymorphicCallCase> callCases;
1749     
1750     // Figure out what our cases are.
1751     for (CallVariant variant : list) {
1752         CodeBlock* codeBlock;
1753         if (variant.executable()->isHostFunction())
1754             codeBlock = nullptr;
1755         else {
1756             codeBlock = jsCast<FunctionExecutable*>(variant.executable())->codeBlockForCall();
1757             
1758             // If we cannot handle a callee, assume that it's better for this whole thing to be a
1759             // virtual call.
1760             if (exec->argumentCountIncludingThis() < static_cast<size_t>(codeBlock->numParameters()) || callLinkInfo.callType == CallLinkInfo::CallVarargs || callLinkInfo.callType == CallLinkInfo::ConstructVarargs) {
1761                 linkVirtualFor(exec, callLinkInfo, CodeForCall, registers);
1762                 return;
1763             }
1764         }
1765         
1766         callCases.append(PolymorphicCallCase(variant, codeBlock));
1767     }
1768     
1769     // If we are over the limit, just use a normal virtual call.
1770     unsigned maxPolymorphicCallVariantListSize;
1771     if (callerCodeBlock->jitType() == JITCode::topTierJIT())
1772         maxPolymorphicCallVariantListSize = Options::maxPolymorphicCallVariantListSizeForTopTier();
1773     else
1774         maxPolymorphicCallVariantListSize = Options::maxPolymorphicCallVariantListSize();
1775     if (list.size() > maxPolymorphicCallVariantListSize) {
1776         linkVirtualFor(exec, callLinkInfo, CodeForCall, registers);
1777         return;
1778     }
1779     
1780     GPRReg calleeGPR = static_cast<GPRReg>(callLinkInfo.calleeGPR);
1781     
1782     CCallHelpers stubJit(vm, callerCodeBlock);
1783     
1784     CCallHelpers::JumpList slowPath;
1785     
1786     ptrdiff_t offsetToFrame = -sizeof(CallerFrameAndPC);
1787
1788     if (!ASSERT_DISABLED) {
1789         CCallHelpers::Jump okArgumentCount = stubJit.branch32(
1790             CCallHelpers::Below, CCallHelpers::Address(CCallHelpers::stackPointerRegister, static_cast<ptrdiff_t>(sizeof(Register) * JSStack::ArgumentCount) + offsetToFrame + PayloadOffset), CCallHelpers::TrustedImm32(10000000));
1791         stubJit.abortWithReason(RepatchInsaneArgumentCount);
1792         okArgumentCount.link(&stubJit);
1793     }
1794     
1795     GPRReg scratch = AssemblyHelpers::selectScratchGPR(calleeGPR);
1796     GPRReg comparisonValueGPR;
1797     
1798     if (isClosureCall) {
1799         // Verify that we have a function and stash the executable in scratch.
1800
1801 #if USE(JSVALUE64)
1802         // We can safely clobber everything except the calleeGPR. We can't rely on tagMaskRegister
1803         // being set. So we do this the hard way.
1804         stubJit.move(MacroAssembler::TrustedImm64(TagMask), scratch);
1805         slowPath.append(stubJit.branchTest64(CCallHelpers::NonZero, calleeGPR, scratch));
1806 #else
1807         // We would have already checked that the callee is a cell.
1808 #endif
1809     
1810         slowPath.append(
1811             stubJit.branch8(
1812                 CCallHelpers::NotEqual,
1813                 CCallHelpers::Address(calleeGPR, JSCell::typeInfoTypeOffset()),
1814                 CCallHelpers::TrustedImm32(JSFunctionType)));
1815     
1816         stubJit.loadPtr(
1817             CCallHelpers::Address(calleeGPR, JSFunction::offsetOfExecutable()),
1818             scratch);
1819         
1820         comparisonValueGPR = scratch;
1821     } else
1822         comparisonValueGPR = calleeGPR;
1823     
1824     Vector<int64_t> caseValues(callCases.size());
1825     Vector<CallToCodePtr> calls(callCases.size());
1826     std::unique_ptr<uint32_t[]> fastCounts;
1827     
1828     if (callerCodeBlock->jitType() != JITCode::topTierJIT())
1829         fastCounts = std::make_unique<uint32_t[]>(callCases.size());
1830     
1831     for (size_t i = 0; i < callCases.size(); ++i) {
1832         if (fastCounts)
1833             fastCounts[i] = 0;
1834         
1835         CallVariant variant = callCases[i].variant();
1836         int64_t newCaseValue;
1837         if (isClosureCall)
1838             newCaseValue = bitwise_cast<intptr_t>(variant.executable());
1839         else
1840             newCaseValue = bitwise_cast<intptr_t>(variant.function());
1841         
1842         if (!ASSERT_DISABLED) {
1843             for (size_t j = 0; j < i; ++j) {
1844                 if (caseValues[j] != newCaseValue)
1845                     continue;
1846
1847                 dataLog("ERROR: Attempt to add duplicate case value.\n");
1848                 dataLog("Existing case values: ");
1849                 CommaPrinter comma;
1850                 for (size_t k = 0; k < i; ++k)
1851                     dataLog(comma, caseValues[k]);
1852                 dataLog("\n");
1853                 dataLog("Attempting to add: ", newCaseValue, "\n");
1854                 dataLog("Variant list: ", listDump(callCases), "\n");
1855                 RELEASE_ASSERT_NOT_REACHED();
1856             }
1857         }
1858         
1859         caseValues[i] = newCaseValue;
1860     }
1861     
1862     GPRReg fastCountsBaseGPR =
1863         AssemblyHelpers::selectScratchGPR(calleeGPR, comparisonValueGPR, GPRInfo::regT3);
1864     stubJit.move(CCallHelpers::TrustedImmPtr(fastCounts.get()), fastCountsBaseGPR);
1865     
1866     BinarySwitch binarySwitch(comparisonValueGPR, caseValues, BinarySwitch::IntPtr);
1867     CCallHelpers::JumpList done;
1868     while (binarySwitch.advance(stubJit)) {
1869         size_t caseIndex = binarySwitch.caseIndex();
1870         
1871         CallVariant variant = callCases[caseIndex].variant();
1872         
1873         ASSERT(variant.executable()->hasJITCodeForCall());
1874         MacroAssemblerCodePtr codePtr =
1875             variant.executable()->generatedJITCodeForCall()->addressForCall(
1876                 *vm, variant.executable(), ArityCheckNotRequired, registers);
1877         
1878         if (fastCounts) {
1879             stubJit.add32(
1880                 CCallHelpers::TrustedImm32(1),
1881                 CCallHelpers::Address(fastCountsBaseGPR, caseIndex * sizeof(uint32_t)));
1882         }
1883         calls[caseIndex].call = stubJit.nearCall();
1884         calls[caseIndex].codePtr = codePtr;
1885         done.append(stubJit.jump());
1886     }
1887     
1888     slowPath.link(&stubJit);
1889     binarySwitch.fallThrough().link(&stubJit);
1890     stubJit.move(calleeGPR, GPRInfo::regT0);
1891 #if USE(JSVALUE32_64)
1892     stubJit.move(CCallHelpers::TrustedImm32(JSValue::CellTag), GPRInfo::regT1);
1893 #endif
1894     stubJit.move(CCallHelpers::TrustedImmPtr(&callLinkInfo), GPRInfo::regT2);
1895     stubJit.move(CCallHelpers::TrustedImmPtr(callLinkInfo.callReturnLocation.executableAddress()), GPRInfo::regT4);
1896     
1897     stubJit.restoreReturnAddressBeforeReturn(GPRInfo::regT4);
1898     AssemblyHelpers::Jump slow = stubJit.jump();
1899         
1900     LinkBuffer patchBuffer(*vm, stubJit, callerCodeBlock, JITCompilationCanFail);
1901     if (patchBuffer.didFailToAllocate()) {
1902         linkVirtualFor(exec, callLinkInfo, CodeForCall, registers);
1903         return;
1904     }
1905     
1906     RELEASE_ASSERT(callCases.size() == calls.size());
1907     for (CallToCodePtr callToCodePtr : calls) {
1908         patchBuffer.link(
1909             callToCodePtr.call, FunctionPtr(callToCodePtr.codePtr.executableAddress()));
1910     }
1911     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType()))
1912         patchBuffer.link(done, callLinkInfo.callReturnLocation.labelAtOffset(0));
1913     else
1914         patchBuffer.link(done, callLinkInfo.hotPathOther.labelAtOffset(0));
1915     patchBuffer.link(slow, CodeLocationLabel(vm->getCTIStub(linkPolymorphicCallThunkGeneratorFor(registers)).code()));
1916     
1917     RefPtr<PolymorphicCallStubRoutine> stubRoutine = adoptRef(new PolymorphicCallStubRoutine(
1918         FINALIZE_CODE_FOR(
1919             callerCodeBlock, patchBuffer,
1920             ("Polymorphic call stub for %s, return point %p, targets %s",
1921                 toCString(*callerCodeBlock).data(), callLinkInfo.callReturnLocation.labelAtOffset(0).executableAddress(),
1922                 toCString(listDump(callCases)).data())),
1923         *vm, callerCodeBlock->ownerExecutable(), exec->callerFrame(), callLinkInfo, callCases,
1924         WTF::move(fastCounts)));
1925     
1926     RepatchBuffer repatchBuffer(callerCodeBlock);
1927     
1928     repatchBuffer.replaceWithJump(
1929         RepatchBuffer::startOfBranchPtrWithPatchOnRegister(callLinkInfo.hotPathBegin),
1930         CodeLocationLabel(stubRoutine->code().code()));
1931     // This is weird. The original slow path should no longer be reachable.
1932     linkSlowFor(repatchBuffer, vm, callLinkInfo, CodeForCall, registers);
1933     
1934     // If there had been a previous stub routine, that one will die as soon as the GC runs and sees
1935     // that it's no longer on stack.
1936     callLinkInfo.stub = stubRoutine.release();
1937     
1938     // The call link info no longer has a call cache apart from the jump to the polymorphic call
1939     // stub.
1940     if (callLinkInfo.isOnList())
1941         callLinkInfo.remove();
1942 }
1943
1944 void resetGetByID(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
1945 {
1946     repatchCall(repatchBuffer, stubInfo.callReturnLocation, operationGetByIdOptimize);
1947     CodeLocationDataLabel32 structureLabel = stubInfo.callReturnLocation.dataLabel32AtOffset(-(intptr_t)stubInfo.patch.deltaCheckImmToCall);
1948     if (MacroAssembler::canJumpReplacePatchableBranch32WithPatch()) {
1949         repatchBuffer.revertJumpReplacementToPatchableBranch32WithPatch(
1950             RepatchBuffer::startOfPatchableBranch32WithPatchOnAddress(structureLabel),
1951             MacroAssembler::Address(
1952                 static_cast<MacroAssembler::RegisterID>(stubInfo.patch.baseGPR),
1953                 JSCell::structureIDOffset()),
1954             static_cast<int32_t>(unusedPointer));
1955     }
1956     repatchBuffer.repatch(structureLabel, static_cast<int32_t>(unusedPointer));
1957 #if USE(JSVALUE64)
1958     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToLoadOrStore), 0);
1959 #else
1960     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToTagLoadOrStore), 0);
1961     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabelCompactAtOffset(stubInfo.patch.deltaCallToPayloadLoadOrStore), 0);
1962 #endif
1963     repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
1964 }
1965
1966 void resetPutByID(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
1967 {
1968     V_JITOperation_ESsiJJI unoptimizedFunction = bitwise_cast<V_JITOperation_ESsiJJI>(readCallTarget(repatchBuffer, stubInfo.callReturnLocation).executableAddress());
1969     V_JITOperation_ESsiJJI optimizedFunction;
1970     if (unoptimizedFunction == operationPutByIdStrict || unoptimizedFunction == operationPutByIdStrictBuildList)
1971         optimizedFunction = operationPutByIdStrictOptimize;
1972     else if (unoptimizedFunction == operationPutByIdNonStrict || unoptimizedFunction == operationPutByIdNonStrictBuildList)
1973         optimizedFunction = operationPutByIdNonStrictOptimize;
1974     else if (unoptimizedFunction == operationPutByIdDirectStrict || unoptimizedFunction == operationPutByIdDirectStrictBuildList)
1975         optimizedFunction = operationPutByIdDirectStrictOptimize;
1976     else {
1977         ASSERT(unoptimizedFunction == operationPutByIdDirectNonStrict || unoptimizedFunction == operationPutByIdDirectNonStrictBuildList);
1978         optimizedFunction = operationPutByIdDirectNonStrictOptimize;
1979     }
1980     repatchCall(repatchBuffer, stubInfo.callReturnLocation, optimizedFunction);
1981     CodeLocationDataLabel32 structureLabel = stubInfo.callReturnLocation.dataLabel32AtOffset(-(intptr_t)stubInfo.patch.deltaCheckImmToCall);
1982     if (MacroAssembler::canJumpReplacePatchableBranch32WithPatch()) {
1983         repatchBuffer.revertJumpReplacementToPatchableBranch32WithPatch(
1984             RepatchBuffer::startOfPatchableBranch32WithPatchOnAddress(structureLabel),
1985             MacroAssembler::Address(
1986                 static_cast<MacroAssembler::RegisterID>(stubInfo.patch.baseGPR),
1987                 JSCell::structureIDOffset()),
1988             static_cast<int32_t>(unusedPointer));
1989     }
1990     repatchBuffer.repatch(structureLabel, static_cast<int32_t>(unusedPointer));
1991 #if USE(JSVALUE64)
1992     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToLoadOrStore), 0);
1993 #else
1994     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToTagLoadOrStore), 0);
1995     repatchBuffer.repatch(stubInfo.callReturnLocation.dataLabel32AtOffset(stubInfo.patch.deltaCallToPayloadLoadOrStore), 0);
1996 #endif
1997     repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
1998 }
1999
2000 void resetIn(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2001 {
2002     repatchBuffer.relink(stubInfo.callReturnLocation.jumpAtOffset(stubInfo.patch.deltaCallToJump), stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
2003 }
2004
2005 } // namespace JSC
2006
2007 #endif