Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ControlHeightReduction.cpp - Control Height Reduction -------------===//
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 merges conditional blocks of code and reduces the number of
10
// conditional branches in the hot paths based on profiles.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
15
#include "llvm/ADT/DenseMap.h"
16
#include "llvm/ADT/DenseSet.h"
17
#include "llvm/ADT/SmallVector.h"
18
#include "llvm/ADT/StringSet.h"
19
#include "llvm/Analysis/BlockFrequencyInfo.h"
20
#include "llvm/Analysis/GlobalsModRef.h"
21
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
22
#include "llvm/Analysis/ProfileSummaryInfo.h"
23
#include "llvm/Analysis/RegionInfo.h"
24
#include "llvm/Analysis/RegionIterator.h"
25
#include "llvm/Analysis/ValueTracking.h"
26
#include "llvm/IR/CFG.h"
27
#include "llvm/IR/Dominators.h"
28
#include "llvm/IR/IRBuilder.h"
29
#include "llvm/IR/IntrinsicInst.h"
30
#include "llvm/IR/MDBuilder.h"
31
#include "llvm/IR/PassManager.h"
32
#include "llvm/IR/ProfDataUtils.h"
33
#include "llvm/Support/BranchProbability.h"
34
#include "llvm/Support/CommandLine.h"
35
#include "llvm/Support/MemoryBuffer.h"
36
#include "llvm/Transforms/Utils.h"
37
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38
#include "llvm/Transforms/Utils/Cloning.h"
39
#include "llvm/Transforms/Utils/ValueMapper.h"
40
41
#include <optional>
42
#include <set>
43
#include <sstream>
44
45
using namespace llvm;
46
47
0
#define DEBUG_TYPE "chr"
48
49
0
#define CHR_DEBUG(X) LLVM_DEBUG(X)
50
51
static cl::opt<bool> DisableCHR("disable-chr", cl::init(false), cl::Hidden,
52
                                cl::desc("Disable CHR for all functions"));
53
54
static cl::opt<bool> ForceCHR("force-chr", cl::init(false), cl::Hidden,
55
                              cl::desc("Apply CHR for all functions"));
56
57
static cl::opt<double> CHRBiasThreshold(
58
    "chr-bias-threshold", cl::init(0.99), cl::Hidden,
59
    cl::desc("CHR considers a branch bias greater than this ratio as biased"));
60
61
static cl::opt<unsigned> CHRMergeThreshold(
62
    "chr-merge-threshold", cl::init(2), cl::Hidden,
63
    cl::desc("CHR merges a group of N branches/selects where N >= this value"));
64
65
static cl::opt<std::string> CHRModuleList(
66
    "chr-module-list", cl::init(""), cl::Hidden,
67
    cl::desc("Specify file to retrieve the list of modules to apply CHR to"));
68
69
static cl::opt<std::string> CHRFunctionList(
70
    "chr-function-list", cl::init(""), cl::Hidden,
71
    cl::desc("Specify file to retrieve the list of functions to apply CHR to"));
72
73
static cl::opt<unsigned> CHRDupThreshsold(
74
    "chr-dup-threshold", cl::init(3), cl::Hidden,
75
    cl::desc("Max number of duplications by CHR for a region"));
76
77
static StringSet<> CHRModules;
78
static StringSet<> CHRFunctions;
79
80
0
static void parseCHRFilterFiles() {
81
0
  if (!CHRModuleList.empty()) {
82
0
    auto FileOrErr = MemoryBuffer::getFile(CHRModuleList);
83
0
    if (!FileOrErr) {
84
0
      errs() << "Error: Couldn't read the chr-module-list file " << CHRModuleList << "\n";
85
0
      std::exit(1);
86
0
    }
87
0
    StringRef Buf = FileOrErr->get()->getBuffer();
88
0
    SmallVector<StringRef, 0> Lines;
89
0
    Buf.split(Lines, '\n');
90
0
    for (StringRef Line : Lines) {
91
0
      Line = Line.trim();
92
0
      if (!Line.empty())
93
0
        CHRModules.insert(Line);
94
0
    }
95
0
  }
96
0
  if (!CHRFunctionList.empty()) {
97
0
    auto FileOrErr = MemoryBuffer::getFile(CHRFunctionList);
98
0
    if (!FileOrErr) {
99
0
      errs() << "Error: Couldn't read the chr-function-list file " << CHRFunctionList << "\n";
100
0
      std::exit(1);
101
0
    }
102
0
    StringRef Buf = FileOrErr->get()->getBuffer();
103
0
    SmallVector<StringRef, 0> Lines;
104
0
    Buf.split(Lines, '\n');
105
0
    for (StringRef Line : Lines) {
106
0
      Line = Line.trim();
107
0
      if (!Line.empty())
108
0
        CHRFunctions.insert(Line);
109
0
    }
110
0
  }
111
0
}
112
113
namespace {
114
115
struct CHRStats {
116
0
  CHRStats() = default;
117
0
  void print(raw_ostream &OS) const {
118
0
    OS << "CHRStats: NumBranches " << NumBranches
119
0
       << " NumBranchesDelta " << NumBranchesDelta
120
0
       << " WeightedNumBranchesDelta " << WeightedNumBranchesDelta;
121
0
  }
122
  // The original number of conditional branches / selects
123
  uint64_t NumBranches = 0;
124
  // The decrease of the number of conditional branches / selects in the hot
125
  // paths due to CHR.
126
  uint64_t NumBranchesDelta = 0;
127
  // NumBranchesDelta weighted by the profile count at the scope entry.
128
  uint64_t WeightedNumBranchesDelta = 0;
129
};
130
131
// RegInfo - some properties of a Region.
132
struct RegInfo {
133
  RegInfo() = default;
134
0
  RegInfo(Region *RegionIn) : R(RegionIn) {}
135
  Region *R = nullptr;
136
  bool HasBranch = false;
137
  SmallVector<SelectInst *, 8> Selects;
138
};
139
140
typedef DenseMap<Region *, DenseSet<Instruction *>> HoistStopMapTy;
141
142
// CHRScope - a sequence of regions to CHR together. It corresponds to a
143
// sequence of conditional blocks. It can have subscopes which correspond to
144
// nested conditional blocks. Nested CHRScopes form a tree.
145
class CHRScope {
146
 public:
147
0
  CHRScope(RegInfo RI) : BranchInsertPoint(nullptr) {
148
0
    assert(RI.R && "Null RegionIn");
149
0
    RegInfos.push_back(RI);
150
0
  }
151
152
0
  Region *getParentRegion() {
153
0
    assert(RegInfos.size() > 0 && "Empty CHRScope");
154
0
    Region *Parent = RegInfos[0].R->getParent();
155
0
    assert(Parent && "Unexpected to call this on the top-level region");
156
0
    return Parent;
157
0
  }
158
159
0
  BasicBlock *getEntryBlock() {
160
0
    assert(RegInfos.size() > 0 && "Empty CHRScope");
161
0
    return RegInfos.front().R->getEntry();
162
0
  }
163
164
0
  BasicBlock *getExitBlock() {
165
0
    assert(RegInfos.size() > 0 && "Empty CHRScope");
166
0
    return RegInfos.back().R->getExit();
167
0
  }
168
169
0
  bool appendable(CHRScope *Next) {
170
    // The next scope is appendable only if this scope is directly connected to
171
    // it (which implies it post-dominates this scope) and this scope dominates
172
    // it (no edge to the next scope outside this scope).
173
0
    BasicBlock *NextEntry = Next->getEntryBlock();
174
0
    if (getExitBlock() != NextEntry)
175
      // Not directly connected.
176
0
      return false;
177
0
    Region *LastRegion = RegInfos.back().R;
178
0
    for (BasicBlock *Pred : predecessors(NextEntry))
179
0
      if (!LastRegion->contains(Pred))
180
        // There's an edge going into the entry of the next scope from outside
181
        // of this scope.
182
0
        return false;
183
0
    return true;
184
0
  }
185
186
0
  void append(CHRScope *Next) {
187
0
    assert(RegInfos.size() > 0 && "Empty CHRScope");
188
0
    assert(Next->RegInfos.size() > 0 && "Empty CHRScope");
189
0
    assert(getParentRegion() == Next->getParentRegion() &&
190
0
           "Must be siblings");
191
0
    assert(getExitBlock() == Next->getEntryBlock() &&
192
0
           "Must be adjacent");
193
0
    RegInfos.append(Next->RegInfos.begin(), Next->RegInfos.end());
194
0
    Subs.append(Next->Subs.begin(), Next->Subs.end());
195
0
  }
196
197
0
  void addSub(CHRScope *SubIn) {
198
0
#ifndef NDEBUG
199
0
    bool IsChild = false;
200
0
    for (RegInfo &RI : RegInfos)
201
0
      if (RI.R == SubIn->getParentRegion()) {
202
0
        IsChild = true;
203
0
        break;
204
0
      }
205
0
    assert(IsChild && "Must be a child");
206
0
#endif
207
0
    Subs.push_back(SubIn);
208
0
  }
209
210
  // Split this scope at the boundary region into two, which will belong to the
211
  // tail and returns the tail.
212
0
  CHRScope *split(Region *Boundary) {
213
0
    assert(Boundary && "Boundary null");
214
0
    assert(RegInfos.begin()->R != Boundary &&
215
0
           "Can't be split at beginning");
216
0
    auto BoundaryIt = llvm::find_if(
217
0
        RegInfos, [&Boundary](const RegInfo &RI) { return Boundary == RI.R; });
218
0
    if (BoundaryIt == RegInfos.end())
219
0
      return nullptr;
220
0
    ArrayRef<RegInfo> TailRegInfos(BoundaryIt, RegInfos.end());
221
0
    DenseSet<Region *> TailRegionSet;
222
0
    for (const RegInfo &RI : TailRegInfos)
223
0
      TailRegionSet.insert(RI.R);
224
225
0
    auto TailIt =
226
0
        std::stable_partition(Subs.begin(), Subs.end(), [&](CHRScope *Sub) {
227
0
          assert(Sub && "null Sub");
228
0
          Region *Parent = Sub->getParentRegion();
229
0
          if (TailRegionSet.count(Parent))
230
0
            return false;
231
232
0
          assert(llvm::any_of(
233
0
                     RegInfos,
234
0
                     [&Parent](const RegInfo &RI) { return Parent == RI.R; }) &&
235
0
                 "Must be in head");
236
0
          return true;
237
0
        });
238
0
    ArrayRef<CHRScope *> TailSubs(TailIt, Subs.end());
239
240
0
    assert(HoistStopMap.empty() && "MapHoistStops must be empty");
241
0
    auto *Scope = new CHRScope(TailRegInfos, TailSubs);
242
0
    RegInfos.erase(BoundaryIt, RegInfos.end());
243
0
    Subs.erase(TailIt, Subs.end());
244
0
    return Scope;
245
0
  }
246
247
0
  bool contains(Instruction *I) const {
248
0
    BasicBlock *Parent = I->getParent();
249
0
    for (const RegInfo &RI : RegInfos)
250
0
      if (RI.R->contains(Parent))
251
0
        return true;
252
0
    return false;
253
0
  }
254
255
  void print(raw_ostream &OS) const;
256
257
  SmallVector<RegInfo, 8> RegInfos; // Regions that belong to this scope
258
  SmallVector<CHRScope *, 8> Subs;  // Subscopes.
259
260
  // The instruction at which to insert the CHR conditional branch (and hoist
261
  // the dependent condition values).
262
  Instruction *BranchInsertPoint;
263
264
  // True-biased and false-biased regions (conditional blocks),
265
  // respectively. Used only for the outermost scope and includes regions in
266
  // subscopes. The rest are unbiased.
267
  DenseSet<Region *> TrueBiasedRegions;
268
  DenseSet<Region *> FalseBiasedRegions;
269
  // Among the biased regions, the regions that get CHRed.
270
  SmallVector<RegInfo, 8> CHRRegions;
271
272
  // True-biased and false-biased selects, respectively. Used only for the
273
  // outermost scope and includes ones in subscopes.
274
  DenseSet<SelectInst *> TrueBiasedSelects;
275
  DenseSet<SelectInst *> FalseBiasedSelects;
276
277
  // Map from one of the above regions to the instructions to stop
278
  // hoisting instructions at through use-def chains.
279
  HoistStopMapTy HoistStopMap;
280
281
 private:
282
   CHRScope(ArrayRef<RegInfo> RegInfosIn, ArrayRef<CHRScope *> SubsIn)
283
       : RegInfos(RegInfosIn.begin(), RegInfosIn.end()),
284
0
         Subs(SubsIn.begin(), SubsIn.end()), BranchInsertPoint(nullptr) {}
285
};
286
287
class CHR {
288
 public:
289
  CHR(Function &Fin, BlockFrequencyInfo &BFIin, DominatorTree &DTin,
290
      ProfileSummaryInfo &PSIin, RegionInfo &RIin,
291
      OptimizationRemarkEmitter &OREin)
292
0
      : F(Fin), BFI(BFIin), DT(DTin), PSI(PSIin), RI(RIin), ORE(OREin) {}
293
294
0
  ~CHR() {
295
0
    for (CHRScope *Scope : Scopes) {
296
0
      delete Scope;
297
0
    }
298
0
  }
299
300
  bool run();
301
302
 private:
303
  // See the comments in CHR::run() for the high level flow of the algorithm and
304
  // what the following functions do.
305
306
0
  void findScopes(SmallVectorImpl<CHRScope *> &Output) {
307
0
    Region *R = RI.getTopLevelRegion();
308
0
    if (CHRScope *Scope = findScopes(R, nullptr, nullptr, Output)) {
309
0
      Output.push_back(Scope);
310
0
    }
311
0
  }
312
  CHRScope *findScopes(Region *R, Region *NextRegion, Region *ParentRegion,
313
                        SmallVectorImpl<CHRScope *> &Scopes);
314
  CHRScope *findScope(Region *R);
315
  void checkScopeHoistable(CHRScope *Scope);
316
317
  void splitScopes(SmallVectorImpl<CHRScope *> &Input,
318
                   SmallVectorImpl<CHRScope *> &Output);
319
  SmallVector<CHRScope *, 8> splitScope(CHRScope *Scope,
320
                                        CHRScope *Outer,
321
                                        DenseSet<Value *> *OuterConditionValues,
322
                                        Instruction *OuterInsertPoint,
323
                                        SmallVectorImpl<CHRScope *> &Output,
324
                                        DenseSet<Instruction *> &Unhoistables);
325
326
  void classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes);
327
  void classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope);
