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/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/IR/CFG.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/Dominators.h"
50 #include "llvm/IR/GetElementPtrTypeIterator.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/PatternMatch.h"
53 #include "llvm/IR/ValueHandle.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Target/TargetLibraryInfo.h"
57 #include "llvm/Transforms/Utils/Local.h"
61 using namespace llvm::PatternMatch;
63 #define DEBUG_TYPE "instcombine"
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
69 STATISTIC(NumExpand, "Number of expansions");
70 STATISTIC(NumFactor , "Number of factorizations");
71 STATISTIC(NumReassoc , "Number of reassociations");
73 // Initialization Routines
74 void llvm::initializeInstCombine(PassRegistry &Registry) {
75 initializeInstCombinerPass(Registry);
78 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
79 initializeInstCombine(*unwrap(R));
82 char InstCombiner::ID = 0;
83 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
84 "Combine redundant instructions", false, false)
85 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
86 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
87 INITIALIZE_PASS_END(InstCombiner, "instcombine",
88 "Combine redundant instructions", false, false)
90 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<AssumptionTracker>();
93 AU.addRequired<TargetLibraryInfo>();
97 Value *InstCombiner::EmitGEPOffset(User *GEP) {
98 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
101 /// ShouldChangeType - Return true if it is desirable to convert a computation
102 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
103 /// type for example, or from a smaller to a larger illegal type.
104 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
105 assert(From->isIntegerTy() && To->isIntegerTy());
107 // If we don't have DL, we don't know if the source/dest are legal.
108 if (!DL) return false;
110 unsigned FromWidth = From->getPrimitiveSizeInBits();
111 unsigned ToWidth = To->getPrimitiveSizeInBits();
112 bool FromLegal = DL->isLegalInteger(FromWidth);
113 bool ToLegal = DL->isLegalInteger(ToWidth);
115 // If this is a legal integer from type, and the result would be an illegal
116 // type, don't do the transformation.
117 if (FromLegal && !ToLegal)
120 // Otherwise, if both are illegal, do not increase the size of the result. We
121 // do allow things like i160 -> i64, but not i64 -> i160.
122 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
128 // Return true, if No Signed Wrap should be maintained for I.
129 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
130 // where both B and C should be ConstantInts, results in a constant that does
131 // not overflow. This function only handles the Add and Sub opcodes. For
132 // all other opcodes, the function conservatively returns false.
133 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
134 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
135 if (!OBO || !OBO->hasNoSignedWrap()) {
139 // We reason about Add and Sub Only.
140 Instruction::BinaryOps Opcode = I.getOpcode();
141 if (Opcode != Instruction::Add &&
142 Opcode != Instruction::Sub) {
146 ConstantInt *CB = dyn_cast<ConstantInt>(B);
147 ConstantInt *CC = dyn_cast<ConstantInt>(C);
153 const APInt &BVal = CB->getValue();
154 const APInt &CVal = CC->getValue();
155 bool Overflow = false;
157 if (Opcode == Instruction::Add) {
158 BVal.sadd_ov(CVal, Overflow);
160 BVal.ssub_ov(CVal, Overflow);
166 /// Conservatively clears subclassOptionalData after a reassociation or
167 /// commutation. We preserve fast-math flags when applicable as they can be
169 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
170 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
172 I.clearSubclassOptionalData();
176 FastMathFlags FMF = I.getFastMathFlags();
177 I.clearSubclassOptionalData();
178 I.setFastMathFlags(FMF);
181 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
182 /// operators which are associative or commutative:
184 // Commutative operators:
186 // 1. Order operands such that they are listed from right (least complex) to
187 // left (most complex). This puts constants before unary operators before
190 // Associative operators:
192 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
193 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
195 // Associative and commutative operators:
197 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
198 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
199 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
200 // if C1 and C2 are constants.
202 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
203 Instruction::BinaryOps Opcode = I.getOpcode();
204 bool Changed = false;
207 // Order operands such that they are listed from right (least complex) to
208 // left (most complex). This puts constants before unary operators before
210 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
211 getComplexity(I.getOperand(1)))
212 Changed = !I.swapOperands();
214 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
215 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
217 if (I.isAssociative()) {
218 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
219 if (Op0 && Op0->getOpcode() == Opcode) {
220 Value *A = Op0->getOperand(0);
221 Value *B = Op0->getOperand(1);
222 Value *C = I.getOperand(1);
224 // Does "B op C" simplify?
225 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
226 // It simplifies to V. Form "A op V".
229 // Conservatively clear the optional flags, since they may not be
230 // preserved by the reassociation.
231 if (MaintainNoSignedWrap(I, B, C) &&
232 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
233 // Note: this is only valid because SimplifyBinOp doesn't look at
234 // the operands to Op0.
235 I.clearSubclassOptionalData();
236 I.setHasNoSignedWrap(true);
238 ClearSubclassDataAfterReassociation(I);
247 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
248 if (Op1 && Op1->getOpcode() == Opcode) {
249 Value *A = I.getOperand(0);
250 Value *B = Op1->getOperand(0);
251 Value *C = Op1->getOperand(1);
253 // Does "A op B" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
255 // It simplifies to V. Form "V op C".
258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
260 ClearSubclassDataAfterReassociation(I);
268 if (I.isAssociative() && I.isCommutative()) {
269 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
270 if (Op0 && Op0->getOpcode() == Opcode) {
271 Value *A = Op0->getOperand(0);
272 Value *B = Op0->getOperand(1);
273 Value *C = I.getOperand(1);
275 // Does "C op A" simplify?
276 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
277 // It simplifies to V. Form "V op B".
280 // Conservatively clear the optional flags, since they may not be
281 // preserved by the reassociation.
282 ClearSubclassDataAfterReassociation(I);
289 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
290 if (Op1 && Op1->getOpcode() == Opcode) {
291 Value *A = I.getOperand(0);
292 Value *B = Op1->getOperand(0);
293 Value *C = Op1->getOperand(1);
295 // Does "C op A" simplify?
296 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
297 // It simplifies to V. Form "B op V".
300 // Conservatively clear the optional flags, since they may not be
301 // preserved by the reassociation.
302 ClearSubclassDataAfterReassociation(I);
309 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
310 // if C1 and C2 are constants.
312 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
313 isa<Constant>(Op0->getOperand(1)) &&
314 isa<Constant>(Op1->getOperand(1)) &&
315 Op0->hasOneUse() && Op1->hasOneUse()) {
316 Value *A = Op0->getOperand(0);
317 Constant *C1 = cast<Constant>(Op0->getOperand(1));
318 Value *B = Op1->getOperand(0);
319 Constant *C2 = cast<Constant>(Op1->getOperand(1));
321 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
322 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
323 if (isa<FPMathOperator>(New)) {
324 FastMathFlags Flags = I.getFastMathFlags();
325 Flags &= Op0->getFastMathFlags();
326 Flags &= Op1->getFastMathFlags();
327 New->setFastMathFlags(Flags);
329 InsertNewInstWith(New, I);
331 I.setOperand(0, New);
332 I.setOperand(1, Folded);
333 // Conservatively clear the optional flags, since they may not be
334 // preserved by the reassociation.
335 ClearSubclassDataAfterReassociation(I);
342 // No further simplifications.
347 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
348 /// "(X LOp Y) ROp (X LOp Z)".
349 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
350 Instruction::BinaryOps ROp) {
355 case Instruction::And:
356 // And distributes over Or and Xor.
360 case Instruction::Or:
361 case Instruction::Xor:
365 case Instruction::Mul:
366 // Multiplication distributes over addition and subtraction.
370 case Instruction::Add:
371 case Instruction::Sub:
375 case Instruction::Or:
376 // Or distributes over And.
380 case Instruction::And:
386 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
387 /// "(X ROp Z) LOp (Y ROp Z)".
388 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
389 Instruction::BinaryOps ROp) {
390 if (Instruction::isCommutative(ROp))
391 return LeftDistributesOverRight(ROp, LOp);
396 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
397 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
398 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
399 case Instruction::And:
400 case Instruction::Or:
401 case Instruction::Xor:
405 case Instruction::Shl:
406 case Instruction::LShr:
407 case Instruction::AShr:
411 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
412 // but this requires knowing that the addition does not overflow and other
417 /// This function returns identity value for given opcode, which can be used to
418 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
419 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
420 if (isa<Constant>(V))
423 if (OpCode == Instruction::Mul)
424 return ConstantInt::get(V->getType(), 1);
426 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
431 /// This function factors binary ops which can be combined using distributive
432 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
433 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
434 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
435 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
437 static Instruction::BinaryOps
438 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
439 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
441 return Instruction::BinaryOpsEnd;
443 LHS = Op->getOperand(0);
444 RHS = Op->getOperand(1);
446 switch (TopLevelOpcode) {
448 return Op->getOpcode();
450 case Instruction::Add:
451 case Instruction::Sub:
452 if (Op->getOpcode() == Instruction::Shl) {
453 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
454 // The multiplier is really 1 << CST.
455 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
456 return Instruction::Mul;
459 return Op->getOpcode();
462 // TODO: We can add other conversions e.g. shr => div etc.
465 /// This tries to simplify binary operations by factorizing out common terms
466 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
467 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
468 const DataLayout *DL, BinaryOperator &I,
469 Instruction::BinaryOps InnerOpcode, Value *A,
470 Value *B, Value *C, Value *D) {
472 // If any of A, B, C, D are null, we can not factor I, return early.
473 // Checking A and C should be enough.
474 if (!A || !C || !B || !D)
477 Value *SimplifiedInst = nullptr;
478 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
479 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
481 // Does "X op' Y" always equal "Y op' X"?
482 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
484 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
485 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
486 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
487 // commutative case, "(A op' B) op (C op' A)"?
488 if (A == C || (InnerCommutative && A == D)) {
491 // Consider forming "A op' (B op D)".
492 // If "B op D" simplifies then it can be formed with no cost.
493 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
494 // If "B op D" doesn't simplify then only go on if both of the existing
495 // operations "A op' B" and "C op' D" will be zapped as no longer used.
496 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
497 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
499 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
503 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
504 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
505 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
506 // commutative case, "(A op' B) op (B op' D)"?
507 if (B == D || (InnerCommutative && B == C)) {
510 // Consider forming "(A op C) op' B".
511 // If "A op C" simplifies then it can be formed with no cost.
512 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
514 // If "A op C" doesn't simplify then only go on if both of the existing
515 // operations "A op' B" and "C op' D" will be zapped as no longer used.
516 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
517 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
519 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
523 if (SimplifiedInst) {
525 SimplifiedInst->takeName(&I);
527 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
528 // TODO: Check for NUW.
529 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
530 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
532 if (isa<OverflowingBinaryOperator>(&I))
533 HasNSW = I.hasNoSignedWrap();
535 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
536 if (isa<OverflowingBinaryOperator>(Op0))
537 HasNSW &= Op0->hasNoSignedWrap();
539 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
540 if (isa<OverflowingBinaryOperator>(Op1))
541 HasNSW &= Op1->hasNoSignedWrap();
542 BO->setHasNoSignedWrap(HasNSW);
546 return SimplifiedInst;
549 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
550 /// which some other binary operation distributes over either by factorizing
551 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
552 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
553 /// a win). Returns the simplified value, or null if it didn't simplify.
554 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
555 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
556 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
557 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
560 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
561 auto TopLevelOpcode = I.getOpcode();
562 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
563 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
565 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
567 if (LHSOpcode == RHSOpcode) {
568 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
572 // The instruction has the form "(A op' B) op (C)". Try to factorize common
574 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
575 getIdentityValue(LHSOpcode, RHS)))
578 // The instruction has the form "(B) op (C op' D)". Try to factorize common
580 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
581 getIdentityValue(RHSOpcode, LHS), C, D))
585 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
586 // The instruction has the form "(A op' B) op C". See if expanding it out
587 // to "(A op C) op' (B op C)" results in simplifications.
588 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
589 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
591 // Do "A op C" and "B op C" both simplify?
592 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
593 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
594 // They do! Return "L op' R".
596 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
597 if ((L == A && R == B) ||
598 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
600 // Otherwise return "L op' R" if it simplifies.
601 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
603 // Otherwise, create a new instruction.
604 C = Builder->CreateBinOp(InnerOpcode, L, R);
610 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
611 // The instruction has the form "A op (B op' C)". See if expanding it out
612 // to "(A op B) op' (A op C)" results in simplifications.
613 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
614 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
616 // Do "A op B" and "A op C" both simplify?
617 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
618 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
619 // They do! Return "L op' R".
621 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
622 if ((L == B && R == C) ||
623 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
625 // Otherwise return "L op' R" if it simplifies.
626 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
628 // Otherwise, create a new instruction.
629 A = Builder->CreateBinOp(InnerOpcode, L, R);
638 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
639 // if the LHS is a constant zero (which is the 'negate' form).
641 Value *InstCombiner::dyn_castNegVal(Value *V) const {
642 if (BinaryOperator::isNeg(V))
643 return BinaryOperator::getNegArgument(V);
645 // Constants can be considered to be negated values if they can be folded.
646 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
647 return ConstantExpr::getNeg(C);
649 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
650 if (C->getType()->getElementType()->isIntegerTy())
651 return ConstantExpr::getNeg(C);
656 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
657 // instruction if the LHS is a constant negative zero (which is the 'negate'
660 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
661 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
662 return BinaryOperator::getFNegArgument(V);
664 // Constants can be considered to be negated values if they can be folded.
665 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
666 return ConstantExpr::getFNeg(C);
668 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
669 if (C->getType()->getElementType()->isFloatingPointTy())
670 return ConstantExpr::getFNeg(C);
675 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
677 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
678 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
681 // Figure out if the constant is the left or the right argument.
682 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
683 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
685 if (Constant *SOC = dyn_cast<Constant>(SO)) {
687 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
688 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
691 Value *Op0 = SO, *Op1 = ConstOperand;
695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
696 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
697 SO->getName()+".op");
698 Instruction *FPInst = dyn_cast<Instruction>(RI);
699 if (FPInst && isa<FPMathOperator>(FPInst))
700 FPInst->copyFastMathFlags(BO);
703 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
704 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
705 SO->getName()+".cmp");
706 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
707 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
708 SO->getName()+".cmp");
709 llvm_unreachable("Unknown binary instruction type!");
712 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
713 // constant as the other operand, try to fold the binary operator into the
714 // select arguments. This also works for Cast instructions, which obviously do
715 // not have a second operand.
716 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
717 // Don't modify shared select instructions
718 if (!SI->hasOneUse()) return nullptr;
719 Value *TV = SI->getOperand(1);
720 Value *FV = SI->getOperand(2);
722 if (isa<Constant>(TV) || isa<Constant>(FV)) {
723 // Bool selects with constant operands can be folded to logical ops.
724 if (SI->getType()->isIntegerTy(1)) return nullptr;
726 // If it's a bitcast involving vectors, make sure it has the same number of
727 // elements on both sides.
728 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
729 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
730 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
732 // Verify that either both or neither are vectors.
733 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
734 // If vectors, verify that they have the same number of elements.
735 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
739 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
740 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
742 return SelectInst::Create(SI->getCondition(),
743 SelectTrueVal, SelectFalseVal);
749 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
750 /// has a PHI node as operand #0, see if we can fold the instruction into the
751 /// PHI (which is only possible if all operands to the PHI are constants).
753 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
754 PHINode *PN = cast<PHINode>(I.getOperand(0));
755 unsigned NumPHIValues = PN->getNumIncomingValues();
756 if (NumPHIValues == 0)
759 // We normally only transform phis with a single use. However, if a PHI has
760 // multiple uses and they are all the same operation, we can fold *all* of the
761 // uses into the PHI.
762 if (!PN->hasOneUse()) {
763 // Walk the use list for the instruction, comparing them to I.
764 for (User *U : PN->users()) {
765 Instruction *UI = cast<Instruction>(U);
766 if (UI != &I && !I.isIdenticalTo(UI))
769 // Otherwise, we can replace *all* users with the new PHI we form.
772 // Check to see if all of the operands of the PHI are simple constants
773 // (constantint/constantfp/undef). If there is one non-constant value,
774 // remember the BB it is in. If there is more than one or if *it* is a PHI,
775 // bail out. We don't do arbitrary constant expressions here because moving
776 // their computation can be expensive without a cost model.
777 BasicBlock *NonConstBB = nullptr;
778 for (unsigned i = 0; i != NumPHIValues; ++i) {
779 Value *InVal = PN->getIncomingValue(i);
780 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
783 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
784 if (NonConstBB) return nullptr; // More than one non-const value.
786 NonConstBB = PN->getIncomingBlock(i);
788 // If the InVal is an invoke at the end of the pred block, then we can't
789 // insert a computation after it without breaking the edge.
790 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
791 if (II->getParent() == NonConstBB)
794 // If the incoming non-constant value is in I's block, we will remove one
795 // instruction, but insert another equivalent one, leading to infinite
797 if (NonConstBB == I.getParent())
801 // If there is exactly one non-constant value, we can insert a copy of the
802 // operation in that block. However, if this is a critical edge, we would be
803 // inserting the computation one some other paths (e.g. inside a loop). Only
804 // do this if the pred block is unconditionally branching into the phi block.
805 if (NonConstBB != nullptr) {
806 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
807 if (!BI || !BI->isUnconditional()) return nullptr;
810 // Okay, we can do the transformation: create the new PHI node.
811 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
812 InsertNewInstBefore(NewPN, *PN);
815 // If we are going to have to insert a new computation, do so right before the
816 // predecessors terminator.
818 Builder->SetInsertPoint(NonConstBB->getTerminator());
820 // Next, add all of the operands to the PHI.
821 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
822 // We only currently try to fold the condition of a select when it is a phi,
823 // not the true/false values.
824 Value *TrueV = SI->getTrueValue();
825 Value *FalseV = SI->getFalseValue();
826 BasicBlock *PhiTransBB = PN->getParent();
827 for (unsigned i = 0; i != NumPHIValues; ++i) {
828 BasicBlock *ThisBB = PN->getIncomingBlock(i);
829 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
830 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
831 Value *InV = nullptr;
832 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
833 // even if currently isNullValue gives false.
834 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
835 if (InC && !isa<ConstantExpr>(InC))
836 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
838 InV = Builder->CreateSelect(PN->getIncomingValue(i),
839 TrueVInPred, FalseVInPred, "phitmp");
840 NewPN->addIncoming(InV, ThisBB);
842 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
843 Constant *C = cast<Constant>(I.getOperand(1));
844 for (unsigned i = 0; i != NumPHIValues; ++i) {
845 Value *InV = nullptr;
846 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
847 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
848 else if (isa<ICmpInst>(CI))
849 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
852 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
854 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
856 } else if (I.getNumOperands() == 2) {
857 Constant *C = cast<Constant>(I.getOperand(1));
858 for (unsigned i = 0; i != NumPHIValues; ++i) {
859 Value *InV = nullptr;
860 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
861 InV = ConstantExpr::get(I.getOpcode(), InC, C);
863 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
864 PN->getIncomingValue(i), C, "phitmp");
865 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
868 CastInst *CI = cast<CastInst>(&I);
869 Type *RetTy = CI->getType();
870 for (unsigned i = 0; i != NumPHIValues; ++i) {
872 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
873 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
875 InV = Builder->CreateCast(CI->getOpcode(),
876 PN->getIncomingValue(i), I.getType(), "phitmp");
877 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
881 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
882 Instruction *User = cast<Instruction>(*UI++);
883 if (User == &I) continue;
884 ReplaceInstUsesWith(*User, NewPN);
885 EraseInstFromFunction(*User);
887 return ReplaceInstUsesWith(I, NewPN);
890 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
891 /// whether or not there is a sequence of GEP indices into the pointed type that
892 /// will land us at the specified offset. If so, fill them into NewIndices and
893 /// return the resultant element type, otherwise return null.
894 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
895 SmallVectorImpl<Value*> &NewIndices) {
896 assert(PtrTy->isPtrOrPtrVectorTy());
901 Type *Ty = PtrTy->getPointerElementType();
905 // Start with the index over the outer type. Note that the type size
906 // might be zero (even if the offset isn't zero) if the indexed type
907 // is something like [0 x {int, int}]
908 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
909 int64_t FirstIdx = 0;
910 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
911 FirstIdx = Offset/TySize;
912 Offset -= FirstIdx*TySize;
914 // Handle hosts where % returns negative instead of values [0..TySize).
920 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
923 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
925 // Index into the types. If we fail, set OrigBase to null.
927 // Indexing into tail padding between struct/array elements.
928 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
931 if (StructType *STy = dyn_cast<StructType>(Ty)) {
932 const StructLayout *SL = DL->getStructLayout(STy);
933 assert(Offset < (int64_t)SL->getSizeInBytes() &&
934 "Offset must stay within the indexed type");
936 unsigned Elt = SL->getElementContainingOffset(Offset);
937 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
940 Offset -= SL->getElementOffset(Elt);
941 Ty = STy->getElementType(Elt);
942 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
943 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
944 assert(EltSize && "Cannot index into a zero-sized array");
945 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
947 Ty = AT->getElementType();
949 // Otherwise, we can't index into the middle of this atomic type, bail.
957 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
958 // If this GEP has only 0 indices, it is the same pointer as
959 // Src. If Src is not a trivial GEP too, don't combine
961 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
967 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
968 /// the multiplication is known not to overflow then NoSignedWrap is set.
969 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
970 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
971 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
972 Scale.getBitWidth() && "Scale not compatible with value!");
974 // If Val is zero or Scale is one then Val = Val * Scale.
975 if (match(Val, m_Zero()) || Scale == 1) {
980 // If Scale is zero then it does not divide Val.
981 if (Scale.isMinValue())
984 // Look through chains of multiplications, searching for a constant that is
985 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
986 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
987 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
990 // Val = M1 * X || Analysis starts here and works down
991 // M1 = M2 * Y || Doesn't descend into terms with more
992 // M2 = Z * 4 \/ than one use
994 // Then to modify a term at the bottom:
997 // M1 = Z * Y || Replaced M2 with Z
999 // Then to work back up correcting nsw flags.
1001 // Op - the term we are currently analyzing. Starts at Val then drills down.
1002 // Replaced with its descaled value before exiting from the drill down loop.
1005 // Parent - initially null, but after drilling down notes where Op came from.
1006 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1007 // 0'th operand of Val.
1008 std::pair<Instruction*, unsigned> Parent;
1010 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1011 // levels that doesn't overflow.
1012 bool RequireNoSignedWrap = false;
1014 // logScale - log base 2 of the scale. Negative if not a power of 2.
1015 int32_t logScale = Scale.exactLogBase2();
1017 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1019 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1020 // If Op is a constant divisible by Scale then descale to the quotient.
1021 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1022 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1023 if (!Remainder.isMinValue())
1024 // Not divisible by Scale.
1026 // Replace with the quotient in the parent.
1027 Op = ConstantInt::get(CI->getType(), Quotient);
1028 NoSignedWrap = true;
1032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1034 if (BO->getOpcode() == Instruction::Mul) {
1036 NoSignedWrap = BO->hasNoSignedWrap();
1037 if (RequireNoSignedWrap && !NoSignedWrap)
1040 // There are three cases for multiplication: multiplication by exactly
1041 // the scale, multiplication by a constant different to the scale, and
1042 // multiplication by something else.
1043 Value *LHS = BO->getOperand(0);
1044 Value *RHS = BO->getOperand(1);
1046 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1047 // Multiplication by a constant.
1048 if (CI->getValue() == Scale) {
1049 // Multiplication by exactly the scale, replace the multiplication
1050 // by its left-hand side in the parent.
1055 // Otherwise drill down into the constant.
1056 if (!Op->hasOneUse())
1059 Parent = std::make_pair(BO, 1);
1063 // Multiplication by something else. Drill down into the left-hand side
1064 // since that's where the reassociate pass puts the good stuff.
1065 if (!Op->hasOneUse())
1068 Parent = std::make_pair(BO, 0);
1072 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1073 isa<ConstantInt>(BO->getOperand(1))) {
1074 // Multiplication by a power of 2.
1075 NoSignedWrap = BO->hasNoSignedWrap();
1076 if (RequireNoSignedWrap && !NoSignedWrap)
1079 Value *LHS = BO->getOperand(0);
1080 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1081 getLimitedValue(Scale.getBitWidth());
1084 if (Amt == logScale) {
1085 // Multiplication by exactly the scale, replace the multiplication
1086 // by its left-hand side in the parent.
1090 if (Amt < logScale || !Op->hasOneUse())
1093 // Multiplication by more than the scale. Reduce the multiplying amount
1094 // by the scale in the parent.
1095 Parent = std::make_pair(BO, 1);
1096 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1101 if (!Op->hasOneUse())
1104 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1105 if (Cast->getOpcode() == Instruction::SExt) {
1106 // Op is sign-extended from a smaller type, descale in the smaller type.
1107 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1108 APInt SmallScale = Scale.trunc(SmallSize);
1109 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1110 // descale Op as (sext Y) * Scale. In order to have
1111 // sext (Y * SmallScale) = (sext Y) * Scale
1112 // some conditions need to hold however: SmallScale must sign-extend to
1113 // Scale and the multiplication Y * SmallScale should not overflow.
1114 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1115 // SmallScale does not sign-extend to Scale.
1117 assert(SmallScale.exactLogBase2() == logScale);
1118 // Require that Y * SmallScale must not overflow.
1119 RequireNoSignedWrap = true;
1121 // Drill down through the cast.
1122 Parent = std::make_pair(Cast, 0);
1127 if (Cast->getOpcode() == Instruction::Trunc) {
1128 // Op is truncated from a larger type, descale in the larger type.
1129 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1130 // trunc (Y * sext Scale) = (trunc Y) * Scale
1131 // always holds. However (trunc Y) * Scale may overflow even if
1132 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1133 // from this point up in the expression (see later).
1134 if (RequireNoSignedWrap)
1137 // Drill down through the cast.
1138 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1139 Parent = std::make_pair(Cast, 0);
1140 Scale = Scale.sext(LargeSize);
1141 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1143 assert(Scale.exactLogBase2() == logScale);
1148 // Unsupported expression, bail out.
1152 // If Op is zero then Val = Op * Scale.
1153 if (match(Op, m_Zero())) {
1154 NoSignedWrap = true;
1158 // We know that we can successfully descale, so from here on we can safely
1159 // modify the IR. Op holds the descaled version of the deepest term in the
1160 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1164 // The expression only had one term.
1167 // Rewrite the parent using the descaled version of its operand.
1168 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1169 assert(Op != Parent.first->getOperand(Parent.second) &&
1170 "Descaling was a no-op?");
1171 Parent.first->setOperand(Parent.second, Op);
1172 Worklist.Add(Parent.first);
1174 // Now work back up the expression correcting nsw flags. The logic is based
1175 // on the following observation: if X * Y is known not to overflow as a signed
1176 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1177 // then X * Z will not overflow as a signed multiplication either. As we work
1178 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1179 // current level has strictly smaller absolute value than the original.
1180 Instruction *Ancestor = Parent.first;
1182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1183 // If the multiplication wasn't nsw then we can't say anything about the
1184 // value of the descaled multiplication, and we have to clear nsw flags
1185 // from this point on up.
1186 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1187 NoSignedWrap &= OpNoSignedWrap;
1188 if (NoSignedWrap != OpNoSignedWrap) {
1189 BO->setHasNoSignedWrap(NoSignedWrap);
1190 Worklist.Add(Ancestor);
1192 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1193 // The fact that the descaled input to the trunc has smaller absolute
1194 // value than the original input doesn't tell us anything useful about
1195 // the absolute values of the truncations.
1196 NoSignedWrap = false;
1198 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1199 "Failed to keep proper track of nsw flags while drilling down?");
1201 if (Ancestor == Val)
1202 // Got to the top, all done!
1205 // Move up one level in the expression.
1206 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1207 Ancestor = Ancestor->user_back();
1211 /// \brief Creates node of binary operation with the same attributes as the
1212 /// specified one but with other operands.
1213 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1214 InstCombiner::BuilderTy *B) {
1215 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1216 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1217 if (isa<OverflowingBinaryOperator>(NewBO)) {
1218 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1219 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1221 if (isa<PossiblyExactOperator>(NewBO))
1222 NewBO->setIsExact(Inst.isExact());
1227 /// \brief Makes transformation of binary operation specific for vector types.
1228 /// \param Inst Binary operator to transform.
1229 /// \return Pointer to node that must replace the original binary operator, or
1230 /// null pointer if no transformation was made.
1231 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1232 if (!Inst.getType()->isVectorTy()) return nullptr;
1234 // It may not be safe to reorder shuffles and things like div, urem, etc.
1235 // because we may trap when executing those ops on unknown vector elements.
1237 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1239 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1240 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1241 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1242 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1244 // If both arguments of binary operation are shuffles, which use the same
1245 // mask and shuffle within a single vector, it is worthwhile to move the
1246 // shuffle after binary operation:
1247 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1248 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1249 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1250 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1251 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1252 isa<UndefValue>(RShuf->getOperand(1)) &&
1253 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1254 LShuf->getMask() == RShuf->getMask()) {
1255 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1256 RShuf->getOperand(0), Builder);
1257 Value *Res = Builder->CreateShuffleVector(NewBO,
1258 UndefValue::get(NewBO->getType()), LShuf->getMask());
1263 // If one argument is a shuffle within one vector, the other is a constant,
1264 // try moving the shuffle after the binary operation.
1265 ShuffleVectorInst *Shuffle = nullptr;
1266 Constant *C1 = nullptr;
1267 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1268 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1269 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1270 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1271 if (Shuffle && C1 &&
1272 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1273 isa<UndefValue>(Shuffle->getOperand(1)) &&
1274 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1275 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1276 // Find constant C2 that has property:
1277 // shuffle(C2, ShMask) = C1
1278 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1279 // reorder is not possible.
1280 SmallVector<Constant*, 16> C2M(VWidth,
1281 UndefValue::get(C1->getType()->getScalarType()));
1282 bool MayChange = true;
1283 for (unsigned I = 0; I < VWidth; ++I) {
1284 if (ShMask[I] >= 0) {
1285 assert(ShMask[I] < (int)VWidth);
1286 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1290 C2M[ShMask[I]] = C1->getAggregateElement(I);
1294 Constant *C2 = ConstantVector::get(C2M);
1295 Value *NewLHS, *NewRHS;
1296 if (isa<Constant>(LHS)) {
1298 NewRHS = Shuffle->getOperand(0);
1300 NewLHS = Shuffle->getOperand(0);
1303 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1304 Value *Res = Builder->CreateShuffleVector(NewBO,
1305 UndefValue::get(Inst.getType()), Shuffle->getMask());
1313 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1314 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1316 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AT))
1317 return ReplaceInstUsesWith(GEP, V);
1319 Value *PtrOp = GEP.getOperand(0);
1321 // Eliminate unneeded casts for indices, and replace indices which displace
1322 // by multiples of a zero size type with zero.
1324 bool MadeChange = false;
1325 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1327 gep_type_iterator GTI = gep_type_begin(GEP);
1328 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1329 I != E; ++I, ++GTI) {
1330 // Skip indices into struct types.
1331 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1332 if (!SeqTy) continue;
1334 // If the element type has zero size then any index over it is equivalent
1335 // to an index of zero, so replace it with zero if it is not zero already.
1336 if (SeqTy->getElementType()->isSized() &&
1337 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1338 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1339 *I = Constant::getNullValue(IntPtrTy);
1343 Type *IndexTy = (*I)->getType();
1344 if (IndexTy != IntPtrTy) {
1345 // If we are using a wider index than needed for this platform, shrink
1346 // it to what we need. If narrower, sign-extend it to what we need.
1347 // This explicit cast can make subsequent optimizations more obvious.
1348 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1352 if (MadeChange) return &GEP;
1355 // Check to see if the inputs to the PHI node are getelementptr instructions.
1356 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1357 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1363 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1364 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1365 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1368 // Keep track of the type as we walk the GEP.
1369 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1371 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1372 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1375 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1377 // We have not seen any differences yet in the GEPs feeding the
1378 // PHI yet, so we record this one if it is allowed to be a
1381 // The first two arguments can vary for any GEP, the rest have to be
1382 // static for struct slots
1383 if (J > 1 && CurTy->isStructTy())
1388 // The GEP is different by more than one input. While this could be
1389 // extended to support GEPs that vary by more than one variable it
1390 // doesn't make sense since it greatly increases the complexity and
1391 // would result in an R+R+R addressing mode which no backend
1392 // directly supports and would need to be broken into several
1393 // simpler instructions anyway.
1398 // Sink down a layer of the type for the next iteration.
1400 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1401 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1409 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1412 // All the GEPs feeding the PHI are identical. Clone one down into our
1413 // BB so that it can be merged with the current GEP.
1414 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1417 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1418 // into the current block so it can be merged, and create a new PHI to
1420 Instruction *InsertPt = Builder->GetInsertPoint();
1421 Builder->SetInsertPoint(PN);
1422 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1423 PN->getNumOperands());
1424 Builder->SetInsertPoint(InsertPt);
1426 for (auto &I : PN->operands())
1427 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1428 PN->getIncomingBlock(I));
1430 NewGEP->setOperand(DI, NewPN);
1431 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1433 NewGEP->setOperand(DI, NewPN);
1436 GEP.setOperand(0, NewGEP);
1440 // Combine Indices - If the source pointer to this getelementptr instruction
1441 // is a getelementptr instruction, combine the indices of the two
1442 // getelementptr instructions into a single instruction.
1444 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1445 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1448 // Note that if our source is a gep chain itself then we wait for that
1449 // chain to be resolved before we perform this transformation. This
1450 // avoids us creating a TON of code in some cases.
1451 if (GEPOperator *SrcGEP =
1452 dyn_cast<GEPOperator>(Src->getOperand(0)))
1453 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1454 return nullptr; // Wait until our source is folded to completion.
1456 SmallVector<Value*, 8> Indices;
1458 // Find out whether the last index in the source GEP is a sequential idx.
1459 bool EndsWithSequential = false;
1460 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1462 EndsWithSequential = !(*I)->isStructTy();
1464 // Can we combine the two pointer arithmetics offsets?
1465 if (EndsWithSequential) {
1466 // Replace: gep (gep %P, long B), long A, ...
1467 // With: T = long A+B; gep %P, T, ...
1470 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1471 Value *GO1 = GEP.getOperand(1);
1472 if (SO1 == Constant::getNullValue(SO1->getType())) {
1474 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1477 // If they aren't the same type, then the input hasn't been processed
1478 // by the loop above yet (which canonicalizes sequential index types to
1479 // intptr_t). Just avoid transforming this until the input has been
1481 if (SO1->getType() != GO1->getType())
1483 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1486 // Update the GEP in place if possible.
1487 if (Src->getNumOperands() == 2) {
1488 GEP.setOperand(0, Src->getOperand(0));
1489 GEP.setOperand(1, Sum);
1492 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1493 Indices.push_back(Sum);
1494 Indices.append(GEP.op_begin()+2, GEP.op_end());
1495 } else if (isa<Constant>(*GEP.idx_begin()) &&
1496 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1497 Src->getNumOperands() != 1) {
1498 // Otherwise we can do the fold if the first index of the GEP is a zero
1499 Indices.append(Src->op_begin()+1, Src->op_end());
1500 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1503 if (!Indices.empty())
1504 return (GEP.isInBounds() && Src->isInBounds()) ?
1505 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1507 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1510 if (DL && GEP.getNumIndices() == 1) {
1511 unsigned AS = GEP.getPointerAddressSpace();
1512 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1513 DL->getPointerSizeInBits(AS)) {
1514 Type *PtrTy = GEP.getPointerOperandType();
1515 Type *Ty = PtrTy->getPointerElementType();
1516 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1518 bool Matched = false;
1521 if (TyAllocSize == 1) {
1522 V = GEP.getOperand(1);
1524 } else if (match(GEP.getOperand(1),
1525 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1526 if (TyAllocSize == 1ULL << C)
1528 } else if (match(GEP.getOperand(1),
1529 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1530 if (TyAllocSize == C)
1535 // Canonicalize (gep i8* X, -(ptrtoint Y))
1536 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1537 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1538 // pointer arithmetic.
1539 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1540 Operator *Index = cast<Operator>(V);
1541 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1542 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1543 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1545 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1548 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1549 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1550 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1557 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1558 Value *StrippedPtr = PtrOp->stripPointerCasts();
1559 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1561 // We do not handle pointer-vector geps here.
1565 if (StrippedPtr != PtrOp) {
1566 bool HasZeroPointerIndex = false;
1567 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1568 HasZeroPointerIndex = C->isZero();
1570 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1571 // into : GEP [10 x i8]* X, i32 0, ...
1573 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1574 // into : GEP i8* X, ...
1576 // This occurs when the program declares an array extern like "int X[];"
1577 if (HasZeroPointerIndex) {
1578 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1579 if (ArrayType *CATy =
1580 dyn_cast<ArrayType>(CPTy->getElementType())) {
1581 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1582 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1583 // -> GEP i8* X, ...
1584 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1585 GetElementPtrInst *Res =
1586 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1587 Res->setIsInBounds(GEP.isInBounds());
1588 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1590 // Insert Res, and create an addrspacecast.
1592 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1594 // %0 = GEP i8 addrspace(1)* X, ...
1595 // addrspacecast i8 addrspace(1)* %0 to i8*
1596 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1599 if (ArrayType *XATy =
1600 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1601 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1602 if (CATy->getElementType() == XATy->getElementType()) {
1603 // -> GEP [10 x i8]* X, i32 0, ...
1604 // At this point, we know that the cast source type is a pointer
1605 // to an array of the same type as the destination pointer
1606 // array. Because the array type is never stepped over (there
1607 // is a leading zero) we can fold the cast into this GEP.
1608 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1609 GEP.setOperand(0, StrippedPtr);
1612 // Cannot replace the base pointer directly because StrippedPtr's
1613 // address space is different. Instead, create a new GEP followed by
1614 // an addrspacecast.
1616 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1619 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1620 // addrspacecast i8 addrspace(1)* %0 to i8*
1621 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1622 Value *NewGEP = GEP.isInBounds() ?
1623 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1624 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1625 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1629 } else if (GEP.getNumOperands() == 2) {
1630 // Transform things like:
1631 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1632 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1633 Type *SrcElTy = StrippedPtrTy->getElementType();
1634 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1635 if (DL && SrcElTy->isArrayTy() &&
1636 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1637 DL->getTypeAllocSize(ResElTy)) {
1638 Type *IdxType = DL->getIntPtrType(GEP.getType());
1639 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1640 Value *NewGEP = GEP.isInBounds() ?
1641 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1642 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1644 // V and GEP are both pointer types --> BitCast
1645 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1649 // Transform things like:
1650 // %V = mul i64 %N, 4
1651 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1652 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1653 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1654 // Check that changing the type amounts to dividing the index by a scale
1656 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1657 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1658 if (ResSize && SrcSize % ResSize == 0) {
1659 Value *Idx = GEP.getOperand(1);
1660 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1661 uint64_t Scale = SrcSize / ResSize;
1663 // Earlier transforms ensure that the index has type IntPtrType, which
1664 // considerably simplifies the logic by eliminating implicit casts.
1665 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1666 "Index not cast to pointer width?");
1669 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1670 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1671 // If the multiplication NewIdx * Scale may overflow then the new
1672 // GEP may not be "inbounds".
1673 Value *NewGEP = GEP.isInBounds() && NSW ?
1674 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1675 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1677 // The NewGEP must be pointer typed, so must the old one -> BitCast
1678 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1684 // Similarly, transform things like:
1685 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1686 // (where tmp = 8*tmp2) into:
1687 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1688 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1689 SrcElTy->isArrayTy()) {
1690 // Check that changing to the array element type amounts to dividing the
1691 // index by a scale factor.
1692 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1693 uint64_t ArrayEltSize
1694 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1695 if (ResSize && ArrayEltSize % ResSize == 0) {
1696 Value *Idx = GEP.getOperand(1);
1697 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1698 uint64_t Scale = ArrayEltSize / ResSize;
1700 // Earlier transforms ensure that the index has type IntPtrType, which
1701 // considerably simplifies the logic by eliminating implicit casts.
1702 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1703 "Index not cast to pointer width?");
1706 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1707 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1708 // If the multiplication NewIdx * Scale may overflow then the new
1709 // GEP may not be "inbounds".
1711 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1715 Value *NewGEP = GEP.isInBounds() && NSW ?
1716 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1717 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1718 // The NewGEP must be pointer typed, so must the old one -> BitCast
1719 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1730 // addrspacecast between types is canonicalized as a bitcast, then an
1731 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1732 // through the addrspacecast.
1733 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1734 // X = bitcast A addrspace(1)* to B addrspace(1)*
1735 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1736 // Z = gep Y, <...constant indices...>
1737 // Into an addrspacecasted GEP of the struct.
1738 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1742 /// See if we can simplify:
1743 /// X = bitcast A* to B*
1744 /// Y = gep X, <...constant indices...>
1745 /// into a gep of the original struct. This is important for SROA and alias
1746 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1747 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1748 Value *Operand = BCI->getOperand(0);
1749 PointerType *OpType = cast<PointerType>(Operand->getType());
1750 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1751 APInt Offset(OffsetBits, 0);
1752 if (!isa<BitCastInst>(Operand) &&
1753 GEP.accumulateConstantOffset(*DL, Offset)) {
1755 // If this GEP instruction doesn't move the pointer, just replace the GEP
1756 // with a bitcast of the real input to the dest type.
1758 // If the bitcast is of an allocation, and the allocation will be
1759 // converted to match the type of the cast, don't touch this.
1760 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1761 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1762 if (Instruction *I = visitBitCast(*BCI)) {
1765 BCI->getParent()->getInstList().insert(BCI, I);
1766 ReplaceInstUsesWith(*BCI, I);
1772 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1773 return new AddrSpaceCastInst(Operand, GEP.getType());
1774 return new BitCastInst(Operand, GEP.getType());
1777 // Otherwise, if the offset is non-zero, we need to find out if there is a
1778 // field at Offset in 'A's type. If so, we can pull the cast through the
1780 SmallVector<Value*, 8> NewIndices;
1781 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1782 Value *NGEP = GEP.isInBounds() ?
1783 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1784 Builder->CreateGEP(Operand, NewIndices);
1786 if (NGEP->getType() == GEP.getType())
1787 return ReplaceInstUsesWith(GEP, NGEP);
1788 NGEP->takeName(&GEP);
1790 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1791 return new AddrSpaceCastInst(NGEP, GEP.getType());
1792 return new BitCastInst(NGEP, GEP.getType());
1801 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1802 const TargetLibraryInfo *TLI) {
1803 SmallVector<Instruction*, 4> Worklist;
1804 Worklist.push_back(AI);
1807 Instruction *PI = Worklist.pop_back_val();
1808 for (User *U : PI->users()) {
1809 Instruction *I = cast<Instruction>(U);
1810 switch (I->getOpcode()) {
1812 // Give up the moment we see something we can't handle.
1815 case Instruction::BitCast:
1816 case Instruction::GetElementPtr:
1818 Worklist.push_back(I);
1821 case Instruction::ICmp: {
1822 ICmpInst *ICI = cast<ICmpInst>(I);
1823 // We can fold eq/ne comparisons with null to false/true, respectively.
1824 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1830 case Instruction::Call:
1831 // Ignore no-op and store intrinsics.
1832 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1833 switch (II->getIntrinsicID()) {
1837 case Intrinsic::memmove:
1838 case Intrinsic::memcpy:
1839 case Intrinsic::memset: {
1840 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1841 if (MI->isVolatile() || MI->getRawDest() != PI)
1845 case Intrinsic::dbg_declare:
1846 case Intrinsic::dbg_value:
1847 case Intrinsic::invariant_start:
1848 case Intrinsic::invariant_end:
1849 case Intrinsic::lifetime_start:
1850 case Intrinsic::lifetime_end:
1851 case Intrinsic::objectsize:
1857 if (isFreeCall(I, TLI)) {
1863 case Instruction::Store: {
1864 StoreInst *SI = cast<StoreInst>(I);
1865 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1871 llvm_unreachable("missing a return?");
1873 } while (!Worklist.empty());
1877 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1878 // If we have a malloc call which is only used in any amount of comparisons
1879 // to null and free calls, delete the calls and replace the comparisons with
1880 // true or false as appropriate.
1881 SmallVector<WeakVH, 64> Users;
1882 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1883 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1884 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1887 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1888 ReplaceInstUsesWith(*C,
1889 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1890 C->isFalseWhenEqual()));
1891 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1892 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1893 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1894 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1895 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1896 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1897 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1900 EraseInstFromFunction(*I);
1903 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1904 // Replace invoke with a NOP intrinsic to maintain the original CFG
1905 Module *M = II->getParent()->getParent()->getParent();
1906 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1907 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1908 None, "", II->getParent());
1910 return EraseInstFromFunction(MI);
1915 /// \brief Move the call to free before a NULL test.
1917 /// Check if this free is accessed after its argument has been test
1918 /// against NULL (property 0).
1919 /// If yes, it is legal to move this call in its predecessor block.
1921 /// The move is performed only if the block containing the call to free
1922 /// will be removed, i.e.:
1923 /// 1. it has only one predecessor P, and P has two successors
1924 /// 2. it contains the call and an unconditional branch
1925 /// 3. its successor is the same as its predecessor's successor
1927 /// The profitability is out-of concern here and this function should
1928 /// be called only if the caller knows this transformation would be
1929 /// profitable (e.g., for code size).
1930 static Instruction *
1931 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1932 Value *Op = FI.getArgOperand(0);
1933 BasicBlock *FreeInstrBB = FI.getParent();
1934 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1936 // Validate part of constraint #1: Only one predecessor
1937 // FIXME: We can extend the number of predecessor, but in that case, we
1938 // would duplicate the call to free in each predecessor and it may
1939 // not be profitable even for code size.
1943 // Validate constraint #2: Does this block contains only the call to
1944 // free and an unconditional branch?
1945 // FIXME: We could check if we can speculate everything in the
1946 // predecessor block
1947 if (FreeInstrBB->size() != 2)
1950 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1953 // Validate the rest of constraint #1 by matching on the pred branch.
1954 TerminatorInst *TI = PredBB->getTerminator();
1955 BasicBlock *TrueBB, *FalseBB;
1956 ICmpInst::Predicate Pred;
1957 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1959 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1962 // Validate constraint #3: Ensure the null case just falls through.
1963 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1965 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1966 "Broken CFG: missing edge from predecessor to successor");
1973 Instruction *InstCombiner::visitFree(CallInst &FI) {
1974 Value *Op = FI.getArgOperand(0);
1976 // free undef -> unreachable.
1977 if (isa<UndefValue>(Op)) {
1978 // Insert a new store to null because we cannot modify the CFG here.
1979 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1980 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1981 return EraseInstFromFunction(FI);
1984 // If we have 'free null' delete the instruction. This can happen in stl code
1985 // when lots of inlining happens.
1986 if (isa<ConstantPointerNull>(Op))
1987 return EraseInstFromFunction(FI);
1989 // If we optimize for code size, try to move the call to free before the null
1990 // test so that simplify cfg can remove the empty block and dead code
1991 // elimination the branch. I.e., helps to turn something like:
1992 // if (foo) free(foo);
1996 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2002 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2003 if (RI.getNumOperands() == 0) // ret void
2006 Value *ResultOp = RI.getOperand(0);
2007 Type *VTy = ResultOp->getType();
2008 if (!VTy->isIntegerTy())
2011 // There might be assume intrinsics dominating this return that completely
2012 // determine the value. If so, constant fold it.
2013 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2014 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2015 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2016 if ((KnownZero|KnownOne).isAllOnesValue())
2017 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2022 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2023 // Change br (not X), label True, label False to: br X, label False, True
2025 BasicBlock *TrueDest;
2026 BasicBlock *FalseDest;
2027 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2028 !isa<Constant>(X)) {
2029 // Swap Destinations and condition...
2031 BI.swapSuccessors();
2035 // Canonicalize fcmp_one -> fcmp_oeq
2036 FCmpInst::Predicate FPred; Value *Y;
2037 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2038 TrueDest, FalseDest)) &&
2039 BI.getCondition()->hasOneUse())
2040 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2041 FPred == FCmpInst::FCMP_OGE) {
2042 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2043 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2045 // Swap Destinations and condition.
2046 BI.swapSuccessors();
2051 // Canonicalize icmp_ne -> icmp_eq
2052 ICmpInst::Predicate IPred;
2053 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2054 TrueDest, FalseDest)) &&
2055 BI.getCondition()->hasOneUse())
2056 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2057 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2058 IPred == ICmpInst::ICMP_SGE) {
2059 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2060 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2061 // Swap Destinations and condition.
2062 BI.swapSuccessors();
2070 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2071 Value *Cond = SI.getCondition();
2072 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2073 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2074 computeKnownBits(Cond, KnownZero, KnownOne);
2075 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2076 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2078 // Compute the number of leading bits we can ignore.
2079 for (auto &C : SI.cases()) {
2080 LeadingKnownZeros = std::min(
2081 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2082 LeadingKnownOnes = std::min(
2083 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2086 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2088 // Truncate the condition operand if the new type is equal to or larger than
2089 // the largest legal integer type. We need to be conservative here since
2090 // x86 generates redundant zero-extenstion instructions if the operand is
2091 // truncated to i8 or i16.
2092 if (BitWidth > NewWidth && NewWidth >= DL->getLargestLegalIntTypeSize()) {
2093 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2094 Builder->SetInsertPoint(&SI);
2095 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2096 SI.setCondition(NewCond);
2098 for (auto &C : SI.cases())
2099 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2100 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2103 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2104 if (I->getOpcode() == Instruction::Add)
2105 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2106 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2107 // Skip the first item since that's the default case.
2108 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2110 ConstantInt* CaseVal = i.getCaseValue();
2111 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
2113 assert(isa<ConstantInt>(NewCaseVal) &&
2114 "Result of expression should be constant");
2115 i.setValue(cast<ConstantInt>(NewCaseVal));
2117 SI.setCondition(I->getOperand(0));
2125 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2126 Value *Agg = EV.getAggregateOperand();
2128 if (!EV.hasIndices())
2129 return ReplaceInstUsesWith(EV, Agg);
2131 if (Constant *C = dyn_cast<Constant>(Agg)) {
2132 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2133 if (EV.getNumIndices() == 0)
2134 return ReplaceInstUsesWith(EV, C2);
2135 // Extract the remaining indices out of the constant indexed by the
2137 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2139 return nullptr; // Can't handle other constants
2142 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2143 // We're extracting from an insertvalue instruction, compare the indices
2144 const unsigned *exti, *exte, *insi, *inse;
2145 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2146 exte = EV.idx_end(), inse = IV->idx_end();
2147 exti != exte && insi != inse;
2150 // The insert and extract both reference distinctly different elements.
2151 // This means the extract is not influenced by the insert, and we can
2152 // replace the aggregate operand of the extract with the aggregate
2153 // operand of the insert. i.e., replace
2154 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2155 // %E = extractvalue { i32, { i32 } } %I, 0
2157 // %E = extractvalue { i32, { i32 } } %A, 0
2158 return ExtractValueInst::Create(IV->getAggregateOperand(),
2161 if (exti == exte && insi == inse)
2162 // Both iterators are at the end: Index lists are identical. Replace
2163 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2164 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2166 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2168 // The extract list is a prefix of the insert list. i.e. replace
2169 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2170 // %E = extractvalue { i32, { i32 } } %I, 1
2172 // %X = extractvalue { i32, { i32 } } %A, 1
2173 // %E = insertvalue { i32 } %X, i32 42, 0
2174 // by switching the order of the insert and extract (though the
2175 // insertvalue should be left in, since it may have other uses).
2176 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2178 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2179 makeArrayRef(insi, inse));
2182 // The insert list is a prefix of the extract list
2183 // We can simply remove the common indices from the extract and make it
2184 // operate on the inserted value instead of the insertvalue result.
2186 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2187 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2189 // %E extractvalue { i32 } { i32 42 }, 0
2190 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2191 makeArrayRef(exti, exte));
2193 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2194 // We're extracting from an intrinsic, see if we're the only user, which
2195 // allows us to simplify multiple result intrinsics to simpler things that
2196 // just get one value.
2197 if (II->hasOneUse()) {
2198 // Check if we're grabbing the overflow bit or the result of a 'with
2199 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2200 // and replace it with a traditional binary instruction.
2201 switch (II->getIntrinsicID()) {
2202 case Intrinsic::uadd_with_overflow:
2203 case Intrinsic::sadd_with_overflow:
2204 if (*EV.idx_begin() == 0) { // Normal result.
2205 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2206 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2207 EraseInstFromFunction(*II);
2208 return BinaryOperator::CreateAdd(LHS, RHS);
2211 // If the normal result of the add is dead, and the RHS is a constant,
2212 // we can transform this into a range comparison.
2213 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2214 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2215 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2216 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2217 ConstantExpr::getNot(CI));
2219 case Intrinsic::usub_with_overflow:
2220 case Intrinsic::ssub_with_overflow:
2221 if (*EV.idx_begin() == 0) { // Normal result.
2222 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2223 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2224 EraseInstFromFunction(*II);
2225 return BinaryOperator::CreateSub(LHS, RHS);
2228 case Intrinsic::umul_with_overflow:
2229 case Intrinsic::smul_with_overflow:
2230 if (*EV.idx_begin() == 0) { // Normal result.
2231 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2232 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2233 EraseInstFromFunction(*II);
2234 return BinaryOperator::CreateMul(LHS, RHS);
2242 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2243 // If the (non-volatile) load only has one use, we can rewrite this to a
2244 // load from a GEP. This reduces the size of the load.
2245 // FIXME: If a load is used only by extractvalue instructions then this
2246 // could be done regardless of having multiple uses.
2247 if (L->isSimple() && L->hasOneUse()) {
2248 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2249 SmallVector<Value*, 4> Indices;
2250 // Prefix an i32 0 since we need the first element.
2251 Indices.push_back(Builder->getInt32(0));
2252 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2254 Indices.push_back(Builder->getInt32(*I));
2256 // We need to insert these at the location of the old load, not at that of
2257 // the extractvalue.
2258 Builder->SetInsertPoint(L->getParent(), L);
2259 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2260 // Returning the load directly will cause the main loop to insert it in
2261 // the wrong spot, so use ReplaceInstUsesWith().
2262 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2264 // We could simplify extracts from other values. Note that nested extracts may
2265 // already be simplified implicitly by the above: extract (extract (insert) )
2266 // will be translated into extract ( insert ( extract ) ) first and then just
2267 // the value inserted, if appropriate. Similarly for extracts from single-use
2268 // loads: extract (extract (load)) will be translated to extract (load (gep))
2269 // and if again single-use then via load (gep (gep)) to load (gep).
2270 // However, double extracts from e.g. function arguments or return values
2271 // aren't handled yet.
2275 enum Personality_Type {
2276 Unknown_Personality,
2277 GNU_Ada_Personality,
2278 GNU_CXX_Personality,
2279 GNU_ObjC_Personality
2282 /// RecognizePersonality - See if the given exception handling personality
2283 /// function is one that we understand. If so, return a description of it;
2284 /// otherwise return Unknown_Personality.
2285 static Personality_Type RecognizePersonality(Value *Pers) {
2286 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2288 return Unknown_Personality;
2289 return StringSwitch<Personality_Type>(F->getName())
2290 .Case("__gnat_eh_personality", GNU_Ada_Personality)
2291 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2292 .Case("__objc_personality_v0", GNU_ObjC_Personality)
2293 .Default(Unknown_Personality);
2296 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2297 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2298 switch (Personality) {
2299 case Unknown_Personality:
2301 case GNU_Ada_Personality:
2302 // While __gnat_all_others_value will match any Ada exception, it doesn't
2303 // match foreign exceptions (or didn't, before gcc-4.7).
2305 case GNU_CXX_Personality:
2306 case GNU_ObjC_Personality:
2307 return TypeInfo->isNullValue();
2309 llvm_unreachable("Unknown personality!");
2312 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2314 cast<ArrayType>(LHS->getType())->getNumElements()
2316 cast<ArrayType>(RHS->getType())->getNumElements();
2319 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2320 // The logic here should be correct for any real-world personality function.
2321 // However if that turns out not to be true, the offending logic can always
2322 // be conditioned on the personality function, like the catch-all logic is.
2323 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2325 // Simplify the list of clauses, eg by removing repeated catch clauses
2326 // (these are often created by inlining).
2327 bool MakeNewInstruction = false; // If true, recreate using the following:
2328 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2329 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2331 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2332 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2333 bool isLastClause = i + 1 == e;
2334 if (LI.isCatch(i)) {
2336 Constant *CatchClause = LI.getClause(i);
2337 Constant *TypeInfo = CatchClause->stripPointerCasts();
2339 // If we already saw this clause, there is no point in having a second
2341 if (AlreadyCaught.insert(TypeInfo)) {
2342 // This catch clause was not already seen.
2343 NewClauses.push_back(CatchClause);
2345 // Repeated catch clause - drop the redundant copy.
2346 MakeNewInstruction = true;
2349 // If this is a catch-all then there is no point in keeping any following
2350 // clauses or marking the landingpad as having a cleanup.
2351 if (isCatchAll(Personality, TypeInfo)) {
2353 MakeNewInstruction = true;
2354 CleanupFlag = false;
2358 // A filter clause. If any of the filter elements were already caught
2359 // then they can be dropped from the filter. It is tempting to try to
2360 // exploit the filter further by saying that any typeinfo that does not
2361 // occur in the filter can't be caught later (and thus can be dropped).
2362 // However this would be wrong, since typeinfos can match without being
2363 // equal (for example if one represents a C++ class, and the other some
2364 // class derived from it).
2365 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2366 Constant *FilterClause = LI.getClause(i);
2367 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2368 unsigned NumTypeInfos = FilterType->getNumElements();
2370 // An empty filter catches everything, so there is no point in keeping any
2371 // following clauses or marking the landingpad as having a cleanup. By
2372 // dealing with this case here the following code is made a bit simpler.
2373 if (!NumTypeInfos) {
2374 NewClauses.push_back(FilterClause);
2376 MakeNewInstruction = true;
2377 CleanupFlag = false;
2381 bool MakeNewFilter = false; // If true, make a new filter.
2382 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2383 if (isa<ConstantAggregateZero>(FilterClause)) {
2384 // Not an empty filter - it contains at least one null typeinfo.
2385 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2386 Constant *TypeInfo =
2387 Constant::getNullValue(FilterType->getElementType());
2388 // If this typeinfo is a catch-all then the filter can never match.
2389 if (isCatchAll(Personality, TypeInfo)) {
2390 // Throw the filter away.
2391 MakeNewInstruction = true;
2395 // There is no point in having multiple copies of this typeinfo, so
2396 // discard all but the first copy if there is more than one.
2397 NewFilterElts.push_back(TypeInfo);
2398 if (NumTypeInfos > 1)
2399 MakeNewFilter = true;
2401 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2402 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2403 NewFilterElts.reserve(NumTypeInfos);
2405 // Remove any filter elements that were already caught or that already
2406 // occurred in the filter. While there, see if any of the elements are
2407 // catch-alls. If so, the filter can be discarded.
2408 bool SawCatchAll = false;
2409 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2410 Constant *Elt = Filter->getOperand(j);
2411 Constant *TypeInfo = Elt->stripPointerCasts();
2412 if (isCatchAll(Personality, TypeInfo)) {
2413 // This element is a catch-all. Bail out, noting this fact.
2417 if (AlreadyCaught.count(TypeInfo))
2418 // Already caught by an earlier clause, so having it in the filter
2421 // There is no point in having multiple copies of the same typeinfo in
2422 // a filter, so only add it if we didn't already.
2423 if (SeenInFilter.insert(TypeInfo))
2424 NewFilterElts.push_back(cast<Constant>(Elt));
2426 // A filter containing a catch-all cannot match anything by definition.
2428 // Throw the filter away.
2429 MakeNewInstruction = true;
2433 // If we dropped something from the filter, make a new one.
2434 if (NewFilterElts.size() < NumTypeInfos)
2435 MakeNewFilter = true;
2437 if (MakeNewFilter) {
2438 FilterType = ArrayType::get(FilterType->getElementType(),
2439 NewFilterElts.size());
2440 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2441 MakeNewInstruction = true;
2444 NewClauses.push_back(FilterClause);
2446 // If the new filter is empty then it will catch everything so there is
2447 // no point in keeping any following clauses or marking the landingpad
2448 // as having a cleanup. The case of the original filter being empty was
2449 // already handled above.
2450 if (MakeNewFilter && !NewFilterElts.size()) {
2451 assert(MakeNewInstruction && "New filter but not a new instruction!");
2452 CleanupFlag = false;
2458 // If several filters occur in a row then reorder them so that the shortest
2459 // filters come first (those with the smallest number of elements). This is
2460 // advantageous because shorter filters are more likely to match, speeding up
2461 // unwinding, but mostly because it increases the effectiveness of the other
2462 // filter optimizations below.
2463 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2465 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2466 for (j = i; j != e; ++j)
2467 if (!isa<ArrayType>(NewClauses[j]->getType()))
2470 // Check whether the filters are already sorted by length. We need to know
2471 // if sorting them is actually going to do anything so that we only make a
2472 // new landingpad instruction if it does.
2473 for (unsigned k = i; k + 1 < j; ++k)
2474 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2475 // Not sorted, so sort the filters now. Doing an unstable sort would be
2476 // correct too but reordering filters pointlessly might confuse users.
2477 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2479 MakeNewInstruction = true;
2483 // Look for the next batch of filters.
2487 // If typeinfos matched if and only if equal, then the elements of a filter L
2488 // that occurs later than a filter F could be replaced by the intersection of
2489 // the elements of F and L. In reality two typeinfos can match without being
2490 // equal (for example if one represents a C++ class, and the other some class
2491 // derived from it) so it would be wrong to perform this transform in general.
2492 // However the transform is correct and useful if F is a subset of L. In that
2493 // case L can be replaced by F, and thus removed altogether since repeating a
2494 // filter is pointless. So here we look at all pairs of filters F and L where
2495 // L follows F in the list of clauses, and remove L if every element of F is
2496 // an element of L. This can occur when inlining C++ functions with exception
2498 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2499 // Examine each filter in turn.
2500 Value *Filter = NewClauses[i];
2501 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2503 // Not a filter - skip it.
2505 unsigned FElts = FTy->getNumElements();
2506 // Examine each filter following this one. Doing this backwards means that
2507 // we don't have to worry about filters disappearing under us when removed.
2508 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2509 Value *LFilter = NewClauses[j];
2510 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2512 // Not a filter - skip it.
2514 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2515 // an element of LFilter, then discard LFilter.
2516 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2517 // If Filter is empty then it is a subset of LFilter.
2520 NewClauses.erase(J);
2521 MakeNewInstruction = true;
2522 // Move on to the next filter.
2525 unsigned LElts = LTy->getNumElements();
2526 // If Filter is longer than LFilter then it cannot be a subset of it.
2528 // Move on to the next filter.
2530 // At this point we know that LFilter has at least one element.
2531 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2532 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2533 // already know that Filter is not longer than LFilter).
2534 if (isa<ConstantAggregateZero>(Filter)) {
2535 assert(FElts <= LElts && "Should have handled this case earlier!");
2537 NewClauses.erase(J);
2538 MakeNewInstruction = true;
2540 // Move on to the next filter.
2543 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2544 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2545 // Since Filter is non-empty and contains only zeros, it is a subset of
2546 // LFilter iff LFilter contains a zero.
2547 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2548 for (unsigned l = 0; l != LElts; ++l)
2549 if (LArray->getOperand(l)->isNullValue()) {
2550 // LFilter contains a zero - discard it.
2551 NewClauses.erase(J);
2552 MakeNewInstruction = true;
2555 // Move on to the next filter.
2558 // At this point we know that both filters are ConstantArrays. Loop over
2559 // operands to see whether every element of Filter is also an element of
2560 // LFilter. Since filters tend to be short this is probably faster than
2561 // using a method that scales nicely.
2562 ConstantArray *FArray = cast<ConstantArray>(Filter);
2563 bool AllFound = true;
2564 for (unsigned f = 0; f != FElts; ++f) {
2565 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2567 for (unsigned l = 0; l != LElts; ++l) {
2568 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2569 if (LTypeInfo == FTypeInfo) {
2579 NewClauses.erase(J);
2580 MakeNewInstruction = true;
2582 // Move on to the next filter.
2586 // If we changed any of the clauses, replace the old landingpad instruction
2588 if (MakeNewInstruction) {
2589 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2590 LI.getPersonalityFn(),
2592 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2593 NLI->addClause(NewClauses[i]);
2594 // A landing pad with no clauses must have the cleanup flag set. It is
2595 // theoretically possible, though highly unlikely, that we eliminated all
2596 // clauses. If so, force the cleanup flag to true.
2597 if (NewClauses.empty())
2599 NLI->setCleanup(CleanupFlag);
2603 // Even if none of the clauses changed, we may nonetheless have understood
2604 // that the cleanup flag is pointless. Clear it if so.
2605 if (LI.isCleanup() != CleanupFlag) {
2606 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2607 LI.setCleanup(CleanupFlag);
2617 /// TryToSinkInstruction - Try to move the specified instruction from its
2618 /// current block into the beginning of DestBlock, which can only happen if it's
2619 /// safe to move the instruction past all of the instructions between it and the
2620 /// end of its block.
2621 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2622 assert(I->hasOneUse() && "Invariants didn't hold!");
2624 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2625 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2626 isa<TerminatorInst>(I))
2629 // Do not sink alloca instructions out of the entry block.
2630 if (isa<AllocaInst>(I) && I->getParent() ==
2631 &DestBlock->getParent()->getEntryBlock())
2634 // We can only sink load instructions if there is nothing between the load and
2635 // the end of block that could change the value.
2636 if (I->mayReadFromMemory()) {
2637 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2639 if (Scan->mayWriteToMemory())
2643 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2644 I->moveBefore(InsertPos);
2650 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2651 /// all reachable code to the worklist.
2653 /// This has a couple of tricks to make the code faster and more powerful. In
2654 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2655 /// them to the worklist (this significantly speeds up instcombine on code where
2656 /// many instructions are dead or constant). Additionally, if we find a branch
2657 /// whose condition is a known constant, we only visit the reachable successors.
2659 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2660 SmallPtrSetImpl<BasicBlock*> &Visited,
2662 const DataLayout *DL,
2663 const TargetLibraryInfo *TLI) {
2664 bool MadeIRChange = false;
2665 SmallVector<BasicBlock*, 256> Worklist;
2666 Worklist.push_back(BB);
2668 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2669 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2672 BB = Worklist.pop_back_val();
2674 // We have now visited this block! If we've already been here, ignore it.
2675 if (!Visited.insert(BB)) continue;
2677 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2678 Instruction *Inst = BBI++;
2680 // DCE instruction if trivially dead.
2681 if (isInstructionTriviallyDead(Inst, TLI)) {
2683 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2684 Inst->eraseFromParent();
2688 // ConstantProp instruction if trivially constant.
2689 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2690 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2691 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2693 Inst->replaceAllUsesWith(C);
2695 Inst->eraseFromParent();
2700 // See if we can constant fold its operands.
2701 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2703 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2704 if (CE == nullptr) continue;
2706 Constant*& FoldRes = FoldedConstants[CE];
2708 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2712 if (FoldRes != CE) {
2714 MadeIRChange = true;
2719 InstrsForInstCombineWorklist.push_back(Inst);
2722 // Recursively visit successors. If this is a branch or switch on a
2723 // constant, only visit the reachable successor.
2724 TerminatorInst *TI = BB->getTerminator();
2725 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2726 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2727 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2728 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2729 Worklist.push_back(ReachableBB);
2732 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2733 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2734 // See if this is an explicit destination.
2735 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2737 if (i.getCaseValue() == Cond) {
2738 BasicBlock *ReachableBB = i.getCaseSuccessor();
2739 Worklist.push_back(ReachableBB);
2743 // Otherwise it is the default destination.
2744 Worklist.push_back(SI->getDefaultDest());
2749 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2750 Worklist.push_back(TI->getSuccessor(i));
2751 } while (!Worklist.empty());
2753 // Once we've found all of the instructions to add to instcombine's worklist,
2754 // add them in reverse order. This way instcombine will visit from the top
2755 // of the function down. This jives well with the way that it adds all uses
2756 // of instructions to the worklist after doing a transformation, thus avoiding
2757 // some N^2 behavior in pathological cases.
2758 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2759 InstrsForInstCombineWorklist.size());
2761 return MadeIRChange;
2764 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2765 MadeIRChange = false;
2767 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2768 << F.getName() << "\n");
2771 // Do a depth-first traversal of the function, populate the worklist with
2772 // the reachable instructions. Ignore blocks that are not reachable. Keep
2773 // track of which blocks we visit.
2774 SmallPtrSet<BasicBlock*, 64> Visited;
2775 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
2778 // Do a quick scan over the function. If we find any blocks that are
2779 // unreachable, remove any instructions inside of them. This prevents
2780 // the instcombine code from having to deal with some bad special cases.
2781 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2782 if (Visited.count(BB)) continue;
2784 // Delete the instructions backwards, as it has a reduced likelihood of
2785 // having to update as many def-use and use-def chains.
2786 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2787 while (EndInst != BB->begin()) {
2788 // Delete the next to last instruction.
2789 BasicBlock::iterator I = EndInst;
2790 Instruction *Inst = --I;
2791 if (!Inst->use_empty())
2792 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2793 if (isa<LandingPadInst>(Inst)) {
2797 if (!isa<DbgInfoIntrinsic>(Inst)) {
2799 MadeIRChange = true;
2801 Inst->eraseFromParent();
2806 while (!Worklist.isEmpty()) {
2807 Instruction *I = Worklist.RemoveOne();
2808 if (I == nullptr) continue; // skip null values.
2810 // Check to see if we can DCE the instruction.
2811 if (isInstructionTriviallyDead(I, TLI)) {
2812 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2813 EraseInstFromFunction(*I);
2815 MadeIRChange = true;
2819 // Instruction isn't dead, see if we can constant propagate it.
2820 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2821 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2822 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2824 // Add operands to the worklist.
2825 ReplaceInstUsesWith(*I, C);
2827 EraseInstFromFunction(*I);
2828 MadeIRChange = true;
2832 // See if we can trivially sink this instruction to a successor basic block.
2833 if (I->hasOneUse()) {
2834 BasicBlock *BB = I->getParent();
2835 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2836 BasicBlock *UserParent;
2838 // Get the block the use occurs in.
2839 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2840 UserParent = PN->getIncomingBlock(*I->use_begin());
2842 UserParent = UserInst->getParent();
2844 if (UserParent != BB) {
2845 bool UserIsSuccessor = false;
2846 // See if the user is one of our successors.
2847 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2848 if (*SI == UserParent) {
2849 UserIsSuccessor = true;
2853 // If the user is one of our immediate successors, and if that successor
2854 // only has us as a predecessors (we'd have to split the critical edge
2855 // otherwise), we can keep going.
2856 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2857 // Okay, the CFG is simple enough, try to sink this instruction.
2858 if (TryToSinkInstruction(I, UserParent)) {
2859 MadeIRChange = true;
2860 // We'll add uses of the sunk instruction below, but since sinking
2861 // can expose opportunities for it's *operands* add them to the
2863 for (Use &U : I->operands())
2864 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2871 // Now that we have an instruction, try combining it to simplify it.
2872 Builder->SetInsertPoint(I->getParent(), I);
2873 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2878 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2879 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2881 if (Instruction *Result = visit(*I)) {
2883 // Should we replace the old instruction with a new one?
2885 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2886 << " New = " << *Result << '\n');
2888 if (!I->getDebugLoc().isUnknown())
2889 Result->setDebugLoc(I->getDebugLoc());
2890 // Everything uses the new instruction now.
2891 I->replaceAllUsesWith(Result);
2893 // Move the name to the new instruction first.
2894 Result->takeName(I);
2896 // Push the new instruction and any users onto the worklist.
2897 Worklist.Add(Result);
2898 Worklist.AddUsersToWorkList(*Result);
2900 // Insert the new instruction into the basic block...
2901 BasicBlock *InstParent = I->getParent();
2902 BasicBlock::iterator InsertPos = I;
2904 // If we replace a PHI with something that isn't a PHI, fix up the
2906 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2907 InsertPos = InstParent->getFirstInsertionPt();
2909 InstParent->getInstList().insert(InsertPos, Result);
2911 EraseInstFromFunction(*I);
2914 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2915 << " New = " << *I << '\n');
2918 // If the instruction was modified, it's possible that it is now dead.
2919 // if so, remove it.
2920 if (isInstructionTriviallyDead(I, TLI)) {
2921 EraseInstFromFunction(*I);
2924 Worklist.AddUsersToWorkList(*I);
2927 MadeIRChange = true;
2932 return MadeIRChange;
2936 class InstCombinerLibCallSimplifier final : public LibCallSimplifier {
2939 InstCombinerLibCallSimplifier(const DataLayout *DL,
2940 const TargetLibraryInfo *TLI,
2942 : LibCallSimplifier(DL, TLI) {
2946 /// replaceAllUsesWith - override so that instruction replacement
2947 /// can be defined in terms of the instruction combiner framework.
2948 void replaceAllUsesWith(Instruction *I, Value *With) const override {
2949 IC->ReplaceInstUsesWith(*I, With);
2954 bool InstCombiner::runOnFunction(Function &F) {
2955 if (skipOptnoneFunction(F))
2958 AT = &getAnalysis<AssumptionTracker>();
2959 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2960 DL = DLP ? &DLP->getDataLayout() : nullptr;
2961 TLI = &getAnalysis<TargetLibraryInfo>();
2963 DominatorTreeWrapperPass *DTWP =
2964 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2965 DT = DTWP ? &DTWP->getDomTree() : nullptr;
2968 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2969 Attribute::MinSize);
2971 /// Builder - This is an IRBuilder that automatically inserts new
2972 /// instructions into the worklist when they are created.
2973 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2974 TheBuilder(F.getContext(), TargetFolder(DL),
2975 InstCombineIRInserter(Worklist, AT));
2976 Builder = &TheBuilder;
2978 InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
2979 Simplifier = &TheSimplifier;
2981 bool EverMadeChange = false;
2983 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2985 EverMadeChange = LowerDbgDeclare(F);
2987 // Iterate while there is work to do.
2988 unsigned Iteration = 0;
2989 while (DoOneIteration(F, Iteration++))
2990 EverMadeChange = true;
2993 return EverMadeChange;
2996 FunctionPass *llvm::createInstructionCombiningPass() {
2997 return new InstCombiner();