move-optimizer.cc 18.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/move-optimizer.h"

namespace v8 {
namespace internal {
namespace compiler {

11
namespace {
12

13 14 15 16
struct MoveKey {
  InstructionOperand source;
  InstructionOperand destination;
};
17 18 19

struct MoveKeyCompare {
  bool operator()(const MoveKey& a, const MoveKey& b) const {
20 21
    if (a.source.EqualsCanonicalized(b.source)) {
      return a.destination.CompareCanonicalized(b.destination);
22
    }
23
    return a.source.CompareCanonicalized(b.source);
24 25 26 27
  }
};

typedef ZoneMap<MoveKey, unsigned, MoveKeyCompare> MoveMap;
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
class OperandSet {
 public:
  explicit OperandSet(Zone* zone) : set_(zone), fp_reps_(0) {}

  void InsertOp(const InstructionOperand& op) {
    set_.insert(op);
    if (!kSimpleFPAliasing && op.IsFPRegister())
      fp_reps_ |= RepBit(LocationOperand::cast(op).representation());
  }

  bool ContainsOpOrAlias(const InstructionOperand& op) const {
    if (set_.find(op) != set_.end()) return true;

    if (!kSimpleFPAliasing && op.IsFPRegister()) {
      // Platforms where FP registers have complex aliasing need extra checks.
      const LocationOperand& loc = LocationOperand::cast(op);
      MachineRepresentation rep = loc.representation();
      // If haven't encountered mixed rep FP registers, skip the extra checks.
      if (!HasMixedFPReps(fp_reps_ | RepBit(rep))) return false;

      // Check register against aliasing registers of other FP representations.
      MachineRepresentation other_rep1, other_rep2;
      switch (rep) {
        case MachineRepresentation::kFloat32:
          other_rep1 = MachineRepresentation::kFloat64;
          other_rep2 = MachineRepresentation::kSimd128;
          break;
        case MachineRepresentation::kFloat64:
          other_rep1 = MachineRepresentation::kFloat32;
          other_rep2 = MachineRepresentation::kSimd128;
          break;
        case MachineRepresentation::kSimd128:
          other_rep1 = MachineRepresentation::kFloat32;
          other_rep2 = MachineRepresentation::kFloat64;
          break;
        default:
          UNREACHABLE();
          break;
      }
      const RegisterConfiguration* config = RegisterConfiguration::Turbofan();
      int base = -1;
      int aliases =
          config->GetAliases(rep, loc.register_code(), other_rep1, &base);
      DCHECK(aliases > 0 || (aliases == 0 && base == -1));
      while (aliases--) {
        if (set_.find(AllocatedOperand(LocationOperand::REGISTER, other_rep1,
                                       base + aliases)) != set_.end())
          return true;
      }
      aliases = config->GetAliases(rep, loc.register_code(), other_rep2, &base);
      DCHECK(aliases > 0 || (aliases == 0 && base == -1));
      while (aliases--) {
        if (set_.find(AllocatedOperand(LocationOperand::REGISTER, other_rep2,
                                       base + aliases)) != set_.end())
          return true;
      }
    }
    return false;
  }

 private:
  static int RepBit(MachineRepresentation rep) {
    return 1 << static_cast<int>(rep);
  }

  static bool HasMixedFPReps(int reps) {
    return reps && !base::bits::IsPowerOfTwo32(reps);
  }