328
329
  void filterScopes(SmallVectorImpl<CHRScope *> &Input,
330
                    SmallVectorImpl<CHRScope *> &Output);
331
332
  void setCHRRegions(SmallVectorImpl<CHRScope *> &Input,
333
                     SmallVectorImpl<CHRScope *> &Output);
334
  void setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope);
335
336
  void sortScopes(SmallVectorImpl<CHRScope *> &Input,
337
                  SmallVectorImpl<CHRScope *> &Output);
338
339
  void transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes);
340
  void transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs);
341
  void cloneScopeBlocks(CHRScope *Scope,
342
                        BasicBlock *PreEntryBlock,
343
                        BasicBlock *ExitBlock,
344
                        Region *LastRegion,
345
                        ValueToValueMapTy &VMap);
346
  BranchInst *createMergedBranch(BasicBlock *PreEntryBlock,
347
                                 BasicBlock *EntryBlock,
348
                                 BasicBlock *NewEntryBlock,
349
                                 ValueToValueMapTy &VMap);
350
  void fixupBranchesAndSelects(CHRScope *Scope, BasicBlock *PreEntryBlock,
351
                               BranchInst *MergedBR, uint64_t ProfileCount);
352
  void fixupBranch(Region *R, CHRScope *Scope, IRBuilder<> &IRB,
353
                   Value *&MergedCondition, BranchProbability &CHRBranchBias);
354
  void fixupSelect(SelectInst *SI, CHRScope *Scope, IRBuilder<> &IRB,
355
                   Value *&MergedCondition, BranchProbability &CHRBranchBias);
356
  void addToMergedCondition(bool IsTrueBiased, Value *Cond,
357
                            Instruction *BranchOrSelect, CHRScope *Scope,
358
                            IRBuilder<> &IRB, Value *&MergedCondition);
359
0
  unsigned getRegionDuplicationCount(const Region *R) {
360
0
    unsigned Count = 0;
361
    // Find out how many times region R is cloned. Note that if the parent
362
    // of R is cloned, R is also cloned, but R's clone count is not updated
363
    // from the clone of the parent. We need to accumlate all the counts
364
    // from the ancestors to get the clone count.
365
0
    while (R) {
366
0
      Count += DuplicationCount[R];
367
0
      R = R->getParent();
368
0
    }
369
0
    return Count;
370
0
  }
371
372
  Function &F;
373
  BlockFrequencyInfo &BFI;
374
  DominatorTree &DT;
375
  ProfileSummaryInfo &PSI;
376
  RegionInfo &RI;
377
  OptimizationRemarkEmitter &ORE;
378
  CHRStats Stats;
379
380
  // All the true-biased regions in the function
381
  DenseSet<Region *> TrueBiasedRegionsGlobal;
382
  // All the false-biased regions in the function
383
  DenseSet<Region *> FalseBiasedRegionsGlobal;
384
  // All the true-biased selects in the function
385
  DenseSet<SelectInst *> TrueBiasedSelectsGlobal;
386
  // All the false-biased selects in the function
387
  DenseSet<SelectInst *> FalseBiasedSelectsGlobal;
388
  // A map from biased regions to their branch bias
389
  DenseMap<Region *, BranchProbability> BranchBiasMap;
390
  // A map from biased selects to their branch bias
391
  DenseMap<SelectInst *, BranchProbability> SelectBiasMap;
392
  // All the scopes.
393
  DenseSet<CHRScope *> Scopes;
394
  // This maps records how many times this region is cloned.
395
  DenseMap<const Region *, unsigned> DuplicationCount;
