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