Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/GVN.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This pass performs global value numbering to eliminate fully redundant
10
// instructions.  It also performs simple dead load elimination.
11
//
12
// Note that this pass does the value numbering itself; it does not use the
13
// ValueNumbering analysis passes.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "llvm/Transforms/Scalar/GVN.h"
18
#include "llvm/ADT/DenseMap.h"
19
#include "llvm/ADT/DepthFirstIterator.h"
20
#include "llvm/ADT/Hashing.h"
21
#include "llvm/ADT/MapVector.h"
22
#include "llvm/ADT/PointerIntPair.h"
23
#include "llvm/ADT/PostOrderIterator.h"
24
#include "llvm/ADT/STLExtras.h"
25
#include "llvm/ADT/SetVector.h"
26
#include "llvm/ADT/SmallPtrSet.h"
27
#include "llvm/ADT/SmallVector.h"
28
#include "llvm/ADT/Statistic.h"
29
#include "llvm/Analysis/AliasAnalysis.h"
30
#include "llvm/Analysis/AssumptionCache.h"
31
#include "llvm/Analysis/CFG.h"
32
#include "llvm/Analysis/DomTreeUpdater.h"
33
#include "llvm/Analysis/GlobalsModRef.h"
34
#include "llvm/Analysis/InstructionSimplify.h"
35
#include "llvm/Analysis/LoopInfo.h"
36
#include "llvm/Analysis/MemoryBuiltins.h"
37
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
39
#include "llvm/Analysis/PHITransAddr.h"
40
#include "llvm/Analysis/TargetLibraryInfo.h"
41
#include "llvm/Analysis/ValueTracking.h"
42
#include "llvm/Config/llvm-config.h"
43
#include "llvm/IR/Attributes.h"
44
#include "llvm/IR/BasicBlock.h"
45
#include "llvm/IR/CallSite.h"
46
#include "llvm/IR/Constant.h"
47
#include "llvm/IR/Constants.h"
48
#include "llvm/IR/DataLayout.h"
49
#include "llvm/IR/DebugInfoMetadata.h"
50
#include "llvm/IR/DebugLoc.h"
51
#include "llvm/IR/Dominators.h"
52
#include "llvm/IR/Function.h"
53
#include "llvm/IR/InstrTypes.h"
54
#include "llvm/IR/Instruction.h"
55
#include "llvm/IR/Instructions.h"
56
#include "llvm/IR/IntrinsicInst.h"
57
#include "llvm/IR/Intrinsics.h"
58
#include "llvm/IR/LLVMContext.h"
59
#include "llvm/IR/Metadata.h"
60
#include "llvm/IR/Module.h"
61
#include "llvm/IR/Operator.h"
62
#include "llvm/IR/PassManager.h"
63
#include "llvm/IR/PatternMatch.h"
64
#include "llvm/IR/Type.h"
65
#include "llvm/IR/Use.h"
66
#include "llvm/IR/Value.h"
67
#include "llvm/Pass.h"
68
#include "llvm/Support/Casting.h"
69
#include "llvm/Support/CommandLine.h"
70
#include "llvm/Support/Compiler.h"
71
#include "llvm/Support/Debug.h"
72
#include "llvm/Support/raw_ostream.h"
73
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
74
#include "llvm/Transforms/Utils/Local.h"
75
#include "llvm/Transforms/Utils/SSAUpdater.h"
76
#include "llvm/Transforms/Utils/VNCoercion.h"
77
#include <algorithm>
78
#include <cassert>
79
#include <cstdint>
80
#include <utility>
81
#include <vector>
82
83
using namespace llvm;
84
using namespace llvm::gvn;
85
using namespace llvm::VNCoercion;
86
using namespace PatternMatch;
87
88
3.77M
#define DEBUG_TYPE "gvn"
89
90
STATISTIC(NumGVNInstr,  "Number of instructions deleted");
91
STATISTIC(NumGVNLoad,   "Number of loads deleted");
92
STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
93
STATISTIC(NumGVNBlocks, "Number of blocks merged");
94
STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
95
STATISTIC(NumGVNEqProp, "Number of equalities propagated");
96
STATISTIC(NumPRELoad,   "Number of loads PRE'd");
97
98
static cl::opt<bool> EnablePRE("enable-pre",
99
                               cl::init(true), cl::Hidden);
100
static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
101
static cl::opt<bool> EnableMemDep("enable-gvn-memdep", cl::init(true));
102
103
// Maximum allowed recursion depth.
104
static cl::opt<uint32_t>
105
MaxRecurseDepth("gvn-max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
106
                cl::desc("Max recurse depth in GVN (default = 1000)"));
107
108
static cl::opt<uint32_t> MaxNumDeps(
109
    "gvn-max-num-deps", cl::Hidden, cl::init(100), cl::ZeroOrMore,
110
    cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
111
112
struct llvm::GVN::Expression {
113
  uint32_t opcode;
114
  Type *type;
115
  bool commutative = false;
116
  SmallVector<uint32_t, 4> varargs;
117
118
89.7M
  Expression(uint32_t o = ~2U) : opcode(o) {}
119
120
169M
  bool operator==(const Expression &other) const {
121
169M
    if (opcode != other.opcode)
122
80.4M
      return false;
123
88.9M
    if (opcode == ~0U || 
opcode == ~1U7.04M
)
124
81.8M
      return true;
125
7.04M
    if (type != other.type)
126
613k
      return false;
127
6.43M
    if (varargs != other.varargs)
128
1.10M
      return false;
129
5.33M
    return true;
130
5.33M
  }
131
132
21.6M
  friend hash_code hash_value(const Expression &Value) {
133
21.6M
    return hash_combine(
134
21.6M
        Value.opcode, Value.type,
135
21.6M
        hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
136
21.6M
  }
137
};
138
139
namespace llvm {
140
141
template <> struct DenseMapInfo<GVN::Expression> {
142
35.3M
  static inline GVN::Expression getEmptyKey() { return ~0U; }
143
22.0M
  static inline GVN::Expression getTombstoneKey() { return ~1U; }
144
145
21.6M
  static unsigned getHashValue(const GVN::Expression &e) {
146
21.6M
    using llvm::hash_value;
147
21.6M
148
21.6M
    return static_cast<unsigned>(hash_value(e));
149
21.6M
  }
150
151
169M
  static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) {
152
169M
    return LHS == RHS;
153
169M
  }
154
};
155
156
} // end namespace llvm
157
158
/// Represents a particular available value that we know how to materialize.
159
/// Materialization of an AvailableValue never fails.  An AvailableValue is
160
/// implicitly associated with a rematerialization point which is the
161
/// location of the instruction from which it was formed.
162
struct llvm::gvn::AvailableValue {
163
  enum ValType {
164
    SimpleVal, // A simple offsetted value that is accessed.
165
    LoadVal,   // A value produced by a load.
166
    MemIntrin, // A memory intrinsic which is loaded from.
167
    UndefVal   // A UndefValue representing a value from dead block (which
168
               // is not yet physically removed from the CFG).
169
  };
170
171
  /// V - The value that is live out of the block.
172
  PointerIntPair<Value *, 2, ValType> Val;
173
174
  /// Offset - The byte offset in Val that is interesting for the load query.
175
  unsigned Offset;
176
177
217k
  static AvailableValue get(Value *V, unsigned Offset = 0) {
178
217k
    AvailableValue Res;
179
217k
    Res.Val.setPointer(V);
180
217k
    Res.Val.setInt(SimpleVal);
181
217k
    Res.Offset = Offset;
182
217k
    return Res;
183
217k
  }
184
185
6.97k
  static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
186
6.97k
    AvailableValue Res;
187
6.97k
    Res.Val.setPointer(MI);
188
6.97k
    Res.Val.setInt(MemIntrin);
189
6.97k
    Res.Offset = Offset;
190
6.97k
    return Res;
191
6.97k
  }
192
193
288k
  static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) {
194
288k
    AvailableValue Res;
195
288k
    Res.Val.setPointer(LI);
196
288k
    Res.Val.setInt(LoadVal);
197
288k
    Res.Offset = Offset;
198
288k
    return Res;
199
288k
  }
200
201
11.6k
  static AvailableValue getUndef() {
202
11.6k
    AvailableValue Res;
203
11.6k
    Res.Val.setPointer(nullptr);
204
11.6k
    Res.Val.setInt(UndefVal);
205
11.6k
    Res.Offset = 0;
206
11.6k
    return Res;
207
11.6k
  }
208
209
132k
  bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
210
64.2k
  bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
211
4.29k
  bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
212
0
  bool isUndefValue() const { return Val.getInt() == UndefVal; }
213
214
70.0k
  Value *getSimpleValue() const {
215
70.0k
    assert(isSimpleValue() && "Wrong accessor");
216
70.0k
    return Val.getPointer();
217
70.0k
  }
218
219
58.2k
  LoadInst *getCoercedLoadValue() const {
220
58.2k
    assert(isCoercedLoadValue() && "Wrong accessor");
221
58.2k
    return cast<LoadInst>(Val.getPointer());
222
58.2k
  }
223
224
2.49k
  MemIntrinsic *getMemIntrinValue() const {
225
2.49k
    assert(isMemIntrinValue() && "Wrong accessor");
226
2.49k
    return cast<MemIntrinsic>(Val.getPointer());
227
2.49k
  }
228
229
  /// Emit code at the specified insertion point to adjust the value defined
230
  /// here to the specified type. This handles various coercion cases.
231
  Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt,
232
                                  GVN &gvn) const;
233
};
234
235
/// Represents an AvailableValue which can be rematerialized at the end of
236
/// the associated BasicBlock.
237
struct llvm::gvn::AvailableValueInBlock {
238
  /// BB - The basic block in question.
239
  BasicBlock *BB;
240
241
  /// AV - The actual available value
242
  AvailableValue AV;
243
244
514k
  static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
245
514k
    AvailableValueInBlock Res;
246
514k
    Res.BB = BB;
247
514k
    Res.AV = std::move(AV);
248
514k
    return Res;
249
514k
  }
250
251
  static AvailableValueInBlock get(BasicBlock *BB, Value *V,
252
25.2k
                                   unsigned Offset = 0) {
253
25.2k
    return get(BB, AvailableValue::get(V, Offset));
254
25.2k
  }
255
256
11.6k
  static AvailableValueInBlock getUndef(BasicBlock *BB) {
257
11.6k
    return get(BB, AvailableValue::getUndef());
258
11.6k
  }
259
260
  /// Emit code at the end of this block to adjust the value defined here to
261
  /// the specified type. This handles various coercion cases.
262
113k
  Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const {
263
113k
    return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn);
264
113k
  }
265
};
266
267
//===----------------------------------------------------------------------===//
268
//                     ValueTable Internal Functions
269
//===----------------------------------------------------------------------===//
270
271
11.0M
GVN::Expression GVN::ValueTable::createExpr(Instruction *I) {
272
11.0M
  Expression e;
273
11.0M
  e.type = I->getType();
274
11.0M
  e.opcode = I->getOpcode();
275
11.0M
  for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
276
36.7M
       OI != OE; 
++OI25.6M
)
277
25.6M
    e.varargs.push_back(lookupOrAdd(*OI));
278
11.0M
  if (I->isCommutative()) {
279
1.57M
    // Ensure that commutative instructions that only differ by a permutation
280
1.57M
    // of their operands get the same value number by sorting the operand value
281
1.57M
    // numbers.  Since all commutative instructions have two operands it is more
282
1.57M
    // efficient to sort by hand rather than using, say, std::sort.
283
1.57M
    assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
284
1.57M
    if (e.varargs[0] > e.varargs[1])
285
863k
      std::swap(e.varargs[0], e.varargs[1]);
286
1.57M
    e.commutative = true;
287
1.57M
  }
288
11.0M
289
11.0M
  if (CmpInst *C = dyn_cast<CmpInst>(I)) {
290
2.33M
    // Sort the operand value numbers so x<y and y>x get the same value number.
291
2.33M
    CmpInst::Predicate Predicate = C->getPredicate();
292
2.33M
    if (e.varargs[0] > e.varargs[1]) {
293
1.47M
      std::swap(e.varargs[0], e.varargs[1]);
294
1.47M
      Predicate = CmpInst::getSwappedPredicate(Predicate);
295
1.47M
    }
296
2.33M
    e.opcode = (C->getOpcode() << 8) | Predicate;
297
2.33M
    e.commutative = true;
298
8.74M
  } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
299
14.6k
    for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
300
32.0k
         II != IE; 
++II17.4k
)
301
17.4k
      e.varargs.push_back(*II);
302
14.6k
  }
303
11.0M
304
11.0M
  return e;
305
11.0M
}
306
307
GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode,
308
                                               CmpInst::Predicate Predicate,
309
4.14M
                                               Value *LHS, Value *RHS) {
310
4.14M
  assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
311
4.14M
         "Not a comparison!");
312
4.14M
  Expression e;
313
4.14M
  e.type = CmpInst::makeCmpResultType(LHS->getType());
314
4.14M
  e.varargs.push_back(lookupOrAdd(LHS));
315
4.14M
  e.varargs.push_back(lookupOrAdd(RHS));
316
4.14M
317
4.14M
  // Sort the operand value numbers so x<y and y>x get the same value number.
318
4.14M
  if (e.varargs[0] > e.varargs[1]) {
319
2.59M
    std::swap(e.varargs[0], e.varargs[1]);
320
2.59M
    Predicate = CmpInst::getSwappedPredicate(Predicate);
321
2.59M
  }
322
4.14M
  e.opcode = (Opcode << 8) | Predicate;
323
4.14M
  e.commutative = true;
324
4.14M
  return e;
325
4.14M
}
326
327
73.4k
GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
328
73.4k
  assert(EI && "Not an ExtractValueInst?");
329
73.4k
  Expression e;
330
73.4k
  e.type = EI->getType();
331
73.4k
  e.opcode = 0;
332
73.4k
333
73.4k
  WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
334
73.4k
  if (WO != nullptr && 
EI->getNumIndices() == 15.45k
&&
*EI->idx_begin() == 05.45k
) {
335
2.73k
    // EI is an extract from one of our with.overflow intrinsics. Synthesize
336
2.73k
    // a semantically equivalent expression instead of an extract value
337
2.73k
    // expression.
338
2.73k
    e.opcode = WO->getBinaryOp();
339
2.73k
    e.varargs.push_back(lookupOrAdd(WO->getLHS()));
340
2.73k
    e.varargs.push_back(lookupOrAdd(WO->getRHS()));
341
2.73k
    return e;
342
2.73k
  }
343
70.7k
344
70.7k
  // Not a recognised intrinsic. Fall back to producing an extract value
345
70.7k
  // expression.
346
70.7k
  e.opcode = EI->getOpcode();
347
70.7k
  for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
348
141k
       OI != OE; 
++OI70.7k
)
349
70.7k
    e.varargs.push_back(lookupOrAdd(*OI));
350
70.7k
351
70.7k
  for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
352
141k
         II != IE; 
++II70.7k
)
353
70.7k
    e.varargs.push_back(*II);
354
70.7k
355
70.7k
  return e;