396
};
397
398
} // end anonymous namespace
399
400
static inline
401
raw_ostream LLVM_ATTRIBUTE_UNUSED &operator<<(raw_ostream &OS,
402
0
                                              const CHRStats &Stats) {
403
0
  Stats.print(OS);
404
0
  return OS;
405
0
}
406
407
static inline
408
0
raw_ostream &operator<<(raw_ostream &OS, const CHRScope &Scope) {
409
0
  Scope.print(OS);
410
0
  return OS;
411
0
}
412
413
0
static bool shouldApply(Function &F, ProfileSummaryInfo &PSI) {
414
0
  if (DisableCHR)
415
0
    return false;
416
417
0
  if (ForceCHR)
418
0
    return true;
419
420
0
  if (!CHRModuleList.empty() || !CHRFunctionList.empty()) {
421
0
    if (CHRModules.count(F.getParent()->getName()))
422
0
      return true;
423
0
    return CHRFunctions.count(F.getName());
424
0
  }
425
426
0
  return PSI.isFunctionEntryHot(&F);
427
0
}
428
429
static void LLVM_ATTRIBUTE_UNUSED dumpIR(Function &F, const char *Label,
430
0
                                         CHRStats *Stats) {
431
0
  StringRef FuncName = F.getName();
432
0
  StringRef ModuleName = F.getParent()->getName();
433
0
  (void)(FuncName); // Unused in release build.
434
0
  (void)(ModuleName); // Unused in release build.
435
0
  CHR_DEBUG(dbgs() << "CHR IR dump " << Label << " " << ModuleName << " "
436
0
            << FuncName);
437
0
  if (Stats)
438
0
    CHR_DEBUG(dbgs() << " " << *Stats);
439
0
  CHR_DEBUG(dbgs() << "\n");
440
0
  CHR_DEBUG(F.dump());
441
0
}
442
443
0
void CHRScope::print(raw_ostream &OS) const {
444
0
  assert(RegInfos.size() > 0 && "Empty CHRScope");
445
0
  OS << "CHRScope[";
446
0
  OS << RegInfos.size() << ", Regions[";
447
0
  for (const RegInfo &RI : RegInfos) {
448
0
    OS << RI.R->getNameStr();
449
0
    if (RI.HasBranch)
450
0
      OS << " B";
451
0
    if (RI.Selects.size() > 0)
452
0
      OS << " S" << RI.Selects.size();
453
0
    OS << ", ";
454
0
  }
455
0
  if (RegInfos[0].R->getParent()) {
456
0
    OS << "], Parent " << RegInfos[0].R->getParent()->getNameStr();
457
0
  } else {
458
    // top level region
459
0
    OS << "]";
460
0
  }
461
0
  OS << ", Subs[";
462
0
  for (CHRScope *Sub : Subs) {
463
0
    OS << *Sub << ", ";
464
0
  }
465
0
  OS << "]]";
466
0
}
467
468
// Return true if the given instruction type can be hoisted by CHR.
469
0
static bool isHoistableInstructionType(Instruction *I) {
470
0
  return isa<BinaryOperator>(I) || isa<CastInst>(I) || isa<SelectInst>(I) ||
471
0
      isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
472
0
      isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
473
0
      isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
474
0
      isa<InsertValueInst>(I);
475
0
}
476
477
// Return true if the given instruction can be hoisted by CHR.
478
0
static bool isHoistable(Instruction *I, DominatorTree &DT) {
479
0
  if (!isHoistableInstructionType(I))
480
0
    return false;
481
0
  return isSafeToSpeculativelyExecute(I, nullptr, nullptr, &DT);
482
0
}
483
484
// Recursively traverse the use-def chains of the given value and return a set
485
// of the unhoistable base values defined within the scope (excluding the
486
// first-region entry block) or the (hoistable or unhoistable) base values that
487
// are defined outside (including the first-region entry block) of the
488
// scope. The returned set doesn't include constants.
489
static const std::set<Value *> &
490
getBaseValues(Value *V, DominatorTree &DT,
491
0
              DenseMap<Value *, std::set<Value *>> &Visited) {
492
0
  auto It = Visited.find(V);
493
0
  if (It != Visited.end()) {
494
0
    return It->second;
495
0
  }
496
0
  std::set<Value *> Result;
497
0
  if (auto *I = dyn_cast<Instruction>(V)) {
498
    // We don't stop at a block that's not in the Scope because we would miss
499
    // some instructions that are based on the same base values if we stop
500
    // there.
501
0
    if (!isHoistable(I, DT)) {
502
0
      Result.insert(I);
503
0
      return Visited.insert(std::make_pair(V, std::move(Result))).first->second;
504
0
    }
505
    // I is hoistable above the Scope.
506
0
    for (Value *Op : I->operands()) {
507
0
      const std::set<Value *> &OpResult = getBaseValues(Op, DT, Visited);
508
0
      Result.insert(OpResult.begin(), OpResult.end());
509
0
    }
510
0
    return Visited.insert(std::make_pair(V, std::move(Result))).first->second;
511
0
  }
512
0
  if (isa<Argument>(V)) {
513
0
    Result.insert(V);
514
0
  }
515
  // We don't include others like constants because those won't lead to any
516
  // chance of folding of conditions (eg two bit checks merged into one check)
517
  // after CHR.
518
0
  return Visited.insert(std::make_pair(V, std::move(Result))).first->second;
519
0
}
520
521
// Return true if V is already hoisted or can be hoisted (along with its
522
// operands) above the insert point. When it returns true and HoistStops is
523
// non-null, the instructions to stop hoisting at through the use-def chains are
524
// inserted into HoistStops.
525
static bool
526
checkHoistValue(Value *V, Instruction *InsertPoint, DominatorTree &DT,
527
                DenseSet<Instruction *> &Unhoistables,
528
                DenseSet<Instruction *> *HoistStops,
529
0
                DenseMap<Instruction *, bool> &Visited) {
530
0
  assert(InsertPoint && "Null InsertPoint");
531
0
  if (auto *I = dyn_cast<Instruction>(V)) {
532
0
    auto It = Visited.find(I);
533
0
    if (It != Visited.end()) {
534
0
      return It->second;
535
0
    }
536
0
    assert(DT.getNode(I->getParent()) && "DT must contain I's parent block");
537
0
    assert(DT.getNode(InsertPoint->getParent()) && "DT must contain Destination");
538
0
    if (Unhoistables.count(I)) {
539
      // Don't hoist if they are not to be hoisted.
540
0
      Visited[I] = false;
541
0
      return false;
542
0
    }
543
0
    if (DT.dominates(I, InsertPoint)) {
544
      // We are already above the insert point. Stop here.
545
0
      if (HoistStops)
546
0
        HoistStops->insert(I);
547
0
      Visited[I] = true;
548
0
      return true;
549
0
    }
550
    // We aren't not above the insert point, check if we can hoist it above the
551
    // insert point.
552
0
    if (isHoistable(I, DT)) {
553
      // Check operands first.
554
0
      DenseSet<Instruction *> OpsHoistStops;
555
0
      bool AllOpsHoisted = true;
556
0
      for (Value *Op : I->operands()) {
557
0
        if (!checkHoistValue(Op, InsertPoint, DT, Unhoistables, &OpsHoistStops,
558
0
                             Visited)) {
559
0
          AllOpsHoisted = false;
560
0
          break;
561
0
        }
562
0
      }
563
0
      if (AllOpsHoisted) {
564
0
        CHR_DEBUG(dbgs() << "checkHoistValue " << *I << "\n");
565
0
        if (HoistStops)
566
0
          HoistStops->insert(OpsHoistStops.begin(), OpsHoistStops.end());
567
0
        Visited[I] = true;
568
0
        return true;
569
0
      }
570
0
    }
571
0
    Visited[I] = false;
572
0
    return false;
573
0
  }
574
  // Non-instructions are considered hoistable.
575
0
  return true;
576
0
}
577
578
// Constructs the true and false branch probabilities if the the instruction has
579
// valid branch weights. Returns true when this was successful, false otherwise.
580
static bool extractBranchProbabilities(Instruction *I,
581
                                       BranchProbability &TrueProb,
582
0
                                       BranchProbability &FalseProb) {
583
0
  uint64_t TrueWeight;
584
0
  uint64_t FalseWeight;
585
0
  if (!extractBranchWeights(*I, TrueWeight, FalseWeight))
586
0
    return false;
587
0
  uint64_t SumWeight = TrueWeight + FalseWeight;
588
589
0
  assert(SumWeight >= TrueWeight && SumWeight >= FalseWeight &&
590
0
         "Overflow calculating branch probabilities.");
591
592
  // Guard against 0-to-0 branch weights to avoid a division-by-zero crash.
593
0
  if (SumWeight == 0)
594
0
    return false;
595
596
0
  TrueProb = BranchProbability::getBranchProbability(TrueWeight, SumWeight);
597
0
  FalseProb = BranchProbability::getBranchProbability(FalseWeight, SumWeight);
598
0
  return true;
599
0
}
600
601
0
static BranchProbability getCHRBiasThreshold() {
602
0
  return BranchProbability::getBranchProbability(
603
0
      static_cast<uint64_t>(CHRBiasThreshold * 1000000), 1000000);
604
0
}
605
606
// A helper for CheckBiasedBranch and CheckBiasedSelect. If TrueProb >=
607
// CHRBiasThreshold, put Key into TrueSet and return true. If FalseProb >=
608
// CHRBiasThreshold, put Key into FalseSet and return true. Otherwise, return
609
// false.
610
template <typename K, typename S, typename M>
611
static bool checkBias(K *Key, BranchProbability TrueProb,
612
                      BranchProbability FalseProb, S &TrueSet, S &FalseSet,
613
0
                      M &BiasMap) {
614
0
  BranchProbability Threshold = getCHRBiasThreshold();
615
0
  if (TrueProb >= Threshold) {
616
0
    TrueSet.insert(Key);
617
0
    BiasMap[Key] = TrueProb;
618
0
    return true;
619
0
  } else if (FalseProb >= Threshold) {
620
0
    FalseSet.insert(Key);
621
0
    BiasMap[Key] = FalseProb;
622
0
    return true;
623
0
  }
624
0
  return false;
625
0
}
Unexecuted instantiation: ControlHeightReduction.cpp:bool checkBias<llvm::Region, llvm::DenseSet<llvm::Region*, llvm::DenseMapInfo<llvm::Region*, void> >, llvm::DenseMap<llvm::Region*, llvm::BranchProbability, llvm::DenseMapInfo<llvm::Region*, void>, llvm::detail::DenseMapPair<llvm::Region*, llvm::BranchProbability> > >(llvm::Region*, llvm::BranchProbability, llvm::BranchProbability, llvm::DenseSet<llvm::Region*, llvm::DenseMapInfo<llvm::Region*, void> >&, llvm::DenseSet<llvm::Region*, llvm::DenseMapInfo<llvm::Region*, void> >&, llvm::DenseMap<llvm::Region*, llvm::BranchProbability, llvm::DenseMapInfo<llvm::Region*, void>, llvm::detail::DenseMapPair<llvm::Region*, llvm::BranchProbability> >&)
Unexecuted instantiation: ControlHeightReduction.cpp:bool checkBias<llvm::SelectInst, llvm::DenseSet<llvm::SelectInst*, llvm::DenseMapInfo<llvm::SelectInst*, void> >, llvm::DenseMap<llvm::SelectInst*, llvm::BranchProbability, llvm::DenseMapInfo<llvm::SelectInst*, void>, llvm::detail::DenseMapPair<llvm::SelectInst*, llvm::BranchProbability> > >(llvm::SelectInst*, llvm::BranchProbability, llvm::BranchProbability, llvm::DenseSet<llvm::SelectInst*, llvm::DenseMapInfo<llvm::SelectInst*, void> >&, llvm::DenseSet<llvm::SelectInst*, llvm::DenseMapInfo<llvm::SelectInst*, void> >&, llvm::DenseMap<llvm::SelectInst*, llvm::BranchProbability, llvm::DenseMapInfo<llvm::SelectInst*, void>, llvm::detail::DenseMapPair<llvm::SelectInst*, llvm::BranchProbability> >&)
626
627
// Returns true and insert a region into the right biased set and the map if the
628
// branch of the region is biased.
629
static bool checkBiasedBranch(BranchInst *BI, Region *R,
630
                              DenseSet<Region *> &TrueBiasedRegionsGlobal,
631
                              DenseSet<Region *> &FalseBiasedRegionsGlobal,
632
0
                              DenseMap<Region *, BranchProbability> &BranchBiasMap) {
633
0
  if (!BI->isConditional())
634
0
    return false;
635
0
  BranchProbability ThenProb, ElseProb;
636
0
  if (!extractBranchProbabilities(BI, ThenProb, ElseProb))
637
0
    return false;
638
0
  BasicBlock *IfThen = BI->getSuccessor(0);
639
0
  BasicBlock *IfElse = BI->getSuccessor(1);
640
0
  assert((IfThen == R->getExit() || IfElse == R->getExit()) &&
641
0
         IfThen != IfElse &&
642
0
         "Invariant from findScopes");
643
0
  if (IfThen == R->getExit()) {
644
    // Swap them so that IfThen/ThenProb means going into the conditional code
645
    // and IfElse/ElseProb means skipping it.
646
0
    std::swap(IfThen, IfElse);
647
0
    std::swap(ThenProb, ElseProb);
648
0
  }
649
0
  CHR_DEBUG(dbgs() << "BI " << *BI << " ");
650
0
  CHR_DEBUG(dbgs() << "ThenProb " << ThenProb << " ");
651
0
  CHR_DEBUG(dbgs() << "ElseProb " << ElseProb << "\n");
652
0
  return checkBias(R, ThenProb, ElseProb,
653
0
                   TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal,
654
0
                   BranchBiasMap);
655
0
}
656
657
// Returns true and insert a select into the right biased set and the map if the
658
// select is biased.
659
static bool checkBiasedSelect(
660
    SelectInst *SI, Region *R,
661
    DenseSet<SelectInst *> &TrueBiasedSelectsGlobal,
662
    DenseSet<SelectInst *> &FalseBiasedSelectsGlobal,
663
0
    DenseMap<SelectInst *, BranchProbability> &SelectBiasMap) {
664
0
  BranchProbability TrueProb, FalseProb;
665
0
  if (!extractBranchProbabilities(SI, TrueProb, FalseProb))
666
0
    return false;
667
0
  CHR_DEBUG(dbgs() << "SI " << *SI << " ");
668
0
  CHR_DEBUG(dbgs() << "TrueProb " << TrueProb << " ");
669
0
  CHR_DEBUG(dbgs() << "FalseProb " << FalseProb << "\n");
670
0
  return checkBias(SI, TrueProb, FalseProb,
671
0
                   TrueBiasedSelectsGlobal, FalseBiasedSelectsGlobal,
672
0
                   SelectBiasMap);
673
0
}
674
675
// Returns the instruction at which to hoist the dependent condition values and
676
// insert the CHR branch for a region. This is the terminator branch in the
677
// entry block or the first select in the entry block, if any.
678
0
static Instruction* getBranchInsertPoint(RegInfo &RI) {
679
0
  Region *R = RI.R;
680
0
  BasicBlock *EntryBB = R->getEntry();
681
  // The hoist point is by default the terminator of the entry block, which is
682
  // the same as the branch instruction if RI.HasBranch is true.
683
0
  Instruction *HoistPoint = EntryBB->getTerminator();
684
0
  for (SelectInst *SI : RI.Selects) {
685
0
    if (SI->getParent() == EntryBB) {
686
      // Pick the first select in Selects in the entry block.  Note Selects is
687
      // sorted in the instruction order within a block (asserted below).
688
0
      HoistPoint = SI;
689
0
      break;
690
0
    }
691
0
  }
692
0
  assert(HoistPoint && "Null HoistPoint");
693
0
#ifndef NDEBUG
694
  // Check that HoistPoint is the first one in Selects in the entry block,
695
  // if any.
696
0
  DenseSet<Instruction *> EntryBlockSelectSet;
697
0
  for (SelectInst *SI : RI.Selects) {
698
0
    if (SI->getParent() == EntryBB) {
699
0
      EntryBlockSelectSet.insert(SI);
700
0
    }
701
0
  }
702
0
  for (Instruction &I : *EntryBB) {
703
0
    if (EntryBlockSelectSet.contains(&I)) {
704
0
      assert(&I == HoistPoint &&
705
0
             "HoistPoint must be the first one in Selects");
706
0
      break;
707
0
    }
708
0
  }
709
0
#endif
710
0
  return HoistPoint;
711
0
}
712
713
// Find a CHR scope in the given region.
714
0
CHRScope * CHR::findScope(Region *R) {
715
0
  CHRScope *Result = nullptr;
716
0
  BasicBlock *Entry = R->getEntry();
717
0
  BasicBlock *Exit = R->getExit();  // null if top level.
718
0
  assert(Entry && "Entry must not be null");
719
0
  assert((Exit == nullptr) == (R->isTopLevelRegion()) &&
720
0
         "Only top level region has a null exit");
721
0
  if (Entry)
722
0
    CHR_DEBUG(dbgs() << "Entry " << Entry->getName() << "\n");
723
0
  else
724
0
    CHR_DEBUG(dbgs() << "Entry null\n");
725
0
  if (Exit)
726
0
    CHR_DEBUG(dbgs() << "Exit " << Exit->getName() << "\n");
727
0
  else
728
0
    CHR_DEBUG(dbgs() << "Exit null\n");
729
  // Exclude cases where Entry is part of a subregion (hence it doesn't belong
730
  // to this region).
731
0
  bool EntryInSubregion = RI.getRegionFor(Entry) != R;
732
0
  if (EntryInSubregion)
733
0
    return nullptr;
734
  // Exclude loops
735
0
  for (BasicBlock *Pred : predecessors(Entry))
736
0
    if (R->contains(Pred))
737
0
      return nullptr;
738
  // If any of the basic blocks have address taken, we must skip this region
739
  // because we cannot clone basic blocks that have address taken.
740
0
  for (BasicBlock *BB : R->blocks()) {
741
0
    if (BB->hasAddressTaken())
742
0
      return nullptr;
743
    // If we encounter llvm.coro.id, skip this region because if the basic block
744
    // is cloned, we end up inserting a token type PHI node to the block with
745
    // llvm.coro.begin.
746
    // FIXME: This could lead to less optimal codegen, because the region is
747
    // excluded, it can prevent CHR from merging adjacent regions into bigger
748
    // scope and hoisting more branches.
749
0
    for (Instruction &I : *BB)
750
0
      if (auto *II = dyn_cast<IntrinsicInst>(&I))
751
0
        if (II->getIntrinsicID() == Intrinsic::coro_id)
752
0
          return nullptr;
753
0
  }
754
755
0
  if (Exit) {
756
    // Try to find an if-then block (check if R is an if-then).
757
    // if (cond) {
758
    //  ...
759
    // }
760
0
    auto *BI = dyn_cast<BranchInst>(Entry->getTerminator());
761
0
    if (BI)
762
0
      CHR_DEBUG(dbgs() << "BI.isConditional " << BI->isConditional() << "\n");
763
0
    else
764
0
      CHR_DEBUG(dbgs() << "BI null\n");
765
0
    if (BI && BI->isConditional()) {
766
0
      BasicBlock *S0 = BI->getSuccessor(0);
767
0
      BasicBlock *S1 = BI->getSuccessor(1);
768
0
      CHR_DEBUG(dbgs() << "S0 " << S0->getName() << "\n");
769
0
      CHR_DEBUG(dbgs() << "S1 " << S1->getName() << "\n");
770
0
      if (S0 != S1 && (S0 == Exit || S1 == Exit)) {
771
0
        RegInfo RI(R);
772
0
        RI.HasBranch = checkBiasedBranch(
773
0
            BI, R, TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal,
774
0
            BranchBiasMap);
775
0
        Result = new CHRScope(RI);
776
0
        Scopes.insert(Result);
777
0
        CHR_DEBUG(dbgs() << "Found a region with a branch\n");
778
0
        ++Stats.NumBranches;
779
0
        if (!RI.HasBranch) {
780
0
          ORE.emit([&]() {
781
0
            return OptimizationRemarkMissed(DEBUG_TYPE, "BranchNotBiased", BI)
782
0
                << "Branch not biased";
783
0
          });
784
0
        }
785
0
      }
786
0
    }
787
0
  }
788
0
  {
789
    // Try to look for selects in the direct child blocks (as opposed to in
790
    // subregions) of R.
791
    // ...
792
    // if (..) { // Some subregion
793
    //   ...
794
    // }
795
    // if (..) { // Some subregion
796
    //   ...
797
    // }
798
    // ...
799
    // a = cond ? b : c;
800
    // ...
801
0
    SmallVector<SelectInst *, 8> Selects;
802
0
    for (RegionNode *E : R->elements()) {
803
0
      if (E->isSubRegion())
804
0
        continue;
805
      // This returns the basic block of E if E is a direct child of R (not a
806
      // subregion.)
807
0
      BasicBlock *BB = E->getEntry();
808
      // Need to push in the order to make it easier to find the first Select
809
      // later.
810
0
      for (Instruction &I : *BB) {
811
0
        if (auto *SI = dyn_cast<SelectInst>(&I)) {
812
0
          Selects.push_back(SI);
813
0
          ++Stats.NumBranches;
814
0
        }
815
0
      }
816
0
    }
817
0
    if (Selects.size() > 0) {
818
0
      auto AddSelects = [&](RegInfo &RI) {
819
0
        for (auto *SI : Selects)
820
0
          if (checkBiasedSelect(SI, RI.R,
821
0
                                TrueBiasedSelectsGlobal,
822
0
                                FalseBiasedSelectsGlobal,
823
0
                                SelectBiasMap))
824
0
            RI.Selects.push_back(SI);
825
0
          else
826
0
            ORE.emit([&]() {
827
0
              return OptimizationRemarkMissed(DEBUG_TYPE, "SelectNotBiased", SI)
828
0
                  << "Select not biased";
829
0
            });
830
0
      };
831
0
      if (!Result) {
832
0
        CHR_DEBUG(dbgs() << "Found a select-only region\n");
833
0
        RegInfo RI(R);
834
0
        AddSelects(RI);
835
0
        Result = new CHRScope(RI);
836
0
        Scopes.insert(Result);
837
0
      } else {
838
0
        CHR_DEBUG(dbgs() << "Found select(s) in a region with a branch\n");
839
0
        AddSelects(Result->RegInfos[0]);
840
0
      }
841
0
    }
842
0
  }
843
844
0
  if (Result) {
845
0
    checkScopeHoistable(Result);
846
0
  }
847
0
  return Result;
848
0
}
849
850
// Check that any of the branch and the selects in the region could be
851
// hoisted above the the CHR branch insert point (the most dominating of
852
// them, either the branch (at the end of the first block) or the first
853
// select in the first block). If the branch can't be hoisted, drop the
854
// selects in the first blocks.
855
//
856
// For example, for the following scope/region with selects, we want to insert
857
// the merged branch right before the first select in the first/entry block by
858
// hoisting c1, c2, c3, and c4.
859
//
860
// // Branch insert point here.
861
// a = c1 ? b : c; // Select 1
862
// d = c2 ? e : f; // Select 2
863
// if (c3) { // Branch
864
//   ...
865
//   c4 = foo() // A call.
866
//   g = c4 ? h : i; // Select 3
867
// }
868
//
869
// But suppose we can't hoist c4 because it's dependent on the preceding
870
// call. Then, we drop Select 3. Furthermore, if we can't hoist c2, we also drop
871
// Select 2. If we can't hoist c3, we drop Selects 1 & 2.
872
0
void CHR::checkScopeHoistable(CHRScope *Scope) {
873
0
  RegInfo &RI = Scope->RegInfos[0];
874
0
  Region *R = RI.R;
875
0
  BasicBlock *EntryBB = R->getEntry();
876
0
  auto *Branch = RI.HasBranch ?
877
0
                 cast<BranchInst>(EntryBB->getTerminator()) : nullptr;
878
0
  SmallVector<SelectInst *, 8> &Selects = RI.Selects;
879
0
  if (RI.HasBranch || !Selects.empty()) {
880
0
    Instruction *InsertPoint = getBranchInsertPoint(RI);
881
0
    CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");
882
    // Avoid a data dependence from a select or a branch to a(nother)
883
    // select. Note no instruction can't data-depend on a branch (a branch
884
    // instruction doesn't produce a value).
885
0
    DenseSet<Instruction *> Unhoistables;
886
    // Initialize Unhoistables with the selects.
887
0
    for (SelectInst *SI : Selects) {
888
0
      Unhoistables.insert(SI);
889
0
    }
890
    // Remove Selects that can't be hoisted.
891
0
    for (auto it = Selects.begin(); it != Selects.end(); ) {
892
0
      SelectInst *SI = *it;
893
0
      if (SI == InsertPoint) {
894
0
        ++it;
895
0
        continue;
896
0
      }
897
0
      DenseMap<Instruction *, bool> Visited;
898
0
      bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint,
899
0
                                         DT, Unhoistables, nullptr, Visited);
900
0
      if (!IsHoistable) {
901
0
        CHR_DEBUG(dbgs() << "Dropping select " << *SI << "\n");
902
0
        ORE.emit([&]() {
903
0
          return OptimizationRemarkMissed(DEBUG_TYPE,
904
0
                                          "DropUnhoistableSelect", SI)
905
0
              << "Dropped unhoistable select";
906
0
        });
907
0
        it = Selects.erase(it);
908
        // Since we are dropping the select here, we also drop it from
909
        // Unhoistables.
910
0
        Unhoistables.erase(SI);
911
0
      } else
912
0
        ++it;
913
0
    }
914
    // Update InsertPoint after potentially removing selects.
915
0
    InsertPoint = getBranchInsertPoint(RI);
916
0
    CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");
917
0
    if (RI.HasBranch && InsertPoint != Branch) {
918
0
      DenseMap<Instruction *, bool> Visited;
919
0
      bool IsHoistable = checkHoistValue(Branch->getCondition(), InsertPoint,
920
0
                                         DT, Unhoistables, nullptr, Visited);
921
0
      if (!IsHoistable) {
922
        // If the branch isn't hoistable, drop the selects in the entry
923
        // block, preferring the branch, which makes the branch the hoist
924
        // point.
925
0
        assert(InsertPoint != Branch && "Branch must not be the hoist point");
926
0
        CHR_DEBUG(dbgs() << "Dropping selects in entry block \n");
927
0
        CHR_DEBUG(
928
0
            for (SelectInst *SI : Selects) {
929
0
              dbgs() << "SI " << *SI << "\n";
930
0
            });
931
0
        for (SelectInst *SI : Selects) {
932
0
          ORE.emit([&]() {
933
0
            return OptimizationRemarkMissed(DEBUG_TYPE,
934
0
                                            "DropSelectUnhoistableBranch", SI)
935
0
                << "Dropped select due to unhoistable branch";
936
0
          });
937
0
        }
938
0
        llvm::erase_if(Selects, [EntryBB](SelectInst *SI) {
939
0
          return SI->getParent() == EntryBB;
940
0
        });
941
0
        Unhoistables.clear();
942
0
        InsertPoint = Branch;
943
0
      }
944
0
    }
945
0
    CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");
946
0
#ifndef NDEBUG
947
0
    if (RI.HasBranch) {
948
0
      assert(!DT.dominates(Branch, InsertPoint) &&
949
0
             "Branch can't be already above the hoist point");
950
0
      DenseMap<Instruction *, bool> Visited;
951
0
      assert(checkHoistValue(Branch->getCondition(), InsertPoint,
952
0
                             DT, Unhoistables, nullptr, Visited) &&
953
0
             "checkHoistValue for branch");
954
0
    }
955
0
    for (auto *SI : Selects) {
956
0
      assert(!DT.dominates(SI, InsertPoint) &&
957
0
             "SI can't be already above the hoist point");
958
0
      DenseMap<Instruction *, bool> Visited;
959
0
      assert(checkHoistValue(SI->getCondition(), InsertPoint, DT,
960
0
                             Unhoistables, nullptr, Visited) &&
961
0
             "checkHoistValue for selects");
962
0
    }
963
0
    CHR_DEBUG(dbgs() << "Result\n");
964
0
    if (RI.HasBranch) {
965
0
      CHR_DEBUG(dbgs() << "BI " << *Branch << "\n");
966
0
    }
967
0
    for (auto *SI : Selects) {
968
0
      CHR_DEBUG(dbgs() << "SI " << *SI << "\n");
969
0
    }
970
0
#endif
971
0
  }
