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/Scalar.h"
37 #include "InstCombine.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/AssumptionTracker.h"
43 #include "llvm/Analysis/CFG.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Analysis/MemoryBuiltins.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/CFG.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Dominators.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/IR/ValueHandle.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Target/TargetLibraryInfo.h"
59 #include "llvm/Transforms/Utils/Local.h"
63 using namespace llvm::PatternMatch;
65 #define DEBUG_TYPE "instcombine"
67 STATISTIC(NumCombined , "Number of insts combined");
68 STATISTIC(NumConstProp, "Number of constant folds");
69 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71 STATISTIC(NumExpand, "Number of expansions");
72 STATISTIC(NumFactor , "Number of factorizations");
73 STATISTIC(NumReassoc , "Number of reassociations");
75 // Initialization Routines
76 void llvm::initializeInstCombine(PassRegistry &Registry) {
77 initializeInstCombinerPass(Registry);
80 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
81 initializeInstCombine(*unwrap(R));
84 char InstCombiner::ID = 0;
85 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
86 "Combine redundant instructions", false, false)
87 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
88 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
89 INITIALIZE_PASS_END(InstCombiner, "instcombine",
90 "Combine redundant instructions", false, false)
92 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addPreserved<DominatorTreeWrapperPass>();
94 AU.addPreserved<LoopInfo>();
95 AU.addRequired<AssumptionTracker>();
96 AU.addRequired<TargetLibraryInfo>();
100 Value *InstCombiner::EmitGEPOffset(User *GEP) {
101 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
104 /// ShouldChangeType - Return true if it is desirable to convert a computation
105 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
106 /// type for example, or from a smaller to a larger illegal type.
107 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
108 assert(From->isIntegerTy() && To->isIntegerTy());
110 // If we don't have DL, we don't know if the source/dest are legal.
111 if (!DL) return false;
113 unsigned FromWidth = From->getPrimitiveSizeInBits();
114 unsigned ToWidth = To->getPrimitiveSizeInBits();
115 bool FromLegal = DL->isLegalInteger(FromWidth);
116 bool ToLegal = DL->isLegalInteger(ToWidth);
118 // If this is a legal integer from type, and the result would be an illegal
119 // type, don't do the transformation.
120 if (FromLegal && !ToLegal)
123 // Otherwise, if both are illegal, do not increase the size of the result. We
124 // do allow things like i160 -> i64, but not i64 -> i160.
125 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
131 // Return true, if No Signed Wrap should be maintained for I.
132 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
133 // where both B and C should be ConstantInts, results in a constant that does
134 // not overflow. This function only handles the Add and Sub opcodes. For
135 // all other opcodes, the function conservatively returns false.
136 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
137 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
138 if (!OBO || !OBO->hasNoSignedWrap()) {
142 // We reason about Add and Sub Only.
143 Instruction::BinaryOps Opcode = I.getOpcode();
144 if (Opcode != Instruction::Add &&
145 Opcode != Instruction::Sub) {
149 ConstantInt *CB = dyn_cast<ConstantInt>(B);
150 ConstantInt *CC = dyn_cast<ConstantInt>(C);
156 const APInt &BVal = CB->getValue();
157 const APInt &CVal = CC->getValue();
158 bool Overflow = false;
160 if (Opcode == Instruction::Add) {
161 BVal.sadd_ov(CVal, Overflow);
163 BVal.ssub_ov(CVal, Overflow);
169 /// Conservatively clears subclassOptionalData after a reassociation or
170 /// commutation. We preserve fast-math flags when applicable as they can be
172 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
173 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
175 I.clearSubclassOptionalData();
179 FastMathFlags FMF = I.getFastMathFlags();
180 I.clearSubclassOptionalData();
181 I.setFastMathFlags(FMF);
184 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
185 /// operators which are associative or commutative:
187 // Commutative operators:
189 // 1. Order operands such that they are listed from right (least complex) to
190 // left (most complex). This puts constants before unary operators before
193 // Associative operators:
195 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
196 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
198 // Associative and commutative operators:
200 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
201 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
202 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
203 // if C1 and C2 are constants.
205 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
206 Instruction::BinaryOps Opcode = I.getOpcode();
207 bool Changed = false;
210 // Order operands such that they are listed from right (least complex) to
211 // left (most complex). This puts constants before unary operators before
213 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
214 getComplexity(I.getOperand(1)))
215 Changed = !I.swapOperands();
217 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
218 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
220 if (I.isAssociative()) {
221 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
222 if (Op0 && Op0->getOpcode() == Opcode) {
223 Value *A = Op0->getOperand(0);
224 Value *B = Op0->getOperand(1);
225 Value *C = I.getOperand(1);
227 // Does "B op C" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
229 // It simplifies to V. Form "A op V".
232 // Conservatively clear the optional flags, since they may not be
233 // preserved by the reassociation.
234 if (MaintainNoSignedWrap(I, B, C) &&
235 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
236 // Note: this is only valid because SimplifyBinOp doesn't look at
237 // the operands to Op0.
238 I.clearSubclassOptionalData();
239 I.setHasNoSignedWrap(true);
241 ClearSubclassDataAfterReassociation(I);
250 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
251 if (Op1 && Op1->getOpcode() == Opcode) {
252 Value *A = I.getOperand(0);
253 Value *B = Op1->getOperand(0);
254 Value *C = Op1->getOperand(1);
256 // Does "A op B" simplify?
257 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
258 // It simplifies to V. Form "V op C".
261 // Conservatively clear the optional flags, since they may not be
262 // preserved by the reassociation.
263 ClearSubclassDataAfterReassociation(I);
271 if (I.isAssociative() && I.isCommutative()) {
272 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
273 if (Op0 && Op0->getOpcode() == Opcode) {
274 Value *A = Op0->getOperand(0);
275 Value *B = Op0->getOperand(1);
276 Value *C = I.getOperand(1);
278 // Does "C op A" simplify?
279 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
280 // It simplifies to V. Form "V op B".
283 // Conservatively clear the optional flags, since they may not be
284 // preserved by the reassociation.
285 ClearSubclassDataAfterReassociation(I);
292 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
293 if (Op1 && Op1->getOpcode() == Opcode) {
294 Value *A = I.getOperand(0);
295 Value *B = Op1->getOperand(0);
296 Value *C = Op1->getOperand(1);
298 // Does "C op A" simplify?
299 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
300 // It simplifies to V. Form "B op V".
303 // Conservatively clear the optional flags, since they may not be
304 // preserved by the reassociation.
305 ClearSubclassDataAfterReassociation(I);
312 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
313 // if C1 and C2 are constants.
315 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
316 isa<Constant>(Op0->getOperand(1)) &&
317 isa<Constant>(Op1->getOperand(1)) &&
318 Op0->hasOneUse() && Op1->hasOneUse()) {
319 Value *A = Op0->getOperand(0);
320 Constant *C1 = cast<Constant>(Op0->getOperand(1));
321 Value *B = Op1->getOperand(0);
322 Constant *C2 = cast<Constant>(Op1->getOperand(1));
324 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
325 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
326 if (isa<FPMathOperator>(New)) {
327 FastMathFlags Flags = I.getFastMathFlags();
328 Flags &= Op0->getFastMathFlags();
329 Flags &= Op1->getFastMathFlags();
330 New->setFastMathFlags(Flags);
332 InsertNewInstWith(New, I);
334 I.setOperand(0, New);
335 I.setOperand(1, Folded);
336 // Conservatively clear the optional flags, since they may not be
337 // preserved by the reassociation.
338 ClearSubclassDataAfterReassociation(I);
345 // No further simplifications.
350 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
351 /// "(X LOp Y) ROp (X LOp Z)".
352 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
353 Instruction::BinaryOps ROp) {
358 case Instruction::And:
359 // And distributes over Or and Xor.
363 case Instruction::Or:
364 case Instruction::Xor:
368 case Instruction::Mul:
369 // Multiplication distributes over addition and subtraction.
373 case Instruction::Add:
374 case Instruction::Sub:
378 case Instruction::Or:
379 // Or distributes over And.
383 case Instruction::And:
389 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
390 /// "(X ROp Z) LOp (Y ROp Z)".
391 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
392 Instruction::BinaryOps ROp) {
393 if (Instruction::isCommutative(ROp))
394 return LeftDistributesOverRight(ROp, LOp);
399 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
400 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
401 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
402 case Instruction::And:
403 case Instruction::Or:
404 case Instruction::Xor:
408 case Instruction::Shl:
409 case Instruction::LShr:
410 case Instruction::AShr:
414 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
415 // but this requires knowing that the addition does not overflow and other
420 /// This function returns identity value for given opcode, which can be used to
421 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
422 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
423 if (isa<Constant>(V))
426 if (OpCode == Instruction::Mul)
427 return ConstantInt::get(V->getType(), 1);
429 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
434 /// This function factors binary ops which can be combined using distributive
435 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
436 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
437 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
438 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
440 static Instruction::BinaryOps
441 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
442 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
444 return Instruction::BinaryOpsEnd;
446 LHS = Op->getOperand(0);
447 RHS = Op->getOperand(1);
449 switch (TopLevelOpcode) {
451 return Op->getOpcode();
453 case Instruction::Add:
454 case Instruction::Sub:
455 if (Op->getOpcode() == Instruction::Shl) {
456 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
457 // The multiplier is really 1 << CST.
458 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
459 return Instruction::Mul;
462 return Op->getOpcode();
465 // TODO: We can add other conversions e.g. shr => div etc.
468 /// This tries to simplify binary operations by factorizing out common terms
469 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
470 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
471 const DataLayout *DL, BinaryOperator &I,
472 Instruction::BinaryOps InnerOpcode, Value *A,
473 Value *B, Value *C, Value *D) {
475 // If any of A, B, C, D are null, we can not factor I, return early.
476 // Checking A and C should be enough.
477 if (!A || !C || !B || !D)
480 Value *SimplifiedInst = nullptr;
481 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
482 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
484 // Does "X op' Y" always equal "Y op' X"?
485 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
487 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
488 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
489 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
490 // commutative case, "(A op' B) op (C op' A)"?
491 if (A == C || (InnerCommutative && A == D)) {
494 // Consider forming "A op' (B op D)".
495 // If "B op D" simplifies then it can be formed with no cost.
496 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
497 // If "B op D" doesn't simplify then only go on if both of the existing
498 // operations "A op' B" and "C op' D" will be zapped as no longer used.
499 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
500 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
502 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
506 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
507 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
508 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
509 // commutative case, "(A op' B) op (B op' D)"?
510 if (B == D || (InnerCommutative && B == C)) {
513 // Consider forming "(A op C) op' B".
514 // If "A op C" simplifies then it can be formed with no cost.
515 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
517 // If "A op C" doesn't simplify then only go on if both of the existing
518 // operations "A op' B" and "C op' D" will be zapped as no longer used.
519 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
520 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
522 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
526 if (SimplifiedInst) {
528 SimplifiedInst->takeName(&I);
530 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
531 // TODO: Check for NUW.
532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
533 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
535 if (isa<OverflowingBinaryOperator>(&I))
536 HasNSW = I.hasNoSignedWrap();
538 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
539 if (isa<OverflowingBinaryOperator>(Op0))
540 HasNSW &= Op0->hasNoSignedWrap();
542 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
543 if (isa<OverflowingBinaryOperator>(Op1))
544 HasNSW &= Op1->hasNoSignedWrap();
545 BO->setHasNoSignedWrap(HasNSW);
549 return SimplifiedInst;
552 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
553 /// which some other binary operation distributes over either by factorizing
554 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
555 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
556 /// a win). Returns the simplified value, or null if it didn't simplify.
557 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
558 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
559 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
560 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
563 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
564 auto TopLevelOpcode = I.getOpcode();
565 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
566 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
568 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
570 if (LHSOpcode == RHSOpcode) {
571 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
575 // The instruction has the form "(A op' B) op (C)". Try to factorize common
577 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
578 getIdentityValue(LHSOpcode, RHS)))
581 // The instruction has the form "(B) op (C op' D)". Try to factorize common
583 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
584 getIdentityValue(RHSOpcode, LHS), C, D))
588 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
589 // The instruction has the form "(A op' B) op C". See if expanding it out
590 // to "(A op C) op' (B op C)" results in simplifications.
591 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
592 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
594 // Do "A op C" and "B op C" both simplify?
595 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
596 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
597 // They do! Return "L op' R".
599 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
600 if ((L == A && R == B) ||
601 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
603 // Otherwise return "L op' R" if it simplifies.
604 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
606 // Otherwise, create a new instruction.
607 C = Builder->CreateBinOp(InnerOpcode, L, R);
613 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
614 // The instruction has the form "A op (B op' C)". See if expanding it out
615 // to "(A op B) op' (A op C)" results in simplifications.
616 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
617 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
619 // Do "A op B" and "A op C" both simplify?
620 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
621 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
622 // They do! Return "L op' R".
624 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
625 if ((L == B && R == C) ||
626 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
628 // Otherwise return "L op' R" if it simplifies.
629 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
631 // Otherwise, create a new instruction.
632 A = Builder->CreateBinOp(InnerOpcode, L, R);
641 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
642 // if the LHS is a constant zero (which is the 'negate' form).
644 Value *InstCombiner::dyn_castNegVal(Value *V) const {
645 if (BinaryOperator::isNeg(V))
646 return BinaryOperator::getNegArgument(V);
648 // Constants can be considered to be negated values if they can be folded.
649 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
650 return ConstantExpr::getNeg(C);
652 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
653 if (C->getType()->getElementType()->isIntegerTy())
654 return ConstantExpr::getNeg(C);
659 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
660 // instruction if the LHS is a constant negative zero (which is the 'negate'
663 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
664 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
665 return BinaryOperator::getFNegArgument(V);
667 // Constants can be considered to be negated values if they can be folded.
668 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
669 return ConstantExpr::getFNeg(C);
671 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
672 if (C->getType()->getElementType()->isFloatingPointTy())
673 return ConstantExpr::getFNeg(C);
678 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
680 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
681 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
684 // Figure out if the constant is the left or the right argument.
685 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
686 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
688 if (Constant *SOC = dyn_cast<Constant>(SO)) {
690 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
691 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
694 Value *Op0 = SO, *Op1 = ConstOperand;
698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
699 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
700 SO->getName()+".op");
701 Instruction *FPInst = dyn_cast<Instruction>(RI);
702 if (FPInst && isa<FPMathOperator>(FPInst))
703 FPInst->copyFastMathFlags(BO);
706 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
707 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
708 SO->getName()+".cmp");
709 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
710 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
711 SO->getName()+".cmp");
712 llvm_unreachable("Unknown binary instruction type!");
715 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
716 // constant as the other operand, try to fold the binary operator into the
717 // select arguments. This also works for Cast instructions, which obviously do
718 // not have a second operand.
719 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
720 // Don't modify shared select instructions
721 if (!SI->hasOneUse()) return nullptr;
722 Value *TV = SI->getOperand(1);
723 Value *FV = SI->getOperand(2);
725 if (isa<Constant>(TV) || isa<Constant>(FV)) {
726 // Bool selects with constant operands can be folded to logical ops.
727 if (SI->getType()->isIntegerTy(1)) return nullptr;
729 // If it's a bitcast involving vectors, make sure it has the same number of
730 // elements on both sides.
731 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
732 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
733 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
735 // Verify that either both or neither are vectors.
736 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
737 // If vectors, verify that they have the same number of elements.
738 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
742 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
743 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
745 return SelectInst::Create(SI->getCondition(),
746 SelectTrueVal, SelectFalseVal);
752 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
753 /// has a PHI node as operand #0, see if we can fold the instruction into the
754 /// PHI (which is only possible if all operands to the PHI are constants).
756 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
757 PHINode *PN = cast<PHINode>(I.getOperand(0));
758 unsigned NumPHIValues = PN->getNumIncomingValues();
759 if (NumPHIValues == 0)
762 // We normally only transform phis with a single use. However, if a PHI has
763 // multiple uses and they are all the same operation, we can fold *all* of the
764 // uses into the PHI.
765 if (!PN->hasOneUse()) {
766 // Walk the use list for the instruction, comparing them to I.
767 for (User *U : PN->users()) {
768 Instruction *UI = cast<Instruction>(U);
769 if (UI != &I && !I.isIdenticalTo(UI))
772 // Otherwise, we can replace *all* users with the new PHI we form.
775 // Check to see if all of the operands of the PHI are simple constants
776 // (constantint/constantfp/undef). If there is one non-constant value,
777 // remember the BB it is in. If there is more than one or if *it* is a PHI,
778 // bail out. We don't do arbitrary constant expressions here because moving
779 // their computation can be expensive without a cost model.
780 BasicBlock *NonConstBB = nullptr;
781 for (unsigned i = 0; i != NumPHIValues; ++i) {
782 Value *InVal = PN->getIncomingValue(i);
783 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
786 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
787 if (NonConstBB) return nullptr; // More than one non-const value.
789 NonConstBB = PN->getIncomingBlock(i);
791 // If the InVal is an invoke at the end of the pred block, then we can't
792 // insert a computation after it without breaking the edge.
793 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
794 if (II->getParent() == NonConstBB)
797 // If the incoming non-constant value is in I's block, we will remove one
798 // instruction, but insert another equivalent one, leading to infinite
800 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT,
801 getAnalysisIfAvailable<LoopInfo>()))
805 // If there is exactly one non-constant value, we can insert a copy of the
806 // operation in that block. However, if this is a critical edge, we would be
807 // inserting the computation on some other paths (e.g. inside a loop). Only
808 // do this if the pred block is unconditionally branching into the phi block.
809 if (NonConstBB != nullptr) {
810 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
811 if (!BI || !BI->isUnconditional()) return nullptr;
814 // Okay, we can do the transformation: create the new PHI node.
815 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
816 InsertNewInstBefore(NewPN, *PN);
819 // If we are going to have to insert a new computation, do so right before the
820 // predecessors terminator.
822 Builder->SetInsertPoint(NonConstBB->getTerminator());
824 // Next, add all of the operands to the PHI.
825 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
826 // We only currently try to fold the condition of a select when it is a phi,
827 // not the true/false values.
828 Value *TrueV = SI->getTrueValue();
829 Value *FalseV = SI->getFalseValue();
830 BasicBlock *PhiTransBB = PN->getParent();
831 for (unsigned i = 0; i != NumPHIValues; ++i) {
832 BasicBlock *ThisBB = PN->getIncomingBlock(i);
833 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
834 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
835 Value *InV = nullptr;
836 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
837 // even if currently isNullValue gives false.
838 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
839 if (InC && !isa<ConstantExpr>(InC))
840 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
842 InV = Builder->CreateSelect(PN->getIncomingValue(i),
843 TrueVInPred, FalseVInPred, "phitmp");
844 NewPN->addIncoming(InV, ThisBB);
846 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
847 Constant *C = cast<Constant>(I.getOperand(1));
848 for (unsigned i = 0; i != NumPHIValues; ++i) {
849 Value *InV = nullptr;
850 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
851 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
852 else if (isa<ICmpInst>(CI))
853 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
856 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
858 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
860 } else if (I.getNumOperands() == 2) {
861 Constant *C = cast<Constant>(I.getOperand(1));
862 for (unsigned i = 0; i != NumPHIValues; ++i) {
863 Value *InV = nullptr;
864 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
865 InV = ConstantExpr::get(I.getOpcode(), InC, C);
867 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
868 PN->getIncomingValue(i), C, "phitmp");
869 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
872 CastInst *CI = cast<CastInst>(&I);
873 Type *RetTy = CI->getType();
874 for (unsigned i = 0; i != NumPHIValues; ++i) {
876 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
877 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
879 InV = Builder->CreateCast(CI->getOpcode(),
880 PN->getIncomingValue(i), I.getType(), "phitmp");
881 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
885 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
886 Instruction *User = cast<Instruction>(*UI++);
887 if (User == &I) continue;
888 ReplaceInstUsesWith(*User, NewPN);
889 EraseInstFromFunction(*User);
891 return ReplaceInstUsesWith(I, NewPN);
894 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
895 /// whether or not there is a sequence of GEP indices into the pointed type that
896 /// will land us at the specified offset. If so, fill them into NewIndices and
897 /// return the resultant element type, otherwise return null.
898 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
899 SmallVectorImpl<Value*> &NewIndices) {
900 assert(PtrTy->isPtrOrPtrVectorTy());
905 Type *Ty = PtrTy->getPointerElementType();
909 // Start with the index over the outer type. Note that the type size
910 // might be zero (even if the offset isn't zero) if the indexed type
911 // is something like [0 x {int, int}]
912 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
913 int64_t FirstIdx = 0;
914 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
915 FirstIdx = Offset/TySize;
916 Offset -= FirstIdx*TySize;
918 // Handle hosts where % returns negative instead of values [0..TySize).
924 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
927 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
929 // Index into the types. If we fail, set OrigBase to null.
931 // Indexing into tail padding between struct/array elements.
932 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
935 if (StructType *STy = dyn_cast<StructType>(Ty)) {
936 const StructLayout *SL = DL->getStructLayout(STy);
937 assert(Offset < (int64_t)SL->getSizeInBytes() &&
938 "Offset must stay within the indexed type");
940 unsigned Elt = SL->getElementContainingOffset(Offset);
941 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
944 Offset -= SL->getElementOffset(Elt);
945 Ty = STy->getElementType(Elt);
946 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
947 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
948 assert(EltSize && "Cannot index into a zero-sized array");
949 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
951 Ty = AT->getElementType();
953 // Otherwise, we can't index into the middle of this atomic type, bail.
961 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
962 // If this GEP has only 0 indices, it is the same pointer as
963 // Src. If Src is not a trivial GEP too, don't combine
965 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
971 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
972 /// the multiplication is known not to overflow then NoSignedWrap is set.
973 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
974 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
975 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
976 Scale.getBitWidth() && "Scale not compatible with value!");
978 // If Val is zero or Scale is one then Val = Val * Scale.
979 if (match(Val, m_Zero()) || Scale == 1) {
984 // If Scale is zero then it does not divide Val.
985 if (Scale.isMinValue())
988 // Look through chains of multiplications, searching for a constant that is
989 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
990 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
991 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
994 // Val = M1 * X || Analysis starts here and works down
995 // M1 = M2 * Y || Doesn't descend into terms with more
996 // M2 = Z * 4 \/ than one use
998 // Then to modify a term at the bottom:
1001 // M1 = Z * Y || Replaced M2 with Z
1003 // Then to work back up correcting nsw flags.
1005 // Op - the term we are currently analyzing. Starts at Val then drills down.
1006 // Replaced with its descaled value before exiting from the drill down loop.
1009 // Parent - initially null, but after drilling down notes where Op came from.
1010 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1011 // 0'th operand of Val.
1012 std::pair<Instruction*, unsigned> Parent;
1014 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1015 // levels that doesn't overflow.
1016 bool RequireNoSignedWrap = false;
1018 // logScale - log base 2 of the scale. Negative if not a power of 2.
1019 int32_t logScale = Scale.exactLogBase2();
1021 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1023 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1024 // If Op is a constant divisible by Scale then descale to the quotient.
1025 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1026 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1027 if (!Remainder.isMinValue())
1028 // Not divisible by Scale.
1030 // Replace with the quotient in the parent.
1031 Op = ConstantInt::get(CI->getType(), Quotient);
1032 NoSignedWrap = true;
1036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1038 if (BO->getOpcode() == Instruction::Mul) {
1040 NoSignedWrap = BO->hasNoSignedWrap();
1041 if (RequireNoSignedWrap && !NoSignedWrap)
1044 // There are three cases for multiplication: multiplication by exactly
1045 // the scale, multiplication by a constant different to the scale, and
1046 // multiplication by something else.
1047 Value *LHS = BO->getOperand(0);
1048 Value *RHS = BO->getOperand(1);
1050 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1051 // Multiplication by a constant.
1052 if (CI->getValue() == Scale) {
1053 // Multiplication by exactly the scale, replace the multiplication
1054 // by its left-hand side in the parent.
1059 // Otherwise drill down into the constant.
1060 if (!Op->hasOneUse())
1063 Parent = std::make_pair(BO, 1);
1067 // Multiplication by something else. Drill down into the left-hand side
1068 // since that's where the reassociate pass puts the good stuff.
1069 if (!Op->hasOneUse())
1072 Parent = std::make_pair(BO, 0);
1076 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1077 isa<ConstantInt>(BO->getOperand(1))) {
1078 // Multiplication by a power of 2.
1079 NoSignedWrap = BO->hasNoSignedWrap();
1080 if (RequireNoSignedWrap && !NoSignedWrap)
1083 Value *LHS = BO->getOperand(0);
1084 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1085 getLimitedValue(Scale.getBitWidth());
1088 if (Amt == logScale) {
1089 // Multiplication by exactly the scale, replace the multiplication
1090 // by its left-hand side in the parent.
1094 if (Amt < logScale || !Op->hasOneUse())
1097 // Multiplication by more than the scale. Reduce the multiplying amount
1098 // by the scale in the parent.
1099 Parent = std::make_pair(BO, 1);
1100 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1105 if (!Op->hasOneUse())
1108 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1109 if (Cast->getOpcode() == Instruction::SExt) {
1110 // Op is sign-extended from a smaller type, descale in the smaller type.
1111 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1112 APInt SmallScale = Scale.trunc(SmallSize);
1113 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1114 // descale Op as (sext Y) * Scale. In order to have
1115 // sext (Y * SmallScale) = (sext Y) * Scale
1116 // some conditions need to hold however: SmallScale must sign-extend to
1117 // Scale and the multiplication Y * SmallScale should not overflow.
1118 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1119 // SmallScale does not sign-extend to Scale.
1121 assert(SmallScale.exactLogBase2() == logScale);
1122 // Require that Y * SmallScale must not overflow.
1123 RequireNoSignedWrap = true;
1125 // Drill down through the cast.
1126 Parent = std::make_pair(Cast, 0);
1131 if (Cast->getOpcode() == Instruction::Trunc) {
1132 // Op is truncated from a larger type, descale in the larger type.
1133 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1134 // trunc (Y * sext Scale) = (trunc Y) * Scale
1135 // always holds. However (trunc Y) * Scale may overflow even if
1136 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1137 // from this point up in the expression (see later).
1138 if (RequireNoSignedWrap)
1141 // Drill down through the cast.
1142 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1143 Parent = std::make_pair(Cast, 0);
1144 Scale = Scale.sext(LargeSize);
1145 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1147 assert(Scale.exactLogBase2() == logScale);
1152 // Unsupported expression, bail out.
1156 // If Op is zero then Val = Op * Scale.
1157 if (match(Op, m_Zero())) {
1158 NoSignedWrap = true;
1162 // We know that we can successfully descale, so from here on we can safely
1163 // modify the IR. Op holds the descaled version of the deepest term in the
1164 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1168 // The expression only had one term.
1171 // Rewrite the parent using the descaled version of its operand.
1172 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1173 assert(Op != Parent.first->getOperand(Parent.second) &&
1174 "Descaling was a no-op?");
1175 Parent.first->setOperand(Parent.second, Op);
1176 Worklist.Add(Parent.first);
1178 // Now work back up the expression correcting nsw flags. The logic is based
1179 // on the following observation: if X * Y is known not to overflow as a signed
1180 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1181 // then X * Z will not overflow as a signed multiplication either. As we work
1182 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1183 // current level has strictly smaller absolute value than the original.
1184 Instruction *Ancestor = Parent.first;
1186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1187 // If the multiplication wasn't nsw then we can't say anything about the
1188 // value of the descaled multiplication, and we have to clear nsw flags
1189 // from this point on up.
1190 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1191 NoSignedWrap &= OpNoSignedWrap;
1192 if (NoSignedWrap != OpNoSignedWrap) {
1193 BO->setHasNoSignedWrap(NoSignedWrap);
1194 Worklist.Add(Ancestor);
1196 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1197 // The fact that the descaled input to the trunc has smaller absolute
1198 // value than the original input doesn't tell us anything useful about
1199 // the absolute values of the truncations.
1200 NoSignedWrap = false;
1202 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1203 "Failed to keep proper track of nsw flags while drilling down?");
1205 if (Ancestor == Val)
1206 // Got to the top, all done!
1209 // Move up one level in the expression.
1210 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1211 Ancestor = Ancestor->user_back();
1215 /// \brief Creates node of binary operation with the same attributes as the
1216 /// specified one but with other operands.
1217 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1218 InstCombiner::BuilderTy *B) {
1219 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1220 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1221 if (isa<OverflowingBinaryOperator>(NewBO)) {
1222 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1223 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1225 if (isa<PossiblyExactOperator>(NewBO))
1226 NewBO->setIsExact(Inst.isExact());
1231 /// \brief Makes transformation of binary operation specific for vector types.
1232 /// \param Inst Binary operator to transform.
1233 /// \return Pointer to node that must replace the original binary operator, or
1234 /// null pointer if no transformation was made.
1235 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1236 if (!Inst.getType()->isVectorTy()) return nullptr;
1238 // It may not be safe to reorder shuffles and things like div, urem, etc.
1239 // because we may trap when executing those ops on unknown vector elements.
1241 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1243 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1244 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1245 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1246 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1248 // If both arguments of binary operation are shuffles, which use the same
1249 // mask and shuffle within a single vector, it is worthwhile to move the
1250 // shuffle after binary operation:
1251 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1252 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1253 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1254 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1255 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1256 isa<UndefValue>(RShuf->getOperand(1)) &&
1257 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1258 LShuf->getMask() == RShuf->getMask()) {
1259 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1260 RShuf->getOperand(0), Builder);
1261 Value *Res = Builder->CreateShuffleVector(NewBO,
1262 UndefValue::get(NewBO->getType()), LShuf->getMask());
1267 // If one argument is a shuffle within one vector, the other is a constant,
1268 // try moving the shuffle after the binary operation.
1269 ShuffleVectorInst *Shuffle = nullptr;
1270 Constant *C1 = nullptr;
1271 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1272 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1273 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1274 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1275 if (Shuffle && C1 &&
1276 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1277 isa<UndefValue>(Shuffle->getOperand(1)) &&
1278 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1279 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1280 // Find constant C2 that has property:
1281 // shuffle(C2, ShMask) = C1
1282 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1283 // reorder is not possible.
1284 SmallVector<Constant*, 16> C2M(VWidth,
1285 UndefValue::get(C1->getType()->getScalarType()));
1286 bool MayChange = true;
1287 for (unsigned I = 0; I < VWidth; ++I) {
1288 if (ShMask[I] >= 0) {
1289 assert(ShMask[I] < (int)VWidth);
1290 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1294 C2M[ShMask[I]] = C1->getAggregateElement(I);
1298 Constant *C2 = ConstantVector::get(C2M);
1299 Value *NewLHS, *NewRHS;
1300 if (isa<Constant>(LHS)) {
1302 NewRHS = Shuffle->getOperand(0);
1304 NewLHS = Shuffle->getOperand(0);
1307 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1308 Value *Res = Builder->CreateShuffleVector(NewBO,
1309 UndefValue::get(Inst.getType()), Shuffle->getMask());
1317 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1318 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1320 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AT))
1321 return ReplaceInstUsesWith(GEP, V);
1323 Value *PtrOp = GEP.getOperand(0);
1325 // Eliminate unneeded casts for indices, and replace indices which displace
1326 // by multiples of a zero size type with zero.
1328 bool MadeChange = false;
1329 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1331 gep_type_iterator GTI = gep_type_begin(GEP);
1332 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1333 I != E; ++I, ++GTI) {
1334 // Skip indices into struct types.
1335 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1336 if (!SeqTy) continue;
1338 // If the element type has zero size then any index over it is equivalent
1339 // to an index of zero, so replace it with zero if it is not zero already.
1340 if (SeqTy->getElementType()->isSized() &&
1341 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1342 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1343 *I = Constant::getNullValue(IntPtrTy);
1347 Type *IndexTy = (*I)->getType();
1348 if (IndexTy != IntPtrTy) {
1349 // If we are using a wider index than needed for this platform, shrink
1350 // it to what we need. If narrower, sign-extend it to what we need.
1351 // This explicit cast can make subsequent optimizations more obvious.
1352 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1356 if (MadeChange) return &GEP;
1359 // Check to see if the inputs to the PHI node are getelementptr instructions.
1360 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1361 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1367 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1368 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1369 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1372 // Keep track of the type as we walk the GEP.
1373 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1375 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1376 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1379 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1381 // We have not seen any differences yet in the GEPs feeding the
1382 // PHI yet, so we record this one if it is allowed to be a
1385 // The first two arguments can vary for any GEP, the rest have to be
1386 // static for struct slots
1387 if (J > 1 && CurTy->isStructTy())
1392 // The GEP is different by more than one input. While this could be
1393 // extended to support GEPs that vary by more than one variable it
1394 // doesn't make sense since it greatly increases the complexity and
1395 // would result in an R+R+R addressing mode which no backend
1396 // directly supports and would need to be broken into several
1397 // simpler instructions anyway.
1402 // Sink down a layer of the type for the next iteration.
1404 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1405 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1413 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1416 // All the GEPs feeding the PHI are identical. Clone one down into our
1417 // BB so that it can be merged with the current GEP.
1418 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1421 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1422 // into the current block so it can be merged, and create a new PHI to
1424 Instruction *InsertPt = Builder->GetInsertPoint();
1425 Builder->SetInsertPoint(PN);
1426 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1427 PN->getNumOperands());
1428 Builder->SetInsertPoint(InsertPt);
1430 for (auto &I : PN->operands())
1431 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1432 PN->getIncomingBlock(I));
1434 NewGEP->setOperand(DI, NewPN);
1435 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1437 NewGEP->setOperand(DI, NewPN);
1440 GEP.setOperand(0, NewGEP);
1444 // Combine Indices - If the source pointer to this getelementptr instruction
1445 // is a getelementptr instruction, combine the indices of the two
1446 // getelementptr instructions into a single instruction.
1448 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1449 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1452 // Note that if our source is a gep chain itself then we wait for that
1453 // chain to be resolved before we perform this transformation. This
1454 // avoids us creating a TON of code in some cases.
1455 if (GEPOperator *SrcGEP =
1456 dyn_cast<GEPOperator>(Src->getOperand(0)))
1457 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1458 return nullptr; // Wait until our source is folded to completion.
1460 SmallVector<Value*, 8> Indices;
1462 // Find out whether the last index in the source GEP is a sequential idx.
1463 bool EndsWithSequential = false;
1464 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1466 EndsWithSequential = !(*I)->isStructTy();
1468 // Can we combine the two pointer arithmetics offsets?
1469 if (EndsWithSequential) {
1470 // Replace: gep (gep %P, long B), long A, ...
1471 // With: T = long A+B; gep %P, T, ...
1474 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1475 Value *GO1 = GEP.getOperand(1);
1476 if (SO1 == Constant::getNullValue(SO1->getType())) {
1478 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1481 // If they aren't the same type, then the input hasn't been processed
1482 // by the loop above yet (which canonicalizes sequential index types to
1483 // intptr_t). Just avoid transforming this until the input has been
1485 if (SO1->getType() != GO1->getType())
1487 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1490 // Update the GEP in place if possible.
1491 if (Src->getNumOperands() == 2) {
1492 GEP.setOperand(0, Src->getOperand(0));
1493 GEP.setOperand(1, Sum);
1496 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1497 Indices.push_back(Sum);
1498 Indices.append(GEP.op_begin()+2, GEP.op_end());
1499 } else if (isa<Constant>(*GEP.idx_begin()) &&
1500 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1501 Src->getNumOperands() != 1) {
1502 // Otherwise we can do the fold if the first index of the GEP is a zero
1503 Indices.append(Src->op_begin()+1, Src->op_end());
1504 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1507 if (!Indices.empty())
1508 return (GEP.isInBounds() && Src->isInBounds()) ?
1509 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1511 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1514 if (DL && GEP.getNumIndices() == 1) {
1515 unsigned AS = GEP.getPointerAddressSpace();
1516 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1517 DL->getPointerSizeInBits(AS)) {
1518 Type *PtrTy = GEP.getPointerOperandType();
1519 Type *Ty = PtrTy->getPointerElementType();
1520 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1522 bool Matched = false;
1525 if (TyAllocSize == 1) {
1526 V = GEP.getOperand(1);
1528 } else if (match(GEP.getOperand(1),
1529 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1530 if (TyAllocSize == 1ULL << C)
1532 } else if (match(GEP.getOperand(1),
1533 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1534 if (TyAllocSize == C)
1539 // Canonicalize (gep i8* X, -(ptrtoint Y))
1540 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1541 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1542 // pointer arithmetic.
1543 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1544 Operator *Index = cast<Operator>(V);
1545 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1546 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1547 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1549 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1552 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1553 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1554 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1561 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1562 Value *StrippedPtr = PtrOp->stripPointerCasts();
1563 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1565 // We do not handle pointer-vector geps here.
1569 if (StrippedPtr != PtrOp) {
1570 bool HasZeroPointerIndex = false;
1571 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1572 HasZeroPointerIndex = C->isZero();
1574 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1575 // into : GEP [10 x i8]* X, i32 0, ...
1577 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1578 // into : GEP i8* X, ...
1580 // This occurs when the program declares an array extern like "int X[];"
1581 if (HasZeroPointerIndex) {
1582 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1583 if (ArrayType *CATy =
1584 dyn_cast<ArrayType>(CPTy->getElementType())) {
1585 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1586 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1587 // -> GEP i8* X, ...
1588 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1589 GetElementPtrInst *Res =
1590 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1591 Res->setIsInBounds(GEP.isInBounds());
1592 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1594 // Insert Res, and create an addrspacecast.
1596 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1598 // %0 = GEP i8 addrspace(1)* X, ...
1599 // addrspacecast i8 addrspace(1)* %0 to i8*
1600 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1603 if (ArrayType *XATy =
1604 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1605 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1606 if (CATy->getElementType() == XATy->getElementType()) {
1607 // -> GEP [10 x i8]* X, i32 0, ...
1608 // At this point, we know that the cast source type is a pointer
1609 // to an array of the same type as the destination pointer
1610 // array. Because the array type is never stepped over (there
1611 // is a leading zero) we can fold the cast into this GEP.
1612 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1613 GEP.setOperand(0, StrippedPtr);
1616 // Cannot replace the base pointer directly because StrippedPtr's
1617 // address space is different. Instead, create a new GEP followed by
1618 // an addrspacecast.
1620 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1623 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1624 // addrspacecast i8 addrspace(1)* %0 to i8*
1625 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1626 Value *NewGEP = GEP.isInBounds() ?
1627 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1628 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1629 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1633 } else if (GEP.getNumOperands() == 2) {
1634 // Transform things like:
1635 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1636 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1637 Type *SrcElTy = StrippedPtrTy->getElementType();
1638 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1639 if (DL && SrcElTy->isArrayTy() &&
1640 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1641 DL->getTypeAllocSize(ResElTy)) {
1642 Type *IdxType = DL->getIntPtrType(GEP.getType());
1643 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1644 Value *NewGEP = GEP.isInBounds() ?
1645 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1646 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1648 // V and GEP are both pointer types --> BitCast
1649 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1653 // Transform things like:
1654 // %V = mul i64 %N, 4
1655 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1656 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1657 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1658 // Check that changing the type amounts to dividing the index by a scale
1660 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1661 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1662 if (ResSize && SrcSize % ResSize == 0) {
1663 Value *Idx = GEP.getOperand(1);
1664 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1665 uint64_t Scale = SrcSize / ResSize;
1667 // Earlier transforms ensure that the index has type IntPtrType, which
1668 // considerably simplifies the logic by eliminating implicit casts.
1669 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1670 "Index not cast to pointer width?");
1673 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1674 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1675 // If the multiplication NewIdx * Scale may overflow then the new
1676 // GEP may not be "inbounds".
1677 Value *NewGEP = GEP.isInBounds() && NSW ?
1678 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1679 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1681 // The NewGEP must be pointer typed, so must the old one -> BitCast
1682 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1688 // Similarly, transform things like:
1689 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1690 // (where tmp = 8*tmp2) into:
1691 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1692 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1693 SrcElTy->isArrayTy()) {
1694 // Check that changing to the array element type amounts to dividing the
1695 // index by a scale factor.
1696 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1697 uint64_t ArrayEltSize
1698 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1699 if (ResSize && ArrayEltSize % ResSize == 0) {
1700 Value *Idx = GEP.getOperand(1);
1701 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1702 uint64_t Scale = ArrayEltSize / ResSize;
1704 // Earlier transforms ensure that the index has type IntPtrType, which
1705 // considerably simplifies the logic by eliminating implicit casts.
1706 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1707 "Index not cast to pointer width?");
1710 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1711 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1712 // If the multiplication NewIdx * Scale may overflow then the new
1713 // GEP may not be "inbounds".
1715 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1719 Value *NewGEP = GEP.isInBounds() && NSW ?
1720 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1721 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1722 // The NewGEP must be pointer typed, so must the old one -> BitCast
1723 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1734 // addrspacecast between types is canonicalized as a bitcast, then an
1735 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1736 // through the addrspacecast.
1737 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1738 // X = bitcast A addrspace(1)* to B addrspace(1)*
1739 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1740 // Z = gep Y, <...constant indices...>
1741 // Into an addrspacecasted GEP of the struct.
1742 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1746 /// See if we can simplify:
1747 /// X = bitcast A* to B*
1748 /// Y = gep X, <...constant indices...>
1749 /// into a gep of the original struct. This is important for SROA and alias
1750 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1751 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1752 Value *Operand = BCI->getOperand(0);
1753 PointerType *OpType = cast<PointerType>(Operand->getType());
1754 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1755 APInt Offset(OffsetBits, 0);
1756 if (!isa<BitCastInst>(Operand) &&
1757 GEP.accumulateConstantOffset(*DL, Offset)) {
1759 // If this GEP instruction doesn't move the pointer, just replace the GEP
1760 // with a bitcast of the real input to the dest type.
1762 // If the bitcast is of an allocation, and the allocation will be
1763 // converted to match the type of the cast, don't touch this.
1764 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1765 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1766 if (Instruction *I = visitBitCast(*BCI)) {
1769 BCI->getParent()->getInstList().insert(BCI, I);
1770 ReplaceInstUsesWith(*BCI, I);
1776 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1777 return new AddrSpaceCastInst(Operand, GEP.getType());
1778 return new BitCastInst(Operand, GEP.getType());
1781 // Otherwise, if the offset is non-zero, we need to find out if there is a
1782 // field at Offset in 'A's type. If so, we can pull the cast through the
1784 SmallVector<Value*, 8> NewIndices;
1785 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1786 Value *NGEP = GEP.isInBounds() ?
1787 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1788 Builder->CreateGEP(Operand, NewIndices);
1790 if (NGEP->getType() == GEP.getType())
1791 return ReplaceInstUsesWith(GEP, NGEP);
1792 NGEP->takeName(&GEP);
1794 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1795 return new AddrSpaceCastInst(NGEP, GEP.getType());
1796 return new BitCastInst(NGEP, GEP.getType());
1805 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1806 const TargetLibraryInfo *TLI) {
1807 SmallVector<Instruction*, 4> Worklist;
1808 Worklist.push_back(AI);
1811 Instruction *PI = Worklist.pop_back_val();
1812 for (User *U : PI->users()) {
1813 Instruction *I = cast<Instruction>(U);
1814 switch (I->getOpcode()) {
1816 // Give up the moment we see something we can't handle.
1819 case Instruction::BitCast:
1820 case Instruction::GetElementPtr:
1822 Worklist.push_back(I);
1825 case Instruction::ICmp: {
1826 ICmpInst *ICI = cast<ICmpInst>(I);
1827 // We can fold eq/ne comparisons with null to false/true, respectively.
1828 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1834 case Instruction::Call:
1835 // Ignore no-op and store intrinsics.
1836 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1837 switch (II->getIntrinsicID()) {
1841 case Intrinsic::memmove:
1842 case Intrinsic::memcpy:
1843 case Intrinsic::memset: {
1844 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1845 if (MI->isVolatile() || MI->getRawDest() != PI)
1849 case Intrinsic::dbg_declare:
1850 case Intrinsic::dbg_value:
1851 case Intrinsic::invariant_start:
1852 case Intrinsic::invariant_end:
1853 case Intrinsic::lifetime_start:
1854 case Intrinsic::lifetime_end:
1855 case Intrinsic::objectsize:
1861 if (isFreeCall(I, TLI)) {
1867 case Instruction::Store: {
1868 StoreInst *SI = cast<StoreInst>(I);
1869 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1875 llvm_unreachable("missing a return?");
1877 } while (!Worklist.empty());
1881 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1882 // If we have a malloc call which is only used in any amount of comparisons
1883 // to null and free calls, delete the calls and replace the comparisons with
1884 // true or false as appropriate.
1885 SmallVector<WeakVH, 64> Users;
1886 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1887 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1888 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1891 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1892 ReplaceInstUsesWith(*C,
1893 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1894 C->isFalseWhenEqual()));
1895 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1896 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1897 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1898 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1899 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1900 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1901 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1904 EraseInstFromFunction(*I);
1907 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1908 // Replace invoke with a NOP intrinsic to maintain the original CFG
1909 Module *M = II->getParent()->getParent()->getParent();
1910 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1911 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1912 None, "", II->getParent());
1914 return EraseInstFromFunction(MI);
1919 /// \brief Move the call to free before a NULL test.
1921 /// Check if this free is accessed after its argument has been test
1922 /// against NULL (property 0).
1923 /// If yes, it is legal to move this call in its predecessor block.
1925 /// The move is performed only if the block containing the call to free
1926 /// will be removed, i.e.:
1927 /// 1. it has only one predecessor P, and P has two successors
1928 /// 2. it contains the call and an unconditional branch
1929 /// 3. its successor is the same as its predecessor's successor
1931 /// The profitability is out-of concern here and this function should
1932 /// be called only if the caller knows this transformation would be
1933 /// profitable (e.g., for code size).
1934 static Instruction *
1935 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1936 Value *Op = FI.getArgOperand(0);
1937 BasicBlock *FreeInstrBB = FI.getParent();
1938 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1940 // Validate part of constraint #1: Only one predecessor
1941 // FIXME: We can extend the number of predecessor, but in that case, we
1942 // would duplicate the call to free in each predecessor and it may
1943 // not be profitable even for code size.
1947 // Validate constraint #2: Does this block contains only the call to
1948 // free and an unconditional branch?
1949 // FIXME: We could check if we can speculate everything in the
1950 // predecessor block
1951 if (FreeInstrBB->size() != 2)
1954 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1957 // Validate the rest of constraint #1 by matching on the pred branch.
1958 TerminatorInst *TI = PredBB->getTerminator();
1959 BasicBlock *TrueBB, *FalseBB;
1960 ICmpInst::Predicate Pred;
1961 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1963 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1966 // Validate constraint #3: Ensure the null case just falls through.
1967 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1969 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1970 "Broken CFG: missing edge from predecessor to successor");
1977 Instruction *InstCombiner::visitFree(CallInst &FI) {
1978 Value *Op = FI.getArgOperand(0);
1980 // free undef -> unreachable.
1981 if (isa<UndefValue>(Op)) {
1982 // Insert a new store to null because we cannot modify the CFG here.
1983 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1984 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1985 return EraseInstFromFunction(FI);
1988 // If we have 'free null' delete the instruction. This can happen in stl code
1989 // when lots of inlining happens.
1990 if (isa<ConstantPointerNull>(Op))
1991 return EraseInstFromFunction(FI);
1993 // If we optimize for code size, try to move the call to free before the null
1994 // test so that simplify cfg can remove the empty block and dead code
1995 // elimination the branch. I.e., helps to turn something like:
1996 // if (foo) free(foo);
2000 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2006 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2007 if (RI.getNumOperands() == 0) // ret void
2010 Value *ResultOp = RI.getOperand(0);
2011 Type *VTy = ResultOp->getType();
2012 if (!VTy->isIntegerTy())
2015 // There might be assume intrinsics dominating this return that completely
2016 // determine the value. If so, constant fold it.
2017 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2018 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2019 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2020 if ((KnownZero|KnownOne).isAllOnesValue())
2021 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2026 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2027 // Change br (not X), label True, label False to: br X, label False, True
2029 BasicBlock *TrueDest;
2030 BasicBlock *FalseDest;
2031 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2032 !isa<Constant>(X)) {
2033 // Swap Destinations and condition...
2035 BI.swapSuccessors();
2039 // Canonicalize fcmp_one -> fcmp_oeq
2040 FCmpInst::Predicate FPred; Value *Y;
2041 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2042 TrueDest, FalseDest)) &&
2043 BI.getCondition()->hasOneUse())
2044 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2045 FPred == FCmpInst::FCMP_OGE) {
2046 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2047 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2049 // Swap Destinations and condition.
2050 BI.swapSuccessors();
2055 // Canonicalize icmp_ne -> icmp_eq
2056 ICmpInst::Predicate IPred;
2057 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2058 TrueDest, FalseDest)) &&
2059 BI.getCondition()->hasOneUse())
2060 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2061 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2062 IPred == ICmpInst::ICMP_SGE) {
2063 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2064 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2065 // Swap Destinations and condition.
2066 BI.swapSuccessors();
2074 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2075 Value *Cond = SI.getCondition();
2076 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2077 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2078 computeKnownBits(Cond, KnownZero, KnownOne);
2079 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2080 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2082 // Compute the number of leading bits we can ignore.
2083 for (auto &C : SI.cases()) {
2084 LeadingKnownZeros = std::min(
2085 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2086 LeadingKnownOnes = std::min(
2087 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2090 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2092 // Truncate the condition operand if the new type is equal to or larger than
2093 // the largest legal integer type. We need to be conservative here since
2094 // x86 generates redundant zero-extenstion instructions if the operand is
2095 // truncated to i8 or i16.
2096 if (BitWidth > NewWidth && NewWidth >= DL->getLargestLegalIntTypeSize()) {
2097 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2098 Builder->SetInsertPoint(&SI);
2099 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2100 SI.setCondition(NewCond);
2102 for (auto &C : SI.cases())
2103 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2104 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2107 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2108 if (I->getOpcode() == Instruction::Add)
2109 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2110 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2111 // Skip the first item since that's the default case.
2112 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2114 ConstantInt* CaseVal = i.getCaseValue();
2115 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
2117 assert(isa<ConstantInt>(NewCaseVal) &&
2118 "Result of expression should be constant");
2119 i.setValue(cast<ConstantInt>(NewCaseVal));
2121 SI.setCondition(I->getOperand(0));
2129 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2130 Value *Agg = EV.getAggregateOperand();
2132 if (!EV.hasIndices())
2133 return ReplaceInstUsesWith(EV, Agg);
2135 if (Constant *C = dyn_cast<Constant>(Agg)) {
2136 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2137 if (EV.getNumIndices() == 0)
2138 return ReplaceInstUsesWith(EV, C2);
2139 // Extract the remaining indices out of the constant indexed by the
2141 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2143 return nullptr; // Can't handle other constants
2146 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2147 // We're extracting from an insertvalue instruction, compare the indices
2148 const unsigned *exti, *exte, *insi, *inse;
2149 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2150 exte = EV.idx_end(), inse = IV->idx_end();
2151 exti != exte && insi != inse;
2154 // The insert and extract both reference distinctly different elements.
2155 // This means the extract is not influenced by the insert, and we can
2156 // replace the aggregate operand of the extract with the aggregate
2157 // operand of the insert. i.e., replace
2158 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2159 // %E = extractvalue { i32, { i32 } } %I, 0
2161 // %E = extractvalue { i32, { i32 } } %A, 0
2162 return ExtractValueInst::Create(IV->getAggregateOperand(),
2165 if (exti == exte && insi == inse)
2166 // Both iterators are at the end: Index lists are identical. Replace
2167 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2168 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2170 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2172 // The extract list is a prefix of the insert list. i.e. replace
2173 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2174 // %E = extractvalue { i32, { i32 } } %I, 1
2176 // %X = extractvalue { i32, { i32 } } %A, 1
2177 // %E = insertvalue { i32 } %X, i32 42, 0
2178 // by switching the order of the insert and extract (though the
2179 // insertvalue should be left in, since it may have other uses).
2180 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2182 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2183 makeArrayRef(insi, inse));
2186 // The insert list is a prefix of the extract list
2187 // We can simply remove the common indices from the extract and make it
2188 // operate on the inserted value instead of the insertvalue result.
2190 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2191 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2193 // %E extractvalue { i32 } { i32 42 }, 0
2194 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2195 makeArrayRef(exti, exte));
2197 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2198 // We're extracting from an intrinsic, see if we're the only user, which
2199 // allows us to simplify multiple result intrinsics to simpler things that
2200 // just get one value.
2201 if (II->hasOneUse()) {
2202 // Check if we're grabbing the overflow bit or the result of a 'with
2203 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2204 // and replace it with a traditional binary instruction.
2205 switch (II->getIntrinsicID()) {
2206 case Intrinsic::uadd_with_overflow:
2207 case Intrinsic::sadd_with_overflow:
2208 if (*EV.idx_begin() == 0) { // Normal result.
2209 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2210 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2211 EraseInstFromFunction(*II);
2212 return BinaryOperator::CreateAdd(LHS, RHS);
2215 // If the normal result of the add is dead, and the RHS is a constant,
2216 // we can transform this into a range comparison.
2217 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2218 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2219 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2220 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2221 ConstantExpr::getNot(CI));
2223 case Intrinsic::usub_with_overflow:
2224 case Intrinsic::ssub_with_overflow:
2225 if (*EV.idx_begin() == 0) { // Normal result.
2226 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2227 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2228 EraseInstFromFunction(*II);
2229 return BinaryOperator::CreateSub(LHS, RHS);
2232 case Intrinsic::umul_with_overflow:
2233 case Intrinsic::smul_with_overflow:
2234 if (*EV.idx_begin() == 0) { // Normal result.
2235 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2236 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2237 EraseInstFromFunction(*II);
2238 return BinaryOperator::CreateMul(LHS, RHS);
2246 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2247 // If the (non-volatile) load only has one use, we can rewrite this to a
2248 // load from a GEP. This reduces the size of the load.
2249 // FIXME: If a load is used only by extractvalue instructions then this
2250 // could be done regardless of having multiple uses.
2251 if (L->isSimple() && L->hasOneUse()) {
2252 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2253 SmallVector<Value*, 4> Indices;
2254 // Prefix an i32 0 since we need the first element.
2255 Indices.push_back(Builder->getInt32(0));
2256 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2258 Indices.push_back(Builder->getInt32(*I));
2260 // We need to insert these at the location of the old load, not at that of
2261 // the extractvalue.
2262 Builder->SetInsertPoint(L->getParent(), L);
2263 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2264 // Returning the load directly will cause the main loop to insert it in
2265 // the wrong spot, so use ReplaceInstUsesWith().
2266 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2268 // We could simplify extracts from other values. Note that nested extracts may
2269 // already be simplified implicitly by the above: extract (extract (insert) )
2270 // will be translated into extract ( insert ( extract ) ) first and then just
2271 // the value inserted, if appropriate. Similarly for extracts from single-use
2272 // loads: extract (extract (load)) will be translated to extract (load (gep))
2273 // and if again single-use then via load (gep (gep)) to load (gep).
2274 // However, double extracts from e.g. function arguments or return values
2275 // aren't handled yet.
2279 enum Personality_Type {
2280 Unknown_Personality,
2281 GNU_Ada_Personality,
2282 GNU_CXX_Personality,
2283 GNU_ObjC_Personality
2286 /// RecognizePersonality - See if the given exception handling personality
2287 /// function is one that we understand. If so, return a description of it;
2288 /// otherwise return Unknown_Personality.
2289 static Personality_Type RecognizePersonality(Value *Pers) {
2290 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2292 return Unknown_Personality;
2293 return StringSwitch<Personality_Type>(F->getName())
2294 .Case("__gnat_eh_personality", GNU_Ada_Personality)
2295 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2296 .Case("__objc_personality_v0", GNU_ObjC_Personality)
2297 .Default(Unknown_Personality);
2300 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2301 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2302 switch (Personality) {
2303 case Unknown_Personality:
2305 case GNU_Ada_Personality:
2306 // While __gnat_all_others_value will match any Ada exception, it doesn't
2307 // match foreign exceptions (or didn't, before gcc-4.7).
2309 case GNU_CXX_Personality:
2310 case GNU_ObjC_Personality:
2311 return TypeInfo->isNullValue();
2313 llvm_unreachable("Unknown personality!");
2316 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2318 cast<ArrayType>(LHS->getType())->getNumElements()
2320 cast<ArrayType>(RHS->getType())->getNumElements();
2323 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2324 // The logic here should be correct for any real-world personality function.
2325 // However if that turns out not to be true, the offending logic can always
2326 // be conditioned on the personality function, like the catch-all logic is.
2327 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2329 // Simplify the list of clauses, eg by removing repeated catch clauses
2330 // (these are often created by inlining).
2331 bool MakeNewInstruction = false; // If true, recreate using the following:
2332 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2333 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2335 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2336 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2337 bool isLastClause = i + 1 == e;
2338 if (LI.isCatch(i)) {
2340 Constant *CatchClause = LI.getClause(i);
2341 Constant *TypeInfo = CatchClause->stripPointerCasts();
2343 // If we already saw this clause, there is no point in having a second
2345 if (AlreadyCaught.insert(TypeInfo)) {
2346 // This catch clause was not already seen.
2347 NewClauses.push_back(CatchClause);
2349 // Repeated catch clause - drop the redundant copy.
2350 MakeNewInstruction = true;
2353 // If this is a catch-all then there is no point in keeping any following
2354 // clauses or marking the landingpad as having a cleanup.
2355 if (isCatchAll(Personality, TypeInfo)) {
2357 MakeNewInstruction = true;
2358 CleanupFlag = false;
2362 // A filter clause. If any of the filter elements were already caught
2363 // then they can be dropped from the filter. It is tempting to try to
2364 // exploit the filter further by saying that any typeinfo that does not
2365 // occur in the filter can't be caught later (and thus can be dropped).
2366 // However this would be wrong, since typeinfos can match without being
2367 // equal (for example if one represents a C++ class, and the other some
2368 // class derived from it).
2369 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2370 Constant *FilterClause = LI.getClause(i);
2371 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2372 unsigned NumTypeInfos = FilterType->getNumElements();
2374 // An empty filter catches everything, so there is no point in keeping any
2375 // following clauses or marking the landingpad as having a cleanup. By
2376 // dealing with this case here the following code is made a bit simpler.
2377 if (!NumTypeInfos) {
2378 NewClauses.push_back(FilterClause);
2380 MakeNewInstruction = true;
2381 CleanupFlag = false;
2385 bool MakeNewFilter = false; // If true, make a new filter.
2386 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2387 if (isa<ConstantAggregateZero>(FilterClause)) {
2388 // Not an empty filter - it contains at least one null typeinfo.
2389 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2390 Constant *TypeInfo =
2391 Constant::getNullValue(FilterType->getElementType());
2392 // If this typeinfo is a catch-all then the filter can never match.
2393 if (isCatchAll(Personality, TypeInfo)) {
2394 // Throw the filter away.
2395 MakeNewInstruction = true;
2399 // There is no point in having multiple copies of this typeinfo, so
2400 // discard all but the first copy if there is more than one.
2401 NewFilterElts.push_back(TypeInfo);
2402 if (NumTypeInfos > 1)
2403 MakeNewFilter = true;
2405 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2406 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2407 NewFilterElts.reserve(NumTypeInfos);
2409 // Remove any filter elements that were already caught or that already
2410 // occurred in the filter. While there, see if any of the elements are
2411 // catch-alls. If so, the filter can be discarded.
2412 bool SawCatchAll = false;
2413 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2414 Constant *Elt = Filter->getOperand(j);
2415 Constant *TypeInfo = Elt->stripPointerCasts();
2416 if (isCatchAll(Personality, TypeInfo)) {
2417 // This element is a catch-all. Bail out, noting this fact.
2421 if (AlreadyCaught.count(TypeInfo))
2422 // Already caught by an earlier clause, so having it in the filter
2425 // There is no point in having multiple copies of the same typeinfo in
2426 // a filter, so only add it if we didn't already.
2427 if (SeenInFilter.insert(TypeInfo))
2428 NewFilterElts.push_back(cast<Constant>(Elt));
2430 // A filter containing a catch-all cannot match anything by definition.
2432 // Throw the filter away.
2433 MakeNewInstruction = true;
2437 // If we dropped something from the filter, make a new one.
2438 if (NewFilterElts.size() < NumTypeInfos)
2439 MakeNewFilter = true;
2441 if (MakeNewFilter) {
2442 FilterType = ArrayType::get(FilterType->getElementType(),
2443 NewFilterElts.size());
2444 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2445 MakeNewInstruction = true;
2448 NewClauses.push_back(FilterClause);
2450 // If the new filter is empty then it will catch everything so there is
2451 // no point in keeping any following clauses or marking the landingpad
2452 // as having a cleanup. The case of the original filter being empty was
2453 // already handled above.
2454 if (MakeNewFilter && !NewFilterElts.size()) {
2455 assert(MakeNewInstruction && "New filter but not a new instruction!");
2456 CleanupFlag = false;
2462 // If several filters occur in a row then reorder them so that the shortest
2463 // filters come first (those with the smallest number of elements). This is
2464 // advantageous because shorter filters are more likely to match, speeding up
2465 // unwinding, but mostly because it increases the effectiveness of the other
2466 // filter optimizations below.
2467 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2469 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2470 for (j = i; j != e; ++j)
2471 if (!isa<ArrayType>(NewClauses[j]->getType()))
2474 // Check whether the filters are already sorted by length. We need to know
2475 // if sorting them is actually going to do anything so that we only make a
2476 // new landingpad instruction if it does.
2477 for (unsigned k = i; k + 1 < j; ++k)
2478 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2479 // Not sorted, so sort the filters now. Doing an unstable sort would be
2480 // correct too but reordering filters pointlessly might confuse users.
2481 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2483 MakeNewInstruction = true;
2487 // Look for the next batch of filters.
2491 // If typeinfos matched if and only if equal, then the elements of a filter L
2492 // that occurs later than a filter F could be replaced by the intersection of
2493 // the elements of F and L. In reality two typeinfos can match without being
2494 // equal (for example if one represents a C++ class, and the other some class
2495 // derived from it) so it would be wrong to perform this transform in general.
2496 // However the transform is correct and useful if F is a subset of L. In that
2497 // case L can be replaced by F, and thus removed altogether since repeating a
2498 // filter is pointless. So here we look at all pairs of filters F and L where
2499 // L follows F in the list of clauses, and remove L if every element of F is
2500 // an element of L. This can occur when inlining C++ functions with exception
2502 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2503 // Examine each filter in turn.
2504 Value *Filter = NewClauses[i];
2505 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2507 // Not a filter - skip it.
2509 unsigned FElts = FTy->getNumElements();
2510 // Examine each filter following this one. Doing this backwards means that
2511 // we don't have to worry about filters disappearing under us when removed.
2512 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2513 Value *LFilter = NewClauses[j];
2514 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2516 // Not a filter - skip it.
2518 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2519 // an element of LFilter, then discard LFilter.
2520 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2521 // If Filter is empty then it is a subset of LFilter.
2524 NewClauses.erase(J);
2525 MakeNewInstruction = true;
2526 // Move on to the next filter.
2529 unsigned LElts = LTy->getNumElements();
2530 // If Filter is longer than LFilter then it cannot be a subset of it.
2532 // Move on to the next filter.
2534 // At this point we know that LFilter has at least one element.
2535 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2536 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2537 // already know that Filter is not longer than LFilter).
2538 if (isa<ConstantAggregateZero>(Filter)) {
2539 assert(FElts <= LElts && "Should have handled this case earlier!");
2541 NewClauses.erase(J);
2542 MakeNewInstruction = true;
2544 // Move on to the next filter.
2547 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2548 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2549 // Since Filter is non-empty and contains only zeros, it is a subset of
2550 // LFilter iff LFilter contains a zero.
2551 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2552 for (unsigned l = 0; l != LElts; ++l)
2553 if (LArray->getOperand(l)->isNullValue()) {
2554 // LFilter contains a zero - discard it.
2555 NewClauses.erase(J);
2556 MakeNewInstruction = true;
2559 // Move on to the next filter.
2562 // At this point we know that both filters are ConstantArrays. Loop over
2563 // operands to see whether every element of Filter is also an element of
2564 // LFilter. Since filters tend to be short this is probably faster than
2565 // using a method that scales nicely.
2566 ConstantArray *FArray = cast<ConstantArray>(Filter);
2567 bool AllFound = true;
2568 for (unsigned f = 0; f != FElts; ++f) {
2569 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2571 for (unsigned l = 0; l != LElts; ++l) {
2572 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2573 if (LTypeInfo == FTypeInfo) {
2583 NewClauses.erase(J);
2584 MakeNewInstruction = true;
2586 // Move on to the next filter.
2590 // If we changed any of the clauses, replace the old landingpad instruction
2592 if (MakeNewInstruction) {
2593 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2594 LI.getPersonalityFn(),
2596 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2597 NLI->addClause(NewClauses[i]);
2598 // A landing pad with no clauses must have the cleanup flag set. It is
2599 // theoretically possible, though highly unlikely, that we eliminated all
2600 // clauses. If so, force the cleanup flag to true.
2601 if (NewClauses.empty())
2603 NLI->setCleanup(CleanupFlag);
2607 // Even if none of the clauses changed, we may nonetheless have understood
2608 // that the cleanup flag is pointless. Clear it if so.
2609 if (LI.isCleanup() != CleanupFlag) {
2610 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2611 LI.setCleanup(CleanupFlag);
2621 /// TryToSinkInstruction - Try to move the specified instruction from its
2622 /// current block into the beginning of DestBlock, which can only happen if it's
2623 /// safe to move the instruction past all of the instructions between it and the
2624 /// end of its block.
2625 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2626 assert(I->hasOneUse() && "Invariants didn't hold!");
2628 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2629 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2630 isa<TerminatorInst>(I))
2633 // Do not sink alloca instructions out of the entry block.
2634 if (isa<AllocaInst>(I) && I->getParent() ==
2635 &DestBlock->getParent()->getEntryBlock())
2638 // We can only sink load instructions if there is nothing between the load and
2639 // the end of block that could change the value.
2640 if (I->mayReadFromMemory()) {
2641 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2643 if (Scan->mayWriteToMemory())
2647 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2648 I->moveBefore(InsertPos);
2654 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2655 /// all reachable code to the worklist.
2657 /// This has a couple of tricks to make the code faster and more powerful. In
2658 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2659 /// them to the worklist (this significantly speeds up instcombine on code where
2660 /// many instructions are dead or constant). Additionally, if we find a branch
2661 /// whose condition is a known constant, we only visit the reachable successors.
2663 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2664 SmallPtrSetImpl<BasicBlock*> &Visited,
2666 const DataLayout *DL,
2667 const TargetLibraryInfo *TLI) {
2668 bool MadeIRChange = false;
2669 SmallVector<BasicBlock*, 256> Worklist;
2670 Worklist.push_back(BB);
2672 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2673 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2676 BB = Worklist.pop_back_val();
2678 // We have now visited this block! If we've already been here, ignore it.
2679 if (!Visited.insert(BB)) continue;
2681 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2682 Instruction *Inst = BBI++;
2684 // DCE instruction if trivially dead.
2685 if (isInstructionTriviallyDead(Inst, TLI)) {
2687 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2688 Inst->eraseFromParent();
2692 // ConstantProp instruction if trivially constant.
2693 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2694 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2695 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2697 Inst->replaceAllUsesWith(C);
2699 Inst->eraseFromParent();
2704 // See if we can constant fold its operands.
2705 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2707 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2708 if (CE == nullptr) continue;
2710 Constant*& FoldRes = FoldedConstants[CE];
2712 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2716 if (FoldRes != CE) {
2718 MadeIRChange = true;
2723 InstrsForInstCombineWorklist.push_back(Inst);
2726 // Recursively visit successors. If this is a branch or switch on a
2727 // constant, only visit the reachable successor.
2728 TerminatorInst *TI = BB->getTerminator();
2729 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2730 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2731 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2732 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2733 Worklist.push_back(ReachableBB);
2736 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2737 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2738 // See if this is an explicit destination.
2739 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2741 if (i.getCaseValue() == Cond) {
2742 BasicBlock *ReachableBB = i.getCaseSuccessor();
2743 Worklist.push_back(ReachableBB);
2747 // Otherwise it is the default destination.
2748 Worklist.push_back(SI->getDefaultDest());
2753 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2754 Worklist.push_back(TI->getSuccessor(i));
2755 } while (!Worklist.empty());
2757 // Once we've found all of the instructions to add to instcombine's worklist,
2758 // add them in reverse order. This way instcombine will visit from the top
2759 // of the function down. This jives well with the way that it adds all uses
2760 // of instructions to the worklist after doing a transformation, thus avoiding
2761 // some N^2 behavior in pathological cases.
2762 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2763 InstrsForInstCombineWorklist.size());
2765 return MadeIRChange;
2768 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2769 MadeIRChange = false;
2771 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2772 << F.getName() << "\n");
2775 // Do a depth-first traversal of the function, populate the worklist with
2776 // the reachable instructions. Ignore blocks that are not reachable. Keep
2777 // track of which blocks we visit.
2778 SmallPtrSet<BasicBlock*, 64> Visited;
2779 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
2782 // Do a quick scan over the function. If we find any blocks that are
2783 // unreachable, remove any instructions inside of them. This prevents
2784 // the instcombine code from having to deal with some bad special cases.
2785 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2786 if (Visited.count(BB)) continue;
2788 // Delete the instructions backwards, as it has a reduced likelihood of
2789 // having to update as many def-use and use-def chains.
2790 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2791 while (EndInst != BB->begin()) {
2792 // Delete the next to last instruction.
2793 BasicBlock::iterator I = EndInst;
2794 Instruction *Inst = --I;
2795 if (!Inst->use_empty())
2796 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2797 if (isa<LandingPadInst>(Inst)) {
2801 if (!isa<DbgInfoIntrinsic>(Inst)) {
2803 MadeIRChange = true;
2805 Inst->eraseFromParent();
2810 while (!Worklist.isEmpty()) {
2811 Instruction *I = Worklist.RemoveOne();
2812 if (I == nullptr) continue; // skip null values.
2814 // Check to see if we can DCE the instruction.
2815 if (isInstructionTriviallyDead(I, TLI)) {
2816 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2817 EraseInstFromFunction(*I);
2819 MadeIRChange = true;
2823 // Instruction isn't dead, see if we can constant propagate it.
2824 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2825 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2826 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2828 // Add operands to the worklist.
2829 ReplaceInstUsesWith(*I, C);
2831 EraseInstFromFunction(*I);
2832 MadeIRChange = true;
2836 // See if we can trivially sink this instruction to a successor basic block.
2837 if (I->hasOneUse()) {
2838 BasicBlock *BB = I->getParent();
2839 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2840 BasicBlock *UserParent;
2842 // Get the block the use occurs in.
2843 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2844 UserParent = PN->getIncomingBlock(*I->use_begin());
2846 UserParent = UserInst->getParent();
2848 if (UserParent != BB) {
2849 bool UserIsSuccessor = false;
2850 // See if the user is one of our successors.
2851 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2852 if (*SI == UserParent) {
2853 UserIsSuccessor = true;
2857 // If the user is one of our immediate successors, and if that successor
2858 // only has us as a predecessors (we'd have to split the critical edge
2859 // otherwise), we can keep going.
2860 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2861 // Okay, the CFG is simple enough, try to sink this instruction.
2862 if (TryToSinkInstruction(I, UserParent)) {
2863 MadeIRChange = true;
2864 // We'll add uses of the sunk instruction below, but since sinking
2865 // can expose opportunities for it's *operands* add them to the
2867 for (Use &U : I->operands())
2868 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2875 // Now that we have an instruction, try combining it to simplify it.
2876 Builder->SetInsertPoint(I->getParent(), I);
2877 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2882 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2883 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2885 if (Instruction *Result = visit(*I)) {
2887 // Should we replace the old instruction with a new one?
2889 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2890 << " New = " << *Result << '\n');
2892 if (!I->getDebugLoc().isUnknown())
2893 Result->setDebugLoc(I->getDebugLoc());
2894 // Everything uses the new instruction now.
2895 I->replaceAllUsesWith(Result);
2897 // Move the name to the new instruction first.
2898 Result->takeName(I);
2900 // Push the new instruction and any users onto the worklist.
2901 Worklist.Add(Result);
2902 Worklist.AddUsersToWorkList(*Result);
2904 // Insert the new instruction into the basic block...
2905 BasicBlock *InstParent = I->getParent();
2906 BasicBlock::iterator InsertPos = I;
2908 // If we replace a PHI with something that isn't a PHI, fix up the
2910 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2911 InsertPos = InstParent->getFirstInsertionPt();
2913 InstParent->getInstList().insert(InsertPos, Result);
2915 EraseInstFromFunction(*I);
2918 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2919 << " New = " << *I << '\n');
2922 // If the instruction was modified, it's possible that it is now dead.
2923 // if so, remove it.
2924 if (isInstructionTriviallyDead(I, TLI)) {
2925 EraseInstFromFunction(*I);
2928 Worklist.AddUsersToWorkList(*I);
2931 MadeIRChange = true;
2936 return MadeIRChange;
2940 class InstCombinerLibCallSimplifier final : public LibCallSimplifier {
2943 InstCombinerLibCallSimplifier(const DataLayout *DL,
2944 const TargetLibraryInfo *TLI,
2946 : LibCallSimplifier(DL, TLI) {
2950 /// replaceAllUsesWith - override so that instruction replacement
2951 /// can be defined in terms of the instruction combiner framework.
2952 void replaceAllUsesWith(Instruction *I, Value *With) const override {
2953 IC->ReplaceInstUsesWith(*I, With);
2958 bool InstCombiner::runOnFunction(Function &F) {
2959 if (skipOptnoneFunction(F))
2962 AT = &getAnalysis<AssumptionTracker>();
2963 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2964 DL = DLP ? &DLP->getDataLayout() : nullptr;
2965 TLI = &getAnalysis<TargetLibraryInfo>();
2967 DominatorTreeWrapperPass *DTWP =
2968 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2969 DT = DTWP ? &DTWP->getDomTree() : nullptr;
2972 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2973 Attribute::MinSize);
2975 /// Builder - This is an IRBuilder that automatically inserts new
2976 /// instructions into the worklist when they are created.
2977 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2978 TheBuilder(F.getContext(), TargetFolder(DL),
2979 InstCombineIRInserter(Worklist, AT));
2980 Builder = &TheBuilder;
2982 InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
2983 Simplifier = &TheSimplifier;
2985 bool EverMadeChange = false;
2987 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2989 EverMadeChange = LowerDbgDeclare(F);
2991 // Iterate while there is work to do.
2992 unsigned Iteration = 0;
2993 while (DoOneIteration(F, Iteration++))
2994 EverMadeChange = true;
2997 return EverMadeChange;
3000 FunctionPass *llvm::createInstructionCombiningPass() {
3001 return new InstCombiner();