1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
|
/*
* Copyright (C) 2016-2019 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "B3EliminateCommonSubexpressions.h"
#if ENABLE(B3_JIT)
#include "B3BlockWorklist.h"
#include "B3Dominators.h"
#include "B3HeapRange.h"
#include "B3InsertionSetInlines.h"
#include "B3MemoryValue.h"
#include "B3MemoryValueInlines.h"
#include "B3PhaseScope.h"
#include "B3ProcedureInlines.h"
#include "B3PureCSE.h"
#include "B3ValueInlines.h"
#include "B3VariableValue.h"
#include <wtf/CommaPrinter.h>
#include <wtf/HashMap.h>
#include <wtf/ListDump.h>
#include <wtf/RangeSet.h>
#include <wtf/Scope.h>
namespace JSC { namespace B3 {
namespace {
namespace B3EliminateCommonSubexpressionsInternal {
static constexpr bool verbose = false;
}
// FIXME: We could treat Patchpoints with a non-empty set of reads as a "memory value" and somehow
// eliminate redundant ones. We would need some way of determining if two patchpoints are replacable.
// It doesn't seem right to use the reads set for this. We could use the generator, but that feels
// lame because the FTL will pretty much use a unique generator for each patchpoint even when two
// patchpoints have the same semantics as far as CSE would be concerned. We could invent something
// like a "value ID" for patchpoints. By default, each one gets a unique value ID, but FTL could force
// some patchpoints to share the same one as a signal that they will return the same value if executed
// in the same heap with the same inputs.
typedef Vector<MemoryValue*, 1> MemoryMatches;
class MemoryValueMap {
public:
MemoryValueMap() { }
void add(MemoryValue* memory)
{
Matches& matches = m_map.add(memory->lastChild(), Matches()).iterator->value;
if (matches.contains(memory))
return;
matches.append(memory);
}
template<typename Functor>
void removeIf(const Functor& functor)
{
m_map.removeIf(
[&] (UncheckedKeyHashMap<Value*, Matches>::KeyValuePairType& entry) -> bool {
entry.value.removeAllMatching(
[&] (Value* value) -> bool {
if (MemoryValue* memory = value->as<MemoryValue>())
return functor(memory);
return true;
});
return entry.value.isEmpty();
});
}
Matches* find(Value* ptr)
{
auto iter = m_map.find(ptr);
if (iter == m_map.end())
return nullptr;
return &iter->value;
}
template<typename Functor>
MemoryValue* find(Value* ptr, const Functor& functor)
{
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Looking for ", pointerDump(ptr), " in ", *this, "\n");
if (Matches* matches = find(ptr)) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Matches: ", pointerListDump(*matches), "\n");
for (Value* candidateValue : *matches) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Having candidate: ", pointerDump(candidateValue), "\n");
if (MemoryValue* candidateMemory = candidateValue->as<MemoryValue>()) {
if (functor(candidateMemory))
return candidateMemory;
}
}
}
return nullptr;
}
void dump(PrintStream& out) const
{
out.print("{"_s);
CommaPrinter comma;
for (auto& entry : m_map)
out.print(comma, pointerDump(entry.key), "=>"_s, pointerListDump(entry.value));
out.print("}"_s);
}
private:
// This uses Matches for two reasons:
// - It cannot be a MemoryValue* because the key is imprecise. Many MemoryValues could have the
// same key while being unaliased.
// - It can't be a MemoryMatches array because the MemoryValue*'s could be turned into Identity's.
UncheckedKeyHashMap<Value*, Matches> m_map;
};
struct ImpureBlockData {
void dump(PrintStream& out) const
{
out.print(
"{reads = ", reads, ", writes = ", writes, ", storesAtHead = ", storesAtHead,
", memoryValuesAtTail = ", memoryValuesAtTail, "}");
}
RangeSet<HeapRange> reads; // This only gets used for forward store elimination.
RangeSet<HeapRange> writes; // This gets used for both load and store elimination.
bool fence { false };
bool writesPinned { false };
MemoryValueMap storesAtHead;
MemoryValueMap memoryValuesAtTail;
// This Maps x->y in "y = WasmAddress(@x)"
UncheckedKeyHashMap<Value*, Value*> m_candidateWasmAddressesAtTail;
};
class CSE {
public:
CSE(Procedure& proc)
: m_proc(proc)
, m_dominators(proc.dominators())
, m_impureBlockData(proc.size())
, m_insertionSet(proc)
{
}
bool run()
{
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog("B3 before CSE:\n", m_proc);
m_proc.resetValueOwners();
// Summarize the impure effects of each block, and the impure values available at the end of
// each block. This doesn't edit code yet.
for (BasicBlock* block : m_proc) {
ImpureBlockData& data = m_impureBlockData[block];
for (Value* value : *block) {
Effects effects = value->effects();
MemoryValue* memory = value->as<MemoryValue>();
if (memory && memory->isStore()
&& !data.reads.overlaps(memory->range())
&& !data.writes.overlaps(memory->range())
&& (!data.fence || !memory->hasFence()))
data.storesAtHead.add(memory);
data.reads.add(effects.reads);
if (HeapRange writes = effects.writes)
clobber(data, writes);
data.fence |= effects.fence;
if (memory)
data.memoryValuesAtTail.add(memory);
if (WasmAddressValue* wasmAddress = value->as<WasmAddressValue>())
data.m_candidateWasmAddressesAtTail.add(wasmAddress->child(0), wasmAddress);
if (effects.writesPinned) {
data.writesPinned = true;
data.m_candidateWasmAddressesAtTail.clear();
}
}
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog("Block ", *block, ": ", data, "\n");
}
// Perform CSE. This edits code.
Vector<BasicBlock*> postOrder = m_proc.blocksInPostOrder();
for (unsigned i = postOrder.size(); i--;) {
m_block = postOrder[i];
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog("Looking at ", *m_block, ":\n");
m_data = ImpureBlockData();
for (m_index = 0; m_index < m_block->size(); ++m_index) {
m_value = m_block->at(m_index);
process();
}
m_insertionSet.execute(m_block);
m_impureBlockData[m_block] = m_data;
}
// The previous pass might have requested that we insert code in some basic block other than
// the one that it was looking at. This inserts them.
for (BasicBlock* block : m_proc) {
for (unsigned valueIndex = 0; valueIndex < block->size(); ++valueIndex) {
auto iter = m_sets.find(block->at(valueIndex));
if (iter == m_sets.end())
continue;
for (Value* value : iter->value)
m_insertionSet.insertValue(valueIndex + 1, value);
}
m_insertionSet.execute(block);
}
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog("B3 after CSE:\n", m_proc);
return m_changed;
}
private:
void process()
{
m_value->performSubstitution();
if (m_pureCSE.process(m_value, m_dominators)) {
ASSERT(!m_value->effects().readsPinned || !m_data.writesPinned);
ASSERT(!m_value->effects().writes);
ASSERT(!m_value->effects().writesPinned);
m_changed = true;
return;
}
if (WasmAddressValue* wasmAddress = m_value->as<WasmAddressValue>()) {
processWasmAddressValue(wasmAddress);
return;
}
Effects effects = m_value->effects();
if (effects.writesPinned) {
m_data.writesPinned = true;
m_data.m_candidateWasmAddressesAtTail.clear();
}
MemoryValue* memory = m_value->as<MemoryValue>();
if (memory && processMemoryBeforeClobber(memory))
return;
if (HeapRange writes = effects.writes)
clobber(m_data, writes);
if (memory)
processMemoryAfterClobber(memory);
// The reads info should be updated even the block is processed
// since the dominated store nodes may dependent on the data
// read from the processed block. Note that there is no need to
// update reads info if the node is deleted.
m_data.reads.add(m_value->effects().reads);
}
// Return true if we got rid of the operation. If you changed IR in this function, you have to
// set m_changed even if you also return true.
bool processMemoryBeforeClobber(MemoryValue* memory)
{
Value* value = memory->child(0);
Value* ptr = memory->lastChild();
HeapRange range = memory->range();
Value::OffsetType offset = memory->offset();
switch (memory->opcode()) {
case Store8:
return handleStoreBeforeClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& ((candidate->opcode() == Store8 && candidate->child(0) == value)
|| ((candidate->opcode() == Load8Z || candidate->opcode() == Load8S)
&& candidate == value));
});
case Store16:
return handleStoreBeforeClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& ((candidate->opcode() == Store16 && candidate->child(0) == value)
|| ((candidate->opcode() == Load16Z || candidate->opcode() == Load16S)
&& candidate == value));
});
case Store:
return handleStoreBeforeClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& ((candidate->opcode() == Store && candidate->child(0) == value)
|| (candidate->opcode() == Load && candidate == value));
});
default:
return false;
}
}
void clobber(ImpureBlockData& data, HeapRange writes)
{
data.writes.add(writes);
data.memoryValuesAtTail.removeIf(
[&] (MemoryValue* memory) {
return memory->range().overlaps(writes);
});
}
void processMemoryAfterClobber(MemoryValue* memory)
{
Value* ptr = memory->lastChild();
HeapRange range = memory->range();
Value::OffsetType offset = memory->offset();
Type type = memory->type();
// FIXME: Empower this to insert more casts and shifts. For example, a Load8 could match a
// Store and mask the result. You could even have:
//
// Store(@value, @ptr, offset = 0)
// Load8Z(@ptr, offset = 2)
//
// Which could be turned into something like this:
//
// Store(@value, @ptr, offset = 0)
// ZShr(@value, 16)
switch (memory->opcode()) {
case Load8Z: {
handleMemoryValue(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& (candidate->opcode() == Load8Z || candidate->opcode() == Store8);
},
[&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
if (match->opcode() == Store8) {
Value* mask = m_proc.add<Const32Value>(m_value->origin(), 0xff);
fixups.append(mask);
Value* zext = m_proc.add<Value>(
BitAnd, m_value->origin(), match->child(0), mask);
fixups.append(zext);
return zext;
}
return nullptr;
});
break;
}
case Load8S: {
handleMemoryValue(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& (candidate->opcode() == Load8S || candidate->opcode() == Store8);
},
[&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
if (match->opcode() == Store8) {
Value* sext = m_proc.add<Value>(
SExt8, m_value->origin(), match->child(0));
fixups.append(sext);
return sext;
}
return nullptr;
});
break;
}
case Load16Z: {
handleMemoryValue(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& (candidate->opcode() == Load16Z || candidate->opcode() == Store16);
},
[&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
if (match->opcode() == Store16) {
Value* mask = m_proc.add<Const32Value>(m_value->origin(), 0xffff);
fixups.append(mask);
Value* zext = m_proc.add<Value>(
BitAnd, m_value->origin(), match->child(0), mask);
fixups.append(zext);
return zext;
}
return nullptr;
});
break;
}
case Load16S: {
handleMemoryValue(
ptr, range, [&] (MemoryValue* candidate) -> bool {
return candidate->offset() == offset
&& (candidate->opcode() == Load16S || candidate->opcode() == Store16);
},
[&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
if (match->opcode() == Store16) {
Value* sext = m_proc.add<Value>(
SExt16, m_value->origin(), match->child(0));
fixups.append(sext);
return sext;
}
return nullptr;
});
break;
}
case Load: {
handleMemoryValue(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
dataLogLnIf(B3EliminateCommonSubexpressionsInternal::verbose, " Consdering ", pointerDump(candidate));
if (candidate->offset() != offset)
return false;
dataLogLnIf(B3EliminateCommonSubexpressionsInternal::verbose, " offset ok.");
if (candidate->opcode() == Load) {
if (candidate->type() == type)
return true;
if (candidate->type() == Int64 && type == Int32)
return true;
}
dataLogLnIf(B3EliminateCommonSubexpressionsInternal::verbose, " not a load with ok type.");
if (candidate->opcode() == Store) {
if (candidate->child(0)->type() == type)
return true;
if (candidate->child(0)->type() == Int64 && type == Int32)
return true;
}
dataLogLnIf(B3EliminateCommonSubexpressionsInternal::verbose, " not a store with ok type.");
return false;
},
[&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
if (match->opcode() == Load) {
if (match->type() == type)
return nullptr;
if (match->type() == Int64 && type == Int32) {
Value* trunc = m_proc.add<Value>(Trunc, m_value->origin(), match);
fixups.append(trunc);
return trunc;
}
}
if (match->opcode() == Store) {
if (match->child(0)->type() == type)
return nullptr;
if (match->child(0)->type() == Int64 && type == Int32) {
Value* trunc = m_proc.add<Value>(Trunc, m_value->origin(), match->child(0));
fixups.append(trunc);
return trunc;
}
}
return nullptr;
});
break;
}
case Store8: {
handleStoreAfterClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->opcode() == Store8
&& candidate->offset() == offset;
});
break;
}
case Store16: {
handleStoreAfterClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->opcode() == Store16
&& candidate->offset() == offset;
});
break;
}
case Store: {
auto clobberWidth = memory->accessWidth();
handleStoreAfterClobber(
ptr, range,
[&] (MemoryValue* candidate) -> bool {
return candidate->opcode() == Store
&& candidate->offset() == offset
&& candidate->accessWidth() >= clobberWidth;
});
break;
}
default:
break;
}
}
template<typename Filter>
bool handleStoreBeforeClobber(Value* ptr, HeapRange range, const Filter& filter)
{
MemoryMatches matches = findMemoryValue(ptr, range, filter);
if (matches.isEmpty())
return false;
m_value->replaceWithNop();
m_changed = true;
return true;
}
template<typename Filter>
void handleStoreAfterClobber(Value* ptr, HeapRange range, const Filter& filter)
{
if (!m_value->traps() && findStoreAfterClobber(ptr, range, filter)) {
m_value->replaceWithNop();
m_changed = true;
return;
}
m_data.memoryValuesAtTail.add(m_value->as<MemoryValue>());
}
template<typename Filter>
bool findStoreAfterClobber(Value* ptr, HeapRange range, const Filter& filter)
{
if (m_value->as<MemoryValue>()->hasFence())
return false;
// We can eliminate a store if every forward path hits a store to the same location before
// hitting any operation that observes the store. This search seems like it should be
// expensive, but in the overwhelming majority of cases it will almost immediately hit an
// operation that interferes.
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(*m_value, ": looking forward for stores to ", *ptr, "...\n");
// First search forward in this basic block.
// FIXME: It would be cool to get rid of this linear search. It's not super critical since
// we will probably bail out very quickly, but it *is* annoying.
for (unsigned index = m_index + 1; index < m_block->size(); ++index) {
Value* value = m_block->at(index);
if (MemoryValue* memoryValue = value->as<MemoryValue>()) {
if (memoryValue->lastChild() == ptr && filter(memoryValue))
return true;
}
Effects effects = value->effects();
if (effects.reads.overlaps(range) || effects.writes.overlaps(range))
return false;
}
if (!m_block->numSuccessors())
return false;
BlockWorklist worklist;
worklist.pushAll(m_block->successorBlocks());
while (BasicBlock* block = worklist.pop()) {
ImpureBlockData& data = m_impureBlockData[block];
MemoryValue* match = data.storesAtHead.find(ptr, filter);
if (match && match != m_value)
continue;
if (data.writes.overlaps(range) || data.reads.overlaps(range))
return false;
if (!block->numSuccessors())
return false;
worklist.pushAll(block->successorBlocks());
}
return true;
}
template<typename Filter>
void handleMemoryValue(Value* ptr, HeapRange range, const Filter& filter)
{
handleMemoryValue(
ptr, range, filter,
[] (MemoryValue*, Vector<Value*>&) -> Value* {
return nullptr;
});
}
template<typename Filter, typename Replace>
void handleMemoryValue(
Value* ptr, HeapRange range, const Filter& filter, const Replace& replace)
{
MemoryMatches matches = findMemoryValue(ptr, range, filter);
if (replaceMemoryValue(matches, replace))
return;
m_data.memoryValuesAtTail.add(m_value->as<MemoryValue>());
}
template<typename Replace>
bool replaceMemoryValue(const MemoryMatches& matches, const Replace& replace)
{
if (matches.isEmpty())
return false;
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog("Eliminating ", *m_value, " due to ", pointerListDump(matches), "\n");
m_changed = true;
if (matches.size() == 1) {
MemoryValue* dominatingMatch = matches[0];
RELEASE_ASSERT(m_dominators.dominates(dominatingMatch->owner, m_block));
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Eliminating using ", *dominatingMatch, "\n");
Vector<Value*> extraValues;
if (Value* value = replace(dominatingMatch, extraValues)) {
for (Value* extraValue : extraValues)
m_insertionSet.insertValue(m_index, extraValue);
m_value->replaceWithIdentity(value);
} else {
if (dominatingMatch->isStore())
m_value->replaceWithIdentity(dominatingMatch->child(0));
else
m_value->replaceWithIdentity(dominatingMatch);
}
return true;
}
// FIXME: It would be way better if this phase just did SSA calculation directly.
// Right now we're relying on the fact that CSE's position in the phase order is
// almost right before SSA fixup.
Variable* variable = m_proc.addVariable(m_value->type());
VariableValue* get = m_insertionSet.insert<VariableValue>(
m_index, Get, m_value->origin(), variable);
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Inserting get of value: ", *get, "\n");
m_value->replaceWithIdentity(get);
for (MemoryValue* match : matches) {
Vector<Value*>& sets = m_sets.add(match, Vector<Value*>()).iterator->value;
Value* value = replace(match, sets);
if (!value) {
if (match->isStore())
value = match->child(0);
else
value = match;
}
Value* set = m_proc.add<VariableValue>(Set, m_value->origin(), variable, value);
sets.append(set);
}
return true;
}
template<typename Filter>
MemoryMatches findMemoryValue(Value* ptr, HeapRange range, const Filter& filter)
{
if (B3EliminateCommonSubexpressionsInternal::verbose) {
dataLog(*m_value, ": looking backward for ", *ptr, "...\n");
dataLog(" Full value: ", deepDump(m_value), "\n");
}
if (m_value->as<MemoryValue>()->hasFence()) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Giving up because fences.\n");
return { };
}
if (MemoryValue* match = m_data.memoryValuesAtTail.find(ptr, filter)) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Found ", *match, " locally.\n");
return { match };
}
if (m_data.writes.overlaps(range)) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Giving up because of writes.\n");
return { };
}
BlockWorklist worklist;
worklist.pushAll(m_block->predecessors());
MemoryMatches matches;
while (BasicBlock* block = worklist.pop()) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Looking at ", *block, "\n");
ImpureBlockData& data = m_impureBlockData[block];
MemoryValue* match = data.memoryValuesAtTail.find(ptr, filter);
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Consdering match: ", pointerDump(match), "\n");
if (match && match != m_value) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Found match: ", *match, "\n");
matches.append(match);
continue;
}
if (data.writes.overlaps(range)) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Giving up because of writes.\n");
return { };
}
if (!block->numPredecessors()) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Giving up because it's live at root.\n");
// This essentially proves that this is live at the prologue. That means that we
// cannot reliably optimize this case.
return { };
}
worklist.pushAll(block->predecessors());
}
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Got matches: ", pointerListDump(matches), "\n");
return matches;
}
void processWasmAddressValue(WasmAddressValue* wasmAddress)
{
Value* ptr = wasmAddress->child(0);
if (Value* replacement = m_data.m_candidateWasmAddressesAtTail.get(ptr)) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Replacing WasmAddress: ", *wasmAddress, " with ", *replacement, "\n");
wasmAddress->replaceWithIdentity(replacement);
m_changed = true;
return;
}
auto addPtrOnScopeExit = makeScopeExit([&] {
m_data.m_candidateWasmAddressesAtTail.add(ptr, wasmAddress);
});
if (m_data.writesPinned) {
// Someone before us in this block wrote to pinned. So we have no
// hope of finding a match if the above search failed.
return;
}
Value* candidateReplacement = nullptr;
BasicBlock* dominator = nullptr;
m_dominators.forAllStrictDominatorsOf(m_block, [&] (BasicBlock* block) {
if (candidateReplacement)
return;
if (Value* replacement = m_impureBlockData[block].m_candidateWasmAddressesAtTail.get(ptr)) {
candidateReplacement = replacement;
dominator = block;
}
});
if (!candidateReplacement)
return;
BlockWorklist worklist;
worklist.pushAll(m_block->predecessors());
while (BasicBlock* block = worklist.pop()) {
if (block == dominator)
continue;
if (m_impureBlockData[block].writesPinned) {
candidateReplacement = nullptr;
break;
}
worklist.pushAll(block->predecessors());
}
if (candidateReplacement) {
if (B3EliminateCommonSubexpressionsInternal::verbose)
dataLog(" Replacing WasmAddress: ", *wasmAddress, " with ", *candidateReplacement, "\n");
wasmAddress->replaceWithIdentity(candidateReplacement);
m_changed = true;
}
}
Procedure& m_proc;
Dominators& m_dominators;
PureCSE m_pureCSE;
IndexMap<BasicBlock*, ImpureBlockData> m_impureBlockData;
ImpureBlockData m_data;
BasicBlock* m_block;
unsigned m_index;
Value* m_value;
UncheckedKeyHashMap<Value*, Vector<Value*>> m_sets;
InsertionSet m_insertionSet;
bool m_changed { false };
};
} // anonymous namespace
bool eliminateCommonSubexpressions(Procedure& proc)
{
PhaseScope phaseScope(proc, "eliminateCommonSubexpressions"_s);
CSE cse(proc);
return cse.run();
}
} } // namespace JSC::B3
#endif // ENABLE(B3_JIT)
|