356
70.7k
}
357
358
//===----------------------------------------------------------------------===//
359
//                     ValueTable External Functions
360
//===----------------------------------------------------------------------===//
361
362
13.7k
GVN::ValueTable::ValueTable() = default;
363
0
GVN::ValueTable::ValueTable(const ValueTable &) = default;
364
314
GVN::ValueTable::ValueTable(ValueTable &&) = default;
365
14.0k
GVN::ValueTable::~ValueTable() = default;
366
367
/// add - Insert a value into the table with a specified value number.
368
24.2k
void GVN::ValueTable::add(Value *V, uint32_t num) {
369
24.2k
  valueNumbering.insert(std::make_pair(V, num));
370
24.2k
  if (PHINode *PN = dyn_cast<PHINode>(V))
371
12.4k
    NumberingPhi[num] = PN;
372
24.2k
}
373
374
1.53M
uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) {
375
1.53M
  if (AA->doesNotAccessMemory(C)) {
376
69.2k
    Expression exp = createExpr(C);
377
69.2k
    uint32_t e = assignExpNewValueNum(exp).first;
378
69.2k
    valueNumbering[C] = e;
379
69.2k
    return e;
380
1.46M
  } else if (MD && 
AA->onlyReadsMemory(C)1.46M
) {
381
43.9k
    Expression exp = createExpr(C);
382
43.9k
    auto ValNum = assignExpNewValueNum(exp);
383
43.9k
    if (ValNum.second) {
384
41.1k
      valueNumbering[C] = ValNum.first;
385
41.1k
      return ValNum.first;
386
41.1k
    }
387
2.79k
388
2.79k
    MemDepResult local_dep = MD->getDependency(C);
389
2.79k
390
2.79k
    if (!local_dep.isDef() && 
!local_dep.isNonLocal()2.78k
) {
391
1.84k
      valueNumbering[C] =  nextValueNumber;
392
1.84k
      return nextValueNumber++;
393
1.84k
    }
394
951
395
951
    if (local_dep.isDef()) {
396
11
      CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
397
11
398
11
      if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
399
0
        valueNumbering[C] = nextValueNumber;
400
0
        return nextValueNumber++;
401
0
      }
402
11
403
28
      
for (unsigned i = 0, e = C->getNumArgOperands(); 11
i < e;
++i17
) {
404
17
        uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
405
17
        uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
406
17
        if (c_vn != cd_vn) {
407
0
          valueNumbering[C] = nextValueNumber;
408
0
          return nextValueNumber++;
409
0
        }
410
17
      }
411
11
412
11
      uint32_t v = lookupOrAdd(local_cdep);
413
11
      valueNumbering[C] = v;
414
11
      return v;
415
940
    }
416
940
417
940
    // Non-local case.
418
940
    const MemoryDependenceResults::NonLocalDepInfo &deps =
419
940
        MD->getNonLocalCallDependency(C);
420
940
    // FIXME: Move the checking logic to MemDep!
421
940
    CallInst* cdep = nullptr;
422
940
423
940
    // Check to see if we have a single dominating call instruction that is
424
940
    // identical to C.
425
2.28k
    for (unsigned i = 0, e = deps.size(); i != e; 
++i1.34k
) {
426
2.28k
      const NonLocalDepEntry *I = &deps[i];
427
2.28k
      if (I->getResult().isNonLocal())
428
1.33k
        continue;
429
951
430
951
      // We don't handle non-definitions.  If we already have a call, reject
431
951
      // instruction dependencies.
432
951
      if (!I->getResult().isDef() || 
cdep != nullptr36
) {
433
915
        cdep = nullptr;
434
915
        break;
435
915
      }
436
36
437
36
      CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
438
36
      // FIXME: All duplicated with non-local case.
439
36
      if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
440
16
        cdep = NonLocalDepCall;
441
16
        continue;
442
16
      }
443
20
444
20
      cdep = nullptr;
445
20
      break;
446
20
    }
447
940
448
940
    if (!cdep) {
449
935
      valueNumbering[C] = nextValueNumber;
450
935
      return nextValueNumber++;
451
935
    }
452
5
453
5
    if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
454
0
      valueNumbering[C] = nextValueNumber;
455
0
      return nextValueNumber++;
456
0
    }
457
10
    
for (unsigned i = 0, e = C->getNumArgOperands(); 5
i < e;
++i5
) {
458
5
      uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
459
5
      uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
460
5
      if (c_vn != cd_vn) {
461
0
        valueNumbering[C] = nextValueNumber;
462
0
        return nextValueNumber++;
463
0
      }
464
5
    }
465
5
466
5
    uint32_t v = lookupOrAdd(cdep);
467
5
    valueNumbering[C] = v;
468
5
    return v;
469
1.42M
  } else {
470
1.42M
    valueNumbering[C] = nextValueNumber;
471
1.42M
    return nextValueNumber++;
472
1.42M
  }
473
1.53M
}
474
475
/// Returns true if a value number exists for the specified value.
476
10.4k
bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; }
477
478
/// lookup_or_add - Returns the value number for the specified value, assigning
479
/// it a new number if it did not have one before.
480
57.3M
uint32_t GVN::ValueTable::lookupOrAdd(Value *V) {
481
57.3M
  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
482
57.3M
  if (VI != valueNumbering.end())
483
36.5M
    return VI->second;
484
20.7M
485
20.7M
  if (!isa<Instruction>(V)) {
486
3.74M
    valueNumbering[V] = nextValueNumber;
487
3.74M
    return nextValueNumber++;
488
3.74M
  }
489
17.0M
490
17.0M
  Instruction* I = cast<Instruction>(V);
491
17.0M
  Expression exp;
492
17.0M
  switch (I->getOpcode()) {
493
17.0M
    case Instruction::Call:
494
1.53M
      return lookupOrAddCall(cast<CallInst>(I));
495
17.0M
    case Instruction::FNeg:
496
10.9M
    case Instruction::Add:
497
10.9M
    case Instruction::FAdd:
498
10.9M
    case Instruction::Sub:
499
10.9M
    case Instruction::FSub:
500
10.9M
    case Instruction::Mul:
501
10.9M
    case Instruction::FMul:
502
10.9M
    case Instruction::UDiv:
503
10.9M
    case Instruction::SDiv:
504
10.9M
    case Instruction::FDiv:
505
10.9M
    case Instruction::URem:
506
10.9M
    case Instruction::SRem:
507
10.9M
    case Instruction::FRem:
508
10.9M
    case Instruction::Shl:
509
10.9M
    case Instruction::LShr:
510
10.9M
    case Instruction::AShr:
511
10.9M
    case Instruction::And:
512
10.9M
    case Instruction::Or:
513
10.9M
    case Instruction::Xor:
514
10.9M
    case Instruction::ICmp:
515
10.9M
    case Instruction::FCmp:
516
10.9M
    case Instruction::Trunc:
517
10.9M
    case Instruction::ZExt:
518
10.9M
    case Instruction::SExt:
519
10.9M
    case Instruction::FPToUI:
520
10.9M
    case Instruction::FPToSI:
521
10.9M
    case Instruction::UIToFP:
522
10.9M
    case Instruction::SIToFP:
523
10.9M
    case Instruction::FPTrunc:
524
10.9M
    case Instruction::FPExt:
525
10.9M
    case Instruction::PtrToInt:
526
10.9M
    case Instruction::IntToPtr:
527
10.9M
    case Instruction::AddrSpaceCast:
528
10.9M
    case Instruction::BitCast:
529
10.9M
    case Instruction::Select:
530
10.9M
    case Instruction::ExtractElement:
531
10.9M
    case Instruction::InsertElement:
532
10.9M
    case Instruction::ShuffleVector:
533
10.9M
    case Instruction::InsertValue:
534
10.9M
    case Instruction::GetElementPtr:
535
10.9M
      exp = createExpr(I);
536
10.9M
      break;
537
10.9M
    case Instruction::ExtractValue:
538
73.4k
      exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
539
73.4k
      break;
540
10.9M
    case Instruction::PHI:
541
1.18M
      valueNumbering[V] = nextValueNumber;
542
1.18M
      NumberingPhi[nextValueNumber] = cast<PHINode>(V);
543
1.18M
      return nextValueNumber++;
544
10.9M
    default:
545
3.25M
      valueNumbering[V] = nextValueNumber;
546
3.25M
      return nextValueNumber++;
547
11.0M
  }
548
11.0M
549
11.0M
  uint32_t e = assignExpNewValueNum(exp).first;
550
11.0M
  valueNumbering[V] = e;
551
11.0M
  return e;
552
11.0M
}
553
554
/// Returns the value number of the specified value. Fails if
555
/// the value has not yet been numbered.
556
3.34M
uint32_t GVN::ValueTable::lookup(Value *V, bool Verify) const {
557
3.34M
  DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
558
3.34M
  if (Verify) {
559
3.03M
    assert(VI != valueNumbering.end() && "Value not numbered?");
560
3.03M
    return VI->second;
561
3.03M
  }
562
309k
  return (VI != valueNumbering.end()) ? 
VI->second294k
:
014.7k
;
563
309k
}
564
565
/// Returns the value number of the given comparison,
566
/// assigning it a new number if it did not have one before.  Useful when
567
/// we deduced the result of a comparison, but don't immediately have an
568
/// instruction realizing that comparison to hand.
569
uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode,
570
                                         CmpInst::Predicate Predicate,
571
4.14M
                                         Value *LHS, Value *RHS) {
572
4.14M
  Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
573
4.14M
  return assignExpNewValueNum(exp).first;
574
4.14M
}
575
576
/// Remove all entries from the ValueTable.
577
994k
void GVN::ValueTable::clear() {
578
994k
  valueNumbering.clear();
579
994k
  expressionNumbering.clear();
580
994k
  NumberingPhi.clear();
581
994k
  PhiTranslateTable.clear();
582
994k
  nextValueNumber = 1;
583
994k
  Expressions.clear();
584
994k
  ExprIdx.clear();
585
994k
  nextExprNumber = 0;
586
994k
}
587
588
/// Remove a value from the value numbering.
589
310k
void GVN::ValueTable::erase(Value *V) {
590
310k
  uint32_t Num = valueNumbering.lookup(V);
591
310k
  valueNumbering.erase(V);
592
310k
  // If V is PHINode, V <--> value number is an one-to-one mapping.
593
310k
  if (isa<PHINode>(V))
594
123k
    NumberingPhi.erase(Num);
595
310k
}
596
597
/// verifyRemoved - Verify that the value is removed from all internal data
598
/// structures.
599
0
void GVN::ValueTable::verifyRemoved(const Value *V) const {
600
0
  for (DenseMap<Value*, uint32_t>::const_iterator
601
0
         I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
602
0
    assert(I->first != V && "Inst still occurs in value numbering map!");
603
0
  }
604
0
}
605
606
//===----------------------------------------------------------------------===//
607
//                                GVN Pass
608
//===----------------------------------------------------------------------===//
609
610
810
PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) {
611
810
  // FIXME: The order of evaluation of these 'getResult' calls is very
612
810
  // significant! Re-ordering these variables will cause GVN when run alone to
613
810
  // be less effective! We should fix memdep and basic-aa to not exhibit this
614
810
  // behavior, but until then don't change the order here.
615
810
  auto &AC = AM.getResult<AssumptionAnalysis>(F);
616
810
  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
617
810
  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
618
810
  auto &AA = AM.getResult<AAManager>(F);
619
810
  auto &MemDep = AM.getResult<MemoryDependenceAnalysis>(F);
620
810
  auto *LI = AM.getCachedResult<LoopAnalysis>(F);
621
810
  auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
622
810
  bool Changed = runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
623
810
  if (!Changed)
624
753
    return PreservedAnalyses::all();
625
57
  PreservedAnalyses PA;
626
57
  PA.preserve<DominatorTreeAnalysis>();
627
57
  PA.preserve<GlobalsAA>();
628
57
  PA.preserve<TargetLibraryAnalysis>();
629
57
  return PA;
630
57
}
631
632
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
633
LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) const {
634
  errs() << "{\n";
635
  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
636
       E = d.end(); I != E; ++I) {
637
      errs() << I->first << "\n";
638
      I->second->dump();
639
  }
640
  errs() << "}\n";
641
}
642
#endif
643
644
/// Return true if we can prove that the value
645
/// we're analyzing is fully available in the specified block.  As we go, keep
646
/// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
647
/// map is actually a tri-state map with the following values:
648
///   0) we know the block *is not* fully available.
649
///   1) we know the block *is* fully available.
650
///   2) we do not know whether the block is fully available or not, but we are
651
///      currently speculating that it will be.
652
///   3) we are speculating for this block and have used that to speculate for
653
///      other blocks.
654
static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
655
                            DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
656
1.04M
                            uint32_t RecurseDepth) {
657
1.04M
  if (RecurseDepth > MaxRecurseDepth)
658
0
    return false;
659
1.04M
660
1.04M
  // Optimistically assume that the block is fully available and check to see
661
1.04M
  // if we already know about this block in one lookup.
662
1.04M
  std::pair<DenseMap<BasicBlock*, char>::iterator, bool> IV =
663
1.04M
    FullyAvailableBlocks.insert(std::make_pair(BB, 2));
664
1.04M
665
1.04M
  // If the entry already existed for this block, return the precomputed value.
666
1.04M
  if (!IV.second) {
667
414k
    // If this is a speculative "available" value, mark it as being used for
668
414k
    // speculation of other blocks.
669
414k
    if (IV.first->second == 2)
670
70.5k
      IV.first->second = 3;
671
414k
    return IV.first->second != 0;
672
414k
  }
673
630k
674
630k
  // Otherwise, see if it is fully available in all predecessors.
675
630k
  pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
676
630k
677
630k
  // If this block has no predecessors, it isn't live-in here.
678
630k
  if (PI == PE)
679
3
    goto SpeculationFailure;
680
630k
681
962k
  
for (; 630k
PI != PE;
++PI331k
)
682
755k
    // If the value isn't fully available in one of our predecessors, then it
683
755k
    // isn't fully available in this block either.  Undo our previous
684
755k
    // optimistic assumption and bail out.
685
755k
    if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
686
423k
      goto SpeculationFailure;
687
630k
688
630k
  
return true206k
;
689
423k
690
423k
// If we get here, we found out that this is not, after
691
423k
// all, a fully-available block.  We have a problem if we speculated on this and
692
423k
// used the speculation to mark other blocks as available.
693
423k
SpeculationFailure:
694
423k
  char &BBVal = FullyAvailableBlocks[BB];
695
423k
696
423k
  // If we didn't speculate on this, just return with it set to false.
697
423k
  if (BBVal == 2) {
698
367k
    BBVal = 0;
699
367k
    return false;
700
367k
  }
701
56.4k
702
56.4k
  // If we did speculate on this value, we could have blocks set to 1 that are
703
56.4k
  // incorrect.  Walk the (transitive) successors of this block and mark them as
704
56.4k
  // 0 if set to one.
705
56.4k
  SmallVector<BasicBlock*, 32> BBWorklist;
706
56.4k
  BBWorklist.push_back(BB);
707
56.4k
708
194k
  do {
709
194k
    BasicBlock *Entry = BBWorklist.pop_back_val();
710
194k
    // Note that this sets blocks to 0 (unavailable) if they happen to not
711
194k
    // already be in FullyAvailableBlocks.  This is safe.
712
194k
    char &EntryVal = FullyAvailableBlocks[Entry];
713
194k
    if (EntryVal == 0) 
continue116k
; // Already unavailable.
714
78.8k
715
78.8k
    // Mark as unavailable.
716
78.8k
    EntryVal = 0;
717
78.8k
718
78.8k
    BBWorklist.append(succ_begin(Entry), succ_end(Entry));
719
194k
  } while (!BBWorklist.empty());
720
56.4k
721
56.4k
  return false;
722
56.4k
}
723
724
/// Given a set of loads specified by ValuesPerBlock,
725
/// construct SSA form, allowing us to eliminate LI.  This returns the value
726
/// that should be used at LI's definition site.
727
static Value *ConstructSSAForLoadSet(LoadInst *LI,
728
                         SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
729
56.4k
                                     GVN &gvn) {
730
56.4k
  // Check for the fully redundant, dominating load case.  In this case, we can
731
56.4k
  // just use the dominating value directly.
732
56.4k
  if (ValuesPerBlock.size() == 1 &&
733
56.4k
      gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
734
15.9k
                                               LI->getParent())) {
735
15.9k
    assert(!ValuesPerBlock[0].AV.isUndefValue() &&
736
15.9k
           "Dead BB dominate this block");
737
15.9k
    return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
738
15.9k
  }
