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/InstructionSimplify.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Analysis/MemoryBuiltins.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/IR/CFG.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/PatternMatch.h"
56 #include "llvm/IR/ValueHandle.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Transforms/Scalar.h"
60 #include "llvm/Transforms/Utils/Local.h"
64 using namespace llvm::PatternMatch;
66 #define DEBUG_TYPE "instcombine"
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumSunkInst , "Number of instructions sunk");
72 STATISTIC(NumExpand, "Number of expansions");
73 STATISTIC(NumFactor , "Number of factorizations");
74 STATISTIC(NumReassoc , "Number of reassociations");
76 Value *InstCombiner::EmitGEPOffset(User *GEP) {
77 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
80 /// ShouldChangeType - Return true if it is desirable to convert a computation
81 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
82 /// type for example, or from a smaller to a larger illegal type.
83 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
84 assert(From->isIntegerTy() && To->isIntegerTy());
86 // If we don't have DL, we don't know if the source/dest are legal.
87 if (!DL) return false;
89 unsigned FromWidth = From->getPrimitiveSizeInBits();
90 unsigned ToWidth = To->getPrimitiveSizeInBits();
91 bool FromLegal = DL->isLegalInteger(FromWidth);
92 bool ToLegal = DL->isLegalInteger(ToWidth);
94 // If this is a legal integer from type, and the result would be an illegal
95 // type, don't do the transformation.
96 if (FromLegal && !ToLegal)
99 // Otherwise, if both are illegal, do not increase the size of the result. We
100 // do allow things like i160 -> i64, but not i64 -> i160.
101 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
107 // Return true, if No Signed Wrap should be maintained for I.
108 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
109 // where both B and C should be ConstantInts, results in a constant that does
110 // not overflow. This function only handles the Add and Sub opcodes. For
111 // all other opcodes, the function conservatively returns false.
112 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
113 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
114 if (!OBO || !OBO->hasNoSignedWrap()) {
118 // We reason about Add and Sub Only.
119 Instruction::BinaryOps Opcode = I.getOpcode();
120 if (Opcode != Instruction::Add &&
121 Opcode != Instruction::Sub) {
125 ConstantInt *CB = dyn_cast<ConstantInt>(B);
126 ConstantInt *CC = dyn_cast<ConstantInt>(C);
132 const APInt &BVal = CB->getValue();
133 const APInt &CVal = CC->getValue();
134 bool Overflow = false;
136 if (Opcode == Instruction::Add) {
137 BVal.sadd_ov(CVal, Overflow);
139 BVal.ssub_ov(CVal, Overflow);
145 /// Conservatively clears subclassOptionalData after a reassociation or
146 /// commutation. We preserve fast-math flags when applicable as they can be
148 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
149 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
151 I.clearSubclassOptionalData();
155 FastMathFlags FMF = I.getFastMathFlags();
156 I.clearSubclassOptionalData();
157 I.setFastMathFlags(FMF);
160 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
161 /// operators which are associative or commutative:
163 // Commutative operators:
165 // 1. Order operands such that they are listed from right (least complex) to
166 // left (most complex). This puts constants before unary operators before
169 // Associative operators:
171 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
172 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
174 // Associative and commutative operators:
176 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
177 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
178 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
179 // if C1 and C2 are constants.
181 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
182 Instruction::BinaryOps Opcode = I.getOpcode();
183 bool Changed = false;
186 // Order operands such that they are listed from right (least complex) to
187 // left (most complex). This puts constants before unary operators before
189 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
190 getComplexity(I.getOperand(1)))
191 Changed = !I.swapOperands();
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
196 if (I.isAssociative()) {
197 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
198 if (Op0 && Op0->getOpcode() == Opcode) {
199 Value *A = Op0->getOperand(0);
200 Value *B = Op0->getOperand(1);
201 Value *C = I.getOperand(1);
203 // Does "B op C" simplify?
204 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
205 // It simplifies to V. Form "A op V".
208 // Conservatively clear the optional flags, since they may not be
209 // preserved by the reassociation.
210 if (MaintainNoSignedWrap(I, B, C) &&
211 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
212 // Note: this is only valid because SimplifyBinOp doesn't look at
213 // the operands to Op0.
214 I.clearSubclassOptionalData();
215 I.setHasNoSignedWrap(true);
217 ClearSubclassDataAfterReassociation(I);
226 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
227 if (Op1 && Op1->getOpcode() == Opcode) {
228 Value *A = I.getOperand(0);
229 Value *B = Op1->getOperand(0);
230 Value *C = Op1->getOperand(1);
232 // Does "A op B" simplify?
233 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
234 // It simplifies to V. Form "V op C".
237 // Conservatively clear the optional flags, since they may not be
238 // preserved by the reassociation.
239 ClearSubclassDataAfterReassociation(I);
247 if (I.isAssociative() && I.isCommutative()) {
248 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
249 if (Op0 && Op0->getOpcode() == Opcode) {
250 Value *A = Op0->getOperand(0);
251 Value *B = Op0->getOperand(1);
252 Value *C = I.getOperand(1);
254 // Does "C op A" simplify?
255 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
256 // It simplifies to V. Form "V op B".
259 // Conservatively clear the optional flags, since they may not be
260 // preserved by the reassociation.
261 ClearSubclassDataAfterReassociation(I);
268 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
269 if (Op1 && Op1->getOpcode() == Opcode) {
270 Value *A = I.getOperand(0);
271 Value *B = Op1->getOperand(0);
272 Value *C = Op1->getOperand(1);
274 // Does "C op A" simplify?
275 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
276 // It simplifies to V. Form "B op V".
279 // Conservatively clear the optional flags, since they may not be
280 // preserved by the reassociation.
281 ClearSubclassDataAfterReassociation(I);
288 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
289 // if C1 and C2 are constants.
291 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
292 isa<Constant>(Op0->getOperand(1)) &&
293 isa<Constant>(Op1->getOperand(1)) &&
294 Op0->hasOneUse() && Op1->hasOneUse()) {
295 Value *A = Op0->getOperand(0);
296 Constant *C1 = cast<Constant>(Op0->getOperand(1));
297 Value *B = Op1->getOperand(0);
298 Constant *C2 = cast<Constant>(Op1->getOperand(1));
300 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
301 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
302 if (isa<FPMathOperator>(New)) {
303 FastMathFlags Flags = I.getFastMathFlags();
304 Flags &= Op0->getFastMathFlags();
305 Flags &= Op1->getFastMathFlags();
306 New->setFastMathFlags(Flags);
308 InsertNewInstWith(New, I);
310 I.setOperand(0, New);
311 I.setOperand(1, Folded);
312 // Conservatively clear the optional flags, since they may not be
313 // preserved by the reassociation.
314 ClearSubclassDataAfterReassociation(I);
321 // No further simplifications.
326 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
327 /// "(X LOp Y) ROp (X LOp Z)".
328 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
329 Instruction::BinaryOps ROp) {
334 case Instruction::And:
335 // And distributes over Or and Xor.
339 case Instruction::Or:
340 case Instruction::Xor:
344 case Instruction::Mul:
345 // Multiplication distributes over addition and subtraction.
349 case Instruction::Add:
350 case Instruction::Sub:
354 case Instruction::Or:
355 // Or distributes over And.
359 case Instruction::And:
365 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
366 /// "(X ROp Z) LOp (Y ROp Z)".
367 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
368 Instruction::BinaryOps ROp) {
369 if (Instruction::isCommutative(ROp))
370 return LeftDistributesOverRight(ROp, LOp);
375 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
376 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
377 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
378 case Instruction::And:
379 case Instruction::Or:
380 case Instruction::Xor:
384 case Instruction::Shl:
385 case Instruction::LShr:
386 case Instruction::AShr:
390 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
391 // but this requires knowing that the addition does not overflow and other
396 /// This function returns identity value for given opcode, which can be used to
397 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
398 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
399 if (isa<Constant>(V))
402 if (OpCode == Instruction::Mul)
403 return ConstantInt::get(V->getType(), 1);
405 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
410 /// This function factors binary ops which can be combined using distributive
411 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
412 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
413 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
414 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
416 static Instruction::BinaryOps
417 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
418 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
420 return Instruction::BinaryOpsEnd;
422 LHS = Op->getOperand(0);
423 RHS = Op->getOperand(1);
425 switch (TopLevelOpcode) {
427 return Op->getOpcode();
429 case Instruction::Add:
430 case Instruction::Sub:
431 if (Op->getOpcode() == Instruction::Shl) {
432 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
433 // The multiplier is really 1 << CST.
434 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
435 return Instruction::Mul;
438 return Op->getOpcode();
441 // TODO: We can add other conversions e.g. shr => div etc.
444 /// This tries to simplify binary operations by factorizing out common terms
445 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
446 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
447 const DataLayout *DL, BinaryOperator &I,
448 Instruction::BinaryOps InnerOpcode, Value *A,
449 Value *B, Value *C, Value *D) {
451 // If any of A, B, C, D are null, we can not factor I, return early.
452 // Checking A and C should be enough.
453 if (!A || !C || !B || !D)
456 Value *SimplifiedInst = nullptr;
457 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
458 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
460 // Does "X op' Y" always equal "Y op' X"?
461 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
463 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
464 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
465 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
466 // commutative case, "(A op' B) op (C op' A)"?
467 if (A == C || (InnerCommutative && A == D)) {
470 // Consider forming "A op' (B op D)".
471 // If "B op D" simplifies then it can be formed with no cost.
472 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
473 // If "B op D" doesn't simplify then only go on if both of the existing
474 // operations "A op' B" and "C op' D" will be zapped as no longer used.
475 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
476 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
478 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
482 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
483 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
484 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
485 // commutative case, "(A op' B) op (B op' D)"?
486 if (B == D || (InnerCommutative && B == C)) {
489 // Consider forming "(A op C) op' B".
490 // If "A op C" simplifies then it can be formed with no cost.
491 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
493 // If "A op C" doesn't simplify then only go on if both of the existing
494 // operations "A op' B" and "C op' D" will be zapped as no longer used.
495 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
496 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
498 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
502 if (SimplifiedInst) {
504 SimplifiedInst->takeName(&I);
506 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
507 // TODO: Check for NUW.
508 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
509 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
511 if (isa<OverflowingBinaryOperator>(&I))
512 HasNSW = I.hasNoSignedWrap();
514 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
515 if (isa<OverflowingBinaryOperator>(Op0))
516 HasNSW &= Op0->hasNoSignedWrap();
518 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
519 if (isa<OverflowingBinaryOperator>(Op1))
520 HasNSW &= Op1->hasNoSignedWrap();
521 BO->setHasNoSignedWrap(HasNSW);
525 return SimplifiedInst;
528 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
529 /// which some other binary operation distributes over either by factorizing
530 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
531 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
532 /// a win). Returns the simplified value, or null if it didn't simplify.
533 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
534 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
535 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
536 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
539 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
540 auto TopLevelOpcode = I.getOpcode();
541 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
542 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
544 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
546 if (LHSOpcode == RHSOpcode) {
547 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
551 // The instruction has the form "(A op' B) op (C)". Try to factorize common
553 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
554 getIdentityValue(LHSOpcode, RHS)))
557 // The instruction has the form "(B) op (C op' D)". Try to factorize common
559 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
560 getIdentityValue(RHSOpcode, LHS), C, D))
564 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
565 // The instruction has the form "(A op' B) op C". See if expanding it out
566 // to "(A op C) op' (B op C)" results in simplifications.
567 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
568 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
570 // Do "A op C" and "B op C" both simplify?
571 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
572 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
573 // They do! Return "L op' R".
575 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
576 if ((L == A && R == B) ||
577 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
579 // Otherwise return "L op' R" if it simplifies.
580 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
582 // Otherwise, create a new instruction.
583 C = Builder->CreateBinOp(InnerOpcode, L, R);
589 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
590 // The instruction has the form "A op (B op' C)". See if expanding it out
591 // to "(A op B) op' (A op C)" results in simplifications.
592 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
593 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
595 // Do "A op B" and "A op C" both simplify?
596 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
597 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
598 // They do! Return "L op' R".
600 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
601 if ((L == B && R == C) ||
602 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
604 // Otherwise return "L op' R" if it simplifies.
605 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
607 // Otherwise, create a new instruction.
608 A = Builder->CreateBinOp(InnerOpcode, L, R);
617 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
618 // if the LHS is a constant zero (which is the 'negate' form).
620 Value *InstCombiner::dyn_castNegVal(Value *V) const {
621 if (BinaryOperator::isNeg(V))
622 return BinaryOperator::getNegArgument(V);
624 // Constants can be considered to be negated values if they can be folded.
625 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
626 return ConstantExpr::getNeg(C);
628 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
629 if (C->getType()->getElementType()->isIntegerTy())
630 return ConstantExpr::getNeg(C);
635 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
636 // instruction if the LHS is a constant negative zero (which is the 'negate'
639 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
640 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
641 return BinaryOperator::getFNegArgument(V);
643 // Constants can be considered to be negated values if they can be folded.
644 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
645 return ConstantExpr::getFNeg(C);
647 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
648 if (C->getType()->getElementType()->isFloatingPointTy())
649 return ConstantExpr::getFNeg(C);
654 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
656 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
657 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
660 // Figure out if the constant is the left or the right argument.
661 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
662 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
664 if (Constant *SOC = dyn_cast<Constant>(SO)) {
666 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
667 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
670 Value *Op0 = SO, *Op1 = ConstOperand;
674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
675 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
676 SO->getName()+".op");
677 Instruction *FPInst = dyn_cast<Instruction>(RI);
678 if (FPInst && isa<FPMathOperator>(FPInst))
679 FPInst->copyFastMathFlags(BO);
682 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
683 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
684 SO->getName()+".cmp");
685 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
686 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
687 SO->getName()+".cmp");
688 llvm_unreachable("Unknown binary instruction type!");
691 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
692 // constant as the other operand, try to fold the binary operator into the
693 // select arguments. This also works for Cast instructions, which obviously do
694 // not have a second operand.
695 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
696 // Don't modify shared select instructions
697 if (!SI->hasOneUse()) return nullptr;
698 Value *TV = SI->getOperand(1);
699 Value *FV = SI->getOperand(2);
701 if (isa<Constant>(TV) || isa<Constant>(FV)) {
702 // Bool selects with constant operands can be folded to logical ops.
703 if (SI->getType()->isIntegerTy(1)) return nullptr;
705 // If it's a bitcast involving vectors, make sure it has the same number of
706 // elements on both sides.
707 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
708 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
709 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
711 // Verify that either both or neither are vectors.
712 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
713 // If vectors, verify that they have the same number of elements.
714 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
718 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
719 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
721 return SelectInst::Create(SI->getCondition(),
722 SelectTrueVal, SelectFalseVal);
728 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
729 /// has a PHI node as operand #0, see if we can fold the instruction into the
730 /// PHI (which is only possible if all operands to the PHI are constants).
732 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
733 PHINode *PN = cast<PHINode>(I.getOperand(0));
734 unsigned NumPHIValues = PN->getNumIncomingValues();
735 if (NumPHIValues == 0)
738 // We normally only transform phis with a single use. However, if a PHI has
739 // multiple uses and they are all the same operation, we can fold *all* of the
740 // uses into the PHI.
741 if (!PN->hasOneUse()) {
742 // Walk the use list for the instruction, comparing them to I.
743 for (User *U : PN->users()) {
744 Instruction *UI = cast<Instruction>(U);
745 if (UI != &I && !I.isIdenticalTo(UI))
748 // Otherwise, we can replace *all* users with the new PHI we form.
751 // Check to see if all of the operands of the PHI are simple constants
752 // (constantint/constantfp/undef). If there is one non-constant value,
753 // remember the BB it is in. If there is more than one or if *it* is a PHI,
754 // bail out. We don't do arbitrary constant expressions here because moving
755 // their computation can be expensive without a cost model.
756 BasicBlock *NonConstBB = nullptr;
757 for (unsigned i = 0; i != NumPHIValues; ++i) {
758 Value *InVal = PN->getIncomingValue(i);
759 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
762 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
763 if (NonConstBB) return nullptr; // More than one non-const value.
765 NonConstBB = PN->getIncomingBlock(i);
767 // If the InVal is an invoke at the end of the pred block, then we can't
768 // insert a computation after it without breaking the edge.
769 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
770 if (II->getParent() == NonConstBB)
773 // If the incoming non-constant value is in I's block, we will remove one
774 // instruction, but insert another equivalent one, leading to infinite
776 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
780 // If there is exactly one non-constant value, we can insert a copy of the
781 // operation in that block. However, if this is a critical edge, we would be
782 // inserting the computation on some other paths (e.g. inside a loop). Only
783 // do this if the pred block is unconditionally branching into the phi block.
784 if (NonConstBB != nullptr) {
785 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
786 if (!BI || !BI->isUnconditional()) return nullptr;
789 // Okay, we can do the transformation: create the new PHI node.
790 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
791 InsertNewInstBefore(NewPN, *PN);
794 // If we are going to have to insert a new computation, do so right before the
795 // predecessors terminator.
797 Builder->SetInsertPoint(NonConstBB->getTerminator());
799 // Next, add all of the operands to the PHI.
800 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
801 // We only currently try to fold the condition of a select when it is a phi,
802 // not the true/false values.
803 Value *TrueV = SI->getTrueValue();
804 Value *FalseV = SI->getFalseValue();
805 BasicBlock *PhiTransBB = PN->getParent();
806 for (unsigned i = 0; i != NumPHIValues; ++i) {
807 BasicBlock *ThisBB = PN->getIncomingBlock(i);
808 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
809 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
810 Value *InV = nullptr;
811 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
812 // even if currently isNullValue gives false.
813 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
814 if (InC && !isa<ConstantExpr>(InC))
815 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
817 InV = Builder->CreateSelect(PN->getIncomingValue(i),
818 TrueVInPred, FalseVInPred, "phitmp");
819 NewPN->addIncoming(InV, ThisBB);
821 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
822 Constant *C = cast<Constant>(I.getOperand(1));
823 for (unsigned i = 0; i != NumPHIValues; ++i) {
824 Value *InV = nullptr;
825 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
826 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
827 else if (isa<ICmpInst>(CI))
828 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
831 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
833 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
835 } else if (I.getNumOperands() == 2) {
836 Constant *C = cast<Constant>(I.getOperand(1));
837 for (unsigned i = 0; i != NumPHIValues; ++i) {
838 Value *InV = nullptr;
839 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
840 InV = ConstantExpr::get(I.getOpcode(), InC, C);
842 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
843 PN->getIncomingValue(i), C, "phitmp");
844 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
847 CastInst *CI = cast<CastInst>(&I);
848 Type *RetTy = CI->getType();
849 for (unsigned i = 0; i != NumPHIValues; ++i) {
851 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
852 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
854 InV = Builder->CreateCast(CI->getOpcode(),
855 PN->getIncomingValue(i), I.getType(), "phitmp");
856 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
860 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
861 Instruction *User = cast<Instruction>(*UI++);
862 if (User == &I) continue;
863 ReplaceInstUsesWith(*User, NewPN);
864 EraseInstFromFunction(*User);
866 return ReplaceInstUsesWith(I, NewPN);
869 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
870 /// whether or not there is a sequence of GEP indices into the pointed type that
871 /// will land us at the specified offset. If so, fill them into NewIndices and
872 /// return the resultant element type, otherwise return null.
873 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
874 SmallVectorImpl<Value*> &NewIndices) {
875 assert(PtrTy->isPtrOrPtrVectorTy());
880 Type *Ty = PtrTy->getPointerElementType();
884 // Start with the index over the outer type. Note that the type size
885 // might be zero (even if the offset isn't zero) if the indexed type
886 // is something like [0 x {int, int}]
887 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
888 int64_t FirstIdx = 0;
889 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
890 FirstIdx = Offset/TySize;
891 Offset -= FirstIdx*TySize;
893 // Handle hosts where % returns negative instead of values [0..TySize).
899 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
902 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
904 // Index into the types. If we fail, set OrigBase to null.
906 // Indexing into tail padding between struct/array elements.
907 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
910 if (StructType *STy = dyn_cast<StructType>(Ty)) {
911 const StructLayout *SL = DL->getStructLayout(STy);
912 assert(Offset < (int64_t)SL->getSizeInBytes() &&
913 "Offset must stay within the indexed type");
915 unsigned Elt = SL->getElementContainingOffset(Offset);
916 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
919 Offset -= SL->getElementOffset(Elt);
920 Ty = STy->getElementType(Elt);
921 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
922 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
923 assert(EltSize && "Cannot index into a zero-sized array");
924 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
926 Ty = AT->getElementType();
928 // Otherwise, we can't index into the middle of this atomic type, bail.
936 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
937 // If this GEP has only 0 indices, it is the same pointer as
938 // Src. If Src is not a trivial GEP too, don't combine
940 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
946 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
947 /// the multiplication is known not to overflow then NoSignedWrap is set.
948 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
949 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
950 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
951 Scale.getBitWidth() && "Scale not compatible with value!");
953 // If Val is zero or Scale is one then Val = Val * Scale.
954 if (match(Val, m_Zero()) || Scale == 1) {
959 // If Scale is zero then it does not divide Val.
960 if (Scale.isMinValue())
963 // Look through chains of multiplications, searching for a constant that is
964 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
965 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
966 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
969 // Val = M1 * X || Analysis starts here and works down
970 // M1 = M2 * Y || Doesn't descend into terms with more
971 // M2 = Z * 4 \/ than one use
973 // Then to modify a term at the bottom:
976 // M1 = Z * Y || Replaced M2 with Z
978 // Then to work back up correcting nsw flags.
980 // Op - the term we are currently analyzing. Starts at Val then drills down.
981 // Replaced with its descaled value before exiting from the drill down loop.
984 // Parent - initially null, but after drilling down notes where Op came from.
985 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
986 // 0'th operand of Val.
987 std::pair<Instruction*, unsigned> Parent;
989 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
990 // levels that doesn't overflow.
991 bool RequireNoSignedWrap = false;
993 // logScale - log base 2 of the scale. Negative if not a power of 2.
994 int32_t logScale = Scale.exactLogBase2();
996 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
998 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
999 // If Op is a constant divisible by Scale then descale to the quotient.
1000 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1001 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1002 if (!Remainder.isMinValue())
1003 // Not divisible by Scale.
1005 // Replace with the quotient in the parent.
1006 Op = ConstantInt::get(CI->getType(), Quotient);
1007 NoSignedWrap = true;
1011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1013 if (BO->getOpcode() == Instruction::Mul) {
1015 NoSignedWrap = BO->hasNoSignedWrap();
1016 if (RequireNoSignedWrap && !NoSignedWrap)
1019 // There are three cases for multiplication: multiplication by exactly
1020 // the scale, multiplication by a constant different to the scale, and
1021 // multiplication by something else.
1022 Value *LHS = BO->getOperand(0);
1023 Value *RHS = BO->getOperand(1);
1025 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1026 // Multiplication by a constant.
1027 if (CI->getValue() == Scale) {
1028 // Multiplication by exactly the scale, replace the multiplication
1029 // by its left-hand side in the parent.
1034 // Otherwise drill down into the constant.
1035 if (!Op->hasOneUse())
1038 Parent = std::make_pair(BO, 1);
1042 // Multiplication by something else. Drill down into the left-hand side
1043 // since that's where the reassociate pass puts the good stuff.
1044 if (!Op->hasOneUse())
1047 Parent = std::make_pair(BO, 0);
1051 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1052 isa<ConstantInt>(BO->getOperand(1))) {
1053 // Multiplication by a power of 2.
1054 NoSignedWrap = BO->hasNoSignedWrap();
1055 if (RequireNoSignedWrap && !NoSignedWrap)
1058 Value *LHS = BO->getOperand(0);
1059 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1060 getLimitedValue(Scale.getBitWidth());
1063 if (Amt == logScale) {
1064 // Multiplication by exactly the scale, replace the multiplication
1065 // by its left-hand side in the parent.
1069 if (Amt < logScale || !Op->hasOneUse())
1072 // Multiplication by more than the scale. Reduce the multiplying amount
1073 // by the scale in the parent.
1074 Parent = std::make_pair(BO, 1);
1075 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1080 if (!Op->hasOneUse())
1083 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1084 if (Cast->getOpcode() == Instruction::SExt) {
1085 // Op is sign-extended from a smaller type, descale in the smaller type.
1086 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1087 APInt SmallScale = Scale.trunc(SmallSize);
1088 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1089 // descale Op as (sext Y) * Scale. In order to have
1090 // sext (Y * SmallScale) = (sext Y) * Scale
1091 // some conditions need to hold however: SmallScale must sign-extend to
1092 // Scale and the multiplication Y * SmallScale should not overflow.
1093 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1094 // SmallScale does not sign-extend to Scale.
1096 assert(SmallScale.exactLogBase2() == logScale);
1097 // Require that Y * SmallScale must not overflow.
1098 RequireNoSignedWrap = true;
1100 // Drill down through the cast.
1101 Parent = std::make_pair(Cast, 0);
1106 if (Cast->getOpcode() == Instruction::Trunc) {
1107 // Op is truncated from a larger type, descale in the larger type.
1108 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1109 // trunc (Y * sext Scale) = (trunc Y) * Scale
1110 // always holds. However (trunc Y) * Scale may overflow even if
1111 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1112 // from this point up in the expression (see later).
1113 if (RequireNoSignedWrap)
1116 // Drill down through the cast.
1117 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1118 Parent = std::make_pair(Cast, 0);
1119 Scale = Scale.sext(LargeSize);
1120 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1122 assert(Scale.exactLogBase2() == logScale);
1127 // Unsupported expression, bail out.
1131 // If Op is zero then Val = Op * Scale.
1132 if (match(Op, m_Zero())) {
1133 NoSignedWrap = true;
1137 // We know that we can successfully descale, so from here on we can safely
1138 // modify the IR. Op holds the descaled version of the deepest term in the
1139 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1143 // The expression only had one term.
1146 // Rewrite the parent using the descaled version of its operand.
1147 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1148 assert(Op != Parent.first->getOperand(Parent.second) &&
1149 "Descaling was a no-op?");
1150 Parent.first->setOperand(Parent.second, Op);
1151 Worklist.Add(Parent.first);
1153 // Now work back up the expression correcting nsw flags. The logic is based
1154 // on the following observation: if X * Y is known not to overflow as a signed
1155 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1156 // then X * Z will not overflow as a signed multiplication either. As we work
1157 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1158 // current level has strictly smaller absolute value than the original.
1159 Instruction *Ancestor = Parent.first;
1161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1162 // If the multiplication wasn't nsw then we can't say anything about the
1163 // value of the descaled multiplication, and we have to clear nsw flags
1164 // from this point on up.
1165 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1166 NoSignedWrap &= OpNoSignedWrap;
1167 if (NoSignedWrap != OpNoSignedWrap) {
1168 BO->setHasNoSignedWrap(NoSignedWrap);
1169 Worklist.Add(Ancestor);
1171 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1172 // The fact that the descaled input to the trunc has smaller absolute
1173 // value than the original input doesn't tell us anything useful about
1174 // the absolute values of the truncations.
1175 NoSignedWrap = false;
1177 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1178 "Failed to keep proper track of nsw flags while drilling down?");
1180 if (Ancestor == Val)
1181 // Got to the top, all done!
1184 // Move up one level in the expression.
1185 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1186 Ancestor = Ancestor->user_back();
1190 /// \brief Creates node of binary operation with the same attributes as the
1191 /// specified one but with other operands.
1192 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1193 InstCombiner::BuilderTy *B) {
1194 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1195 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1196 if (isa<OverflowingBinaryOperator>(NewBO)) {
1197 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1198 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1200 if (isa<PossiblyExactOperator>(NewBO))
1201 NewBO->setIsExact(Inst.isExact());
1206 /// \brief Makes transformation of binary operation specific for vector types.
1207 /// \param Inst Binary operator to transform.
1208 /// \return Pointer to node that must replace the original binary operator, or
1209 /// null pointer if no transformation was made.
1210 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1211 if (!Inst.getType()->isVectorTy()) return nullptr;
1213 // It may not be safe to reorder shuffles and things like div, urem, etc.
1214 // because we may trap when executing those ops on unknown vector elements.
1216 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1218 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1219 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1220 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1221 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1223 // If both arguments of binary operation are shuffles, which use the same
1224 // mask and shuffle within a single vector, it is worthwhile to move the
1225 // shuffle after binary operation:
1226 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1227 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1228 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1229 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1230 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1231 isa<UndefValue>(RShuf->getOperand(1)) &&
1232 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1233 LShuf->getMask() == RShuf->getMask()) {
1234 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1235 RShuf->getOperand(0), Builder);
1236 Value *Res = Builder->CreateShuffleVector(NewBO,
1237 UndefValue::get(NewBO->getType()), LShuf->getMask());
1242 // If one argument is a shuffle within one vector, the other is a constant,
1243 // try moving the shuffle after the binary operation.
1244 ShuffleVectorInst *Shuffle = nullptr;
1245 Constant *C1 = nullptr;
1246 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1247 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1248 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1249 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1250 if (Shuffle && C1 &&
1251 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1252 isa<UndefValue>(Shuffle->getOperand(1)) &&
1253 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1254 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1255 // Find constant C2 that has property:
1256 // shuffle(C2, ShMask) = C1
1257 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1258 // reorder is not possible.
1259 SmallVector<Constant*, 16> C2M(VWidth,
1260 UndefValue::get(C1->getType()->getScalarType()));
1261 bool MayChange = true;
1262 for (unsigned I = 0; I < VWidth; ++I) {
1263 if (ShMask[I] >= 0) {
1264 assert(ShMask[I] < (int)VWidth);
1265 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1269 C2M[ShMask[I]] = C1->getAggregateElement(I);
1273 Constant *C2 = ConstantVector::get(C2M);
1274 Value *NewLHS, *NewRHS;
1275 if (isa<Constant>(LHS)) {
1277 NewRHS = Shuffle->getOperand(0);
1279 NewLHS = Shuffle->getOperand(0);
1282 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1283 Value *Res = Builder->CreateShuffleVector(NewBO,
1284 UndefValue::get(Inst.getType()), Shuffle->getMask());
1292 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1293 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1295 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1296 return ReplaceInstUsesWith(GEP, V);
1298 Value *PtrOp = GEP.getOperand(0);
1300 // Eliminate unneeded casts for indices, and replace indices which displace
1301 // by multiples of a zero size type with zero.
1303 bool MadeChange = false;
1304 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1306 gep_type_iterator GTI = gep_type_begin(GEP);
1307 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1308 I != E; ++I, ++GTI) {
1309 // Skip indices into struct types.
1310 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1311 if (!SeqTy) continue;
1313 // If the element type has zero size then any index over it is equivalent
1314 // to an index of zero, so replace it with zero if it is not zero already.
1315 if (SeqTy->getElementType()->isSized() &&
1316 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1317 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1318 *I = Constant::getNullValue(IntPtrTy);
1322 Type *IndexTy = (*I)->getType();
1323 if (IndexTy != IntPtrTy) {
1324 // If we are using a wider index than needed for this platform, shrink
1325 // it to what we need. If narrower, sign-extend it to what we need.
1326 // This explicit cast can make subsequent optimizations more obvious.
1327 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1331 if (MadeChange) return &GEP;
1334 // Check to see if the inputs to the PHI node are getelementptr instructions.
1335 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1336 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1342 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1343 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1344 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1347 // Keep track of the type as we walk the GEP.
1348 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1350 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1351 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1354 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1356 // We have not seen any differences yet in the GEPs feeding the
1357 // PHI yet, so we record this one if it is allowed to be a
1360 // The first two arguments can vary for any GEP, the rest have to be
1361 // static for struct slots
1362 if (J > 1 && CurTy->isStructTy())
1367 // The GEP is different by more than one input. While this could be
1368 // extended to support GEPs that vary by more than one variable it
1369 // doesn't make sense since it greatly increases the complexity and
1370 // would result in an R+R+R addressing mode which no backend
1371 // directly supports and would need to be broken into several
1372 // simpler instructions anyway.
1377 // Sink down a layer of the type for the next iteration.
1379 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1380 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1388 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1391 // All the GEPs feeding the PHI are identical. Clone one down into our
1392 // BB so that it can be merged with the current GEP.
1393 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1396 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1397 // into the current block so it can be merged, and create a new PHI to
1399 Instruction *InsertPt = Builder->GetInsertPoint();
1400 Builder->SetInsertPoint(PN);
1401 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1402 PN->getNumOperands());
1403 Builder->SetInsertPoint(InsertPt);
1405 for (auto &I : PN->operands())
1406 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1407 PN->getIncomingBlock(I));
1409 NewGEP->setOperand(DI, NewPN);
1410 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1412 NewGEP->setOperand(DI, NewPN);
1415 GEP.setOperand(0, NewGEP);
1419 // Combine Indices - If the source pointer to this getelementptr instruction
1420 // is a getelementptr instruction, combine the indices of the two
1421 // getelementptr instructions into a single instruction.
1423 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1424 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1427 // Note that if our source is a gep chain itself then we wait for that
1428 // chain to be resolved before we perform this transformation. This
1429 // avoids us creating a TON of code in some cases.
1430 if (GEPOperator *SrcGEP =
1431 dyn_cast<GEPOperator>(Src->getOperand(0)))
1432 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1433 return nullptr; // Wait until our source is folded to completion.
1435 SmallVector<Value*, 8> Indices;
1437 // Find out whether the last index in the source GEP is a sequential idx.
1438 bool EndsWithSequential = false;
1439 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1441 EndsWithSequential = !(*I)->isStructTy();
1443 // Can we combine the two pointer arithmetics offsets?
1444 if (EndsWithSequential) {
1445 // Replace: gep (gep %P, long B), long A, ...
1446 // With: T = long A+B; gep %P, T, ...
1449 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1450 Value *GO1 = GEP.getOperand(1);
1451 if (SO1 == Constant::getNullValue(SO1->getType())) {
1453 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1456 // If they aren't the same type, then the input hasn't been processed
1457 // by the loop above yet (which canonicalizes sequential index types to
1458 // intptr_t). Just avoid transforming this until the input has been
1460 if (SO1->getType() != GO1->getType())
1462 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1465 // Update the GEP in place if possible.
1466 if (Src->getNumOperands() == 2) {
1467 GEP.setOperand(0, Src->getOperand(0));
1468 GEP.setOperand(1, Sum);
1471 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1472 Indices.push_back(Sum);
1473 Indices.append(GEP.op_begin()+2, GEP.op_end());
1474 } else if (isa<Constant>(*GEP.idx_begin()) &&
1475 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1476 Src->getNumOperands() != 1) {
1477 // Otherwise we can do the fold if the first index of the GEP is a zero
1478 Indices.append(Src->op_begin()+1, Src->op_end());
1479 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1482 if (!Indices.empty())
1483 return (GEP.isInBounds() && Src->isInBounds()) ?
1484 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1486 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1489 if (DL && GEP.getNumIndices() == 1) {
1490 unsigned AS = GEP.getPointerAddressSpace();
1491 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1492 DL->getPointerSizeInBits(AS)) {
1493 Type *PtrTy = GEP.getPointerOperandType();
1494 Type *Ty = PtrTy->getPointerElementType();
1495 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1497 bool Matched = false;
1500 if (TyAllocSize == 1) {
1501 V = GEP.getOperand(1);
1503 } else if (match(GEP.getOperand(1),
1504 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1505 if (TyAllocSize == 1ULL << C)
1507 } else if (match(GEP.getOperand(1),
1508 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1509 if (TyAllocSize == C)
1514 // Canonicalize (gep i8* X, -(ptrtoint Y))
1515 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1516 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1517 // pointer arithmetic.
1518 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1519 Operator *Index = cast<Operator>(V);
1520 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1521 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1522 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1524 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1527 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1528 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1529 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1536 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1537 Value *StrippedPtr = PtrOp->stripPointerCasts();
1538 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1540 // We do not handle pointer-vector geps here.
1544 if (StrippedPtr != PtrOp) {
1545 bool HasZeroPointerIndex = false;
1546 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1547 HasZeroPointerIndex = C->isZero();
1549 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1550 // into : GEP [10 x i8]* X, i32 0, ...
1552 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1553 // into : GEP i8* X, ...
1555 // This occurs when the program declares an array extern like "int X[];"
1556 if (HasZeroPointerIndex) {
1557 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1558 if (ArrayType *CATy =
1559 dyn_cast<ArrayType>(CPTy->getElementType())) {
1560 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1561 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1562 // -> GEP i8* X, ...
1563 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1564 GetElementPtrInst *Res =
1565 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1566 Res->setIsInBounds(GEP.isInBounds());
1567 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1569 // Insert Res, and create an addrspacecast.
1571 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1573 // %0 = GEP i8 addrspace(1)* X, ...
1574 // addrspacecast i8 addrspace(1)* %0 to i8*
1575 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1578 if (ArrayType *XATy =
1579 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1580 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1581 if (CATy->getElementType() == XATy->getElementType()) {
1582 // -> GEP [10 x i8]* X, i32 0, ...
1583 // At this point, we know that the cast source type is a pointer
1584 // to an array of the same type as the destination pointer
1585 // array. Because the array type is never stepped over (there
1586 // is a leading zero) we can fold the cast into this GEP.
1587 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1588 GEP.setOperand(0, StrippedPtr);
1591 // Cannot replace the base pointer directly because StrippedPtr's
1592 // address space is different. Instead, create a new GEP followed by
1593 // an addrspacecast.
1595 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1598 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1599 // addrspacecast i8 addrspace(1)* %0 to i8*
1600 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1601 Value *NewGEP = GEP.isInBounds() ?
1602 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1603 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1604 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1608 } else if (GEP.getNumOperands() == 2) {
1609 // Transform things like:
1610 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1611 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1612 Type *SrcElTy = StrippedPtrTy->getElementType();
1613 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1614 if (DL && SrcElTy->isArrayTy() &&
1615 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1616 DL->getTypeAllocSize(ResElTy)) {
1617 Type *IdxType = DL->getIntPtrType(GEP.getType());
1618 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1619 Value *NewGEP = GEP.isInBounds() ?
1620 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1621 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1623 // V and GEP are both pointer types --> BitCast
1624 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1628 // Transform things like:
1629 // %V = mul i64 %N, 4
1630 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1631 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1632 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1633 // Check that changing the type amounts to dividing the index by a scale
1635 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1636 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1637 if (ResSize && SrcSize % ResSize == 0) {
1638 Value *Idx = GEP.getOperand(1);
1639 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1640 uint64_t Scale = SrcSize / ResSize;
1642 // Earlier transforms ensure that the index has type IntPtrType, which
1643 // considerably simplifies the logic by eliminating implicit casts.
1644 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1645 "Index not cast to pointer width?");
1648 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1649 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1650 // If the multiplication NewIdx * Scale may overflow then the new
1651 // GEP may not be "inbounds".
1652 Value *NewGEP = GEP.isInBounds() && NSW ?
1653 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1654 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1656 // The NewGEP must be pointer typed, so must the old one -> BitCast
1657 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1663 // Similarly, transform things like:
1664 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1665 // (where tmp = 8*tmp2) into:
1666 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1667 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1668 SrcElTy->isArrayTy()) {
1669 // Check that changing to the array element type amounts to dividing the
1670 // index by a scale factor.
1671 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1672 uint64_t ArrayEltSize
1673 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1674 if (ResSize && ArrayEltSize % ResSize == 0) {
1675 Value *Idx = GEP.getOperand(1);
1676 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1677 uint64_t Scale = ArrayEltSize / ResSize;
1679 // Earlier transforms ensure that the index has type IntPtrType, which
1680 // considerably simplifies the logic by eliminating implicit casts.
1681 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1682 "Index not cast to pointer width?");
1685 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1686 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1687 // If the multiplication NewIdx * Scale may overflow then the new
1688 // GEP may not be "inbounds".
1690 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1694 Value *NewGEP = GEP.isInBounds() && NSW ?
1695 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1696 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1697 // The NewGEP must be pointer typed, so must the old one -> BitCast
1698 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1709 // addrspacecast between types is canonicalized as a bitcast, then an
1710 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1711 // through the addrspacecast.
1712 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1713 // X = bitcast A addrspace(1)* to B addrspace(1)*
1714 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1715 // Z = gep Y, <...constant indices...>
1716 // Into an addrspacecasted GEP of the struct.
1717 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1721 /// See if we can simplify:
1722 /// X = bitcast A* to B*
1723 /// Y = gep X, <...constant indices...>
1724 /// into a gep of the original struct. This is important for SROA and alias
1725 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1726 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1727 Value *Operand = BCI->getOperand(0);
1728 PointerType *OpType = cast<PointerType>(Operand->getType());
1729 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1730 APInt Offset(OffsetBits, 0);
1731 if (!isa<BitCastInst>(Operand) &&
1732 GEP.accumulateConstantOffset(*DL, Offset)) {
1734 // If this GEP instruction doesn't move the pointer, just replace the GEP
1735 // with a bitcast of the real input to the dest type.
1737 // If the bitcast is of an allocation, and the allocation will be
1738 // converted to match the type of the cast, don't touch this.
1739 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1740 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1741 if (Instruction *I = visitBitCast(*BCI)) {
1744 BCI->getParent()->getInstList().insert(BCI, I);
1745 ReplaceInstUsesWith(*BCI, I);
1751 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1752 return new AddrSpaceCastInst(Operand, GEP.getType());
1753 return new BitCastInst(Operand, GEP.getType());
1756 // Otherwise, if the offset is non-zero, we need to find out if there is a
1757 // field at Offset in 'A's type. If so, we can pull the cast through the
1759 SmallVector<Value*, 8> NewIndices;
1760 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1761 Value *NGEP = GEP.isInBounds() ?
1762 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1763 Builder->CreateGEP(Operand, NewIndices);
1765 if (NGEP->getType() == GEP.getType())
1766 return ReplaceInstUsesWith(GEP, NGEP);
1767 NGEP->takeName(&GEP);
1769 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1770 return new AddrSpaceCastInst(NGEP, GEP.getType());
1771 return new BitCastInst(NGEP, GEP.getType());
1780 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1781 const TargetLibraryInfo *TLI) {
1782 SmallVector<Instruction*, 4> Worklist;
1783 Worklist.push_back(AI);
1786 Instruction *PI = Worklist.pop_back_val();
1787 for (User *U : PI->users()) {
1788 Instruction *I = cast<Instruction>(U);
1789 switch (I->getOpcode()) {
1791 // Give up the moment we see something we can't handle.
1794 case Instruction::BitCast:
1795 case Instruction::GetElementPtr:
1797 Worklist.push_back(I);
1800 case Instruction::ICmp: {
1801 ICmpInst *ICI = cast<ICmpInst>(I);
1802 // We can fold eq/ne comparisons with null to false/true, respectively.
1803 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1809 case Instruction::Call:
1810 // Ignore no-op and store intrinsics.
1811 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1812 switch (II->getIntrinsicID()) {
1816 case Intrinsic::memmove:
1817 case Intrinsic::memcpy:
1818 case Intrinsic::memset: {
1819 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1820 if (MI->isVolatile() || MI->getRawDest() != PI)
1824 case Intrinsic::dbg_declare:
1825 case Intrinsic::dbg_value:
1826 case Intrinsic::invariant_start:
1827 case Intrinsic::invariant_end:
1828 case Intrinsic::lifetime_start:
1829 case Intrinsic::lifetime_end:
1830 case Intrinsic::objectsize:
1836 if (isFreeCall(I, TLI)) {
1842 case Instruction::Store: {
1843 StoreInst *SI = cast<StoreInst>(I);
1844 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1850 llvm_unreachable("missing a return?");
1852 } while (!Worklist.empty());
1856 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1857 // If we have a malloc call which is only used in any amount of comparisons
1858 // to null and free calls, delete the calls and replace the comparisons with
1859 // true or false as appropriate.
1860 SmallVector<WeakVH, 64> Users;
1861 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1862 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1863 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1866 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1867 ReplaceInstUsesWith(*C,
1868 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1869 C->isFalseWhenEqual()));
1870 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1871 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1872 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1873 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1874 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1875 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1876 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1879 EraseInstFromFunction(*I);
1882 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1883 // Replace invoke with a NOP intrinsic to maintain the original CFG
1884 Module *M = II->getParent()->getParent()->getParent();
1885 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1886 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1887 None, "", II->getParent());
1889 return EraseInstFromFunction(MI);
1894 /// \brief Move the call to free before a NULL test.
1896 /// Check if this free is accessed after its argument has been test
1897 /// against NULL (property 0).
1898 /// If yes, it is legal to move this call in its predecessor block.
1900 /// The move is performed only if the block containing the call to free
1901 /// will be removed, i.e.:
1902 /// 1. it has only one predecessor P, and P has two successors
1903 /// 2. it contains the call and an unconditional branch
1904 /// 3. its successor is the same as its predecessor's successor
1906 /// The profitability is out-of concern here and this function should
1907 /// be called only if the caller knows this transformation would be
1908 /// profitable (e.g., for code size).
1909 static Instruction *
1910 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1911 Value *Op = FI.getArgOperand(0);
1912 BasicBlock *FreeInstrBB = FI.getParent();
1913 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1915 // Validate part of constraint #1: Only one predecessor
1916 // FIXME: We can extend the number of predecessor, but in that case, we
1917 // would duplicate the call to free in each predecessor and it may
1918 // not be profitable even for code size.
1922 // Validate constraint #2: Does this block contains only the call to
1923 // free and an unconditional branch?
1924 // FIXME: We could check if we can speculate everything in the
1925 // predecessor block
1926 if (FreeInstrBB->size() != 2)
1929 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1932 // Validate the rest of constraint #1 by matching on the pred branch.
1933 TerminatorInst *TI = PredBB->getTerminator();
1934 BasicBlock *TrueBB, *FalseBB;
1935 ICmpInst::Predicate Pred;
1936 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1938 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1941 // Validate constraint #3: Ensure the null case just falls through.
1942 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1944 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1945 "Broken CFG: missing edge from predecessor to successor");
1952 Instruction *InstCombiner::visitFree(CallInst &FI) {
1953 Value *Op = FI.getArgOperand(0);
1955 // free undef -> unreachable.
1956 if (isa<UndefValue>(Op)) {
1957 // Insert a new store to null because we cannot modify the CFG here.
1958 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1959 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1960 return EraseInstFromFunction(FI);
1963 // If we have 'free null' delete the instruction. This can happen in stl code
1964 // when lots of inlining happens.
1965 if (isa<ConstantPointerNull>(Op))
1966 return EraseInstFromFunction(FI);
1968 // If we optimize for code size, try to move the call to free before the null
1969 // test so that simplify cfg can remove the empty block and dead code
1970 // elimination the branch. I.e., helps to turn something like:
1971 // if (foo) free(foo);
1975 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1981 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
1982 if (RI.getNumOperands() == 0) // ret void
1985 Value *ResultOp = RI.getOperand(0);
1986 Type *VTy = ResultOp->getType();
1987 if (!VTy->isIntegerTy())
1990 // There might be assume intrinsics dominating this return that completely
1991 // determine the value. If so, constant fold it.
1992 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1993 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1994 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
1995 if ((KnownZero|KnownOne).isAllOnesValue())
1996 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2001 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2002 // Change br (not X), label True, label False to: br X, label False, True
2004 BasicBlock *TrueDest;
2005 BasicBlock *FalseDest;
2006 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2007 !isa<Constant>(X)) {
2008 // Swap Destinations and condition...
2010 BI.swapSuccessors();
2014 // Canonicalize fcmp_one -> fcmp_oeq
2015 FCmpInst::Predicate FPred; Value *Y;
2016 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2017 TrueDest, FalseDest)) &&
2018 BI.getCondition()->hasOneUse())
2019 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2020 FPred == FCmpInst::FCMP_OGE) {
2021 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2022 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2024 // Swap Destinations and condition.
2025 BI.swapSuccessors();
2030 // Canonicalize icmp_ne -> icmp_eq
2031 ICmpInst::Predicate IPred;
2032 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2033 TrueDest, FalseDest)) &&
2034 BI.getCondition()->hasOneUse())
2035 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2036 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2037 IPred == ICmpInst::ICMP_SGE) {
2038 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2039 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2040 // Swap Destinations and condition.
2041 BI.swapSuccessors();
2049 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2050 Value *Cond = SI.getCondition();
2051 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2052 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2053 computeKnownBits(Cond, KnownZero, KnownOne);
2054 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2055 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2057 // Compute the number of leading bits we can ignore.
2058 for (auto &C : SI.cases()) {
2059 LeadingKnownZeros = std::min(
2060 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2061 LeadingKnownOnes = std::min(
2062 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2065 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2067 // Truncate the condition operand if the new type is equal to or larger than
2068 // the largest legal integer type. We need to be conservative here since
2069 // x86 generates redundant zero-extenstion instructions if the operand is
2070 // truncated to i8 or i16.
2071 bool TruncCond = false;
2072 if (DL && BitWidth > NewWidth &&
2073 NewWidth >= DL->getLargestLegalIntTypeSize()) {
2075 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2076 Builder->SetInsertPoint(&SI);
2077 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2078 SI.setCondition(NewCond);
2080 for (auto &C : SI.cases())
2081 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2082 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2085 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2086 if (I->getOpcode() == Instruction::Add)
2087 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2088 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2089 // Skip the first item since that's the default case.
2090 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2092 ConstantInt* CaseVal = i.getCaseValue();
2093 Constant *LHS = CaseVal;
2095 LHS = LeadingKnownZeros
2096 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2097 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2098 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2099 assert(isa<ConstantInt>(NewCaseVal) &&
2100 "Result of expression should be constant");
2101 i.setValue(cast<ConstantInt>(NewCaseVal));
2103 SI.setCondition(I->getOperand(0));
2109 return TruncCond ? &SI : nullptr;
2112 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2113 Value *Agg = EV.getAggregateOperand();
2115 if (!EV.hasIndices())
2116 return ReplaceInstUsesWith(EV, Agg);
2118 if (Constant *C = dyn_cast<Constant>(Agg)) {
2119 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2120 if (EV.getNumIndices() == 0)
2121 return ReplaceInstUsesWith(EV, C2);
2122 // Extract the remaining indices out of the constant indexed by the
2124 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2126 return nullptr; // Can't handle other constants
2129 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2130 // We're extracting from an insertvalue instruction, compare the indices
2131 const unsigned *exti, *exte, *insi, *inse;
2132 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2133 exte = EV.idx_end(), inse = IV->idx_end();
2134 exti != exte && insi != inse;
2137 // The insert and extract both reference distinctly different elements.
2138 // This means the extract is not influenced by the insert, and we can
2139 // replace the aggregate operand of the extract with the aggregate
2140 // operand of the insert. i.e., replace
2141 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2142 // %E = extractvalue { i32, { i32 } } %I, 0
2144 // %E = extractvalue { i32, { i32 } } %A, 0
2145 return ExtractValueInst::Create(IV->getAggregateOperand(),
2148 if (exti == exte && insi == inse)
2149 // Both iterators are at the end: Index lists are identical. Replace
2150 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2151 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2153 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2155 // The extract list is a prefix of the insert list. i.e. replace
2156 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2157 // %E = extractvalue { i32, { i32 } } %I, 1
2159 // %X = extractvalue { i32, { i32 } } %A, 1
2160 // %E = insertvalue { i32 } %X, i32 42, 0
2161 // by switching the order of the insert and extract (though the
2162 // insertvalue should be left in, since it may have other uses).
2163 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2165 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2166 makeArrayRef(insi, inse));
2169 // The insert list is a prefix of the extract list
2170 // We can simply remove the common indices from the extract and make it
2171 // operate on the inserted value instead of the insertvalue result.
2173 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2174 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2176 // %E extractvalue { i32 } { i32 42 }, 0
2177 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2178 makeArrayRef(exti, exte));
2180 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2181 // We're extracting from an intrinsic, see if we're the only user, which
2182 // allows us to simplify multiple result intrinsics to simpler things that
2183 // just get one value.
2184 if (II->hasOneUse()) {
2185 // Check if we're grabbing the overflow bit or the result of a 'with
2186 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2187 // and replace it with a traditional binary instruction.
2188 switch (II->getIntrinsicID()) {
2189 case Intrinsic::uadd_with_overflow:
2190 case Intrinsic::sadd_with_overflow:
2191 if (*EV.idx_begin() == 0) { // Normal result.
2192 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2193 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2194 EraseInstFromFunction(*II);
2195 return BinaryOperator::CreateAdd(LHS, RHS);
2198 // If the normal result of the add is dead, and the RHS is a constant,
2199 // we can transform this into a range comparison.
2200 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2201 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2202 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2203 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2204 ConstantExpr::getNot(CI));
2206 case Intrinsic::usub_with_overflow:
2207 case Intrinsic::ssub_with_overflow:
2208 if (*EV.idx_begin() == 0) { // Normal result.
2209 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2210 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2211 EraseInstFromFunction(*II);
2212 return BinaryOperator::CreateSub(LHS, RHS);
2215 case Intrinsic::umul_with_overflow:
2216 case Intrinsic::smul_with_overflow:
2217 if (*EV.idx_begin() == 0) { // Normal result.
2218 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2219 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2220 EraseInstFromFunction(*II);
2221 return BinaryOperator::CreateMul(LHS, RHS);
2229 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2230 // If the (non-volatile) load only has one use, we can rewrite this to a
2231 // load from a GEP. This reduces the size of the load.
2232 // FIXME: If a load is used only by extractvalue instructions then this
2233 // could be done regardless of having multiple uses.
2234 if (L->isSimple() && L->hasOneUse()) {
2235 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2236 SmallVector<Value*, 4> Indices;
2237 // Prefix an i32 0 since we need the first element.
2238 Indices.push_back(Builder->getInt32(0));
2239 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2241 Indices.push_back(Builder->getInt32(*I));
2243 // We need to insert these at the location of the old load, not at that of
2244 // the extractvalue.
2245 Builder->SetInsertPoint(L->getParent(), L);
2246 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2247 // Returning the load directly will cause the main loop to insert it in
2248 // the wrong spot, so use ReplaceInstUsesWith().
2249 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2251 // We could simplify extracts from other values. Note that nested extracts may
2252 // already be simplified implicitly by the above: extract (extract (insert) )
2253 // will be translated into extract ( insert ( extract ) ) first and then just
2254 // the value inserted, if appropriate. Similarly for extracts from single-use
2255 // loads: extract (extract (load)) will be translated to extract (load (gep))
2256 // and if again single-use then via load (gep (gep)) to load (gep).
2257 // However, double extracts from e.g. function arguments or return values
2258 // aren't handled yet.
2262 enum Personality_Type {
2263 Unknown_Personality,
2264 GNU_Ada_Personality,
2265 GNU_CXX_Personality,
2266 GNU_ObjC_Personality
2269 /// RecognizePersonality - See if the given exception handling personality
2270 /// function is one that we understand. If so, return a description of it;
2271 /// otherwise return Unknown_Personality.
2272 static Personality_Type RecognizePersonality(Value *Pers) {
2273 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2275 return Unknown_Personality;
2276 return StringSwitch<Personality_Type>(F->getName())
2277 .Case("__gnat_eh_personality", GNU_Ada_Personality)
2278 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2279 .Case("__objc_personality_v0", GNU_ObjC_Personality)
2280 .Default(Unknown_Personality);
2283 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2284 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2285 switch (Personality) {
2286 case Unknown_Personality:
2288 case GNU_Ada_Personality:
2289 // While __gnat_all_others_value will match any Ada exception, it doesn't
2290 // match foreign exceptions (or didn't, before gcc-4.7).
2292 case GNU_CXX_Personality:
2293 case GNU_ObjC_Personality:
2294 return TypeInfo->isNullValue();
2296 llvm_unreachable("Unknown personality!");
2299 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2301 cast<ArrayType>(LHS->getType())->getNumElements()
2303 cast<ArrayType>(RHS->getType())->getNumElements();
2306 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2307 // The logic here should be correct for any real-world personality function.
2308 // However if that turns out not to be true, the offending logic can always
2309 // be conditioned on the personality function, like the catch-all logic is.
2310 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2312 // Simplify the list of clauses, eg by removing repeated catch clauses
2313 // (these are often created by inlining).
2314 bool MakeNewInstruction = false; // If true, recreate using the following:
2315 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2316 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2318 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2319 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2320 bool isLastClause = i + 1 == e;
2321 if (LI.isCatch(i)) {
2323 Constant *CatchClause = LI.getClause(i);
2324 Constant *TypeInfo = CatchClause->stripPointerCasts();
2326 // If we already saw this clause, there is no point in having a second
2328 if (AlreadyCaught.insert(TypeInfo).second) {
2329 // This catch clause was not already seen.
2330 NewClauses.push_back(CatchClause);
2332 // Repeated catch clause - drop the redundant copy.
2333 MakeNewInstruction = true;
2336 // If this is a catch-all then there is no point in keeping any following
2337 // clauses or marking the landingpad as having a cleanup.
2338 if (isCatchAll(Personality, TypeInfo)) {
2340 MakeNewInstruction = true;
2341 CleanupFlag = false;
2345 // A filter clause. If any of the filter elements were already caught
2346 // then they can be dropped from the filter. It is tempting to try to
2347 // exploit the filter further by saying that any typeinfo that does not
2348 // occur in the filter can't be caught later (and thus can be dropped).
2349 // However this would be wrong, since typeinfos can match without being
2350 // equal (for example if one represents a C++ class, and the other some
2351 // class derived from it).
2352 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2353 Constant *FilterClause = LI.getClause(i);
2354 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2355 unsigned NumTypeInfos = FilterType->getNumElements();
2357 // An empty filter catches everything, so there is no point in keeping any
2358 // following clauses or marking the landingpad as having a cleanup. By
2359 // dealing with this case here the following code is made a bit simpler.
2360 if (!NumTypeInfos) {
2361 NewClauses.push_back(FilterClause);
2363 MakeNewInstruction = true;
2364 CleanupFlag = false;
2368 bool MakeNewFilter = false; // If true, make a new filter.
2369 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2370 if (isa<ConstantAggregateZero>(FilterClause)) {
2371 // Not an empty filter - it contains at least one null typeinfo.
2372 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2373 Constant *TypeInfo =
2374 Constant::getNullValue(FilterType->getElementType());
2375 // If this typeinfo is a catch-all then the filter can never match.
2376 if (isCatchAll(Personality, TypeInfo)) {
2377 // Throw the filter away.
2378 MakeNewInstruction = true;
2382 // There is no point in having multiple copies of this typeinfo, so
2383 // discard all but the first copy if there is more than one.
2384 NewFilterElts.push_back(TypeInfo);
2385 if (NumTypeInfos > 1)
2386 MakeNewFilter = true;
2388 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2389 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2390 NewFilterElts.reserve(NumTypeInfos);
2392 // Remove any filter elements that were already caught or that already
2393 // occurred in the filter. While there, see if any of the elements are
2394 // catch-alls. If so, the filter can be discarded.
2395 bool SawCatchAll = false;
2396 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2397 Constant *Elt = Filter->getOperand(j);
2398 Constant *TypeInfo = Elt->stripPointerCasts();
2399 if (isCatchAll(Personality, TypeInfo)) {
2400 // This element is a catch-all. Bail out, noting this fact.
2404 if (AlreadyCaught.count(TypeInfo))
2405 // Already caught by an earlier clause, so having it in the filter
2408 // There is no point in having multiple copies of the same typeinfo in
2409 // a filter, so only add it if we didn't already.
2410 if (SeenInFilter.insert(TypeInfo).second)
2411 NewFilterElts.push_back(cast<Constant>(Elt));
2413 // A filter containing a catch-all cannot match anything by definition.
2415 // Throw the filter away.
2416 MakeNewInstruction = true;
2420 // If we dropped something from the filter, make a new one.
2421 if (NewFilterElts.size() < NumTypeInfos)
2422 MakeNewFilter = true;
2424 if (MakeNewFilter) {
2425 FilterType = ArrayType::get(FilterType->getElementType(),
2426 NewFilterElts.size());
2427 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2428 MakeNewInstruction = true;
2431 NewClauses.push_back(FilterClause);
2433 // If the new filter is empty then it will catch everything so there is
2434 // no point in keeping any following clauses or marking the landingpad
2435 // as having a cleanup. The case of the original filter being empty was
2436 // already handled above.
2437 if (MakeNewFilter && !NewFilterElts.size()) {
2438 assert(MakeNewInstruction && "New filter but not a new instruction!");
2439 CleanupFlag = false;
2445 // If several filters occur in a row then reorder them so that the shortest
2446 // filters come first (those with the smallest number of elements). This is
2447 // advantageous because shorter filters are more likely to match, speeding up
2448 // unwinding, but mostly because it increases the effectiveness of the other
2449 // filter optimizations below.
2450 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2452 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2453 for (j = i; j != e; ++j)
2454 if (!isa<ArrayType>(NewClauses[j]->getType()))
2457 // Check whether the filters are already sorted by length. We need to know
2458 // if sorting them is actually going to do anything so that we only make a
2459 // new landingpad instruction if it does.
2460 for (unsigned k = i; k + 1 < j; ++k)
2461 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2462 // Not sorted, so sort the filters now. Doing an unstable sort would be
2463 // correct too but reordering filters pointlessly might confuse users.
2464 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2466 MakeNewInstruction = true;
2470 // Look for the next batch of filters.
2474 // If typeinfos matched if and only if equal, then the elements of a filter L
2475 // that occurs later than a filter F could be replaced by the intersection of
2476 // the elements of F and L. In reality two typeinfos can match without being
2477 // equal (for example if one represents a C++ class, and the other some class
2478 // derived from it) so it would be wrong to perform this transform in general.
2479 // However the transform is correct and useful if F is a subset of L. In that
2480 // case L can be replaced by F, and thus removed altogether since repeating a
2481 // filter is pointless. So here we look at all pairs of filters F and L where
2482 // L follows F in the list of clauses, and remove L if every element of F is
2483 // an element of L. This can occur when inlining C++ functions with exception
2485 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2486 // Examine each filter in turn.
2487 Value *Filter = NewClauses[i];
2488 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2490 // Not a filter - skip it.
2492 unsigned FElts = FTy->getNumElements();
2493 // Examine each filter following this one. Doing this backwards means that
2494 // we don't have to worry about filters disappearing under us when removed.
2495 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2496 Value *LFilter = NewClauses[j];
2497 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2499 // Not a filter - skip it.
2501 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2502 // an element of LFilter, then discard LFilter.
2503 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2504 // If Filter is empty then it is a subset of LFilter.
2507 NewClauses.erase(J);
2508 MakeNewInstruction = true;
2509 // Move on to the next filter.
2512 unsigned LElts = LTy->getNumElements();
2513 // If Filter is longer than LFilter then it cannot be a subset of it.
2515 // Move on to the next filter.
2517 // At this point we know that LFilter has at least one element.
2518 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2519 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2520 // already know that Filter is not longer than LFilter).
2521 if (isa<ConstantAggregateZero>(Filter)) {
2522 assert(FElts <= LElts && "Should have handled this case earlier!");
2524 NewClauses.erase(J);
2525 MakeNewInstruction = true;
2527 // Move on to the next filter.
2530 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2531 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2532 // Since Filter is non-empty and contains only zeros, it is a subset of
2533 // LFilter iff LFilter contains a zero.
2534 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2535 for (unsigned l = 0; l != LElts; ++l)
2536 if (LArray->getOperand(l)->isNullValue()) {
2537 // LFilter contains a zero - discard it.
2538 NewClauses.erase(J);
2539 MakeNewInstruction = true;
2542 // Move on to the next filter.
2545 // At this point we know that both filters are ConstantArrays. Loop over
2546 // operands to see whether every element of Filter is also an element of
2547 // LFilter. Since filters tend to be short this is probably faster than
2548 // using a method that scales nicely.
2549 ConstantArray *FArray = cast<ConstantArray>(Filter);
2550 bool AllFound = true;
2551 for (unsigned f = 0; f != FElts; ++f) {
2552 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2554 for (unsigned l = 0; l != LElts; ++l) {
2555 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2556 if (LTypeInfo == FTypeInfo) {
2566 NewClauses.erase(J);
2567 MakeNewInstruction = true;
2569 // Move on to the next filter.
2573 // If we changed any of the clauses, replace the old landingpad instruction
2575 if (MakeNewInstruction) {
2576 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2577 LI.getPersonalityFn(),
2579 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2580 NLI->addClause(NewClauses[i]);
2581 // A landing pad with no clauses must have the cleanup flag set. It is
2582 // theoretically possible, though highly unlikely, that we eliminated all
2583 // clauses. If so, force the cleanup flag to true.
2584 if (NewClauses.empty())
2586 NLI->setCleanup(CleanupFlag);
2590 // Even if none of the clauses changed, we may nonetheless have understood
2591 // that the cleanup flag is pointless. Clear it if so.
2592 if (LI.isCleanup() != CleanupFlag) {
2593 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2594 LI.setCleanup(CleanupFlag);
2601 /// TryToSinkInstruction - Try to move the specified instruction from its
2602 /// current block into the beginning of DestBlock, which can only happen if it's
2603 /// safe to move the instruction past all of the instructions between it and the
2604 /// end of its block.
2605 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2606 assert(I->hasOneUse() && "Invariants didn't hold!");
2608 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2609 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2610 isa<TerminatorInst>(I))
2613 // Do not sink alloca instructions out of the entry block.
2614 if (isa<AllocaInst>(I) && I->getParent() ==
2615 &DestBlock->getParent()->getEntryBlock())
2618 // We can only sink load instructions if there is nothing between the load and
2619 // the end of block that could change the value.
2620 if (I->mayReadFromMemory()) {
2621 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2623 if (Scan->mayWriteToMemory())
2627 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2628 I->moveBefore(InsertPos);
2633 bool InstCombiner::run() {
2634 while (!Worklist.isEmpty()) {
2635 Instruction *I = Worklist.RemoveOne();
2636 if (I == nullptr) continue; // skip null values.
2638 // Check to see if we can DCE the instruction.
2639 if (isInstructionTriviallyDead(I, TLI)) {
2640 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2641 EraseInstFromFunction(*I);
2643 MadeIRChange = true;
2647 // Instruction isn't dead, see if we can constant propagate it.
2648 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2649 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2650 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2652 // Add operands to the worklist.
2653 ReplaceInstUsesWith(*I, C);
2655 EraseInstFromFunction(*I);
2656 MadeIRChange = true;
2660 // See if we can trivially sink this instruction to a successor basic block.
2661 if (I->hasOneUse()) {
2662 BasicBlock *BB = I->getParent();
2663 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2664 BasicBlock *UserParent;
2666 // Get the block the use occurs in.
2667 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2668 UserParent = PN->getIncomingBlock(*I->use_begin());
2670 UserParent = UserInst->getParent();
2672 if (UserParent != BB) {
2673 bool UserIsSuccessor = false;
2674 // See if the user is one of our successors.
2675 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2676 if (*SI == UserParent) {
2677 UserIsSuccessor = true;
2681 // If the user is one of our immediate successors, and if that successor
2682 // only has us as a predecessors (we'd have to split the critical edge
2683 // otherwise), we can keep going.
2684 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2685 // Okay, the CFG is simple enough, try to sink this instruction.
2686 if (TryToSinkInstruction(I, UserParent)) {
2687 MadeIRChange = true;
2688 // We'll add uses of the sunk instruction below, but since sinking
2689 // can expose opportunities for it's *operands* add them to the
2691 for (Use &U : I->operands())
2692 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2699 // Now that we have an instruction, try combining it to simplify it.
2700 Builder->SetInsertPoint(I->getParent(), I);
2701 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2706 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2707 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2709 if (Instruction *Result = visit(*I)) {
2711 // Should we replace the old instruction with a new one?
2713 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2714 << " New = " << *Result << '\n');
2716 if (!I->getDebugLoc().isUnknown())
2717 Result->setDebugLoc(I->getDebugLoc());
2718 // Everything uses the new instruction now.
2719 I->replaceAllUsesWith(Result);
2721 // Move the name to the new instruction first.
2722 Result->takeName(I);
2724 // Push the new instruction and any users onto the worklist.
2725 Worklist.Add(Result);
2726 Worklist.AddUsersToWorkList(*Result);
2728 // Insert the new instruction into the basic block...
2729 BasicBlock *InstParent = I->getParent();
2730 BasicBlock::iterator InsertPos = I;
2732 // If we replace a PHI with something that isn't a PHI, fix up the
2734 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2735 InsertPos = InstParent->getFirstInsertionPt();
2737 InstParent->getInstList().insert(InsertPos, Result);
2739 EraseInstFromFunction(*I);
2742 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2743 << " New = " << *I << '\n');
2746 // If the instruction was modified, it's possible that it is now dead.
2747 // if so, remove it.
2748 if (isInstructionTriviallyDead(I, TLI)) {
2749 EraseInstFromFunction(*I);
2752 Worklist.AddUsersToWorkList(*I);
2755 MadeIRChange = true;
2760 return MadeIRChange;
2763 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2764 /// all reachable code to the worklist.
2766 /// This has a couple of tricks to make the code faster and more powerful. In
2767 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2768 /// them to the worklist (this significantly speeds up instcombine on code where
2769 /// many instructions are dead or constant). Additionally, if we find a branch
2770 /// whose condition is a known constant, we only visit the reachable successors.
2772 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2773 SmallPtrSetImpl<BasicBlock*> &Visited,
2774 InstCombineWorklist &ICWorklist,
2775 const DataLayout *DL,
2776 const TargetLibraryInfo *TLI) {
2777 bool MadeIRChange = false;
2778 SmallVector<BasicBlock*, 256> Worklist;
2779 Worklist.push_back(BB);
2781 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2782 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2785 BB = Worklist.pop_back_val();
2787 // We have now visited this block! If we've already been here, ignore it.
2788 if (!Visited.insert(BB).second)
2791 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2792 Instruction *Inst = BBI++;
2794 // DCE instruction if trivially dead.
2795 if (isInstructionTriviallyDead(Inst, TLI)) {
2797 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2798 Inst->eraseFromParent();
2802 // ConstantProp instruction if trivially constant.
2803 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2804 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2805 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2807 Inst->replaceAllUsesWith(C);
2809 Inst->eraseFromParent();
2814 // See if we can constant fold its operands.
2815 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2817 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2818 if (CE == nullptr) continue;
2820 Constant*& FoldRes = FoldedConstants[CE];
2822 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2826 if (FoldRes != CE) {
2828 MadeIRChange = true;
2833 InstrsForInstCombineWorklist.push_back(Inst);
2836 // Recursively visit successors. If this is a branch or switch on a
2837 // constant, only visit the reachable successor.
2838 TerminatorInst *TI = BB->getTerminator();
2839 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2840 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2841 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2842 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2843 Worklist.push_back(ReachableBB);
2846 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2847 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2848 // See if this is an explicit destination.
2849 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2851 if (i.getCaseValue() == Cond) {
2852 BasicBlock *ReachableBB = i.getCaseSuccessor();
2853 Worklist.push_back(ReachableBB);
2857 // Otherwise it is the default destination.
2858 Worklist.push_back(SI->getDefaultDest());
2863 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2864 Worklist.push_back(TI->getSuccessor(i));
2865 } while (!Worklist.empty());
2867 // Once we've found all of the instructions to add to instcombine's worklist,
2868 // add them in reverse order. This way instcombine will visit from the top
2869 // of the function down. This jives well with the way that it adds all uses
2870 // of instructions to the worklist after doing a transformation, thus avoiding
2871 // some N^2 behavior in pathological cases.
2872 ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2873 InstrsForInstCombineWorklist.size());
2875 return MadeIRChange;
2878 /// \brief Populate the IC worklist from a function, and prune any dead basic
2879 /// blocks discovered in the process.
2881 /// This also does basic constant propagation and other forward fixing to make
2882 /// the combiner itself run much faster.
2883 static bool prepareICWorklistFromFunction(Function &F, const DataLayout *DL,
2884 TargetLibraryInfo *TLI,
2885 InstCombineWorklist &ICWorklist) {
2886 bool MadeIRChange = false;
2888 // Do a depth-first traversal of the function, populate the worklist with
2889 // the reachable instructions. Ignore blocks that are not reachable. Keep
2890 // track of which blocks we visit.
2891 SmallPtrSet<BasicBlock *, 64> Visited;
2893 AddReachableCodeToWorklist(F.begin(), Visited, ICWorklist, DL, TLI);
2895 // Do a quick scan over the function. If we find any blocks that are
2896 // unreachable, remove any instructions inside of them. This prevents
2897 // the instcombine code from having to deal with some bad special cases.
2898 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2899 if (Visited.count(BB))
2902 // Delete the instructions backwards, as it has a reduced likelihood of
2903 // having to update as many def-use and use-def chains.
2904 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2905 while (EndInst != BB->begin()) {
2906 // Delete the next to last instruction.
2907 BasicBlock::iterator I = EndInst;
2908 Instruction *Inst = --I;
2909 if (!Inst->use_empty())
2910 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2911 if (isa<LandingPadInst>(Inst)) {
2915 if (!isa<DbgInfoIntrinsic>(Inst)) {
2917 MadeIRChange = true;
2919 Inst->eraseFromParent();
2923 return MadeIRChange;
2926 static bool combineInstructionsOverFunction(
2927 Function &F, InstCombineWorklist &Worklist, AssumptionCache &AC,
2928 TargetLibraryInfo &TLI, DominatorTree &DT, const DataLayout *DL = nullptr,
2929 LoopInfo *LI = nullptr) {
2931 bool MinimizeSize = F.getAttributes().hasAttribute(
2932 AttributeSet::FunctionIndex, Attribute::MinSize);
2934 /// Builder - This is an IRBuilder that automatically inserts new
2935 /// instructions into the worklist when they are created.
2936 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
2937 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
2939 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2941 bool DbgDeclaresChanged = LowerDbgDeclare(F);
2943 // Iterate while there is work to do.
2947 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2948 << F.getName() << "\n");
2950 bool Changed = false;
2951 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
2954 InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI);
2962 return DbgDeclaresChanged || Iteration > 1;
2965 PreservedAnalyses InstCombinePass::run(Function &F,
2966 AnalysisManager<Function> *AM) {
2967 auto *DL = F.getParent()->getDataLayout();
2969 auto &AC = AM->getResult<AssumptionAnalysis>(F);
2970 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
2971 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
2973 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
2975 if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI))
2976 // No changes, all analyses are preserved.
2977 return PreservedAnalyses::all();
2979 // Mark all the analyses that instcombine updates as preserved.
2980 // FIXME: Need a way to preserve CFG analyses here!
2981 PreservedAnalyses PA;
2982 PA.preserve<DominatorTreeAnalysis>();
2987 /// \brief The legacy pass manager's instcombine pass.
2989 /// This is a basic whole-function wrapper around the instcombine utility. It
2990 /// will try to combine all instructions in the function.
2991 class InstructionCombiningPass : public FunctionPass {
2992 InstCombineWorklist Worklist;
2995 static char ID; // Pass identification, replacement for typeid
2997 InstructionCombiningPass() : FunctionPass(ID) {
2998 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3001 void getAnalysisUsage(AnalysisUsage &AU) const override;
3002 bool runOnFunction(Function &F) override;
3006 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3007 AU.setPreservesCFG();
3008 AU.addRequired<AssumptionCacheTracker>();
3009 AU.addRequired<TargetLibraryInfoWrapperPass>();
3010 AU.addRequired<DominatorTreeWrapperPass>();
3011 AU.addPreserved<DominatorTreeWrapperPass>();
3014 bool InstructionCombiningPass::runOnFunction(Function &F) {
3015 if (skipOptnoneFunction(F))
3018 // Required analyses.
3019 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3020 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3021 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3023 // Optional analyses.
3024 auto *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3025 auto *DL = DLP ? &DLP->getDataLayout() : nullptr;
3026 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3027 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3029 return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI);
3032 char InstructionCombiningPass::ID = 0;
3033 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3034 "Combine redundant instructions", false, false)
3035 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3036 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3037 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3038 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3039 "Combine redundant instructions", false, false)
3041 // Initialization Routines
3042 void llvm::initializeInstCombine(PassRegistry &Registry) {
3043 initializeInstructionCombiningPassPass(Registry);
3046 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3047 initializeInstructionCombiningPassPass(*unwrap(R));
3050 FunctionPass *llvm::createInstructionCombiningPass() {
3051 return new InstructionCombiningPass();