1//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
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 reassociates commutative expressions in an order that is designed
10// to promote better constant propagation, GCSE, LICM, PRE, etc.
11//
12// For example: 4 + (x + 5) -> x + (4 + 5)
13//
14// In the implementation of this algorithm, constants are assigned rank = 0,
15// function arguments are rank = 1, and other values are assigned ranks
16// corresponding to the reverse post order traversal of current function
17// (starting at 2), which effectively gives values in deep loops higher rank
18// than values not in loops.
19//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar/Reassociate.h"
23#include "ScalarOptions.h"
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/BasicAliasAnalysis.h"
33#include "llvm/Analysis/ConstantFolding.h"
34#include "llvm/Analysis/GlobalsModRef.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/IR/Argument.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/Operator.h"
47#include "llvm/IR/PassManager.h"
48#include "llvm/IR/PatternMatch.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/IR/ValueHandle.h"
53#include "llvm/InitializePasses.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Transforms/Scalar.h"
59#include "llvm/Transforms/Utils/Local.h"
60#include <algorithm>
61#include <cassert>
62#include <utility>
63
64using namespace llvm;
65using namespace reassociate;
66using namespace PatternMatch;
67
68#define DEBUG_TYPE "reassociate"
69
70STATISTIC(NumChanged, "Number of insts reassociated");
71STATISTIC(NumAnnihil, "Number of expr tree annihilated");
72STATISTIC(NumFactor , "Number of multiplies factored");
73
74#ifndef NDEBUG
75/// Print out the expression identified in the Ops list.
76static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
77 Module *M = I->getModule();
78 dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
79 << *Ops[0].Op->getType() << '\t';
80 for (const ValueEntry &Op : Ops) {
81 dbgs() << "[ ";
82 Op.Op->printAsOperand(dbgs(), false, M);
83 dbgs() << ", #" << Op.Rank << "] ";
84 }
85}
86#endif
87
88/// Utility class representing a non-constant Xor-operand. We classify
89/// non-constant Xor-Operands into two categories:
90/// C1) The operand is in the form "X & C", where C is a constant and C != ~0
91/// C2)
92/// C2.1) The operand is in the form of "X | C", where C is a non-zero
93/// constant.
94/// C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
95/// operand as "E | 0"
96class llvm::reassociate::XorOpnd {
97public:
98 XorOpnd(Value *V);
99
100 bool isInvalid() const { return SymbolicPart == nullptr; }
101 bool isOrExpr() const { return isOr; }
102 Value *getValue() const { return OrigVal; }
103 Value *getSymbolicPart() const { return SymbolicPart; }
104 unsigned getSymbolicRank() const { return SymbolicRank; }
105 const APInt &getConstPart() const { return ConstPart; }
106
107 void Invalidate() { SymbolicPart = OrigVal = nullptr; }
108 void setSymbolicRank(unsigned R) { SymbolicRank = R; }
109
110private:
111 Value *OrigVal;
112 Value *SymbolicPart;
113 APInt ConstPart;
114 unsigned SymbolicRank;
115 bool isOr;
116};
117
118XorOpnd::XorOpnd(Value *V) {
119 assert(!isa<ConstantInt>(V) && "No ConstantInt");
120 OrigVal = V;
121 Instruction *I = dyn_cast<Instruction>(Val: V);
122 SymbolicRank = 0;
123
124 if (I && (I->getOpcode() == Instruction::Or ||
125 I->getOpcode() == Instruction::And)) {
126 Value *V0 = I->getOperand(i: 0);
127 Value *V1 = I->getOperand(i: 1);
128 const APInt *C;
129 if (match(V: V0, P: m_APInt(Res&: C)))
130 std::swap(a&: V0, b&: V1);
131
132 if (match(V: V1, P: m_APInt(Res&: C))) {
133 ConstPart = *C;
134 SymbolicPart = V0;
135 isOr = (I->getOpcode() == Instruction::Or);
136 return;
137 }
138 }
139
140 // view the operand as "V | 0"
141 SymbolicPart = V;
142 ConstPart = APInt::getZero(numBits: V->getType()->getScalarSizeInBits());
143 isOr = true;
144}
145
146/// Return true if I is an instruction with the FastMathFlags that are needed
147/// for general reassociation set. This is not the same as testing
148/// Instruction::isAssociative() because it includes operations like fsub.
149/// (This routine is only intended to be called for floating-point operations.)
150static bool hasFPAssociativeFlags(Instruction *I) {
151 assert(I && isa<FPMathOperator>(I) && "Should only check FP ops");
152 return I->hasAllowReassoc() && I->hasNoSignedZeros();
153}
154
155/// Return true if V is an instruction of the specified opcode and if it
156/// only has one use.
157static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
158 auto *BO = dyn_cast<BinaryOperator>(Val: V);
159 if (BO && BO->hasOneUse() && BO->getOpcode() == Opcode)
160 if (!isa<FPMathOperator>(Val: BO) || hasFPAssociativeFlags(I: BO))
161 return BO;
162 return nullptr;
163}
164
165static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1,
166 unsigned Opcode2) {
167 auto *BO = dyn_cast<BinaryOperator>(Val: V);
168 if (BO && BO->hasOneUse() &&
169 (BO->getOpcode() == Opcode1 || BO->getOpcode() == Opcode2))
170 if (!isa<FPMathOperator>(Val: BO) || hasFPAssociativeFlags(I: BO))
171 return BO;
172 return nullptr;
173}
174
175/// Return the fmul operand if V is a one-use fadd with a single one-use fmul
176/// operand, both allowing contraction. Such pairs can be fused into a single
177/// fma, so they are kept together as leaves of the enclosing expression tree
178/// instead of being linearized into it.
179///
180/// Do not keep the pair together if the other operand is itself a reassociable
181/// fadd. Treating the outer fadd as a leaf would hide the nested addition from
182/// reassociation and prevent the complete expression from being optimized.
183static BinaryOperator *isFMulAddCandidate(Value *V) {
184 BinaryOperator *FAdd = isReassociableOp(V, Opcode: Instruction::FAdd);
185 if (!FAdd || !FAdd->hasAllowContract())
186 return nullptr;
187 auto ContractableFMul = [](BinaryOperator *&FMul) {
188 return m_CombineAnd(Ps: m_AllowContract(SubPattern: m_OneUse(SubPattern: m_FMul(L: m_Value(), R: m_Value()))),
189 Ps: m_BinOp(I&: FMul));
190 };
191 BinaryOperator *Mul = nullptr;
192 Value *OtherOp = nullptr;
193 // Keep constants, nested additions and other contractible multiplies visible
194 // to the enclosing expression so they can participate in folding,
195 // reassociation and factorization.
196 if (!match(V: FAdd, P: m_c_FAdd(L: ContractableFMul(Mul), R: m_Value(V&: OtherOp))) ||
197 isa<Constant>(Val: OtherOp) || isReassociableOp(V: OtherOp, Opcode: Instruction::FAdd) ||
198 match(V: OtherOp, P: m_AllowContract(SubPattern: m_FMul(L: m_Value(), R: m_Value()))))
199 return nullptr;
200 return Mul;
201}
202
203void ReassociatePass::BuildRankMap(Function &F,
204 ReversePostOrderTraversal<Function*> &RPOT) {
205 unsigned Rank = 2;
206
207 // Assign distinct ranks to function arguments.
208 for (auto &Arg : F.args()) {
209 ValueRankMap[&Arg] = ++Rank;
210 LLVM_DEBUG(dbgs() << "Calculated Rank[" << Arg.getName() << "] = " << Rank
211 << "\n");
212 }
213
214 // Traverse basic blocks in ReversePostOrder.
215 for (BasicBlock *BB : RPOT) {
216 unsigned BBRank = RankMap[BB] = ++Rank << 16;
217
218 // Walk the basic block, adding precomputed ranks for any instructions that
219 // we cannot move. This ensures that the ranks for these instructions are
220 // all different in the block.
221 for (Instruction &I : *BB)
222 if (mayHaveNonDefUseDependency(I))
223 ValueRankMap[&I] = ++BBRank;
224 }
225}
226
227unsigned ReassociatePass::getRank(Value *V) {
228 // Return 1+MAX(rank(LHS), rank(RHS)) for expressions so we can reassociate
229 // expressions for code motion. Use an explicit worklist rather than native
230 // recursion so long acyclic use-def chains do not overflow the stack.
231 struct RankWorkItem {
232 Value *V;
233 unsigned OpNo;
234 unsigned Rank;
235 };
236
237 // Each item is one suspended recursive getRank() call.
238 // Completed ranks are folded back into the parent.
239 SmallVector<RankWorkItem, 16> Worklist;
240 Worklist.push_back(Elt: RankWorkItem{.V: V, .OpNo: 0, .Rank: 0});
241
242 while (true) {
243 RankWorkItem &Item = Worklist.back();
244 Instruction *I = dyn_cast<Instruction>(Val: Item.V);
245 unsigned Rank = 0;
246 if (!I) {
247 // Function argument, global or constant
248 Rank = isa<Argument>(Val: Item.V) ? ValueRankMap[Item.V] : 0;
249 } else if (ValueRankMap[I]) {
250 // Instruction that is not movable.
251 Rank = ValueRankMap[I];
252 } else if (Item.OpNo == I->getNumOperands() ||
253 Item.Rank == RankMap[I->getParent()]) {
254 // All operands were visited or the max block rank was reached.
255 Rank = Item.Rank;
256 // If this is a 'not' or 'neg' instruction, do not count it for rank.
257 // This assures us that X and ~X will have the same rank.
258 if (!match(V: I, P: m_Not(V: m_Value())) && !match(V: I, P: m_Neg(V: m_Value())) &&
259 !match(V: I, P: m_FNeg(X: m_Value())))
260 ++Rank;
261
262 LLVM_DEBUG(dbgs() << "Calculated Rank[" << I->getName() << "] = " << Rank
263 << "\n");
264
265 ValueRankMap[I] = Rank;
266 } else {
267 Worklist.push_back(Elt: RankWorkItem{.V: I->getOperand(i: Item.OpNo), .OpNo: 0, .Rank: 0});
268 continue;
269 }
270
271 // Once the current use-def node has a known rank, carry that rank back to
272 // the parent expression and advance past the operand that led here.
273 Worklist.pop_back();
274 if (Worklist.empty())
275 return Rank;
276
277 RankWorkItem &Parent = Worklist.back();
278 Parent.Rank = std::max(a: Parent.Rank, b: Rank);
279 ++Parent.OpNo;
280 }
281}
282
283// Canonicalize constants to RHS. Otherwise, sort the operands by rank.
284void ReassociatePass::canonicalizeOperands(Instruction *I) {
285 assert(isa<BinaryOperator>(I) && "Expected binary operator.");
286 assert(I->isCommutative() && "Expected commutative operator.");
287
288 Value *LHS = I->getOperand(i: 0);
289 Value *RHS = I->getOperand(i: 1);
290 if (LHS == RHS || isa<Constant>(Val: RHS))
291 return;
292 if (isa<Constant>(Val: LHS) || getRank(V: RHS) < getRank(V: LHS)) {
293 cast<BinaryOperator>(Val: I)->swapOperands();
294 MadeChange = true;
295 }
296}
297
298static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name,
299 BasicBlock::iterator InsertBefore,
300 Value *FlagsOp) {
301 if (S1->getType()->isIntOrIntVectorTy())
302 return BinaryOperator::CreateAdd(V1: S1, V2: S2, Name, InsertBefore);
303 else {
304 BinaryOperator *Res =
305 BinaryOperator::CreateFAdd(V1: S1, V2: S2, Name, InsertBefore);
306 Res->setFastMathFlags(cast<FPMathOperator>(Val: FlagsOp)->getFastMathFlags());
307 return Res;
308 }
309}
310
311static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name,
312 BasicBlock::iterator InsertBefore,
313 Value *FlagsOp) {
314 if (S1->getType()->isIntOrIntVectorTy())
315 return BinaryOperator::CreateMul(V1: S1, V2: S2, Name, InsertBefore);
316 else {
317 BinaryOperator *Res =
318 BinaryOperator::CreateFMul(V1: S1, V2: S2, Name, InsertBefore);
319 Res->setFastMathFlags(cast<FPMathOperator>(Val: FlagsOp)->getFastMathFlags());
320 return Res;
321 }
322}
323
324static Instruction *CreateNeg(Value *S1, const Twine &Name,
325 BasicBlock::iterator InsertBefore,
326 Value *FlagsOp) {
327 if (S1->getType()->isIntOrIntVectorTy())
328 return BinaryOperator::CreateNeg(Op: S1, Name, InsertBefore);
329
330 if (auto *FMFSource = dyn_cast<Instruction>(Val: FlagsOp))
331 return UnaryOperator::CreateFNegFMF(Op: S1, FMFSource, Name, InsertBefore);
332
333 return UnaryOperator::CreateFNeg(V: S1, Name, InsertBefore);
334}
335
336/// Replace 0-X with X*-1.
337static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
338 assert((isa<UnaryOperator>(Neg) || isa<BinaryOperator>(Neg)) &&
339 "Expected a Negate!");
340 // FIXME: It's not safe to lower a unary FNeg into a FMul by -1.0.
341 unsigned OpNo = isa<BinaryOperator>(Val: Neg) ? 1 : 0;
342 Type *Ty = Neg->getType();
343 Constant *NegOne = Ty->isIntOrIntVectorTy() ?
344 ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, V: -1.0);
345
346 BinaryOperator *Res =
347 CreateMul(S1: Neg->getOperand(i: OpNo), S2: NegOne, Name: "", InsertBefore: Neg->getIterator(), FlagsOp: Neg);
348 Neg->setOperand(i: OpNo, Val: Constant::getNullValue(Ty)); // Drop use of op.
349 Res->takeName(V: Neg);
350 Neg->replaceAllUsesWith(V: Res);
351 Res->setDebugLoc(Neg->getDebugLoc());
352 return Res;
353}
354
355using RepeatedValue = std::pair<Value *, uint64_t>;
356
357/// Given an associative binary expression, return the leaf
358/// nodes in Ops along with their weights (how many times the leaf occurs). The
359/// original expression is the same as
360/// (Ops[0].first op Ops[0].first op ... Ops[0].first) <- Ops[0].second times
361/// op
362/// (Ops[1].first op Ops[1].first op ... Ops[1].first) <- Ops[1].second times
363/// op
364/// ...
365/// op
366/// (Ops[N].first op Ops[N].first op ... Ops[N].first) <- Ops[N].second times
367///
368/// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
369///
370/// This routine may modify the function, in which case it returns 'true'. The
371/// changes it makes may well be destructive, changing the value computed by 'I'
372/// to something completely different. Thus if the routine returns 'true' then
373/// you MUST either replace I with a new expression computed from the Ops array,
374/// or use RewriteExprTree to put the values back in.
375///
376/// A leaf node is either not a binary operation of the same kind as the root
377/// node 'I' (i.e. is not a binary operator at all, or is, but with a different
378/// opcode), or is the same kind of binary operator but has a use which either
379/// does not belong to the expression, or does belong to the expression but is
380/// a leaf node. Every leaf node has at least one use that is a non-leaf node
381/// of the expression, while for non-leaf nodes (except for the root 'I') every
382/// use is a non-leaf node of the expression.
383///
384/// For example:
385/// expression graph node names
386///
387/// + | I
388/// / \ |
389/// + + | A, B
390/// / \ / \ |
391/// * + * | C, D, E
392/// / \ / \ / \ |
393/// + * | F, G
394///
395/// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in
396/// that order) (C, 1), (E, 1), (F, 2), (G, 2).
397///
398/// The expression is maximal: if some instruction is a binary operator of the
399/// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
400/// then the instruction also belongs to the expression, is not a leaf node of
401/// it, and its operands also belong to the expression (but may be leaf nodes).
402///
403/// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
404/// order to ensure that every non-root node in the expression has *exactly one*
405/// use by a non-leaf node of the expression. This destruction means that the
406/// caller MUST either replace 'I' with a new expression or use something like
407/// RewriteExprTree to put the values back in if the routine indicates that it
408/// made a change by returning 'true'.
409///
410/// In the above example either the right operand of A or the left operand of B
411/// will be replaced by undef. If it is B's operand then this gives:
412///
413/// + | I
414/// / \ |
415/// + + | A, B - operand of B replaced with undef
416/// / \ \ |
417/// * + * | C, D, E
418/// / \ / \ / \ |
419/// + * | F, G
420///
421/// Note that such undef operands can only be reached by passing through 'I'.
422/// For example, if you visit operands recursively starting from a leaf node
423/// then you will never see such an undef operand unless you get back to 'I',
424/// which requires passing through a phi node.
425///
426/// Note that this routine may also mutate binary operators of the wrong type
427/// that have all uses inside the expression (i.e. only used by non-leaf nodes
428/// of the expression) if it can turn them into binary operators of the right
429/// type and thus make the expression bigger.
430static bool LinearizeExprTree(Instruction *I,
431 SmallVectorImpl<RepeatedValue> &Ops,
432 ReassociatePass::OrderedSet &ToRedo,
433 OverflowTracking &Flags) {
434 assert((isa<UnaryOperator>(I) || isa<BinaryOperator>(I)) &&
435 "Expected a UnaryOperator or BinaryOperator!");
436 LLVM_DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
437 unsigned Opcode = I->getOpcode();
438 assert(I->isAssociative() && I->isCommutative() &&
439 "Expected an associative and commutative operation!");
440
441 // Visit all operands of the expression, keeping track of their weight (the
442 // number of paths from the expression root to the operand, or if you like
443 // the number of times that operand occurs in the linearized expression).
444 // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
445 // while A has weight two.
446
447 // Worklist of non-leaf nodes (their operands are in the expression too) along
448 // with their weights, representing a certain number of paths to the operator.
449 // If an operator occurs in the worklist multiple times then we found multiple
450 // ways to get to it.
451 SmallVector<std::pair<Instruction *, uint64_t>, 8> Worklist; // (Op, Weight)
452 Worklist.push_back(Elt: std::make_pair(x&: I, y: 1));
453 bool Changed = false;
454
455 // Leaves of the expression are values that either aren't the right kind of
456 // operation (eg: a constant, or a multiply in an add tree), or are, but have
457 // some uses that are not inside the expression. For example, in I = X + X,
458 // X = A + B, the value X has two uses (by I) that are in the expression. If
459 // X has any other uses, for example in a return instruction, then we consider
460 // X to be a leaf, and won't analyze it further. When we first visit a value,
461 // if it has more than one use then at first we conservatively consider it to
462 // be a leaf. Later, as the expression is explored, we may discover some more
463 // uses of the value from inside the expression. If all uses turn out to be
464 // from within the expression (and the value is a binary operator of the right
465 // kind) then the value is no longer considered to be a leaf, and its operands
466 // are explored.
467
468 // Leaves - Keeps track of the set of putative leaves as well as the number of
469 // paths to each leaf seen so far.
470 using LeafMap = DenseMap<Value *, uint64_t>;
471 LeafMap Leaves; // Leaf -> Total weight so far.
472 SmallVector<Value *, 8> LeafOrder; // Ensure deterministic leaf output order.
473 const DataLayout &DL = I->getDataLayout();
474
475#ifndef NDEBUG
476 SmallPtrSet<Value *, 8> Visited; // For checking the iteration scheme.
477#endif
478 while (!Worklist.empty()) {
479 // We examine the operands of this binary operator.
480 auto [I, Weight] = Worklist.pop_back_val();
481
482 Flags.mergeFlags(I&: *I);
483
484 for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); ++OpIdx) { // Visit operands.
485 Value *Op = I->getOperand(i: OpIdx);
486 LLVM_DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
487 assert((!Op->hasUseList() || !Op->use_empty()) &&
488 "No uses, so how did we get to it?!");
489
490 // If this is a binary operation of the right kind with only one use then
491 // add its operands to the expression.
492 if (BinaryOperator *BO = isReassociableOp(V: Op, Opcode);
493 BO && (Opcode != Instruction::FAdd || !isFMulAddCandidate(V: BO))) {
494 assert(Visited.insert(Op).second && "Not first visit!");
495 LLVM_DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
496 Worklist.push_back(Elt: std::make_pair(x&: BO, y&: Weight));
497 continue;
498 }
499
500 // Appears to be a leaf. Is the operand already in the set of leaves?
501 LeafMap::iterator It = Leaves.find(Val: Op);
502 if (It == Leaves.end()) {
503 // Not in the leaf map. Must be the first time we saw this operand.
504 assert(Visited.insert(Op).second && "Not first visit!");
505 if (!Op->hasOneUse()) {
506 // This value has uses not accounted for by the expression, so it is
507 // not safe to modify. Mark it as being a leaf.
508 LLVM_DEBUG(dbgs()
509 << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
510 LeafOrder.push_back(Elt: Op);
511 Leaves[Op] = Weight;
512 continue;
513 }
514 // No uses outside the expression, try morphing it.
515 } else {
516 // Already in the leaf map.
517 assert(It != Leaves.end() && Visited.count(Op) &&
518 "In leaf map but not visited!");
519
520 // Update the number of paths to the leaf.
521 It->second += Weight;
522 assert(It->second >= Weight && "Weight overflows");
523
524 // If we still have uses that are not accounted for by the expression
525 // then it is not safe to modify the value.
526 if (!Op->hasOneUse())
527 continue;
528
529 // No uses outside the expression, try morphing it.
530 Weight = It->second;
531 Leaves.erase(I: It); // Since the value may be morphed below.
532 }
533
534 // At this point we have a value which, first of all, is not a binary
535 // expression of the right kind, and secondly, is only used inside the
536 // expression. This means that it can safely be modified. See if we
537 // can usefully morph it into an expression of the right kind.
538 assert((!isa<Instruction>(Op) ||
539 cast<Instruction>(Op)->getOpcode() != Opcode ||
540 (isa<FPMathOperator>(Op) &&
541 !hasFPAssociativeFlags(cast<Instruction>(Op))) ||
542 isFMulAddCandidate(Op)) &&
543 "Should have been handled above!");
544 assert(Op->hasOneUse() && "Has uses outside the expression tree!");
545
546 // If this is a multiply expression, turn any internal negations into
547 // multiplies by -1 so they can be reassociated. Add any users of the
548 // newly created multiplication by -1 to the redo list, so any
549 // reassociation opportunities that are exposed will be reassociated
550 // further.
551 Instruction *Neg;
552 if (((Opcode == Instruction::Mul && match(V: Op, P: m_Neg(V: m_Value()))) ||
553 (Opcode == Instruction::FMul && match(V: Op, P: m_FNeg(X: m_Value())))) &&
554 match(V: Op, P: m_Instruction(I&: Neg))) {
555 LLVM_DEBUG(dbgs()
556 << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
557 Instruction *Mul = LowerNegateToMultiply(Neg);
558 LLVM_DEBUG(dbgs() << *Mul << '\n');
559 Worklist.push_back(Elt: std::make_pair(x&: Mul, y&: Weight));
560 for (User *U : Mul->users()) {
561 if (BinaryOperator *UserBO = dyn_cast<BinaryOperator>(Val: U))
562 ToRedo.insert(X: UserBO);
563 }
564 ToRedo.insert(X: Neg);
565 Changed = true;
566 continue;
567 }
568
569 // Failed to morph into an expression of the right type. This really is
570 // a leaf.
571 LLVM_DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
572 assert((!isReassociableOp(Op, Opcode) || isFMulAddCandidate(Op)) &&
573 "Value was morphed?");
574 LeafOrder.push_back(Elt: Op);
575 Leaves[Op] = Weight;
576 }
577 }
578
579 // The leaves, repeated according to their weights, represent the linearized
580 // form of the expression.
581 for (Value *V : LeafOrder) {
582 LeafMap::iterator It = Leaves.find(Val: V);
583 if (It == Leaves.end())
584 // Node initially thought to be a leaf wasn't.
585 continue;
586 assert((!isReassociableOp(V, Opcode) || isFMulAddCandidate(V)) &&
587 "Shouldn't be a leaf!");
588 uint64_t Weight = It->second;
589 // Ensure the leaf is only output once.
590 It->second = 0;
591 Ops.push_back(Elt: std::make_pair(x&: V, y&: Weight));
592 if (Opcode == Instruction::Add && Flags.AllKnownNonNegative && Flags.HasNSW)
593 Flags.AllKnownNonNegative &= isKnownNonNegative(V, SQ: SimplifyQuery(DL));
594 else if (Opcode == Instruction::Mul) {
595 // To preserve NUW we need all inputs non-zero.
596 // To preserve NSW we need all inputs strictly positive.
597 if (Flags.AllKnownNonZero &&
598 (Flags.HasNUW || (Flags.HasNSW && Flags.AllKnownNonNegative))) {
599 Flags.AllKnownNonZero &= isKnownNonZero(V, Q: SimplifyQuery(DL));
600 if (Flags.HasNSW && Flags.AllKnownNonNegative)
601 Flags.AllKnownNonNegative &= isKnownNonNegative(V, SQ: SimplifyQuery(DL));
602 }
603 }
604 }
605
606 // For nilpotent operations or addition there may be no operands, for example
607 // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
608 // in both cases the weight reduces to 0 causing the value to be skipped.
609 if (Ops.empty()) {
610 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, Ty: I->getType());
611 assert(Identity && "Associative operation without identity!");
612 Ops.emplace_back(Args&: Identity, Args: 1);
613 }
614
615 return Changed;
616}
617
618/// Now that the operands for this expression tree are
619/// linearized and optimized, emit them in-order.
620void ReassociatePass::RewriteExprTree(BinaryOperator *I,
621 SmallVectorImpl<ValueEntry> &Ops,
622 OverflowTracking Flags) {
623 assert(Ops.size() > 1 && "Single values should be used directly!");
624
625 // Since our optimizations should never increase the number of operations, the
626 // new expression can usually be written reusing the existing binary operators
627 // from the original expression tree, without creating any new instructions,
628 // though the rewritten expression may have a completely different topology.
629 // We take care to not change anything if the new expression will be the same
630 // as the original. If more than trivial changes (like commuting operands)
631 // were made then we are obliged to clear out any optional subclass data like
632 // nsw flags.
633
634 /// NodesToRewrite - Nodes from the original expression available for writing
635 /// the new expression into.
636 SmallVector<BinaryOperator*, 8> NodesToRewrite;
637 unsigned Opcode = I->getOpcode();
638 BinaryOperator *Op = I;
639
640 /// NotRewritable - The operands being written will be the leaves of the new
641 /// expression and must not be used as inner nodes (via NodesToRewrite) by
642 /// mistake. Inner nodes are always reassociable, and usually leaves are not
643 /// (if they were they would have been incorporated into the expression and so
644 /// would not be leaves), so most of the time there is no danger of this. But
645 /// in rare cases a leaf may become reassociable if an optimization kills uses
646 /// of it, or it may momentarily become reassociable during rewriting (below)
647 /// due it being removed as an operand of one of its uses. Ensure that misuse
648 /// of leaf nodes as inner nodes cannot occur by remembering all of the future
649 /// leaves and refusing to reuse any of them as inner nodes.
650 SmallPtrSet<Value*, 8> NotRewritable;
651 for (const ValueEntry &Op : Ops)
652 NotRewritable.insert(Ptr: Op.Op);
653
654 // ExpressionChangedStart - Non-null if the rewritten expression differs from
655 // the original in some non-trivial way, requiring the clearing of optional
656 // flags. Flags are cleared from the operator in ExpressionChangedStart up to
657 // ExpressionChangedEnd inclusive.
658 BinaryOperator *ExpressionChangedStart = nullptr,
659 *ExpressionChangedEnd = nullptr;
660 for (unsigned i = 0; ; ++i) {
661 // The last operation (which comes earliest in the IR) is special as both
662 // operands will come from Ops, rather than just one with the other being
663 // a subexpression.
664 if (i+2 == Ops.size()) {
665 Value *NewLHS = Ops[i].Op;
666 Value *NewRHS = Ops[i+1].Op;
667 Value *OldLHS = Op->getOperand(i_nocapture: 0);
668 Value *OldRHS = Op->getOperand(i_nocapture: 1);
669
670 if (NewLHS == OldLHS && NewRHS == OldRHS)
671 // Nothing changed, leave it alone.
672 break;
673
674 if (NewLHS == OldRHS && NewRHS == OldLHS) {
675 // The order of the operands was reversed. Swap them.
676 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
677 Op->swapOperands();
678 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
679 MadeChange = true;
680 ++NumChanged;
681 break;
682 }
683
684 // The new operation differs non-trivially from the original. Overwrite
685 // the old operands with the new ones.
686 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
687 if (NewLHS != OldLHS) {
688 BinaryOperator *BO = isReassociableOp(V: OldLHS, Opcode);
689 if (BO && !NotRewritable.count(Ptr: BO))
690 NodesToRewrite.push_back(Elt: BO);
691 salvageDebugInfo(I&: *Op);
692 Op->setOperand(i_nocapture: 0, Val_nocapture: NewLHS);
693 }
694 if (NewRHS != OldRHS) {
695 BinaryOperator *BO = isReassociableOp(V: OldRHS, Opcode);
696 if (BO && !NotRewritable.count(Ptr: BO))
697 NodesToRewrite.push_back(Elt: BO);
698 salvageDebugInfo(I&: *Op);
699 Op->setOperand(i_nocapture: 1, Val_nocapture: NewRHS);
700 }
701 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
702
703 ExpressionChangedStart = Op;
704 if (!ExpressionChangedEnd)
705 ExpressionChangedEnd = Op;
706 MadeChange = true;
707 ++NumChanged;
708
709 break;
710 }
711
712 // Not the last operation. The left-hand side will be a sub-expression
713 // while the right-hand side will be the current element of Ops.
714 Value *NewRHS = Ops[i].Op;
715 if (NewRHS != Op->getOperand(i_nocapture: 1)) {
716 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
717 if (NewRHS == Op->getOperand(i_nocapture: 0)) {
718 // The new right-hand side was already present as the left operand. If
719 // we are lucky then swapping the operands will sort out both of them.
720 Op->swapOperands();
721 } else {
722 // Overwrite with the new right-hand side.
723 BinaryOperator *BO = isReassociableOp(V: Op->getOperand(i_nocapture: 1), Opcode);
724 if (BO && !NotRewritable.count(Ptr: BO))
725 NodesToRewrite.push_back(Elt: BO);
726 salvageDebugInfo(I&: *Op);
727 Op->setOperand(i_nocapture: 1, Val_nocapture: NewRHS);
728 ExpressionChangedStart = Op;
729 if (!ExpressionChangedEnd)
730 ExpressionChangedEnd = Op;
731 }
732 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
733 MadeChange = true;
734 ++NumChanged;
735 }
736
737 // Now deal with the left-hand side. If this is already an operation node
738 // from the original expression then just rewrite the rest of the expression
739 // into it.
740 BinaryOperator *BO = isReassociableOp(V: Op->getOperand(i_nocapture: 0), Opcode);
741 if (BO && !NotRewritable.count(Ptr: BO)) {
742 Op = BO;
743 continue;
744 }
745
746 // Otherwise, grab a spare node from the original expression and use that as
747 // the left-hand side. If there are no nodes left then the optimizers made
748 // an expression with more nodes than the original! This usually means that
749 // they did something stupid but it might mean that the problem was just too
750 // hard (finding the mimimal number of multiplications needed to realize a
751 // multiplication expression is NP-complete). Whatever the reason, smart or
752 // stupid, create a new node if there are none left.
753 BinaryOperator *NewOp;
754 if (NodesToRewrite.empty()) {
755 Constant *Poison = PoisonValue::get(T: I->getType());
756 NewOp = BinaryOperator::Create(Op: Instruction::BinaryOps(Opcode), S1: Poison,
757 S2: Poison, Name: "", InsertBefore: I->getIterator());
758 if (isa<FPMathOperator>(Val: NewOp))
759 NewOp->setFastMathFlags(I->getFastMathFlags());
760 } else {
761 NewOp = NodesToRewrite.pop_back_val();
762 }
763
764 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
765 salvageDebugInfo(I&: *Op);
766 Op->setOperand(i_nocapture: 0, Val_nocapture: NewOp);
767 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
768 ExpressionChangedStart = Op;
769 if (!ExpressionChangedEnd)
770 ExpressionChangedEnd = Op;
771 MadeChange = true;
772 ++NumChanged;
773 Op = NewOp;
774 }
775
776 // If the expression changed non-trivially then clear out all subclass data
777 // starting from the operator specified in ExpressionChanged, and compactify
778 // the operators to just before the expression root to guarantee that the
779 // expression tree is dominated by all of Ops.
780 if (ExpressionChangedStart) {
781 bool ClearFlags = true;
782 do {
783 // Preserve flags.
784 if (ClearFlags) {
785 if (isa<FPMathOperator>(Val: I)) {
786 ExpressionChangedStart->copyFastMathFlags(FMF: I->getFastMathFlags());
787 } else {
788 Flags.applyFlags(I&: *ExpressionChangedStart);
789 }
790 }
791
792 if (ExpressionChangedStart == ExpressionChangedEnd)
793 ClearFlags = false;
794 if (ExpressionChangedStart == I)
795 break;
796
797 ExpressionChangedStart->moveBefore(InsertPos: I->getIterator());
798 ExpressionChangedStart =
799 cast<BinaryOperator>(Val: *ExpressionChangedStart->user_begin());
800 } while (true);
801 }
802
803 // Throw away any left over nodes from the original expression.
804 RedoInsts.insert_range(R&: NodesToRewrite);
805}
806
807/// Insert instructions before the instruction pointed to by BI,
808/// that computes the negative version of the value specified. The negative
809/// version of the value is returned, and BI is left pointing at the instruction
810/// that should be processed next by the reassociation pass.
811/// Also add intermediate instructions to the redo list that are modified while
812/// pushing the negates through adds. These will be revisited to see if
813/// additional opportunities have been exposed.
814static Value *NegateValue(Value *V, Instruction *BI,
815 ReassociatePass::OrderedSet &ToRedo) {
816 if (auto *C = dyn_cast<Constant>(Val: V)) {
817 const DataLayout &DL = BI->getDataLayout();
818 Constant *Res = C->getType()->isFPOrFPVectorTy()
819 ? ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)
820 : ConstantExpr::getNeg(C);
821 if (Res)
822 return Res;
823 }
824
825 // We are trying to expose opportunity for reassociation. One of the things
826 // that we want to do to achieve this is to push a negation as deep into an
827 // expression chain as possible, to expose the add instructions. In practice,
828 // this means that we turn this:
829 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
830 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
831 // the constants. We assume that instcombine will clean up the mess later if
832 // we introduce tons of unnecessary negation instructions.
833 //
834 if (BinaryOperator *I =
835 isReassociableOp(V, Opcode1: Instruction::Add, Opcode2: Instruction::FAdd)) {
836 // Push the negates through the add.
837 I->setOperand(i_nocapture: 0, Val_nocapture: NegateValue(V: I->getOperand(i_nocapture: 0), BI, ToRedo));
838 I->setOperand(i_nocapture: 1, Val_nocapture: NegateValue(V: I->getOperand(i_nocapture: 1), BI, ToRedo));
839 if (I->getOpcode() == Instruction::Add) {
840 I->setHasNoUnsignedWrap(false);
841 I->setHasNoSignedWrap(false);
842 }
843
844 // We must move the add instruction here, because the neg instructions do
845 // not dominate the old add instruction in general. By moving it, we are
846 // assured that the neg instructions we just inserted dominate the
847 // instruction we are about to insert after them.
848 //
849 I->moveBefore(InsertPos: BI->getIterator());
850 I->setName(I->getName()+".neg");
851
852 // Add the intermediate negates to the redo list as processing them later
853 // could expose more reassociating opportunities.
854 ToRedo.insert(X: I);
855 return I;
856 }
857
858 // Okay, we need to materialize a negated version of V with an instruction.
859 // Scan the use lists of V to see if we have one already.
860 for (User *U : V->users()) {
861 if (!match(V: U, P: m_Neg(V: m_Value())) && !match(V: U, P: m_FNeg(X: m_Value())))
862 continue;
863
864 // We found one! Now we have to make sure that the definition dominates
865 // this use. We do this by moving it to the entry block (if it is a
866 // non-instruction value) or right after the definition. These negates will
867 // be zapped by reassociate later, so we don't need much finesse here.
868 Instruction *TheNeg = dyn_cast<Instruction>(Val: U);
869
870 // We can't safely propagate a vector zero constant with poison/undef lanes.
871 Constant *C;
872 if (match(V: TheNeg, P: m_BinOp(L: m_Constant(C), R: m_Value())) &&
873 C->containsUndefOrPoisonElement())
874 continue;
875
876 // Verify that the negate is in this function, V might be a constant expr.
877 if (!TheNeg ||
878 TheNeg->getParent()->getParent() != BI->getParent()->getParent())
879 continue;
880
881 BasicBlock::iterator InsertPt;
882 if (Instruction *InstInput = dyn_cast<Instruction>(Val: V)) {
883 auto InsertPtOpt = InstInput->getInsertionPointAfterDef();
884 if (!InsertPtOpt)
885 continue;
886 InsertPt = *InsertPtOpt;
887 } else {
888 InsertPt = TheNeg->getFunction()
889 ->getEntryBlock()
890 .getFirstNonPHIOrDbg()
891 ->getIterator();
892 }
893
894 // Check that if TheNeg is moved out of its parent block, we drop its
895 // debug location to avoid extra coverage.
896 // See test dropping_debugloc_the_neg.ll for a detailed example.
897 if (TheNeg->getParent() != InsertPt->getParent())
898 TheNeg->dropLocation();
899 TheNeg->moveBefore(BB&: *InsertPt->getParent(), I: InsertPt);
900
901 if (TheNeg->getOpcode() == Instruction::Sub) {
902 TheNeg->setHasNoUnsignedWrap(false);
903 TheNeg->setHasNoSignedWrap(false);
904 } else {
905 TheNeg->andIRFlags(V: BI);
906 }
907 ToRedo.insert(X: TheNeg);
908 return TheNeg;
909 }
910
911 // Insert a 'neg' instruction that subtracts the value from zero to get the
912 // negation.
913 Instruction *NewNeg =
914 CreateNeg(S1: V, Name: V->getName() + ".neg", InsertBefore: BI->getIterator(), FlagsOp: BI);
915 // NewNeg is generated to potentially replace BI, so use its DebugLoc.
916 NewNeg->setDebugLoc(BI->getDebugLoc());
917 ToRedo.insert(X: NewNeg);
918 return NewNeg;
919}
920
921// See if this `or` looks like an load widening reduction, i.e. that it
922// consists of an `or`/`shl`/`zext`/`load` nodes only. Note that we don't
923// ensure that the pattern is *really* a load widening reduction,
924// we do not ensure that it can really be replaced with a widened load,
925// only that it mostly looks like one.
926static bool isLoadCombineCandidate(Instruction *Or) {
927 SmallVector<Instruction *, 8> Worklist;
928 SmallPtrSet<Instruction *, 8> Visited;
929
930 auto Enqueue = [&](Value *V) {
931 auto *I = dyn_cast<Instruction>(Val: V);
932 // Each node of an `or` reduction must be an instruction,
933 if (!I)
934 return false; // Node is certainly not part of an `or` load reduction.
935 // Only process instructions we have never processed before.
936 if (Visited.insert(Ptr: I).second)
937 Worklist.emplace_back(Args&: I);
938 return true; // Will need to look at parent nodes.
939 };
940
941 if (!Enqueue(Or))
942 return false; // Not an `or` reduction pattern.
943
944 while (!Worklist.empty()) {
945 auto *I = Worklist.pop_back_val();
946
947 // Okay, which instruction is this node?
948 switch (I->getOpcode()) {
949 case Instruction::Or:
950 // Got an `or` node. That's fine, just recurse into it's operands.
951 for (Value *Op : I->operands())
952 if (!Enqueue(Op))
953 return false; // Not an `or` reduction pattern.
954 continue;
955
956 case Instruction::Shl:
957 case Instruction::ZExt:
958 // `shl`/`zext` nodes are fine, just recurse into their base operand.
959 if (!Enqueue(I->getOperand(i: 0)))
960 return false; // Not an `or` reduction pattern.
961 continue;
962
963 case Instruction::Load:
964 // Perfect, `load` node means we've reached an edge of the graph.
965 continue;
966
967 default: // Unknown node.
968 return false; // Not an `or` reduction pattern.
969 }
970 }
971
972 return true;
973}
974
975/// Return true if it may be profitable to convert this (X|Y) into (X+Y).
976static bool shouldConvertOrWithNoCommonBitsToAdd(Instruction *Or) {
977 // Don't bother to convert this up unless either the LHS is an associable add
978 // or subtract or mul or if this is only used by one of the above.
979 // This is only a compile-time improvement, it is not needed for correctness!
980 auto isInteresting = [](Value *V) {
981 for (auto Op : {Instruction::Add, Instruction::Sub, Instruction::Mul,
982 Instruction::Shl})
983 if (isReassociableOp(V, Opcode: Op))
984 return true;
985 return false;
986 };
987
988 if (any_of(Range: Or->operands(), P: isInteresting))
989 return true;
990
991 Value *VB = Or->user_back();
992 if (Or->hasOneUse() && isInteresting(VB))
993 return true;
994
995 return false;
996}
997
998/// If we have (X|Y), and iff X and Y have no common bits set,
999/// transform this into (X+Y) to allow arithmetics reassociation.
1000static BinaryOperator *convertOrWithNoCommonBitsToAdd(Instruction *Or) {
1001 // Convert an or into an add.
1002 BinaryOperator *New = CreateAdd(S1: Or->getOperand(i: 0), S2: Or->getOperand(i: 1), Name: "",
1003 InsertBefore: Or->getIterator(), FlagsOp: Or);
1004 New->setHasNoSignedWrap();
1005 New->setHasNoUnsignedWrap();
1006 New->takeName(V: Or);
1007
1008 // Everyone now refers to the add instruction.
1009 Or->replaceAllUsesWith(V: New);
1010 New->setDebugLoc(Or->getDebugLoc());
1011
1012 LLVM_DEBUG(dbgs() << "Converted or into an add: " << *New << '\n');
1013 return New;
1014}
1015
1016/// Return true if Mul is of the form (X+Y)*C or (X-Y)*C where C is a
1017/// constant, and there exists a sibling instruction of the form X*C' or Y*C'
1018/// in the same expression — indicating that distribution followed by
1019/// factoring will reduce the instruction count.
1020static bool ShouldBreakUpDistribution(Instruction *Mul) {
1021 Value *A, *B;
1022 if (!match(V: Mul, P: m_OneUse(SubPattern: m_Mul(
1023 L: m_OneUse(SubPattern: m_CombineOr(Ps: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)),
1024 Ps: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)))),
1025 R: m_ImmConstant()))))
1026 return false;
1027
1028 auto *MulUser = cast<Instruction>(Val: Mul->user_back());
1029 // The parent MUST be an Add or Sub to ensure the tree is flattened
1030 if (MulUser->getOpcode() != Instruction::Add &&
1031 MulUser->getOpcode() != Instruction::Sub)
1032 return false;
1033
1034 for (Value *Sibling : MulUser->operands()) {
1035 if (Sibling == Mul || !Sibling->hasOneUse())
1036 continue;
1037
1038 // Sibling must be NonConst * C'.
1039 Value *SibNC;
1040 if (match(V: Sibling, P: m_Mul(L: m_Value(V&: SibNC), R: m_ImmConstant())) &&
1041 (SibNC == A || SibNC == B) && !isa<Constant>(Val: SibNC))
1042 return true;
1043 }
1044 return false;
1045}
1046
1047/// Distribute Mul of the form (X+Y)*C into X*C + Y*C.
1048/// For the sub case (X-Y)*C, the second term uses -C to avoid
1049/// introducing a negation instruction.
1050static BinaryOperator *BreakUpDistribute(Instruction *Mul,
1051 ReassociatePass::OrderedSet &ToRedo) {
1052 Instruction *AddSub = cast<Instruction>(Val: Mul->getOperand(i: 0));
1053 Constant *C = cast<Constant>(Val: Mul->getOperand(i: 1));
1054 Constant *C2 =
1055 AddSub->getOpcode() == Instruction::Sub ? ConstantExpr::getNeg(C) : C;
1056
1057 BinaryOperator *M1 = BinaryOperator::CreateMul(V1: AddSub->getOperand(i: 0), V2: C,
1058 Name: "Mul1", InsertBefore: Mul->getIterator());
1059 BinaryOperator *M2 = BinaryOperator::CreateMul(V1: AddSub->getOperand(i: 1), V2: C2,
1060 Name: "Mul2", InsertBefore: Mul->getIterator());
1061 BinaryOperator *Result =
1062 BinaryOperator::CreateAdd(V1: M1, V2: M2, Name: "DistAdd", InsertBefore: Mul->getIterator());
1063
1064 Mul->replaceAllUsesWith(V: Result);
1065 Result->setDebugLoc(Mul->getDebugLoc());
1066
1067 ToRedo.insert(X: M1);
1068 ToRedo.insert(X: M2);
1069 ToRedo.insert(X: Result);
1070
1071 return Result;
1072}
1073
1074/// Return true if we should break up this subtract of X-Y into (X + -Y).
1075static bool ShouldBreakUpSubtract(Instruction *Sub) {
1076 // If this is a negation, we can't split it up!
1077 if (match(V: Sub, P: m_Neg(V: m_Value())) || match(V: Sub, P: m_FNeg(X: m_Value())))
1078 return false;
1079
1080 // Don't breakup X - undef.
1081 if (isa<UndefValue>(Val: Sub->getOperand(i: 1)))
1082 return false;
1083
1084 // Don't bother to break this up unless either the LHS is an associable add or
1085 // subtract or if this is only used by one.
1086 Value *V0 = Sub->getOperand(i: 0);
1087 if (isReassociableOp(V: V0, Opcode1: Instruction::Add, Opcode2: Instruction::FAdd) ||
1088 isReassociableOp(V: V0, Opcode1: Instruction::Sub, Opcode2: Instruction::FSub))
1089 return true;
1090 Value *V1 = Sub->getOperand(i: 1);
1091 if (isReassociableOp(V: V1, Opcode1: Instruction::Add, Opcode2: Instruction::FAdd) ||
1092 isReassociableOp(V: V1, Opcode1: Instruction::Sub, Opcode2: Instruction::FSub))
1093 return true;
1094 Value *VB = Sub->user_back();
1095 if (Sub->hasOneUse() &&
1096 (isReassociableOp(V: VB, Opcode1: Instruction::Add, Opcode2: Instruction::FAdd) ||
1097 isReassociableOp(V: VB, Opcode1: Instruction::Sub, Opcode2: Instruction::FSub)))
1098 return true;
1099
1100 return false;
1101}
1102
1103/// If we have (X-Y), and if either X is an add, or if this is only used by an
1104/// add, transform this into (X+(0-Y)) to promote better reassociation.
1105static BinaryOperator *BreakUpSubtract(Instruction *Sub,
1106 ReassociatePass::OrderedSet &ToRedo) {
1107 // Convert a subtract into an add and a neg instruction. This allows sub
1108 // instructions to be commuted with other add instructions.
1109 //
1110 // Calculate the negative value of Operand 1 of the sub instruction,
1111 // and set it as the RHS of the add instruction we just made.
1112 Value *NegVal = NegateValue(V: Sub->getOperand(i: 1), BI: Sub, ToRedo);
1113 BinaryOperator *New =
1114 CreateAdd(S1: Sub->getOperand(i: 0), S2: NegVal, Name: "", InsertBefore: Sub->getIterator(), FlagsOp: Sub);
1115 Sub->setOperand(i: 0, Val: Constant::getNullValue(Ty: Sub->getType())); // Drop use of op.
1116 Sub->setOperand(i: 1, Val: Constant::getNullValue(Ty: Sub->getType())); // Drop use of op.
1117 New->takeName(V: Sub);
1118
1119 // Everyone now refers to the add instruction.
1120 Sub->replaceAllUsesWith(V: New);
1121 New->setDebugLoc(Sub->getDebugLoc());
1122
1123 LLVM_DEBUG(dbgs() << "Negated: " << *New << '\n');
1124 return New;
1125}
1126
1127/// If this is a shift of a reassociable multiply or is used by one, change
1128/// this into a multiply by a constant to assist with further reassociation.
1129static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
1130 Constant *MulCst = ConstantInt::get(Ty: Shl->getType(), V: 1);
1131 auto *SA = cast<ConstantInt>(Val: Shl->getOperand(i: 1));
1132 MulCst = ConstantFoldBinaryInstruction(Opcode: Instruction::Shl, V1: MulCst, V2: SA);
1133 assert(MulCst && "Constant folding of immediate constants failed");
1134
1135 BinaryOperator *Mul = BinaryOperator::CreateMul(V1: Shl->getOperand(i: 0), V2: MulCst,
1136 Name: "", InsertBefore: Shl->getIterator());
1137 Shl->setOperand(i: 0, Val: PoisonValue::get(T: Shl->getType())); // Drop use of op.
1138 Mul->takeName(V: Shl);
1139
1140 // Everyone now refers to the mul instruction.
1141 Shl->replaceAllUsesWith(V: Mul);
1142 Mul->setDebugLoc(Shl->getDebugLoc());
1143
1144 // We can safely preserve the nuw flag in all cases. It's also safe to turn a
1145 // nuw nsw shl into a nuw nsw mul. However, nsw in isolation requires special
1146 // handling. It can be preserved as long as we're not left shifting by
1147 // bitwidth - 1.
1148 bool NSW = cast<BinaryOperator>(Val: Shl)->hasNoSignedWrap();
1149 bool NUW = cast<BinaryOperator>(Val: Shl)->hasNoUnsignedWrap();
1150 unsigned BitWidth = Shl->getType()->getScalarSizeInBits();
1151 if (NSW && (NUW || SA->getValue().ult(RHS: BitWidth - 1)))
1152 Mul->setHasNoSignedWrap(true);
1153 Mul->setHasNoUnsignedWrap(NUW);
1154 return Mul;
1155}
1156
1157/// Scan backwards and forwards among values with the same rank as element i
1158/// to see if X exists. If X does not exist, return i. This is useful when
1159/// scanning for 'x' when we see '-x' because they both get the same rank.
1160static unsigned FindInOperandList(const SmallVectorImpl<ValueEntry> &Ops,
1161 unsigned i, Value *X) {
1162 unsigned XRank = Ops[i].Rank;
1163 unsigned e = Ops.size();
1164 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
1165 if (Ops[j].Op == X)
1166 return j;
1167 if (Instruction *I1 = dyn_cast<Instruction>(Val: Ops[j].Op))
1168 if (Instruction *I2 = dyn_cast<Instruction>(Val: X))
1169 if (I1->isIdenticalTo(I: I2))
1170 return j;
1171 }
1172 // Scan backwards.
1173 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
1174 if (Ops[j].Op == X)
1175 return j;
1176 if (Instruction *I1 = dyn_cast<Instruction>(Val: Ops[j].Op))
1177 if (Instruction *I2 = dyn_cast<Instruction>(Val: X))
1178 if (I1->isIdenticalTo(I: I2))
1179 return j;
1180 }
1181 return i;
1182}
1183
1184/// Emit a tree of add instructions, summing Ops together
1185/// and returning the result. Insert the tree before I.
1186static Value *EmitAddTreeOfValues(Instruction *I,
1187 SmallVectorImpl<WeakTrackingVH> &Ops) {
1188 if (Ops.size() == 1) return Ops.back();
1189
1190 Value *V1 = Ops.pop_back_val();
1191 Value *V2 = EmitAddTreeOfValues(I, Ops);
1192 auto *NewAdd = CreateAdd(S1: V2, S2: V1, Name: "reass.add", InsertBefore: I->getIterator(), FlagsOp: I);
1193 NewAdd->setDebugLoc(I->getDebugLoc());
1194 return NewAdd;
1195}
1196
1197/// If V is an expression tree that is a multiplication sequence,
1198/// and if this sequence contains a multiply by Factor,
1199/// remove Factor from the tree and return the new tree.
1200/// If new instructions are inserted to generate this tree, DL should be used
1201/// as the DebugLoc for these instructions.
1202Value *ReassociatePass::RemoveFactorFromExpression(Value *V, Value *Factor,
1203 DebugLoc DL) {
1204 BinaryOperator *BO = isReassociableOp(V, Opcode1: Instruction::Mul, Opcode2: Instruction::FMul);
1205 if (!BO)
1206 return nullptr;
1207
1208 SmallVector<RepeatedValue, 8> Tree;
1209 OverflowTracking Flags;
1210 MadeChange |= LinearizeExprTree(I: BO, Ops&: Tree, ToRedo&: RedoInsts, Flags);
1211 SmallVector<ValueEntry, 8> Factors;
1212 Factors.reserve(N: Tree.size());
1213 for (const RepeatedValue &E : Tree)
1214 Factors.append(NumInputs: E.second, Elt: ValueEntry(getRank(V: E.first), E.first));
1215
1216 bool FoundFactor = false;
1217 bool NeedsNegate = false;
1218 for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1219 if (Factors[i].Op == Factor) {
1220 FoundFactor = true;
1221 Factors.erase(CI: Factors.begin()+i);
1222 break;
1223 }
1224
1225 // If this is a negative version of this factor, remove it.
1226 if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Val: Factor)) {
1227 if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Val: Factors[i].Op))
1228 if (FC1->getValue() == -FC2->getValue()) {
1229 FoundFactor = NeedsNegate = true;
1230 Factors.erase(CI: Factors.begin()+i);
1231 break;
1232 }
1233 } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Val: Factor)) {
1234 if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Val: Factors[i].Op)) {
1235 const APFloat &F1 = FC1->getValueAPF();
1236 APFloat F2(FC2->getValueAPF());
1237 F2.changeSign();
1238 if (F1 == F2) {
1239 FoundFactor = NeedsNegate = true;
1240 Factors.erase(CI: Factors.begin() + i);
1241 break;
1242 }
1243 }
1244 }
1245 }
1246
1247 if (!FoundFactor) {
1248 // Make sure to restore the operands to the expression tree.
1249 RewriteExprTree(I: BO, Ops&: Factors, Flags);
1250 return nullptr;
1251 }
1252
1253 BasicBlock::iterator InsertPt = ++BO->getIterator();
1254
1255 // If this was just a single multiply, remove the multiply and return the only
1256 // remaining operand.
1257 if (Factors.size() == 1) {
1258 RedoInsts.insert(X: BO);
1259 V = Factors[0].Op;
1260 } else {
1261 RewriteExprTree(I: BO, Ops&: Factors, Flags);
1262 V = BO;
1263 }
1264
1265 if (NeedsNegate) {
1266 V = CreateNeg(S1: V, Name: "neg", InsertBefore: InsertPt, FlagsOp: BO);
1267 cast<Instruction>(Val: V)->setDebugLoc(DL);
1268 }
1269
1270 return V;
1271}
1272
1273/// If V is a single-use multiply, recursively add its operands as factors,
1274/// otherwise add V to the list of factors.
1275///
1276/// Ops is the top-level list of add operands we're trying to factor.
1277static void FindSingleUseMultiplyFactors(Value *V,
1278 SmallVectorImpl<Value*> &Factors) {
1279 BinaryOperator *BO = isReassociableOp(V, Opcode1: Instruction::Mul, Opcode2: Instruction::FMul);
1280 if (!BO) {
1281 Factors.push_back(Elt: V);
1282 return;
1283 }
1284
1285 // Otherwise, add the LHS and RHS to the list of factors.
1286 FindSingleUseMultiplyFactors(V: BO->getOperand(i_nocapture: 1), Factors);
1287 FindSingleUseMultiplyFactors(V: BO->getOperand(i_nocapture: 0), Factors);
1288}
1289
1290/// Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
1291/// This optimizes based on identities. If it can be reduced to a single Value,
1292/// it is returned, otherwise the Ops list is mutated as necessary.
1293static Value *OptimizeAndOrXor(unsigned Opcode,
1294 SmallVectorImpl<ValueEntry> &Ops) {
1295 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
1296 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
1297 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1298 // First, check for X and ~X in the operand list.
1299 assert(i < Ops.size());
1300 Value *X;
1301 if (match(V: Ops[i].Op, P: m_Not(V: m_Value(V&: X)))) { // Cannot occur for ^.
1302 unsigned FoundX = FindInOperandList(Ops, i, X);
1303 if (FoundX != i) {
1304 if (Opcode == Instruction::And) // ...&X&~X = 0
1305 return Constant::getNullValue(Ty: X->getType());
1306
1307 if (Opcode == Instruction::Or) // ...|X|~X = -1
1308 return Constant::getAllOnesValue(Ty: X->getType());
1309 }
1310 }
1311
1312 // Next, check for duplicate pairs of values, which we assume are next to
1313 // each other, due to our sorting criteria.
1314 assert(i < Ops.size());
1315 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
1316 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1317 // Drop duplicate values for And and Or.
1318 Ops.erase(CI: Ops.begin()+i);
1319 --i; --e;
1320 ++NumAnnihil;
1321 continue;
1322 }
1323
1324 // Drop pairs of values for Xor.
1325 assert(Opcode == Instruction::Xor);
1326 if (e == 2)
1327 return Constant::getNullValue(Ty: Ops[0].Op->getType());
1328
1329 // Y ^ X^X -> Y
1330 Ops.erase(CS: Ops.begin()+i, CE: Ops.begin()+i+2);
1331 i -= 1; e -= 2;
1332 ++NumAnnihil;
1333 }
1334 }
1335 return nullptr;
1336}
1337
1338/// Helper function of CombineXorOpnd(). It creates a bitwise-and
1339/// instruction with the given two operands, and return the resulting
1340/// instruction. There are two special cases: 1) if the constant operand is 0,
1341/// it will return NULL. 2) if the constant is ~0, the symbolic operand will
1342/// be returned.
1343static Value *createAndInstr(BasicBlock::iterator InsertBefore, Value *Opnd,
1344 const APInt &ConstOpnd) {
1345 if (ConstOpnd.isZero())
1346 return nullptr;
1347
1348 if (ConstOpnd.isAllOnes())
1349 return Opnd;
1350
1351 Instruction *I = BinaryOperator::CreateAnd(
1352 V1: Opnd, V2: ConstantInt::get(Ty: Opnd->getType(), V: ConstOpnd), Name: "and.ra",
1353 InsertBefore);
1354 I->setDebugLoc(InsertBefore->getDebugLoc());
1355 return I;
1356}
1357
1358// Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
1359// into "R ^ C", where C would be 0, and R is a symbolic value.
1360//
1361// If it was successful, true is returned, and the "R" and "C" is returned
1362// via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
1363// and both "Res" and "ConstOpnd" remain unchanged.
1364bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1,
1365 APInt &ConstOpnd, Value *&Res) {
1366 // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
1367 // = ((x | c1) ^ c1) ^ (c1 ^ c2)
1368 // = (x & ~c1) ^ (c1 ^ c2)
1369 // It is useful only when c1 == c2.
1370 if (!Opnd1->isOrExpr() || Opnd1->getConstPart().isZero())
1371 return false;
1372
1373 if (!Opnd1->getValue()->hasOneUse())
1374 return false;
1375
1376 const APInt &C1 = Opnd1->getConstPart();
1377 if (C1 != ConstOpnd)
1378 return false;
1379
1380 Value *X = Opnd1->getSymbolicPart();
1381 Res = createAndInstr(InsertBefore: It, Opnd: X, ConstOpnd: ~C1);
1382 // ConstOpnd was C2, now C1 ^ C2.
1383 ConstOpnd ^= C1;
1384
1385 if (Instruction *T = dyn_cast<Instruction>(Val: Opnd1->getValue()))
1386 RedoInsts.insert(X: T);
1387 return true;
1388}
1389
1390// Helper function of OptimizeXor(). It tries to simplify
1391// "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
1392// symbolic value.
1393//
1394// If it was successful, true is returned, and the "R" and "C" is returned
1395// via "Res" and "ConstOpnd", respectively (If the entire expression is
1396// evaluated to a constant, the Res is set to NULL); otherwise, false is
1397// returned, and both "Res" and "ConstOpnd" remain unchanged.
1398bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1,
1399 XorOpnd *Opnd2, APInt &ConstOpnd,
1400 Value *&Res) {
1401 Value *X = Opnd1->getSymbolicPart();
1402 if (X != Opnd2->getSymbolicPart())
1403 return false;
1404
1405 // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
1406 int DeadInstNum = 1;
1407 if (Opnd1->getValue()->hasOneUse())
1408 DeadInstNum++;
1409 if (Opnd2->getValue()->hasOneUse())
1410 DeadInstNum++;
1411
1412 // Xor-Rule 2:
1413 // (x | c1) ^ (x & c2)
1414 // = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
1415 // = (x & ~c1) ^ (x & c2) ^ c1 // Xor-Rule 1
1416 // = (x & c3) ^ c1, where c3 = ~c1 ^ c2 // Xor-rule 3
1417 //
1418 if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
1419 if (Opnd2->isOrExpr())
1420 std::swap(a&: Opnd1, b&: Opnd2);
1421
1422 const APInt &C1 = Opnd1->getConstPart();
1423 const APInt &C2 = Opnd2->getConstPart();
1424 APInt C3((~C1) ^ C2);
1425
1426 // Do not increase code size!
1427 if (!C3.isZero() && !C3.isAllOnes()) {
1428 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
1429 if (NewInstNum > DeadInstNum)
1430 return false;
1431 }
1432
1433 Res = createAndInstr(InsertBefore: It, Opnd: X, ConstOpnd: C3);
1434 ConstOpnd ^= C1;
1435 } else if (Opnd1->isOrExpr()) {
1436 // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
1437 //
1438 const APInt &C1 = Opnd1->getConstPart();
1439 const APInt &C2 = Opnd2->getConstPart();
1440 APInt C3 = C1 ^ C2;
1441
1442 // Do not increase code size
1443 if (!C3.isZero() && !C3.isAllOnes()) {
1444 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
1445 if (NewInstNum > DeadInstNum)
1446 return false;
1447 }
1448
1449 Res = createAndInstr(InsertBefore: It, Opnd: X, ConstOpnd: C3);
1450 ConstOpnd ^= C3;
1451 } else {
1452 // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
1453 //
1454 const APInt &C1 = Opnd1->getConstPart();
1455 const APInt &C2 = Opnd2->getConstPart();
1456 APInt C3 = C1 ^ C2;
1457 Res = createAndInstr(InsertBefore: It, Opnd: X, ConstOpnd: C3);
1458 }
1459
1460 // Put the original operands in the Redo list; hope they will be deleted
1461 // as dead code.
1462 if (Instruction *T = dyn_cast<Instruction>(Val: Opnd1->getValue()))
1463 RedoInsts.insert(X: T);
1464 if (Instruction *T = dyn_cast<Instruction>(Val: Opnd2->getValue()))
1465 RedoInsts.insert(X: T);
1466
1467 return true;
1468}
1469
1470/// Optimize a series of operands to an 'xor' instruction. If it can be reduced
1471/// to a single Value, it is returned, otherwise the Ops list is mutated as
1472/// necessary.
1473Value *ReassociatePass::OptimizeXor(Instruction *I,
1474 SmallVectorImpl<ValueEntry> &Ops) {
1475 if (Value *V = OptimizeAndOrXor(Opcode: Instruction::Xor, Ops))
1476 return V;
1477
1478 if (Ops.size() == 1)
1479 return nullptr;
1480
1481 SmallVector<XorOpnd, 8> Opnds;
1482 SmallVector<XorOpnd*, 8> OpndPtrs;
1483 Type *Ty = Ops[0].Op->getType();
1484 APInt ConstOpnd(Ty->getScalarSizeInBits(), 0);
1485
1486 // Step 1: Convert ValueEntry to XorOpnd
1487 for (const ValueEntry &Op : Ops) {
1488 Value *V = Op.Op;
1489 const APInt *C;
1490 // TODO: Support non-splat vectors.
1491 if (match(V, P: m_APInt(Res&: C))) {
1492 ConstOpnd ^= *C;
1493 } else {
1494 XorOpnd O(V);
1495 O.setSymbolicRank(getRank(V: O.getSymbolicPart()));
1496 Opnds.push_back(Elt: O);
1497 }
1498 }
1499
1500 // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
1501 // It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
1502 // the "OpndPtrs" as well. For the similar reason, do not fuse this loop
1503 // with the previous loop --- the iterator of the "Opnds" may be invalidated
1504 // when new elements are added to the vector.
1505 for (XorOpnd &Op : Opnds)
1506 OpndPtrs.push_back(Elt: &Op);
1507
1508 // Step 2: Sort the Xor-Operands in a way such that the operands containing
1509 // the same symbolic value cluster together. For instance, the input operand
1510 // sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
1511 // ("x | 123", "x & 789", "y & 456").
1512 //
1513 // The purpose is twofold:
1514 // 1) Cluster together the operands sharing the same symbolic-value.
1515 // 2) Operand having smaller symbolic-value-rank is permuted earlier, which
1516 // could potentially shorten crital path, and expose more loop-invariants.
1517 // Note that values' rank are basically defined in RPO order (FIXME).
1518 // So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
1519 // than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
1520 // "z" in the order of X-Y-Z is better than any other orders.
1521 llvm::stable_sort(Range&: OpndPtrs, C: [](XorOpnd *LHS, XorOpnd *RHS) {
1522 return LHS->getSymbolicRank() < RHS->getSymbolicRank();
1523 });
1524
1525 // Step 3: Combine adjacent operands
1526 XorOpnd *PrevOpnd = nullptr;
1527 bool Changed = false;
1528 for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
1529 XorOpnd *CurrOpnd = OpndPtrs[i];
1530 // The combined value
1531 Value *CV;
1532
1533 // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
1534 if (!ConstOpnd.isZero() &&
1535 CombineXorOpnd(It: I->getIterator(), Opnd1: CurrOpnd, ConstOpnd, Res&: CV)) {
1536 Changed = true;
1537 if (CV)
1538 *CurrOpnd = XorOpnd(CV);
1539 else {
1540 CurrOpnd->Invalidate();
1541 continue;
1542 }
1543 }
1544
1545 if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1546 PrevOpnd = CurrOpnd;
1547 continue;
1548 }
1549
1550 // step 3.2: When previous and current operands share the same symbolic
1551 // value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
1552 if (CombineXorOpnd(It: I->getIterator(), Opnd1: CurrOpnd, Opnd2: PrevOpnd, ConstOpnd, Res&: CV)) {
1553 // Remove previous operand
1554 PrevOpnd->Invalidate();
1555 if (CV) {
1556 *CurrOpnd = XorOpnd(CV);
1557 PrevOpnd = CurrOpnd;
1558 } else {
1559 CurrOpnd->Invalidate();
1560 PrevOpnd = nullptr;
1561 }
1562 Changed = true;
1563 }
1564 }
1565
1566 // Step 4: Reassemble the Ops
1567 if (Changed) {
1568 Ops.clear();
1569 for (const XorOpnd &O : Opnds) {
1570 if (O.isInvalid())
1571 continue;
1572 ValueEntry VE(getRank(V: O.getValue()), O.getValue());
1573 Ops.push_back(Elt: VE);
1574 }
1575 if (!ConstOpnd.isZero()) {
1576 Value *C = ConstantInt::get(Ty, V: ConstOpnd);
1577 ValueEntry VE(getRank(V: C), C);
1578 Ops.push_back(Elt: VE);
1579 }
1580 unsigned Sz = Ops.size();
1581 if (Sz == 1)
1582 return Ops.back().Op;
1583 if (Sz == 0) {
1584 assert(ConstOpnd.isZero());
1585 return ConstantInt::get(Ty, V: ConstOpnd);
1586 }
1587 }
1588
1589 return nullptr;
1590}
1591
1592/// Optimize a series of operands to an 'add' instruction. This
1593/// optimizes based on identities. If it can be reduced to a single Value, it
1594/// is returned, otherwise the Ops list is mutated as necessary.
1595Value *ReassociatePass::OptimizeAdd(Instruction *I,
1596 SmallVectorImpl<ValueEntry> &Ops) {
1597 // Scan the operand lists looking for X and -X pairs. If we find any, we
1598 // can simplify expressions like X+-X == 0 and X+~X ==-1. While we're at it,
1599 // scan for any
1600 // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
1601
1602 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1603 Value *TheOp = Ops[i].Op;
1604 // Check to see if we've seen this operand before. If so, we factor all
1605 // instances of the operand together. Due to our sorting criteria, we know
1606 // that these need to be next to each other in the vector.
1607 if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
1608 // Rescan the list, remove all instances of this operand from the expr.
1609 unsigned NumFound = 0;
1610 do {
1611 Ops.erase(CI: Ops.begin()+i);
1612 ++NumFound;
1613 } while (i != Ops.size() && Ops[i].Op == TheOp);
1614
1615 LLVM_DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp
1616 << '\n');
1617 ++NumFactor;
1618
1619 // Insert a new multiply.
1620 Type *Ty = TheOp->getType();
1621 // Truncate if NumFound overflows the type.
1622 Constant *C = Ty->isIntOrIntVectorTy()
1623 ? ConstantInt::get(Ty, V: NumFound, /*IsSigned=*/false,
1624 /*ImplicitTrunc=*/true)
1625 : ConstantFP::get(Ty, V: NumFound);
1626 Instruction *Mul = CreateMul(S1: TheOp, S2: C, Name: "factor", InsertBefore: I->getIterator(), FlagsOp: I);
1627 Mul->setDebugLoc(I->getDebugLoc());
1628
1629 // Now that we have inserted a multiply, optimize it. This allows us to
1630 // handle cases that require multiple factoring steps, such as this:
1631 // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
1632 RedoInsts.insert(X: Mul);
1633
1634 // If every add operand was a duplicate, return the multiply.
1635 if (Ops.empty())
1636 return Mul;
1637
1638 // Otherwise, we had some input that didn't have the dupe, such as
1639 // "A + A + B" -> "A*2 + B". Add the new multiply to the list of
1640 // things being added by this operation.
1641 Ops.insert(I: Ops.begin(), Elt: ValueEntry(getRank(V: Mul), Mul));
1642
1643 --i;
1644 e = Ops.size();
1645 continue;
1646 }
1647
1648 // Check for X and -X or X and ~X in the operand list.
1649 Value *X;
1650 if (!match(V: TheOp, P: m_Neg(V: m_Value(V&: X))) && !match(V: TheOp, P: m_Not(V: m_Value(V&: X))) &&
1651 !match(V: TheOp, P: m_FNeg(X: m_Value(V&: X))))
1652 continue;
1653
1654 unsigned FoundX = FindInOperandList(Ops, i, X);
1655 if (FoundX == i)
1656 continue;
1657
1658 // Remove X and -X from the operand list.
1659 if (Ops.size() == 2 &&
1660 (match(V: TheOp, P: m_Neg(V: m_Value())) || match(V: TheOp, P: m_FNeg(X: m_Value()))))
1661 return Constant::getNullValue(Ty: X->getType());
1662
1663 // Remove X and ~X from the operand list.
1664 if (Ops.size() == 2 && match(V: TheOp, P: m_Not(V: m_Value())))
1665 return Constant::getAllOnesValue(Ty: X->getType());
1666
1667 Ops.erase(CI: Ops.begin()+i);
1668 if (i < FoundX)
1669 --FoundX;
1670 else
1671 --i; // Need to back up an extra one.
1672 Ops.erase(CI: Ops.begin()+FoundX);
1673 ++NumAnnihil;
1674 --i; // Revisit element.
1675 e -= 2; // Removed two elements.
1676
1677 // if X and ~X we append -1 to the operand list.
1678 if (match(V: TheOp, P: m_Not(V: m_Value()))) {
1679 Value *V = Constant::getAllOnesValue(Ty: X->getType());
1680 Ops.insert(I: Ops.end(), Elt: ValueEntry(getRank(V), V));
1681 e += 1;
1682 }
1683 }
1684
1685 // Scan the operand list, checking to see if there are any common factors
1686 // between operands. Consider something like A*A+A*B*C+D. We would like to
1687 // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
1688 // To efficiently find this, we count the number of times a factor occurs
1689 // for any ADD operands that are MULs.
1690 DenseMap<Value*, unsigned> FactorOccurrences;
1691
1692 // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
1693 // where they are actually the same multiply.
1694 unsigned MaxOcc = 0;
1695 Value *MaxOccVal = nullptr;
1696
1697 // Prefer a non-constant factor over a constant when occurrence counts
1698 // tie. Factoring out a variable (e.g., X from X*C1 + X*C2) exposes
1699 // downstream constant folding; factoring out a constant does not.
1700 auto IsBetterFactor = [](Value *Factor, Value *MaxOccVal, unsigned Occ,
1701 unsigned MaxOcc) {
1702 return Occ > MaxOcc ||
1703 (Occ == MaxOcc &&
1704 (isa<Instruction>(Val: Factor) || isa<Argument>(Val: Factor)) &&
1705 isa<Constant>(Val: MaxOccVal) && !isa<UndefValue>(Val: MaxOccVal));
1706 };
1707 auto CountFactors = [&](BinaryOperator *BOp) {
1708 // Compute all of the factors of this added value.
1709 SmallVector<Value*, 8> Factors;
1710 FindSingleUseMultiplyFactors(V: BOp, Factors);
1711 assert(Factors.size() > 1 && "Bad linearize!");
1712
1713 // Add one to FactorOccurrences for each unique factor in this op.
1714 SmallPtrSet<Value*, 8> Duplicates;
1715 for (Value *Factor : Factors) {
1716 if (!Duplicates.insert(Ptr: Factor).second)
1717 continue;
1718
1719 unsigned Occ = ++FactorOccurrences[Factor];
1720 if (IsBetterFactor(Factor, MaxOccVal, Occ, MaxOcc)) {
1721 MaxOcc = Occ;
1722 MaxOccVal = Factor;
1723 }
1724
1725 // If Factor is a negative constant, add the negated value as a factor
1726 // because we can percolate the negate out. Watch for minint, which
1727 // cannot be positivified.
1728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Factor)) {
1729 if (CI->isNegative() && !CI->isMinValue(IsSigned: true)) {
1730 Factor = ConstantInt::get(Context&: CI->getContext(), V: -CI->getValue());
1731 if (!Duplicates.insert(Ptr: Factor).second)
1732 continue;
1733 unsigned Occ = ++FactorOccurrences[Factor];
1734 if (IsBetterFactor(Factor, MaxOccVal, Occ, MaxOcc)) {
1735 MaxOcc = Occ;
1736 MaxOccVal = Factor;
1737 }
1738 }
1739 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Val: Factor)) {
1740 if (CF->isNegative()) {
1741 APFloat F(CF->getValueAPF());
1742 F.changeSign();
1743 Factor = ConstantFP::get(Ty: CF->getType(), V: F);
1744 if (!Duplicates.insert(Ptr: Factor).second)
1745 continue;
1746 unsigned Occ = ++FactorOccurrences[Factor];
1747 if (IsBetterFactor(Factor, MaxOccVal, Occ, MaxOcc)) {
1748 MaxOcc = Occ;
1749 MaxOccVal = Factor;
1750 }
1751 }
1752 }
1753 }
1754 };
1755
1756 // fmul/fadd pairs kept together for fma hide their muls; count the factors
1757 // of the reassociable ones as well and break those pairs up if a repeated
1758 // factor exists, so that factorization still applies.
1759 SmallVector<Value *> FMulAddCands;
1760 for (const ValueEntry &Entry : Ops) {
1761 if (BinaryOperator *BOp =
1762 isReassociableOp(V: Entry.Op, Opcode1: Instruction::Mul, Opcode2: Instruction::FMul)) {
1763 CountFactors(BOp);
1764 continue;
1765 }
1766 if (BinaryOperator *BOp = isFMulAddCandidate(V: Entry.Op);
1767 BOp && hasFPAssociativeFlags(I: BOp)) {
1768 FMulAddCands.push_back(Elt: Entry.Op);
1769 CountFactors(BOp);
1770 }
1771 }
1772
1773 if (MaxOcc > 1) {
1774 for (Value *V : FMulAddCands) {
1775 erase_if(C&: Ops, P: [V](const ValueEntry &E) { return E.Op == V; });
1776 for (Value *Op : cast<BinaryOperator>(Val: V)->operands())
1777 Ops.emplace_back(Args: getRank(V: Op), Args&: Op);
1778 }
1779 }
1780
1781 // If any factor occurred more than one time, we can pull it out.
1782 if (MaxOcc > 1) {
1783 LLVM_DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal
1784 << '\n');
1785 ++NumFactor;
1786
1787 // Create a new instruction that uses the MaxOccVal twice. If we don't do
1788 // this, we could otherwise run into situations where removing a factor
1789 // from an expression will drop a use of maxocc, and this can cause
1790 // RemoveFactorFromExpression on successive values to behave differently.
1791 Instruction *DummyInst =
1792 I->getType()->isIntOrIntVectorTy()
1793 ? BinaryOperator::CreateAdd(V1: MaxOccVal, V2: MaxOccVal)
1794 : BinaryOperator::CreateFAdd(V1: MaxOccVal, V2: MaxOccVal);
1795
1796 SmallVector<WeakTrackingVH, 4> NewMulOps;
1797 for (unsigned i = 0; i != Ops.size(); ++i) {
1798 // Only try to remove factors from expressions we're allowed to.
1799 BinaryOperator *BOp =
1800 isReassociableOp(V: Ops[i].Op, Opcode1: Instruction::Mul, Opcode2: Instruction::FMul);
1801 if (!BOp)
1802 continue;
1803
1804 if (Value *V = RemoveFactorFromExpression(V: Ops[i].Op, Factor: MaxOccVal,
1805 DL: I->getDebugLoc())) {
1806 // The factorized operand may occur several times. Convert them all in
1807 // one fell swoop.
1808 for (unsigned j = Ops.size(); j != i;) {
1809 --j;
1810 if (Ops[j].Op == Ops[i].Op) {
1811 NewMulOps.push_back(Elt: V);
1812 Ops.erase(CI: Ops.begin()+j);
1813 }
1814 }
1815 --i;
1816 }
1817 }
1818
1819 // No need for extra uses anymore.
1820 DummyInst->deleteValue();
1821
1822 unsigned NumAddedValues = NewMulOps.size();
1823 Value *V = EmitAddTreeOfValues(I, Ops&: NewMulOps);
1824
1825 // Now that we have inserted the add tree, optimize it. This allows us to
1826 // handle cases that require multiple factoring steps, such as this:
1827 // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
1828 assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
1829 (void)NumAddedValues;
1830 if (Instruction *VI = dyn_cast<Instruction>(Val: V))
1831 RedoInsts.insert(X: VI);
1832
1833 // Create the multiply.
1834 Instruction *V2 = CreateMul(S1: V, S2: MaxOccVal, Name: "reass.mul", InsertBefore: I->getIterator(), FlagsOp: I);
1835 V2->setDebugLoc(I->getDebugLoc());
1836
1837 // Rerun associate on the multiply in case the inner expression turned into
1838 // a multiply. We want to make sure that we keep things in canonical form.
1839 RedoInsts.insert(X: V2);
1840
1841 // If every add operand included the factor (e.g. "A*B + A*C"), then the
1842 // entire result expression is just the multiply "A*(B+C)".
1843 if (Ops.empty())
1844 return V2;
1845
1846 // Otherwise, we had some input that didn't have the factor, such as
1847 // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
1848 // things being added by this operation.
1849 Ops.insert(I: Ops.begin(), Elt: ValueEntry(getRank(V: V2), V2));
1850 }
1851
1852 return nullptr;
1853}
1854
1855/// Build up a vector of value/power pairs factoring a product.
1856///
1857/// Given a series of multiplication operands, build a vector of factors and
1858/// the powers each is raised to when forming the final product. Sort them in
1859/// the order of descending power.
1860///
1861/// (x*x) -> [(x, 2)]
1862/// ((x*x)*x) -> [(x, 3)]
1863/// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1864///
1865/// \returns Whether any factors have a power greater than one.
1866static bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1867 SmallVectorImpl<Factor> &Factors) {
1868 // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1869 // Compute the sum of powers of simplifiable factors.
1870 unsigned FactorPowerSum = 0;
1871 for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1872 Value *Op = Ops[Idx-1].Op;
1873
1874 // Count the number of occurrences of this value.
1875 unsigned Count = 1;
1876 for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1877 ++Count;
1878 // Track for simplification all factors which occur 2 or more times.
1879 if (Count > 1)
1880 FactorPowerSum += Count;
1881 }
1882
1883 // We can only simplify factors if the sum of the powers of our simplifiable
1884 // factors is 4 or higher. When that is the case, we will *always* have
1885 // a simplification. This is an important invariant to prevent cyclicly
1886 // trying to simplify already minimal formations.
1887 if (FactorPowerSum < 4)
1888 return false;
1889
1890 // Now gather the simplifiable factors, removing them from Ops.
1891 FactorPowerSum = 0;
1892 for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1893 Value *Op = Ops[Idx-1].Op;
1894
1895 // Count the number of occurrences of this value.
1896 unsigned Count = 1;
1897 for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1898 ++Count;
1899 if (Count == 1)
1900 continue;
1901 // Move an even number of occurrences to Factors.
1902 Count &= ~1U;
1903 Idx -= Count;
1904 FactorPowerSum += Count;
1905 Factors.push_back(Elt: Factor(Op, Count));
1906 Ops.erase(CS: Ops.begin()+Idx, CE: Ops.begin()+Idx+Count);
1907 }
1908
1909 // None of the adjustments above should have reduced the sum of factor powers
1910 // below our mininum of '4'.
1911 assert(FactorPowerSum >= 4);
1912
1913 llvm::stable_sort(Range&: Factors, C: [](const Factor &LHS, const Factor &RHS) {
1914 return LHS.Power > RHS.Power;
1915 });
1916 return true;
1917}
1918
1919/// Build a tree of multiplies, computing the product of Ops.
1920static Value *buildMultiplyTree(IRBuilderBase &Builder,
1921 SmallVectorImpl<Value*> &Ops) {
1922 if (Ops.size() == 1)
1923 return Ops.back();
1924
1925 Value *LHS = Ops.pop_back_val();
1926 do {
1927 if (LHS->getType()->isIntOrIntVectorTy())
1928 LHS = Builder.CreateMul(LHS, RHS: Ops.pop_back_val());
1929 else
1930 LHS = Builder.CreateFMul(L: LHS, R: Ops.pop_back_val());
1931 } while (!Ops.empty());
1932
1933 return LHS;
1934}
1935
1936/// Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1937///
1938/// Given a vector of values raised to various powers, where no two values are
1939/// equal and the powers are sorted in decreasing order, compute the minimal
1940/// DAG of multiplies to compute the final product, and return that product
1941/// value.
1942Value *
1943ReassociatePass::buildMinimalMultiplyDAG(IRBuilderBase &Builder,
1944 SmallVectorImpl<Factor> &Factors) {
1945 assert(Factors[0].Power);
1946 SmallVector<Value *, 4> OuterProduct;
1947 for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1948 Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1949 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1950 LastIdx = Idx;
1951 continue;
1952 }
1953
1954 // We want to multiply across all the factors with the same power so that
1955 // we can raise them to that power as a single entity. Build a mini tree
1956 // for that.
1957 SmallVector<Value *, 4> InnerProduct;
1958 InnerProduct.push_back(Elt: Factors[LastIdx].Base);
1959 do {
1960 InnerProduct.push_back(Elt: Factors[Idx].Base);
1961 ++Idx;
1962 } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1963
1964 // Reset the base value of the first factor to the new expression tree.
1965 // We'll remove all the factors with the same power in a second pass.
1966 Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, Ops&: InnerProduct);
1967 if (Instruction *MI = dyn_cast<Instruction>(Val: M))
1968 RedoInsts.insert(X: MI);
1969
1970 LastIdx = Idx;
1971 }
1972 // Unique factors with equal powers -- we've folded them into the first one's
1973 // base.
1974 Factors.erase(CS: llvm::unique(R&: Factors,
1975 P: [](const Factor &LHS, const Factor &RHS) {
1976 return LHS.Power == RHS.Power;
1977 }),
1978 CE: Factors.end());
1979
1980 // Iteratively collect the base of each factor with an add power into the
1981 // outer product, and halve each power in preparation for squaring the
1982 // expression.
1983 for (Factor &F : Factors) {
1984 if (F.Power & 1)
1985 OuterProduct.push_back(Elt: F.Base);
1986 F.Power >>= 1;
1987 }
1988 if (Factors[0].Power) {
1989 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1990 OuterProduct.push_back(Elt: SquareRoot);
1991 OuterProduct.push_back(Elt: SquareRoot);
1992 }
1993 if (OuterProduct.size() == 1)
1994 return OuterProduct.front();
1995
1996 Value *V = buildMultiplyTree(Builder, Ops&: OuterProduct);
1997 return V;
1998}
1999
2000Value *ReassociatePass::OptimizeMul(BinaryOperator *I,
2001 SmallVectorImpl<ValueEntry> &Ops) {
2002 // We can only optimize the multiplies when there is a chain of more than
2003 // three, such that a balanced tree might require fewer total multiplies.
2004 if (Ops.size() < 4)
2005 return nullptr;
2006
2007 // Try to turn linear trees of multiplies without other uses of the
2008 // intermediate stages into minimal multiply DAGs with perfect sub-expression
2009 // re-use.
2010 SmallVector<Factor, 4> Factors;
2011 if (!collectMultiplyFactors(Ops, Factors))
2012 return nullptr; // All distinct factors, so nothing left for us to do.
2013
2014 IRBuilder<> Builder(I);
2015 // The reassociate transformation for FP operations is performed only
2016 // if unsafe algebra is permitted by FastMathFlags. Propagate those flags
2017 // to the newly generated operations.
2018 if (auto FPI = dyn_cast<FPMathOperator>(Val: I))
2019 Builder.setFastMathFlags(FPI->getFastMathFlags());
2020
2021 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
2022 if (Ops.empty())
2023 return V;
2024
2025 ValueEntry NewEntry = ValueEntry(getRank(V), V);
2026 Ops.insert(I: llvm::lower_bound(Range&: Ops, Value&: NewEntry), Elt: NewEntry);
2027 return nullptr;
2028}
2029
2030Value *ReassociatePass::OptimizeExpression(BinaryOperator *I,
2031 SmallVectorImpl<ValueEntry> &Ops) {
2032 // Now that we have the linearized expression tree, try to optimize it.
2033 // Start by folding any constants that we found.
2034 const DataLayout &DL = I->getDataLayout();
2035 Constant *Cst = nullptr;
2036 unsigned Opcode = I->getOpcode();
2037 while (!Ops.empty()) {
2038 if (auto *C = dyn_cast<Constant>(Val: Ops.back().Op)) {
2039 if (!Cst) {
2040 Ops.pop_back();
2041 Cst = C;
2042 continue;
2043 }
2044 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, LHS: C, RHS: Cst, DL)) {
2045 Ops.pop_back();
2046 Cst = Res;
2047 continue;
2048 }
2049 }
2050 break;
2051 }
2052 // If there was nothing but constants then we are done.
2053 if (Ops.empty())
2054 return Cst;
2055
2056 // Put the combined constant back at the end of the operand list, except if
2057 // there is no point. For example, an add of 0 gets dropped here, while a
2058 // multiplication by zero turns the whole expression into zero.
2059 if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, Ty: I->getType())) {
2060 if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, Ty: I->getType()))
2061 return Cst;
2062 Ops.push_back(Elt: ValueEntry(0, Cst));
2063 }
2064
2065 if (Ops.size() == 1) return Ops[0].Op;
2066
2067 // Handle destructive annihilation due to identities between elements in the
2068 // argument list here.
2069 unsigned NumOps = Ops.size();
2070 switch (Opcode) {
2071 default: break;
2072 case Instruction::And:
2073 case Instruction::Or:
2074 if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
2075 return Result;
2076 break;
2077
2078 case Instruction::Xor:
2079 if (Value *Result = OptimizeXor(I, Ops))
2080 return Result;
2081 break;
2082
2083 case Instruction::Add:
2084 case Instruction::FAdd:
2085 if (Value *Result = OptimizeAdd(I, Ops))
2086 return Result;
2087 break;
2088
2089 case Instruction::Mul:
2090 case Instruction::FMul:
2091 if (Value *Result = OptimizeMul(I, Ops))
2092 return Result;
2093 break;
2094 }
2095
2096 if (Ops.size() != NumOps)
2097 return OptimizeExpression(I, Ops);
2098 return nullptr;
2099}
2100
2101// Remove dead instructions and if any operands are trivially dead add them to
2102// Insts so they will be removed as well.
2103void ReassociatePass::RecursivelyEraseDeadInsts(Instruction *I,
2104 OrderedSet &Insts) {
2105 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
2106 SmallVector<Value *, 4> Ops(I->operands());
2107 ValueRankMap.erase(Val: I);
2108 Insts.remove(X: I);
2109 RedoInsts.remove(X: I);
2110 if (UA)
2111 UA->forgetValue(V: I);
2112 llvm::salvageDebugInfo(I&: *I);
2113 I->eraseFromParent();
2114 for (auto *Op : Ops)
2115 if (Instruction *OpInst = dyn_cast<Instruction>(Val: Op))
2116 if (OpInst->use_empty())
2117 Insts.insert(X: OpInst);
2118}
2119
2120/// Zap the given instruction, adding interesting operands to the work list.
2121void ReassociatePass::EraseInst(Instruction *I) {
2122 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
2123 LLVM_DEBUG(dbgs() << "Erasing dead inst: "; I->dump());
2124
2125 SmallVector<Value *, 8> Ops(I->operands());
2126 // Erase the dead instruction.
2127 ValueRankMap.erase(Val: I);
2128 RedoInsts.remove(X: I);
2129 if (UA)
2130 UA->forgetValue(V: I);
2131 llvm::salvageDebugInfo(I&: *I);
2132 I->eraseFromParent();
2133 // Optimize its operands.
2134 SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
2135 for (Value *V : Ops)
2136 if (Instruction *Op = dyn_cast<Instruction>(Val: V)) {
2137 // If this is a node in an expression tree, climb to the expression root
2138 // and add that since that's where optimization actually happens.
2139 unsigned Opcode = Op->getOpcode();
2140 while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
2141 Visited.insert(Ptr: Op).second)
2142 Op = Op->user_back();
2143
2144 // The instruction we're going to push may be coming from a
2145 // dead block, and Reassociate skips the processing of unreachable
2146 // blocks because it's a waste of time and also because it can
2147 // lead to infinite loop due to LLVM's non-standard definition
2148 // of dominance.
2149 if (ValueRankMap.contains(Val: Op))
2150 RedoInsts.insert(X: Op);
2151 }
2152
2153 MadeChange = true;
2154}
2155
2156/// Recursively analyze an expression to build a list of instructions that have
2157/// negative floating-point constant operands. The caller can then transform
2158/// the list to create positive constants for better reassociation and CSE.
2159static void getNegatibleInsts(Value *V,
2160 SmallVectorImpl<Instruction *> &Candidates) {
2161 // Handle only one-use instructions. Combining negations does not justify
2162 // replicating instructions.
2163 Instruction *I;
2164 if (!match(V, P: m_OneUse(SubPattern: m_Instruction(I))))
2165 return;
2166
2167 // Handle expressions of multiplications and divisions.
2168 // TODO: This could look through floating-point casts.
2169 const APFloat *C;
2170 switch (I->getOpcode()) {
2171 case Instruction::FMul:
2172 // Not expecting non-canonical code here. Bail out and wait.
2173 if (match(V: I->getOperand(i: 0), P: m_Constant()))
2174 break;
2175
2176 if (match(V: I->getOperand(i: 1), P: m_APFloat(Res&: C)) && C->isNegative()) {
2177 Candidates.push_back(Elt: I);
2178 LLVM_DEBUG(dbgs() << "FMul with negative constant: " << *I << '\n');
2179 }
2180 getNegatibleInsts(V: I->getOperand(i: 0), Candidates);
2181 getNegatibleInsts(V: I->getOperand(i: 1), Candidates);
2182 break;
2183 case Instruction::FDiv:
2184 // Not expecting non-canonical code here. Bail out and wait.
2185 if (match(V: I->getOperand(i: 0), P: m_Constant()) &&
2186 match(V: I->getOperand(i: 1), P: m_Constant()))
2187 break;
2188
2189 if ((match(V: I->getOperand(i: 0), P: m_APFloat(Res&: C)) && C->isNegative()) ||
2190 (match(V: I->getOperand(i: 1), P: m_APFloat(Res&: C)) && C->isNegative())) {
2191 Candidates.push_back(Elt: I);
2192 LLVM_DEBUG(dbgs() << "FDiv with negative constant: " << *I << '\n');
2193 }
2194 getNegatibleInsts(V: I->getOperand(i: 0), Candidates);
2195 getNegatibleInsts(V: I->getOperand(i: 1), Candidates);
2196 break;
2197 default:
2198 break;
2199 }
2200}
2201
2202/// Given an fadd/fsub with an operand that is a one-use instruction
2203/// (the fadd/fsub), try to change negative floating-point constants into
2204/// positive constants to increase potential for reassociation and CSE.
2205Instruction *ReassociatePass::canonicalizeNegFPConstantsForOp(Instruction *I,
2206 Instruction *Op,
2207 Value *OtherOp) {
2208 assert((I->getOpcode() == Instruction::FAdd ||
2209 I->getOpcode() == Instruction::FSub) && "Expected fadd/fsub");
2210
2211 // Collect instructions with negative FP constants from the subtree that ends
2212 // in Op.
2213 SmallVector<Instruction *, 4> Candidates;
2214 getNegatibleInsts(V: Op, Candidates);
2215 if (Candidates.empty())
2216 return nullptr;
2217
2218 // Don't canonicalize x + (-Constant * y) -> x - (Constant * y), if the
2219 // resulting subtract will be broken up later. This can get us into an
2220 // infinite loop during reassociation.
2221 bool IsFSub = I->getOpcode() == Instruction::FSub;
2222 bool NeedsSubtract = !IsFSub && Candidates.size() % 2 == 1;
2223 if (NeedsSubtract && ShouldBreakUpSubtract(Sub: I))
2224 return nullptr;
2225
2226 for (Instruction *Negatible : Candidates) {
2227 const APFloat *C;
2228 if (match(V: Negatible->getOperand(i: 0), P: m_APFloat(Res&: C))) {
2229 assert(!match(Negatible->getOperand(1), m_Constant()) &&
2230 "Expecting only 1 constant operand");
2231 assert(C->isNegative() && "Expected negative FP constant");
2232 Negatible->setOperand(i: 0, Val: ConstantFP::get(Ty: Negatible->getType(), V: abs(X: *C)));
2233 MadeChange = true;
2234 }
2235 if (match(V: Negatible->getOperand(i: 1), P: m_APFloat(Res&: C))) {
2236 assert(!match(Negatible->getOperand(0), m_Constant()) &&
2237 "Expecting only 1 constant operand");
2238 assert(C->isNegative() && "Expected negative FP constant");
2239 Negatible->setOperand(i: 1, Val: ConstantFP::get(Ty: Negatible->getType(), V: abs(X: *C)));
2240 MadeChange = true;
2241 }
2242 }
2243 assert(MadeChange == true && "Negative constant candidate was not changed");
2244
2245 // Negations cancelled out.
2246 if (Candidates.size() % 2 == 0)
2247 return I;
2248
2249 // Negate the final operand in the expression by flipping the opcode of this
2250 // fadd/fsub.
2251 assert(Candidates.size() % 2 == 1 && "Expected odd number");
2252 IRBuilder<> Builder(I);
2253 Value *NewInst = IsFSub ? Builder.CreateFAddFMF(L: OtherOp, R: Op, FMFSource: I)
2254 : Builder.CreateFSubFMF(L: OtherOp, R: Op, FMFSource: I);
2255 I->replaceAllUsesWith(V: NewInst);
2256 RedoInsts.insert(X: I);
2257 return dyn_cast<Instruction>(Val: NewInst);
2258}
2259
2260/// Canonicalize expressions that contain a negative floating-point constant
2261/// of the following form:
2262/// OtherOp + (subtree) -> OtherOp {+/-} (canonical subtree)
2263/// (subtree) + OtherOp -> OtherOp {+/-} (canonical subtree)
2264/// OtherOp - (subtree) -> OtherOp {+/-} (canonical subtree)
2265///
2266/// The fadd/fsub opcode may be switched to allow folding a negation into the
2267/// input instruction.
2268Instruction *ReassociatePass::canonicalizeNegFPConstants(Instruction *I) {
2269 LLVM_DEBUG(dbgs() << "Combine negations for: " << *I << '\n');
2270 Value *X;
2271 Instruction *Op;
2272 if (match(V: I, P: m_FAdd(L: m_Value(V&: X), R: m_OneUse(SubPattern: m_Instruction(I&: Op)))))
2273 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, OtherOp: X))
2274 I = R;
2275 if (match(V: I, P: m_FAdd(L: m_OneUse(SubPattern: m_Instruction(I&: Op)), R: m_Value(V&: X))))
2276 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, OtherOp: X))
2277 I = R;
2278 if (match(V: I, P: m_FSub(L: m_Value(V&: X), R: m_OneUse(SubPattern: m_Instruction(I&: Op)))))
2279 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, OtherOp: X))
2280 I = R;
2281 return I;
2282}
2283
2284/// Inspect and optimize the given instruction. Note that erasing
2285/// instructions is not allowed.
2286void ReassociatePass::OptimizeInst(Instruction *I) {
2287 // Only consider operations that we understand.
2288 if (!isa<UnaryOperator>(Val: I) && !isa<BinaryOperator>(Val: I))
2289 return;
2290
2291 if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(Val: I->getOperand(i: 1)))
2292 // If an operand of this shift is a reassociable multiply, or if the shift
2293 // is used by a reassociable multiply or add, turn into a multiply.
2294 if (isReassociableOp(V: I->getOperand(i: 0), Opcode: Instruction::Mul) ||
2295 (I->hasOneUse() &&
2296 (isReassociableOp(V: I->user_back(), Opcode: Instruction::Mul) ||
2297 isReassociableOp(V: I->user_back(), Opcode: Instruction::Add)))) {
2298 Instruction *NI = ConvertShiftToMul(Shl: I);
2299 RedoInsts.insert(X: I);
2300 MadeChange = true;
2301 I = NI;
2302 }
2303
2304 // Commute binary operators, to canonicalize the order of their operands.
2305 // This can potentially expose more CSE opportunities, and makes writing other
2306 // transformations simpler.
2307 if (I->isCommutative())
2308 canonicalizeOperands(I);
2309
2310 // Canonicalize negative constants out of expressions.
2311 if (Instruction *Res = canonicalizeNegFPConstants(I))
2312 I = Res;
2313
2314 // Don't optimize floating-point instructions unless they have the
2315 // appropriate FastMathFlags for reassociation enabled.
2316 if (isa<FPMathOperator>(Val: I) && !hasFPAssociativeFlags(I))
2317 return;
2318
2319 // Do not reassociate boolean (i1/vXi1) expressions. We want to preserve the
2320 // original order of evaluation for short-circuited comparisons that
2321 // SimplifyCFG has folded to AND/OR expressions. If the expression
2322 // is not further optimized, it is likely to be transformed back to a
2323 // short-circuited form for code gen, and the source order may have been
2324 // optimized for the most likely conditions. For vector boolean expressions,
2325 // we should be optimizing for ILP and not serializing the logical operations.
2326 if (I->getType()->isIntOrIntVectorTy(BitWidth: 1))
2327 return;
2328
2329 // If this is a bitwise or instruction of operands
2330 // with no common bits set, convert it to X+Y.
2331 if (I->getOpcode() == Instruction::Or &&
2332 shouldConvertOrWithNoCommonBitsToAdd(Or: I) && !isLoadCombineCandidate(Or: I) &&
2333 (cast<PossiblyDisjointInst>(Val: I)->isDisjoint() ||
2334 haveNoCommonBitsSet(LHSCache: I->getOperand(i: 0), RHSCache: I->getOperand(i: 1),
2335 SQ: SimplifyQuery(I->getDataLayout(),
2336 /*DT=*/nullptr, /*AC=*/nullptr, I)))) {
2337 Instruction *NI = convertOrWithNoCommonBitsToAdd(Or: I);
2338 RedoInsts.insert(X: I);
2339 MadeChange = true;
2340 I = NI;
2341 }
2342
2343 if (I->getOpcode() == Instruction::Mul && ShouldBreakUpDistribution(Mul: I)) {
2344 Instruction *MulUser = cast<Instruction>(Val: I->user_back());
2345 Instruction *NI = BreakUpDistribute(Mul: I, ToRedo&: RedoInsts);
2346 RedoInsts.insert(X: I);
2347 RedoInsts.insert(X: MulUser);
2348 MadeChange = true;
2349 I = NI;
2350 }
2351
2352 // If this is a subtract instruction which is not already in negate form,
2353 // see if we can convert it to X+-Y.
2354 if (I->getOpcode() == Instruction::Sub) {
2355 if (ShouldBreakUpSubtract(Sub: I)) {
2356 Instruction *NI = BreakUpSubtract(Sub: I, ToRedo&: RedoInsts);
2357 RedoInsts.insert(X: I);
2358 MadeChange = true;
2359 I = NI;
2360 } else if (match(V: I, P: m_Neg(V: m_Value()))) {
2361 // Otherwise, this is a negation. See if the operand is a multiply tree
2362 // and if this is not an inner node of a multiply tree.
2363 if (isReassociableOp(V: I->getOperand(i: 1), Opcode: Instruction::Mul) &&
2364 (!I->hasOneUse() ||
2365 !isReassociableOp(V: I->user_back(), Opcode: Instruction::Mul))) {
2366 Instruction *NI = LowerNegateToMultiply(Neg: I);
2367 // If the negate was simplified, revisit the users to see if we can
2368 // reassociate further.
2369 for (User *U : NI->users()) {
2370 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(Val: U))
2371 RedoInsts.insert(X: Tmp);
2372 }
2373 RedoInsts.insert(X: I);
2374 MadeChange = true;
2375 I = NI;
2376 }
2377 }
2378 } else if (I->getOpcode() == Instruction::FNeg ||
2379 I->getOpcode() == Instruction::FSub) {
2380 if (ShouldBreakUpSubtract(Sub: I)) {
2381 Instruction *NI = BreakUpSubtract(Sub: I, ToRedo&: RedoInsts);
2382 RedoInsts.insert(X: I);
2383 MadeChange = true;
2384 I = NI;
2385 } else if (match(V: I, P: m_FNeg(X: m_Value()))) {
2386 // Otherwise, this is a negation. See if the operand is a multiply tree
2387 // and if this is not an inner node of a multiply tree.
2388 Value *Op = isa<BinaryOperator>(Val: I) ? I->getOperand(i: 1) :
2389 I->getOperand(i: 0);
2390 if (isReassociableOp(V: Op, Opcode: Instruction::FMul) &&
2391 (!I->hasOneUse() ||
2392 !isReassociableOp(V: I->user_back(), Opcode: Instruction::FMul))) {
2393 // If the negate was simplified, revisit the users to see if we can
2394 // reassociate further.
2395 Instruction *NI = LowerNegateToMultiply(Neg: I);
2396 for (User *U : NI->users()) {
2397 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(Val: U))
2398 RedoInsts.insert(X: Tmp);
2399 }
2400 RedoInsts.insert(X: I);
2401 MadeChange = true;
2402 I = NI;
2403 }
2404 }
2405 }
2406
2407 // If this instruction is an associative binary operator, process it.
2408 if (!I->isAssociative()) return;
2409 BinaryOperator *BO = cast<BinaryOperator>(Val: I);
2410
2411 // If this is an interior node of a reassociable tree, ignore it until we
2412 // get to the root of the tree, to avoid N^2 analysis.
2413 unsigned Opcode = BO->getOpcode();
2414 if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode) {
2415 // During the initial run we will get to the root of the tree.
2416 // But if we get here while we are redoing instructions, there is no
2417 // guarantee that the root will be visited. So Redo later
2418 if (BO->user_back() != BO &&
2419 BO->getParent() == BO->user_back()->getParent())
2420 RedoInsts.insert(X: BO->user_back());
2421 return;
2422 }
2423
2424 // If this is an add tree that is used by a sub instruction, ignore it
2425 // until we process the subtract.
2426 if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
2427 cast<Instruction>(Val: BO->user_back())->getOpcode() == Instruction::Sub)
2428 return;
2429 if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd &&
2430 cast<Instruction>(Val: BO->user_back())->getOpcode() == Instruction::FSub)
2431 return;
2432
2433 ReassociateExpression(I: BO);
2434}
2435
2436void ReassociatePass::ReassociateExpression(BinaryOperator *I) {
2437 // First, walk the expression tree, linearizing the tree, collecting the
2438 // operand information.
2439 SmallVector<RepeatedValue, 8> Tree;
2440 OverflowTracking Flags;
2441 MadeChange |= LinearizeExprTree(I, Ops&: Tree, ToRedo&: RedoInsts, Flags);
2442 SmallVector<ValueEntry, 8> Ops;
2443 Ops.reserve(N: Tree.size());
2444 for (const RepeatedValue &E : Tree)
2445 Ops.append(NumInputs: E.second, Elt: ValueEntry(getRank(V: E.first), E.first));
2446
2447 LLVM_DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
2448
2449 // Boost the rank of divergent operands so they sort towards the root of the
2450 // expression tree, clustering uniform operands together at the leaves. On
2451 // targets without divergence UniformityInfo is empty and this is a no-op.
2452 //
2453 // Example: (uniform1 + divergent) + uniform2
2454 // -> (uniform1 + uniform2) + divergent
2455 if (UA && Ops.size() > 2) {
2456 constexpr unsigned DivergentRankOffset = 1U << 28;
2457 BasicBlock *ParentBB = I->getParent();
2458 for (ValueEntry &Entry : Ops) {
2459 if (isa<Constant>(Val: Entry.Op))
2460 continue;
2461 bool Divergent = false;
2462 for (const Use &U : Entry.Op->uses()) {
2463 Instruction *Usr = dyn_cast<Instruction>(Val: U.getUser());
2464 if (Usr && Usr->getParent() == ParentBB) {
2465 Divergent = UA->isDivergentAtUse(U);
2466 break;
2467 }
2468 }
2469 if (Divergent)
2470 Entry.Rank += DivergentRankOffset;
2471 }
2472 }
2473
2474 // Now that we have linearized the tree to a list and have gathered all of
2475 // the operands and their ranks, sort the operands by their rank. Use a
2476 // stable_sort so that values with equal ranks will have their relative
2477 // positions maintained (and so the compiler is deterministic). Note that
2478 // this sorts so that the highest ranking values end up at the beginning of
2479 // the vector.
2480 llvm::stable_sort(Range&: Ops);
2481
2482 // Now that we have the expression tree in a convenient
2483 // sorted form, optimize it globally if possible.
2484 if (Value *V = OptimizeExpression(I, Ops)) {
2485 if (V == I)
2486 // Self-referential expression in unreachable code.
2487 return;
2488 // This expression tree simplified to something that isn't a tree,
2489 // eliminate it.
2490 LLVM_DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
2491 I->replaceAllUsesWith(V);
2492 if (Instruction *VI = dyn_cast<Instruction>(Val: V))
2493 if (I->getDebugLoc())
2494 VI->setDebugLoc(I->getDebugLoc());
2495 RedoInsts.insert(X: I);
2496 ++NumAnnihil;
2497 return;
2498 }
2499
2500 // We want to sink immediates as deeply as possible except in the case where
2501 // this is a multiply tree used only by an add, and the immediate is a -1.
2502 // In this case we reassociate to put the negation on the outside so that we
2503 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
2504 if (I->hasOneUse()) {
2505 if (I->getOpcode() == Instruction::Mul &&
2506 cast<Instruction>(Val: I->user_back())->getOpcode() == Instruction::Add &&
2507 isa<ConstantInt>(Val: Ops.back().Op) &&
2508 cast<ConstantInt>(Val: Ops.back().Op)->isMinusOne()) {
2509 ValueEntry Tmp = Ops.pop_back_val();
2510 Ops.insert(I: Ops.begin(), Elt: Tmp);
2511 } else if (I->getOpcode() == Instruction::FMul &&
2512 cast<Instruction>(Val: I->user_back())->getOpcode() ==
2513 Instruction::FAdd &&
2514 isa<ConstantFP>(Val: Ops.back().Op) &&
2515 cast<ConstantFP>(Val: Ops.back().Op)->isMinusOne()) {
2516 ValueEntry Tmp = Ops.pop_back_val();
2517 Ops.insert(I: Ops.begin(), Elt: Tmp);
2518 }
2519 }
2520
2521 LLVM_DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
2522
2523 if (Ops.size() == 1) {
2524 if (Ops[0].Op == I)
2525 // Self-referential expression in unreachable code.
2526 return;
2527
2528 // This expression tree simplified to something that isn't a tree,
2529 // eliminate it.
2530 I->replaceAllUsesWith(V: Ops[0].Op);
2531 if (Instruction *OI = dyn_cast<Instruction>(Val: Ops[0].Op))
2532 OI->setDebugLoc(I->getDebugLoc());
2533 RedoInsts.insert(X: I);
2534 return;
2535 }
2536
2537 if (Ops.size() > 2 && Ops.size() <= GlobalReassociateLimit) {
2538 // Find the pair with the highest count in the pairmap and move it to the
2539 // back of the list so that it can later be CSE'd.
2540 // example:
2541 // a*b*c*d*e
2542 // if c*e is the most "popular" pair, we can express this as
2543 // (((c*e)*d)*b)*a
2544 unsigned Max = 1;
2545 unsigned BestRank = 0;
2546 std::pair<unsigned, unsigned> BestPair;
2547 unsigned Idx = I->getOpcode() - Instruction::BinaryOpsBegin;
2548 unsigned LimitIdx = 0;
2549 // With the CSE-driven heuristic, we are about to slap two values at the
2550 // beginning of the expression whereas they could live very late in the CFG.
2551 // When using the CSE-local heuristic we avoid creating dependences from
2552 // completely unrelated part of the CFG by limiting the expression
2553 // reordering on the values that live in the first seen basic block.
2554 // The main idea is that we want to avoid forming expressions that would
2555 // become loop dependent.
2556 if (ScalarOptions::Global.reassociate_use_cse_local) {
2557 const BasicBlock *FirstSeenBB = nullptr;
2558 int StartIdx = Ops.size() - 1;
2559 // Skip the first value of the expression since we need at least two
2560 // values to materialize an expression. I.e., even if this value is
2561 // anchored in a different basic block, the actual first sub expression
2562 // will be anchored on the second value.
2563 for (int i = StartIdx - 1; i != -1; --i) {
2564 const Value *Val = Ops[i].Op;
2565 const auto *CurrLeafInstr = dyn_cast<Instruction>(Val);
2566 const BasicBlock *SeenBB = nullptr;
2567 if (!CurrLeafInstr) {
2568 // The value is free of any CFG dependencies.
2569 // Do as if it lives in the entry block.
2570 //
2571 // We do this to make sure all the values falling on this path are
2572 // seen through the same anchor point. The rationale is these values
2573 // can be combined together to from a sub expression free of any CFG
2574 // dependencies so we want them to stay together.
2575 // We could be cleverer and postpone the anchor down to the first
2576 // anchored value, but that's likely complicated to get right.
2577 // E.g., we wouldn't want to do that if that means being stuck in a
2578 // loop.
2579 //
2580 // For instance, we wouldn't want to change:
2581 // res = arg1 op arg2 op arg3 op ... op loop_val1 op loop_val2 ...
2582 // into
2583 // res = loop_val1 op arg1 op arg2 op arg3 op ... op loop_val2 ...
2584 // Because all the sub expressions with arg2..N would be stuck between
2585 // two loop dependent values.
2586 SeenBB = &I->getParent()->getParent()->getEntryBlock();
2587 } else {
2588 SeenBB = CurrLeafInstr->getParent();
2589 }
2590
2591 if (!FirstSeenBB) {
2592 FirstSeenBB = SeenBB;
2593 continue;
2594 }
2595 if (FirstSeenBB != SeenBB) {
2596 // ith value is in a different basic block.
2597 // Rewind the index once to point to the last value on the same basic
2598 // block.
2599 LimitIdx = i + 1;
2600 LLVM_DEBUG(dbgs() << "CSE reordering: Consider values between ["
2601 << LimitIdx << ", " << StartIdx << "]\n");
2602 break;
2603 }
2604 }
2605 }
2606 for (unsigned i = Ops.size() - 1; i > LimitIdx; --i) {
2607 // We must use int type to go below zero when LimitIdx is 0.
2608 for (int j = i - 1; j >= (int)LimitIdx; --j) {
2609 unsigned Score = 0;
2610 Value *Op0 = Ops[i].Op;
2611 Value *Op1 = Ops[j].Op;
2612 if (std::less<Value *>()(Op1, Op0))
2613 std::swap(a&: Op0, b&: Op1);
2614 auto it = PairMap[Idx].find(Val: {Op0, Op1});
2615 if (it != PairMap[Idx].end()) {
2616 // Functions like BreakUpSubtract() can erase the Values we're using
2617 // as keys and create new Values after we built the PairMap. There's a
2618 // small chance that the new nodes can have the same address as
2619 // something already in the table. We shouldn't accumulate the stored
2620 // score in that case as it refers to the wrong Value.
2621 if (it->second.isValid())
2622 Score += it->second.Score;
2623 }
2624
2625 unsigned MaxRank = std::max(a: Ops[i].Rank, b: Ops[j].Rank);
2626
2627 // By construction, the operands are sorted in reverse order of their
2628 // topological order.
2629 // So we tend to form (sub) expressions with values that are close to
2630 // each other.
2631 //
2632 // Now to expose more CSE opportunities we want to expose the pair of
2633 // operands that occur the most (as statically computed in
2634 // BuildPairMap.) as the first sub-expression.
2635 //
2636 // If two pairs occur as many times, we pick the one with the
2637 // lowest rank, meaning the one with both operands appearing first in
2638 // the topological order.
2639 if (Score > Max || (Score == Max && MaxRank < BestRank)) {
2640 BestPair = {j, i};
2641 Max = Score;
2642 BestRank = MaxRank;
2643 }
2644 }
2645 }
2646 if (Max > 1) {
2647 auto Op0 = Ops[BestPair.first];
2648 auto Op1 = Ops[BestPair.second];
2649 Ops.erase(CI: &Ops[BestPair.second]);
2650 Ops.erase(CI: &Ops[BestPair.first]);
2651 Ops.push_back(Elt: Op0);
2652 Ops.push_back(Elt: Op1);
2653 }
2654 }
2655 LLVM_DEBUG(dbgs() << "RAOut after CSE reorder:\t"; PrintOps(I, Ops);
2656 dbgs() << '\n');
2657 // Now that we ordered and optimized the expressions, splat them back into
2658 // the expression tree, removing any unneeded nodes.
2659 RewriteExprTree(I, Ops, Flags);
2660}
2661
2662void
2663ReassociatePass::BuildPairMap(ReversePostOrderTraversal<Function *> &RPOT) {
2664 // Make a "pairmap" of how often each operand pair occurs.
2665 for (BasicBlock *BI : RPOT) {
2666 for (Instruction &I : *BI) {
2667 if (!I.isAssociative() || !I.isBinaryOp())
2668 continue;
2669
2670 // Ignore nodes that aren't at the root of trees.
2671 if (I.hasOneUse() && I.user_back()->getOpcode() == I.getOpcode())
2672 continue;
2673
2674 // Collect all operands in a single reassociable expression.
2675 // Since Reassociate has already been run once, we can assume things
2676 // are already canonical according to Reassociation's regime.
2677 SmallVector<Value *, 8> Worklist = { I.getOperand(i: 0), I.getOperand(i: 1) };
2678 SmallVector<Value *, 8> Ops;
2679 while (!Worklist.empty() && Ops.size() <= GlobalReassociateLimit) {
2680 Value *Op = Worklist.pop_back_val();
2681 Instruction *OpI = dyn_cast<Instruction>(Val: Op);
2682 if (!OpI || OpI->getOpcode() != I.getOpcode() || !OpI->hasOneUse()) {
2683 Ops.push_back(Elt: Op);
2684 continue;
2685 }
2686 // Be paranoid about self-referencing expressions in unreachable code.
2687 if (OpI->getOperand(i: 0) != OpI)
2688 Worklist.push_back(Elt: OpI->getOperand(i: 0));
2689 if (OpI->getOperand(i: 1) != OpI)
2690 Worklist.push_back(Elt: OpI->getOperand(i: 1));
2691 }
2692 // Skip extremely long expressions.
2693 if (Ops.size() > GlobalReassociateLimit)
2694 continue;
2695
2696 // Add all pairwise combinations of operands to the pair map.
2697 unsigned BinaryIdx = I.getOpcode() - Instruction::BinaryOpsBegin;
2698 SmallSet<std::pair<Value *, Value*>, 32> Visited;
2699 for (unsigned i = 0; i < Ops.size() - 1; ++i) {
2700 for (unsigned j = i + 1; j < Ops.size(); ++j) {
2701 // Canonicalize operand orderings.
2702 Value *Op0 = Ops[i];
2703 Value *Op1 = Ops[j];
2704 if (std::less<Value *>()(Op1, Op0))
2705 std::swap(a&: Op0, b&: Op1);
2706 if (!Visited.insert(V: {Op0, Op1}).second)
2707 continue;
2708 auto res = PairMap[BinaryIdx].insert(KV: {{Op0, Op1}, {.Value1: Op0, .Value2: Op1, .Score: 1}});
2709 if (!res.second) {
2710 // If either key value has been erased then we've got the same
2711 // address by coincidence. That can't happen here because nothing is
2712 // erasing values but it can happen by the time we're querying the
2713 // map.
2714 assert(res.first->second.isValid() && "WeakVH invalidated");
2715 ++res.first->second.Score;
2716 }
2717 }
2718 }
2719 }
2720 }
2721}
2722
2723PreservedAnalyses ReassociatePass::run(Function &F,
2724 FunctionAnalysisManager &AM) {
2725 // UniformityInfo is empty (and cheap) on targets without branch divergence,
2726 // so request it unconditionally.
2727 UniformityInfo &UI = AM.getResult<UniformityInfoAnalysis>(IR&: F);
2728 return runImpl(F, UI);
2729}
2730
2731PreservedAnalyses ReassociatePass::runImpl(Function &F, UniformityInfo &UI) {
2732 UA = &UI;
2733
2734 // Get the functions basic blocks in Reverse Post Order. This order is used by
2735 // BuildRankMap to pre calculate ranks correctly. It also excludes dead basic
2736 // blocks (it has been seen that the analysis in this pass could hang when
2737 // analysing dead basic blocks).
2738 ReversePostOrderTraversal<Function *> RPOT(&F);
2739
2740 // Calculate the rank map for F.
2741 BuildRankMap(F, RPOT);
2742
2743 // Build the pair map before running reassociate.
2744 // Technically this would be more accurate if we did it after one round
2745 // of reassociation, but in practice it doesn't seem to help much on
2746 // real-world code, so don't waste the compile time running reassociate
2747 // twice.
2748 // If a user wants, they could expicitly run reassociate twice in their
2749 // pass pipeline for further potential gains.
2750 // It might also be possible to update the pair map during runtime, but the
2751 // overhead of that may be large if there's many reassociable chains.
2752 BuildPairMap(RPOT);
2753
2754 MadeChange = false;
2755
2756 // Traverse the same blocks that were analysed by BuildRankMap.
2757 for (BasicBlock *BI : RPOT) {
2758 assert(RankMap.count(&*BI) && "BB should be ranked.");
2759 // Optimize every instruction in the basic block.
2760 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;)
2761 if (isInstructionTriviallyDead(I: &*II)) {
2762 EraseInst(I: &*II++);
2763 } else {
2764 OptimizeInst(I: &*II);
2765 assert(II->getParent() == &*BI && "Moved to a different block!");
2766 ++II;
2767 }
2768
2769 // Make a copy of all the instructions to be redone so we can remove dead
2770 // instructions.
2771 OrderedSet ToRedo(RedoInsts);
2772 // Iterate over all instructions to be reevaluated and remove trivially dead
2773 // instructions. If any operand of the trivially dead instruction becomes
2774 // dead mark it for deletion as well. Continue this process until all
2775 // trivially dead instructions have been removed.
2776 while (!ToRedo.empty()) {
2777 Instruction *I = ToRedo.pop_back_val();
2778 if (isInstructionTriviallyDead(I)) {
2779 RecursivelyEraseDeadInsts(I, Insts&: ToRedo);
2780 MadeChange = true;
2781 }
2782 }
2783
2784 // Now that we have removed dead instructions, we can reoptimize the
2785 // remaining instructions.
2786 while (!RedoInsts.empty()) {
2787 Instruction *I = RedoInsts.front();
2788 RedoInsts.erase(I: RedoInsts.begin());
2789 if (isInstructionTriviallyDead(I))
2790 EraseInst(I);
2791 else
2792 OptimizeInst(I);
2793 }
2794 }
2795
2796 // We are done with the rank map, pair map, and uniformity info.
2797 RankMap.clear();
2798 ValueRankMap.clear();
2799 for (auto &Entry : PairMap)
2800 Entry.clear();
2801 UA = nullptr;
2802
2803 if (MadeChange) {
2804 PreservedAnalyses PA;
2805 PA.preserveSet<CFGAnalyses>();
2806 return PA;
2807 }
2808
2809 return PreservedAnalyses::all();
2810}
2811
2812namespace {
2813
2814class ReassociateLegacyPass : public FunctionPass {
2815 ReassociatePass Impl;
2816
2817public:
2818 static char ID; // Pass identification, replacement for typeid
2819
2820 ReassociateLegacyPass() : FunctionPass(ID) {
2821 initializeReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
2822 }
2823
2824 bool runOnFunction(Function &F) override {
2825 if (skipFunction(F))
2826 return false;
2827
2828 UniformityInfo &UI =
2829 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
2830
2831 PreservedAnalyses PA = Impl.runImpl(F, UI);
2832 return !PA.areAllPreserved();
2833 }
2834
2835 void getAnalysisUsage(AnalysisUsage &AU) const override {
2836 AU.setPreservesCFG();
2837 AU.addRequired<UniformityInfoWrapperPass>();
2838 AU.addPreserved<AAResultsWrapperPass>();
2839 AU.addPreserved<GlobalsAAWrapperPass>();
2840 }
2841};
2842
2843} // end anonymous namespace
2844
2845char ReassociateLegacyPass::ID = 0;
2846
2847INITIALIZE_PASS_BEGIN(ReassociateLegacyPass, "reassociate",
2848 "Reassociate expressions", false, false)
2849INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
2850INITIALIZE_PASS_END(ReassociateLegacyPass, "reassociate",
2851 "Reassociate expressions", false, false)
2852
2853// Public interface to the Reassociate pass
2854FunctionPass *llvm::createReassociatePass() {
2855 return new ReassociateLegacyPass();
2856}
2857