972
0
}
973
974
// Traverse the region tree, find all nested scopes and merge them if possible.
975
CHRScope * CHR::findScopes(Region *R, Region *NextRegion, Region *ParentRegion,
976
0
                           SmallVectorImpl<CHRScope *> &Scopes) {
977
0
  CHR_DEBUG(dbgs() << "findScopes " << R->getNameStr() << "\n");
978
0
  CHRScope *Result = findScope(R);
979
  // Visit subscopes.
980
0
  CHRScope *ConsecutiveSubscope = nullptr;
981
0
  SmallVector<CHRScope *, 8> Subscopes;
982
0
  for (auto It = R->begin(); It != R->end(); ++It) {
983
0
    const std::unique_ptr<Region> &SubR = *It;
984
0
    auto NextIt = std::next(It);
985
0
    Region *NextSubR = NextIt != R->end() ? NextIt->get() : nullptr;
986
0
    CHR_DEBUG(dbgs() << "Looking at subregion " << SubR.get()->getNameStr()
987
0
              << "\n");
988
0
    CHRScope *SubCHRScope = findScopes(SubR.get(), NextSubR, R, Scopes);
989
0
    if (SubCHRScope) {
990
0
      CHR_DEBUG(dbgs() << "Subregion Scope " << *SubCHRScope << "\n");
991
0
    } else {
992
0
      CHR_DEBUG(dbgs() << "Subregion Scope null\n");
993
0
    }
994
0
    if (SubCHRScope) {
995
0
      if (!ConsecutiveSubscope)
996
0
        ConsecutiveSubscope = SubCHRScope;
997
0
      else if (!ConsecutiveSubscope->appendable(SubCHRScope)) {
998
0
        Subscopes.push_back(ConsecutiveSubscope);
999
0
        ConsecutiveSubscope = SubCHRScope;
1000
0
      } else
1001
0
        ConsecutiveSubscope->append(SubCHRScope);
1002
0
    } else {
1003
0
      if (ConsecutiveSubscope) {
1004
0
        Subscopes.push_back(ConsecutiveSubscope);
1005
0
      }
1006
0
      ConsecutiveSubscope = nullptr;
1007
0
    }
1008
0
  }
1009
0
  if (ConsecutiveSubscope) {
1010
0
    Subscopes.push_back(ConsecutiveSubscope);
1011
0
  }
1012
0
  for (CHRScope *Sub : Subscopes) {
1013
0
    if (Result) {
1014
      // Combine it with the parent.
1015
0
      Result->addSub(Sub);
1016
0
    } else {
1017
      // Push Subscopes as they won't be combined with the parent.
1018
0
      Scopes.push_back(Sub);
1019
0
    }
1020
0
  }
1021
0
  return Result;
1022
0
}
1023
1024
0
static DenseSet<Value *> getCHRConditionValuesForRegion(RegInfo &RI) {
1025
0
  DenseSet<Value *> ConditionValues;
1026
0
  if (RI.HasBranch) {
1027
0
    auto *BI = cast<BranchInst>(RI.R->getEntry()->getTerminator());
1028
0
    ConditionValues.insert(BI->getCondition());
1029
0
  }
1030
0
  for (SelectInst *SI : RI.Selects) {
1031
0
    ConditionValues.insert(SI->getCondition());
1032
0
  }
1033
0
  return ConditionValues;
1034
0
}
1035
1036
1037
// Determine whether to split a scope depending on the sets of the branch
1038
// condition values of the previous region and the current region. We split
1039
// (return true) it if 1) the condition values of the inner/lower scope can't be
1040
// hoisted up to the outer/upper scope, or 2) the two sets of the condition
1041
// values have an empty intersection (because the combined branch conditions
1042
// won't probably lead to a simpler combined condition).
1043
static bool shouldSplit(Instruction *InsertPoint,
1044
                        DenseSet<Value *> &PrevConditionValues,
1045
                        DenseSet<Value *> &ConditionValues,
1046
                        DominatorTree &DT,
1047
0
                        DenseSet<Instruction *> &Unhoistables) {
1048
0
  assert(InsertPoint && "Null InsertPoint");
1049
0
  CHR_DEBUG(
1050
0
      dbgs() << "shouldSplit " << *InsertPoint << " PrevConditionValues ";
1051
0
      for (Value *V : PrevConditionValues) {
1052
0
        dbgs() << *V << ", ";
1053
0
      }
1054
0
      dbgs() << " ConditionValues ";
1055
0
      for (Value *V : ConditionValues) {
1056
0
        dbgs() << *V << ", ";
1057
0
      }
1058
0
      dbgs() << "\n");
1059
  // If any of Bases isn't hoistable to the hoist point, split.
1060
0
  for (Value *V : ConditionValues) {
1061
0
    DenseMap<Instruction *, bool> Visited;
1062
0
    if (!checkHoistValue(V, InsertPoint, DT, Unhoistables, nullptr, Visited)) {
1063
0
      CHR_DEBUG(dbgs() << "Split. checkHoistValue false " << *V << "\n");
1064
0
      return true; // Not hoistable, split.
1065
0
    }
1066
0
  }
1067
  // If PrevConditionValues or ConditionValues is empty, don't split to avoid
1068
  // unnecessary splits at scopes with no branch/selects.  If
1069
  // PrevConditionValues and ConditionValues don't intersect at all, split.
1070
0
  if (!PrevConditionValues.empty() && !ConditionValues.empty()) {
1071
    // Use std::set as DenseSet doesn't work with set_intersection.
1072
0
    std::set<Value *> PrevBases, Bases;
1073
0
    DenseMap<Value *, std::set<Value *>> Visited;
1074
0
    for (Value *V : PrevConditionValues) {
1075
0
      const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited);
1076
0
      PrevBases.insert(BaseValues.begin(), BaseValues.end());
1077
0
    }
1078
0
    for (Value *V : ConditionValues) {
1079
0
      const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited);
1080
0
      Bases.insert(BaseValues.begin(), BaseValues.end());
1081
0
    }
1082
0
    CHR_DEBUG(
1083
0
        dbgs() << "PrevBases ";
1084
0
        for (Value *V : PrevBases) {
1085
0
          dbgs() << *V << ", ";
1086
0
        }
1087
0
        dbgs() << " Bases ";
1088
0
        for (Value *V : Bases) {
1089
0
          dbgs() << *V << ", ";
1090
0
        }
1091
0
        dbgs() << "\n");
1092
0
    std::vector<Value *> Intersection;
1093
0
    std::set_intersection(PrevBases.begin(), PrevBases.end(), Bases.begin(),
1094
0
                          Bases.end(), std::back_inserter(Intersection));
1095
0
    if (Intersection.empty()) {
1096
      // Empty intersection, split.
1097
0
      CHR_DEBUG(dbgs() << "Split. Intersection empty\n");
1098
0
      return true;
1099
0
    }
1100
0
  }
1101
0
  CHR_DEBUG(dbgs() << "No split\n");
1102
0
  return false;  // Don't split.
