1 // Copyright 2013 the V8 project authors. All rights reserved. 2 // Redistribution and use in source and binary forms, with or without 3 // modification, are permitted provided that the following conditions are 4 // met: 5 // 6 // * Redistributions of source code must retain the above copyright 7 // notice, this list of conditions and the following disclaimer. 8 // * Redistributions in binary form must reproduce the above 9 // copyright notice, this list of conditions and the following 10 // disclaimer in the documentation and/or other materials provided 11 // with the distribution. 12 // * Neither the name of Google Inc. nor the names of its 13 // contributors may be used to endorse or promote products derived 14 // from this software without specific prior written permission. 15 // 16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 28 #include "hydrogen-bce.h" 29 30 namespace v8 { 31 namespace internal { 32 33 // We try to "factor up" HBoundsCheck instructions towards the root of the 34 // dominator tree. 35 // For now we handle checks where the index is like "exp + int32value". 36 // If in the dominator tree we check "exp + v1" and later (dominated) 37 // "exp + v2", if v2 <= v1 we can safely remove the second check, and if 38 // v2 > v1 we can use v2 in the 1st check and again remove the second. 39 // To do so we keep a dictionary of all checks where the key if the pair 40 // "exp, length". 41 // The class BoundsCheckKey represents this key. 42 class BoundsCheckKey : public ZoneObject { 43 public: 44 HValue* IndexBase() const { return index_base_; } 45 HValue* Length() const { return length_; } 46 47 uint32_t Hash() { 48 return static_cast<uint32_t>(index_base_->Hashcode() ^ length_->Hashcode()); 49 } 50 51 static BoundsCheckKey* Create(Zone* zone, 52 HBoundsCheck* check, 53 int32_t* offset) { 54 if (!check->index()->representation().IsSmiOrInteger32()) return NULL; 55 56 HValue* index_base = NULL; 57 HConstant* constant = NULL; 58 bool is_sub = false; 59 60 if (check->index()->IsAdd()) { 61 HAdd* index = HAdd::cast(check->index()); 62 if (index->left()->IsConstant()) { 63 constant = HConstant::cast(index->left()); 64 index_base = index->right(); 65 } else if (index->right()->IsConstant()) { 66 constant = HConstant::cast(index->right()); 67 index_base = index->left(); 68 } 69 } else if (check->index()->IsSub()) { 70 HSub* index = HSub::cast(check->index()); 71 is_sub = true; 72 if (index->left()->IsConstant()) { 73 constant = HConstant::cast(index->left()); 74 index_base = index->right(); 75 } else if (index->right()->IsConstant()) { 76 constant = HConstant::cast(index->right()); 77 index_base = index->left(); 78 } 79 } 80 81 if (constant != NULL && constant->HasInteger32Value()) { 82 *offset = is_sub ? - constant->Integer32Value() 83 : constant->Integer32Value(); 84 } else { 85 *offset = 0; 86 index_base = check->index(); 87 } 88 89 return new(zone) BoundsCheckKey(index_base, check->length()); 90 } 91 92 private: 93 BoundsCheckKey(HValue* index_base, HValue* length) 94 : index_base_(index_base), 95 length_(length) { } 96 97 HValue* index_base_; 98 HValue* length_; 99 100 DISALLOW_COPY_AND_ASSIGN(BoundsCheckKey); 101 }; 102 103 104 // Data about each HBoundsCheck that can be eliminated or moved. 105 // It is the "value" in the dictionary indexed by "base-index, length" 106 // (the key is BoundsCheckKey). 107 // We scan the code with a dominator tree traversal. 108 // Traversing the dominator tree we keep a stack (implemented as a singly 109 // linked list) of "data" for each basic block that contains a relevant check 110 // with the same key (the dictionary holds the head of the list). 111 // We also keep all the "data" created for a given basic block in a list, and 112 // use it to "clean up" the dictionary when backtracking in the dominator tree 113 // traversal. 114 // Doing this each dictionary entry always directly points to the check that 115 // is dominating the code being examined now. 116 // We also track the current "offset" of the index expression and use it to 117 // decide if any check is already "covered" (so it can be removed) or not. 118 class BoundsCheckBbData: public ZoneObject { 119 public: 120 BoundsCheckKey* Key() const { return key_; } 121 int32_t LowerOffset() const { return lower_offset_; } 122 int32_t UpperOffset() const { return upper_offset_; } 123 HBasicBlock* BasicBlock() const { return basic_block_; } 124 HBoundsCheck* LowerCheck() const { return lower_check_; } 125 HBoundsCheck* UpperCheck() const { return upper_check_; } 126 BoundsCheckBbData* NextInBasicBlock() const { return next_in_bb_; } 127 BoundsCheckBbData* FatherInDominatorTree() const { return father_in_dt_; } 128 129 bool OffsetIsCovered(int32_t offset) const { 130 return offset >= LowerOffset() && offset <= UpperOffset(); 131 } 132 133 bool HasSingleCheck() { return lower_check_ == upper_check_; } 134 135 // The goal of this method is to modify either upper_offset_ or 136 // lower_offset_ so that also new_offset is covered (the covered 137 // range grows). 138 // 139 // The precondition is that new_check follows UpperCheck() and 140 // LowerCheck() in the same basic block, and that new_offset is not 141 // covered (otherwise we could simply remove new_check). 142 // 143 // If HasSingleCheck() is true then new_check is added as "second check" 144 // (either upper or lower; note that HasSingleCheck() becomes false). 145 // Otherwise one of the current checks is modified so that it also covers 146 // new_offset, and new_check is removed. 147 void CoverCheck(HBoundsCheck* new_check, 148 int32_t new_offset) { 149 ASSERT(new_check->index()->representation().IsSmiOrInteger32()); 150 bool keep_new_check = false; 151 152 if (new_offset > upper_offset_) { 153 upper_offset_ = new_offset; 154 if (HasSingleCheck()) { 155 keep_new_check = true; 156 upper_check_ = new_check; 157 } else { 158 TightenCheck(upper_check_, new_check); 159 } 160 } else if (new_offset < lower_offset_) { 161 lower_offset_ = new_offset; 162 if (HasSingleCheck()) { 163 keep_new_check = true; 164 lower_check_ = new_check; 165 } else { 166 TightenCheck(lower_check_, new_check); 167 } 168 } else { 169 // Should never have called CoverCheck() in this case. 170 UNREACHABLE(); 171 } 172 173 if (!keep_new_check) { 174 new_check->block()->graph()->isolate()->counters()-> 175 bounds_checks_eliminated()->Increment(); 176 new_check->DeleteAndReplaceWith(new_check->ActualValue()); 177 } else { 178 HBoundsCheck* first_check = new_check == lower_check_ ? upper_check_ 179 : lower_check_; 180 // The length is guaranteed to be live at first_check. 181 ASSERT(new_check->length() == first_check->length()); 182 HInstruction* old_position = new_check->next(); 183 new_check->Unlink(); 184 new_check->InsertAfter(first_check); 185 MoveIndexIfNecessary(new_check->index(), new_check, old_position); 186 } 187 } 188 189 BoundsCheckBbData(BoundsCheckKey* key, 190 int32_t lower_offset, 191 int32_t upper_offset, 192 HBasicBlock* bb, 193 HBoundsCheck* lower_check, 194 HBoundsCheck* upper_check, 195 BoundsCheckBbData* next_in_bb, 196 BoundsCheckBbData* father_in_dt) 197 : key_(key), 198 lower_offset_(lower_offset), 199 upper_offset_(upper_offset), 200 basic_block_(bb), 201 lower_check_(lower_check), 202 upper_check_(upper_check), 203 next_in_bb_(next_in_bb), 204 father_in_dt_(father_in_dt) { } 205 206 private: 207 BoundsCheckKey* key_; 208 int32_t lower_offset_; 209 int32_t upper_offset_; 210 HBasicBlock* basic_block_; 211 HBoundsCheck* lower_check_; 212 HBoundsCheck* upper_check_; 213 BoundsCheckBbData* next_in_bb_; 214 BoundsCheckBbData* father_in_dt_; 215 216 void MoveIndexIfNecessary(HValue* index_raw, 217 HBoundsCheck* insert_before, 218 HInstruction* end_of_scan_range) { 219 if (!index_raw->IsAdd() && !index_raw->IsSub()) { 220 // index_raw can be HAdd(index_base, offset), HSub(index_base, offset), 221 // or index_base directly. In the latter case, no need to move anything. 222 return; 223 } 224 HArithmeticBinaryOperation* index = 225 HArithmeticBinaryOperation::cast(index_raw); 226 HValue* left_input = index->left(); 227 HValue* right_input = index->right(); 228 bool must_move_index = false; 229 bool must_move_left_input = false; 230 bool must_move_right_input = false; 231 for (HInstruction* cursor = end_of_scan_range; cursor != insert_before;) { 232 if (cursor == left_input) must_move_left_input = true; 233 if (cursor == right_input) must_move_right_input = true; 234 if (cursor == index) must_move_index = true; 235 if (cursor->previous() == NULL) { 236 cursor = cursor->block()->dominator()->end(); 237 } else { 238 cursor = cursor->previous(); 239 } 240 } 241 if (must_move_index) { 242 index->Unlink(); 243 index->InsertBefore(insert_before); 244 } 245 // The BCE algorithm only selects mergeable bounds checks that share 246 // the same "index_base", so we'll only ever have to move constants. 247 if (must_move_left_input) { 248 HConstant::cast(left_input)->Unlink(); 249 HConstant::cast(left_input)->InsertBefore(index); 250 } 251 if (must_move_right_input) { 252 HConstant::cast(right_input)->Unlink(); 253 HConstant::cast(right_input)->InsertBefore(index); 254 } 255 } 256 257 void TightenCheck(HBoundsCheck* original_check, 258 HBoundsCheck* tighter_check) { 259 ASSERT(original_check->length() == tighter_check->length()); 260 MoveIndexIfNecessary(tighter_check->index(), original_check, tighter_check); 261 original_check->ReplaceAllUsesWith(original_check->index()); 262 original_check->SetOperandAt(0, tighter_check->index()); 263 } 264 265 DISALLOW_COPY_AND_ASSIGN(BoundsCheckBbData); 266 }; 267 268 269 static bool BoundsCheckKeyMatch(void* key1, void* key2) { 270 BoundsCheckKey* k1 = static_cast<BoundsCheckKey*>(key1); 271 BoundsCheckKey* k2 = static_cast<BoundsCheckKey*>(key2); 272 return k1->IndexBase() == k2->IndexBase() && k1->Length() == k2->Length(); 273 } 274 275 276 BoundsCheckTable::BoundsCheckTable(Zone* zone) 277 : ZoneHashMap(BoundsCheckKeyMatch, ZoneHashMap::kDefaultHashMapCapacity, 278 ZoneAllocationPolicy(zone)) { } 279 280 281 BoundsCheckBbData** BoundsCheckTable::LookupOrInsert(BoundsCheckKey* key, 282 Zone* zone) { 283 return reinterpret_cast<BoundsCheckBbData**>( 284 &(Lookup(key, key->Hash(), true, ZoneAllocationPolicy(zone))->value)); 285 } 286 287 288 void BoundsCheckTable::Insert(BoundsCheckKey* key, 289 BoundsCheckBbData* data, 290 Zone* zone) { 291 Lookup(key, key->Hash(), true, ZoneAllocationPolicy(zone))->value = data; 292 } 293 294 295 void BoundsCheckTable::Delete(BoundsCheckKey* key) { 296 Remove(key, key->Hash()); 297 } 298 299 300 class HBoundsCheckEliminationState { 301 public: 302 HBasicBlock* block_; 303 BoundsCheckBbData* bb_data_list_; 304 int index_; 305 }; 306 307 308 // Eliminates checks in bb and recursively in the dominated blocks. 309 // Also replace the results of check instructions with the original value, if 310 // the result is used. This is safe now, since we don't do code motion after 311 // this point. It enables better register allocation since the value produced 312 // by check instructions is really a copy of the original value. 313 void HBoundsCheckEliminationPhase::EliminateRedundantBoundsChecks( 314 HBasicBlock* entry) { 315 // Allocate the stack. 316 HBoundsCheckEliminationState* stack = 317 zone()->NewArray<HBoundsCheckEliminationState>(graph()->blocks()->length()); 318 319 // Explicitly push the entry block. 320 stack[0].block_ = entry; 321 stack[0].bb_data_list_ = PreProcessBlock(entry); 322 stack[0].index_ = 0; 323 int stack_depth = 1; 324 325 // Implement depth-first traversal with a stack. 326 while (stack_depth > 0) { 327 int current = stack_depth - 1; 328 HBoundsCheckEliminationState* state = &stack[current]; 329 const ZoneList<HBasicBlock*>* children = state->block_->dominated_blocks(); 330 331 if (state->index_ < children->length()) { 332 // Recursively visit children blocks. 333 HBasicBlock* child = children->at(state->index_++); 334 int next = stack_depth++; 335 stack[next].block_ = child; 336 stack[next].bb_data_list_ = PreProcessBlock(child); 337 stack[next].index_ = 0; 338 } else { 339 // Finished with all children; post process the block. 340 PostProcessBlock(state->block_, state->bb_data_list_); 341 stack_depth--; 342 } 343 } 344 } 345 346 347 BoundsCheckBbData* HBoundsCheckEliminationPhase::PreProcessBlock( 348 HBasicBlock* bb) { 349 BoundsCheckBbData* bb_data_list = NULL; 350 351 for (HInstructionIterator it(bb); !it.Done(); it.Advance()) { 352 HInstruction* i = it.Current(); 353 if (!i->IsBoundsCheck()) continue; 354 355 HBoundsCheck* check = HBoundsCheck::cast(i); 356 int32_t offset; 357 BoundsCheckKey* key = 358 BoundsCheckKey::Create(zone(), check, &offset); 359 if (key == NULL) continue; 360 BoundsCheckBbData** data_p = table_.LookupOrInsert(key, zone()); 361 BoundsCheckBbData* data = *data_p; 362 if (data == NULL) { 363 bb_data_list = new(zone()) BoundsCheckBbData(key, 364 offset, 365 offset, 366 bb, 367 check, 368 check, 369 bb_data_list, 370 NULL); 371 *data_p = bb_data_list; 372 } else if (data->OffsetIsCovered(offset)) { 373 bb->graph()->isolate()->counters()-> 374 bounds_checks_eliminated()->Increment(); 375 check->DeleteAndReplaceWith(check->ActualValue()); 376 } else if (data->BasicBlock() == bb) { 377 data->CoverCheck(check, offset); 378 } else if (graph()->use_optimistic_licm() || 379 bb->IsLoopSuccessorDominator()) { 380 int32_t new_lower_offset = offset < data->LowerOffset() 381 ? offset 382 : data->LowerOffset(); 383 int32_t new_upper_offset = offset > data->UpperOffset() 384 ? offset 385 : data->UpperOffset(); 386 bb_data_list = new(zone()) BoundsCheckBbData(key, 387 new_lower_offset, 388 new_upper_offset, 389 bb, 390 data->LowerCheck(), 391 data->UpperCheck(), 392 bb_data_list, 393 data); 394 table_.Insert(key, bb_data_list, zone()); 395 } 396 } 397 398 return bb_data_list; 399 } 400 401 402 void HBoundsCheckEliminationPhase::PostProcessBlock( 403 HBasicBlock* block, BoundsCheckBbData* data) { 404 while (data != NULL) { 405 if (data->FatherInDominatorTree()) { 406 table_.Insert(data->Key(), data->FatherInDominatorTree(), zone()); 407 } else { 408 table_.Delete(data->Key()); 409 } 410 data = data->NextInBasicBlock(); 411 } 412 } 413 414 } } // namespace v8::internal 415