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