1103
0
}
1104
1105
static void getSelectsInScope(CHRScope *Scope,
1106
0
                              DenseSet<Instruction *> &Output) {
1107
0
  for (RegInfo &RI : Scope->RegInfos)
1108
0
    for (SelectInst *SI : RI.Selects)
1109
0
      Output.insert(SI);
1110
0
  for (CHRScope *Sub : Scope->Subs)
1111
0
    getSelectsInScope(Sub, Output);
1112
0
}
1113
1114
void CHR::splitScopes(SmallVectorImpl<CHRScope *> &Input,
1115
0
                      SmallVectorImpl<CHRScope *> &Output) {
1116
0
  for (CHRScope *Scope : Input) {
1117
0
    assert(!Scope->BranchInsertPoint &&
1118
0
           "BranchInsertPoint must not be set");
1119
0
    DenseSet<Instruction *> Unhoistables;
1120
0
    getSelectsInScope(Scope, Unhoistables);
1121
0
    splitScope(Scope, nullptr, nullptr, nullptr, Output, Unhoistables);
1122
0
  }
1123
0
#ifndef NDEBUG
1124
0
  for (CHRScope *Scope : Output) {
1125
0
    assert(Scope->BranchInsertPoint && "BranchInsertPoint must be set");
1126
0
  }
1127
0
#endif
1128
0
}
1129
1130
SmallVector<CHRScope *, 8> CHR::splitScope(
1131
    CHRScope *Scope,
1132
    CHRScope *Outer,
1133
    DenseSet<Value *> *OuterConditionValues,
1134
    Instruction *OuterInsertPoint,
1135
    SmallVectorImpl<CHRScope *> &Output,
1136
0
    DenseSet<Instruction *> &Unhoistables) {
1137
0
  if (Outer) {
1138
0
    assert(OuterConditionValues && "Null OuterConditionValues");
1139
0
    assert(OuterInsertPoint && "Null OuterInsertPoint");
1140
0
  }
1141
0
  bool PrevSplitFromOuter = true;
1142
0
  DenseSet<Value *> PrevConditionValues;
1143
0
  Instruction *PrevInsertPoint = nullptr;
1144
0
  SmallVector<CHRScope *, 8> Splits;
1145
0
  SmallVector<bool, 8> SplitsSplitFromOuter;
1146
0
  SmallVector<DenseSet<Value *>, 8> SplitsConditionValues;
1147
0
  SmallVector<Instruction *, 8> SplitsInsertPoints;
1148
0
  SmallVector<RegInfo, 8> RegInfos(Scope->RegInfos);  // Copy
1149
0
  for (RegInfo &RI : RegInfos) {
1150
0
    Instruction *InsertPoint = getBranchInsertPoint(RI);
1151
0
    DenseSet<Value *> ConditionValues = getCHRConditionValuesForRegion(RI);
1152
0
    CHR_DEBUG(
1153
0
        dbgs() << "ConditionValues ";
1154
0
        for (Value *V : ConditionValues) {
1155
0
          dbgs() << *V << ", ";
1156
0
        }
1157
0
        dbgs() << "\n");
1158
0
    if (RI.R == RegInfos[0].R) {
1159
      // First iteration. Check to see if we should split from the outer.
1160
0
      if (Outer) {
1161
0
        CHR_DEBUG(dbgs() << "Outer " << *Outer << "\n");
1162
0
        CHR_DEBUG(dbgs() << "Should split from outer at "
1163
0
                  << RI.R->getNameStr() << "\n");
1164
0
        if (shouldSplit(OuterInsertPoint, *OuterConditionValues,
1165
0
                        ConditionValues, DT, Unhoistables)) {
1166
0
          PrevConditionValues = ConditionValues;
1167
0
          PrevInsertPoint = InsertPoint;
1168
0
          ORE.emit([&]() {
1169
0
            return OptimizationRemarkMissed(DEBUG_TYPE,
1170
0
                                            "SplitScopeFromOuter",
1171
0
                                            RI.R->getEntry()->getTerminator())
1172
0
                << "Split scope from outer due to unhoistable branch/select "
1173
0
                << "and/or lack of common condition values";
1174
0
          });
1175
0
        } else {
1176
          // Not splitting from the outer. Use the outer bases and insert
1177
          // point. Union the bases.
1178
0
          PrevSplitFromOuter = false;
1179
0
          PrevConditionValues = *OuterConditionValues;
1180
0
          PrevConditionValues.insert(ConditionValues.begin(),
1181
0
                                     ConditionValues.end());
1182
0
          PrevInsertPoint = OuterInsertPoint;
1183
0
        }
1184
0
      } else {
1185
0
        CHR_DEBUG(dbgs() << "Outer null\n");
1186
0
        PrevConditionValues = ConditionValues;
1187
0
        PrevInsertPoint = InsertPoint;
1188
0
      }
1189
0
    } else {
1190
0
      CHR_DEBUG(dbgs() << "Should split from prev at "
1191
0
                << RI.R->getNameStr() << "\n");
1192
0
      if (shouldSplit(PrevInsertPoint, PrevConditionValues, ConditionValues,
1193
0
                      DT, Unhoistables)) {
1194
0
        CHRScope *Tail = Scope->split(RI.R);
1195
0
        Scopes.insert(Tail);
1196
0
        Splits.push_back(Scope);
1197
0
        SplitsSplitFromOuter.push_back(PrevSplitFromOuter);
1198
0
        SplitsConditionValues.push_back(PrevConditionValues);
1199
0
        SplitsInsertPoints.push_back(PrevInsertPoint);
1200
0
        Scope = Tail;
1201
0
        PrevConditionValues = ConditionValues;
1202
0
        PrevInsertPoint = InsertPoint;
1203
0
        PrevSplitFromOuter = true;
1204
0
        ORE.emit([&]() {
1205
0
          return OptimizationRemarkMissed(DEBUG_TYPE,
1206
0
                                          "SplitScopeFromPrev",
1207
0
                                          RI.R->getEntry()->getTerminator())
1208
0
              << "Split scope from previous due to unhoistable branch/select "
1209
0
              << "and/or lack of common condition values";
1210
0
        });
1211
0
      } else {
1212
        // Not splitting. Union the bases. Keep the hoist point.
1213
0
        PrevConditionValues.insert(ConditionValues.begin(), ConditionValues.end());
1214
0
      }
1215
0
    }
1216
0
  }
1217
0
  Splits.push_back(Scope);
1218
0
  SplitsSplitFromOuter.push_back(PrevSplitFromOuter);
1219
0
  SplitsConditionValues.push_back(PrevConditionValues);
1220
0
  assert(PrevInsertPoint && "Null PrevInsertPoint");
1221
0
  SplitsInsertPoints.push_back(PrevInsertPoint);
1222
0
  assert(Splits.size() == SplitsConditionValues.size() &&
1223
0
         Splits.size() == SplitsSplitFromOuter.size() &&
1224
0
         Splits.size() == SplitsInsertPoints.size() && "Mismatching sizes");
1225
0
  for (size_t I = 0; I < Splits.size(); ++I) {
1226
0
    CHRScope *Split = Splits[I];
1227
0
    DenseSet<Value *> &SplitConditionValues = SplitsConditionValues[I];
1228
0
    Instruction *SplitInsertPoint = SplitsInsertPoints[I];
1229
0
    SmallVector<CHRScope *, 8> NewSubs;
1230
0
    DenseSet<Instruction *> SplitUnhoistables;
1231
0
    getSelectsInScope(Split, SplitUnhoistables);
1232
0
    for (CHRScope *Sub : Split->Subs) {
1233
0
      SmallVector<CHRScope *, 8> SubSplits = splitScope(
1234
0
          Sub, Split, &SplitConditionValues, SplitInsertPoint, Output,
1235
0
          SplitUnhoistables);
1236
0
      llvm::append_range(NewSubs, SubSplits);
1237
0
    }
1238
0
    Split->Subs = NewSubs;
1239
0
  }
1240
0
  SmallVector<CHRScope *, 8> Result;
1241
0
  for (size_t I = 0; I < Splits.size(); ++I) {
1242
0
    CHRScope *Split = Splits[I];
1243
0
    if (SplitsSplitFromOuter[I]) {
1244
      // Split from the outer.
1245
0
      Output.push_back(Split);
1246
0
      Split->BranchInsertPoint = SplitsInsertPoints[I];
1247
0
      CHR_DEBUG(dbgs() << "BranchInsertPoint " << *SplitsInsertPoints[I]
1248
0
                << "\n");
1249
0
    } else {
1250
      // Connected to the outer.
1251
0
      Result.push_back(Split);
1252
0
    }
1253
0
  }
1254
0
  if (!Outer)
1255
0
    assert(Result.empty() &&
1256
0
           "If no outer (top-level), must return no nested ones");
1257
0
  return Result;
1258
0
}
1259
1260
0
void CHR::classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes) {
1261
0
  for (CHRScope *Scope : Scopes) {
1262
0
    assert(Scope->TrueBiasedRegions.empty() && Scope->FalseBiasedRegions.empty() && "Empty");
1263
0
    classifyBiasedScopes(Scope, Scope);
1264
0
    CHR_DEBUG(
1265
0
        dbgs() << "classifyBiasedScopes " << *Scope << "\n";
1266
0
        dbgs() << "TrueBiasedRegions ";
1267
0
        for (Region *R : Scope->TrueBiasedRegions) {
1268
0
          dbgs() << R->getNameStr() << ", ";
1269
0
        }
1270
0
        dbgs() << "\n";
1271
0
        dbgs() << "FalseBiasedRegions ";
1272
0
        for (Region *R : Scope->FalseBiasedRegions) {
1273
0
          dbgs() << R->getNameStr() << ", ";
1274
0
        }
1275
0
        dbgs() << "\n";
1276
0
        dbgs() << "TrueBiasedSelects ";
1277
0
        for (SelectInst *SI : Scope->TrueBiasedSelects) {
1278
0
          dbgs() << *SI << ", ";
1279
0
        }
1280
0
        dbgs() << "\n";
1281
0
        dbgs() << "FalseBiasedSelects ";
1282
0
        for (SelectInst *SI : Scope->FalseBiasedSelects) {
1283
0
          dbgs() << *SI << ", ";
1284
0
        }
1285
0
        dbgs() << "\n";);
1286
0
  }
1287
0
}
1288
1289
0
void CHR::classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope) {
1290
0
  for (RegInfo &RI : Scope->RegInfos) {
1291
0
    if (RI.HasBranch) {
1292
0
      Region *R = RI.R;
1293
0
      if (TrueBiasedRegionsGlobal.contains(R))
1294
0
        OutermostScope->TrueBiasedRegions.insert(R);
1295
0
      else if (FalseBiasedRegionsGlobal.contains(R))
1296
0
        OutermostScope->FalseBiasedRegions.insert(R);
1297
0
      else
1298
0
        llvm_unreachable("Must be biased");
1299
0
    }
1300
0
    for (SelectInst *SI : RI.Selects) {
1301
0
      if (TrueBiasedSelectsGlobal.contains(SI))
1302
0
        OutermostScope->TrueBiasedSelects.insert(SI);
1303
0
      else if (FalseBiasedSelectsGlobal.contains(SI))
1304
0
        OutermostScope->FalseBiasedSelects.insert(SI);
1305
0
      else
1306
0
        llvm_unreachable("Must be biased");
1307
0
    }
1308
0
  }
1309
0
  for (CHRScope *Sub : Scope->Subs) {
1310
0
    classifyBiasedScopes(Sub, OutermostScope);
1311
0
  }
1312
0
}
1313
1314
0
static bool hasAtLeastTwoBiasedBranches(CHRScope *Scope) {
1315
0
  unsigned NumBiased = Scope->TrueBiasedRegions.size() +
1316
0
                       Scope->FalseBiasedRegions.size() +
1317
0
                       Scope->TrueBiasedSelects.size() +
1318
0
                       Scope->FalseBiasedSelects.size();
1319
0
  return NumBiased >= CHRMergeThreshold;
1320
0
}
1321
1322
void CHR::filterScopes(SmallVectorImpl<CHRScope *> &Input,
1323
0
                       SmallVectorImpl<CHRScope *> &Output) {
1324
0
  for (CHRScope *Scope : Input) {
1325
    // Filter out the ones with only one region and no subs.
1326
0
    if (!hasAtLeastTwoBiasedBranches(Scope)) {
1327
0
      CHR_DEBUG(dbgs() << "Filtered out by biased branches truthy-regions "
1328
0
                << Scope->TrueBiasedRegions.size()
1329
0
                << " falsy-regions " << Scope->FalseBiasedRegions.size()
1330
0
                << " true-selects " << Scope->TrueBiasedSelects.size()
1331
0
                << " false-selects " << Scope->FalseBiasedSelects.size() << "\n");
1332
0
      ORE.emit([&]() {
1333
0
        return OptimizationRemarkMissed(
1334
0
            DEBUG_TYPE,
1335
0
            "DropScopeWithOneBranchOrSelect",
1336
0
            Scope->RegInfos[0].R->getEntry()->getTerminator())
1337
0
            << "Drop scope with < "
1338
0
            << ore::NV("CHRMergeThreshold", CHRMergeThreshold)
1339
0
            << " biased branch(es) or select(s)";
1340
0
      });
1341
0
      continue;
1342
0
    }
1343
0
    Output.push_back(Scope);
1344
0
  }
1345
0
}
1346
1347
void CHR::setCHRRegions(SmallVectorImpl<CHRScope *> &Input,
1348
0
                        SmallVectorImpl<CHRScope *> &Output) {
1349
0
  for (CHRScope *Scope : Input) {
1350
0
    assert(Scope->HoistStopMap.empty() && Scope->CHRRegions.empty() &&
1351
0
           "Empty");
1352
0
    setCHRRegions(Scope, Scope);
1353
0
    Output.push_back(Scope);
1354
0
    CHR_DEBUG(
1355
0
        dbgs() << "setCHRRegions HoistStopMap " << *Scope << "\n";
1356
0
        for (auto pair : Scope->HoistStopMap) {
1357
0
          Region *R = pair.first;
1358
0
          dbgs() << "Region " << R->getNameStr() << "\n";
1359
0
          for (Instruction *I : pair.second) {
1360
0
            dbgs() << "HoistStop " << *I << "\n";
1361
0
          }
1362
0
        }
1363
0
        dbgs() << "CHRRegions" << "\n";
1364
0
        for (RegInfo &RI : Scope->CHRRegions) {
1365
0
          dbgs() << RI.R->getNameStr() << "\n";
1366
0
        });
1367
0
  }
1368
0
}
1369
1370
0
void CHR::setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope) {
1371
0
  DenseSet<Instruction *> Unhoistables;
1372
  // Put the biased selects in Unhoistables because they should stay where they
1373
  // are and constant-folded after CHR (in case one biased select or a branch
1374
  // can depend on another biased select.)
1375
0
  for (RegInfo &RI : Scope->RegInfos) {
1376
0
    for (SelectInst *SI : RI.Selects) {
1377
0
      Unhoistables.insert(SI);
1378
0
    }
1379
0
  }
1380
0
  Instruction *InsertPoint = OutermostScope->BranchInsertPoint;
1381
0
  for (RegInfo &RI : Scope->RegInfos) {
1382
0
    Region *R = RI.R;
1383
0
    DenseSet<Instruction *> HoistStops;
1384
0
    bool IsHoisted = false;
1385
0
    if (RI.HasBranch) {
1386
0
      assert((OutermostScope->TrueBiasedRegions.contains(R) ||
1387
0
              OutermostScope->FalseBiasedRegions.contains(R)) &&
1388
0
             "Must be truthy or falsy");
1389
0
      auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());
1390
      // Note checkHoistValue fills in HoistStops.
1391
0
      DenseMap<Instruction *, bool> Visited;
1392
0
      bool IsHoistable = checkHoistValue(BI->getCondition(), InsertPoint, DT,
1393
0
                                         Unhoistables, &HoistStops, Visited);
1394
0
      assert(IsHoistable && "Must be hoistable");
1395
0
      (void)(IsHoistable);  // Unused in release build
1396
0
      IsHoisted = true;
1397
0
    }
1398
0
    for (SelectInst *SI : RI.Selects) {
1399
0
      assert((OutermostScope->TrueBiasedSelects.contains(SI) ||
1400
0
              OutermostScope->FalseBiasedSelects.contains(SI)) &&
1401
0
             "Must be true or false biased");
1402
      // Note checkHoistValue fills in HoistStops.
1403
0
      DenseMap<Instruction *, bool> Visited;
1404
0
      bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint, DT,
1405
0
                                         Unhoistables, &HoistStops, Visited);
1406
0
      assert(IsHoistable && "Must be hoistable");
1407
0
      (void)(IsHoistable);  // Unused in release build
1408
0
      IsHoisted = true;
1409
0
    }
