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/LibCallSemantics.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/MemoryBuiltins.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/CFG.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/IR/ValueHandle.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Transforms/Utils/Local.h"
65 using namespace llvm::PatternMatch;
67 #define DEBUG_TYPE "instcombine"
69 STATISTIC(NumCombined , "Number of insts combined");
70 STATISTIC(NumConstProp, "Number of constant folds");
71 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
73 STATISTIC(NumExpand, "Number of expansions");
74 STATISTIC(NumFactor , "Number of factorizations");
75 STATISTIC(NumReassoc , "Number of reassociations");
77 Value *InstCombiner::EmitGEPOffset(User *GEP) {
78 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
81 /// ShouldChangeType - Return true if it is desirable to convert a computation
82 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
83 /// type for example, or from a smaller to a larger illegal type.
84 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
85 assert(From->isIntegerTy() && To->isIntegerTy());
87 // If we don't have DL, we don't know if the source/dest are legal.
88 if (!DL) return false;
90 unsigned FromWidth = From->getPrimitiveSizeInBits();
91 unsigned ToWidth = To->getPrimitiveSizeInBits();
92 bool FromLegal = DL->isLegalInteger(FromWidth);
93 bool ToLegal = DL->isLegalInteger(ToWidth);
95 // If this is a legal integer from type, and the result would be an illegal
96 // type, don't do the transformation.
97 if (FromLegal && !ToLegal)
100 // Otherwise, if both are illegal, do not increase the size of the result. We
101 // do allow things like i160 -> i64, but not i64 -> i160.
102 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
108 // Return true, if No Signed Wrap should be maintained for I.
109 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
110 // where both B and C should be ConstantInts, results in a constant that does
111 // not overflow. This function only handles the Add and Sub opcodes. For
112 // all other opcodes, the function conservatively returns false.
113 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
114 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
115 if (!OBO || !OBO->hasNoSignedWrap()) {
119 // We reason about Add and Sub Only.
120 Instruction::BinaryOps Opcode = I.getOpcode();
121 if (Opcode != Instruction::Add &&
122 Opcode != Instruction::Sub) {
126 ConstantInt *CB = dyn_cast<ConstantInt>(B);
127 ConstantInt *CC = dyn_cast<ConstantInt>(C);
133 const APInt &BVal = CB->getValue();
134 const APInt &CVal = CC->getValue();
135 bool Overflow = false;
137 if (Opcode == Instruction::Add) {
138 BVal.sadd_ov(CVal, Overflow);
140 BVal.ssub_ov(CVal, Overflow);
146 /// Conservatively clears subclassOptionalData after a reassociation or
147 /// commutation. We preserve fast-math flags when applicable as they can be
149 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
150 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
152 I.clearSubclassOptionalData();
156 FastMathFlags FMF = I.getFastMathFlags();
157 I.clearSubclassOptionalData();
158 I.setFastMathFlags(FMF);
161 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
162 /// operators which are associative or commutative:
164 // Commutative operators:
166 // 1. Order operands such that they are listed from right (least complex) to
167 // left (most complex). This puts constants before unary operators before
170 // Associative operators:
172 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
173 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
175 // Associative and commutative operators:
177 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
178 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
179 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
180 // if C1 and C2 are constants.
182 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
183 Instruction::BinaryOps Opcode = I.getOpcode();
184 bool Changed = false;
187 // Order operands such that they are listed from right (least complex) to
188 // left (most complex). This puts constants before unary operators before
190 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
191 getComplexity(I.getOperand(1)))
192 Changed = !I.swapOperands();
194 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
195 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
197 if (I.isAssociative()) {
198 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
199 if (Op0 && Op0->getOpcode() == Opcode) {
200 Value *A = Op0->getOperand(0);
201 Value *B = Op0->getOperand(1);
202 Value *C = I.getOperand(1);
204 // Does "B op C" simplify?
205 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
206 // It simplifies to V. Form "A op V".
209 // Conservatively clear the optional flags, since they may not be
210 // preserved by the reassociation.
211 if (MaintainNoSignedWrap(I, B, C) &&
212 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
213 // Note: this is only valid because SimplifyBinOp doesn't look at
214 // the operands to Op0.
215 I.clearSubclassOptionalData();
216 I.setHasNoSignedWrap(true);
218 ClearSubclassDataAfterReassociation(I);
227 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
228 if (Op1 && Op1->getOpcode() == Opcode) {
229 Value *A = I.getOperand(0);
230 Value *B = Op1->getOperand(0);
231 Value *C = Op1->getOperand(1);
233 // Does "A op B" simplify?
234 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
235 // It simplifies to V. Form "V op C".
238 // Conservatively clear the optional flags, since they may not be
239 // preserved by the reassociation.
240 ClearSubclassDataAfterReassociation(I);
248 if (I.isAssociative() && I.isCommutative()) {
249 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
250 if (Op0 && Op0->getOpcode() == Opcode) {
251 Value *A = Op0->getOperand(0);
252 Value *B = Op0->getOperand(1);
253 Value *C = I.getOperand(1);
255 // Does "C op A" simplify?
256 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
257 // It simplifies to V. Form "V op B".
260 // Conservatively clear the optional flags, since they may not be
261 // preserved by the reassociation.
262 ClearSubclassDataAfterReassociation(I);
269 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
270 if (Op1 && Op1->getOpcode() == Opcode) {
271 Value *A = I.getOperand(0);
272 Value *B = Op1->getOperand(0);
273 Value *C = Op1->getOperand(1);
275 // Does "C op A" simplify?
276 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
277 // It simplifies to V. Form "B op V".
280 // Conservatively clear the optional flags, since they may not be
281 // preserved by the reassociation.
282 ClearSubclassDataAfterReassociation(I);
289 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
290 // if C1 and C2 are constants.
292 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
293 isa<Constant>(Op0->getOperand(1)) &&
294 isa<Constant>(Op1->getOperand(1)) &&
295 Op0->hasOneUse() && Op1->hasOneUse()) {
296 Value *A = Op0->getOperand(0);
297 Constant *C1 = cast<Constant>(Op0->getOperand(1));
298 Value *B = Op1->getOperand(0);
299 Constant *C2 = cast<Constant>(Op1->getOperand(1));
301 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
302 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
303 if (isa<FPMathOperator>(New)) {
304 FastMathFlags Flags = I.getFastMathFlags();
305 Flags &= Op0->getFastMathFlags();
306 Flags &= Op1->getFastMathFlags();
307 New->setFastMathFlags(Flags);
309 InsertNewInstWith(New, I);
311 I.setOperand(0, New);
312 I.setOperand(1, Folded);
313 // Conservatively clear the optional flags, since they may not be
314 // preserved by the reassociation.
315 ClearSubclassDataAfterReassociation(I);
322 // No further simplifications.
327 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
328 /// "(X LOp Y) ROp (X LOp Z)".
329 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
330 Instruction::BinaryOps ROp) {
335 case Instruction::And:
336 // And distributes over Or and Xor.
340 case Instruction::Or:
341 case Instruction::Xor:
345 case Instruction::Mul:
346 // Multiplication distributes over addition and subtraction.
350 case Instruction::Add:
351 case Instruction::Sub:
355 case Instruction::Or:
356 // Or distributes over And.
360 case Instruction::And:
366 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
367 /// "(X ROp Z) LOp (Y ROp Z)".
368 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
369 Instruction::BinaryOps ROp) {
370 if (Instruction::isCommutative(ROp))
371 return LeftDistributesOverRight(ROp, LOp);
376 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
377 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
378 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
379 case Instruction::And:
380 case Instruction::Or:
381 case Instruction::Xor:
385 case Instruction::Shl:
386 case Instruction::LShr:
387 case Instruction::AShr:
391 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
392 // but this requires knowing that the addition does not overflow and other
397 /// This function returns identity value for given opcode, which can be used to
398 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
399 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
400 if (isa<Constant>(V))
403 if (OpCode == Instruction::Mul)
404 return ConstantInt::get(V->getType(), 1);
406 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
411 /// This function factors binary ops which can be combined using distributive
412 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
413 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
414 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
415 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
417 static Instruction::BinaryOps
418 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
419 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
421 return Instruction::BinaryOpsEnd;
423 LHS = Op->getOperand(0);
424 RHS = Op->getOperand(1);
426 switch (TopLevelOpcode) {
428 return Op->getOpcode();
430 case Instruction::Add:
431 case Instruction::Sub:
432 if (Op->getOpcode() == Instruction::Shl) {
433 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
434 // The multiplier is really 1 << CST.
435 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
436 return Instruction::Mul;
439 return Op->getOpcode();
442 // TODO: We can add other conversions e.g. shr => div etc.
445 /// This tries to simplify binary operations by factorizing out common terms
446 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
447 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
448 const DataLayout *DL, BinaryOperator &I,
449 Instruction::BinaryOps InnerOpcode, Value *A,
450 Value *B, Value *C, Value *D) {
452 // If any of A, B, C, D are null, we can not factor I, return early.
453 // Checking A and C should be enough.
454 if (!A || !C || !B || !D)
457 Value *SimplifiedInst = nullptr;
458 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
459 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
461 // Does "X op' Y" always equal "Y op' X"?
462 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
464 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
465 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
466 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
467 // commutative case, "(A op' B) op (C op' A)"?
468 if (A == C || (InnerCommutative && A == D)) {
471 // Consider forming "A op' (B op D)".
472 // If "B op D" simplifies then it can be formed with no cost.
473 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
474 // If "B op D" doesn't simplify then only go on if both of the existing
475 // operations "A op' B" and "C op' D" will be zapped as no longer used.
476 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
477 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
479 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
483 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
484 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
485 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
486 // commutative case, "(A op' B) op (B op' D)"?
487 if (B == D || (InnerCommutative && B == C)) {
490 // Consider forming "(A op C) op' B".
491 // If "A op C" simplifies then it can be formed with no cost.
492 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
494 // If "A op C" doesn't simplify then only go on if both of the existing
495 // operations "A op' B" and "C op' D" will be zapped as no longer used.
496 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
497 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
499 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
503 if (SimplifiedInst) {
505 SimplifiedInst->takeName(&I);
507 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
508 // TODO: Check for NUW.
509 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
510 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
512 if (isa<OverflowingBinaryOperator>(&I))
513 HasNSW = I.hasNoSignedWrap();
515 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
516 if (isa<OverflowingBinaryOperator>(Op0))
517 HasNSW &= Op0->hasNoSignedWrap();
519 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
520 if (isa<OverflowingBinaryOperator>(Op1))
521 HasNSW &= Op1->hasNoSignedWrap();
522 BO->setHasNoSignedWrap(HasNSW);
526 return SimplifiedInst;
529 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
530 /// which some other binary operation distributes over either by factorizing
531 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
532 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
533 /// a win). Returns the simplified value, or null if it didn't simplify.
534 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
535 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
536 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
537 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
540 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
541 auto TopLevelOpcode = I.getOpcode();
542 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
543 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
545 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
547 if (LHSOpcode == RHSOpcode) {
548 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
552 // The instruction has the form "(A op' B) op (C)". Try to factorize common
554 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
555 getIdentityValue(LHSOpcode, RHS)))
558 // The instruction has the form "(B) op (C op' D)". Try to factorize common
560 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
561 getIdentityValue(RHSOpcode, LHS), C, D))
565 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
566 // The instruction has the form "(A op' B) op C". See if expanding it out
567 // to "(A op C) op' (B op C)" results in simplifications.
568 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
569 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
571 // Do "A op C" and "B op C" both simplify?
572 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
573 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
574 // They do! Return "L op' R".
576 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
577 if ((L == A && R == B) ||
578 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
580 // Otherwise return "L op' R" if it simplifies.
581 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
583 // Otherwise, create a new instruction.
584 C = Builder->CreateBinOp(InnerOpcode, L, R);
590 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
591 // The instruction has the form "A op (B op' C)". See if expanding it out
592 // to "(A op B) op' (A op C)" results in simplifications.
593 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
594 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
596 // Do "A op B" and "A op C" both simplify?
597 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
598 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
599 // They do! Return "L op' R".
601 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
602 if ((L == B && R == C) ||
603 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
605 // Otherwise return "L op' R" if it simplifies.
606 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
608 // Otherwise, create a new instruction.
609 A = Builder->CreateBinOp(InnerOpcode, L, R);
618 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
619 // if the LHS is a constant zero (which is the 'negate' form).
621 Value *InstCombiner::dyn_castNegVal(Value *V) const {
622 if (BinaryOperator::isNeg(V))
623 return BinaryOperator::getNegArgument(V);
625 // Constants can be considered to be negated values if they can be folded.
626 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
627 return ConstantExpr::getNeg(C);
629 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
630 if (C->getType()->getElementType()->isIntegerTy())
631 return ConstantExpr::getNeg(C);
636 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
637 // instruction if the LHS is a constant negative zero (which is the 'negate'
640 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
641 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
642 return BinaryOperator::getFNegArgument(V);
644 // Constants can be considered to be negated values if they can be folded.
645 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
646 return ConstantExpr::getFNeg(C);
648 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
649 if (C->getType()->getElementType()->isFloatingPointTy())
650 return ConstantExpr::getFNeg(C);
655 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
657 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
658 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
661 // Figure out if the constant is the left or the right argument.
662 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
663 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
665 if (Constant *SOC = dyn_cast<Constant>(SO)) {
667 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
668 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
671 Value *Op0 = SO, *Op1 = ConstOperand;
675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
676 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
677 SO->getName()+".op");
678 Instruction *FPInst = dyn_cast<Instruction>(RI);
679 if (FPInst && isa<FPMathOperator>(FPInst))
680 FPInst->copyFastMathFlags(BO);
683 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
684 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
685 SO->getName()+".cmp");
686 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
687 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
688 SO->getName()+".cmp");
689 llvm_unreachable("Unknown binary instruction type!");
692 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
693 // constant as the other operand, try to fold the binary operator into the
694 // select arguments. This also works for Cast instructions, which obviously do
695 // not have a second operand.
696 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
697 // Don't modify shared select instructions
698 if (!SI->hasOneUse()) return nullptr;
699 Value *TV = SI->getOperand(1);
700 Value *FV = SI->getOperand(2);
702 if (isa<Constant>(TV) || isa<Constant>(FV)) {
703 // Bool selects with constant operands can be folded to logical ops.
704 if (SI->getType()->isIntegerTy(1)) return nullptr;
706 // If it's a bitcast involving vectors, make sure it has the same number of
707 // elements on both sides.
708 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
709 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
710 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
712 // Verify that either both or neither are vectors.
713 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
714 // If vectors, verify that they have the same number of elements.
715 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
719 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
720 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
722 return SelectInst::Create(SI->getCondition(),
723 SelectTrueVal, SelectFalseVal);
729 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
730 /// has a PHI node as operand #0, see if we can fold the instruction into the
731 /// PHI (which is only possible if all operands to the PHI are constants).
733 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
734 PHINode *PN = cast<PHINode>(I.getOperand(0));
735 unsigned NumPHIValues = PN->getNumIncomingValues();
736 if (NumPHIValues == 0)
739 // We normally only transform phis with a single use. However, if a PHI has
740 // multiple uses and they are all the same operation, we can fold *all* of the
741 // uses into the PHI.
742 if (!PN->hasOneUse()) {
743 // Walk the use list for the instruction, comparing them to I.
744 for (User *U : PN->users()) {
745 Instruction *UI = cast<Instruction>(U);
746 if (UI != &I && !I.isIdenticalTo(UI))
749 // Otherwise, we can replace *all* users with the new PHI we form.
752 // Check to see if all of the operands of the PHI are simple constants
753 // (constantint/constantfp/undef). If there is one non-constant value,
754 // remember the BB it is in. If there is more than one or if *it* is a PHI,
755 // bail out. We don't do arbitrary constant expressions here because moving
756 // their computation can be expensive without a cost model.
757 BasicBlock *NonConstBB = nullptr;
758 for (unsigned i = 0; i != NumPHIValues; ++i) {
759 Value *InVal = PN->getIncomingValue(i);
760 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
763 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
764 if (NonConstBB) return nullptr; // More than one non-const value.
766 NonConstBB = PN->getIncomingBlock(i);
768 // If the InVal is an invoke at the end of the pred block, then we can't
769 // insert a computation after it without breaking the edge.
770 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
771 if (II->getParent() == NonConstBB)
774 // If the incoming non-constant value is in I's block, we will remove one
775 // instruction, but insert another equivalent one, leading to infinite
777 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
781 // If there is exactly one non-constant value, we can insert a copy of the
782 // operation in that block. However, if this is a critical edge, we would be
783 // inserting the computation on some other paths (e.g. inside a loop). Only
784 // do this if the pred block is unconditionally branching into the phi block.
785 if (NonConstBB != nullptr) {
786 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
787 if (!BI || !BI->isUnconditional()) return nullptr;
790 // Okay, we can do the transformation: create the new PHI node.
791 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
792 InsertNewInstBefore(NewPN, *PN);
795 // If we are going to have to insert a new computation, do so right before the
796 // predecessors terminator.
798 Builder->SetInsertPoint(NonConstBB->getTerminator());
800 // Next, add all of the operands to the PHI.
801 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
802 // We only currently try to fold the condition of a select when it is a phi,
803 // not the true/false values.
804 Value *TrueV = SI->getTrueValue();
805 Value *FalseV = SI->getFalseValue();
806 BasicBlock *PhiTransBB = PN->getParent();
807 for (unsigned i = 0; i != NumPHIValues; ++i) {
808 BasicBlock *ThisBB = PN->getIncomingBlock(i);
809 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
810 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
811 Value *InV = nullptr;
812 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
813 // even if currently isNullValue gives false.
814 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
815 if (InC && !isa<ConstantExpr>(InC))
816 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
818 InV = Builder->CreateSelect(PN->getIncomingValue(i),
819 TrueVInPred, FalseVInPred, "phitmp");
820 NewPN->addIncoming(InV, ThisBB);
822 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
823 Constant *C = cast<Constant>(I.getOperand(1));
824 for (unsigned i = 0; i != NumPHIValues; ++i) {
825 Value *InV = nullptr;
826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
827 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
828 else if (isa<ICmpInst>(CI))
829 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
832 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
834 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
836 } else if (I.getNumOperands() == 2) {
837 Constant *C = cast<Constant>(I.getOperand(1));
838 for (unsigned i = 0; i != NumPHIValues; ++i) {
839 Value *InV = nullptr;
840 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
841 InV = ConstantExpr::get(I.getOpcode(), InC, C);
843 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
844 PN->getIncomingValue(i), C, "phitmp");
845 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
848 CastInst *CI = cast<CastInst>(&I);
849 Type *RetTy = CI->getType();
850 for (unsigned i = 0; i != NumPHIValues; ++i) {
852 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
853 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
855 InV = Builder->CreateCast(CI->getOpcode(),
856 PN->getIncomingValue(i), I.getType(), "phitmp");
857 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
861 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
862 Instruction *User = cast<Instruction>(*UI++);
863 if (User == &I) continue;
864 ReplaceInstUsesWith(*User, NewPN);
865 EraseInstFromFunction(*User);
867 return ReplaceInstUsesWith(I, NewPN);
870 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
871 /// whether or not there is a sequence of GEP indices into the pointed type that
872 /// will land us at the specified offset. If so, fill them into NewIndices and
873 /// return the resultant element type, otherwise return null.
874 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
875 SmallVectorImpl<Value*> &NewIndices) {
876 assert(PtrTy->isPtrOrPtrVectorTy());
881 Type *Ty = PtrTy->getPointerElementType();
885 // Start with the index over the outer type. Note that the type size
886 // might be zero (even if the offset isn't zero) if the indexed type
887 // is something like [0 x {int, int}]
888 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
889 int64_t FirstIdx = 0;
890 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
891 FirstIdx = Offset/TySize;
892 Offset -= FirstIdx*TySize;
894 // Handle hosts where % returns negative instead of values [0..TySize).
900 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
903 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
905 // Index into the types. If we fail, set OrigBase to null.
907 // Indexing into tail padding between struct/array elements.
908 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
911 if (StructType *STy = dyn_cast<StructType>(Ty)) {
912 const StructLayout *SL = DL->getStructLayout(STy);
913 assert(Offset < (int64_t)SL->getSizeInBytes() &&
914 "Offset must stay within the indexed type");
916 unsigned Elt = SL->getElementContainingOffset(Offset);
917 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
920 Offset -= SL->getElementOffset(Elt);
921 Ty = STy->getElementType(Elt);
922 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
923 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
924 assert(EltSize && "Cannot index into a zero-sized array");
925 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
927 Ty = AT->getElementType();
929 // Otherwise, we can't index into the middle of this atomic type, bail.
937 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
938 // If this GEP has only 0 indices, it is the same pointer as
939 // Src. If Src is not a trivial GEP too, don't combine
941 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
947 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
948 /// the multiplication is known not to overflow then NoSignedWrap is set.
949 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
950 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
951 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
952 Scale.getBitWidth() && "Scale not compatible with value!");
954 // If Val is zero or Scale is one then Val = Val * Scale.
955 if (match(Val, m_Zero()) || Scale == 1) {
960 // If Scale is zero then it does not divide Val.
961 if (Scale.isMinValue())
964 // Look through chains of multiplications, searching for a constant that is
965 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
966 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
967 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
970 // Val = M1 * X || Analysis starts here and works down
971 // M1 = M2 * Y || Doesn't descend into terms with more
972 // M2 = Z * 4 \/ than one use
974 // Then to modify a term at the bottom:
977 // M1 = Z * Y || Replaced M2 with Z
979 // Then to work back up correcting nsw flags.
981 // Op - the term we are currently analyzing. Starts at Val then drills down.
982 // Replaced with its descaled value before exiting from the drill down loop.
985 // Parent - initially null, but after drilling down notes where Op came from.
986 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
987 // 0'th operand of Val.
988 std::pair<Instruction*, unsigned> Parent;
990 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
991 // levels that doesn't overflow.
992 bool RequireNoSignedWrap = false;
994 // logScale - log base 2 of the scale. Negative if not a power of 2.
995 int32_t logScale = Scale.exactLogBase2();
997 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
999 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1000 // If Op is a constant divisible by Scale then descale to the quotient.
1001 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1002 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1003 if (!Remainder.isMinValue())
1004 // Not divisible by Scale.
1006 // Replace with the quotient in the parent.
1007 Op = ConstantInt::get(CI->getType(), Quotient);
1008 NoSignedWrap = true;
1012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1014 if (BO->getOpcode() == Instruction::Mul) {
1016 NoSignedWrap = BO->hasNoSignedWrap();
1017 if (RequireNoSignedWrap && !NoSignedWrap)
1020 // There are three cases for multiplication: multiplication by exactly
1021 // the scale, multiplication by a constant different to the scale, and
1022 // multiplication by something else.
1023 Value *LHS = BO->getOperand(0);
1024 Value *RHS = BO->getOperand(1);
1026 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1027 // Multiplication by a constant.
1028 if (CI->getValue() == Scale) {
1029 // Multiplication by exactly the scale, replace the multiplication
1030 // by its left-hand side in the parent.
1035 // Otherwise drill down into the constant.
1036 if (!Op->hasOneUse())
1039 Parent = std::make_pair(BO, 1);
1043 // Multiplication by something else. Drill down into the left-hand side
1044 // since that's where the reassociate pass puts the good stuff.
1045 if (!Op->hasOneUse())
1048 Parent = std::make_pair(BO, 0);
1052 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1053 isa<ConstantInt>(BO->getOperand(1))) {
1054 // Multiplication by a power of 2.
1055 NoSignedWrap = BO->hasNoSignedWrap();
1056 if (RequireNoSignedWrap && !NoSignedWrap)
1059 Value *LHS = BO->getOperand(0);
1060 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1061 getLimitedValue(Scale.getBitWidth());
1064 if (Amt == logScale) {
1065 // Multiplication by exactly the scale, replace the multiplication
1066 // by its left-hand side in the parent.
1070 if (Amt < logScale || !Op->hasOneUse())
1073 // Multiplication by more than the scale. Reduce the multiplying amount
1074 // by the scale in the parent.
1075 Parent = std::make_pair(BO, 1);
1076 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1081 if (!Op->hasOneUse())
1084 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1085 if (Cast->getOpcode() == Instruction::SExt) {
1086 // Op is sign-extended from a smaller type, descale in the smaller type.
1087 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1088 APInt SmallScale = Scale.trunc(SmallSize);
1089 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1090 // descale Op as (sext Y) * Scale. In order to have
1091 // sext (Y * SmallScale) = (sext Y) * Scale
1092 // some conditions need to hold however: SmallScale must sign-extend to
1093 // Scale and the multiplication Y * SmallScale should not overflow.
1094 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1095 // SmallScale does not sign-extend to Scale.
1097 assert(SmallScale.exactLogBase2() == logScale);
1098 // Require that Y * SmallScale must not overflow.
1099 RequireNoSignedWrap = true;
1101 // Drill down through the cast.
1102 Parent = std::make_pair(Cast, 0);
1107 if (Cast->getOpcode() == Instruction::Trunc) {
1108 // Op is truncated from a larger type, descale in the larger type.
1109 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1110 // trunc (Y * sext Scale) = (trunc Y) * Scale
1111 // always holds. However (trunc Y) * Scale may overflow even if
1112 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1113 // from this point up in the expression (see later).
1114 if (RequireNoSignedWrap)
1117 // Drill down through the cast.
1118 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1119 Parent = std::make_pair(Cast, 0);
1120 Scale = Scale.sext(LargeSize);
1121 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1123 assert(Scale.exactLogBase2() == logScale);
1128 // Unsupported expression, bail out.
1132 // If Op is zero then Val = Op * Scale.
1133 if (match(Op, m_Zero())) {
1134 NoSignedWrap = true;
1138 // We know that we can successfully descale, so from here on we can safely
1139 // modify the IR. Op holds the descaled version of the deepest term in the
1140 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1144 // The expression only had one term.
1147 // Rewrite the parent using the descaled version of its operand.
1148 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1149 assert(Op != Parent.first->getOperand(Parent.second) &&
1150 "Descaling was a no-op?");
1151 Parent.first->setOperand(Parent.second, Op);
1152 Worklist.Add(Parent.first);
1154 // Now work back up the expression correcting nsw flags. The logic is based
1155 // on the following observation: if X * Y is known not to overflow as a signed
1156 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1157 // then X * Z will not overflow as a signed multiplication either. As we work
1158 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1159 // current level has strictly smaller absolute value than the original.
1160 Instruction *Ancestor = Parent.first;
1162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1163 // If the multiplication wasn't nsw then we can't say anything about the
1164 // value of the descaled multiplication, and we have to clear nsw flags
1165 // from this point on up.
1166 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1167 NoSignedWrap &= OpNoSignedWrap;
1168 if (NoSignedWrap != OpNoSignedWrap) {
1169 BO->setHasNoSignedWrap(NoSignedWrap);
1170 Worklist.Add(Ancestor);
1172 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1173 // The fact that the descaled input to the trunc has smaller absolute
1174 // value than the original input doesn't tell us anything useful about
1175 // the absolute values of the truncations.
1176 NoSignedWrap = false;
1178 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1179 "Failed to keep proper track of nsw flags while drilling down?");
1181 if (Ancestor == Val)
1182 // Got to the top, all done!
1185 // Move up one level in the expression.
1186 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1187 Ancestor = Ancestor->user_back();
1191 /// \brief Creates node of binary operation with the same attributes as the
1192 /// specified one but with other operands.
1193 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1194 InstCombiner::BuilderTy *B) {
1195 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1196 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1197 if (isa<OverflowingBinaryOperator>(NewBO)) {
1198 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1199 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1201 if (isa<PossiblyExactOperator>(NewBO))
1202 NewBO->setIsExact(Inst.isExact());
1207 /// \brief Makes transformation of binary operation specific for vector types.
1208 /// \param Inst Binary operator to transform.
1209 /// \return Pointer to node that must replace the original binary operator, or
1210 /// null pointer if no transformation was made.
1211 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1212 if (!Inst.getType()->isVectorTy()) return nullptr;
1214 // It may not be safe to reorder shuffles and things like div, urem, etc.
1215 // because we may trap when executing those ops on unknown vector elements.
1217 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1219 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1220 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1221 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1222 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1224 // If both arguments of binary operation are shuffles, which use the same
1225 // mask and shuffle within a single vector, it is worthwhile to move the
1226 // shuffle after binary operation:
1227 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1228 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1229 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1230 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1231 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1232 isa<UndefValue>(RShuf->getOperand(1)) &&
1233 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1234 LShuf->getMask() == RShuf->getMask()) {
1235 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1236 RShuf->getOperand(0), Builder);
1237 Value *Res = Builder->CreateShuffleVector(NewBO,
1238 UndefValue::get(NewBO->getType()), LShuf->getMask());
1243 // If one argument is a shuffle within one vector, the other is a constant,
1244 // try moving the shuffle after the binary operation.
1245 ShuffleVectorInst *Shuffle = nullptr;
1246 Constant *C1 = nullptr;
1247 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1248 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1249 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1250 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1251 if (Shuffle && C1 &&
1252 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1253 isa<UndefValue>(Shuffle->getOperand(1)) &&
1254 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1255 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1256 // Find constant C2 that has property:
1257 // shuffle(C2, ShMask) = C1
1258 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1259 // reorder is not possible.
1260 SmallVector<Constant*, 16> C2M(VWidth,
1261 UndefValue::get(C1->getType()->getScalarType()));
1262 bool MayChange = true;
1263 for (unsigned I = 0; I < VWidth; ++I) {
1264 if (ShMask[I] >= 0) {
1265 assert(ShMask[I] < (int)VWidth);
1266 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1270 C2M[ShMask[I]] = C1->getAggregateElement(I);
1274 Constant *C2 = ConstantVector::get(C2M);
1275 Value *NewLHS, *NewRHS;
1276 if (isa<Constant>(LHS)) {
1278 NewRHS = Shuffle->getOperand(0);
1280 NewLHS = Shuffle->getOperand(0);
1283 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1284 Value *Res = Builder->CreateShuffleVector(NewBO,
1285 UndefValue::get(Inst.getType()), Shuffle->getMask());
1293 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1294 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1296 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1297 return ReplaceInstUsesWith(GEP, V);
1299 Value *PtrOp = GEP.getOperand(0);
1301 // Eliminate unneeded casts for indices, and replace indices which displace
1302 // by multiples of a zero size type with zero.
1304 bool MadeChange = false;
1305 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1307 gep_type_iterator GTI = gep_type_begin(GEP);
1308 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1309 I != E; ++I, ++GTI) {
1310 // Skip indices into struct types.
1311 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1312 if (!SeqTy) continue;
1314 // If the element type has zero size then any index over it is equivalent
1315 // to an index of zero, so replace it with zero if it is not zero already.
1316 if (SeqTy->getElementType()->isSized() &&
1317 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1318 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1319 *I = Constant::getNullValue(IntPtrTy);
1323 Type *IndexTy = (*I)->getType();
1324 if (IndexTy != IntPtrTy) {
1325 // If we are using a wider index than needed for this platform, shrink
1326 // it to what we need. If narrower, sign-extend it to what we need.
1327 // This explicit cast can make subsequent optimizations more obvious.
1328 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1332 if (MadeChange) return &GEP;
1335 // Check to see if the inputs to the PHI node are getelementptr instructions.
1336 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1337 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1343 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1344 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1345 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1348 // Keep track of the type as we walk the GEP.
1349 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1351 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1352 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1355 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1357 // We have not seen any differences yet in the GEPs feeding the
1358 // PHI yet, so we record this one if it is allowed to be a
1361 // The first two arguments can vary for any GEP, the rest have to be
1362 // static for struct slots
1363 if (J > 1 && CurTy->isStructTy())
1368 // The GEP is different by more than one input. While this could be
1369 // extended to support GEPs that vary by more than one variable it
1370 // doesn't make sense since it greatly increases the complexity and
1371 // would result in an R+R+R addressing mode which no backend
1372 // directly supports and would need to be broken into several
1373 // simpler instructions anyway.
1378 // Sink down a layer of the type for the next iteration.
1380 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1381 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1389 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1392 // All the GEPs feeding the PHI are identical. Clone one down into our
1393 // BB so that it can be merged with the current GEP.
1394 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1397 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1398 // into the current block so it can be merged, and create a new PHI to
1400 Instruction *InsertPt = Builder->GetInsertPoint();
1401 Builder->SetInsertPoint(PN);
1402 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1403 PN->getNumOperands());
1404 Builder->SetInsertPoint(InsertPt);
1406 for (auto &I : PN->operands())
1407 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1408 PN->getIncomingBlock(I));
1410 NewGEP->setOperand(DI, NewPN);
1411 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1413 NewGEP->setOperand(DI, NewPN);
1416 GEP.setOperand(0, NewGEP);
1420 // Combine Indices - If the source pointer to this getelementptr instruction
1421 // is a getelementptr instruction, combine the indices of the two
1422 // getelementptr instructions into a single instruction.
1424 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1425 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1428 // Note that if our source is a gep chain itself then we wait for that
1429 // chain to be resolved before we perform this transformation. This
1430 // avoids us creating a TON of code in some cases.
1431 if (GEPOperator *SrcGEP =
1432 dyn_cast<GEPOperator>(Src->getOperand(0)))
1433 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1434 return nullptr; // Wait until our source is folded to completion.
1436 SmallVector<Value*, 8> Indices;
1438 // Find out whether the last index in the source GEP is a sequential idx.
1439 bool EndsWithSequential = false;
1440 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1442 EndsWithSequential = !(*I)->isStructTy();
1444 // Can we combine the two pointer arithmetics offsets?
1445 if (EndsWithSequential) {
1446 // Replace: gep (gep %P, long B), long A, ...
1447 // With: T = long A+B; gep %P, T, ...
1450 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1451 Value *GO1 = GEP.getOperand(1);
1452 if (SO1 == Constant::getNullValue(SO1->getType())) {
1454 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1457 // If they aren't the same type, then the input hasn't been processed
1458 // by the loop above yet (which canonicalizes sequential index types to
1459 // intptr_t). Just avoid transforming this until the input has been
1461 if (SO1->getType() != GO1->getType())
1463 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1466 // Update the GEP in place if possible.
1467 if (Src->getNumOperands() == 2) {
1468 GEP.setOperand(0, Src->getOperand(0));
1469 GEP.setOperand(1, Sum);
1472 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1473 Indices.push_back(Sum);
1474 Indices.append(GEP.op_begin()+2, GEP.op_end());
1475 } else if (isa<Constant>(*GEP.idx_begin()) &&
1476 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1477 Src->getNumOperands() != 1) {
1478 // Otherwise we can do the fold if the first index of the GEP is a zero
1479 Indices.append(Src->op_begin()+1, Src->op_end());
1480 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1483 if (!Indices.empty())
1484 return (GEP.isInBounds() && Src->isInBounds()) ?
1485 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1487 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1490 if (DL && GEP.getNumIndices() == 1) {
1491 unsigned AS = GEP.getPointerAddressSpace();
1492 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1493 DL->getPointerSizeInBits(AS)) {
1494 Type *PtrTy = GEP.getPointerOperandType();
1495 Type *Ty = PtrTy->getPointerElementType();
1496 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1498 bool Matched = false;
1501 if (TyAllocSize == 1) {
1502 V = GEP.getOperand(1);
1504 } else if (match(GEP.getOperand(1),
1505 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1506 if (TyAllocSize == 1ULL << C)
1508 } else if (match(GEP.getOperand(1),
1509 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1510 if (TyAllocSize == C)
1515 // Canonicalize (gep i8* X, -(ptrtoint Y))
1516 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1517 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1518 // pointer arithmetic.
1519 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1520 Operator *Index = cast<Operator>(V);
1521 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1522 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1523 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1525 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1528 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1529 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1530 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1537 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1538 Value *StrippedPtr = PtrOp->stripPointerCasts();
1539 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1541 // We do not handle pointer-vector geps here.
1545 if (StrippedPtr != PtrOp) {
1546 bool HasZeroPointerIndex = false;
1547 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1548 HasZeroPointerIndex = C->isZero();
1550 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1551 // into : GEP [10 x i8]* X, i32 0, ...
1553 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1554 // into : GEP i8* X, ...
1556 // This occurs when the program declares an array extern like "int X[];"
1557 if (HasZeroPointerIndex) {
1558 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1559 if (ArrayType *CATy =
1560 dyn_cast<ArrayType>(CPTy->getElementType())) {
1561 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1562 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1563 // -> GEP i8* X, ...
1564 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1565 GetElementPtrInst *Res =
1566 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1567 Res->setIsInBounds(GEP.isInBounds());
1568 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1570 // Insert Res, and create an addrspacecast.
1572 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1574 // %0 = GEP i8 addrspace(1)* X, ...
1575 // addrspacecast i8 addrspace(1)* %0 to i8*
1576 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1579 if (ArrayType *XATy =
1580 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1581 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1582 if (CATy->getElementType() == XATy->getElementType()) {
1583 // -> GEP [10 x i8]* X, i32 0, ...
1584 // At this point, we know that the cast source type is a pointer
1585 // to an array of the same type as the destination pointer
1586 // array. Because the array type is never stepped over (there
1587 // is a leading zero) we can fold the cast into this GEP.
1588 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1589 GEP.setOperand(0, StrippedPtr);
1592 // Cannot replace the base pointer directly because StrippedPtr's
1593 // address space is different. Instead, create a new GEP followed by
1594 // an addrspacecast.
1596 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1599 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1600 // addrspacecast i8 addrspace(1)* %0 to i8*
1601 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1602 Value *NewGEP = GEP.isInBounds() ?
1603 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1604 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1605 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1609 } else if (GEP.getNumOperands() == 2) {
1610 // Transform things like:
1611 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1612 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1613 Type *SrcElTy = StrippedPtrTy->getElementType();
1614 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1615 if (DL && SrcElTy->isArrayTy() &&
1616 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1617 DL->getTypeAllocSize(ResElTy)) {
1618 Type *IdxType = DL->getIntPtrType(GEP.getType());
1619 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1620 Value *NewGEP = GEP.isInBounds() ?
1621 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1622 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1624 // V and GEP are both pointer types --> BitCast
1625 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1629 // Transform things like:
1630 // %V = mul i64 %N, 4
1631 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1632 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1633 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1634 // Check that changing the type amounts to dividing the index by a scale
1636 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1637 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1638 if (ResSize && SrcSize % ResSize == 0) {
1639 Value *Idx = GEP.getOperand(1);
1640 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1641 uint64_t Scale = SrcSize / ResSize;
1643 // Earlier transforms ensure that the index has type IntPtrType, which
1644 // considerably simplifies the logic by eliminating implicit casts.
1645 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1646 "Index not cast to pointer width?");
1649 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1650 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1651 // If the multiplication NewIdx * Scale may overflow then the new
1652 // GEP may not be "inbounds".
1653 Value *NewGEP = GEP.isInBounds() && NSW ?
1654 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1655 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1657 // The NewGEP must be pointer typed, so must the old one -> BitCast
1658 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1664 // Similarly, transform things like:
1665 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1666 // (where tmp = 8*tmp2) into:
1667 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1668 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1669 SrcElTy->isArrayTy()) {
1670 // Check that changing to the array element type amounts to dividing the
1671 // index by a scale factor.
1672 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1673 uint64_t ArrayEltSize
1674 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1675 if (ResSize && ArrayEltSize % ResSize == 0) {
1676 Value *Idx = GEP.getOperand(1);
1677 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1678 uint64_t Scale = ArrayEltSize / ResSize;
1680 // Earlier transforms ensure that the index has type IntPtrType, which
1681 // considerably simplifies the logic by eliminating implicit casts.
1682 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1683 "Index not cast to pointer width?");
1686 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1687 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1688 // If the multiplication NewIdx * Scale may overflow then the new
1689 // GEP may not be "inbounds".
1691 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1695 Value *NewGEP = GEP.isInBounds() && NSW ?
1696 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1697 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1698 // The NewGEP must be pointer typed, so must the old one -> BitCast
1699 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1710 // addrspacecast between types is canonicalized as a bitcast, then an
1711 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1712 // through the addrspacecast.
1713 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1714 // X = bitcast A addrspace(1)* to B addrspace(1)*
1715 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1716 // Z = gep Y, <...constant indices...>
1717 // Into an addrspacecasted GEP of the struct.
1718 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1722 /// See if we can simplify:
1723 /// X = bitcast A* to B*
1724 /// Y = gep X, <...constant indices...>
1725 /// into a gep of the original struct. This is important for SROA and alias
1726 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1727 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1728 Value *Operand = BCI->getOperand(0);
1729 PointerType *OpType = cast<PointerType>(Operand->getType());
1730 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1731 APInt Offset(OffsetBits, 0);
1732 if (!isa<BitCastInst>(Operand) &&
1733 GEP.accumulateConstantOffset(*DL, Offset)) {
1735 // If this GEP instruction doesn't move the pointer, just replace the GEP
1736 // with a bitcast of the real input to the dest type.
1738 // If the bitcast is of an allocation, and the allocation will be
1739 // converted to match the type of the cast, don't touch this.
1740 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1741 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1742 if (Instruction *I = visitBitCast(*BCI)) {
1745 BCI->getParent()->getInstList().insert(BCI, I);
1746 ReplaceInstUsesWith(*BCI, I);
1752 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1753 return new AddrSpaceCastInst(Operand, GEP.getType());
1754 return new BitCastInst(Operand, GEP.getType());
1757 // Otherwise, if the offset is non-zero, we need to find out if there is a
1758 // field at Offset in 'A's type. If so, we can pull the cast through the
1760 SmallVector<Value*, 8> NewIndices;
1761 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1762 Value *NGEP = GEP.isInBounds() ?
1763 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1764 Builder->CreateGEP(Operand, NewIndices);
1766 if (NGEP->getType() == GEP.getType())
1767 return ReplaceInstUsesWith(GEP, NGEP);
1768 NGEP->takeName(&GEP);
1770 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1771 return new AddrSpaceCastInst(NGEP, GEP.getType());
1772 return new BitCastInst(NGEP, GEP.getType());
1781 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1782 const TargetLibraryInfo *TLI) {
1783 SmallVector<Instruction*, 4> Worklist;
1784 Worklist.push_back(AI);
1787 Instruction *PI = Worklist.pop_back_val();
1788 for (User *U : PI->users()) {
1789 Instruction *I = cast<Instruction>(U);
1790 switch (I->getOpcode()) {
1792 // Give up the moment we see something we can't handle.
1795 case Instruction::BitCast:
1796 case Instruction::GetElementPtr:
1798 Worklist.push_back(I);
1801 case Instruction::ICmp: {
1802 ICmpInst *ICI = cast<ICmpInst>(I);
1803 // We can fold eq/ne comparisons with null to false/true, respectively.
1804 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1810 case Instruction::Call:
1811 // Ignore no-op and store intrinsics.
1812 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1813 switch (II->getIntrinsicID()) {
1817 case Intrinsic::memmove:
1818 case Intrinsic::memcpy:
1819 case Intrinsic::memset: {
1820 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1821 if (MI->isVolatile() || MI->getRawDest() != PI)
1825 case Intrinsic::dbg_declare:
1826 case Intrinsic::dbg_value:
1827 case Intrinsic::invariant_start:
1828 case Intrinsic::invariant_end:
1829 case Intrinsic::lifetime_start:
1830 case Intrinsic::lifetime_end:
1831 case Intrinsic::objectsize:
1837 if (isFreeCall(I, TLI)) {
1843 case Instruction::Store: {
1844 StoreInst *SI = cast<StoreInst>(I);
1845 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1851 llvm_unreachable("missing a return?");
1853 } while (!Worklist.empty());
1857 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1858 // If we have a malloc call which is only used in any amount of comparisons
1859 // to null and free calls, delete the calls and replace the comparisons with
1860 // true or false as appropriate.
1861 SmallVector<WeakVH, 64> Users;
1862 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1863 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1864 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1867 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1868 ReplaceInstUsesWith(*C,
1869 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1870 C->isFalseWhenEqual()));
1871 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1872 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1873 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1874 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1875 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1876 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1877 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1880 EraseInstFromFunction(*I);
1883 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1884 // Replace invoke with a NOP intrinsic to maintain the original CFG
1885 Module *M = II->getParent()->getParent()->getParent();
1886 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1887 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1888 None, "", II->getParent());
1890 return EraseInstFromFunction(MI);
1895 /// \brief Move the call to free before a NULL test.
1897 /// Check if this free is accessed after its argument has been test
1898 /// against NULL (property 0).
1899 /// If yes, it is legal to move this call in its predecessor block.
1901 /// The move is performed only if the block containing the call to free
1902 /// will be removed, i.e.:
1903 /// 1. it has only one predecessor P, and P has two successors
1904 /// 2. it contains the call and an unconditional branch
1905 /// 3. its successor is the same as its predecessor's successor
1907 /// The profitability is out-of concern here and this function should
1908 /// be called only if the caller knows this transformation would be
1909 /// profitable (e.g., for code size).
1910 static Instruction *
1911 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1912 Value *Op = FI.getArgOperand(0);
1913 BasicBlock *FreeInstrBB = FI.getParent();
1914 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1916 // Validate part of constraint #1: Only one predecessor
1917 // FIXME: We can extend the number of predecessor, but in that case, we
1918 // would duplicate the call to free in each predecessor and it may
1919 // not be profitable even for code size.
1923 // Validate constraint #2: Does this block contains only the call to
1924 // free and an unconditional branch?
1925 // FIXME: We could check if we can speculate everything in the
1926 // predecessor block
1927 if (FreeInstrBB->size() != 2)
1930 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1933 // Validate the rest of constraint #1 by matching on the pred branch.
1934 TerminatorInst *TI = PredBB->getTerminator();
1935 BasicBlock *TrueBB, *FalseBB;
1936 ICmpInst::Predicate Pred;
1937 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1939 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1942 // Validate constraint #3: Ensure the null case just falls through.
1943 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1945 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1946 "Broken CFG: missing edge from predecessor to successor");
1953 Instruction *InstCombiner::visitFree(CallInst &FI) {
1954 Value *Op = FI.getArgOperand(0);
1956 // free undef -> unreachable.
1957 if (isa<UndefValue>(Op)) {
1958 // Insert a new store to null because we cannot modify the CFG here.
1959 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1960 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1961 return EraseInstFromFunction(FI);
1964 // If we have 'free null' delete the instruction. This can happen in stl code
1965 // when lots of inlining happens.
1966 if (isa<ConstantPointerNull>(Op))
1967 return EraseInstFromFunction(FI);
1969 // If we optimize for code size, try to move the call to free before the null
1970 // test so that simplify cfg can remove the empty block and dead code
1971 // elimination the branch. I.e., helps to turn something like:
1972 // if (foo) free(foo);
1976 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1982 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
1983 if (RI.getNumOperands() == 0) // ret void
1986 Value *ResultOp = RI.getOperand(0);
1987 Type *VTy = ResultOp->getType();
1988 if (!VTy->isIntegerTy())
1991 // There might be assume intrinsics dominating this return that completely
1992 // determine the value. If so, constant fold it.
1993 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1994 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1995 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
1996 if ((KnownZero|KnownOne).isAllOnesValue())
1997 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2002 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2003 // Change br (not X), label True, label False to: br X, label False, True
2005 BasicBlock *TrueDest;
2006 BasicBlock *FalseDest;
2007 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2008 !isa<Constant>(X)) {
2009 // Swap Destinations and condition...
2011 BI.swapSuccessors();
2015 // Canonicalize fcmp_one -> fcmp_oeq
2016 FCmpInst::Predicate FPred; Value *Y;
2017 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2018 TrueDest, FalseDest)) &&
2019 BI.getCondition()->hasOneUse())
2020 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2021 FPred == FCmpInst::FCMP_OGE) {
2022 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2023 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2025 // Swap Destinations and condition.
2026 BI.swapSuccessors();
2031 // Canonicalize icmp_ne -> icmp_eq
2032 ICmpInst::Predicate IPred;
2033 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2034 TrueDest, FalseDest)) &&
2035 BI.getCondition()->hasOneUse())
2036 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2037 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2038 IPred == ICmpInst::ICMP_SGE) {
2039 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2040 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2041 // Swap Destinations and condition.
2042 BI.swapSuccessors();
2050 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2051 Value *Cond = SI.getCondition();
2052 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2053 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2054 computeKnownBits(Cond, KnownZero, KnownOne);
2055 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2056 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2058 // Compute the number of leading bits we can ignore.
2059 for (auto &C : SI.cases()) {
2060 LeadingKnownZeros = std::min(
2061 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2062 LeadingKnownOnes = std::min(
2063 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2066 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2068 // Truncate the condition operand if the new type is equal to or larger than
2069 // the largest legal integer type. We need to be conservative here since
2070 // x86 generates redundant zero-extenstion instructions if the operand is
2071 // truncated to i8 or i16.
2072 bool TruncCond = false;
2073 if (DL && BitWidth > NewWidth &&
2074 NewWidth >= DL->getLargestLegalIntTypeSize()) {
2076 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2077 Builder->SetInsertPoint(&SI);
2078 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2079 SI.setCondition(NewCond);
2081 for (auto &C : SI.cases())
2082 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2083 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2086 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2087 if (I->getOpcode() == Instruction::Add)
2088 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2089 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2090 // Skip the first item since that's the default case.
2091 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2093 ConstantInt* CaseVal = i.getCaseValue();
2094 Constant *LHS = CaseVal;
2096 LHS = LeadingKnownZeros
2097 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2098 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2099 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2100 assert(isa<ConstantInt>(NewCaseVal) &&
2101 "Result of expression should be constant");
2102 i.setValue(cast<ConstantInt>(NewCaseVal));
2104 SI.setCondition(I->getOperand(0));
2110 return TruncCond ? &SI : nullptr;
2113 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2114 Value *Agg = EV.getAggregateOperand();
2116 if (!EV.hasIndices())
2117 return ReplaceInstUsesWith(EV, Agg);
2119 if (Constant *C = dyn_cast<Constant>(Agg)) {
2120 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2121 if (EV.getNumIndices() == 0)
2122 return ReplaceInstUsesWith(EV, C2);
2123 // Extract the remaining indices out of the constant indexed by the
2125 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2127 return nullptr; // Can't handle other constants
2130 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2131 // We're extracting from an insertvalue instruction, compare the indices
2132 const unsigned *exti, *exte, *insi, *inse;
2133 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2134 exte = EV.idx_end(), inse = IV->idx_end();
2135 exti != exte && insi != inse;
2138 // The insert and extract both reference distinctly different elements.
2139 // This means the extract is not influenced by the insert, and we can
2140 // replace the aggregate operand of the extract with the aggregate
2141 // operand of the insert. i.e., replace
2142 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2143 // %E = extractvalue { i32, { i32 } } %I, 0
2145 // %E = extractvalue { i32, { i32 } } %A, 0
2146 return ExtractValueInst::Create(IV->getAggregateOperand(),
2149 if (exti == exte && insi == inse)
2150 // Both iterators are at the end: Index lists are identical. Replace
2151 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2152 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2154 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2156 // The extract list is a prefix of the insert list. i.e. replace
2157 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2158 // %E = extractvalue { i32, { i32 } } %I, 1
2160 // %X = extractvalue { i32, { i32 } } %A, 1
2161 // %E = insertvalue { i32 } %X, i32 42, 0
2162 // by switching the order of the insert and extract (though the
2163 // insertvalue should be left in, since it may have other uses).
2164 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2166 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2167 makeArrayRef(insi, inse));
2170 // The insert list is a prefix of the extract list
2171 // We can simply remove the common indices from the extract and make it
2172 // operate on the inserted value instead of the insertvalue result.
2174 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2175 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2177 // %E extractvalue { i32 } { i32 42 }, 0
2178 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2179 makeArrayRef(exti, exte));
2181 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2182 // We're extracting from an intrinsic, see if we're the only user, which
2183 // allows us to simplify multiple result intrinsics to simpler things that
2184 // just get one value.
2185 if (II->hasOneUse()) {
2186 // Check if we're grabbing the overflow bit or the result of a 'with
2187 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2188 // and replace it with a traditional binary instruction.
2189 switch (II->getIntrinsicID()) {
2190 case Intrinsic::uadd_with_overflow:
2191 case Intrinsic::sadd_with_overflow:
2192 if (*EV.idx_begin() == 0) { // Normal result.
2193 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2194 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2195 EraseInstFromFunction(*II);
2196 return BinaryOperator::CreateAdd(LHS, RHS);
2199 // If the normal result of the add is dead, and the RHS is a constant,
2200 // we can transform this into a range comparison.
2201 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2202 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2203 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2204 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2205 ConstantExpr::getNot(CI));
2207 case Intrinsic::usub_with_overflow:
2208 case Intrinsic::ssub_with_overflow:
2209 if (*EV.idx_begin() == 0) { // Normal result.
2210 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2211 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2212 EraseInstFromFunction(*II);
2213 return BinaryOperator::CreateSub(LHS, RHS);
2216 case Intrinsic::umul_with_overflow:
2217 case Intrinsic::smul_with_overflow:
2218 if (*EV.idx_begin() == 0) { // Normal result.
2219 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2220 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2221 EraseInstFromFunction(*II);
2222 return BinaryOperator::CreateMul(LHS, RHS);
2230 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2231 // If the (non-volatile) load only has one use, we can rewrite this to a
2232 // load from a GEP. This reduces the size of the load.
2233 // FIXME: If a load is used only by extractvalue instructions then this
2234 // could be done regardless of having multiple uses.
2235 if (L->isSimple() && L->hasOneUse()) {
2236 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2237 SmallVector<Value*, 4> Indices;
2238 // Prefix an i32 0 since we need the first element.
2239 Indices.push_back(Builder->getInt32(0));
2240 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2242 Indices.push_back(Builder->getInt32(*I));
2244 // We need to insert these at the location of the old load, not at that of
2245 // the extractvalue.
2246 Builder->SetInsertPoint(L->getParent(), L);
2247 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2248 // Returning the load directly will cause the main loop to insert it in
2249 // the wrong spot, so use ReplaceInstUsesWith().
2250 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2252 // We could simplify extracts from other values. Note that nested extracts may
2253 // already be simplified implicitly by the above: extract (extract (insert) )
2254 // will be translated into extract ( insert ( extract ) ) first and then just
2255 // the value inserted, if appropriate. Similarly for extracts from single-use
2256 // loads: extract (extract (load)) will be translated to extract (load (gep))
2257 // and if again single-use then via load (gep (gep)) to load (gep).
2258 // However, double extracts from e.g. function arguments or return values
2259 // aren't handled yet.
2263 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2264 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2265 switch (Personality) {
2266 case EHPersonality::GNU_C:
2267 // The GCC C EH personality only exists to support cleanups, so it's not
2268 // clear what the semantics of catch clauses are.
2270 case EHPersonality::Unknown:
2272 case EHPersonality::GNU_Ada:
2273 // While __gnat_all_others_value will match any Ada exception, it doesn't
2274 // match foreign exceptions (or didn't, before gcc-4.7).
2276 case EHPersonality::GNU_CXX:
2277 case EHPersonality::GNU_ObjC:
2278 case EHPersonality::MSVC_Win64SEH:
2279 case EHPersonality::MSVC_CXX:
2280 return TypeInfo->isNullValue();
2282 llvm_unreachable("invalid enum");
2285 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2287 cast<ArrayType>(LHS->getType())->getNumElements()
2289 cast<ArrayType>(RHS->getType())->getNumElements();
2292 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2293 // The logic here should be correct for any real-world personality function.
2294 // However if that turns out not to be true, the offending logic can always
2295 // be conditioned on the personality function, like the catch-all logic is.
2296 EHPersonality Personality = ClassifyEHPersonality(LI.getPersonalityFn());
2298 // Simplify the list of clauses, eg by removing repeated catch clauses
2299 // (these are often created by inlining).
2300 bool MakeNewInstruction = false; // If true, recreate using the following:
2301 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2302 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2304 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2305 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2306 bool isLastClause = i + 1 == e;
2307 if (LI.isCatch(i)) {
2309 Constant *CatchClause = LI.getClause(i);
2310 Constant *TypeInfo = CatchClause->stripPointerCasts();
2312 // If we already saw this clause, there is no point in having a second
2314 if (AlreadyCaught.insert(TypeInfo).second) {
2315 // This catch clause was not already seen.
2316 NewClauses.push_back(CatchClause);
2318 // Repeated catch clause - drop the redundant copy.
2319 MakeNewInstruction = true;
2322 // If this is a catch-all then there is no point in keeping any following
2323 // clauses or marking the landingpad as having a cleanup.
2324 if (isCatchAll(Personality, TypeInfo)) {
2326 MakeNewInstruction = true;
2327 CleanupFlag = false;
2331 // A filter clause. If any of the filter elements were already caught
2332 // then they can be dropped from the filter. It is tempting to try to
2333 // exploit the filter further by saying that any typeinfo that does not
2334 // occur in the filter can't be caught later (and thus can be dropped).
2335 // However this would be wrong, since typeinfos can match without being
2336 // equal (for example if one represents a C++ class, and the other some
2337 // class derived from it).
2338 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2339 Constant *FilterClause = LI.getClause(i);
2340 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2341 unsigned NumTypeInfos = FilterType->getNumElements();
2343 // An empty filter catches everything, so there is no point in keeping any
2344 // following clauses or marking the landingpad as having a cleanup. By
2345 // dealing with this case here the following code is made a bit simpler.
2346 if (!NumTypeInfos) {
2347 NewClauses.push_back(FilterClause);
2349 MakeNewInstruction = true;
2350 CleanupFlag = false;
2354 bool MakeNewFilter = false; // If true, make a new filter.
2355 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2356 if (isa<ConstantAggregateZero>(FilterClause)) {
2357 // Not an empty filter - it contains at least one null typeinfo.
2358 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2359 Constant *TypeInfo =
2360 Constant::getNullValue(FilterType->getElementType());
2361 // If this typeinfo is a catch-all then the filter can never match.
2362 if (isCatchAll(Personality, TypeInfo)) {
2363 // Throw the filter away.
2364 MakeNewInstruction = true;
2368 // There is no point in having multiple copies of this typeinfo, so
2369 // discard all but the first copy if there is more than one.
2370 NewFilterElts.push_back(TypeInfo);
2371 if (NumTypeInfos > 1)
2372 MakeNewFilter = true;
2374 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2375 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2376 NewFilterElts.reserve(NumTypeInfos);
2378 // Remove any filter elements that were already caught or that already
2379 // occurred in the filter. While there, see if any of the elements are
2380 // catch-alls. If so, the filter can be discarded.
2381 bool SawCatchAll = false;
2382 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2383 Constant *Elt = Filter->getOperand(j);
2384 Constant *TypeInfo = Elt->stripPointerCasts();
2385 if (isCatchAll(Personality, TypeInfo)) {
2386 // This element is a catch-all. Bail out, noting this fact.
2390 if (AlreadyCaught.count(TypeInfo))
2391 // Already caught by an earlier clause, so having it in the filter
2394 // There is no point in having multiple copies of the same typeinfo in
2395 // a filter, so only add it if we didn't already.
2396 if (SeenInFilter.insert(TypeInfo).second)
2397 NewFilterElts.push_back(cast<Constant>(Elt));
2399 // A filter containing a catch-all cannot match anything by definition.
2401 // Throw the filter away.
2402 MakeNewInstruction = true;
2406 // If we dropped something from the filter, make a new one.
2407 if (NewFilterElts.size() < NumTypeInfos)
2408 MakeNewFilter = true;
2410 if (MakeNewFilter) {
2411 FilterType = ArrayType::get(FilterType->getElementType(),
2412 NewFilterElts.size());
2413 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2414 MakeNewInstruction = true;
2417 NewClauses.push_back(FilterClause);
2419 // If the new filter is empty then it will catch everything so there is
2420 // no point in keeping any following clauses or marking the landingpad
2421 // as having a cleanup. The case of the original filter being empty was
2422 // already handled above.
2423 if (MakeNewFilter && !NewFilterElts.size()) {
2424 assert(MakeNewInstruction && "New filter but not a new instruction!");
2425 CleanupFlag = false;
2431 // If several filters occur in a row then reorder them so that the shortest
2432 // filters come first (those with the smallest number of elements). This is
2433 // advantageous because shorter filters are more likely to match, speeding up
2434 // unwinding, but mostly because it increases the effectiveness of the other
2435 // filter optimizations below.
2436 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2438 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2439 for (j = i; j != e; ++j)
2440 if (!isa<ArrayType>(NewClauses[j]->getType()))
2443 // Check whether the filters are already sorted by length. We need to know
2444 // if sorting them is actually going to do anything so that we only make a
2445 // new landingpad instruction if it does.
2446 for (unsigned k = i; k + 1 < j; ++k)
2447 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2448 // Not sorted, so sort the filters now. Doing an unstable sort would be
2449 // correct too but reordering filters pointlessly might confuse users.
2450 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2452 MakeNewInstruction = true;
2456 // Look for the next batch of filters.
2460 // If typeinfos matched if and only if equal, then the elements of a filter L
2461 // that occurs later than a filter F could be replaced by the intersection of
2462 // the elements of F and L. In reality two typeinfos can match without being
2463 // equal (for example if one represents a C++ class, and the other some class
2464 // derived from it) so it would be wrong to perform this transform in general.
2465 // However the transform is correct and useful if F is a subset of L. In that
2466 // case L can be replaced by F, and thus removed altogether since repeating a
2467 // filter is pointless. So here we look at all pairs of filters F and L where
2468 // L follows F in the list of clauses, and remove L if every element of F is
2469 // an element of L. This can occur when inlining C++ functions with exception
2471 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2472 // Examine each filter in turn.
2473 Value *Filter = NewClauses[i];
2474 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2476 // Not a filter - skip it.
2478 unsigned FElts = FTy->getNumElements();
2479 // Examine each filter following this one. Doing this backwards means that
2480 // we don't have to worry about filters disappearing under us when removed.
2481 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2482 Value *LFilter = NewClauses[j];
2483 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2485 // Not a filter - skip it.
2487 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2488 // an element of LFilter, then discard LFilter.
2489 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2490 // If Filter is empty then it is a subset of LFilter.
2493 NewClauses.erase(J);
2494 MakeNewInstruction = true;
2495 // Move on to the next filter.
2498 unsigned LElts = LTy->getNumElements();
2499 // If Filter is longer than LFilter then it cannot be a subset of it.
2501 // Move on to the next filter.
2503 // At this point we know that LFilter has at least one element.
2504 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2505 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2506 // already know that Filter is not longer than LFilter).
2507 if (isa<ConstantAggregateZero>(Filter)) {
2508 assert(FElts <= LElts && "Should have handled this case earlier!");
2510 NewClauses.erase(J);
2511 MakeNewInstruction = true;
2513 // Move on to the next filter.
2516 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2517 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2518 // Since Filter is non-empty and contains only zeros, it is a subset of
2519 // LFilter iff LFilter contains a zero.
2520 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2521 for (unsigned l = 0; l != LElts; ++l)
2522 if (LArray->getOperand(l)->isNullValue()) {
2523 // LFilter contains a zero - discard it.
2524 NewClauses.erase(J);
2525 MakeNewInstruction = true;
2528 // Move on to the next filter.
2531 // At this point we know that both filters are ConstantArrays. Loop over
2532 // operands to see whether every element of Filter is also an element of
2533 // LFilter. Since filters tend to be short this is probably faster than
2534 // using a method that scales nicely.
2535 ConstantArray *FArray = cast<ConstantArray>(Filter);
2536 bool AllFound = true;
2537 for (unsigned f = 0; f != FElts; ++f) {
2538 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2540 for (unsigned l = 0; l != LElts; ++l) {
2541 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2542 if (LTypeInfo == FTypeInfo) {
2552 NewClauses.erase(J);
2553 MakeNewInstruction = true;
2555 // Move on to the next filter.
2559 // If we changed any of the clauses, replace the old landingpad instruction
2561 if (MakeNewInstruction) {
2562 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2563 LI.getPersonalityFn(),
2565 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2566 NLI->addClause(NewClauses[i]);
2567 // A landing pad with no clauses must have the cleanup flag set. It is
2568 // theoretically possible, though highly unlikely, that we eliminated all
2569 // clauses. If so, force the cleanup flag to true.
2570 if (NewClauses.empty())
2572 NLI->setCleanup(CleanupFlag);
2576 // Even if none of the clauses changed, we may nonetheless have understood
2577 // that the cleanup flag is pointless. Clear it if so.
2578 if (LI.isCleanup() != CleanupFlag) {
2579 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2580 LI.setCleanup(CleanupFlag);
2587 /// TryToSinkInstruction - Try to move the specified instruction from its
2588 /// current block into the beginning of DestBlock, which can only happen if it's
2589 /// safe to move the instruction past all of the instructions between it and the
2590 /// end of its block.
2591 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2592 assert(I->hasOneUse() && "Invariants didn't hold!");
2594 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2595 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2596 isa<TerminatorInst>(I))
2599 // Do not sink alloca instructions out of the entry block.
2600 if (isa<AllocaInst>(I) && I->getParent() ==
2601 &DestBlock->getParent()->getEntryBlock())
2604 // We can only sink load instructions if there is nothing between the load and
2605 // the end of block that could change the value.
2606 if (I->mayReadFromMemory()) {
2607 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2609 if (Scan->mayWriteToMemory())
2613 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2614 I->moveBefore(InsertPos);
2619 bool InstCombiner::run() {
2620 while (!Worklist.isEmpty()) {
2621 Instruction *I = Worklist.RemoveOne();
2622 if (I == nullptr) continue; // skip null values.
2624 // Check to see if we can DCE the instruction.
2625 if (isInstructionTriviallyDead(I, TLI)) {
2626 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2627 EraseInstFromFunction(*I);
2629 MadeIRChange = true;
2633 // Instruction isn't dead, see if we can constant propagate it.
2634 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2635 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2636 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2638 // Add operands to the worklist.
2639 ReplaceInstUsesWith(*I, C);
2641 EraseInstFromFunction(*I);
2642 MadeIRChange = true;
2646 // See if we can trivially sink this instruction to a successor basic block.
2647 if (I->hasOneUse()) {
2648 BasicBlock *BB = I->getParent();
2649 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2650 BasicBlock *UserParent;
2652 // Get the block the use occurs in.
2653 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2654 UserParent = PN->getIncomingBlock(*I->use_begin());
2656 UserParent = UserInst->getParent();
2658 if (UserParent != BB) {
2659 bool UserIsSuccessor = false;
2660 // See if the user is one of our successors.
2661 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2662 if (*SI == UserParent) {
2663 UserIsSuccessor = true;
2667 // If the user is one of our immediate successors, and if that successor
2668 // only has us as a predecessors (we'd have to split the critical edge
2669 // otherwise), we can keep going.
2670 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2671 // Okay, the CFG is simple enough, try to sink this instruction.
2672 if (TryToSinkInstruction(I, UserParent)) {
2673 MadeIRChange = true;
2674 // We'll add uses of the sunk instruction below, but since sinking
2675 // can expose opportunities for it's *operands* add them to the
2677 for (Use &U : I->operands())
2678 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2685 // Now that we have an instruction, try combining it to simplify it.
2686 Builder->SetInsertPoint(I->getParent(), I);
2687 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2692 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2693 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2695 if (Instruction *Result = visit(*I)) {
2697 // Should we replace the old instruction with a new one?
2699 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2700 << " New = " << *Result << '\n');
2702 if (!I->getDebugLoc().isUnknown())
2703 Result->setDebugLoc(I->getDebugLoc());
2704 // Everything uses the new instruction now.
2705 I->replaceAllUsesWith(Result);
2707 // Move the name to the new instruction first.
2708 Result->takeName(I);
2710 // Push the new instruction and any users onto the worklist.
2711 Worklist.Add(Result);
2712 Worklist.AddUsersToWorkList(*Result);
2714 // Insert the new instruction into the basic block...
2715 BasicBlock *InstParent = I->getParent();
2716 BasicBlock::iterator InsertPos = I;
2718 // If we replace a PHI with something that isn't a PHI, fix up the
2720 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2721 InsertPos = InstParent->getFirstInsertionPt();
2723 InstParent->getInstList().insert(InsertPos, Result);
2725 EraseInstFromFunction(*I);
2728 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2729 << " New = " << *I << '\n');
2732 // If the instruction was modified, it's possible that it is now dead.
2733 // if so, remove it.
2734 if (isInstructionTriviallyDead(I, TLI)) {
2735 EraseInstFromFunction(*I);
2738 Worklist.AddUsersToWorkList(*I);
2741 MadeIRChange = true;
2746 return MadeIRChange;
2749 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2750 /// all reachable code to the worklist.
2752 /// This has a couple of tricks to make the code faster and more powerful. In
2753 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2754 /// them to the worklist (this significantly speeds up instcombine on code where
2755 /// many instructions are dead or constant). Additionally, if we find a branch
2756 /// whose condition is a known constant, we only visit the reachable successors.
2758 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2759 SmallPtrSetImpl<BasicBlock*> &Visited,
2760 InstCombineWorklist &ICWorklist,
2761 const DataLayout *DL,
2762 const TargetLibraryInfo *TLI) {
2763 bool MadeIRChange = false;
2764 SmallVector<BasicBlock*, 256> Worklist;
2765 Worklist.push_back(BB);
2767 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2768 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2771 BB = Worklist.pop_back_val();
2773 // We have now visited this block! If we've already been here, ignore it.
2774 if (!Visited.insert(BB).second)
2777 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2778 Instruction *Inst = BBI++;
2780 // DCE instruction if trivially dead.
2781 if (isInstructionTriviallyDead(Inst, TLI)) {
2783 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2784 Inst->eraseFromParent();
2788 // ConstantProp instruction if trivially constant.
2789 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2790 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2791 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2793 Inst->replaceAllUsesWith(C);
2795 Inst->eraseFromParent();
2800 // See if we can constant fold its operands.
2801 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2803 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2804 if (CE == nullptr) continue;
2806 Constant*& FoldRes = FoldedConstants[CE];
2808 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2812 if (FoldRes != CE) {
2814 MadeIRChange = true;
2819 InstrsForInstCombineWorklist.push_back(Inst);
2822 // Recursively visit successors. If this is a branch or switch on a
2823 // constant, only visit the reachable successor.
2824 TerminatorInst *TI = BB->getTerminator();
2825 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2826 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2827 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2828 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2829 Worklist.push_back(ReachableBB);
2832 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2833 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2834 // See if this is an explicit destination.
2835 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2837 if (i.getCaseValue() == Cond) {
2838 BasicBlock *ReachableBB = i.getCaseSuccessor();
2839 Worklist.push_back(ReachableBB);
2843 // Otherwise it is the default destination.
2844 Worklist.push_back(SI->getDefaultDest());
2849 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2850 Worklist.push_back(TI->getSuccessor(i));
2851 } while (!Worklist.empty());
2853 // Once we've found all of the instructions to add to instcombine's worklist,
2854 // add them in reverse order. This way instcombine will visit from the top
2855 // of the function down. This jives well with the way that it adds all uses
2856 // of instructions to the worklist after doing a transformation, thus avoiding
2857 // some N^2 behavior in pathological cases.
2858 ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2859 InstrsForInstCombineWorklist.size());
2861 return MadeIRChange;
2864 /// \brief Populate the IC worklist from a function, and prune any dead basic
2865 /// blocks discovered in the process.
2867 /// This also does basic constant propagation and other forward fixing to make
2868 /// the combiner itself run much faster.
2869 static bool prepareICWorklistFromFunction(Function &F, const DataLayout *DL,
2870 TargetLibraryInfo *TLI,
2871 InstCombineWorklist &ICWorklist) {
2872 bool MadeIRChange = false;
2874 // Do a depth-first traversal of the function, populate the worklist with
2875 // the reachable instructions. Ignore blocks that are not reachable. Keep
2876 // track of which blocks we visit.
2877 SmallPtrSet<BasicBlock *, 64> Visited;
2879 AddReachableCodeToWorklist(F.begin(), Visited, ICWorklist, DL, TLI);
2881 // Do a quick scan over the function. If we find any blocks that are
2882 // unreachable, remove any instructions inside of them. This prevents
2883 // the instcombine code from having to deal with some bad special cases.
2884 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2885 if (Visited.count(BB))
2888 // Delete the instructions backwards, as it has a reduced likelihood of
2889 // having to update as many def-use and use-def chains.
2890 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2891 while (EndInst != BB->begin()) {
2892 // Delete the next to last instruction.
2893 BasicBlock::iterator I = EndInst;
2894 Instruction *Inst = --I;
2895 if (!Inst->use_empty())
2896 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2897 if (isa<LandingPadInst>(Inst)) {
2901 if (!isa<DbgInfoIntrinsic>(Inst)) {
2903 MadeIRChange = true;
2905 Inst->eraseFromParent();
2909 return MadeIRChange;
2912 static bool combineInstructionsOverFunction(
2913 Function &F, InstCombineWorklist &Worklist, AssumptionCache &AC,
2914 TargetLibraryInfo &TLI, DominatorTree &DT, const DataLayout *DL = nullptr,
2915 LoopInfo *LI = nullptr) {
2917 bool MinimizeSize = F.getAttributes().hasAttribute(
2918 AttributeSet::FunctionIndex, Attribute::MinSize);
2920 /// Builder - This is an IRBuilder that automatically inserts new
2921 /// instructions into the worklist when they are created.
2922 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
2923 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
2925 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2927 bool DbgDeclaresChanged = LowerDbgDeclare(F);
2929 // Iterate while there is work to do.
2933 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2934 << F.getName() << "\n");
2936 bool Changed = false;
2937 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
2940 InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI);
2948 return DbgDeclaresChanged || Iteration > 1;
2951 PreservedAnalyses InstCombinePass::run(Function &F,
2952 AnalysisManager<Function> *AM) {
2953 auto *DL = F.getParent()->getDataLayout();
2955 auto &AC = AM->getResult<AssumptionAnalysis>(F);
2956 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
2957 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
2959 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
2961 if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI))
2962 // No changes, all analyses are preserved.
2963 return PreservedAnalyses::all();
2965 // Mark all the analyses that instcombine updates as preserved.
2966 // FIXME: Need a way to preserve CFG analyses here!
2967 PreservedAnalyses PA;
2968 PA.preserve<DominatorTreeAnalysis>();
2973 /// \brief The legacy pass manager's instcombine pass.
2975 /// This is a basic whole-function wrapper around the instcombine utility. It
2976 /// will try to combine all instructions in the function.
2977 class InstructionCombiningPass : public FunctionPass {
2978 InstCombineWorklist Worklist;
2981 static char ID; // Pass identification, replacement for typeid
2983 InstructionCombiningPass() : FunctionPass(ID) {
2984 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
2987 void getAnalysisUsage(AnalysisUsage &AU) const override;
2988 bool runOnFunction(Function &F) override;
2992 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
2993 AU.setPreservesCFG();
2994 AU.addRequired<AssumptionCacheTracker>();
2995 AU.addRequired<TargetLibraryInfoWrapperPass>();
2996 AU.addRequired<DominatorTreeWrapperPass>();
2997 AU.addPreserved<DominatorTreeWrapperPass>();
3000 bool InstructionCombiningPass::runOnFunction(Function &F) {
3001 if (skipOptnoneFunction(F))
3004 // Required analyses.
3005 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3006 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3007 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3009 // Optional analyses.
3010 auto *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3011 auto *DL = DLP ? &DLP->getDataLayout() : nullptr;
3012 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3013 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3015 return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI);
3018 char InstructionCombiningPass::ID = 0;
3019 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3020 "Combine redundant instructions", false, false)
3021 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3022 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3023 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3024 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3025 "Combine redundant instructions", false, false)
3027 // Initialization Routines
3028 void llvm::initializeInstCombine(PassRegistry &Registry) {
3029 initializeInstructionCombiningPassPass(Registry);
3032 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3033 initializeInstructionCombiningPassPass(*unwrap(R));
3036 FunctionPass *llvm::createInstructionCombiningPass() {
3037 return new InstructionCombiningPass();