739
40.5k
740
40.5k
  // Otherwise, we have to construct SSA form.
741
40.5k
  SmallVector<PHINode*, 8> NewPHIs;
742
40.5k
  SSAUpdater SSAUpdate(&NewPHIs);
743
40.5k
  SSAUpdate.Initialize(LI->getType(), LI->getName());
744
40.5k
745
104k
  for (const AvailableValueInBlock &AV : ValuesPerBlock) {
746
104k
    BasicBlock *BB = AV.BB;
747
104k
748
104k
    if (SSAUpdate.HasValueForBlock(BB))
749
1
      continue;
750
104k
751
104k
    // If the value is the load that we will be eliminating, and the block it's
752
104k
    // available in is the block that the load is in, then don't add it as
753
104k
    // SSAUpdater will resolve the value to the relevant phi which may let it
754
104k
    // avoid phi construction entirely if there's actually only one value.
755
104k
    if (BB == LI->getParent() &&
756
104k
        
(9.09k
(9.09k
AV.AV.isSimpleValue()9.09k
&&
AV.AV.getSimpleValue() == LI1.73k
) ||
757
9.09k
         
(9.08k
AV.AV.isCoercedLoadValue()9.08k
&&
AV.AV.getCoercedLoadValue() == LI7.36k
)))
758
6.80k
      continue;
759
97.5k
760
97.5k
    SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
761
97.5k
  }
762
40.5k
763
40.5k
  // Perform PHI construction.
764
40.5k
  return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
765
40.5k
}
766
767
Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI,
768
                                                Instruction *InsertPt,
769
123k
                                                GVN &gvn) const {
770
123k
  Value *Res;
771
123k
  Type *LoadTy = LI->getType();
772
123k
  const DataLayout &DL = LI->getModule()->getDataLayout();
773
123k
  if (isSimpleValue()) {
774
68.3k
    Res = getSimpleValue();
775
68.3k
    if (Res->getType() != LoadTy) {
776
12.5k
      Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
777
12.5k
778
12.5k
      LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
779
12.5k
                        << "  " << *getSimpleValue() << '\n'
780
12.5k
                        << *Res << '\n'
781
12.5k
                        << "\n\n\n");
782
12.5k
    }
783
68.3k
  } else 
if (55.2k
isCoercedLoadValue()55.2k
) {
784
50.9k
    LoadInst *Load = getCoercedLoadValue();
785
50.9k
    if (Load->getType() == LoadTy && 
Offset == 042.5k
) {
786
42.5k
      Res = Load;
787
42.5k
    } else {
788
8.37k
      Res = getLoadValueForLoad(Load, Offset, LoadTy, InsertPt, DL);
789
8.37k
      // We would like to use gvn.markInstructionForDeletion here, but we can't
790
8.37k
      // because the load is already memoized into the leader map table that GVN
791
8.37k
      // tracks.  It is potentially possible to remove the load from the table,
792
8.37k
      // but then there all of the operations based on it would need to be
793
8.37k
      // rehashed.  Just leave the dead load around.
794
8.37k
      gvn.getMemDep().removeInstruction(Load);
795
8.37k
      LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
796
8.37k
                        << "  " << *getCoercedLoadValue() << '\n'
797
8.37k
                        << *Res << '\n'
798
8.37k
                        << "\n\n\n");
799
8.37k
    }
800
50.9k
  } else 
if (4.29k
isMemIntrinValue()4.29k
) {
801
2.49k
    Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
802
2.49k
                                 InsertPt, DL);
803
2.49k
    LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
804
2.49k
                      << "  " << *getMemIntrinValue() << '\n'
805
2.49k
                      << *Res << '\n'
806
2.49k
                      << "\n\n\n");
807
2.49k
  } else {
808
1.79k
    assert(isUndefValue() && "Should be UndefVal");
809
1.79k
    LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
810
1.79k
    return UndefValue::get(LoadTy);
811
1.79k
  }
812
121k
  assert(Res && "failed to materialize?");
813
121k
  return Res;
814
121k
}
815
816
483k
static bool isLifetimeStart(const Instruction *Inst) {
817
483k
  if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
818
418
    return II->getIntrinsicID() == Intrinsic::lifetime_start;
819
483k
  return false;
820
483k
}
821
822
/// Try to locate the three instruction involved in a missed
823
/// load-elimination case that is due to an intervening store.
824
static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo,
825
                                   DominatorTree *DT,
826
19
                                   OptimizationRemarkEmitter *ORE) {
827
19
  using namespace ore;
828
19
829
19
  User *OtherAccess = nullptr;
830
19
831
19
  OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI);
832
19
  R << "load of type " << NV("Type", LI->getType()) << " not eliminated"
833
19
    << setExtraArgs();
834
19
835
19
  for (auto *U : LI->getPointerOperand()->users())
836
29
    if (U != LI && 
(10
isa<LoadInst>(U)10
||
isa<StoreInst>(U)0
) &&
837
29
        
DT->dominates(cast<Instruction>(U), LI)10
) {
838
10
      // FIXME: for now give up if there are multiple memory accesses that
839
10
      // dominate the load.  We need further analysis to decide which one is
840
10
      // that we're forwarding from.
841
10
      if (OtherAccess)
842
0
        OtherAccess = nullptr;
843
10
      else
844
10
        OtherAccess = U;
845
10
    }
846
19
847
19
  if (OtherAccess)
848
10
    R << " in favor of " << NV("OtherAccess", OtherAccess);
849
19
850
19
  R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
851
19
852
19
  ORE->emit(R);
853
19
}
854
855
bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
856
4.26M
                                  Value *Address, AvailableValue &Res) {
857
4.26M
  assert((DepInfo.isDef() || DepInfo.isClobber()) &&
858
4.26M
         "expected a local dependence");
859
4.26M
  assert(LI->isUnordered() && "rules below are incorrect for ordered access");
860
4.26M
861
4.26M
  const DataLayout &DL = LI->getModule()->getDataLayout();
862
4.26M
863
4.26M
  Instruction *DepInst = DepInfo.getInst();
864
4.26M
  if (DepInfo.isClobber()) {
865
3.77M
    // If the dependence is to a store that writes to a superset of the bits
866
3.77M
    // read by the load, we can extract the bits we need for the load from the
867
3.77M
    // stored value.
868
3.77M
    if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
869
691k
      // Can't forward from non-atomic to atomic without violating memory model.
870
691k
      if (Address && LI->isAtomic() <= DepSI->isAtomic()) {
871
691k
        int Offset =
872
691k
          analyzeLoadFromClobberingStore(LI->getType(), Address, DepSI, DL);
873
691k
        if (Offset != -1) {
874
264
          Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
875
264
          return true;
876
264
        }
877
3.77M
      }
878
691k
    }
879
3.77M
880
3.77M
    // Check to see if we have something like this:
881
3.77M
    //    load i32* P
882
3.77M
    //    load i8* (P+1)
883
3.77M
    // if we have this, replace the later with an extraction from the former.
884
3.77M
    if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
885
3.22k
      // If this is a clobber and L is the first instruction in its block, then
886
3.22k
      // we have the first instruction in the entry block.
887
3.22k
      // Can't forward from non-atomic to atomic without violating memory model.
888
3.22k
      if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) {
889
3.22k
        int Offset =
890
3.22k
          analyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
891
3.22k
892
3.22k
        if (Offset != -1) {
893
3
          Res = AvailableValue::getLoad(DepLI, Offset);
894
3
          return true;
895
3
        }
896
3.77M
      }
897
3.22k
    }
898
3.77M
899
3.77M
    // If the clobbering value is a memset/memcpy/memmove, see if we can
900
3.77M
    // forward a value on from it.
901
3.77M
    if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
902
53.3k
      if (Address && !LI->isAtomic()) {
903
53.3k
        int Offset = analyzeLoadFromClobberingMemInst(LI->getType(), Address,
904
53.3k
                                                      DepMI, DL);
905
53.3k
        if (Offset != -1) {
906
6.97k
          Res = AvailableValue::getMI(DepMI, Offset);
907
6.97k
          return true;
908
6.97k
        }
909
3.77M
      }
910
53.3k
    }
911
3.77M
    // Nothing known about this clobber, have to be conservative
912
3.77M
    LLVM_DEBUG(
913
3.77M
        // fast print dep, using operator<< on instruction is too slow.
914
3.77M
        dbgs() << "GVN: load "; LI->printAsOperand(dbgs());
915
3.77M
        dbgs() << " is clobbered by " << *DepInst << '\n';);
916
3.77M
    if (ORE->allowExtraAnalysis(DEBUG_TYPE))
917
19
      reportMayClobberedLoad(LI, DepInfo, DT, ORE);
918
3.77M
919
3.77M
    return false;
920
3.77M
  }
921
484k
  assert(DepInfo.isDef() && "follows from above");
922
484k
923
484k
  // Loading the allocation -> undef.
924
484k
  if (isa<AllocaInst>(DepInst) || 
isMallocLikeFn(DepInst, TLI)484k
||
925
484k
      // Loading immediately after lifetime begin -> undef.
926
484k
      
isLifetimeStart(DepInst)483k
) {
927
1.27k
    Res = AvailableValue::get(UndefValue::get(LI->getType()));
928
1.27k
    return true;
929
1.27k
  }
930
483k
931
483k
  // Loading from calloc (which zero initializes memory) -> zero
932
483k
  if (isCallocLikeFn(DepInst, TLI)) {
933
44
    Res = AvailableValue::get(Constant::getNullValue(LI->getType()));
934
44
    return true;
935
44
  }
936
483k
937
483k
  if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
938
193k
    // Reject loads and stores that are to the same address but are of
939
193k
    // different types if we have to. If the stored value is larger or equal to
940
193k
    // the loaded value, we can reuse it.
941
193k
    if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), LI->getType(),
942
193k
                                         DL))
943
3.01k
      return false;
944
190k
945
190k
    // Can't forward from non-atomic to atomic without violating memory model.
946
190k
    if (S->isAtomic() < LI->isAtomic())
947
1
      return false;
948
190k
949
190k
    Res = AvailableValue::get(S->getValueOperand());
950
190k
    return true;
951
190k
  }
952
289k
953
289k
  if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
954
289k
    // If the types mismatch and we can't handle it, reject reuse of the load.
955
289k
    // If the stored value is larger or equal to the loaded value, we can reuse
956
289k
    // it.
957
289k
    if (!canCoerceMustAliasedValueToLoad(LD, LI->getType(), DL))
958
468
      return false;
959
288k
960
288k
    // Can't forward from non-atomic to atomic without violating memory model.
961
288k
    if (LD->isAtomic() < LI->isAtomic())
962
3
      return false;
963
288k
964
288k
    Res = AvailableValue::getLoad(LD);
965
288k
    return true;
966
288k
  }
967
311
968
311
  // Unknown def - must be conservative
969
311
  LLVM_DEBUG(
970
311
      // fast print dep, using operator<< on instruction is too slow.
971
311
      dbgs() << "GVN: load "; LI->printAsOperand(dbgs());
972
311
      dbgs() << " has unknown def " << *DepInst << '\n';);
973
311
  return false;
974
311
}
975
976
void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
977
                                  AvailValInBlkVect &ValuesPerBlock,
978
1.61M
                                  UnavailBlkVect &UnavailableBlocks) {
979
1.61M
  // Filter out useless results (non-locals, etc).  Keep track of the blocks
980
1.61M
  // where we have a value available in repl, also keep track of whether we see
981
1.61M
  // dependencies that produce an unknown value for the load (such as a call
982
1.61M
  // that could potentially clobber the load).
983
1.61M
  unsigned NumDeps = Deps.size();
984
6.59M
  for (unsigned i = 0, e = NumDeps; i != e; 
++i4.97M
) {
985
4.97M
    BasicBlock *DepBB = Deps[i].getBB();
986
4.97M
    MemDepResult DepInfo = Deps[i].getResult();
987
4.97M
988
4.97M
    if (DeadBlocks.count(DepBB)) {
989
11.6k
      // Dead dependent mem-op disguise as a load evaluating the same value
990
11.6k
      // as the load in question.
991
11.6k
      ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
992
11.6k
      continue;
993
11.6k
    }
994
4.96M
995
4.96M
    if (!DepInfo.isDef() && 
!DepInfo.isClobber()4.49M
) {
996
1.33M
      UnavailableBlocks.push_back(DepBB);
997
1.33M
      continue;
998
1.33M
    }
999
3.62M
1000
3.62M
    // The address being loaded in this non-local block may not be the same as
1001
3.62M
    // the pointer operand of the load if PHI translation occurs.  Make sure
1002
3.62M
    // to consider the right address.
1003
3.62M
    Value *Address = Deps[i].getAddress();
1004
3.62M
1005
3.62M
    AvailableValue AV;
1006
3.62M
    if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
1007
478k
      // subtlety: because we know this was a non-local dependency, we know
1008
478k
      // it's safe to materialize anywhere between the instruction within
1009
478k
      // DepInfo and the end of it's block.
1010
478k
      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1011
478k
                                                          std::move(AV)));
1012
3.15M
    } else {
1013
3.15M
      UnavailableBlocks.push_back(DepBB);
1014
3.15M
    }
1015
3.62M
  }
1016
1.61M
1017
1.61M
  assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1018
1.61M
         "post condition violation");
1019
1.61M
}
1020
1021
bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1022
190k
                         UnavailBlkVect &UnavailableBlocks) {
1023
190k
  // Okay, we have *some* definitions of the value.  This means that the value
1024
190k
  // is available in some of our (transitive) predecessors.  Lets think about
1025
190k
  // doing PRE of this load.  This will involve inserting a new load into the
1026
190k
  // predecessor when it's not available.  We could do this in general, but
1027
190k
  // prefer to not increase code size.  As such, we only do this when we know
1028
190k
  // that we only have to insert *one* load (which means we're basically moving
1029
190k
  // the load, not inserting a new one).
1030
190k
1031
190k
  SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
1032
190k
                                        UnavailableBlocks.end());
1033
190k
1034
190k
  // Let's find the first basic block with more than one predecessor.  Walk
1035
190k
  // backwards through predecessors if needed.
1036
190k
  BasicBlock *LoadBB = LI->getParent();
1037
190k
  BasicBlock *TmpBB = LoadBB;
1038
190k
  bool IsSafeToSpeculativelyExecute = isSafeToSpeculativelyExecute(LI);
1039
190k
1040
190k
  // Check that there is no implicit control flow instructions above our load in
1041
190k
  // its block. If there is an instruction that doesn't always pass the
1042
190k
  // execution to the following instruction, then moving through it may become
1043
190k
  // invalid. For example:
1044
190k
  //
1045
190k
  // int arr[LEN];
1046
190k
  // int index = ???;
1047
190k
  // ...
1048
190k
  // guard(0 <= index && index < LEN);
1049
190k
  // use(arr[index]);
1050
190k
  //
1051
190k
  // It is illegal to move the array access to any point above the guard,
1052
190k
  // because if the index is out of bounds we should deoptimize rather than