1410
0
    if (IsHoisted) {
1411
0
      OutermostScope->CHRRegions.push_back(RI);
1412
0
      OutermostScope->HoistStopMap[R] = HoistStops;
1413
0
    }
1414
0
  }
1415
0
  for (CHRScope *Sub : Scope->Subs)
1416
0
    setCHRRegions(Sub, OutermostScope);
1417
0
}
1418
1419
0
static bool CHRScopeSorter(CHRScope *Scope1, CHRScope *Scope2) {
1420
0
  return Scope1->RegInfos[0].R->getDepth() < Scope2->RegInfos[0].R->getDepth();
1421
0
}
1422
1423
void CHR::sortScopes(SmallVectorImpl<CHRScope *> &Input,
1424
0
                     SmallVectorImpl<CHRScope *> &Output) {
1425
0
  Output.resize(Input.size());
1426
0
  llvm::copy(Input, Output.begin());
1427
0
  llvm::stable_sort(Output, CHRScopeSorter);
1428
0
}
1429
1430
// Return true if V is already hoisted or was hoisted (along with its operands)
1431
// to the insert point.
1432
static void hoistValue(Value *V, Instruction *HoistPoint, Region *R,
1433
                       HoistStopMapTy &HoistStopMap,
1434
                       DenseSet<Instruction *> &HoistedSet,
1435
                       DenseSet<PHINode *> &TrivialPHIs,
1436
0
                       DominatorTree &DT) {
1437
0
  auto IT = HoistStopMap.find(R);
1438
0
  assert(IT != HoistStopMap.end() && "Region must be in hoist stop map");
1439
0
  DenseSet<Instruction *> &HoistStops = IT->second;
1440
0
  if (auto *I = dyn_cast<Instruction>(V)) {
1441
0
    if (I == HoistPoint)
1442
0
      return;
1443
0
    if (HoistStops.count(I))
1444
0
      return;
1445
0
    if (auto *PN = dyn_cast<PHINode>(I))
1446
0
      if (TrivialPHIs.count(PN))
1447
        // The trivial phi inserted by the previous CHR scope could replace a
1448
        // non-phi in HoistStops. Note that since this phi is at the exit of a
1449
        // previous CHR scope, which dominates this scope, it's safe to stop
1450
        // hoisting there.
1451
0
        return;
1452
0
    if (HoistedSet.count(I))
1453
      // Already hoisted, return.
1454
0
      return;
1455
0
    assert(isHoistableInstructionType(I) && "Unhoistable instruction type");
1456
0
    assert(DT.getNode(I->getParent()) && "DT must contain I's block");
1457
0
    assert(DT.getNode(HoistPoint->getParent()) &&
1458
0
           "DT must contain HoistPoint block");
1459
0
    if (DT.dominates(I, HoistPoint))
1460
      // We are already above the hoist point. Stop here. This may be necessary
1461
      // when multiple scopes would independently hoist the same
1462
      // instruction. Since an outer (dominating) scope would hoist it to its
1463
      // entry before an inner (dominated) scope would to its entry, the inner
1464
      // scope may see the instruction already hoisted, in which case it
1465
      // potentially wrong for the inner scope to hoist it and could cause bad
1466
      // IR (non-dominating def), but safe to skip hoisting it instead because
1467
      // it's already in a block that dominates the inner scope.
1468
0
      return;
1469
0
    for (Value *Op : I->operands()) {
1470
0
      hoistValue(Op, HoistPoint, R, HoistStopMap, HoistedSet, TrivialPHIs, DT);
1471
0
    }
1472
0
    I->moveBefore(HoistPoint);
1473
0
    HoistedSet.insert(I);
1474
0
    CHR_DEBUG(dbgs() << "hoistValue " << *I << "\n");
1475
0
  }
1476
0
}
1477
1478
// Hoist the dependent condition values of the branches and the selects in the
1479
// scope to the insert point.
1480
static void hoistScopeConditions(CHRScope *Scope, Instruction *HoistPoint,
1481
                                 DenseSet<PHINode *> &TrivialPHIs,
1482
0
                                 DominatorTree &DT) {
1483
0
  DenseSet<Instruction *> HoistedSet;
1484
0
  for (const RegInfo &RI : Scope->CHRRegions) {
1485
0
    Region *R = RI.R;
1486
0
    bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);
1487
0
    bool IsFalseBiased = Scope->FalseBiasedRegions.count(R);
1488
0
    if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) {
1489
0
      auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());
1490
0
      hoistValue(BI->getCondition(), HoistPoint, R, Scope->HoistStopMap,
1491
0
                 HoistedSet, TrivialPHIs, DT);
1492
0
    }
1493
0
    for (SelectInst *SI : RI.Selects) {
1494
0
      bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);
1495
0
      bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI);
1496
0
      if (!(IsTrueBiased || IsFalseBiased))
1497
0
        continue;
1498
0
      hoistValue(SI->getCondition(), HoistPoint, R, Scope->HoistStopMap,
1499
0
                 HoistedSet, TrivialPHIs, DT);
1500
0
    }
1501
0
  }
1502
0
}
1503
1504
// Negate the predicate if an ICmp if it's used only by branches or selects by
1505
// swapping the operands of the branches or the selects. Returns true if success.
1506
static bool negateICmpIfUsedByBranchOrSelectOnly(ICmpInst *ICmp,
1507
                                                 Instruction *ExcludedUser,
1508
0
                                                 CHRScope *Scope) {
1509
0
  for (User *U : ICmp->users()) {
1510
0
    if (U == ExcludedUser)
1511
0
      continue;
1512
0
    if (isa<BranchInst>(U) && cast<BranchInst>(U)->isConditional())
1513
0
      continue;
1514
0
    if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == ICmp)
1515
0
      continue;
1516
0
    return false;
1517
0
  }
1518
0
  for (User *U : ICmp->users()) {
1519
0
    if (U == ExcludedUser)
1520
0
      continue;
1521
0
    if (auto *BI = dyn_cast<BranchInst>(U)) {
1522
0
      assert(BI->isConditional() && "Must be conditional");
1523
0
      BI->swapSuccessors();
1524
      // Don't need to swap this in terms of
1525
      // TrueBiasedRegions/FalseBiasedRegions because true-based/false-based
1526
      // mean whehter the branch is likely go into the if-then rather than
1527
      // successor0/successor1 and because we can tell which edge is the then or
1528
      // the else one by comparing the destination to the region exit block.
1529
0
      continue;
1530
0
    }
1531
0
    if (auto *SI = dyn_cast<SelectInst>(U)) {
1532
      // Swap operands
1533
0
      SI->swapValues();
1534
0
      SI->swapProfMetadata();
1535
0
      if (Scope->TrueBiasedSelects.count(SI)) {
1536
0
        assert(!Scope->FalseBiasedSelects.contains(SI) &&
1537
0
               "Must not be already in");
1538
0
        Scope->FalseBiasedSelects.insert(SI);
1539
0
      } else if (Scope->FalseBiasedSelects.count(SI)) {
1540
0
        assert(!Scope->TrueBiasedSelects.contains(SI) &&
1541
0
               "Must not be already in");
1542
0
        Scope->TrueBiasedSelects.insert(SI);
1543
0
      }
1544
0
      continue;
1545
0
    }
1546
0
    llvm_unreachable("Must be a branch or a select");
1547
0
  }
1548
0
  ICmp->setPredicate(CmpInst::getInversePredicate(ICmp->getPredicate()));
1549
0
  return true;
1550
0
}
1551
1552
// A helper for transformScopes. Insert a trivial phi at the scope exit block
1553
// for a value that's defined in the scope but used outside it (meaning it's
1554
// alive at the exit block).
1555
static void insertTrivialPHIs(CHRScope *Scope,
1556
                              BasicBlock *EntryBlock, BasicBlock *ExitBlock,
1557
0
                              DenseSet<PHINode *> &TrivialPHIs) {
1558
0
  SmallSetVector<BasicBlock *, 8> BlocksInScope;
1559
0
  for (RegInfo &RI : Scope->RegInfos) {
1560
0
    for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the
1561
                                            // sub-Scopes.
1562
0
      BlocksInScope.insert(BB);
1563
0
    }
1564
0
  }
1565
0
  CHR_DEBUG({
1566
0
    dbgs() << "Inserting redundant phis\n";
1567
0
    for (BasicBlock *BB : BlocksInScope)
1568
0
      dbgs() << "BlockInScope " << BB->getName() << "\n";
1569
0
  });
1570
0
  for (BasicBlock *BB : BlocksInScope) {
1571
0
    for (Instruction &I : *BB) {
1572
0
      SmallVector<Instruction *, 8> Users;
1573
0
      for (User *U : I.users()) {
1574
0
        if (auto *UI = dyn_cast<Instruction>(U)) {
1575
0
          if (!BlocksInScope.contains(UI->getParent()) &&
1576
              // Unless there's already a phi for I at the exit block.
1577
0
              !(isa<PHINode>(UI) && UI->getParent() == ExitBlock)) {
1578
0
            CHR_DEBUG(dbgs() << "V " << I << "\n");
1579
0
            CHR_DEBUG(dbgs() << "Used outside scope by user " << *UI << "\n");
1580
0
            Users.push_back(UI);
1581
0
          } else if (UI->getParent() == EntryBlock && isa<PHINode>(UI)) {
1582
            // There's a loop backedge from a block that's dominated by this
1583
            // scope to the entry block.
1584
0
            CHR_DEBUG(dbgs() << "V " << I << "\n");
1585
0
            CHR_DEBUG(dbgs()
1586
0
                      << "Used at entry block (for a back edge) by a phi user "
1587
0
                      << *UI << "\n");
1588
0
            Users.push_back(UI);
1589
0
          }
1590
0
        }
1591
0
      }
1592
0
      if (Users.size() > 0) {
1593
        // Insert a trivial phi for I (phi [&I, P0], [&I, P1], ...) at
1594
        // ExitBlock. Replace I with the new phi in UI unless UI is another
1595
        // phi at ExitBlock.
1596
0
        PHINode *PN = PHINode::Create(I.getType(), pred_size(ExitBlock), "");
1597
0
        PN->insertBefore(ExitBlock->begin());
1598
0
        for (BasicBlock *Pred : predecessors(ExitBlock)) {
1599
0
          PN->addIncoming(&I, Pred);
1600
0
        }
1601
0
        TrivialPHIs.insert(PN);
1602
0
        CHR_DEBUG(dbgs() << "Insert phi " << *PN << "\n");
1603
0
        for (Instruction *UI : Users) {
1604
0
          for (unsigned J = 0, NumOps = UI->getNumOperands(); J < NumOps; ++J) {
1605
0
            if (UI->getOperand(J) == &I) {
1606
0
              UI->setOperand(J, PN);
1607
0
            }
1608
0
          }
1609
0
          CHR_DEBUG(dbgs() << "Updated user " << *UI << "\n");
1610
0
        }
1611
0
      }
1612
0
    }
1613
0
  }