  ZoneSet<InstructionOperand, CompareOperandModuloType> set_;
  int fp_reps_;
};
101

mtrofin's avatar
mtrofin committed
102
int FindFirstNonEmptySlot(const Instruction* instr) {
103 104
  int i = Instruction::FIRST_GAP_POSITION;
  for (; i <= Instruction::LAST_GAP_POSITION; i++) {
mtrofin's avatar
mtrofin committed
105
    ParallelMove* moves = instr->parallel_moves()[i];
106
    if (moves == nullptr) continue;
mtrofin's avatar
mtrofin committed
107
    for (MoveOperands* move : *moves) {
108 109
      if (!move->IsRedundant()) return i;
      move->Eliminate();
110
    }
111
    moves->clear();  // Clear this redundant move.
112 113 114 115
  }
  return i;
}

116
}  // namespace
117 118 119 120 121


MoveOptimizer::MoveOptimizer(Zone* local_zone, InstructionSequence* code)
    : local_zone_(local_zone),
      code_(code),
122
      local_vector_(local_zone) {}
123 124 125


void MoveOptimizer::Run() {
126 127 128
  for (Instruction* instruction : code()->instructions()) {
    CompressGaps(instruction);
  }
129
  for (InstructionBlock* block : code()->instruction_blocks()) {
130 131
    CompressBlock(block);
  }
132
  for (InstructionBlock* block : code()->instruction_blocks()) {
133
    if (block->PredecessorCount() <= 1) continue;
134 135
    if (!block->IsDeferred()) {
      bool has_only_deferred = true;
mtrofin's avatar
mtrofin committed
136
      for (RpoNumber& pred_id : block->predecessors()) {
137 138 139 140
        if (!code()->InstructionBlockAt(pred_id)->IsDeferred()) {
          has_only_deferred = false;
          break;
        }
141
      }
142 143 144 145 146
      // This would pull down common moves. If the moves occur in deferred
      // blocks, and the closest common successor is not deferred, we lose the
      // optimization of just spilling/filling in deferred blocks, when the
      // current block is not deferred.
      if (has_only_deferred) continue;
147
    }
148 149
    OptimizeMerge(block);
  }
150
  for (Instruction* gap : code()->instructions()) {
151 152 153 154
    FinalizeMoves(gap);
  }
}

155 156 157 158
void MoveOptimizer::RemoveClobberedDestinations(Instruction* instruction) {
  if (instruction->IsCall()) return;
  ParallelMove* moves = instruction->parallel_moves()[0];
  if (moves == nullptr) return;
159

160 161 162 163 164 165 166 167 168
  DCHECK(instruction->parallel_moves()[1] == nullptr ||
         instruction->parallel_moves()[1]->empty());

  OperandSet outputs(local_zone());
  OperandSet inputs(local_zone());

  // Outputs and temps are treated together as potentially clobbering a
  // destination operand.
  for (size_t i = 0; i < instruction->OutputCount(); ++i) {
169
    outputs.InsertOp(*instruction->OutputAt(i));
170 171
  }
  for (size_t i = 0; i < instruction->TempCount(); ++i) {
172
    outputs.InsertOp(*instruction->TempAt(i));
173 174 175 176
  }

  // Input operands block elisions.
  for (size_t i = 0; i < instruction->InputCount(); ++i) {
177
    inputs.InsertOp(*instruction->InputAt(i));
178 179 180 181
  }

  // Elide moves made redundant by the instruction.
  for (MoveOperands* move : *moves) {
182 183
    if (outputs.ContainsOpOrAlias(move->destination()) &&
        !inputs.ContainsOpOrAlias(move->destination())) {
184 185 186 187 188 189
      move->Eliminate();
    }
  }

  // The ret instruction makes any assignment before it unnecessary, except for
  // the one for its input.
190
  if (instruction->IsRet() || instruction->IsTailCall()) {
191
    for (MoveOperands* move : *moves) {
192
      if (!inputs.ContainsOpOrAlias(move->destination())) {
193 194 195 196 197 198 199 200 201 202 203 204
        move->Eliminate();
      }
    }
  }
}

void MoveOptimizer::MigrateMoves(Instruction* to, Instruction* from) {
  if (from->IsCall()) return;

  ParallelMove* from_moves = from->parallel_moves()[0];
  if (from_moves == nullptr || from_moves->empty()) return;

205 206
  OperandSet dst_cant_be(local_zone());
  OperandSet src_cant_be(local_zone());
207 208 209 210

  // If an operand is an input to the instruction, we cannot move assignments
  // where it appears on the LHS.
  for (size_t i = 0; i < from->InputCount(); ++i) {
211
    dst_cant_be.InsertOp(*from->InputAt(i));
212 213 214 215 216 217 218 219
  }
  // If an operand is output to the instruction, we cannot move assignments
  // where it appears on the RHS, because we would lose its value before the
  // instruction.
  // Same for temp operands.
  // The output can't appear on the LHS because we performed
  // RemoveClobberedDestinations for the "from" instruction.
  for (size_t i = 0; i < from->OutputCount(); ++i) {
220
    src_cant_be.InsertOp(*from->OutputAt(i));
221 222
  }
  for (size_t i = 0; i < from->TempCount(); ++i) {
223
    src_cant_be.InsertOp(*from->TempAt(i));
224 225 226 227 228 229 230
  }
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
    // Assume dest has a value "V". If we have a "dest = y" move, then we can't
    // move "z = dest", because z would become y rather than "V".
    // We assume CompressMoves has happened before this, which means we don't
    // have more than one assignment to dest.
231
    src_cant_be.InsertOp(move->destination());
232 233 234 235 236 237 238
  }