1053
190k
  // access the array.
1054
190k
  // Check that there is no guard in this block above our instruction.
1055
190k
  if (!IsSafeToSpeculativelyExecute && 
ICF->isDominatedByICFIFromSameBlock(LI)120k
)
1056
651
    return false;
1057
189k
  while (TmpBB->getSinglePredecessor()) {
1058
82.8k
    TmpBB = TmpBB->getSinglePredecessor();
1059
82.8k
    if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1060
0
      return false;
1061
82.8k
    if (Blockers.count(TmpBB))
1062
0
      return false;
1063
82.8k
1064
82.8k
    // If any of these blocks has more than one successor (i.e. if the edge we
1065
82.8k
    // just traversed was critical), then there are other paths through this
1066
82.8k
    // block along which the load may not be anticipated.  Hoisting the load
1067
82.8k
    // above this block would be adding the load to execution paths along
1068
82.8k
    // which it was not previously executed.
1069
82.8k
    if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1070
82.8k
      return false;
1071
0
1072
0
    // Check that there is no implicit control flow in a block above.
1073
0
    if (!IsSafeToSpeculativelyExecute && ICF->hasICF(TmpBB))
1074
0
      return false;
1075
0
  }
1076
189k
1077
189k
  assert(TmpBB);
1078
106k
  LoadBB = TmpBB;
1079
106k
1080
106k
  // Check to see how many predecessors have the loaded value fully
1081
106k
  // available.
1082
106k
  MapVector<BasicBlock *, Value *> PredLoads;
1083
106k
  DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1084
106k
  for (const AvailableValueInBlock &AV : ValuesPerBlock)
1085
176k
    FullyAvailableBlocks[AV.BB] = true;
1086
106k
  for (BasicBlock *UnavailableBB : UnavailableBlocks)
1087
397k
    FullyAvailableBlocks[UnavailableBB] = false;
1088
106k
1089
106k
  SmallVector<BasicBlock *, 4> CriticalEdgePred;
1090
289k
  for (BasicBlock *Pred : predecessors(LoadBB)) {
1091
289k
    // If any predecessor block is an EH pad that does not allow non-PHI
1092
289k
    // instructions before the terminator, we can't PRE the load.
1093
289k
    if (Pred->getTerminator()->isEHPad()) {
1094
1
      LLVM_DEBUG(
1095
1
          dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1096
1
                 << Pred->getName() << "': " << *LI << '\n');
1097
1
      return false;
1098
1
    }
1099
289k
1100
289k
    if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1101
52.4k
      continue;
1102
52.4k
    }
1103
236k
1104
236k
    if (Pred->getTerminator()->getNumSuccessors() != 1) {
1105
97.6k
      if (isa<IndirectBrInst>(Pred->getTerminator())) {
1106
0
        LLVM_DEBUG(
1107
0
            dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1108
0
                   << Pred->getName() << "': " << *LI << '\n');
1109
0
        return false;
1110
0
      }
1111
97.6k
1112
97.6k
      // FIXME: Can we support the fallthrough edge?
1113
97.6k
      if (isa<CallBrInst>(Pred->getTerminator())) {
1114
1
        LLVM_DEBUG(
1115
1
            dbgs() << "COULD NOT PRE LOAD BECAUSE OF CALLBR CRITICAL EDGE '"
1116
1
                   << Pred->getName() << "': " << *LI << '\n');
1117
1
        return false;
1118
1
      }
1119
97.6k
1120
97.6k
      if (LoadBB->isEHPad()) {
1121
1.20k
        LLVM_DEBUG(
1122
1.20k
            dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
1123
1.20k
                   << Pred->getName() << "': " << *LI << '\n');
1124
1.20k
        return false;
1125
1.20k
      }
1126
96.4k
1127
96.4k
      CriticalEdgePred.push_back(Pred);
1128
139k
    } else {
1129
139k
      // Only add the predecessors that will not be split for now.
1130
139k
      PredLoads[Pred] = nullptr;
1131
139k
    }
1132
236k
  }
1133
106k
1134
106k
  // Decide whether PRE is profitable for this load.
1135
106k
  unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
1136
105k
  assert(NumUnavailablePreds != 0 &&
1137
105k
         "Fully available value should already be eliminated!");
1138
105k
1139
105k
  // If this load is unavailable in multiple predecessors, reject it.
1140
105k
  // FIXME: If we could restructure the CFG, we could make a common pred with
1141
105k
  // all the preds that don't have an available LI and insert a new load into
1142
105k
  // that one block.
1143
105k
  if (NumUnavailablePreds != 1)
1144
79.8k
      return false;
1145
25.8k
1146
25.8k
  // Split critical edges, and update the unavailable predecessors accordingly.
1147
25.8k
  for (BasicBlock *OrigPred : CriticalEdgePred) {
1148
6.02k
    BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1149
6.02k
    assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
1150
6.02k
    PredLoads[NewPred] = nullptr;
1151
6.02k
    LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1152
6.02k
                      << LoadBB->getName() << '\n');
1153
6.02k
  }
1154
25.8k
1155
25.8k
  // Check if the load can safely be moved to all the unavailable predecessors.
1156
25.8k
  bool CanDoPRE = true;
1157
25.8k
  const DataLayout &DL = LI->getModule()->getDataLayout();
1158
25.8k
  SmallVector<Instruction*, 8> NewInsts;
1159
25.8k
  for (auto &PredLoad : PredLoads) {
1160
25.8k
    BasicBlock *UnavailablePred = PredLoad.first;
1161
25.8k
1162
25.8k
    // Do PHI translation to get its value in the predecessor if necessary.  The
1163
25.8k
    // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1164
25.8k
1165
25.8k
    // If all preds have a single successor, then we know it is safe to insert
1166
25.8k
    // the load on the pred (?!?), so we can insert code to materialize the
1167
25.8k
    // pointer if it is not available.
1168
25.8k
    PHITransAddr Address(LI->getPointerOperand(), DL, AC);
1169
25.8k
    Value *LoadPtr = nullptr;
1170
25.8k
    LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1171
25.8k
                                                *DT, NewInsts);
1172
25.8k
1173
25.8k
    // If we couldn't find or insert a computation of this phi translated value,
1174
25.8k
    // we fail PRE.
1175
25.8k
    if (!LoadPtr) {
1176
630
      LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1177
630
                        << *LI->getPointerOperand() << "\n");
1178
630
      CanDoPRE = false;
1179
630
      break;
1180
630
    }
1181
25.2k
1182
25.2k
    PredLoad.second = LoadPtr;
1183
25.2k
  }
1184
25.8k
1185
25.8k
  if (!CanDoPRE) {
1186
630
    while (!NewInsts.empty()) {
1187
0
      Instruction *I = NewInsts.pop_back_val();
1188
0
      markInstructionForDeletion(I);
1189
0
    }
1190
630
    // HINT: Don't revert the edge-splitting as following transformation may
1191
630
    // also need to split these critical edges.
1192
630
    return !CriticalEdgePred.empty();
1193
630
  }
1194
25.2k
1195
25.2k
  // Okay, we can eliminate this load by inserting a reload in the predecessor
1196
25.2k
  // and using PHI construction to get the value in the other predecessors, do
1197
25.2k
  // it.
1198
25.2k
  LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1199
25.2k
  LLVM_DEBUG(if (!NewInsts.empty()) dbgs()
1200
25.2k
             << "INSERTED " << NewInsts.size() << " INSTS: " << *NewInsts.back()
1201
25.2k
             << '\n');
1202
25.2k
1203
25.2k
  // Assign value numbers to the new instructions.
1204
25.2k
  for (Instruction *I : NewInsts) {
1205
7.01k
    // Instructions that have been inserted in predecessor(s) to materialize
1206
7.01k
    // the load address do not retain their original debug locations. Doing
1207
7.01k
    // so could lead to confusing (but correct) source attributions.
1208
7.01k
    if (const DebugLoc &DL = I->getDebugLoc())
1209
1.67k
      I->setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
1210
7.01k
1211
7.01k
    // FIXME: We really _ought_ to insert these value numbers into their
1212
7.01k
    // parent's availability map.  However, in doing so, we risk getting into
1213
7.01k
    // ordering issues.  If a block hasn't been processed yet, we would be
1214
7.01k
    // marking a value as AVAIL-IN, which isn't what we intend.
1215
7.01k
    VN.lookupOrAdd(I);
1216
7.01k
  }
1217
25.2k
1218
25.2k
  for (const auto &PredLoad : PredLoads) {
1219
25.2k
    BasicBlock *UnavailablePred = PredLoad.first;
1220
25.2k
    Value *LoadPtr = PredLoad.second;
1221
25.2k
1222
25.2k
    auto *NewLoad =
1223
25.2k
        new LoadInst(LI->getType(), LoadPtr, LI->getName() + ".pre",
1224
25.2k
                     LI->isVolatile(), LI->getAlignment(), LI->getOrdering(),
1225
25.2k
                     LI->getSyncScopeID(), UnavailablePred->getTerminator());
1226
25.2k
    NewLoad->setDebugLoc(LI->getDebugLoc());
1227
25.2k
1228
25.2k
    // Transfer the old load's AA tags to the new load.
1229
25.2k
    AAMDNodes Tags;
1230
25.2k
    LI->getAAMetadata(Tags);
1231
25.2k
    if (Tags)
1232
23.5k
      NewLoad->setAAMetadata(Tags);
1233
25.2k
1234
25.2k
    if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load))
1235
2
      NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1236
25.2k
    if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group))
1237
1
      NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1238
25.2k
    if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range))
1239
73
      NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1240
25.2k
1241
25.2k
    // We do not propagate the old load's debug location, because the new
1242
25.2k
    // load now lives in a different BB, and we want to avoid a jumpy line
1243
25.2k
    // table.
1244
25.2k
    // FIXME: How do we retain source locations without causing poor debugging
1245
25.2k
    // behavior?
1246
25.2k
1247
25.2k
    // Add the newly created load.
1248
25.2k
    ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1249
25.2k
                                                        NewLoad));
1250
25.2k
    MD->invalidateCachedPointerInfo(LoadPtr);
1251
25.2k
    LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1252
25.2k
  }
1253
25.2k
1254
25.2k
  // Perform PHI construction.
1255
25.2k
  Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1256
25.2k
  LI->replaceAllUsesWith(V);
1257
25.2k
  if (isa<PHINode>(V))
1258
23.9k
    V->takeName(LI);
1259
25.2k
  if (Instruction *I = dyn_cast<Instruction>(V))
1260
25.2k
    I->setDebugLoc(LI->getDebugLoc());
1261
25.2k
  if (V->getType()->isPtrOrPtrVectorTy())
1262
9.33k
    MD->invalidateCachedPointerInfo(V);
1263
25.2k
  markInstructionForDeletion(LI);
1264
25.2k
  ORE->emit([&]() {
1265
0
    return OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI)
1266
0
           << "load eliminated by PRE";
1267
0
  });
1268
25.2k
  ++NumPRELoad;
1269
25.2k
  return true;
1270
25.2k
}
1271
1272
static void reportLoadElim(LoadInst *LI, Value *AvailableValue,
1273
41.2k
                           OptimizationRemarkEmitter *ORE) {
1274
41.2k
  using namespace ore;
1275
41.2k
1276
41.2k
  ORE->emit([&]() {
1277
12
    return OptimizationRemark(DEBUG_TYPE, "LoadElim", LI)
1278
12
           << "load of type " << NV("Type", LI->getType()) << " eliminated"
1279
12
           << setExtraArgs() << " in favor of "
1280
12
           << NV("InfavorOfValue", AvailableValue);
1281
12
  });
1282
41.2k
}
1283
1284
/// Attempt to eliminate a load whose dependencies are
1285
/// non-local by performing PHI construction.
1286
2.04M
bool GVN::processNonLocalLoad(LoadInst *LI) {
1287
2.04M
  // non-local speculations are not allowed under asan.
1288
2.04M
  if (LI->getParent()->getParent()->hasFnAttribute(
1289
2.04M
          Attribute::SanitizeAddress) ||
1290
2.04M
      LI->getParent()->getParent()->hasFnAttribute(
1291
2.04M
          Attribute::SanitizeHWAddress))
1292
4
    return false;
1293
2.04M
1294
2.04M
  // Step 1: Find the non-local dependencies of the load.
1295
2.04M
  LoadDepVect Deps;
1296
2.04M
  MD->getNonLocalPointerDependency(LI, Deps);
1297
2.04M
1298
2.04M
  // If we had to process more than one hundred blocks to find the
1299
2.04M
  // dependencies, this load isn't worth worrying about.  Optimizing
1300
2.04M
  // it will be too expensive.
1301
2.04M
  unsigned NumDeps = Deps.size();
1302
2.04M
  if (NumDeps > MaxNumDeps)
1303
656
    return false;
1304
2.04M
1305
2.04M
  // If we had a phi translation failure, we'll have a single entry which is a
1306
2.04M
  // clobber in the current block.  Reject this early.
1307
2.04M
  if (NumDeps == 1 &&
1308
2.04M
      
!Deps[0].getResult().isDef()893k
&&
!Deps[0].getResult().isClobber()878k
) {
1309
430k
    LLVM_DEBUG(dbgs() << "GVN: non-local load "; LI->printAsOperand(dbgs());
1310
430k
               dbgs() << " has unknown dependencies\n";);
1311
430k
    return false;
1312
430k
  }
1313
1.61M
1314
1.61M
  // If this load follows a GEP, see if we can PRE the indices before analyzing.
1315
1.61M
  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
1316
1.14M
    for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
1317
1.14M
                                        OE = GEP->idx_end();
1318
3.87M
         OI != OE; 
++OI2.72M
)
1319
2.72M
      if (Instruction *I = dyn_cast<Instruction>(OI->get()))
1320
225k
        performScalarPRE(I);
1321
1.14M
  }
1322
1.61M
1323
1.61M
  // Step 2: Analyze the availability of the load
1324
1.61M
  AvailValInBlkVect ValuesPerBlock;
1325
1.61M
  UnavailBlkVect UnavailableBlocks;
1326
1.61M
  AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1327
1.61M
1328
1.61M
  // If we have no predecessors that produce a known value for this load, exit
1329
1.61M
  // early.
1330
1.61M
  if (ValuesPerBlock.empty())
1331
1.39M
    return false;
1332
221k
1333
221k
  // Step 3: Eliminate fully redundancy.
1334
221k
  //
1335
221k
  // If all of the instructions we depend on produce a known value for this
1336
221k
  // load, then it is fully redundant and we can use PHI insertion to compute
1337
221k
  // its value.  Insert PHIs and remove the fully redundant value now.
1338
221k
  if (UnavailableBlocks.empty()) {
1339
31.2k
    LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1340
31.2k
1341
31.2k
    // Perform PHI construction.
1342
31.2k
    Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1343
31.2k
    LI->replaceAllUsesWith(V);
1344
31.2k
1345
31.2k
    if (isa<PHINode>(V))
1346
13.9k
      V->takeName(LI);
1347
31.2k
    if (Instruction *I = dyn_cast<Instruction>(V))
1348
29.7k
      // If instruction I has debug info, then we should not update it.
1349
29.7k
      // Also, if I has a null DebugLoc, then it is still potentially incorrect
1350
29.7k
      // to propagate LI's DebugLoc because LI may not post-dominate I.
1351
29.7k
      if (LI->getDebugLoc() && 
LI->getParent() == I->getParent()5.61k
)
1352
1.69k
        I->setDebugLoc(LI->getDebugLoc());
1353
31.2k
    if (V->getType()->isPtrOrPtrVectorTy())
1354
12.6k
      MD->invalidateCachedPointerInfo(V);
1355
31.2k
    markInstructionForDeletion(LI);
1356
31.2k
    ++NumGVNLoad;
1357
31.2k
    reportLoadElim(LI, V, ORE);
1358
31.2k
    return true;
1359
31.2k
  }