1614
0
}
1615
1616
// Assert that all the CHR regions of the scope have a biased branch or select.
1617
static void LLVM_ATTRIBUTE_UNUSED
1618
0
assertCHRRegionsHaveBiasedBranchOrSelect(CHRScope *Scope) {
1619
0
#ifndef NDEBUG
1620
0
  auto HasBiasedBranchOrSelect = [](RegInfo &RI, CHRScope *Scope) {
1621
0
    if (Scope->TrueBiasedRegions.count(RI.R) ||
1622
0
        Scope->FalseBiasedRegions.count(RI.R))
1623
0
      return true;
1624
0
    for (SelectInst *SI : RI.Selects)
1625
0
      if (Scope->TrueBiasedSelects.count(SI) ||
1626
0
          Scope->FalseBiasedSelects.count(SI))
1627
0
        return true;
1628
0
    return false;
1629
0
  };
1630
0
  for (RegInfo &RI : Scope->CHRRegions) {
1631
0
    assert(HasBiasedBranchOrSelect(RI, Scope) &&
1632
0
           "Must have biased branch or select");
1633
0
  }
1634
0
#endif
1635
0
}
1636
1637
// Assert that all the condition values of the biased branches and selects have
1638
// been hoisted to the pre-entry block or outside of the scope.
1639
static void LLVM_ATTRIBUTE_UNUSED assertBranchOrSelectConditionHoisted(
1640
0
    CHRScope *Scope, BasicBlock *PreEntryBlock) {
1641
0
  CHR_DEBUG(dbgs() << "Biased regions condition values \n");
1642
0
  for (RegInfo &RI : Scope->CHRRegions) {
1643
0
    Region *R = RI.R;
1644
0
    bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);
1645
0
    bool IsFalseBiased = Scope->FalseBiasedRegions.count(R);
1646
0
    if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) {
1647
0
      auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());
1648
0
      Value *V = BI->getCondition();
1649
0
      CHR_DEBUG(dbgs() << *V << "\n");
1650
0
      if (auto *I = dyn_cast<Instruction>(V)) {
1651
0
        (void)(I); // Unused in release build.
1652
0
        assert((I->getParent() == PreEntryBlock ||
1653
0
                !Scope->contains(I)) &&
1654
0
               "Must have been hoisted to PreEntryBlock or outside the scope");
1655
0
      }
1656
0
    }
1657
0
    for (SelectInst *SI : RI.Selects) {
1658
0
      bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);
1659
0
      bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI);
1660
0
      if (!(IsTrueBiased || IsFalseBiased))
1661
0
        continue;
1662
0
      Value *V = SI->getCondition();
1663
0
      CHR_DEBUG(dbgs() << *V << "\n");
1664
0
      if (auto *I = dyn_cast<Instruction>(V)) {
1665
0
        (void)(I); // Unused in release build.
1666
0
        assert((I->getParent() == PreEntryBlock ||
1667
0
                !Scope->contains(I)) &&
1668
0
               "Must have been hoisted to PreEntryBlock or outside the scope");
1669
0
      }
1670
0
    }
1671
0
  }
1672
0
}
1673
1674
0
void CHR::transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs) {
1675
0
  CHR_DEBUG(dbgs() << "transformScopes " << *Scope << "\n");
1676
1677
0
  assert(Scope->RegInfos.size() >= 1 && "Should have at least one Region");
1678
1679
0
  for (RegInfo &RI : Scope->RegInfos) {
1680
0
    const Region *R = RI.R;
1681
0
    unsigned Duplication = getRegionDuplicationCount(R);
1682
0
    CHR_DEBUG(dbgs() << "Dup count for R=" << R << "  is " << Duplication
1683
0
                     << "\n");
1684
0
    if (Duplication >= CHRDupThreshsold) {
1685
0
      CHR_DEBUG(dbgs() << "Reached the dup threshold of " << Duplication
1686
0
                       << " for this region");
1687
0
      ORE.emit([&]() {
1688
0
        return OptimizationRemarkMissed(DEBUG_TYPE, "DupThresholdReached",
1689
0
                                        R->getEntry()->getTerminator())
1690
0
               << "Reached the duplication threshold for the region";
1691
0
      });
1692
0
      return;
1693
0
    }
1694
0
  }
1695
0
  for (RegInfo &RI : Scope->RegInfos) {
1696
0
    DuplicationCount[RI.R]++;
1697
0
  }
1698
1699
0
  Region *FirstRegion = Scope->RegInfos[0].R;
1700
0
  BasicBlock *EntryBlock = FirstRegion->getEntry();
1701
0
  Region *LastRegion = Scope->RegInfos[Scope->RegInfos.size() - 1].R;
1702
0
  BasicBlock *ExitBlock = LastRegion->getExit();
1703
0
  std::optional<uint64_t> ProfileCount = BFI.getBlockProfileCount(EntryBlock);
1704
1705
0
  if (ExitBlock) {
1706
    // Insert a trivial phi at the exit block (where the CHR hot path and the
1707
    // cold path merges) for a value that's defined in the scope but used
1708
    // outside it (meaning it's alive at the exit block). We will add the
1709
    // incoming values for the CHR cold paths to it below. Without this, we'd
1710
    // miss updating phi's for such values unless there happens to already be a
1711
    // phi for that value there.
1712
0
    insertTrivialPHIs(Scope, EntryBlock, ExitBlock, TrivialPHIs);
1713
0
  }
1714
1715
  // Split the entry block of the first region. The new block becomes the new
1716
  // entry block of the first region. The old entry block becomes the block to
1717
  // insert the CHR branch into. Note DT gets updated. Since DT gets updated
1718
  // through the split, we update the entry of the first region after the split,
1719
  // and Region only points to the entry and the exit blocks, rather than
1720
  // keeping everything in a list or set, the blocks membership and the
1721
  // entry/exit blocks of the region are still valid after the split.
1722
0
  CHR_DEBUG(dbgs() << "Splitting entry block " << EntryBlock->getName()
1723
0
            << " at " << *Scope->BranchInsertPoint << "\n");
1724
0
  BasicBlock *NewEntryBlock =
1725
0
      SplitBlock(EntryBlock, Scope->BranchInsertPoint, &DT);
1726
0
  assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&
1727
0
         "NewEntryBlock's only pred must be EntryBlock");
1728
0
  FirstRegion->replaceEntryRecursive(NewEntryBlock);
1729
0
  BasicBlock *PreEntryBlock = EntryBlock;
1730
1731
0
  ValueToValueMapTy VMap;
1732
  // Clone the blocks in the scope (excluding the PreEntryBlock) to split into a
1733
  // hot path (originals) and a cold path (clones) and update the PHIs at the
1734
  // exit block.
1735
0
  cloneScopeBlocks(Scope, PreEntryBlock, ExitBlock, LastRegion, VMap);
1736
1737
  // Replace the old (placeholder) branch with the new (merged) conditional
1738
  // branch.
1739
0
  BranchInst *MergedBr = createMergedBranch(PreEntryBlock, EntryBlock,
1740
0
                                            NewEntryBlock, VMap);
1741
1742
0
#ifndef NDEBUG
1743
0
  assertCHRRegionsHaveBiasedBranchOrSelect(Scope);
1744
0
#endif
1745
1746
  // Hoist the conditional values of the branches/selects.
1747
0
  hoistScopeConditions(Scope, PreEntryBlock->getTerminator(), TrivialPHIs, DT);
1748
1749
0
#ifndef NDEBUG
1750
0
  assertBranchOrSelectConditionHoisted(Scope, PreEntryBlock);
1751
0
#endif
1752
1753
  // Create the combined branch condition and constant-fold the branches/selects
1754
  // in the hot path.
1755
0
  fixupBranchesAndSelects(Scope, PreEntryBlock, MergedBr,
1756
0
                          ProfileCount.value_or(0));
1757
0
}
1758
1759
// A helper for transformScopes. Clone the blocks in the scope (excluding the
1760
// PreEntryBlock) to split into a hot path and a cold path and update the PHIs
1761
// at the exit block.
1762
void CHR::cloneScopeBlocks(CHRScope *Scope,
1763
                           BasicBlock *PreEntryBlock,
1764
                           BasicBlock *ExitBlock,
1765
                           Region *LastRegion,
1766
0
                           ValueToValueMapTy &VMap) {
1767
  // Clone all the blocks. The original blocks will be the hot-path
1768
  // CHR-optimized code and the cloned blocks will be the original unoptimized
1769
  // code. This is so that the block pointers from the
1770
  // CHRScope/Region/RegionInfo can stay valid in pointing to the hot-path code
1771
  // which CHR should apply to.
1772
0
  SmallVector<BasicBlock*, 8> NewBlocks;
1773
0
  for (RegInfo &RI : Scope->RegInfos)
1774
0
    for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the
1775
                                            // sub-Scopes.
1776
0
      assert(BB != PreEntryBlock && "Don't copy the preetntry block");
1777
0
      BasicBlock *NewBB = CloneBasicBlock(BB, VMap, ".nonchr", &F);
1778
0
      NewBlocks.push_back(NewBB);
1779
0
      VMap[BB] = NewBB;
1780
1781
      // Unreachable predecessors will not be cloned and will not have an edge
1782
      // to the cloned block. As such, also remove them from any phi nodes.
1783
0
      for (PHINode &PN : make_early_inc_range(NewBB->phis()))
1784
0
        PN.removeIncomingValueIf([&](unsigned Idx) {
1785
0
          return !DT.isReachableFromEntry(PN.getIncomingBlock(Idx));
1786
0
        });
1787
0
    }
1788
1789
  // Place the cloned blocks right after the original blocks (right before the
1790
  // exit block of.)
1791
0
  if (ExitBlock)
1792
0
    F.splice(ExitBlock->getIterator(), &F, NewBlocks[0]->getIterator(),
1793
0
             F.end());
1794
1795
  // Update the cloned blocks/instructions to refer to themselves.
1796
0
  for (BasicBlock *NewBB : NewBlocks)
1797
0
    for (Instruction &I : *NewBB)
1798
0
      RemapInstruction(&I, VMap,
1799
0
                       RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1800
1801
  // Add the cloned blocks to the PHIs of the exit blocks. ExitBlock is null for
1802
  // the top-level region but we don't need to add PHIs. The trivial PHIs
1803
  // inserted above will be updated here.
1804
0
  if (ExitBlock)
1805
0
    for (PHINode &PN : ExitBlock->phis())
1806
0
      for (unsigned I = 0, NumOps = PN.getNumIncomingValues(); I < NumOps;
1807
0
           ++I) {
1808
0
        BasicBlock *Pred = PN.getIncomingBlock(I);
1809
0
        if (LastRegion->contains(Pred)) {
1810
0
          Value *V = PN.getIncomingValue(I);
1811
0
          auto It = VMap.find(V);
1812
0
          if (It != VMap.end()) V = It->second;
1813
0
          assert(VMap.find(Pred) != VMap.end() && "Pred must have been cloned");
1814
0
          PN.addIncoming(V, cast<BasicBlock>(VMap[Pred]));
1815
0
        }
1816
0
      }
1817
0
}
1818
1819
// A helper for transformScope. Replace the old (placeholder) branch with the
1820
// new (merged) conditional branch.
1821
BranchInst *CHR::createMergedBranch(BasicBlock *PreEntryBlock,
1822
                                    BasicBlock *EntryBlock,
1823
                                    BasicBlock *NewEntryBlock,
1824
0
                                    ValueToValueMapTy &VMap) {
1825
0
  BranchInst *OldBR = cast<BranchInst>(PreEntryBlock->getTerminator());
1826
0
  assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == NewEntryBlock &&
1827
0
         "SplitBlock did not work correctly!");
1828
0
  assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&
1829
0
         "NewEntryBlock's only pred must be EntryBlock");
1830
0
  assert(VMap.find(NewEntryBlock) != VMap.end() &&
1831
0
         "NewEntryBlock must have been copied");
1832
0
  OldBR->dropAllReferences();
1833
0
  OldBR->eraseFromParent();
1834
  // The true predicate is a placeholder. It will be replaced later in
1835
  // fixupBranchesAndSelects().
1836
0
  BranchInst *NewBR = BranchInst::Create(NewEntryBlock,
1837
0
                                         cast<BasicBlock>(VMap[NewEntryBlock]),
1838
0
                                         ConstantInt::getTrue(F.getContext()));
1839
0
  NewBR->insertInto(PreEntryBlock, PreEntryBlock->end());
1840
0
  assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&
1841
0
         "NewEntryBlock's only pred must be EntryBlock");
1842
0
  return NewBR;