  ZoneSet<MoveKey, MoveKeyCompare> move_candidates(local_zone());
  // We start with all the moves that don't have conflicting source or
  // destination operands are eligible for being moved down.
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
239
    if (!dst_cant_be.ContainsOpOrAlias(move->destination())) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253
      MoveKey key = {move->source(), move->destination()};
      move_candidates.insert(key);
    }
  }
  if (move_candidates.empty()) return;

  // Stabilize the candidate set.
  bool changed = false;
  do {
    changed = false;
    for (auto iter = move_candidates.begin(); iter != move_candidates.end();) {
      auto current = iter;
      ++iter;
      InstructionOperand src = current->source;
254 255
      if (src_cant_be.ContainsOpOrAlias(src)) {
        src_cant_be.InsertOp(current->destination);
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
        move_candidates.erase(current);
        changed = true;
      }
    }
  } while (changed);

  ParallelMove to_move(local_zone());
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
    MoveKey key = {move->source(), move->destination()};
    if (move_candidates.find(key) != move_candidates.end()) {
      to_move.AddMove(move->source(), move->destination(), code_zone());
      move->Eliminate();
    }
  }
  if (to_move.empty()) return;

  ParallelMove* dest =
      to->GetOrCreateParallelMove(Instruction::GapPosition::START, code_zone());

  CompressMoves(&to_move, dest);
  DCHECK(dest->empty());
  for (MoveOperands* m : to_move) {
    dest->push_back(m);
  }
}

void MoveOptimizer::CompressMoves(ParallelMove* left, MoveOpVector* right) {
284 285
  if (right == nullptr) return;

286 287 288
  MoveOpVector& eliminated = local_vector();
  DCHECK(eliminated.empty());

289
  if (!left->empty()) {
290 291
    // Modify the right moves in place and collect moves that will be killed by
    // merging the two gaps.
mtrofin's avatar
mtrofin committed
292
    for (MoveOperands* move : *right) {
293
      if (move->IsRedundant()) continue;
294
      left->PrepareInsertAfter(move, &eliminated);
295
    }
296
    // Eliminate dead moves.
297
    for (MoveOperands* to_eliminate : eliminated) {
298 299
      to_eliminate->Eliminate();
    }
300
    eliminated.clear();
301 302
  }
  // Add all possibly modified moves from right side.
mtrofin's avatar
mtrofin committed
303
  for (MoveOperands* move : *right) {
304 305
    if (move->IsRedundant()) continue;
    left->push_back(move);
306 307
  }
  // Nuke right.
308
  right->clear();
309
  DCHECK(eliminated.empty());
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
void MoveOptimizer::CompressGaps(Instruction* instruction) {
  int i = FindFirstNonEmptySlot(instruction);
  bool has_moves = i <= Instruction::LAST_GAP_POSITION;
  USE(has_moves);

  if (i == Instruction::LAST_GAP_POSITION) {
    std::swap(instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION],
              instruction->parallel_moves()[Instruction::LAST_GAP_POSITION]);
  } else if (i == Instruction::FIRST_GAP_POSITION) {
    CompressMoves(
        instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION],
        instruction->parallel_moves()[Instruction::LAST_GAP_POSITION]);
  }
  // We either have no moves, or, after swapping or compressing, we have
  // all the moves in the first gap position, and none in the second/end gap
  // position.
  ParallelMove* first =
      instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION];
  ParallelMove* last =
      instruction->parallel_moves()[Instruction::LAST_GAP_POSITION];
  USE(first);
  USE(last);

  DCHECK(!has_moves ||
         (first != nullptr && (last == nullptr || last->empty())));
}
338