1360
190k
1361
190k
  // Step 4: Eliminate partial redundancy.
1362
190k
  if (!EnablePRE || !EnableLoadPRE)
1363
0
    return false;
1364
190k
1365
190k
  return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1366
190k
}
1367
1368
67
bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) {
1369
67
  assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume &&
1370
67
         "This function can only be called with llvm.assume intrinsic");
1371
67
  Value *V = IntrinsicI->getArgOperand(0);
1372
67
1373
67
  if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1374
5
    if (Cond->isZero()) {
1375
1
      Type *Int8Ty = Type::getInt8Ty(V->getContext());
1376
1
      // Insert a new store to null instruction before the load to indicate that
1377
1
      // this code is not reachable.  FIXME: We could insert unreachable
1378
1
      // instruction directly because we can modify the CFG.
1379
1
      new StoreInst(UndefValue::get(Int8Ty),
1380
1
                    Constant::getNullValue(Int8Ty->getPointerTo()),
1381
1
                    IntrinsicI);
1382
1
    }
1383
5
    markInstructionForDeletion(IntrinsicI);
1384
5
    return false;
1385
62
  } else if (isa<Constant>(V)) {
1386
1
    // If it's not false, and constant, it must evaluate to true. This means our
1387
1
    // assume is assume(true), and thus, pointless, and we don't want to do
1388
1
    // anything more here.
1389
1
    return false;
1390
1
  }
1391
61
1392
61
  Constant *True = ConstantInt::getTrue(V->getContext());
1393
61
  bool Changed = false;
1394
61
1395
61
  for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
1396
59
    BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
1397
59
1398
59
    // This property is only true in dominated successors, propagateEquality
1399
59
    // will check dominance for us.
1400
59
    Changed |= propagateEquality(V, True, Edge, false);
1401
59
  }
1402
61
1403
61
  // We can replace assume value with true, which covers cases like this:
1404
61
  // call void @llvm.assume(i1 %cmp)
1405
61
  // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
1406
61
  ReplaceWithConstMap[V] = True;
1407
61
1408
61
  // If one of *cmp *eq operand is const, adding it to map will cover this:
1409
61
  // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
1410
61
  // call void @llvm.assume(i1 %cmp)
1411
61
  // ret float %0 ; will change it to ret float 3.000000e+00
1412
61
  if (auto *CmpI = dyn_cast<CmpInst>(V)) {
1413
53
    if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
1414
53
        
CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ7
||
1415
53
        
(5
CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ5
&&
1416
50
         
CmpI->getFastMathFlags().noNaNs()4
)) {
1417
50
      Value *CmpLHS = CmpI->getOperand(0);
1418
50
      Value *CmpRHS = CmpI->getOperand(1);
1419
50
      if (isa<Constant>(CmpLHS))
1420
2
        std::swap(CmpLHS, CmpRHS);
1421
50
      auto *RHSConst = dyn_cast<Constant>(CmpRHS);
1422
50
1423
50
      // If only one operand is constant.
1424
50
      if (RHSConst != nullptr && !isa<Constant>(CmpLHS))
1425
50
        ReplaceWithConstMap[CmpLHS] = RHSConst;
1426
50
    }
1427
53
  }
1428
61
  return Changed;
1429
61
}
1430
1431
100k
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1432
100k
  patchReplacementInstruction(I, Repl);
1433
100k
  I->replaceAllUsesWith(Repl);
1434
100k
}
1435
1436
/// Attempt to eliminate a load, first by eliminating it
1437
/// locally, and then attempting non-local elimination if that fails.
1438
3.03M
bool GVN::processLoad(LoadInst *L) {
1439
3.03M
  if (!MD)
1440
1
    return false;
1441
3.03M
1442
3.03M
  // This code hasn't been audited for ordered or volatile memory access
1443
3.03M
  if (!L->isUnordered())
1444
28.1k
    return false;
1445
3.00M
1446
3.00M
  if (L->use_empty()) {
1447
502
    markInstructionForDeletion(L);
1448
502
    return true;
1449
502
  }
1450
3.00M
1451
3.00M
  // ... to a pointer that has been loaded from before...
1452
3.00M
  MemDepResult Dep = MD->getDependency(L);
1453
3.00M
1454
3.00M
  // If it is defined in another block, try harder.
1455
3.00M
  if (Dep.isNonLocal())
1456
2.04M
    return processNonLocalLoad(L);
1457
963k
1458
963k
  // Only handle the local case below
1459
963k
  if (!Dep.isDef() && 
!Dep.isClobber()953k
) {
1460
328k
    // This might be a NonFuncLocal or an Unknown
1461
328k
    LLVM_DEBUG(
1462
328k
        // fast print dep, using operator<< on instruction is too slow.
1463
328k
        dbgs() << "GVN: load "; L->printAsOperand(dbgs());
1464
328k
        dbgs() << " has unknown dependence\n";);
1465
328k
    return false;
1466
328k
  }
1467
634k
1468
634k
  AvailableValue AV;
1469
634k
  if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) {
1470
10.0k
    Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
1471
10.0k
1472
10.0k
    // Replace the load!
1473
10.0k
    patchAndReplaceAllUsesWith(L, AvailableValue);
1474
10.0k
    markInstructionForDeletion(L);
1475
10.0k
    ++NumGVNLoad;
1476
10.0k
    reportLoadElim(L, AvailableValue, ORE);
1477
10.0k
    // Tell MDA to rexamine the reused pointer since we might have more
1478
10.0k
    // information after forwarding it.
1479
10.0k
    if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
1480
3.20k
      MD->invalidateCachedPointerInfo(AvailableValue);
1481
10.0k
    return true;
1482
10.0k
  }
1483
624k
1484
624k
  return false;
1485
624k
}
1486
1487
/// Return a pair the first field showing the value number of \p Exp and the
1488
/// second field showing whether it is a value number newly created.
1489
std::pair<uint32_t, bool>
1490
15.2M
GVN::ValueTable::assignExpNewValueNum(Expression &Exp) {
1491
15.2M
  uint32_t &e = expressionNumbering[Exp];
1492
15.2M
  bool CreateNewValNum = !e;
1493
15.2M
  if (CreateNewValNum) {
1494
12.7M
    Expressions.push_back(Exp);
1495
12.7M
    if (ExprIdx.size() < nextValueNumber + 1)
1496
1.24M
      ExprIdx.resize(nextValueNumber * 2);
1497
12.7M
    e = nextValueNumber;
1498
12.7M
    ExprIdx[nextValueNumber++] = nextExprNumber++;
1499
12.7M
  }
1500
15.2M
  return {e, CreateNewValNum};
1501
15.2M
}
1502
1503
/// Return whether all the values related with the same \p num are
1504
/// defined in \p BB.
1505
bool GVN::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
1506
5.92M
                                     GVN &Gvn) {
1507
5.92M
  LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
1508
9.76M
  while (Vals && 
Vals->BB == BB6.12M
)
1509
3.83M
    Vals = Vals->Next;
1510
5.92M
  return !Vals;
1511
5.92M
}
1512
1513
/// Wrap phiTranslateImpl to provide caching functionality.
1514
uint32_t GVN::ValueTable::phiTranslate(const BasicBlock *Pred,
1515
                                       const BasicBlock *PhiBlock, uint32_t Num,
1516
9.30M
                                       GVN &Gvn) {
1517
9.30M
  auto FindRes = PhiTranslateTable.find({Num, Pred});
1518
9.30M
  if (FindRes != PhiTranslateTable.end())
1519
2.86M
    return FindRes->second;
1520
6.44M
  uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
1521
6.44M
  PhiTranslateTable.insert({{Num, Pred}, NewNum});
1522
6.44M
  return NewNum;
1523
6.44M
}
1524
1525
/// Translate value number \p Num using phis, so that it has the values of
1526
/// the phis in BB.
1527
uint32_t GVN::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
1528
                                           const BasicBlock *PhiBlock,
1529
6.44M
                                           uint32_t Num, GVN &Gvn) {
1530
6.44M
  if (PHINode *PN = NumberingPhi[Num]) {
1531
2.06M
    for (unsigned i = 0; i != PN->getNumIncomingValues(); 
++i1.55M
) {
1532
1.84M
      if (PN->getParent() == PhiBlock && 
PN->getIncomingBlock(i) == Pred1.36M
)
1533
309k
        if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false))
1534
294k
          return TransVal;
1535
1.84M
    }
1536
513k
    
return Num219k
;
1537
5.92M
  }
1538
5.92M
1539
5.92M
  // If there is any value related with Num is defined in a BB other than
1540
5.92M
  // PhiBlock, it cannot depend on a phi in PhiBlock without going through
1541
5.92M
  // a backedge. We can do an early exit in that case to save compile time.
1542
5.92M
  if (!areAllValsInBB(Num, PhiBlock, Gvn))
1543
2.28M
    return Num;
1544
3.64M
1545
3.64M
  if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
1546
591k
    return Num;
1547
3.04M
  Expression Exp = Expressions[ExprIdx[Num]];
1548
3.04M
1549
8.35M
  for (unsigned i = 0; i < Exp.varargs.size(); 
i++5.30M
) {
1550
5.30M
    // For InsertValue and ExtractValue, some varargs are index numbers
1551
5.30M
    // instead of value numbers. Those index numbers should not be
1552
5.30M
    // translated.
1553
5.30M
    if ((i > 1 && 
Exp.opcode == Instruction::InsertValue421k
) ||
1554
5.30M
        
(5.29M
i > 05.29M
&&
Exp.opcode == Instruction::ExtractValue2.24M
))
1555
31.1k
      continue;
1556
5.27M
    Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn);
1557
5.27M
  }
1558
3.04M
1559
3.04M
  if (Exp.commutative) {
1560
930k
    assert(Exp.varargs.size() == 2 && "Unsupported commutative expression!");
1561
930k
    if (Exp.varargs[0] > Exp.varargs[1]) {
1562
29.7k
      std::swap(Exp.varargs[0], Exp.varargs[1]);
1563
29.7k
      uint32_t Opcode = Exp.opcode >> 8;
1564
29.7k
      if (Opcode == Instruction::ICmp || 
Opcode == Instruction::FCmp29.0k
)
1565
747
        Exp.opcode = (Opcode << 8) |
1566
747
                     CmpInst::getSwappedPredicate(
1567
747
                         static_cast<CmpInst::Predicate>(Exp.opcode & 255));
1568
29.7k
    }
1569
930k
  }
1570
3.04M
1571
3.04M
  if (uint32_t NewNum = expressionNumbering[Exp])
1572
2.71M
    return NewNum;
1573
333k
  return Num;
1574
333k
}
1575
1576
/// Erase stale entry from phiTranslate cache so phiTranslate can be computed
1577
/// again.
1578
void GVN::ValueTable::eraseTranslateCacheEntry(uint32_t Num,
1579
12.4k
                                               const BasicBlock &CurrBlock) {
1580
27.0k
  for (const BasicBlock *Pred : predecessors(&CurrBlock)) {
1581
27.0k
    auto FindRes = PhiTranslateTable.find({Num, Pred});
1582
27.0k
    if (FindRes != PhiTranslateTable.end())
1583
27.0k
      PhiTranslateTable.erase(FindRes);
1584
27.0k
  }
1585
12.4k
}
1586
1587
// In order to find a leader for a given value number at a
1588
// specific basic block, we first obtain the list of all Values for that number,
1589
// and then scan the list to find one whose block dominates the block in
1590
// question.  This is fast because dominator tree queries consist of only
1591
// a few comparisons of DFS numbers.
1592
6.59M
Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1593
6.59M
  LeaderTableEntry Vals = LeaderTable[num];
1594
6.59M
  if (!Vals.Val) 
return nullptr819k
;
1595
5.77M
1596
5.77M
  Value *Val = nullptr;
1597
5.77M
  if (DT->dominates(Vals.BB, BB)) {
1598
114k
    Val = Vals.Val;
1599
114k
    if (isa<Constant>(Val)) 
return Val67
;
1600
5.77M
  }
1601
5.77M
1602
5.77M
  LeaderTableEntry* Next = Vals.Next;
1603
8.36M
  while (Next) {
1604
2.59M
    if (DT->dominates(Next->BB, BB)) {
1605
24.1k
      if (isa<Constant>(Next->Val)) 
return Next->Val874
;
1606
23.2k
      if (!Val) 
Val = Next->Val23.2k
;
1607
23.2k
    }
1608
2.59M
1609
2.59M
    Next = Next->Next;
1610
2.59M
  }
1611
5.77M
1612
5.77M
  
return Val5.77M
;
1613
5.77M
}
1614
1615
/// There is an edge from 'Src' to 'Dst'.  Return
1616
/// true if every path from the entry block to 'Dst' passes via this edge.  In
1617
/// particular 'Dst' must not be reachable via another edge from 'Src'.
1618
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
1619
4.36M
                                       DominatorTree *DT) {
1620
4.36M
  // While in theory it is interesting to consider the case in which Dst has
1621
4.36M
  // more than one predecessor, because Dst might be part of a loop which is
1622
4.36M
  // only reachable from Src, in practice it is pointless since at the time
1623
4.36M
  // GVN runs all such loops have preheaders, which means that Dst will have
1624
4.36M
  // been changed to have only one predecessor, namely Src.
1625
4.36M
  const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1626
4.36M
  assert((!Pred || Pred == E.getStart()) &&
1627
4.36M
         "No edge between these basic blocks!");
1628
4.36M
  return Pred != nullptr;
1629
4.36M
}
1630
1631
160k
void GVN::assignBlockRPONumber(Function &F) {
1632
160k
  BlockRPONumber.clear();
1633
160k
  uint32_t NextBlockNumber = 1;
1634
160k
  ReversePostOrderTraversal<Function *> RPOT(&F);
1635
160k
  for (BasicBlock *BB : RPOT)
1636
3.56M
    BlockRPONumber[BB] = NextBlockNumber++;
1637
160k
  InvalidBlockRPONumbers = false;
1638
160k
}
1639
1640
// Tries to replace instruction with const, using information from
1641
// ReplaceWithConstMap.
1642
167
bool GVN::replaceOperandsWithConsts(Instruction *Instr) const {
1643
167
  bool Changed = false;
1644
460
  for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); 
++OpNum293
) {
1645
293
    Value *Operand = Instr->getOperand(OpNum);
1646
293
    auto it = ReplaceWithConstMap.find(Operand);
1647
293
    if (it != ReplaceWithConstMap.end()) {
1648
13
      assert(!isa<Constant>(Operand) &&
1649
13
             "Replacing constants with constants is invalid");
1650
13
      LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with "
1651
13
                        << *it->second << " in instruction " << *Instr << '\n');
1652
13
      Instr->setOperand(OpNum, it->second);
1653
13
      Changed = true;
1654
13
    }
1655
293
  }
1656
167
  return Changed;