1843
0
}
1844
1845
// A helper for transformScopes. Create the combined branch condition and
1846
// constant-fold the branches/selects in the hot path.
1847
void CHR::fixupBranchesAndSelects(CHRScope *Scope,
1848
                                  BasicBlock *PreEntryBlock,
1849
                                  BranchInst *MergedBR,
1850
0
                                  uint64_t ProfileCount) {
1851
0
  Value *MergedCondition = ConstantInt::getTrue(F.getContext());
1852
0
  BranchProbability CHRBranchBias(1, 1);
1853
0
  uint64_t NumCHRedBranches = 0;
1854
0
  IRBuilder<> IRB(PreEntryBlock->getTerminator());
1855
0
  for (RegInfo &RI : Scope->CHRRegions) {
1856
0
    Region *R = RI.R;
1857
0
    if (RI.HasBranch) {
1858
0
      fixupBranch(R, Scope, IRB, MergedCondition, CHRBranchBias);
1859
0
      ++NumCHRedBranches;
1860
0
    }
1861
0
    for (SelectInst *SI : RI.Selects) {
1862
0
      fixupSelect(SI, Scope, IRB, MergedCondition, CHRBranchBias);
1863
0
      ++NumCHRedBranches;
1864
0
    }
1865
0
  }
1866
0
  Stats.NumBranchesDelta += NumCHRedBranches - 1;
1867
0
  Stats.WeightedNumBranchesDelta += (NumCHRedBranches - 1) * ProfileCount;
1868
0
  ORE.emit([&]() {
1869
0
    return OptimizationRemark(DEBUG_TYPE,
1870
0
                              "CHR",
1871
                              // Refer to the hot (original) path
1872
0
                              MergedBR->getSuccessor(0)->getTerminator())
1873
0
        << "Merged " << ore::NV("NumCHRedBranches", NumCHRedBranches)
1874
0
        << " branches or selects";
1875
0
  });
1876
0
  MergedBR->setCondition(MergedCondition);
1877
0
  uint32_t Weights[] = {
1878
0
      static_cast<uint32_t>(CHRBranchBias.scale(1000)),
1879
0
      static_cast<uint32_t>(CHRBranchBias.getCompl().scale(1000)),
1880
0
  };
1881
0
  setBranchWeights(*MergedBR, Weights);
1882
0
  CHR_DEBUG(dbgs() << "CHR branch bias " << Weights[0] << ":" << Weights[1]
1883
0
            << "\n");
1884
0
}
1885
1886
// A helper for fixupBranchesAndSelects. Add to the combined branch condition
1887
// and constant-fold a branch in the hot path.
1888
void CHR::fixupBranch(Region *R, CHRScope *Scope,
1889
                      IRBuilder<> &IRB,
1890
                      Value *&MergedCondition,
1891
0
                      BranchProbability &CHRBranchBias) {
1892
0
  bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);
1893
0
  assert((IsTrueBiased || Scope->FalseBiasedRegions.count(R)) &&
1894
0
         "Must be truthy or falsy");
1895
0
  auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());
1896
0
  assert(BranchBiasMap.contains(R) && "Must be in the bias map");
1897
0
  BranchProbability Bias = BranchBiasMap[R];
1898
0
  assert(Bias >= getCHRBiasThreshold() && "Must be highly biased");
1899
  // Take the min.
1900
0
  if (CHRBranchBias > Bias)
1901
0
    CHRBranchBias = Bias;
1902
0
  BasicBlock *IfThen = BI->getSuccessor(1);
1903
0
  BasicBlock *IfElse = BI->getSuccessor(0);
1904
0
  BasicBlock *RegionExitBlock = R->getExit();
1905
0
  assert(RegionExitBlock && "Null ExitBlock");
1906
0
  assert((IfThen == RegionExitBlock || IfElse == RegionExitBlock) &&
1907
0
         IfThen != IfElse && "Invariant from findScopes");
1908
0
  if (IfThen == RegionExitBlock) {
1909
    // Swap them so that IfThen means going into it and IfElse means skipping
1910
    // it.
1911
0
    std::swap(IfThen, IfElse);
1912
0
  }
1913
0
  CHR_DEBUG(dbgs() << "IfThen " << IfThen->getName()
1914
0
            << " IfElse " << IfElse->getName() << "\n");
1915
0
  Value *Cond = BI->getCondition();
1916
0
  BasicBlock *HotTarget = IsTrueBiased ? IfThen : IfElse;
1917
0
  bool ConditionTrue = HotTarget == BI->getSuccessor(0);
1918
0
  addToMergedCondition(ConditionTrue, Cond, BI, Scope, IRB,
1919
0
                       MergedCondition);
1920
  // Constant-fold the branch at ClonedEntryBlock.
1921
0
  assert(ConditionTrue == (HotTarget == BI->getSuccessor(0)) &&
1922
0
         "The successor shouldn't change");
1923
0
  Value *NewCondition = ConditionTrue ?
1924
0
                        ConstantInt::getTrue(F.getContext()) :
1925
0
                        ConstantInt::getFalse(F.getContext());
1926
0
  BI->setCondition(NewCondition);
1927
0
}
1928
1929
// A helper for fixupBranchesAndSelects. Add to the combined branch condition
1930
// and constant-fold a select in the hot path.
1931
void CHR::fixupSelect(SelectInst *SI, CHRScope *Scope,
1932
                      IRBuilder<> &IRB,
1933
                      Value *&MergedCondition,
1934
0
                      BranchProbability &CHRBranchBias) {
1935
0
  bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);
1936
0
  assert((IsTrueBiased ||
1937
0
          Scope->FalseBiasedSelects.count(SI)) && "Must be biased");
1938
0
  assert(SelectBiasMap.contains(SI) && "Must be in the bias map");
1939
0
  BranchProbability Bias = SelectBiasMap[SI];
1940
0
  assert(Bias >= getCHRBiasThreshold() && "Must be highly biased");
1941
  // Take the min.
1942
0
  if (CHRBranchBias > Bias)
1943
0
    CHRBranchBias = Bias;
1944
0
  Value *Cond = SI->getCondition();
1945
0
  addToMergedCondition(IsTrueBiased, Cond, SI, Scope, IRB,
1946
0
                       MergedCondition);
1947
0
  Value *NewCondition = IsTrueBiased ?
1948
0
                        ConstantInt::getTrue(F.getContext()) :
1949
0
                        ConstantInt::getFalse(F.getContext());
1950
0
  SI->setCondition(NewCondition);
1951
0
}
1952
1953
// A helper for fixupBranch/fixupSelect. Add a branch condition to the merged
1954
// condition.
1955
void CHR::addToMergedCondition(bool IsTrueBiased, Value *Cond,
1956
                               Instruction *BranchOrSelect, CHRScope *Scope,
1957
0
                               IRBuilder<> &IRB, Value *&MergedCondition) {
1958
0
  if (!IsTrueBiased) {
1959
    // If Cond is an icmp and all users of V except for BranchOrSelect is a
1960
    // branch, negate the icmp predicate and swap the branch targets and avoid
1961
    // inserting an Xor to negate Cond.
1962
0
    auto *ICmp = dyn_cast<ICmpInst>(Cond);
1963
0
    if (!ICmp ||
1964
0
        !negateICmpIfUsedByBranchOrSelectOnly(ICmp, BranchOrSelect, Scope))
1965
0
      Cond = IRB.CreateXor(ConstantInt::getTrue(F.getContext()), Cond);
1966
0
  }
1967
1968
  // Freeze potentially poisonous conditions.
1969
0
  if (!isGuaranteedNotToBeUndefOrPoison(Cond))
1970
0
    Cond = IRB.CreateFreeze(Cond);
1971
1972
  // Use logical and to avoid propagating poison from later conditions.
1973
0
  MergedCondition = IRB.CreateLogicalAnd(MergedCondition, Cond);
1974
0
}
1975
1976
0
void CHR::transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes) {
1977
0
  unsigned I = 0;
1978
0
  DenseSet<PHINode *> TrivialPHIs;
1979
0
  for (CHRScope *Scope : CHRScopes) {
1980
0
    transformScopes(Scope, TrivialPHIs);
1981
0
    CHR_DEBUG(
1982
0
        std::ostringstream oss;
1983
0
        oss << " after transformScopes " << I++;
1984
0
        dumpIR(F, oss.str().c_str(), nullptr));
1985
0
    (void)I;
1986
0
  }
1987
0
}
1988
1989
static void LLVM_ATTRIBUTE_UNUSED
1990
0
dumpScopes(SmallVectorImpl<CHRScope *> &Scopes, const char *Label) {
1991
0
  dbgs() << Label << " " << Scopes.size() << "\n";
1992
0
  for (CHRScope *Scope : Scopes) {
1993
0
    dbgs() << *Scope << "\n";
1994
0
  }
1995
0
}
1996
1997
0
bool CHR::run() {
1998
0
  if (!shouldApply(F, PSI))
1999
0
    return false;
2000
2001
0
  CHR_DEBUG(dumpIR(F, "before", nullptr));
2002
2003
0
  bool Changed = false;
2004
0
  {
2005
0
    CHR_DEBUG(
2006
0
        dbgs() << "RegionInfo:\n";
2007
0
        RI.print(dbgs()));
2008
2009
    // Recursively traverse the region tree and find regions that have biased
2010
    // branches and/or selects and create scopes.
2011
0
    SmallVector<CHRScope *, 8> AllScopes;
2012
0
    findScopes(AllScopes);
2013
0
    CHR_DEBUG(dumpScopes(AllScopes, "All scopes"));
2014
2015
    // Split the scopes if 1) the conditional values of the biased
2016
    // branches/selects of the inner/lower scope can't be hoisted up to the
2017
    // outermost/uppermost scope entry, or 2) the condition values of the biased
2018
    // branches/selects in a scope (including subscopes) don't share at least
2019
    // one common value.
2020
0
    SmallVector<CHRScope *, 8> SplitScopes;
2021
0
    splitScopes(AllScopes, SplitScopes);
2022
0
    CHR_DEBUG(dumpScopes(SplitScopes, "Split scopes"));
2023
2024
    // After splitting, set the biased regions and selects of a scope (a tree
2025
    // root) that include those of the subscopes.
2026
0
    classifyBiasedScopes(SplitScopes);
2027
0
    CHR_DEBUG(dbgs() << "Set per-scope bias " << SplitScopes.size() << "\n");
2028
2029
    // Filter out the scopes that has only one biased region or select (CHR
2030
    // isn't useful in such a case).
2031
0
    SmallVector<CHRScope *, 8> FilteredScopes;
2032
0
    filterScopes(SplitScopes, FilteredScopes);
2033
0
    CHR_DEBUG(dumpScopes(FilteredScopes, "Filtered scopes"));
2034
2035
    // Set the regions to be CHR'ed and their hoist stops for each scope.
2036
0
    SmallVector<CHRScope *, 8> SetScopes;
2037
0
    setCHRRegions(FilteredScopes, SetScopes);
2038
0
    CHR_DEBUG(dumpScopes(SetScopes, "Set CHR regions"));
2039
2040
    // Sort CHRScopes by the depth so that outer CHRScopes comes before inner
2041
    // ones. We need to apply CHR from outer to inner so that we apply CHR only
2042
    // to the hot path, rather than both hot and cold paths.
2043
0
    SmallVector<CHRScope *, 8> SortedScopes;
2044
0
    sortScopes(SetScopes, SortedScopes);
2045
0
    CHR_DEBUG(dumpScopes(SortedScopes, "Sorted scopes"));
2046
2047
0
    CHR_DEBUG(
2048
0
        dbgs() << "RegionInfo:\n";
2049
0
        RI.print(dbgs()));
2050
2051
    // Apply the CHR transformation.
2052
0
    if (!SortedScopes.empty()) {
2053
0
      transformScopes(SortedScopes);
2054
0
      Changed = true;
2055
0
    }
2056
0
  }
2057
2058
0
  if (Changed) {
2059
0
    CHR_DEBUG(dumpIR(F, "after", &Stats));
2060
0
    ORE.emit([&]() {
2061
0
      return OptimizationRemark(DEBUG_TYPE, "Stats", &F)
2062
0
          << ore::NV("Function", &F) << " "
2063
0
          << "Reduced the number of branches in hot paths by "
2064
0
          << ore::NV("NumBranchesDelta", Stats.NumBranchesDelta)
2065
0
          << " (static) and "
2066
0
          << ore::NV("WeightedNumBranchesDelta", Stats.WeightedNumBranchesDelta)
2067
0
          << " (weighted by PGO count)";
2068
0
    });
2069
0
  }
2070
2071
0
  return Changed;
2072
0
}
2073
2074
namespace llvm {
2075
2076
0
ControlHeightReductionPass::ControlHeightReductionPass() {
2077
0
  parseCHRFilterFiles();
2078
0
}
2079
2080
PreservedAnalyses ControlHeightReductionPass::run(
2081
    Function &F,
2082
0
    FunctionAnalysisManager &FAM) {
2083
0
  auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
2084
0
  auto PPSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
2085
  // If there is no profile summary, we should not do CHR.
2086
0
  if (!PPSI || !PPSI->hasProfileSummary())
2087
0
    return PreservedAnalyses::all();
2088
0
  auto &PSI = *PPSI;
2089
0
  auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
2090
0
  auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2091
0
  auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
2092
0
  auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2093
0
  bool Changed = CHR(F, BFI, DT, PSI, RI, ORE).run();
2094
0
  if (!Changed)
2095
0
    return PreservedAnalyses::all();
2096
0
  return PreservedAnalyses::none();
2097
0
}
2098
2099
} // namespace llvm