1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "InstCombineInternal.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/CFG.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/GlobalsModRef.h"
46 #include "llvm/Analysis/InstructionSimplify.h"
47 #include "llvm/Analysis/LibCallSemantics.h"
48 #include "llvm/Analysis/LoopInfo.h"
49 #include "llvm/Analysis/MemoryBuiltins.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/CFG.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/GetElementPtrTypeIterator.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/PatternMatch.h"
58 #include "llvm/IR/ValueHandle.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include "llvm/Transforms/Utils/Local.h"
67 using namespace llvm::PatternMatch;
69 #define DEBUG_TYPE "instcombine"
71 STATISTIC(NumCombined , "Number of insts combined");
72 STATISTIC(NumConstProp, "Number of constant folds");
73 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75 STATISTIC(NumExpand, "Number of expansions");
76 STATISTIC(NumFactor , "Number of factorizations");
77 STATISTIC(NumReassoc , "Number of reassociations");
79 Value *InstCombiner::EmitGEPOffset(User *GEP) {
80 return llvm::EmitGEPOffset(Builder, DL, GEP);
83 /// Return true if it is desirable to convert an integer computation from a
84 /// given bit width to a new bit width.
85 /// We don't want to convert from a legal to an illegal type for example or from
86 /// a smaller to a larger illegal type.
87 bool InstCombiner::ShouldChangeType(unsigned FromWidth,
88 unsigned ToWidth) const {
89 bool FromLegal = DL.isLegalInteger(FromWidth);
90 bool ToLegal = DL.isLegalInteger(ToWidth);
92 // If this is a legal integer from type, and the result would be an illegal
93 // type, don't do the transformation.
94 if (FromLegal && !ToLegal)
97 // Otherwise, if both are illegal, do not increase the size of the result. We
98 // do allow things like i160 -> i64, but not i64 -> i160.
99 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
105 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
106 /// We don't want to convert from a legal to an illegal type for example or from
107 /// a smaller to a larger illegal type.
108 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
109 assert(From->isIntegerTy() && To->isIntegerTy());
111 unsigned FromWidth = From->getPrimitiveSizeInBits();
112 unsigned ToWidth = To->getPrimitiveSizeInBits();
113 return ShouldChangeType(FromWidth, ToWidth);
116 // Return true, if No Signed Wrap should be maintained for I.
117 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
118 // where both B and C should be ConstantInts, results in a constant that does
119 // not overflow. This function only handles the Add and Sub opcodes. For
120 // all other opcodes, the function conservatively returns false.
121 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
122 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
123 if (!OBO || !OBO->hasNoSignedWrap()) {
127 // We reason about Add and Sub Only.
128 Instruction::BinaryOps Opcode = I.getOpcode();
129 if (Opcode != Instruction::Add &&
130 Opcode != Instruction::Sub) {
134 ConstantInt *CB = dyn_cast<ConstantInt>(B);
135 ConstantInt *CC = dyn_cast<ConstantInt>(C);
141 const APInt &BVal = CB->getValue();
142 const APInt &CVal = CC->getValue();
143 bool Overflow = false;
145 if (Opcode == Instruction::Add) {
146 BVal.sadd_ov(CVal, Overflow);
148 BVal.ssub_ov(CVal, Overflow);
154 /// Conservatively clears subclassOptionalData after a reassociation or
155 /// commutation. We preserve fast-math flags when applicable as they can be
157 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
158 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
160 I.clearSubclassOptionalData();
164 FastMathFlags FMF = I.getFastMathFlags();
165 I.clearSubclassOptionalData();
166 I.setFastMathFlags(FMF);
169 /// This performs a few simplifications for operators that are associative or
172 /// Commutative operators:
174 /// 1. Order operands such that they are listed from right (least complex) to
175 /// left (most complex). This puts constants before unary operators before
176 /// binary operators.
178 /// Associative operators:
180 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
181 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
183 /// Associative and commutative operators:
185 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
186 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
187 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
188 /// if C1 and C2 are constants.
189 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
190 Instruction::BinaryOps Opcode = I.getOpcode();
191 bool Changed = false;
194 // Order operands such that they are listed from right (least complex) to
195 // left (most complex). This puts constants before unary operators before
197 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
198 getComplexity(I.getOperand(1)))
199 Changed = !I.swapOperands();
201 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
202 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
204 if (I.isAssociative()) {
205 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
206 if (Op0 && Op0->getOpcode() == Opcode) {
207 Value *A = Op0->getOperand(0);
208 Value *B = Op0->getOperand(1);
209 Value *C = I.getOperand(1);
211 // Does "B op C" simplify?
212 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
213 // It simplifies to V. Form "A op V".
216 // Conservatively clear the optional flags, since they may not be
217 // preserved by the reassociation.
218 if (MaintainNoSignedWrap(I, B, C) &&
219 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
220 // Note: this is only valid because SimplifyBinOp doesn't look at
221 // the operands to Op0.
222 I.clearSubclassOptionalData();
223 I.setHasNoSignedWrap(true);
225 ClearSubclassDataAfterReassociation(I);
234 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
235 if (Op1 && Op1->getOpcode() == Opcode) {
236 Value *A = I.getOperand(0);
237 Value *B = Op1->getOperand(0);
238 Value *C = Op1->getOperand(1);
240 // Does "A op B" simplify?
241 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
242 // It simplifies to V. Form "V op C".
245 // Conservatively clear the optional flags, since they may not be
246 // preserved by the reassociation.
247 ClearSubclassDataAfterReassociation(I);
255 if (I.isAssociative() && I.isCommutative()) {
256 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
257 if (Op0 && Op0->getOpcode() == Opcode) {
258 Value *A = Op0->getOperand(0);
259 Value *B = Op0->getOperand(1);
260 Value *C = I.getOperand(1);
262 // Does "C op A" simplify?
263 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
264 // It simplifies to V. Form "V op B".
267 // Conservatively clear the optional flags, since they may not be
268 // preserved by the reassociation.
269 ClearSubclassDataAfterReassociation(I);
276 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
277 if (Op1 && Op1->getOpcode() == Opcode) {
278 Value *A = I.getOperand(0);
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
282 // Does "C op A" simplify?
283 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
284 // It simplifies to V. Form "B op V".
287 // Conservatively clear the optional flags, since they may not be
288 // preserved by the reassociation.
289 ClearSubclassDataAfterReassociation(I);
296 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
297 // if C1 and C2 are constants.
299 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
300 isa<Constant>(Op0->getOperand(1)) &&
301 isa<Constant>(Op1->getOperand(1)) &&
302 Op0->hasOneUse() && Op1->hasOneUse()) {
303 Value *A = Op0->getOperand(0);
304 Constant *C1 = cast<Constant>(Op0->getOperand(1));
305 Value *B = Op1->getOperand(0);
306 Constant *C2 = cast<Constant>(Op1->getOperand(1));
308 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
309 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
310 if (isa<FPMathOperator>(New)) {
311 FastMathFlags Flags = I.getFastMathFlags();
312 Flags &= Op0->getFastMathFlags();
313 Flags &= Op1->getFastMathFlags();
314 New->setFastMathFlags(Flags);
316 InsertNewInstWith(New, I);
318 I.setOperand(0, New);
319 I.setOperand(1, Folded);
320 // Conservatively clear the optional flags, since they may not be
321 // preserved by the reassociation.
322 ClearSubclassDataAfterReassociation(I);
329 // No further simplifications.
334 /// Return whether "X LOp (Y ROp Z)" is always equal to
335 /// "(X LOp Y) ROp (X LOp Z)".
336 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
337 Instruction::BinaryOps ROp) {
342 case Instruction::And:
343 // And distributes over Or and Xor.
347 case Instruction::Or:
348 case Instruction::Xor:
352 case Instruction::Mul:
353 // Multiplication distributes over addition and subtraction.
357 case Instruction::Add:
358 case Instruction::Sub:
362 case Instruction::Or:
363 // Or distributes over And.
367 case Instruction::And:
373 /// Return whether "(X LOp Y) ROp Z" is always equal to
374 /// "(X ROp Z) LOp (Y ROp Z)".
375 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
376 Instruction::BinaryOps ROp) {
377 if (Instruction::isCommutative(ROp))
378 return LeftDistributesOverRight(ROp, LOp);
383 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
384 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
385 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
386 case Instruction::And:
387 case Instruction::Or:
388 case Instruction::Xor:
392 case Instruction::Shl:
393 case Instruction::LShr:
394 case Instruction::AShr:
398 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
399 // but this requires knowing that the addition does not overflow and other
404 /// This function returns identity value for given opcode, which can be used to
405 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
406 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
407 if (isa<Constant>(V))
410 if (OpCode == Instruction::Mul)
411 return ConstantInt::get(V->getType(), 1);
413 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
418 /// This function factors binary ops which can be combined using distributive
419 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
420 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
421 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
422 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
424 static Instruction::BinaryOps
425 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
426 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
428 return Instruction::BinaryOpsEnd;
430 LHS = Op->getOperand(0);
431 RHS = Op->getOperand(1);
433 switch (TopLevelOpcode) {
435 return Op->getOpcode();
437 case Instruction::Add:
438 case Instruction::Sub:
439 if (Op->getOpcode() == Instruction::Shl) {
440 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
441 // The multiplier is really 1 << CST.
442 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
443 return Instruction::Mul;
446 return Op->getOpcode();
449 // TODO: We can add other conversions e.g. shr => div etc.
452 /// This tries to simplify binary operations by factorizing out common terms
453 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
454 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
455 const DataLayout &DL, BinaryOperator &I,
456 Instruction::BinaryOps InnerOpcode, Value *A,
457 Value *B, Value *C, Value *D) {
459 // If any of A, B, C, D are null, we can not factor I, return early.
460 // Checking A and C should be enough.
461 if (!A || !C || !B || !D)
465 Value *SimplifiedInst = nullptr;
466 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
467 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
469 // Does "X op' Y" always equal "Y op' X"?
470 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
472 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
473 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
474 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
475 // commutative case, "(A op' B) op (C op' A)"?
476 if (A == C || (InnerCommutative && A == D)) {
479 // Consider forming "A op' (B op D)".
480 // If "B op D" simplifies then it can be formed with no cost.
481 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
482 // If "B op D" doesn't simplify then only go on if both of the existing
483 // operations "A op' B" and "C op' D" will be zapped as no longer used.
484 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
485 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
487 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
491 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
492 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
493 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
494 // commutative case, "(A op' B) op (B op' D)"?
495 if (B == D || (InnerCommutative && B == C)) {
498 // Consider forming "(A op C) op' B".
499 // If "A op C" simplifies then it can be formed with no cost.
500 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
502 // If "A op C" doesn't simplify then only go on if both of the existing
503 // operations "A op' B" and "C op' D" will be zapped as no longer used.
504 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
505 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
507 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
511 if (SimplifiedInst) {
513 SimplifiedInst->takeName(&I);
515 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
516 // TODO: Check for NUW.
517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
518 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
520 if (isa<OverflowingBinaryOperator>(&I))
521 HasNSW = I.hasNoSignedWrap();
523 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
524 if (isa<OverflowingBinaryOperator>(Op0))
525 HasNSW &= Op0->hasNoSignedWrap();
527 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
528 if (isa<OverflowingBinaryOperator>(Op1))
529 HasNSW &= Op1->hasNoSignedWrap();
531 // We can propagate 'nsw' if we know that
532 // %Y = mul nsw i16 %X, C
533 // %Z = add nsw i16 %Y, %X
535 // %Z = mul nsw i16 %X, C+1
537 // iff C+1 isn't INT_MIN
539 if (TopLevelOpcode == Instruction::Add &&
540 InnerOpcode == Instruction::Mul)
541 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
542 BO->setHasNoSignedWrap(HasNSW);
546 return SimplifiedInst;
549 /// This tries to simplify binary operations which some other binary operation
550 /// distributes over either by factorizing out common terms
551 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
552 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
553 /// Returns the simplified value, or null if it didn't simplify.
554 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
555 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
556 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
557 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
560 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
561 auto TopLevelOpcode = I.getOpcode();
562 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
563 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
565 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
567 if (LHSOpcode == RHSOpcode) {
568 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
572 // The instruction has the form "(A op' B) op (C)". Try to factorize common
574 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
575 getIdentityValue(LHSOpcode, RHS)))
578 // The instruction has the form "(B) op (C op' D)". Try to factorize common
580 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
581 getIdentityValue(RHSOpcode, LHS), C, D))
585 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
586 // The instruction has the form "(A op' B) op C". See if expanding it out
587 // to "(A op C) op' (B op C)" results in simplifications.
588 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
589 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
591 // Do "A op C" and "B op C" both simplify?
592 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
593 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
594 // They do! Return "L op' R".
596 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
597 if ((L == A && R == B) ||
598 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
600 // Otherwise return "L op' R" if it simplifies.
601 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
603 // Otherwise, create a new instruction.
604 C = Builder->CreateBinOp(InnerOpcode, L, R);
610 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
611 // The instruction has the form "A op (B op' C)". See if expanding it out
612 // to "(A op B) op' (A op C)" results in simplifications.
613 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
614 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
616 // Do "A op B" and "A op C" both simplify?
617 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
618 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
619 // They do! Return "L op' R".
621 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
622 if ((L == B && R == C) ||
623 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
625 // Otherwise return "L op' R" if it simplifies.
626 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
628 // Otherwise, create a new instruction.
629 A = Builder->CreateBinOp(InnerOpcode, L, R);
635 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
636 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
637 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
638 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
639 if (SI0->getCondition() == SI1->getCondition()) {
641 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
642 SI1->getFalseValue(), DL, TLI, DT, AC))
643 SI = Builder->CreateSelect(SI0->getCondition(),
644 Builder->CreateBinOp(TopLevelOpcode,
646 SI1->getTrueValue()),
648 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
649 SI1->getTrueValue(), DL, TLI, DT, AC))
650 SI = Builder->CreateSelect(
651 SI0->getCondition(), V,
652 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
653 SI1->getFalseValue()));
665 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
666 /// constant zero (which is the 'negate' form).
667 Value *InstCombiner::dyn_castNegVal(Value *V) const {
668 if (BinaryOperator::isNeg(V))
669 return BinaryOperator::getNegArgument(V);
671 // Constants can be considered to be negated values if they can be folded.
672 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
673 return ConstantExpr::getNeg(C);
675 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
676 if (C->getType()->getElementType()->isIntegerTy())
677 return ConstantExpr::getNeg(C);
682 /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
683 /// a constant negative zero (which is the 'negate' form).
684 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
685 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
686 return BinaryOperator::getFNegArgument(V);
688 // Constants can be considered to be negated values if they can be folded.
689 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
690 return ConstantExpr::getFNeg(C);
692 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
693 if (C->getType()->getElementType()->isFloatingPointTy())
694 return ConstantExpr::getFNeg(C);
699 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
701 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
702 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
705 // Figure out if the constant is the left or the right argument.
706 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
707 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
709 if (Constant *SOC = dyn_cast<Constant>(SO)) {
711 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
712 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
715 Value *Op0 = SO, *Op1 = ConstOperand;
719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
720 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
721 SO->getName()+".op");
722 Instruction *FPInst = dyn_cast<Instruction>(RI);
723 if (FPInst && isa<FPMathOperator>(FPInst))
724 FPInst->copyFastMathFlags(BO);
727 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
728 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
729 SO->getName()+".cmp");
730 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
731 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
732 SO->getName()+".cmp");
733 llvm_unreachable("Unknown binary instruction type!");
736 /// Given an instruction with a select as one operand and a constant as the
737 /// other operand, try to fold the binary operator into the select arguments.
738 /// This also works for Cast instructions, which obviously do not have a second
740 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
741 // Don't modify shared select instructions
742 if (!SI->hasOneUse()) return nullptr;
743 Value *TV = SI->getOperand(1);
744 Value *FV = SI->getOperand(2);
746 if (isa<Constant>(TV) || isa<Constant>(FV)) {
747 // Bool selects with constant operands can be folded to logical ops.
748 if (SI->getType()->isIntegerTy(1)) return nullptr;
750 // If it's a bitcast involving vectors, make sure it has the same number of
751 // elements on both sides.
752 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
753 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
754 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
756 // Verify that either both or neither are vectors.
757 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
758 // If vectors, verify that they have the same number of elements.
759 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
763 // Test if a CmpInst instruction is used exclusively by a select as
764 // part of a minimum or maximum operation. If so, refrain from doing
765 // any other folding. This helps out other analyses which understand
766 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
767 // and CodeGen. And in this case, at least one of the comparison
768 // operands has at least one user besides the compare (the select),
769 // which would often largely negate the benefit of folding anyway.
770 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
771 if (CI->hasOneUse()) {
772 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
773 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
774 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
779 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
780 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
782 return SelectInst::Create(SI->getCondition(),
783 SelectTrueVal, SelectFalseVal);
788 /// Given a binary operator, cast instruction, or select which has a PHI node as
789 /// operand #0, see if we can fold the instruction into the PHI (which is only
790 /// possible if all operands to the PHI are constants).
791 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
792 PHINode *PN = cast<PHINode>(I.getOperand(0));
793 unsigned NumPHIValues = PN->getNumIncomingValues();
794 if (NumPHIValues == 0)
797 // We normally only transform phis with a single use. However, if a PHI has
798 // multiple uses and they are all the same operation, we can fold *all* of the
799 // uses into the PHI.
800 if (!PN->hasOneUse()) {
801 // Walk the use list for the instruction, comparing them to I.
802 for (User *U : PN->users()) {
803 Instruction *UI = cast<Instruction>(U);
804 if (UI != &I && !I.isIdenticalTo(UI))
807 // Otherwise, we can replace *all* users with the new PHI we form.
810 // Check to see if all of the operands of the PHI are simple constants
811 // (constantint/constantfp/undef). If there is one non-constant value,
812 // remember the BB it is in. If there is more than one or if *it* is a PHI,
813 // bail out. We don't do arbitrary constant expressions here because moving
814 // their computation can be expensive without a cost model.
815 BasicBlock *NonConstBB = nullptr;
816 for (unsigned i = 0; i != NumPHIValues; ++i) {
817 Value *InVal = PN->getIncomingValue(i);
818 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
821 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
822 if (NonConstBB) return nullptr; // More than one non-const value.
824 NonConstBB = PN->getIncomingBlock(i);
826 // If the InVal is an invoke at the end of the pred block, then we can't
827 // insert a computation after it without breaking the edge.
828 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
829 if (II->getParent() == NonConstBB)
832 // If the incoming non-constant value is in I's block, we will remove one
833 // instruction, but insert another equivalent one, leading to infinite
835 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
839 // If there is exactly one non-constant value, we can insert a copy of the
840 // operation in that block. However, if this is a critical edge, we would be
841 // inserting the computation on some other paths (e.g. inside a loop). Only
842 // do this if the pred block is unconditionally branching into the phi block.
843 if (NonConstBB != nullptr) {
844 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
845 if (!BI || !BI->isUnconditional()) return nullptr;
848 // Okay, we can do the transformation: create the new PHI node.
849 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
850 InsertNewInstBefore(NewPN, *PN);
853 // If we are going to have to insert a new computation, do so right before the
854 // predecessor's terminator.
856 Builder->SetInsertPoint(NonConstBB->getTerminator());
858 // Next, add all of the operands to the PHI.
859 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
860 // We only currently try to fold the condition of a select when it is a phi,
861 // not the true/false values.
862 Value *TrueV = SI->getTrueValue();
863 Value *FalseV = SI->getFalseValue();
864 BasicBlock *PhiTransBB = PN->getParent();
865 for (unsigned i = 0; i != NumPHIValues; ++i) {
866 BasicBlock *ThisBB = PN->getIncomingBlock(i);
867 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
868 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
869 Value *InV = nullptr;
870 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
871 // even if currently isNullValue gives false.
872 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
873 if (InC && !isa<ConstantExpr>(InC))
874 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
876 InV = Builder->CreateSelect(PN->getIncomingValue(i),
877 TrueVInPred, FalseVInPred, "phitmp");
878 NewPN->addIncoming(InV, ThisBB);
880 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
881 Constant *C = cast<Constant>(I.getOperand(1));
882 for (unsigned i = 0; i != NumPHIValues; ++i) {
883 Value *InV = nullptr;
884 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
885 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
886 else if (isa<ICmpInst>(CI))
887 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
890 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
892 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
894 } else if (I.getNumOperands() == 2) {
895 Constant *C = cast<Constant>(I.getOperand(1));
896 for (unsigned i = 0; i != NumPHIValues; ++i) {
897 Value *InV = nullptr;
898 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
899 InV = ConstantExpr::get(I.getOpcode(), InC, C);
901 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
902 PN->getIncomingValue(i), C, "phitmp");
903 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
906 CastInst *CI = cast<CastInst>(&I);
907 Type *RetTy = CI->getType();
908 for (unsigned i = 0; i != NumPHIValues; ++i) {
910 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
911 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
913 InV = Builder->CreateCast(CI->getOpcode(),
914 PN->getIncomingValue(i), I.getType(), "phitmp");
915 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
919 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
920 Instruction *User = cast<Instruction>(*UI++);
921 if (User == &I) continue;
922 ReplaceInstUsesWith(*User, NewPN);
923 EraseInstFromFunction(*User);
925 return ReplaceInstUsesWith(I, NewPN);
928 /// Given a pointer type and a constant offset, determine whether or not there
929 /// is a sequence of GEP indices into the pointed type that will land us at the
930 /// specified offset. If so, fill them into NewIndices and return the resultant
931 /// element type, otherwise return null.
932 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
933 SmallVectorImpl<Value *> &NewIndices) {
934 Type *Ty = PtrTy->getElementType();
938 // Start with the index over the outer type. Note that the type size
939 // might be zero (even if the offset isn't zero) if the indexed type
940 // is something like [0 x {int, int}]
941 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
942 int64_t FirstIdx = 0;
943 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
944 FirstIdx = Offset/TySize;
945 Offset -= FirstIdx*TySize;
947 // Handle hosts where % returns negative instead of values [0..TySize).
953 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
956 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
958 // Index into the types. If we fail, set OrigBase to null.
960 // Indexing into tail padding between struct/array elements.
961 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
964 if (StructType *STy = dyn_cast<StructType>(Ty)) {
965 const StructLayout *SL = DL.getStructLayout(STy);
966 assert(Offset < (int64_t)SL->getSizeInBytes() &&
967 "Offset must stay within the indexed type");
969 unsigned Elt = SL->getElementContainingOffset(Offset);
970 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
973 Offset -= SL->getElementOffset(Elt);
974 Ty = STy->getElementType(Elt);
975 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
976 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
977 assert(EltSize && "Cannot index into a zero-sized array");
978 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
980 Ty = AT->getElementType();
982 // Otherwise, we can't index into the middle of this atomic type, bail.
990 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
991 // If this GEP has only 0 indices, it is the same pointer as
992 // Src. If Src is not a trivial GEP too, don't combine
994 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1000 /// Return a value X such that Val = X * Scale, or null if none.
1001 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1002 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1003 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1004 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1005 Scale.getBitWidth() && "Scale not compatible with value!");
1007 // If Val is zero or Scale is one then Val = Val * Scale.
1008 if (match(Val, m_Zero()) || Scale == 1) {
1009 NoSignedWrap = true;
1013 // If Scale is zero then it does not divide Val.
1014 if (Scale.isMinValue())
1017 // Look through chains of multiplications, searching for a constant that is
1018 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1019 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1020 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1023 // Val = M1 * X || Analysis starts here and works down
1024 // M1 = M2 * Y || Doesn't descend into terms with more
1025 // M2 = Z * 4 \/ than one use
1027 // Then to modify a term at the bottom:
1030 // M1 = Z * Y || Replaced M2 with Z
1032 // Then to work back up correcting nsw flags.
1034 // Op - the term we are currently analyzing. Starts at Val then drills down.
1035 // Replaced with its descaled value before exiting from the drill down loop.
1038 // Parent - initially null, but after drilling down notes where Op came from.
1039 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1040 // 0'th operand of Val.
1041 std::pair<Instruction*, unsigned> Parent;
1043 // Set if the transform requires a descaling at deeper levels that doesn't
1045 bool RequireNoSignedWrap = false;
1047 // Log base 2 of the scale. Negative if not a power of 2.
1048 int32_t logScale = Scale.exactLogBase2();
1050 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1053 // If Op is a constant divisible by Scale then descale to the quotient.
1054 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1055 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1056 if (!Remainder.isMinValue())
1057 // Not divisible by Scale.
1059 // Replace with the quotient in the parent.
1060 Op = ConstantInt::get(CI->getType(), Quotient);
1061 NoSignedWrap = true;
1065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1067 if (BO->getOpcode() == Instruction::Mul) {
1069 NoSignedWrap = BO->hasNoSignedWrap();
1070 if (RequireNoSignedWrap && !NoSignedWrap)
1073 // There are three cases for multiplication: multiplication by exactly
1074 // the scale, multiplication by a constant different to the scale, and
1075 // multiplication by something else.
1076 Value *LHS = BO->getOperand(0);
1077 Value *RHS = BO->getOperand(1);
1079 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1080 // Multiplication by a constant.
1081 if (CI->getValue() == Scale) {
1082 // Multiplication by exactly the scale, replace the multiplication
1083 // by its left-hand side in the parent.
1088 // Otherwise drill down into the constant.
1089 if (!Op->hasOneUse())
1092 Parent = std::make_pair(BO, 1);
1096 // Multiplication by something else. Drill down into the left-hand side
1097 // since that's where the reassociate pass puts the good stuff.
1098 if (!Op->hasOneUse())
1101 Parent = std::make_pair(BO, 0);
1105 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1106 isa<ConstantInt>(BO->getOperand(1))) {
1107 // Multiplication by a power of 2.
1108 NoSignedWrap = BO->hasNoSignedWrap();
1109 if (RequireNoSignedWrap && !NoSignedWrap)
1112 Value *LHS = BO->getOperand(0);
1113 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1114 getLimitedValue(Scale.getBitWidth());
1117 if (Amt == logScale) {
1118 // Multiplication by exactly the scale, replace the multiplication
1119 // by its left-hand side in the parent.
1123 if (Amt < logScale || !Op->hasOneUse())
1126 // Multiplication by more than the scale. Reduce the multiplying amount
1127 // by the scale in the parent.
1128 Parent = std::make_pair(BO, 1);
1129 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1134 if (!Op->hasOneUse())
1137 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1138 if (Cast->getOpcode() == Instruction::SExt) {
1139 // Op is sign-extended from a smaller type, descale in the smaller type.
1140 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1141 APInt SmallScale = Scale.trunc(SmallSize);
1142 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1143 // descale Op as (sext Y) * Scale. In order to have
1144 // sext (Y * SmallScale) = (sext Y) * Scale
1145 // some conditions need to hold however: SmallScale must sign-extend to
1146 // Scale and the multiplication Y * SmallScale should not overflow.
1147 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1148 // SmallScale does not sign-extend to Scale.
1150 assert(SmallScale.exactLogBase2() == logScale);
1151 // Require that Y * SmallScale must not overflow.
1152 RequireNoSignedWrap = true;
1154 // Drill down through the cast.
1155 Parent = std::make_pair(Cast, 0);
1160 if (Cast->getOpcode() == Instruction::Trunc) {
1161 // Op is truncated from a larger type, descale in the larger type.
1162 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1163 // trunc (Y * sext Scale) = (trunc Y) * Scale
1164 // always holds. However (trunc Y) * Scale may overflow even if
1165 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1166 // from this point up in the expression (see later).
1167 if (RequireNoSignedWrap)
1170 // Drill down through the cast.
1171 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1172 Parent = std::make_pair(Cast, 0);
1173 Scale = Scale.sext(LargeSize);
1174 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1176 assert(Scale.exactLogBase2() == logScale);
1181 // Unsupported expression, bail out.
1185 // If Op is zero then Val = Op * Scale.
1186 if (match(Op, m_Zero())) {
1187 NoSignedWrap = true;
1191 // We know that we can successfully descale, so from here on we can safely
1192 // modify the IR. Op holds the descaled version of the deepest term in the
1193 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1197 // The expression only had one term.
1200 // Rewrite the parent using the descaled version of its operand.
1201 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1202 assert(Op != Parent.first->getOperand(Parent.second) &&
1203 "Descaling was a no-op?");
1204 Parent.first->setOperand(Parent.second, Op);
1205 Worklist.Add(Parent.first);
1207 // Now work back up the expression correcting nsw flags. The logic is based
1208 // on the following observation: if X * Y is known not to overflow as a signed
1209 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1210 // then X * Z will not overflow as a signed multiplication either. As we work
1211 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1212 // current level has strictly smaller absolute value than the original.
1213 Instruction *Ancestor = Parent.first;
1215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1216 // If the multiplication wasn't nsw then we can't say anything about the
1217 // value of the descaled multiplication, and we have to clear nsw flags
1218 // from this point on up.
1219 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1220 NoSignedWrap &= OpNoSignedWrap;
1221 if (NoSignedWrap != OpNoSignedWrap) {
1222 BO->setHasNoSignedWrap(NoSignedWrap);
1223 Worklist.Add(Ancestor);
1225 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1226 // The fact that the descaled input to the trunc has smaller absolute
1227 // value than the original input doesn't tell us anything useful about
1228 // the absolute values of the truncations.
1229 NoSignedWrap = false;
1231 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1232 "Failed to keep proper track of nsw flags while drilling down?");
1234 if (Ancestor == Val)
1235 // Got to the top, all done!
1238 // Move up one level in the expression.
1239 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1240 Ancestor = Ancestor->user_back();
1244 /// \brief Creates node of binary operation with the same attributes as the
1245 /// specified one but with other operands.
1246 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1247 InstCombiner::BuilderTy *B) {
1248 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1249 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1250 if (isa<OverflowingBinaryOperator>(NewBO)) {
1251 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1252 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1254 if (isa<PossiblyExactOperator>(NewBO))
1255 NewBO->setIsExact(Inst.isExact());
1260 /// \brief Makes transformation of binary operation specific for vector types.
1261 /// \param Inst Binary operator to transform.
1262 /// \return Pointer to node that must replace the original binary operator, or
1263 /// null pointer if no transformation was made.
1264 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1265 if (!Inst.getType()->isVectorTy()) return nullptr;
1267 // It may not be safe to reorder shuffles and things like div, urem, etc.
1268 // because we may trap when executing those ops on unknown vector elements.
1270 if (!isSafeToSpeculativelyExecute(&Inst))
1273 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1274 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1275 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1276 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1278 // If both arguments of binary operation are shuffles, which use the same
1279 // mask and shuffle within a single vector, it is worthwhile to move the
1280 // shuffle after binary operation:
1281 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1282 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1283 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1284 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1285 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1286 isa<UndefValue>(RShuf->getOperand(1)) &&
1287 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1288 LShuf->getMask() == RShuf->getMask()) {
1289 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1290 RShuf->getOperand(0), Builder);
1291 Value *Res = Builder->CreateShuffleVector(NewBO,
1292 UndefValue::get(NewBO->getType()), LShuf->getMask());
1297 // If one argument is a shuffle within one vector, the other is a constant,
1298 // try moving the shuffle after the binary operation.
1299 ShuffleVectorInst *Shuffle = nullptr;
1300 Constant *C1 = nullptr;
1301 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1302 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1303 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1304 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1305 if (Shuffle && C1 &&
1306 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1307 isa<UndefValue>(Shuffle->getOperand(1)) &&
1308 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1309 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1310 // Find constant C2 that has property:
1311 // shuffle(C2, ShMask) = C1
1312 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1313 // reorder is not possible.
1314 SmallVector<Constant*, 16> C2M(VWidth,
1315 UndefValue::get(C1->getType()->getScalarType()));
1316 bool MayChange = true;
1317 for (unsigned I = 0; I < VWidth; ++I) {
1318 if (ShMask[I] >= 0) {
1319 assert(ShMask[I] < (int)VWidth);
1320 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1324 C2M[ShMask[I]] = C1->getAggregateElement(I);
1328 Constant *C2 = ConstantVector::get(C2M);
1329 Value *NewLHS, *NewRHS;
1330 if (isa<Constant>(LHS)) {
1332 NewRHS = Shuffle->getOperand(0);
1334 NewLHS = Shuffle->getOperand(0);
1337 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1338 Value *Res = Builder->CreateShuffleVector(NewBO,
1339 UndefValue::get(Inst.getType()), Shuffle->getMask());
1347 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1348 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1350 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1351 return ReplaceInstUsesWith(GEP, V);
1353 Value *PtrOp = GEP.getOperand(0);
1355 // Eliminate unneeded casts for indices, and replace indices which displace
1356 // by multiples of a zero size type with zero.
1357 bool MadeChange = false;
1358 Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
1360 gep_type_iterator GTI = gep_type_begin(GEP);
1361 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1363 // Skip indices into struct types.
1364 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1368 // If the element type has zero size then any index over it is equivalent
1369 // to an index of zero, so replace it with zero if it is not zero already.
1370 if (SeqTy->getElementType()->isSized() &&
1371 DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1372 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1373 *I = Constant::getNullValue(IntPtrTy);
1377 Type *IndexTy = (*I)->getType();
1378 if (IndexTy != IntPtrTy) {
1379 // If we are using a wider index than needed for this platform, shrink
1380 // it to what we need. If narrower, sign-extend it to what we need.
1381 // This explicit cast can make subsequent optimizations more obvious.
1382 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1389 // Check to see if the inputs to the PHI node are getelementptr instructions.
1390 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1391 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1395 // Don't fold a GEP into itself through a PHI node. This can only happen
1396 // through the back-edge of a loop. Folding a GEP into itself means that
1397 // the value of the previous iteration needs to be stored in the meantime,
1398 // thus requiring an additional register variable to be live, but not
1399 // actually achieving anything (the GEP still needs to be executed once per
1406 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1407 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1408 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1411 // As for Op1 above, don't try to fold a GEP into itself.
1415 // Keep track of the type as we walk the GEP.
1416 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1418 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1419 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1422 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1424 // We have not seen any differences yet in the GEPs feeding the
1425 // PHI yet, so we record this one if it is allowed to be a
1428 // The first two arguments can vary for any GEP, the rest have to be
1429 // static for struct slots
1430 if (J > 1 && CurTy->isStructTy())
1435 // The GEP is different by more than one input. While this could be
1436 // extended to support GEPs that vary by more than one variable it
1437 // doesn't make sense since it greatly increases the complexity and
1438 // would result in an R+R+R addressing mode which no backend
1439 // directly supports and would need to be broken into several
1440 // simpler instructions anyway.
1445 // Sink down a layer of the type for the next iteration.
1447 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1448 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1456 // If not all GEPs are identical we'll have to create a new PHI node.
1457 // Check that the old PHI node has only one use so that it will get
1459 if (DI != -1 && !PN->hasOneUse())
1462 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1464 // All the GEPs feeding the PHI are identical. Clone one down into our
1465 // BB so that it can be merged with the current GEP.
1466 GEP.getParent()->getInstList().insert(
1467 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1469 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1470 // into the current block so it can be merged, and create a new PHI to
1474 IRBuilderBase::InsertPointGuard Guard(*Builder);
1475 Builder->SetInsertPoint(PN);
1476 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1477 PN->getNumOperands());
1480 for (auto &I : PN->operands())
1481 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1482 PN->getIncomingBlock(I));
1484 NewGEP->setOperand(DI, NewPN);
1485 GEP.getParent()->getInstList().insert(
1486 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1487 NewGEP->setOperand(DI, NewPN);
1490 GEP.setOperand(0, NewGEP);
1494 // Combine Indices - If the source pointer to this getelementptr instruction
1495 // is a getelementptr instruction, combine the indices of the two
1496 // getelementptr instructions into a single instruction.
1498 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1499 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1502 // Note that if our source is a gep chain itself then we wait for that
1503 // chain to be resolved before we perform this transformation. This
1504 // avoids us creating a TON of code in some cases.
1505 if (GEPOperator *SrcGEP =
1506 dyn_cast<GEPOperator>(Src->getOperand(0)))
1507 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1508 return nullptr; // Wait until our source is folded to completion.
1510 SmallVector<Value*, 8> Indices;
1512 // Find out whether the last index in the source GEP is a sequential idx.
1513 bool EndsWithSequential = false;
1514 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1516 EndsWithSequential = !(*I)->isStructTy();
1518 // Can we combine the two pointer arithmetics offsets?
1519 if (EndsWithSequential) {
1520 // Replace: gep (gep %P, long B), long A, ...
1521 // With: T = long A+B; gep %P, T, ...
1524 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1525 Value *GO1 = GEP.getOperand(1);
1526 if (SO1 == Constant::getNullValue(SO1->getType())) {
1528 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1531 // If they aren't the same type, then the input hasn't been processed
1532 // by the loop above yet (which canonicalizes sequential index types to
1533 // intptr_t). Just avoid transforming this until the input has been
1535 if (SO1->getType() != GO1->getType())
1537 // Only do the combine when GO1 and SO1 are both constants. Only in
1538 // this case, we are sure the cost after the merge is never more than
1539 // that before the merge.
1540 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1542 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1545 // Update the GEP in place if possible.
1546 if (Src->getNumOperands() == 2) {
1547 GEP.setOperand(0, Src->getOperand(0));
1548 GEP.setOperand(1, Sum);
1551 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1552 Indices.push_back(Sum);
1553 Indices.append(GEP.op_begin()+2, GEP.op_end());
1554 } else if (isa<Constant>(*GEP.idx_begin()) &&
1555 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1556 Src->getNumOperands() != 1) {
1557 // Otherwise we can do the fold if the first index of the GEP is a zero
1558 Indices.append(Src->op_begin()+1, Src->op_end());
1559 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1562 if (!Indices.empty())
1563 return GEP.isInBounds() && Src->isInBounds()
1564 ? GetElementPtrInst::CreateInBounds(
1565 Src->getSourceElementType(), Src->getOperand(0), Indices,
1567 : GetElementPtrInst::Create(Src->getSourceElementType(),
1568 Src->getOperand(0), Indices,
1572 if (GEP.getNumIndices() == 1) {
1573 unsigned AS = GEP.getPointerAddressSpace();
1574 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1575 DL.getPointerSizeInBits(AS)) {
1576 Type *PtrTy = GEP.getPointerOperandType();
1577 Type *Ty = PtrTy->getPointerElementType();
1578 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1580 bool Matched = false;
1583 if (TyAllocSize == 1) {
1584 V = GEP.getOperand(1);
1586 } else if (match(GEP.getOperand(1),
1587 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1588 if (TyAllocSize == 1ULL << C)
1590 } else if (match(GEP.getOperand(1),
1591 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1592 if (TyAllocSize == C)
1597 // Canonicalize (gep i8* X, -(ptrtoint Y))
1598 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1599 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1600 // pointer arithmetic.
1601 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1602 Operator *Index = cast<Operator>(V);
1603 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1604 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1605 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1607 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1610 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1611 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1612 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1619 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1620 Value *StrippedPtr = PtrOp->stripPointerCasts();
1621 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1623 // We do not handle pointer-vector geps here.
1627 if (StrippedPtr != PtrOp) {
1628 bool HasZeroPointerIndex = false;
1629 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1630 HasZeroPointerIndex = C->isZero();
1632 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1633 // into : GEP [10 x i8]* X, i32 0, ...
1635 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1636 // into : GEP i8* X, ...
1638 // This occurs when the program declares an array extern like "int X[];"
1639 if (HasZeroPointerIndex) {
1640 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1641 if (ArrayType *CATy =
1642 dyn_cast<ArrayType>(CPTy->getElementType())) {
1643 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1644 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1645 // -> GEP i8* X, ...
1646 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1647 GetElementPtrInst *Res = GetElementPtrInst::Create(
1648 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1649 Res->setIsInBounds(GEP.isInBounds());
1650 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1652 // Insert Res, and create an addrspacecast.
1654 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1656 // %0 = GEP i8 addrspace(1)* X, ...
1657 // addrspacecast i8 addrspace(1)* %0 to i8*
1658 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1661 if (ArrayType *XATy =
1662 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1663 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1664 if (CATy->getElementType() == XATy->getElementType()) {
1665 // -> GEP [10 x i8]* X, i32 0, ...
1666 // At this point, we know that the cast source type is a pointer
1667 // to an array of the same type as the destination pointer
1668 // array. Because the array type is never stepped over (there
1669 // is a leading zero) we can fold the cast into this GEP.
1670 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1671 GEP.setOperand(0, StrippedPtr);
1672 GEP.setSourceElementType(XATy);
1675 // Cannot replace the base pointer directly because StrippedPtr's
1676 // address space is different. Instead, create a new GEP followed by
1677 // an addrspacecast.
1679 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1682 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1683 // addrspacecast i8 addrspace(1)* %0 to i8*
1684 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1685 Value *NewGEP = GEP.isInBounds()
1686 ? Builder->CreateInBoundsGEP(
1687 nullptr, StrippedPtr, Idx, GEP.getName())
1688 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1690 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1694 } else if (GEP.getNumOperands() == 2) {
1695 // Transform things like:
1696 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1697 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1698 Type *SrcElTy = StrippedPtrTy->getElementType();
1699 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1700 if (SrcElTy->isArrayTy() &&
1701 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1702 DL.getTypeAllocSize(ResElTy)) {
1703 Type *IdxType = DL.getIntPtrType(GEP.getType());
1704 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1707 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1709 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1711 // V and GEP are both pointer types --> BitCast
1712 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1716 // Transform things like:
1717 // %V = mul i64 %N, 4
1718 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1719 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1720 if (ResElTy->isSized() && SrcElTy->isSized()) {
1721 // Check that changing the type amounts to dividing the index by a scale
1723 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1724 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1725 if (ResSize && SrcSize % ResSize == 0) {
1726 Value *Idx = GEP.getOperand(1);
1727 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1728 uint64_t Scale = SrcSize / ResSize;
1730 // Earlier transforms ensure that the index has type IntPtrType, which
1731 // considerably simplifies the logic by eliminating implicit casts.
1732 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1733 "Index not cast to pointer width?");
1736 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1737 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1738 // If the multiplication NewIdx * Scale may overflow then the new
1739 // GEP may not be "inbounds".
1741 GEP.isInBounds() && NSW
1742 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1744 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1747 // The NewGEP must be pointer typed, so must the old one -> BitCast
1748 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1754 // Similarly, transform things like:
1755 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1756 // (where tmp = 8*tmp2) into:
1757 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1758 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1759 // Check that changing to the array element type amounts to dividing the
1760 // index by a scale factor.
1761 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1762 uint64_t ArrayEltSize =
1763 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1764 if (ResSize && ArrayEltSize % ResSize == 0) {
1765 Value *Idx = GEP.getOperand(1);
1766 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1767 uint64_t Scale = ArrayEltSize / ResSize;
1769 // Earlier transforms ensure that the index has type IntPtrType, which
1770 // considerably simplifies the logic by eliminating implicit casts.
1771 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1772 "Index not cast to pointer width?");
1775 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1776 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1777 // If the multiplication NewIdx * Scale may overflow then the new
1778 // GEP may not be "inbounds".
1780 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1783 Value *NewGEP = GEP.isInBounds() && NSW
1784 ? Builder->CreateInBoundsGEP(
1785 SrcElTy, StrippedPtr, Off, GEP.getName())
1786 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1788 // The NewGEP must be pointer typed, so must the old one -> BitCast
1789 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1797 // addrspacecast between types is canonicalized as a bitcast, then an
1798 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1799 // through the addrspacecast.
1800 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1801 // X = bitcast A addrspace(1)* to B addrspace(1)*
1802 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1803 // Z = gep Y, <...constant indices...>
1804 // Into an addrspacecasted GEP of the struct.
1805 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1809 /// See if we can simplify:
1810 /// X = bitcast A* to B*
1811 /// Y = gep X, <...constant indices...>
1812 /// into a gep of the original struct. This is important for SROA and alias
1813 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1814 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1815 Value *Operand = BCI->getOperand(0);
1816 PointerType *OpType = cast<PointerType>(Operand->getType());
1817 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1818 APInt Offset(OffsetBits, 0);
1819 if (!isa<BitCastInst>(Operand) &&
1820 GEP.accumulateConstantOffset(DL, Offset)) {
1822 // If this GEP instruction doesn't move the pointer, just replace the GEP
1823 // with a bitcast of the real input to the dest type.
1825 // If the bitcast is of an allocation, and the allocation will be
1826 // converted to match the type of the cast, don't touch this.
1827 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1828 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1829 if (Instruction *I = visitBitCast(*BCI)) {
1832 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1833 ReplaceInstUsesWith(*BCI, I);
1839 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1840 return new AddrSpaceCastInst(Operand, GEP.getType());
1841 return new BitCastInst(Operand, GEP.getType());
1844 // Otherwise, if the offset is non-zero, we need to find out if there is a
1845 // field at Offset in 'A's type. If so, we can pull the cast through the
1847 SmallVector<Value*, 8> NewIndices;
1848 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1851 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1852 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1854 if (NGEP->getType() == GEP.getType())
1855 return ReplaceInstUsesWith(GEP, NGEP);
1856 NGEP->takeName(&GEP);
1858 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1859 return new AddrSpaceCastInst(NGEP, GEP.getType());
1860 return new BitCastInst(NGEP, GEP.getType());
1869 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1870 const TargetLibraryInfo *TLI) {
1871 SmallVector<Instruction*, 4> Worklist;
1872 Worklist.push_back(AI);
1875 Instruction *PI = Worklist.pop_back_val();
1876 for (User *U : PI->users()) {
1877 Instruction *I = cast<Instruction>(U);
1878 switch (I->getOpcode()) {
1880 // Give up the moment we see something we can't handle.
1883 case Instruction::BitCast:
1884 case Instruction::GetElementPtr:
1885 Users.emplace_back(I);
1886 Worklist.push_back(I);
1889 case Instruction::ICmp: {
1890 ICmpInst *ICI = cast<ICmpInst>(I);
1891 // We can fold eq/ne comparisons with null to false/true, respectively.
1892 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1894 Users.emplace_back(I);
1898 case Instruction::Call:
1899 // Ignore no-op and store intrinsics.
1900 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1901 switch (II->getIntrinsicID()) {
1905 case Intrinsic::memmove:
1906 case Intrinsic::memcpy:
1907 case Intrinsic::memset: {
1908 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1909 if (MI->isVolatile() || MI->getRawDest() != PI)
1913 case Intrinsic::dbg_declare:
1914 case Intrinsic::dbg_value:
1915 case Intrinsic::invariant_start:
1916 case Intrinsic::invariant_end:
1917 case Intrinsic::lifetime_start:
1918 case Intrinsic::lifetime_end:
1919 case Intrinsic::objectsize:
1920 Users.emplace_back(I);
1925 if (isFreeCall(I, TLI)) {
1926 Users.emplace_back(I);
1931 case Instruction::Store: {
1932 StoreInst *SI = cast<StoreInst>(I);
1933 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1935 Users.emplace_back(I);
1939 llvm_unreachable("missing a return?");
1941 } while (!Worklist.empty());
1945 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1946 // If we have a malloc call which is only used in any amount of comparisons
1947 // to null and free calls, delete the calls and replace the comparisons with
1948 // true or false as appropriate.
1949 SmallVector<WeakVH, 64> Users;
1950 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1951 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1952 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1955 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1956 ReplaceInstUsesWith(*C,
1957 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1958 C->isFalseWhenEqual()));
1959 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1960 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1961 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1962 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1963 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1964 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1965 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1968 EraseInstFromFunction(*I);
1971 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1972 // Replace invoke with a NOP intrinsic to maintain the original CFG
1973 Module *M = II->getParent()->getParent()->getParent();
1974 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1975 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1976 None, "", II->getParent());
1978 return EraseInstFromFunction(MI);
1983 /// \brief Move the call to free before a NULL test.
1985 /// Check if this free is accessed after its argument has been test
1986 /// against NULL (property 0).
1987 /// If yes, it is legal to move this call in its predecessor block.
1989 /// The move is performed only if the block containing the call to free
1990 /// will be removed, i.e.:
1991 /// 1. it has only one predecessor P, and P has two successors
1992 /// 2. it contains the call and an unconditional branch
1993 /// 3. its successor is the same as its predecessor's successor
1995 /// The profitability is out-of concern here and this function should
1996 /// be called only if the caller knows this transformation would be
1997 /// profitable (e.g., for code size).
1998 static Instruction *
1999 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2000 Value *Op = FI.getArgOperand(0);
2001 BasicBlock *FreeInstrBB = FI.getParent();
2002 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2004 // Validate part of constraint #1: Only one predecessor
2005 // FIXME: We can extend the number of predecessor, but in that case, we
2006 // would duplicate the call to free in each predecessor and it may
2007 // not be profitable even for code size.
2011 // Validate constraint #2: Does this block contains only the call to
2012 // free and an unconditional branch?
2013 // FIXME: We could check if we can speculate everything in the
2014 // predecessor block
2015 if (FreeInstrBB->size() != 2)
2018 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2021 // Validate the rest of constraint #1 by matching on the pred branch.
2022 TerminatorInst *TI = PredBB->getTerminator();
2023 BasicBlock *TrueBB, *FalseBB;
2024 ICmpInst::Predicate Pred;
2025 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2027 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2030 // Validate constraint #3: Ensure the null case just falls through.
2031 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2033 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2034 "Broken CFG: missing edge from predecessor to successor");
2041 Instruction *InstCombiner::visitFree(CallInst &FI) {
2042 Value *Op = FI.getArgOperand(0);
2044 // free undef -> unreachable.
2045 if (isa<UndefValue>(Op)) {
2046 // Insert a new store to null because we cannot modify the CFG here.
2047 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2048 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2049 return EraseInstFromFunction(FI);
2052 // If we have 'free null' delete the instruction. This can happen in stl code
2053 // when lots of inlining happens.
2054 if (isa<ConstantPointerNull>(Op))
2055 return EraseInstFromFunction(FI);
2057 // If we optimize for code size, try to move the call to free before the null
2058 // test so that simplify cfg can remove the empty block and dead code
2059 // elimination the branch. I.e., helps to turn something like:
2060 // if (foo) free(foo);
2064 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2070 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2071 if (RI.getNumOperands() == 0) // ret void
2074 Value *ResultOp = RI.getOperand(0);
2075 Type *VTy = ResultOp->getType();
2076 if (!VTy->isIntegerTy())
2079 // There might be assume intrinsics dominating this return that completely
2080 // determine the value. If so, constant fold it.
2081 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2082 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2083 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2084 if ((KnownZero|KnownOne).isAllOnesValue())
2085 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2090 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2091 // Change br (not X), label True, label False to: br X, label False, True
2093 BasicBlock *TrueDest;
2094 BasicBlock *FalseDest;
2095 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2096 !isa<Constant>(X)) {
2097 // Swap Destinations and condition...
2099 BI.swapSuccessors();
2103 // If the condition is irrelevant, remove the use so that other
2104 // transforms on the condition become more effective.
2105 if (BI.isConditional() &&
2106 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2107 !isa<UndefValue>(BI.getCondition())) {
2108 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2112 // Canonicalize fcmp_one -> fcmp_oeq
2113 FCmpInst::Predicate FPred; Value *Y;
2114 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2115 TrueDest, FalseDest)) &&
2116 BI.getCondition()->hasOneUse())
2117 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2118 FPred == FCmpInst::FCMP_OGE) {
2119 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2120 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2122 // Swap Destinations and condition.
2123 BI.swapSuccessors();
2128 // Canonicalize icmp_ne -> icmp_eq
2129 ICmpInst::Predicate IPred;
2130 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2131 TrueDest, FalseDest)) &&
2132 BI.getCondition()->hasOneUse())
2133 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2134 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2135 IPred == ICmpInst::ICMP_SGE) {
2136 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2137 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2138 // Swap Destinations and condition.
2139 BI.swapSuccessors();
2147 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2148 Value *Cond = SI.getCondition();
2149 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2150 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2151 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2152 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2153 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2155 // Compute the number of leading bits we can ignore.
2156 for (auto &C : SI.cases()) {
2157 LeadingKnownZeros = std::min(
2158 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2159 LeadingKnownOnes = std::min(
2160 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2163 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2165 // Truncate the condition operand if the new type is equal to or larger than
2166 // the largest legal integer type. We need to be conservative here since
2167 // x86 generates redundant zero-extension instructions if the operand is
2168 // truncated to i8 or i16.
2169 bool TruncCond = false;
2170 if (NewWidth > 0 && BitWidth > NewWidth &&
2171 NewWidth >= DL.getLargestLegalIntTypeSize()) {
2173 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2174 Builder->SetInsertPoint(&SI);
2175 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2176 SI.setCondition(NewCond);
2178 for (auto &C : SI.cases())
2179 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2180 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2183 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2184 if (I->getOpcode() == Instruction::Add)
2185 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2186 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2187 // Skip the first item since that's the default case.
2188 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2190 ConstantInt* CaseVal = i.getCaseValue();
2191 Constant *LHS = CaseVal;
2193 LHS = LeadingKnownZeros
2194 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2195 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2196 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2197 assert(isa<ConstantInt>(NewCaseVal) &&
2198 "Result of expression should be constant");
2199 i.setValue(cast<ConstantInt>(NewCaseVal));
2201 SI.setCondition(I->getOperand(0));
2207 return TruncCond ? &SI : nullptr;
2210 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2211 Value *Agg = EV.getAggregateOperand();
2213 if (!EV.hasIndices())
2214 return ReplaceInstUsesWith(EV, Agg);
2217 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
2218 return ReplaceInstUsesWith(EV, V);
2220 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2221 // We're extracting from an insertvalue instruction, compare the indices
2222 const unsigned *exti, *exte, *insi, *inse;
2223 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2224 exte = EV.idx_end(), inse = IV->idx_end();
2225 exti != exte && insi != inse;
2228 // The insert and extract both reference distinctly different elements.
2229 // This means the extract is not influenced by the insert, and we can
2230 // replace the aggregate operand of the extract with the aggregate
2231 // operand of the insert. i.e., replace
2232 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2233 // %E = extractvalue { i32, { i32 } } %I, 0
2235 // %E = extractvalue { i32, { i32 } } %A, 0
2236 return ExtractValueInst::Create(IV->getAggregateOperand(),
2239 if (exti == exte && insi == inse)
2240 // Both iterators are at the end: Index lists are identical. Replace
2241 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2242 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2244 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2246 // The extract list is a prefix of the insert list. i.e. replace
2247 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2248 // %E = extractvalue { i32, { i32 } } %I, 1
2250 // %X = extractvalue { i32, { i32 } } %A, 1
2251 // %E = insertvalue { i32 } %X, i32 42, 0
2252 // by switching the order of the insert and extract (though the
2253 // insertvalue should be left in, since it may have other uses).
2254 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2256 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2257 makeArrayRef(insi, inse));
2260 // The insert list is a prefix of the extract list
2261 // We can simply remove the common indices from the extract and make it
2262 // operate on the inserted value instead of the insertvalue result.
2264 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2265 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2267 // %E extractvalue { i32 } { i32 42 }, 0
2268 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2269 makeArrayRef(exti, exte));
2271 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2272 // We're extracting from an intrinsic, see if we're the only user, which
2273 // allows us to simplify multiple result intrinsics to simpler things that
2274 // just get one value.
2275 if (II->hasOneUse()) {
2276 // Check if we're grabbing the overflow bit or the result of a 'with
2277 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2278 // and replace it with a traditional binary instruction.
2279 switch (II->getIntrinsicID()) {
2280 case Intrinsic::uadd_with_overflow:
2281 case Intrinsic::sadd_with_overflow:
2282 if (*EV.idx_begin() == 0) { // Normal result.
2283 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2284 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2285 EraseInstFromFunction(*II);
2286 return BinaryOperator::CreateAdd(LHS, RHS);
2289 // If the normal result of the add is dead, and the RHS is a constant,
2290 // we can transform this into a range comparison.
2291 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2292 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2293 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2294 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2295 ConstantExpr::getNot(CI));
2297 case Intrinsic::usub_with_overflow:
2298 case Intrinsic::ssub_with_overflow:
2299 if (*EV.idx_begin() == 0) { // Normal result.
2300 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2301 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2302 EraseInstFromFunction(*II);
2303 return BinaryOperator::CreateSub(LHS, RHS);
2306 case Intrinsic::umul_with_overflow:
2307 case Intrinsic::smul_with_overflow:
2308 if (*EV.idx_begin() == 0) { // Normal result.
2309 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2310 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2311 EraseInstFromFunction(*II);
2312 return BinaryOperator::CreateMul(LHS, RHS);
2320 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2321 // If the (non-volatile) load only has one use, we can rewrite this to a
2322 // load from a GEP. This reduces the size of the load.
2323 // FIXME: If a load is used only by extractvalue instructions then this
2324 // could be done regardless of having multiple uses.
2325 if (L->isSimple() && L->hasOneUse()) {
2326 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2327 SmallVector<Value*, 4> Indices;
2328 // Prefix an i32 0 since we need the first element.
2329 Indices.push_back(Builder->getInt32(0));
2330 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2332 Indices.push_back(Builder->getInt32(*I));
2334 // We need to insert these at the location of the old load, not at that of
2335 // the extractvalue.
2336 Builder->SetInsertPoint(L);
2337 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2338 L->getPointerOperand(), Indices);
2339 // Returning the load directly will cause the main loop to insert it in
2340 // the wrong spot, so use ReplaceInstUsesWith().
2341 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2343 // We could simplify extracts from other values. Note that nested extracts may
2344 // already be simplified implicitly by the above: extract (extract (insert) )
2345 // will be translated into extract ( insert ( extract ) ) first and then just
2346 // the value inserted, if appropriate. Similarly for extracts from single-use
2347 // loads: extract (extract (load)) will be translated to extract (load (gep))
2348 // and if again single-use then via load (gep (gep)) to load (gep).
2349 // However, double extracts from e.g. function arguments or return values
2350 // aren't handled yet.
2354 /// Return 'true' if the given typeinfo will match anything.
2355 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2356 switch (Personality) {
2357 case EHPersonality::GNU_C:
2358 // The GCC C EH personality only exists to support cleanups, so it's not
2359 // clear what the semantics of catch clauses are.
2361 case EHPersonality::Unknown:
2363 case EHPersonality::GNU_Ada:
2364 // While __gnat_all_others_value will match any Ada exception, it doesn't
2365 // match foreign exceptions (or didn't, before gcc-4.7).
2367 case EHPersonality::GNU_CXX:
2368 case EHPersonality::GNU_ObjC:
2369 case EHPersonality::MSVC_X86SEH:
2370 case EHPersonality::MSVC_Win64SEH:
2371 case EHPersonality::MSVC_CXX:
2372 case EHPersonality::CoreCLR:
2373 return TypeInfo->isNullValue();
2375 llvm_unreachable("invalid enum");
2378 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2380 cast<ArrayType>(LHS->getType())->getNumElements()
2382 cast<ArrayType>(RHS->getType())->getNumElements();
2385 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2386 // The logic here should be correct for any real-world personality function.
2387 // However if that turns out not to be true, the offending logic can always
2388 // be conditioned on the personality function, like the catch-all logic is.
2389 EHPersonality Personality =
2390 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2392 // Simplify the list of clauses, eg by removing repeated catch clauses
2393 // (these are often created by inlining).
2394 bool MakeNewInstruction = false; // If true, recreate using the following:
2395 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2396 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2398 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2399 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2400 bool isLastClause = i + 1 == e;
2401 if (LI.isCatch(i)) {
2403 Constant *CatchClause = LI.getClause(i);
2404 Constant *TypeInfo = CatchClause->stripPointerCasts();
2406 // If we already saw this clause, there is no point in having a second
2408 if (AlreadyCaught.insert(TypeInfo).second) {
2409 // This catch clause was not already seen.
2410 NewClauses.push_back(CatchClause);
2412 // Repeated catch clause - drop the redundant copy.
2413 MakeNewInstruction = true;
2416 // If this is a catch-all then there is no point in keeping any following
2417 // clauses or marking the landingpad as having a cleanup.
2418 if (isCatchAll(Personality, TypeInfo)) {
2420 MakeNewInstruction = true;
2421 CleanupFlag = false;
2425 // A filter clause. If any of the filter elements were already caught
2426 // then they can be dropped from the filter. It is tempting to try to
2427 // exploit the filter further by saying that any typeinfo that does not
2428 // occur in the filter can't be caught later (and thus can be dropped).
2429 // However this would be wrong, since typeinfos can match without being
2430 // equal (for example if one represents a C++ class, and the other some
2431 // class derived from it).
2432 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2433 Constant *FilterClause = LI.getClause(i);
2434 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2435 unsigned NumTypeInfos = FilterType->getNumElements();
2437 // An empty filter catches everything, so there is no point in keeping any
2438 // following clauses or marking the landingpad as having a cleanup. By
2439 // dealing with this case here the following code is made a bit simpler.
2440 if (!NumTypeInfos) {
2441 NewClauses.push_back(FilterClause);
2443 MakeNewInstruction = true;
2444 CleanupFlag = false;
2448 bool MakeNewFilter = false; // If true, make a new filter.
2449 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2450 if (isa<ConstantAggregateZero>(FilterClause)) {
2451 // Not an empty filter - it contains at least one null typeinfo.
2452 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2453 Constant *TypeInfo =
2454 Constant::getNullValue(FilterType->getElementType());
2455 // If this typeinfo is a catch-all then the filter can never match.
2456 if (isCatchAll(Personality, TypeInfo)) {
2457 // Throw the filter away.
2458 MakeNewInstruction = true;
2462 // There is no point in having multiple copies of this typeinfo, so
2463 // discard all but the first copy if there is more than one.
2464 NewFilterElts.push_back(TypeInfo);
2465 if (NumTypeInfos > 1)
2466 MakeNewFilter = true;
2468 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2469 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2470 NewFilterElts.reserve(NumTypeInfos);
2472 // Remove any filter elements that were already caught or that already
2473 // occurred in the filter. While there, see if any of the elements are
2474 // catch-alls. If so, the filter can be discarded.
2475 bool SawCatchAll = false;
2476 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2477 Constant *Elt = Filter->getOperand(j);
2478 Constant *TypeInfo = Elt->stripPointerCasts();
2479 if (isCatchAll(Personality, TypeInfo)) {
2480 // This element is a catch-all. Bail out, noting this fact.
2484 if (AlreadyCaught.count(TypeInfo))
2485 // Already caught by an earlier clause, so having it in the filter
2488 // There is no point in having multiple copies of the same typeinfo in
2489 // a filter, so only add it if we didn't already.
2490 if (SeenInFilter.insert(TypeInfo).second)
2491 NewFilterElts.push_back(cast<Constant>(Elt));
2493 // A filter containing a catch-all cannot match anything by definition.
2495 // Throw the filter away.
2496 MakeNewInstruction = true;
2500 // If we dropped something from the filter, make a new one.
2501 if (NewFilterElts.size() < NumTypeInfos)
2502 MakeNewFilter = true;
2504 if (MakeNewFilter) {
2505 FilterType = ArrayType::get(FilterType->getElementType(),
2506 NewFilterElts.size());
2507 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2508 MakeNewInstruction = true;
2511 NewClauses.push_back(FilterClause);
2513 // If the new filter is empty then it will catch everything so there is
2514 // no point in keeping any following clauses or marking the landingpad
2515 // as having a cleanup. The case of the original filter being empty was
2516 // already handled above.
2517 if (MakeNewFilter && !NewFilterElts.size()) {
2518 assert(MakeNewInstruction && "New filter but not a new instruction!");
2519 CleanupFlag = false;
2525 // If several filters occur in a row then reorder them so that the shortest
2526 // filters come first (those with the smallest number of elements). This is
2527 // advantageous because shorter filters are more likely to match, speeding up
2528 // unwinding, but mostly because it increases the effectiveness of the other
2529 // filter optimizations below.
2530 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2532 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2533 for (j = i; j != e; ++j)
2534 if (!isa<ArrayType>(NewClauses[j]->getType()))
2537 // Check whether the filters are already sorted by length. We need to know
2538 // if sorting them is actually going to do anything so that we only make a
2539 // new landingpad instruction if it does.
2540 for (unsigned k = i; k + 1 < j; ++k)
2541 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2542 // Not sorted, so sort the filters now. Doing an unstable sort would be
2543 // correct too but reordering filters pointlessly might confuse users.
2544 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2546 MakeNewInstruction = true;
2550 // Look for the next batch of filters.
2554 // If typeinfos matched if and only if equal, then the elements of a filter L
2555 // that occurs later than a filter F could be replaced by the intersection of
2556 // the elements of F and L. In reality two typeinfos can match without being
2557 // equal (for example if one represents a C++ class, and the other some class
2558 // derived from it) so it would be wrong to perform this transform in general.
2559 // However the transform is correct and useful if F is a subset of L. In that
2560 // case L can be replaced by F, and thus removed altogether since repeating a
2561 // filter is pointless. So here we look at all pairs of filters F and L where
2562 // L follows F in the list of clauses, and remove L if every element of F is
2563 // an element of L. This can occur when inlining C++ functions with exception
2565 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2566 // Examine each filter in turn.
2567 Value *Filter = NewClauses[i];
2568 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2570 // Not a filter - skip it.
2572 unsigned FElts = FTy->getNumElements();
2573 // Examine each filter following this one. Doing this backwards means that
2574 // we don't have to worry about filters disappearing under us when removed.
2575 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2576 Value *LFilter = NewClauses[j];
2577 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2579 // Not a filter - skip it.
2581 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2582 // an element of LFilter, then discard LFilter.
2583 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2584 // If Filter is empty then it is a subset of LFilter.
2587 NewClauses.erase(J);
2588 MakeNewInstruction = true;
2589 // Move on to the next filter.
2592 unsigned LElts = LTy->getNumElements();
2593 // If Filter is longer than LFilter then it cannot be a subset of it.
2595 // Move on to the next filter.
2597 // At this point we know that LFilter has at least one element.
2598 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2599 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2600 // already know that Filter is not longer than LFilter).
2601 if (isa<ConstantAggregateZero>(Filter)) {
2602 assert(FElts <= LElts && "Should have handled this case earlier!");
2604 NewClauses.erase(J);
2605 MakeNewInstruction = true;
2607 // Move on to the next filter.
2610 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2611 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2612 // Since Filter is non-empty and contains only zeros, it is a subset of
2613 // LFilter iff LFilter contains a zero.
2614 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2615 for (unsigned l = 0; l != LElts; ++l)
2616 if (LArray->getOperand(l)->isNullValue()) {
2617 // LFilter contains a zero - discard it.
2618 NewClauses.erase(J);
2619 MakeNewInstruction = true;
2622 // Move on to the next filter.
2625 // At this point we know that both filters are ConstantArrays. Loop over
2626 // operands to see whether every element of Filter is also an element of
2627 // LFilter. Since filters tend to be short this is probably faster than
2628 // using a method that scales nicely.
2629 ConstantArray *FArray = cast<ConstantArray>(Filter);
2630 bool AllFound = true;
2631 for (unsigned f = 0; f != FElts; ++f) {
2632 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2634 for (unsigned l = 0; l != LElts; ++l) {
2635 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2636 if (LTypeInfo == FTypeInfo) {
2646 NewClauses.erase(J);
2647 MakeNewInstruction = true;
2649 // Move on to the next filter.
2653 // If we changed any of the clauses, replace the old landingpad instruction
2655 if (MakeNewInstruction) {
2656 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2658 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2659 NLI->addClause(NewClauses[i]);
2660 // A landing pad with no clauses must have the cleanup flag set. It is
2661 // theoretically possible, though highly unlikely, that we eliminated all
2662 // clauses. If so, force the cleanup flag to true.
2663 if (NewClauses.empty())
2665 NLI->setCleanup(CleanupFlag);
2669 // Even if none of the clauses changed, we may nonetheless have understood
2670 // that the cleanup flag is pointless. Clear it if so.
2671 if (LI.isCleanup() != CleanupFlag) {
2672 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2673 LI.setCleanup(CleanupFlag);
2680 /// Try to move the specified instruction from its current block into the
2681 /// beginning of DestBlock, which can only happen if it's safe to move the
2682 /// instruction past all of the instructions between it and the end of its
2684 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2685 assert(I->hasOneUse() && "Invariants didn't hold!");
2687 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2688 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2689 isa<TerminatorInst>(I))
2692 // Do not sink alloca instructions out of the entry block.
2693 if (isa<AllocaInst>(I) && I->getParent() ==
2694 &DestBlock->getParent()->getEntryBlock())
2697 // We can only sink load instructions if there is nothing between the load and
2698 // the end of block that could change the value.
2699 if (I->mayReadFromMemory()) {
2700 for (BasicBlock::iterator Scan = I->getIterator(),
2701 E = I->getParent()->end();
2703 if (Scan->mayWriteToMemory())
2707 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2708 I->moveBefore(&*InsertPos);
2713 bool InstCombiner::run() {
2714 while (!Worklist.isEmpty()) {
2715 Instruction *I = Worklist.RemoveOne();
2716 if (I == nullptr) continue; // skip null values.
2718 // Check to see if we can DCE the instruction.
2719 if (isInstructionTriviallyDead(I, TLI)) {
2720 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2721 EraseInstFromFunction(*I);
2723 MadeIRChange = true;
2727 // Instruction isn't dead, see if we can constant propagate it.
2728 if (!I->use_empty() &&
2729 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2730 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2731 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2733 // Add operands to the worklist.
2734 ReplaceInstUsesWith(*I, C);
2736 EraseInstFromFunction(*I);
2737 MadeIRChange = true;
2742 // In general, it is possible for computeKnownBits to determine all bits in a
2743 // value even when the operands are not all constants.
2744 if (!I->use_empty() && I->getType()->isIntegerTy()) {
2745 unsigned BitWidth = I->getType()->getScalarSizeInBits();
2746 APInt KnownZero(BitWidth, 0);
2747 APInt KnownOne(BitWidth, 0);
2748 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2749 if ((KnownZero | KnownOne).isAllOnesValue()) {
2750 Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2751 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2752 " from: " << *I << '\n');
2754 // Add operands to the worklist.
2755 ReplaceInstUsesWith(*I, C);
2757 EraseInstFromFunction(*I);
2758 MadeIRChange = true;
2763 // See if we can trivially sink this instruction to a successor basic block.
2764 if (I->hasOneUse()) {
2765 BasicBlock *BB = I->getParent();
2766 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2767 BasicBlock *UserParent;
2769 // Get the block the use occurs in.
2770 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2771 UserParent = PN->getIncomingBlock(*I->use_begin());
2773 UserParent = UserInst->getParent();
2775 if (UserParent != BB) {
2776 bool UserIsSuccessor = false;
2777 // See if the user is one of our successors.
2778 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2779 if (*SI == UserParent) {
2780 UserIsSuccessor = true;
2784 // If the user is one of our immediate successors, and if that successor
2785 // only has us as a predecessors (we'd have to split the critical edge
2786 // otherwise), we can keep going.
2787 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2788 // Okay, the CFG is simple enough, try to sink this instruction.
2789 if (TryToSinkInstruction(I, UserParent)) {
2790 MadeIRChange = true;
2791 // We'll add uses of the sunk instruction below, but since sinking
2792 // can expose opportunities for it's *operands* add them to the
2794 for (Use &U : I->operands())
2795 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2802 // Now that we have an instruction, try combining it to simplify it.
2803 Builder->SetInsertPoint(I);
2804 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2809 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2810 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2812 if (Instruction *Result = visit(*I)) {
2814 // Should we replace the old instruction with a new one?
2816 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2817 << " New = " << *Result << '\n');
2819 if (I->getDebugLoc())
2820 Result->setDebugLoc(I->getDebugLoc());
2821 // Everything uses the new instruction now.
2822 I->replaceAllUsesWith(Result);
2824 // Move the name to the new instruction first.
2825 Result->takeName(I);
2827 // Push the new instruction and any users onto the worklist.
2828 Worklist.Add(Result);
2829 Worklist.AddUsersToWorkList(*Result);
2831 // Insert the new instruction into the basic block...
2832 BasicBlock *InstParent = I->getParent();
2833 BasicBlock::iterator InsertPos = I->getIterator();
2835 // If we replace a PHI with something that isn't a PHI, fix up the
2837 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2838 InsertPos = InstParent->getFirstInsertionPt();
2840 InstParent->getInstList().insert(InsertPos, Result);
2842 EraseInstFromFunction(*I);
2845 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2846 << " New = " << *I << '\n');
2849 // If the instruction was modified, it's possible that it is now dead.
2850 // if so, remove it.
2851 if (isInstructionTriviallyDead(I, TLI)) {
2852 EraseInstFromFunction(*I);
2855 Worklist.AddUsersToWorkList(*I);
2858 MadeIRChange = true;
2863 return MadeIRChange;
2866 /// Walk the function in depth-first order, adding all reachable code to the
2869 /// This has a couple of tricks to make the code faster and more powerful. In
2870 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2871 /// them to the worklist (this significantly speeds up instcombine on code where
2872 /// many instructions are dead or constant). Additionally, if we find a branch
2873 /// whose condition is a known constant, we only visit the reachable successors.
2875 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2876 SmallPtrSetImpl<BasicBlock *> &Visited,
2877 InstCombineWorklist &ICWorklist,
2878 const TargetLibraryInfo *TLI) {
2879 bool MadeIRChange = false;
2880 SmallVector<BasicBlock*, 256> Worklist;
2881 Worklist.push_back(BB);
2883 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2884 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2887 BB = Worklist.pop_back_val();
2889 // We have now visited this block! If we've already been here, ignore it.
2890 if (!Visited.insert(BB).second)
2893 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2894 Instruction *Inst = &*BBI++;
2896 // DCE instruction if trivially dead.
2897 if (isInstructionTriviallyDead(Inst, TLI)) {
2899 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2900 Inst->eraseFromParent();
2904 // ConstantProp instruction if trivially constant.
2905 if (!Inst->use_empty() &&
2906 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
2907 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2908 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2910 Inst->replaceAllUsesWith(C);
2912 Inst->eraseFromParent();
2916 // See if we can constant fold its operands.
2917 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2919 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2923 Constant *&FoldRes = FoldedConstants[CE];
2925 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2929 if (FoldRes != CE) {
2931 MadeIRChange = true;
2935 InstrsForInstCombineWorklist.push_back(Inst);
2938 // Recursively visit successors. If this is a branch or switch on a
2939 // constant, only visit the reachable successor.
2940 TerminatorInst *TI = BB->getTerminator();
2941 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2942 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2943 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2944 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2945 Worklist.push_back(ReachableBB);
2948 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2949 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2950 // See if this is an explicit destination.
2951 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2953 if (i.getCaseValue() == Cond) {
2954 BasicBlock *ReachableBB = i.getCaseSuccessor();
2955 Worklist.push_back(ReachableBB);
2959 // Otherwise it is the default destination.
2960 Worklist.push_back(SI->getDefaultDest());
2965 for (BasicBlock *SuccBB : TI->successors())
2966 Worklist.push_back(SuccBB);
2967 } while (!Worklist.empty());
2969 // Once we've found all of the instructions to add to instcombine's worklist,
2970 // add them in reverse order. This way instcombine will visit from the top
2971 // of the function down. This jives well with the way that it adds all uses
2972 // of instructions to the worklist after doing a transformation, thus avoiding
2973 // some N^2 behavior in pathological cases.
2974 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
2976 return MadeIRChange;
2979 /// \brief Populate the IC worklist from a function, and prune any dead basic
2980 /// blocks discovered in the process.
2982 /// This also does basic constant propagation and other forward fixing to make
2983 /// the combiner itself run much faster.
2984 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
2985 TargetLibraryInfo *TLI,
2986 InstCombineWorklist &ICWorklist) {
2987 bool MadeIRChange = false;
2989 // Do a depth-first traversal of the function, populate the worklist with
2990 // the reachable instructions. Ignore blocks that are not reachable. Keep
2991 // track of which blocks we visit.
2992 SmallPtrSet<BasicBlock *, 64> Visited;
2994 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
2996 // Do a quick scan over the function. If we find any blocks that are
2997 // unreachable, remove any instructions inside of them. This prevents
2998 // the instcombine code from having to deal with some bad special cases.
2999 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
3000 if (Visited.count(&*BB))
3003 // Delete the instructions backwards, as it has a reduced likelihood of
3004 // having to update as many def-use and use-def chains.
3005 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
3006 while (EndInst != BB->begin()) {
3007 // Delete the next to last instruction.
3008 Instruction *Inst = &*--EndInst->getIterator();
3009 if (!Inst->use_empty())
3010 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
3011 if (Inst->isEHPad()) {
3015 if (!isa<DbgInfoIntrinsic>(Inst)) {
3017 MadeIRChange = true;
3019 Inst->eraseFromParent();
3023 return MadeIRChange;
3027 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3028 AliasAnalysis *AA, AssumptionCache &AC,
3029 TargetLibraryInfo &TLI, DominatorTree &DT,
3030 LoopInfo *LI = nullptr) {
3031 auto &DL = F.getParent()->getDataLayout();
3033 /// Builder - This is an IRBuilder that automatically inserts new
3034 /// instructions into the worklist when they are created.
3035 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
3036 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
3038 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3040 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3042 // Iterate while there is work to do.
3046 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3047 << F.getName() << "\n");
3049 bool Changed = false;
3050 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
3053 InstCombiner IC(Worklist, &Builder, F.optForMinSize(),
3054 AA, &AC, &TLI, &DT, DL, LI);
3062 return DbgDeclaresChanged || Iteration > 1;
3065 PreservedAnalyses InstCombinePass::run(Function &F,
3066 AnalysisManager<Function> *AM) {
3067 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3068 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3069 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3071 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3073 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3074 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
3075 // No changes, all analyses are preserved.
3076 return PreservedAnalyses::all();
3078 // Mark all the analyses that instcombine updates as preserved.
3079 // FIXME: Need a way to preserve CFG analyses here!
3080 PreservedAnalyses PA;
3081 PA.preserve<DominatorTreeAnalysis>();
3086 /// \brief The legacy pass manager's instcombine pass.
3088 /// This is a basic whole-function wrapper around the instcombine utility. It
3089 /// will try to combine all instructions in the function.
3090 class InstructionCombiningPass : public FunctionPass {
3091 InstCombineWorklist Worklist;
3094 static char ID; // Pass identification, replacement for typeid
3096 InstructionCombiningPass() : FunctionPass(ID) {
3097 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3100 void getAnalysisUsage(AnalysisUsage &AU) const override;
3101 bool runOnFunction(Function &F) override;
3105 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3106 AU.setPreservesCFG();
3107 AU.addRequired<AAResultsWrapperPass>();
3108 AU.addRequired<AssumptionCacheTracker>();
3109 AU.addRequired<TargetLibraryInfoWrapperPass>();
3110 AU.addRequired<DominatorTreeWrapperPass>();
3111 AU.addPreserved<DominatorTreeWrapperPass>();
3112 AU.addPreserved<GlobalsAAWrapperPass>();
3115 bool InstructionCombiningPass::runOnFunction(Function &F) {
3116 if (skipOptnoneFunction(F))
3119 // Required analyses.
3120 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3121 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3122 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3123 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3125 // Optional analyses.
3126 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3127 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3129 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
3132 char InstructionCombiningPass::ID = 0;
3133 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3134 "Combine redundant instructions", false, false)
3135 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3136 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3137 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3138 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3139 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3140 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3141 "Combine redundant instructions", false, false)
3143 // Initialization Routines
3144 void llvm::initializeInstCombine(PassRegistry &Registry) {
3145 initializeInstructionCombiningPassPass(Registry);
3148 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3149 initializeInstructionCombiningPassPass(*unwrap(R));
3152 FunctionPass *llvm::createInstructionCombiningPass() {
3153 return new InstructionCombiningPass();