1657
167
}
1658
1659
/// The given values are known to be equal in every block
1660
/// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
1661
/// 'RHS' everywhere in the scope.  Returns whether a change was made.
1662
/// If DominatesByEdge is false, then it means that we will propagate the RHS
1663
/// value starting from the end of Root.Start.
1664
bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
1665
4.36M
                            bool DominatesByEdge) {
1666
4.36M
  SmallVector<std::pair<Value*, Value*>, 4> Worklist;
1667
4.36M
  Worklist.push_back(std::make_pair(LHS, RHS));
1668
4.36M
  bool Changed = false;
1669
4.36M
  // For speed, compute a conservative fast approximation to
1670
4.36M
  // DT->dominates(Root, Root.getEnd());
1671
4.36M
  const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
1672
4.36M
1673
10.4M
  while (!Worklist.empty()) {
1674
6.06M
    std::pair<Value*, Value*> Item = Worklist.pop_back_val();
1675
6.06M
    LHS = Item.first; RHS = Item.second;
1676
6.06M
1677
6.06M
    if (LHS == RHS)
1678
44
      continue;
1679
6.06M
    assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
1680
6.06M
1681
6.06M
    // Don't try to propagate equalities between constants.
1682
6.06M
    if (isa<Constant>(LHS) && 
isa<Constant>(RHS)807
)
1683
160
      continue;
1684
6.06M
1685
6.06M
    // Prefer a constant on the right-hand side, or an Argument if no constants.
1686
6.06M
    if (isa<Constant>(LHS) || 
(6.06M
isa<Argument>(LHS)6.06M
&&
!isa<Constant>(RHS)175k
))
1687
3.82k
      std::swap(LHS, RHS);
1688
6.06M
    assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
1689
6.06M
1690
6.06M
    // If there is no obvious reason to prefer the left-hand side over the
1691
6.06M
    // right-hand side, ensure the longest lived term is on the right-hand side,
1692
6.06M
    // so the shortest lived term will be replaced by the longest lived.
1693
6.06M
    // This tends to expose more simplifications.
1694
6.06M
    uint32_t LVN = VN.lookupOrAdd(LHS);
1695
6.06M
    if ((isa<Argument>(LHS) && 
isa<Argument>(RHS)175k
) ||
1696
6.06M
        
(6.06M
isa<Instruction>(LHS)6.06M
&&
isa<Instruction>(RHS)5.89M
)) {
1697
259k
      // Move the 'oldest' value to the right-hand side, using the value number
1698
259k
      // as a proxy for age.
1699
259k
      uint32_t RVN = VN.lookupOrAdd(RHS);
1700
259k
      if (LVN < RVN) {
1701
84.5k
        std::swap(LHS, RHS);
1702
84.5k
        LVN = RVN;
1703
84.5k
      }
1704
259k
    }
1705
6.06M
1706
6.06M
    // If value numbering later sees that an instruction in the scope is equal
1707
6.06M
    // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
1708
6.06M
    // the invariant that instructions only occur in the leader table for their
1709
6.06M
    // own value number (this is used by removeFromLeaderTable), do not do this
1710
6.06M
    // if RHS is an instruction (if an instruction in the scope is morphed into
1711
6.06M
    // LHS then it will be turned into RHS by the next GVN iteration anyway, so
1712
6.06M
    // using the leader table is about compiling faster, not optimizing better).
1713
6.06M
    // The leader table only tracks basic blocks, not edges. Only add to if we
1714
6.06M
    // have the simple case where the edge dominates the end.
1715
6.06M
    if (RootDominatesEnd && 
!isa<Instruction>(RHS)3.64M
)
1716
3.45M
      addToLeaderTable(LVN, RHS, Root.getEnd());
1717
6.06M
1718
6.06M
    // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
1719
6.06M
    // LHS always has at least one use that is not dominated by Root, this will
1720
6.06M
    // never do anything if LHS has only one use.
1721
6.06M
    if (!LHS->hasOneUse()) {
1722
1.20M
      unsigned NumReplacements =
1723
1.20M
          DominatesByEdge
1724
1.20M
              ? 
replaceDominatedUsesWith(LHS, RHS, *DT, Root)1.20M
1725
1.20M
              : 
replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart())18
;
1726
1.20M
1727
1.20M
      Changed |= NumReplacements > 0;
1728
1.20M
      NumGVNEqProp += NumReplacements;
1729
1.20M
      // Cached information for anything that uses LHS will be invalid.
1730
1.20M
      if (MD)
1731
1.20M
        MD->invalidateCachedPointerInfo(LHS);
1732
1.20M
    }
1733
6.06M
1734
6.06M
    // Now try to deduce additional equalities from this one. For example, if
1735
6.06M
    // the known equality was "(A != B)" == "false" then it follows that A and B
1736
6.06M
    // are equal in the scope. Only boolean equalities with an explicit true or
1737
6.06M
    // false RHS are currently supported.
1738
6.06M
    if (!RHS->getType()->isIntegerTy(1))
1739
1.53M
      // Not a boolean equality - bail out.
1740
1.53M
      continue;
1741
4.53M
    ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1742
4.53M
    if (!CI)
1743
0
      // RHS neither 'true' nor 'false' - bail out.
1744
0
      continue;
1745
4.53M
    // Whether RHS equals 'true'.  Otherwise it equals 'false'.
1746
4.53M
    bool isKnownTrue = CI->isMinusOne();
1747
4.53M
    bool isKnownFalse = !isKnownTrue;
1748
4.53M
1749
4.53M
    // If "A && B" is known true then both A and B are known true.  If "A || B"
1750
4.53M
    // is known false then both A and B are known false.
1751
4.53M
    Value *A, *B;
1752
4.53M
    if ((isKnownTrue && 
match(LHS, m_And(m_Value(A), m_Value(B)))2.30M
) ||
1753
4.53M
        
(4.44M
isKnownFalse4.44M
&&
match(LHS, m_Or(m_Value(A), m_Value(B)))2.22M
)) {
1754
122k
      Worklist.push_back(std::make_pair(A, RHS));
1755
122k
      Worklist.push_back(std::make_pair(B, RHS));
1756
122k
      continue;
1757
122k
    }
1758
4.40M
1759
4.40M
    // If we are propagating an equality like "(A == B)" == "true" then also
1760
4.40M
    // propagate the equality A == B.  When propagating a comparison such as
1761
4.40M
    // "(A >= B)" == "true", replace all instances of "A < B" with "false".
1762
4.40M
    if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
1763
4.14M
      Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1764
4.14M
1765
4.14M
      // If "A == B" is known true, or "A != B" is known false, then replace
1766
4.14M
      // A with B everywhere in the scope.
1767
4.14M
      if ((isKnownTrue && 
Cmp->getPredicate() == CmpInst::ICMP_EQ2.11M
) ||
1768
4.14M
          
(2.75M
isKnownFalse2.75M
&&
Cmp->getPredicate() == CmpInst::ICMP_NE2.02M
))
1769
1.45M
        Worklist.push_back(std::make_pair(Op0, Op1));
1770
4.14M
1771
4.14M
      // Handle the floating point versions of equality comparisons too.
1772
4.14M
      if ((isKnownTrue && 
Cmp->getPredicate() == CmpInst::FCMP_OEQ2.11M
) ||
1773
4.14M
          
(4.14M
isKnownFalse4.14M
&&
Cmp->getPredicate() == CmpInst::FCMP_UNE2.02M
)) {
1774
2.19k
1775
2.19k
        // Floating point -0.0 and 0.0 compare equal, so we can only
1776
2.19k
        // propagate values if we know that we have a constant and that
1777
2.19k
        // its value is non-zero.
1778
2.19k
1779
2.19k
        // FIXME: We should do this optimization if 'no signed zeros' is
1780
2.19k
        // applicable via an instruction-level fast-math-flag or some other
1781
2.19k
        // indicator that relaxed FP semantics are being used.
1782
2.19k
1783
2.19k
        if (isa<ConstantFP>(Op1) && 
!cast<ConstantFP>(Op1)->isZero()1.70k
)
1784
311
          Worklist.push_back(std::make_pair(Op0, Op1));
1785
2.19k
      }
1786
4.14M
1787
4.14M
      // If "A >= B" is known true, replace "A < B" with false everywhere.
1788
4.14M
      CmpInst::Predicate NotPred = Cmp->getInversePredicate();
1789
4.14M
      Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
1790
4.14M
      // Since we don't have the instruction "A < B" immediately to hand, work
1791
4.14M
      // out the value number that it would have and use that to find an
1792
4.14M
      // appropriate instruction (if any).
1793
4.14M
      uint32_t NextNum = VN.getNextUnusedValueNumber();
1794
4.14M
      uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
1795
4.14M
      // If the number we were assigned was brand new then there is no point in
1796
4.14M
      // looking for an instruction realizing it: there cannot be one!
1797
4.14M
      if (Num < NextNum) {
1798
2.05M
        Value *NotCmp = findLeader(Root.getEnd(), Num);
1799
2.05M
        if (NotCmp && 
isa<Instruction>(NotCmp)2.78k
) {
1800
2.72k
          unsigned NumReplacements =
1801
2.72k
              DominatesByEdge
1802
2.72k
                  ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
1803
2.72k
                  : replaceDominatedUsesWith(NotCmp, NotVal, *DT,
1804
0
                                             Root.getStart());
1805
2.72k
          Changed |= NumReplacements > 0;
1806
2.72k
          NumGVNEqProp += NumReplacements;
1807
2.72k
          // Cached information for anything that uses NotCmp will be invalid.
1808
2.72k
          if (MD)
1809
2.72k
            MD->invalidateCachedPointerInfo(NotCmp);
1810
2.72k
        }
1811
2.05M
      }
1812
4.14M
      // Ensure that any instruction in scope that gets the "A < B" value number
1813
4.14M
      // is replaced with false.
1814
4.14M
      // The leader table only tracks basic blocks, not edges. Only add to if we
1815
4.14M
      // have the simple case where the edge dominates the end.
1816
4.14M
      if (RootDominatesEnd)
1817
2.50M
        addToLeaderTable(Num, NotVal, Root.getEnd());
1818
4.14M
1819
4.14M
      continue;
1820
4.14M
    }
1821
4.40M
  }
1822
4.36M
1823
4.36M
  return Changed;
1824
4.36M
}
1825
1826
/// When calculating availability, handle an instruction
1827
/// by inserting it into the appropriate sets
1828
25.1M
bool GVN::processInstruction(Instruction *I) {
1829
25.1M
  // Ignore dbg info intrinsics.
1830
25.1M
  if (isa<DbgInfoIntrinsic>(I))
1831
134
    return false;
1832
25.1M
1833
25.1M
  // If the instruction can be easily simplified then do so now in preference
1834
25.1M
  // to value numbering it.  Value numbering often exposes redundancies, for
1835
25.1M
  // example if it determines that %y is equal to %x then the instruction
1836
25.1M
  // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
1837
25.1M
  const DataLayout &DL = I->getModule()->getDataLayout();
1838
25.1M
  if (Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC})) {
1839
140k
    bool Changed = false;
1840
140k
    if (!I->use_empty()) {
1841
140k
      I->replaceAllUsesWith(V);
1842
140k
      Changed = true;
1843
140k
    }
1844
140k
    if (isInstructionTriviallyDead(I, TLI)) {
1845
140k
      markInstructionForDeletion(I);
1846
140k
      Changed = true;
1847
140k
    }
1848
140k
    if (Changed) {
1849
140k
      if (MD && V->getType()->isPtrOrPtrVectorTy())
1850
59.8k
        MD->invalidateCachedPointerInfo(V);
1851
140k
      ++NumGVNSimpl;
1852
140k
      return true;
1853
140k
    }
1854
25.0M
  }
1855
25.0M
1856
25.0M
  if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I))
1857
476k
    if (IntrinsicI->getIntrinsicID() == Intrinsic::assume)
1858
67
      return processAssumeIntrinsic(IntrinsicI);
1859
25.0M
1860
25.0M
  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1861
3.03M
    if (processLoad(LI))
1862
67.1k
      return true;
1863
2.97M
1864
2.97M
    unsigned Num = VN.lookupOrAdd(LI);
1865
2.97M
    addToLeaderTable(Num, LI, LI->getParent());
1866
2.97M
    return false;
1867
2.97M
  }
1868
22.0M
1869
22.0M
  // For conditional branches, we can perform simple conditional propagation on
1870
22.0M
  // the condition value itself.
1871
22.0M
  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1872
3.96M
    if (!BI->isConditional())
1873
1.80M
      return false;
1874
2.15M
1875
2.15M
    if (isa<Constant>(BI->getCondition()))
1876
14.9k
      return processFoldableCondBr(BI);
1877
2.14M
1878
2.14M
    Value *BranchCond = BI->getCondition();
1879
2.14M
    BasicBlock *TrueSucc = BI->getSuccessor(0);
1880
2.14M
    BasicBlock *FalseSucc = BI->getSuccessor(1);
1881
2.14M
    // Avoid multiple edges early.
1882
2.14M
    if (TrueSucc == FalseSucc)
1883
0
      return false;
1884
2.14M
1885
2.14M
    BasicBlock *Parent = BI->getParent();
1886
2.14M
    bool Changed = false;
1887
2.14M
1888
2.14M
    Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
1889
2.14M
    BasicBlockEdge TrueE(Parent, TrueSucc);
1890
2.14M
    Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
1891
2.14M
1892
2.14M
    Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
1893
2.14M
    BasicBlockEdge FalseE(Parent, FalseSucc);
1894
2.14M
    Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
1895
2.14M
1896
2.14M
    return Changed;
1897
2.14M
  }
1898
18.0M
1899
18.0M
  // For switches, propagate the case values into the case destinations.
1900
18.0M
  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1901
38.6k
    Value *SwitchCond = SI->getCondition();
1902
38.6k
    BasicBlock *Parent = SI->getParent();
1903
38.6k
    bool Changed = false;
1904
38.6k
1905
38.6k
    // Remember how many outgoing edges there are to every successor.
1906
38.6k
    SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1907
205k
    for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; 
++i167k
)
1908
167k
      ++SwitchEdges[SI->getSuccessor(i)];
1909
38.6k
1910
38.6k
    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
1911
167k
         i != e; 
++i128k
) {
1912
128k
      BasicBlock *Dst = i->getCaseSuccessor();
1913
128k
      // If there is only a single edge, propagate the case value into it.
1914
128k
      if (SwitchEdges.lookup(Dst) == 1) {
1915
78.4k
        BasicBlockEdge E(Parent, Dst);
1916
78.4k
        Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true);
1917
78.4k
      }
1918
128k
    }
1919
38.6k
    return Changed;
1920
38.6k
  }
1921
18.0M
1922
18.0M
  // Instructions with void type don't return a value, so there's
1923
18.0M
  // no point in trying to find redundancies in them.
1924
18.0M
  if (I->getType()->isVoidTy())
1925
4.03M
    return false;
1926
13.9M
1927
13.9M
  uint32_t NextNum = VN.getNextUnusedValueNumber();
1928
13.9M
  unsigned Num = VN.lookupOrAdd(I);
1929
13.9M
1930
13.9M
  // Allocations are always uniquely numbered, so we can save time and memory
1931
13.9M
  // by fast failing them.
1932
13.9M
  if (isa<AllocaInst>(I) || 
I->isTerminator()13.8M
||
isa<PHINode>(I)13.7M
) {
1933
1.34M
    addToLeaderTable(Num, I, I->getParent());
1934
1.34M
    return false;
1935
1.34M
  }
1936
12.6M
1937
12.6M
  // If the number we were assigned was a brand new VN, then we don't
1938
12.6M
  // need to do a lookup to see if the number already exists
1939
12.6M
  // somewhere in the domtree: it can't!
1940
12.6M
  if (Num >= NextNum) {
1941
12.1M
    addToLeaderTable(Num, I, I->getParent());
1942
12.1M
    return false;
1943
12.1M
  }
1944
506k
1945
506k
  // Perform fast-path value-number based elimination of values inherited from
