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