339
void MoveOptimizer::CompressBlock(InstructionBlock* block) {
340 341
  int first_instr_index = block->first_instruction_index();
  int last_instr_index = block->last_instruction_index();
342

343 344 345 346 347 348 349 350 351 352 353 354
  // Start by removing gap assignments where the output of the subsequent
  // instruction appears on LHS, as long as they are not needed by its input.
  Instruction* prev_instr = code()->instructions()[first_instr_index];
  RemoveClobberedDestinations(prev_instr);

  for (int index = first_instr_index + 1; index <= last_instr_index; ++index) {
    Instruction* instr = code()->instructions()[index];
    // Migrate to the gap of prev_instr eligible moves from instr.
    MigrateMoves(instr, prev_instr);
    // Remove gap assignments clobbered by instr's output.
    RemoveClobberedDestinations(instr);
    prev_instr = instr;
355
  }
356 357 358
}


mtrofin's avatar
mtrofin committed
359 360
const Instruction* MoveOptimizer::LastInstruction(
    const InstructionBlock* block) const {
361
  return code()->instructions()[block->last_instruction_index()];
362 363 364 365 366 367 368
}


void MoveOptimizer::OptimizeMerge(InstructionBlock* block) {
  DCHECK(block->PredecessorCount() > 1);
  // Ensure that the last instruction in all incoming blocks don't contain
  // things that would prevent moving gap moves across them.
mtrofin's avatar
mtrofin committed
369 370
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
371 372 373 374 375 376

    // If the predecessor has more than one successor, we shouldn't attempt to
    // move down to this block (one of the successors) any of the gap moves,
    // because their effect may be necessary to the other successors.
    if (pred->SuccessorCount() > 1) return;

mtrofin's avatar
mtrofin committed
377 378
    const Instruction* last_instr =
        code()->instructions()[pred->last_instruction_index()];
379 380 381 382
    if (last_instr->IsCall()) return;
    if (last_instr->TempCount() != 0) return;
    if (last_instr->OutputCount() != 0) return;
    for (size_t i = 0; i < last_instr->InputCount(); ++i) {
mtrofin's avatar
mtrofin committed
383
      const InstructionOperand* op = last_instr->InputAt(i);
384 385 386
      if (!op->IsConstant() && !op->IsImmediate()) return;
    }
  }
387
  // TODO(dcarney): pass a ZoneStats down for this?
388 389 390
  MoveMap move_map(local_zone());
  size_t correct_counts = 0;
  // Accumulate set of shared moves.
mtrofin's avatar
mtrofin committed
391 392 393
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
    const Instruction* instr = LastInstruction(pred);
394
    if (instr->parallel_moves()[0] == nullptr ||
395
        instr->parallel_moves()[0]->empty()) {
396 397
      return;
    }
mtrofin's avatar
mtrofin committed
398
    for (const MoveOperands* move : *instr->parallel_moves()[0]) {
399
      if (move->IsRedundant()) continue;
mtrofin's avatar
mtrofin committed
400 401
      InstructionOperand src = move->source();
      InstructionOperand dst = move->destination();
402 403 404 405 406 407 408 409 410 411
      MoveKey key = {src, dst};
      auto res = move_map.insert(std::make_pair(key, 1));
      if (!res.second) {
        res.first->second++;
        if (res.first->second == block->PredecessorCount()) {
          correct_counts++;
        }
      }
    }
  }
412 413
  if (move_map.empty() || correct_counts == 0) return;

414
  // Find insertion point.
415
  Instruction* instr = code()->instructions()[block->first_instruction_index()];
416 417 418 419 420 421 422 423 424

  if (correct_counts != move_map.size()) {
    // Moves that are unique to each predecessor won't be pushed to the common
    // successor.
    OperandSet conflicting_srcs(local_zone());
    for (auto iter = move_map.begin(), end = move_map.end(); iter != end;) {
      auto current = iter;
      ++iter;
      if (current->second != block->PredecessorCount()) {
425
        InstructionOperand dest = current->first.destination;
426 427 428 429
        // Not all the moves in all the gaps are the same. Maybe some are. If
        // there are such moves, we could move them, but the destination of the
        // moves staying behind can't appear as a source of a common move,
        // because the move staying behind will clobber this destination.
430
        conflicting_srcs.InsertOp(dest);
431 432 433 434 435 436 437 438 439 440 441 442 443
        move_map.erase(current);
      }
    }

    bool changed = false;
    do {
      // If a common move can't be pushed to the common successor, then its
      // destination also can't appear as source to any move being pushed.
      changed = false;
      for (auto iter = move_map.begin(), end = move_map.end(); iter != end;) {
        auto current = iter;
        ++iter;
        DCHECK_EQ(block->PredecessorCount(), current->second);
444 445
        if (conflicting_srcs.ContainsOpOrAlias(current->first.source)) {
          conflicting_srcs.InsertOp(current->first.destination);
446 447 448 449 450 451 452 453 454
          move_map.erase(current);
          changed = true;
        }
      }
    } while (changed);
  }

  if (move_map.empty()) return;