1946
506k
  // dominators.
1947
506k
  Value *Repl = findLeader(I->getParent(), Num);
1948
506k
  if (!Repl) {
1949
415k
    // Failure, just remember this instance for future use.
1950
415k
    addToLeaderTable(Num, I, I->getParent());
1951
415k
    return false;
1952
415k
  } else 
if (90.8k
Repl == I90.8k
) {
1953
2
    // If I was the result of a shortcut PRE, it might already be in the table
1954
2
    // and the best replacement for itself. Nothing to do.
1955
2
    return false;
1956
2
  }
1957
90.8k
1958
90.8k
  // Remove it!
1959
90.8k
  patchAndReplaceAllUsesWith(I, Repl);
1960
90.8k
  if (
MD90.8k
&& Repl->getType()->isPtrOrPtrVectorTy())
1961
60.7k
    MD->invalidateCachedPointerInfo(Repl);
1962
90.8k
  markInstructionForDeletion(I);
1963
90.8k
  return true;
1964
90.8k
}
1965
1966
/// runOnFunction - This is the main transformation entry point for a function.
1967
bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
1968
                  const TargetLibraryInfo &RunTLI, AAResults &RunAA,
1969
                  MemoryDependenceResults *RunMD, LoopInfo *LI,
1970
464k
                  OptimizationRemarkEmitter *RunORE) {
1971
464k
  AC = &RunAC;
1972
464k
  DT = &RunDT;
1973
464k
  VN.setDomTree(DT);
1974
464k
  TLI = &RunTLI;
1975
464k
  VN.setAliasAnalysis(&RunAA);
1976
464k
  MD = RunMD;
1977
464k
  ImplicitControlFlowTracking ImplicitCFT(DT);
1978
464k
  ICF = &ImplicitCFT;
1979
464k
  VN.setMemDep(MD);
1980
464k
  ORE = RunORE;
1981
464k
  InvalidBlockRPONumbers = true;
1982
464k
1983
464k
  bool Changed = false;
1984
464k
  bool ShouldContinue = true;
1985
464k
1986
464k
  DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1987
464k
  // Merge unconditional branches, allowing PRE to catch more
1988
464k
  // optimization opportunities.
1989
3.37M
  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1990
2.91M
    BasicBlock *BB = &*FI++;
1991
2.91M
1992
2.91M
    bool removedBlock = MergeBlockIntoPredecessor(BB, &DTU, LI, nullptr, MD);
1993
2.91M
    if (removedBlock)
1994
23.7k
      ++NumGVNBlocks;
1995
2.91M
1996
2.91M
    Changed |= removedBlock;
1997
2.91M
  }
1998
464k
1999
464k
  unsigned Iteration = 0;
2000
994k
  while (ShouldContinue) {
2001
529k
    LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2002
529k
    ShouldContinue = iterateOnFunction(F);
2003
529k
    Changed |= ShouldContinue;
2004
529k
    ++Iteration;
2005
529k
  }
2006
464k
2007
464k
  if (EnablePRE) {
2008
464k
    // Fabricate val-num for dead-code in order to suppress assertion in
2009
464k
    // performPRE().
2010
464k
    assignValNumForDeadCode();
2011
464k
    bool PREChanged = true;
2012
940k
    while (PREChanged) {
2013
475k
      PREChanged = performPRE(F);
2014
475k
      Changed |= PREChanged;
2015
475k
    }
2016
464k
  }
2017
464k
2018
464k
  // FIXME: Should perform GVN again after PRE does something.  PRE can move
2019
464k
  // computations into blocks where they become fully redundant.  Note that
2020
464k
  // we can't do this until PRE's critical edge splitting updates memdep.
2021
464k
  // Actually, when this happens, we should just fully integrate PRE into GVN.
2022
464k
2023
464k
  cleanupGlobalSets();
2024
464k
  // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
2025
464k
  // iteration.
2026
464k
  DeadBlocks.clear();
2027
464k
2028
464k
  return Changed;
2029
464k
}
2030
2031
4.70M
bool GVN::processBlock(BasicBlock *BB) {
2032
4.70M
  // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2033
4.70M
  // (and incrementing BI before processing an instruction).
2034
4.70M
  assert(InstrsToErase.empty() &&
2035
4.70M
         "We expect InstrsToErase to be empty across iterations");
2036
4.70M
  if (DeadBlocks.count(BB))
2037
13.8k
    return false;
2038
4.68M
2039
4.68M
  // Clearing map before every BB because it can be used only for single BB.
2040
4.68M
  ReplaceWithConstMap.clear();
2041
4.68M
  bool ChangedFunction = false;
2042
4.68M
2043
4.68M
  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2044
29.8M
       BI != BE;) {
2045
25.1M
    if (!ReplaceWithConstMap.empty())
2046
167
      ChangedFunction |= replaceOperandsWithConsts(&*BI);
2047
25.1M
    ChangedFunction |= processInstruction(&*BI);
2048
25.1M
2049
25.1M
    if (InstrsToErase.empty()) {
2050
24.8M
      ++BI;
2051
24.8M
      continue;
2052
24.8M
    }
2053
298k
2054
298k
    // If we need some instructions deleted, do it now.
2055
298k
    NumGVNInstr += InstrsToErase.size();
2056
298k
2057
298k
    // Avoid iterator invalidation.
2058
298k
    bool AtStart = BI == BB->begin();
2059
298k
    if (!AtStart)
2060
138k
      --BI;
2061
298k
2062
298k
    for (auto *I : InstrsToErase) {
2063
298k
      assert(I->getParent() == BB && "Removing instruction from wrong block?");
2064
298k
      LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n');
2065
298k
      salvageDebugInfo(*I);
2066
298k
      if (MD) MD->removeInstruction(I);
2067
298k
      LLVM_DEBUG(verifyRemoved(I));
2068
298k
      ICF->removeInstruction(I);
2069
298k
      I->eraseFromParent();
2070
298k
    }
2071
298k
    InstrsToErase.clear();
2072
298k
2073
298k
    if (AtStart)
2074
159k
      BI = BB->begin();
2075
138k
    else
2076
138k
      ++BI;
2077
298k
  }
2078
4.68M
2079
4.68M
  return ChangedFunction;
2080
4.68M
}
2081
2082
// Instantiate an expression in a predecessor that lacked it.
2083
bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
2084
13.6k
                                    BasicBlock *Curr, unsigned int ValNo) {
2085
13.6k
  // Because we are going top-down through the block, all value numbers
2086
13.6k
  // will be available in the predecessor by the time we need them.  Any
2087
13.6k
  // that weren't originally present will have been instantiated earlier
2088
13.6k
  // in this loop.
2089
13.6k
  bool success = true;
2090
30.9k
  for (unsigned i = 0, e = Instr->getNumOperands(); i != e; 
++i17.2k
) {
2091
19.0k
    Value *Op = Instr->getOperand(i);
2092
19.0k
    if (isa<Argument>(Op) || 
isa<Constant>(Op)17.9k
||
isa<GlobalValue>(Op)10.4k
)
2093
8.64k
      continue;
2094
10.4k
    // This could be a newly inserted instruction, in which case, we won't
2095
10.4k
    // find a value number, and should give up before we hurt ourselves.
2096
10.4k
    // FIXME: Rewrite the infrastructure to let it easier to value number
2097
10.4k
    // and process newly inserted instructions.
2098
10.4k
    if (!VN.exists(Op)) {
2099
0
      success = false;
2100
0
      break;
2101
0
    }
2102
10.4k
    uint32_t TValNo =
2103
10.4k
        VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
2104
10.4k
    if (Value *V = findLeader(Pred, TValNo)) {
2105
8.63k
      Instr->setOperand(i, V);
2106
8.63k
    } else {
2107
1.79k
      success = false;
2108
1.79k
      break;
2109
1.79k
    }
2110
10.4k
  }
2111
13.6k
2112
13.6k
  // Fail out if we encounter an operand that is not available in
2113
13.6k
  // the PRE predecessor.  This is typically because of loads which
2114
13.6k
  // are not value numbered precisely.
2115
13.6k
  if (!success)
2116
1.79k
    return false;
2117
11.8k
2118
11.8k
  Instr->insertBefore(Pred->getTerminator());
2119
11.8k
  Instr->setName(Instr->getName() + ".pre");
2120
11.8k
  Instr->setDebugLoc(Instr->getDebugLoc());
2121
11.8k
2122
11.8k
  unsigned Num = VN.lookupOrAdd(Instr);
2123
11.8k
  VN.add(Instr, Num);
2124
11.8k
2125
11.8k
  // Update the availability map to include the new instruction.
2126
11.8k
  addToLeaderTable(Num, Instr, Pred);
2127
11.8k
  return true;
2128
11.8k
}
2129
2130
15.6M
bool GVN::performScalarPRE(Instruction *CurInst) {
2131
15.6M
  if (isa<AllocaInst>(CurInst) || 
CurInst->isTerminator()15.6M
||
2132
15.6M
      
isa<PHINode>(CurInst)12.6M
||
CurInst->getType()->isVoidTy()11.6M
||
2133
15.6M
      
CurInst->mayReadFromMemory()9.60M
||
CurInst->mayHaveSideEffects()6.86M
||
2134
15.6M
      
isa<DbgInfoIntrinsic>(CurInst)6.86M
)
2135
8.81M
    return false;
2136
6.86M
2137
6.86M
  // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2138
6.86M
  // sinking the compare again, and it would force the code generator to
2139
6.86M
  // move the i1 from processor flags or predicate registers into a general
2140
6.86M
  // purpose register.
2141
6.86M
  if (isa<CmpInst>(CurInst))
2142
1.54M
    return false;
2143
5.32M
2144
5.32M
  // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from
2145
5.32M
  // sinking the addressing mode computation back to its uses. Extending the
2146
5.32M
  // GEP's live range increases the register pressure, and therefore it can
2147
5.32M
  // introduce unnecessary spills.
2148
5.32M
  //
2149
5.32M
  // This doesn't prevent Load PRE. PHI translation will make the GEP available
2150
5.32M
  // to the load by moving it to the predecessor block if necessary.
2151
5.32M
  if (isa<GetElementPtrInst>(CurInst))
2152
2.30M
    return false;
2153
3.02M
2154
3.02M
  // We don't currently value number ANY inline asm calls.
2155
3.02M
  if (auto *CallB = dyn_cast<CallBase>(CurInst))
2156
55.0k
    if (CallB->isInlineAsm())
2157
61
      return false;
2158
3.02M
2159
3.02M
  uint32_t ValNo = VN.lookup(CurInst);
2160
3.02M
2161
3.02M
  // Look for the predecessors for PRE opportunities.  We're
2162
3.02M
  // only trying to solve the basic diamond case, where
2163
3.02M
  // a value is computed in the successor and one predecessor,
2164
3.02M
  // but not the other.  We also explicitly disallow cases
2165
3.02M
  // where the successor is its own predecessor, because they're
2166
3.02M
  // more complicated to get right.
2167
3.02M
  unsigned NumWith = 0;
2168
3.02M
  unsigned NumWithout = 0;
2169
3.02M
  BasicBlock *PREPred = nullptr;
2170
3.02M
  BasicBlock *CurrentBlock = CurInst->getParent();
2171
3.02M
2172
3.02M
  // Update the RPO numbers for this function.
2173
3.02M
  if (InvalidBlockRPONumbers)
2174
160k
    assignBlockRPONumber(*CurrentBlock->getParent());
2175
3.02M
2176
3.02M
  SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
2177
4.59M
  for (BasicBlock *P : predecessors(CurrentBlock)) {
2178
4.59M
    // We're not interested in PRE where blocks with predecessors that are
2179
4.59M
    // not reachable.
2180
4.59M
    if (!DT->isReachableFromEntry(P)) {
2181
1
      NumWithout = 2;
2182
1
      break;
2183
1
    }
2184
4.59M
    // It is not safe to do PRE when P->CurrentBlock is a loop backedge, and
2185
4.59M
    // when CurInst has operand defined in CurrentBlock (so it may be defined
2186
4.59M
    // by phi in the loop header).
2187
4.59M
    assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
2188
4.59M
           "Invalid BlockRPONumber map.");
2189
4.59M
    if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
2190
4.59M
        
llvm::any_of(CurInst->operands(), [&](const Use &U) 576k
{
2191
596k
          if (auto *Inst = dyn_cast<Instruction>(U.get()))
2192
582k
            return Inst->getParent() == CurrentBlock;
2193
13.3k
          return false;
2194
573k
        })) {
2195
573k
      NumWithout = 2;
2196
573k
      break;
2197
573k
    }
2198
4.01M
2199
4.01M
    uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
2200
4.01M
    Value *predV = findLeader(P, TValNo);
2201
4.01M
    if (!predV) {
2202
3.98M
      predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
2203
3.98M
      PREPred = P;
2204
3.98M
      ++NumWithout;
2205
3.98M
    } else 
if (35.9k
predV == CurInst35.9k
) {
2206
2.53k
      /* CurInst dominates this predecessor. */
2207
2.53k
      NumWithout = 2;
2208
2.53k
      break;
2209
33.4k
    } else {
2210
33.4k
      predMap.push_back(std::make_pair(predV, P));
2211
33.4k
      ++NumWith;
2212
33.4k
    }
2213
4.01M
  }
2214
3.02M
2215
3.02M
  // Don't do PRE when it might increase code size, i.e. when
2216
3.02M
  // we would need to insert instructions in more than one pred.
2217
3.02M
  if (NumWithout > 1 || 
NumWith == 01.74M
)
2218
3.00M
    return false;
2219
23.8k
2220
23.8k
  // We may have a case where all predecessors have the instruction,
2221
23.8k
  // and we just need to insert a phi node. Otherwise, perform
2222
23.8k
  // insertion.
2223
23.8k
  Instruction *PREInstr = nullptr;
2224
23.8k
2225
23.8k
  if (NumWithout != 0) {
2226
23.2k
    if (!isSafeToSpeculativelyExecute(CurInst)) {
2227
5.16k
      // It is only valid to insert a new instruction if the current instruction
2228
5.16k
      // is always executed. An instruction with implicit control flow could
2229
5.16k
      // prevent us from doing it. If we cannot speculate the execution, then
2230
5.16k
      // PRE should be prohibited.
2231
5.16k
      if (ICF->isDominatedByICFIFromSameBlock(CurInst))
2232
1
        return false;
2233
23.2k
    }
2234
23.2k
2235
23.2k
    // Don't do PRE across indirect branch.
2236
23.2k
    if (isa<IndirectBrInst>(PREPred->getTerminator()))
2237
0
      return false;
2238
23.2k
2239
23.2k
    // Don't do PRE across callbr.
2240
23.2k
    // FIXME: Can we do this across the fallthrough edge?
2241
23.2k
    if (isa<CallBrInst>(PREPred->getTerminator()))
2242
1
      return false;
2243
23.2k
2244
23.2k
    // We can't do PRE safely on a critical edge, so instead we schedule
2245
23.2k
    // the edge to be split and perform the PRE the next time we iterate
2246
23.2k
    // on the function.
2247
23.2k
    unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2248
23.2k
    if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2249
9.61k
      toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2250
9.61k
      return false;
2251
9.61k
    }
2252
13.6k
    // We need to insert somewhere, so let's give it a shot
2253
13.6k
    PREInstr = CurInst->clone();
2254
13.6k
    if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
2255
1.79k
      // If we failed insertion, make sure we remove the instruction.
2256
1.79k
      LLVM_DEBUG(verifyRemoved(PREInstr));
2257
1.79k
      PREInstr->deleteValue();
