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