455
  DCHECK_NOT_NULL(instr);
456
  bool gap_initialized = true;
457 458
  if (instr->parallel_moves()[0] != nullptr &&
      !instr->parallel_moves()[0]->empty()) {
459 460
    // Will compress after insertion.
    gap_initialized = false;
461
    std::swap(instr->parallel_moves()[0], instr->parallel_moves()[1]);
462
  }
mtrofin's avatar
mtrofin committed
463
  ParallelMove* moves = instr->GetOrCreateParallelMove(
464
      static_cast<Instruction::GapPosition>(0), code_zone());
465 466
  // Delete relevant entries in predecessors and move everything to block.
  bool first_iteration = true;
mtrofin's avatar
mtrofin committed
467 468 469
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
    for (MoveOperands* move : *LastInstruction(pred)->parallel_moves()[0]) {
470 471
      if (move->IsRedundant()) continue;
      MoveKey key = {move->source(), move->destination()};
472
      auto it = move_map.find(key);
473 474 475 476 477
      if (it != move_map.end()) {
        if (first_iteration) {
          moves->AddMove(move->source(), move->destination());
        }
        move->Eliminate();
478 479 480 481 482 483
      }
    }
    first_iteration = false;
  }
  // Compress.
  if (!gap_initialized) {
484
    CompressMoves(instr->parallel_moves()[0], instr->parallel_moves()[1]);
485
  }
486
  CompressBlock(block);
487 488 489
}


490 491 492
namespace {

bool IsSlot(const InstructionOperand& op) {
493
  return op.IsStackSlot() || op.IsFPStackSlot();
494 495 496 497
}


bool LoadCompare(const MoveOperands* a, const MoveOperands* b) {
498 499
  if (!a->source().EqualsCanonicalized(b->source())) {
    return a->source().CompareCanonicalized(b->source());
500
  }
501 502
  if (IsSlot(a->destination()) && !IsSlot(b->destination())) return false;
  if (!IsSlot(a->destination()) && IsSlot(b->destination())) return true;
503
  return a->destination().CompareCanonicalized(b->destination());
504 505 506 507 508
}

}  // namespace


509 510
// Split multiple loads of the same constant or stack slot off into the second
// slot and keep remaining moves in the first slot.
511
void MoveOptimizer::FinalizeMoves(Instruction* instr) {
512
  MoveOpVector& loads = local_vector();
513
  DCHECK(loads.empty());
514

515 516
  ParallelMove* parallel_moves = instr->parallel_moves()[0];
  if (parallel_moves == nullptr) return;
517
  // Find all the loads.
518
  for (MoveOperands* move : *parallel_moves) {
519 520
    if (move->IsRedundant()) continue;
    if (move->source().IsConstant() || IsSlot(move->source())) {
521
      loads.push_back(move);
522
    }
523 524 525 526 527 528
  }
  if (loads.empty()) return;
  // Group the loads by source, moving the preferred destination to the
  // beginning of the group.
  std::sort(loads.begin(), loads.end(), LoadCompare);
  MoveOperands* group_begin = nullptr;
mtrofin's avatar
mtrofin committed
529
  for (MoveOperands* load : loads) {
530
    // New group.
531
    if (group_begin == nullptr ||
532
        !load->source().EqualsCanonicalized(group_begin->source())) {
533 534
      group_begin = load;
      continue;
535
    }
536 537 538
    // Nothing to be gained from splitting here.
    if (IsSlot(group_begin->destination())) continue;
    // Insert new move into slot 1.
mtrofin's avatar
mtrofin committed
539
    ParallelMove* slot_1 = instr->GetOrCreateParallelMove(
540 541 542
        static_cast<Instruction::GapPosition>(1), code_zone());
    slot_1->AddMove(group_begin->destination(), load->destination());
    load->Eliminate();
543
  }
544
  loads.clear();
545 546 547 548 549
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8