2258
1.79k
      return false;
2259
1.79k
    }
2260
12.4k
  }
2261
12.4k
2262
12.4k
  // Either we should have filled in the PRE instruction, or we should
2263
12.4k
  // not have needed insertions.
2264
12.4k
  assert(PREInstr != nullptr || NumWithout == 0);
2265
12.4k
2266
12.4k
  ++NumGVNPRE;
2267
12.4k
2268
12.4k
  // Create a PHI to make the value available in this block.
2269
12.4k
  PHINode *Phi =
2270
12.4k
      PHINode::Create(CurInst->getType(), predMap.size(),
2271
12.4k
                      CurInst->getName() + ".pre-phi", &CurrentBlock->front());
2272
39.4k
  for (unsigned i = 0, e = predMap.size(); i != e; 
++i27.0k
) {
2273
27.0k
    if (Value *V = predMap[i].first) {
2274
15.1k
      // If we use an existing value in this phi, we have to patch the original
2275
15.1k
      // value because the phi will be used to replace a later value.
2276
15.1k
      patchReplacementInstruction(CurInst, V);
2277
15.1k
      Phi->addIncoming(V, predMap[i].second);
2278
15.1k
    } else
2279
11.8k
      Phi->addIncoming(PREInstr, PREPred);
2280
27.0k
  }
2281
12.4k
2282
12.4k
  VN.add(Phi, ValNo);
2283
12.4k
  // After creating a new PHI for ValNo, the phi translate result for ValNo will
2284
12.4k
  // be changed, so erase the related stale entries in phi translate cache.
2285
12.4k
  VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
2286
12.4k
  addToLeaderTable(ValNo, Phi, CurrentBlock);
2287
12.4k
  Phi->setDebugLoc(CurInst->getDebugLoc());
2288
12.4k
  CurInst->replaceAllUsesWith(Phi);
2289
12.4k
  if (MD && Phi->getType()->isPtrOrPtrVectorTy())
2290
5.58k
    MD->invalidateCachedPointerInfo(Phi);
2291
12.4k
  VN.erase(CurInst);
2292
12.4k
  removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2293
12.4k
2294
12.4k
  LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2295
12.4k
  if (MD)
2296
12.4k
    MD->removeInstruction(CurInst);
2297
12.4k
  LLVM_DEBUG(verifyRemoved(CurInst));
2298
12.4k
  // FIXME: Intended to be markInstructionForDeletion(CurInst), but it causes
2299
12.4k
  // some assertion failures.
2300
12.4k
  ICF->removeInstruction(CurInst);
2301
12.4k
  CurInst->eraseFromParent();
2302
12.4k
  ++NumGVNInstr;
2303
12.4k
2304
12.4k
  return true;
2305
12.4k
}
2306
2307
/// Perform a purely local form of PRE that looks for diamond
2308
/// control flow patterns and attempts to perform simple PRE at the join point.
2309
475k
bool GVN::performPRE(Function &F) {
2310
475k
  bool Changed = false;
2311
3.56M
  for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
2312
3.56M
    // Nothing to PRE in the entry block.
2313
3.56M
    if (CurrentBlock == &F.getEntryBlock())
2314
475k
      continue;
2315
3.08M
2316
3.08M
    // Don't perform PRE on an EH pad.
2317
3.08M
    if (CurrentBlock->isEHPad())
2318
27.9k
      continue;
2319
3.05M
2320
3.05M
    for (BasicBlock::iterator BI = CurrentBlock->begin(),
2321
3.05M
                              BE = CurrentBlock->end();
2322
18.5M
         BI != BE;) {
2323
15.4M
      Instruction *CurInst = &*BI++;
2324
15.4M
      Changed |= performScalarPRE(CurInst);
2325
15.4M
    }
2326
3.05M
  }
2327
475k
2328
475k
  if (splitCriticalEdges())
2329
4.90k
    Changed = true;
2330
475k
2331
475k
  return Changed;
2332
475k
}
2333
2334
/// Split the critical edge connecting the given two blocks, and return
2335
/// the block inserted to the critical edge.
2336
10.7k
BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2337
10.7k
  BasicBlock *BB =
2338
10.7k
      SplitCriticalEdge(Pred, Succ, CriticalEdgeSplittingOptions(DT));
2339
10.7k
  if (MD)
2340
10.7k
    MD->invalidateCachedPredecessors();
2341
10.7k
  InvalidBlockRPONumbers = true;
2342
10.7k
  return BB;
2343
10.7k
}
2344
2345
/// Split critical edges found during the previous
2346
/// iteration that may enable further optimization.
2347
475k
bool GVN::splitCriticalEdges() {
2348
475k
  if (toSplit.empty())
2349
471k
    return false;
2350
9.60k
  
do 4.89k
{
2351
9.60k
    std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
2352
9.60k
    SplitCriticalEdge(Edge.first, Edge.second,
2353
9.60k
                      CriticalEdgeSplittingOptions(DT));
2354
9.60k
  } while (!toSplit.empty());
2355
4.90k
  if (
MD4.89k
) MD->invalidateCachedPredecessors();
2356
4.89k
  InvalidBlockRPONumbers = true;
2357
4.89k
  return true;
2358
4.89k
}
2359
2360
/// Executes one iteration of GVN
2361
529k
bool GVN::iterateOnFunction(Function &F) {
2362
529k
  cleanupGlobalSets();
2363
529k
2364
529k
  // Top-down walk of the dominator tree
2365
529k
  bool Changed = false;
2366
529k
  // Needed for value numbering with phi construction to work.
2367
529k
  // RPOT walks the graph in its constructor and will not be invalidated during
2368
529k
  // processBlock.
2369
529k
  ReversePostOrderTraversal<Function *> RPOT(&F);
2370
529k
2371
529k
  for (BasicBlock *BB : RPOT)
2372
4.70M
    Changed |= processBlock(BB);
2373
529k
2374
529k
  return Changed;
2375
529k
}
2376
2377
994k
void GVN::cleanupGlobalSets() {
2378
994k
  VN.clear();
2379
994k
  LeaderTable.clear();
2380
994k
  BlockRPONumber.clear();
2381
994k
  TableAllocator.Reset();
2382
994k
  ICF->clear();
2383
994k
  InvalidBlockRPONumbers = true;
2384
994k
}
2385
2386
/// Verify that the specified instruction does not occur in our
2387
/// internal data structures.
2388
0
void GVN::verifyRemoved(const Instruction *Inst) const {
2389
0
  VN.verifyRemoved(Inst);
2390
0
2391
0
  // Walk through the value number scope to make sure the instruction isn't
2392
0
  // ferreted away in it.
2393
0
  for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2394
0
       I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2395
0
    const LeaderTableEntry *Node = &I->second;
2396
0
    assert(Node->Val != Inst && "Inst still in value numbering scope!");
2397
0
2398
0
    while (Node->Next) {
2399
0
      Node = Node->Next;
2400
0
      assert(Node->Val != Inst && "Inst still in value numbering scope!");
2401
0
    }
2402
0
  }
2403
0
}
2404
2405
/// BB is declared dead, which implied other blocks become dead as well. This
2406
/// function is to add all these blocks to "DeadBlocks". For the dead blocks'
2407
/// live successors, update their phi nodes by replacing the operands
2408
/// corresponding to dead blocks with UndefVal.
2409
6.26k
void GVN::addDeadBlock(BasicBlock *BB) {
2410
6.26k
  SmallVector<BasicBlock *, 4> NewDead;
2411
6.26k
  SmallSetVector<BasicBlock *, 4> DF;
2412
6.26k
2413
6.26k
  NewDead.push_back(BB);
2414
12.5k
  while (!NewDead.empty()) {
2415
6.32k
    BasicBlock *D = NewDead.pop_back_val();
2416
6.32k
    if (DeadBlocks.count(D))
2417
0
      continue;
2418
6.32k
2419
6.32k
    // All blocks dominated by D are dead.
2420
6.32k
    SmallVector<BasicBlock *, 8> Dom;
2421
6.32k
    DT->getDescendants(D, Dom);
2422
6.32k
    DeadBlocks.insert(Dom.begin(), Dom.end());
2423
6.32k
2424
6.32k
    // Figure out the dominance-frontier(D).
2425
7.45k
    for (BasicBlock *B : Dom) {
2426
7.85k
      for (BasicBlock *S : successors(B)) {
2427
7.85k
        if (DeadBlocks.count(S))
2428
1.47k
          continue;
2429
6.38k
2430
6.38k
        bool AllPredDead = true;
2431
6.38k
        for (BasicBlock *P : predecessors(S))
2432
12.6k
          if (!DeadBlocks.count(P)) {
2433
6.32k
            AllPredDead = false;
2434
6.32k
            break;
2435
6.32k
          }
2436
6.38k
2437
6.38k
        if (!AllPredDead) {
2438
6.32k
          // S could be proved dead later on. That is why we don't update phi
2439
6.32k
          // operands at this moment.
2440
6.32k
          DF.insert(S);
2441
6.32k
        } else {
2442
60
          // While S is not dominated by D, it is dead by now. This could take
2443
60
          // place if S already have a dead predecessor before D is declared
2444
60
          // dead.
2445
60
          NewDead.push_back(S);
2446
60
        }
2447
6.38k
      }
2448
7.45k
    }
2449
6.32k
  }
2450
6.26k
2451
6.26k
  // For the dead blocks' live successors, update their phi nodes by replacing
2452
6.26k
  // the operands corresponding to dead blocks with UndefVal.
2453
6.26k
  for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2454
12.3k
        I != E; 
I++6.06k
) {
2455
6.06k
    BasicBlock *B = *I;
2456
6.06k
    if (DeadBlocks.count(B))
2457
1
      continue;
2458
6.05k
2459
6.05k
    SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
2460
20.4k
    for (BasicBlock *P : Preds) {
2461
20.4k
      if (!DeadBlocks.count(P))
2462
13.5k
        continue;
2463
6.88k
2464
6.88k
      if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2465
394
        if (BasicBlock *S = splitCriticalEdges(P, B))
2466
339
          DeadBlocks.insert(P = S);
2467
394
      }
2468
6.88k
2469
9.92k
      for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); 
++II3.04k
) {
2470
3.04k
        PHINode &Phi = cast<PHINode>(*II);
2471
3.04k
        Phi.setIncomingValueForBlock(P, UndefValue::get(Phi.getType()));
2472
3.04k
        if (MD)
2473
3.04k
          MD->invalidateCachedPointerInfo(&Phi);
2474
3.04k
      }
2475
6.88k
    }
2476
6.05k
  }
2477
6.26k
}
2478
2479
// If the given branch is recognized as a foldable branch (i.e. conditional
2480
// branch with constant condition), it will perform following analyses and
2481
// transformation.
2482
//  1) If the dead out-coming edge is a critical-edge, split it. Let
2483
//     R be the target of the dead out-coming edge.
2484
//  1) Identify the set of dead blocks implied by the branch's dead outcoming
2485
//     edge. The result of this step will be {X| X is dominated by R}
2486
//  2) Identify those blocks which haves at least one dead predecessor. The
2487
//     result of this step will be dominance-frontier(R).
2488
//  3) Update the PHIs in DF(R) by replacing the operands corresponding to
2489
//     dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2490
//
2491
// Return true iff *NEW* dead code are found.
2492
14.9k
bool GVN::processFoldableCondBr(BranchInst *BI) {
2493
14.9k
  if (!BI || BI->isUnconditional())
2494
0
    return false;
2495
14.9k
2496
14.9k
  // If a branch has two identical successors, we cannot declare either dead.
2497
14.9k
  if (BI->getSuccessor(0) == BI->getSuccessor(1))
2498
12
    return false;
2499
14.9k
2500
14.9k
  ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2501
14.9k
  if (!Cond)
2502
461
    return false;
2503
14.5k
2504
14.5k
  BasicBlock *DeadRoot =
2505
14.5k
      Cond->getZExtValue() ? 
BI->getSuccessor(1)4.84k
:
BI->getSuccessor(0)9.66k
;
2506
14.5k
  if (DeadBlocks.count(DeadRoot))
2507
8.24k
    return false;
2508
6.26k
2509
6.26k
  if (!DeadRoot->getSinglePredecessor())
2510
4.32k
    DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2511
6.26k
2512
6.26k
  addDeadBlock(DeadRoot);
2513
6.26k
  return true;
2514
6.26k
}
2515
2516
// performPRE() will trigger assert if it comes across an instruction without
2517
// associated val-num. As it normally has far more live instructions than dead
2518
// instructions, it makes more sense just to "fabricate" a val-number for the
2519
// dead code than checking if instruction involved is dead or not.
2520
464k
void GVN::assignValNumForDeadCode() {
2521
464k
  for (BasicBlock *BB : DeadBlocks) {
2522
17.3k
    for (Instruction &Inst : *BB) {
2523
17.3k
      unsigned ValNum = VN.lookupOrAdd(&Inst);
2524
17.3k
      addToLeaderTable(ValNum, &Inst, BB);
2525
17.3k
    }
2526
7.79k
  }
2527
464k
}
2528
2529
class llvm::gvn::GVNLegacyPass : public FunctionPass {
2530
public:
2531
  static char ID; // Pass identification, replacement for typeid
2532
2533
  explicit GVNLegacyPass(bool NoMemDepAnalysis = !EnableMemDep)
2534
13.5k
      : FunctionPass(ID), NoMemDepAnalysis(NoMemDepAnalysis) {
2535
13.5k
    initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2536
13.5k
  }
2537
2538
464k
  bool runOnFunction(Function &F) override {
2539
464k
    if (skipFunction(F))
2540
43
      return false;
2541
464k
2542
464k
    auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2543
464k
2544
464k
    return Impl.runImpl(
2545
464k
        F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2546
464k
        getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2547
464k
        getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2548
464k
        getAnalysis<AAResultsWrapperPass>().getAAResults(),
2549
464k
        NoMemDepAnalysis ? 
nullptr1
2550
464k
                : 
&getAnalysis<MemoryDependenceWrapperPass>().getMemDep()464k
,
2551
18.4E
        LIWP ? 
&LIWP->getLoopInfo()464k
: nullptr,
2552
464k
        &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
2553
464k
  }
2554
2555
13.5k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
2556
13.5k
    AU.addRequired<AssumptionCacheTracker>();
2557
13.5k
    AU.addRequired<DominatorTreeWrapperPass>();
2558
13.5k
    AU.addRequired<TargetLibraryInfoWrapperPass>();
2559
13.5k
    if (!NoMemDepAnalysis)
2560
13.5k
      AU.addRequired<MemoryDependenceWrapperPass>();
2561
13.5k
    AU.addRequired<AAResultsWrapperPass>();
2562
13.5k
2563
13.5k
    AU.addPreserved<DominatorTreeWrapperPass>();
2564
13.5k
    AU.addPreserved<GlobalsAAWrapperPass>();
2565
13.5k
    AU.addPreserved<TargetLibraryInfoWrapperPass>();
2566
13.5k
    AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2567
13.5k
  }
2568
2569
private:
2570
  bool NoMemDepAnalysis;
2571
  GVN Impl;
2572
};
2573
2574
char GVNLegacyPass::ID = 0;
2575
2576
48.8k
INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2577
48.8k
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2578
48.8k
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2579
48.8k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2580
48.8k
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2581
48.8k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2582
48.8k
INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2583
48.8k
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
2584
48.8k
INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2585
2586
// The public interface to this file...
2587
13.2k
FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) {
2588
13.2k
  return new GVNLegacyPass(NoMemDepAnalysis);
2589
13.2k
}