1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "InstCombineInternal.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/CFG.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/LibCallSemantics.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/MemoryBuiltins.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/CFG.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/IR/ValueHandle.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Transforms/Utils/Local.h"
66 using namespace llvm::PatternMatch;
68 #define DEBUG_TYPE "instcombine"
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
74 STATISTIC(NumExpand, "Number of expansions");
75 STATISTIC(NumFactor , "Number of factorizations");
76 STATISTIC(NumReassoc , "Number of reassociations");
78 Value *InstCombiner::EmitGEPOffset(User *GEP) {
79 return llvm::EmitGEPOffset(Builder, DL, GEP);
82 /// ShouldChangeType - Return true if it is desirable to convert a computation
83 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
84 /// type for example, or from a smaller to a larger illegal type.
85 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
86 assert(From->isIntegerTy() && To->isIntegerTy());
88 unsigned FromWidth = From->getPrimitiveSizeInBits();
89 unsigned ToWidth = To->getPrimitiveSizeInBits();
90 bool FromLegal = DL.isLegalInteger(FromWidth);
91 bool ToLegal = DL.isLegalInteger(ToWidth);
93 // If this is a legal integer from type, and the result would be an illegal
94 // type, don't do the transformation.
95 if (FromLegal && !ToLegal)
98 // Otherwise, if both are illegal, do not increase the size of the result. We
99 // do allow things like i160 -> i64, but not i64 -> i160.
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106 // Return true, if No Signed Wrap should be maintained for I.
107 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
108 // where both B and C should be ConstantInts, results in a constant that does
109 // not overflow. This function only handles the Add and Sub opcodes. For
110 // all other opcodes, the function conservatively returns false.
111 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
112 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
113 if (!OBO || !OBO->hasNoSignedWrap()) {
117 // We reason about Add and Sub Only.
118 Instruction::BinaryOps Opcode = I.getOpcode();
119 if (Opcode != Instruction::Add &&
120 Opcode != Instruction::Sub) {
124 ConstantInt *CB = dyn_cast<ConstantInt>(B);
125 ConstantInt *CC = dyn_cast<ConstantInt>(C);
131 const APInt &BVal = CB->getValue();
132 const APInt &CVal = CC->getValue();
133 bool Overflow = false;
135 if (Opcode == Instruction::Add) {
136 BVal.sadd_ov(CVal, Overflow);
138 BVal.ssub_ov(CVal, Overflow);
144 /// Conservatively clears subclassOptionalData after a reassociation or
145 /// commutation. We preserve fast-math flags when applicable as they can be
147 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
148 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
150 I.clearSubclassOptionalData();
154 FastMathFlags FMF = I.getFastMathFlags();
155 I.clearSubclassOptionalData();
156 I.setFastMathFlags(FMF);
159 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
160 /// operators which are associative or commutative:
162 // Commutative operators:
164 // 1. Order operands such that they are listed from right (least complex) to
165 // left (most complex). This puts constants before unary operators before
168 // Associative operators:
170 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
171 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
173 // Associative and commutative operators:
175 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
176 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
177 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
178 // if C1 and C2 are constants.
180 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
181 Instruction::BinaryOps Opcode = I.getOpcode();
182 bool Changed = false;
185 // Order operands such that they are listed from right (least complex) to
186 // left (most complex). This puts constants before unary operators before
188 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
189 getComplexity(I.getOperand(1)))
190 Changed = !I.swapOperands();
192 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
193 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
195 if (I.isAssociative()) {
196 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
197 if (Op0 && Op0->getOpcode() == Opcode) {
198 Value *A = Op0->getOperand(0);
199 Value *B = Op0->getOperand(1);
200 Value *C = I.getOperand(1);
202 // Does "B op C" simplify?
203 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
204 // It simplifies to V. Form "A op V".
207 // Conservatively clear the optional flags, since they may not be
208 // preserved by the reassociation.
209 if (MaintainNoSignedWrap(I, B, C) &&
210 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
211 // Note: this is only valid because SimplifyBinOp doesn't look at
212 // the operands to Op0.
213 I.clearSubclassOptionalData();
214 I.setHasNoSignedWrap(true);
216 ClearSubclassDataAfterReassociation(I);
225 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
226 if (Op1 && Op1->getOpcode() == Opcode) {
227 Value *A = I.getOperand(0);
228 Value *B = Op1->getOperand(0);
229 Value *C = Op1->getOperand(1);
231 // Does "A op B" simplify?
232 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
233 // It simplifies to V. Form "V op C".
236 // Conservatively clear the optional flags, since they may not be
237 // preserved by the reassociation.
238 ClearSubclassDataAfterReassociation(I);
246 if (I.isAssociative() && I.isCommutative()) {
247 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
248 if (Op0 && Op0->getOpcode() == Opcode) {
249 Value *A = Op0->getOperand(0);
250 Value *B = Op0->getOperand(1);
251 Value *C = I.getOperand(1);
253 // Does "C op A" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
255 // It simplifies to V. Form "V op B".
258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
260 ClearSubclassDataAfterReassociation(I);
267 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
268 if (Op1 && Op1->getOpcode() == Opcode) {
269 Value *A = I.getOperand(0);
270 Value *B = Op1->getOperand(0);
271 Value *C = Op1->getOperand(1);
273 // Does "C op A" simplify?
274 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
275 // It simplifies to V. Form "B op V".
278 // Conservatively clear the optional flags, since they may not be
279 // preserved by the reassociation.
280 ClearSubclassDataAfterReassociation(I);
287 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
288 // if C1 and C2 are constants.
290 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
291 isa<Constant>(Op0->getOperand(1)) &&
292 isa<Constant>(Op1->getOperand(1)) &&
293 Op0->hasOneUse() && Op1->hasOneUse()) {
294 Value *A = Op0->getOperand(0);
295 Constant *C1 = cast<Constant>(Op0->getOperand(1));
296 Value *B = Op1->getOperand(0);
297 Constant *C2 = cast<Constant>(Op1->getOperand(1));
299 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
300 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
301 if (isa<FPMathOperator>(New)) {
302 FastMathFlags Flags = I.getFastMathFlags();
303 Flags &= Op0->getFastMathFlags();
304 Flags &= Op1->getFastMathFlags();
305 New->setFastMathFlags(Flags);
307 InsertNewInstWith(New, I);
309 I.setOperand(0, New);
310 I.setOperand(1, Folded);
311 // Conservatively clear the optional flags, since they may not be
312 // preserved by the reassociation.
313 ClearSubclassDataAfterReassociation(I);
320 // No further simplifications.
325 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
326 /// "(X LOp Y) ROp (X LOp Z)".
327 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
328 Instruction::BinaryOps ROp) {
333 case Instruction::And:
334 // And distributes over Or and Xor.
338 case Instruction::Or:
339 case Instruction::Xor:
343 case Instruction::Mul:
344 // Multiplication distributes over addition and subtraction.
348 case Instruction::Add:
349 case Instruction::Sub:
353 case Instruction::Or:
354 // Or distributes over And.
358 case Instruction::And:
364 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
365 /// "(X ROp Z) LOp (Y ROp Z)".
366 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
367 Instruction::BinaryOps ROp) {
368 if (Instruction::isCommutative(ROp))
369 return LeftDistributesOverRight(ROp, LOp);
374 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
375 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
376 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
377 case Instruction::And:
378 case Instruction::Or:
379 case Instruction::Xor:
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
389 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
390 // but this requires knowing that the addition does not overflow and other
395 /// This function returns identity value for given opcode, which can be used to
396 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
397 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
398 if (isa<Constant>(V))
401 if (OpCode == Instruction::Mul)
402 return ConstantInt::get(V->getType(), 1);
404 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
409 /// This function factors binary ops which can be combined using distributive
410 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
411 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
412 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
413 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
415 static Instruction::BinaryOps
416 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
417 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
419 return Instruction::BinaryOpsEnd;
421 LHS = Op->getOperand(0);
422 RHS = Op->getOperand(1);
424 switch (TopLevelOpcode) {
426 return Op->getOpcode();
428 case Instruction::Add:
429 case Instruction::Sub:
430 if (Op->getOpcode() == Instruction::Shl) {
431 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
432 // The multiplier is really 1 << CST.
433 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
434 return Instruction::Mul;
437 return Op->getOpcode();
440 // TODO: We can add other conversions e.g. shr => div etc.
443 /// This tries to simplify binary operations by factorizing out common terms
444 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
445 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
446 const DataLayout &DL, BinaryOperator &I,
447 Instruction::BinaryOps InnerOpcode, Value *A,
448 Value *B, Value *C, Value *D) {
450 // If any of A, B, C, D are null, we can not factor I, return early.
451 // Checking A and C should be enough.
452 if (!A || !C || !B || !D)
455 Value *SimplifiedInst = nullptr;
456 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
457 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
459 // Does "X op' Y" always equal "Y op' X"?
460 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
462 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
463 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
464 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
465 // commutative case, "(A op' B) op (C op' A)"?
466 if (A == C || (InnerCommutative && A == D)) {
469 // Consider forming "A op' (B op D)".
470 // If "B op D" simplifies then it can be formed with no cost.
471 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
472 // If "B op D" doesn't simplify then only go on if both of the existing
473 // operations "A op' B" and "C op' D" will be zapped as no longer used.
474 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
475 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
477 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
481 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
482 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
483 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
484 // commutative case, "(A op' B) op (B op' D)"?
485 if (B == D || (InnerCommutative && B == C)) {
488 // Consider forming "(A op C) op' B".
489 // If "A op C" simplifies then it can be formed with no cost.
490 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
492 // If "A op C" doesn't simplify then only go on if both of the existing
493 // operations "A op' B" and "C op' D" will be zapped as no longer used.
494 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
495 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
497 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
501 if (SimplifiedInst) {
503 SimplifiedInst->takeName(&I);
505 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
506 // TODO: Check for NUW.
507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
508 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
510 if (isa<OverflowingBinaryOperator>(&I))
511 HasNSW = I.hasNoSignedWrap();
513 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
514 if (isa<OverflowingBinaryOperator>(Op0))
515 HasNSW &= Op0->hasNoSignedWrap();
517 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
518 if (isa<OverflowingBinaryOperator>(Op1))
519 HasNSW &= Op1->hasNoSignedWrap();
520 BO->setHasNoSignedWrap(HasNSW);
524 return SimplifiedInst;
527 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
528 /// which some other binary operation distributes over either by factorizing
529 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
530 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
531 /// a win). Returns the simplified value, or null if it didn't simplify.
532 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
533 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
534 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
535 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
538 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
539 auto TopLevelOpcode = I.getOpcode();
540 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
541 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
543 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
545 if (LHSOpcode == RHSOpcode) {
546 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
550 // The instruction has the form "(A op' B) op (C)". Try to factorize common
552 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
553 getIdentityValue(LHSOpcode, RHS)))
556 // The instruction has the form "(B) op (C op' D)". Try to factorize common
558 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
559 getIdentityValue(RHSOpcode, LHS), C, D))
563 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
564 // The instruction has the form "(A op' B) op C". See if expanding it out
565 // to "(A op C) op' (B op C)" results in simplifications.
566 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
567 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
569 // Do "A op C" and "B op C" both simplify?
570 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
571 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
572 // They do! Return "L op' R".
574 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
575 if ((L == A && R == B) ||
576 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
578 // Otherwise return "L op' R" if it simplifies.
579 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
581 // Otherwise, create a new instruction.
582 C = Builder->CreateBinOp(InnerOpcode, L, R);
588 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
589 // The instruction has the form "A op (B op' C)". See if expanding it out
590 // to "(A op B) op' (A op C)" results in simplifications.
591 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
592 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
594 // Do "A op B" and "A op C" both simplify?
595 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
596 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
597 // They do! Return "L op' R".
599 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
600 if ((L == B && R == C) ||
601 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
603 // Otherwise return "L op' R" if it simplifies.
604 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
606 // Otherwise, create a new instruction.
607 A = Builder->CreateBinOp(InnerOpcode, L, R);
616 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
617 // if the LHS is a constant zero (which is the 'negate' form).
619 Value *InstCombiner::dyn_castNegVal(Value *V) const {
620 if (BinaryOperator::isNeg(V))
621 return BinaryOperator::getNegArgument(V);
623 // Constants can be considered to be negated values if they can be folded.
624 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
625 return ConstantExpr::getNeg(C);
627 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
628 if (C->getType()->getElementType()->isIntegerTy())
629 return ConstantExpr::getNeg(C);
634 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
635 // instruction if the LHS is a constant negative zero (which is the 'negate'
638 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
639 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
640 return BinaryOperator::getFNegArgument(V);
642 // Constants can be considered to be negated values if they can be folded.
643 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
644 return ConstantExpr::getFNeg(C);
646 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
647 if (C->getType()->getElementType()->isFloatingPointTy())
648 return ConstantExpr::getFNeg(C);
653 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
655 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
656 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
659 // Figure out if the constant is the left or the right argument.
660 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
661 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
663 if (Constant *SOC = dyn_cast<Constant>(SO)) {
665 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
666 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
669 Value *Op0 = SO, *Op1 = ConstOperand;
673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
674 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
675 SO->getName()+".op");
676 Instruction *FPInst = dyn_cast<Instruction>(RI);
677 if (FPInst && isa<FPMathOperator>(FPInst))
678 FPInst->copyFastMathFlags(BO);
681 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
682 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
683 SO->getName()+".cmp");
684 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
685 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
686 SO->getName()+".cmp");
687 llvm_unreachable("Unknown binary instruction type!");
690 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
691 // constant as the other operand, try to fold the binary operator into the
692 // select arguments. This also works for Cast instructions, which obviously do
693 // not have a second operand.
694 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
695 // Don't modify shared select instructions
696 if (!SI->hasOneUse()) return nullptr;
697 Value *TV = SI->getOperand(1);
698 Value *FV = SI->getOperand(2);
700 if (isa<Constant>(TV) || isa<Constant>(FV)) {
701 // Bool selects with constant operands can be folded to logical ops.
702 if (SI->getType()->isIntegerTy(1)) return nullptr;
704 // If it's a bitcast involving vectors, make sure it has the same number of
705 // elements on both sides.
706 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
707 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
708 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
710 // Verify that either both or neither are vectors.
711 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
712 // If vectors, verify that they have the same number of elements.
713 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
717 // Test if a CmpInst instruction is used exclusively by a select as
718 // part of a minimum or maximum operation. If so, refrain from doing
719 // any other folding. This helps out other analyses which understand
720 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
721 // and CodeGen. And in this case, at least one of the comparison
722 // operands has at least one user besides the compare (the select),
723 // which would often largely negate the benefit of folding anyway.
724 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
725 if (CI->hasOneUse()) {
726 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
727 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
728 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
733 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
734 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
736 return SelectInst::Create(SI->getCondition(),
737 SelectTrueVal, SelectFalseVal);
742 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
743 /// has a PHI node as operand #0, see if we can fold the instruction into the
744 /// PHI (which is only possible if all operands to the PHI are constants).
746 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
747 PHINode *PN = cast<PHINode>(I.getOperand(0));
748 unsigned NumPHIValues = PN->getNumIncomingValues();
749 if (NumPHIValues == 0)
752 // We normally only transform phis with a single use. However, if a PHI has
753 // multiple uses and they are all the same operation, we can fold *all* of the
754 // uses into the PHI.
755 if (!PN->hasOneUse()) {
756 // Walk the use list for the instruction, comparing them to I.
757 for (User *U : PN->users()) {
758 Instruction *UI = cast<Instruction>(U);
759 if (UI != &I && !I.isIdenticalTo(UI))
762 // Otherwise, we can replace *all* users with the new PHI we form.
765 // Check to see if all of the operands of the PHI are simple constants
766 // (constantint/constantfp/undef). If there is one non-constant value,
767 // remember the BB it is in. If there is more than one or if *it* is a PHI,
768 // bail out. We don't do arbitrary constant expressions here because moving
769 // their computation can be expensive without a cost model.
770 BasicBlock *NonConstBB = nullptr;
771 for (unsigned i = 0; i != NumPHIValues; ++i) {
772 Value *InVal = PN->getIncomingValue(i);
773 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
776 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
777 if (NonConstBB) return nullptr; // More than one non-const value.
779 NonConstBB = PN->getIncomingBlock(i);
781 // If the InVal is an invoke at the end of the pred block, then we can't
782 // insert a computation after it without breaking the edge.
783 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
784 if (II->getParent() == NonConstBB)
787 // If the incoming non-constant value is in I's block, we will remove one
788 // instruction, but insert another equivalent one, leading to infinite
790 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
794 // If there is exactly one non-constant value, we can insert a copy of the
795 // operation in that block. However, if this is a critical edge, we would be
796 // inserting the computation on some other paths (e.g. inside a loop). Only
797 // do this if the pred block is unconditionally branching into the phi block.
798 if (NonConstBB != nullptr) {
799 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
800 if (!BI || !BI->isUnconditional()) return nullptr;
803 // Okay, we can do the transformation: create the new PHI node.
804 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
805 InsertNewInstBefore(NewPN, *PN);
808 // If we are going to have to insert a new computation, do so right before the
809 // predecessors terminator.
811 Builder->SetInsertPoint(NonConstBB->getTerminator());
813 // Next, add all of the operands to the PHI.
814 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
815 // We only currently try to fold the condition of a select when it is a phi,
816 // not the true/false values.
817 Value *TrueV = SI->getTrueValue();
818 Value *FalseV = SI->getFalseValue();
819 BasicBlock *PhiTransBB = PN->getParent();
820 for (unsigned i = 0; i != NumPHIValues; ++i) {
821 BasicBlock *ThisBB = PN->getIncomingBlock(i);
822 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
823 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
824 Value *InV = nullptr;
825 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
826 // even if currently isNullValue gives false.
827 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
828 if (InC && !isa<ConstantExpr>(InC))
829 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
831 InV = Builder->CreateSelect(PN->getIncomingValue(i),
832 TrueVInPred, FalseVInPred, "phitmp");
833 NewPN->addIncoming(InV, ThisBB);
835 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
836 Constant *C = cast<Constant>(I.getOperand(1));
837 for (unsigned i = 0; i != NumPHIValues; ++i) {
838 Value *InV = nullptr;
839 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
840 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
841 else if (isa<ICmpInst>(CI))
842 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
845 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
849 } else if (I.getNumOperands() == 2) {
850 Constant *C = cast<Constant>(I.getOperand(1));
851 for (unsigned i = 0; i != NumPHIValues; ++i) {
852 Value *InV = nullptr;
853 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
854 InV = ConstantExpr::get(I.getOpcode(), InC, C);
856 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
857 PN->getIncomingValue(i), C, "phitmp");
858 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
861 CastInst *CI = cast<CastInst>(&I);
862 Type *RetTy = CI->getType();
863 for (unsigned i = 0; i != NumPHIValues; ++i) {
865 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
866 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
868 InV = Builder->CreateCast(CI->getOpcode(),
869 PN->getIncomingValue(i), I.getType(), "phitmp");
870 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
874 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
875 Instruction *User = cast<Instruction>(*UI++);
876 if (User == &I) continue;
877 ReplaceInstUsesWith(*User, NewPN);
878 EraseInstFromFunction(*User);
880 return ReplaceInstUsesWith(I, NewPN);
883 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
884 /// whether or not there is a sequence of GEP indices into the pointed type that
885 /// will land us at the specified offset. If so, fill them into NewIndices and
886 /// return the resultant element type, otherwise return null.
887 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
888 SmallVectorImpl<Value *> &NewIndices) {
889 Type *Ty = PtrTy->getElementType();
893 // Start with the index over the outer type. Note that the type size
894 // might be zero (even if the offset isn't zero) if the indexed type
895 // is something like [0 x {int, int}]
896 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
897 int64_t FirstIdx = 0;
898 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
899 FirstIdx = Offset/TySize;
900 Offset -= FirstIdx*TySize;
902 // Handle hosts where % returns negative instead of values [0..TySize).
908 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
911 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
913 // Index into the types. If we fail, set OrigBase to null.
915 // Indexing into tail padding between struct/array elements.
916 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
919 if (StructType *STy = dyn_cast<StructType>(Ty)) {
920 const StructLayout *SL = DL.getStructLayout(STy);
921 assert(Offset < (int64_t)SL->getSizeInBytes() &&
922 "Offset must stay within the indexed type");
924 unsigned Elt = SL->getElementContainingOffset(Offset);
925 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
928 Offset -= SL->getElementOffset(Elt);
929 Ty = STy->getElementType(Elt);
930 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
931 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
932 assert(EltSize && "Cannot index into a zero-sized array");
933 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
935 Ty = AT->getElementType();
937 // Otherwise, we can't index into the middle of this atomic type, bail.
945 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
946 // If this GEP has only 0 indices, it is the same pointer as
947 // Src. If Src is not a trivial GEP too, don't combine
949 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
955 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
956 /// the multiplication is known not to overflow then NoSignedWrap is set.
957 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
958 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
959 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
960 Scale.getBitWidth() && "Scale not compatible with value!");
962 // If Val is zero or Scale is one then Val = Val * Scale.
963 if (match(Val, m_Zero()) || Scale == 1) {
968 // If Scale is zero then it does not divide Val.
969 if (Scale.isMinValue())
972 // Look through chains of multiplications, searching for a constant that is
973 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
974 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
975 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
978 // Val = M1 * X || Analysis starts here and works down
979 // M1 = M2 * Y || Doesn't descend into terms with more
980 // M2 = Z * 4 \/ than one use
982 // Then to modify a term at the bottom:
985 // M1 = Z * Y || Replaced M2 with Z
987 // Then to work back up correcting nsw flags.
989 // Op - the term we are currently analyzing. Starts at Val then drills down.
990 // Replaced with its descaled value before exiting from the drill down loop.
993 // Parent - initially null, but after drilling down notes where Op came from.
994 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
995 // 0'th operand of Val.
996 std::pair<Instruction*, unsigned> Parent;
998 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
999 // levels that doesn't overflow.
1000 bool RequireNoSignedWrap = false;
1002 // logScale - log base 2 of the scale. Negative if not a power of 2.
1003 int32_t logScale = Scale.exactLogBase2();
1005 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1007 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1008 // If Op is a constant divisible by Scale then descale to the quotient.
1009 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1010 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1011 if (!Remainder.isMinValue())
1012 // Not divisible by Scale.
1014 // Replace with the quotient in the parent.
1015 Op = ConstantInt::get(CI->getType(), Quotient);
1016 NoSignedWrap = true;
1020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1022 if (BO->getOpcode() == Instruction::Mul) {
1024 NoSignedWrap = BO->hasNoSignedWrap();
1025 if (RequireNoSignedWrap && !NoSignedWrap)
1028 // There are three cases for multiplication: multiplication by exactly
1029 // the scale, multiplication by a constant different to the scale, and
1030 // multiplication by something else.
1031 Value *LHS = BO->getOperand(0);
1032 Value *RHS = BO->getOperand(1);
1034 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1035 // Multiplication by a constant.
1036 if (CI->getValue() == Scale) {
1037 // Multiplication by exactly the scale, replace the multiplication
1038 // by its left-hand side in the parent.
1043 // Otherwise drill down into the constant.
1044 if (!Op->hasOneUse())
1047 Parent = std::make_pair(BO, 1);
1051 // Multiplication by something else. Drill down into the left-hand side
1052 // since that's where the reassociate pass puts the good stuff.
1053 if (!Op->hasOneUse())
1056 Parent = std::make_pair(BO, 0);
1060 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1061 isa<ConstantInt>(BO->getOperand(1))) {
1062 // Multiplication by a power of 2.
1063 NoSignedWrap = BO->hasNoSignedWrap();
1064 if (RequireNoSignedWrap && !NoSignedWrap)
1067 Value *LHS = BO->getOperand(0);
1068 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1069 getLimitedValue(Scale.getBitWidth());
1072 if (Amt == logScale) {
1073 // Multiplication by exactly the scale, replace the multiplication
1074 // by its left-hand side in the parent.
1078 if (Amt < logScale || !Op->hasOneUse())
1081 // Multiplication by more than the scale. Reduce the multiplying amount
1082 // by the scale in the parent.
1083 Parent = std::make_pair(BO, 1);
1084 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1089 if (!Op->hasOneUse())
1092 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1093 if (Cast->getOpcode() == Instruction::SExt) {
1094 // Op is sign-extended from a smaller type, descale in the smaller type.
1095 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1096 APInt SmallScale = Scale.trunc(SmallSize);
1097 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1098 // descale Op as (sext Y) * Scale. In order to have
1099 // sext (Y * SmallScale) = (sext Y) * Scale
1100 // some conditions need to hold however: SmallScale must sign-extend to
1101 // Scale and the multiplication Y * SmallScale should not overflow.
1102 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1103 // SmallScale does not sign-extend to Scale.
1105 assert(SmallScale.exactLogBase2() == logScale);
1106 // Require that Y * SmallScale must not overflow.
1107 RequireNoSignedWrap = true;
1109 // Drill down through the cast.
1110 Parent = std::make_pair(Cast, 0);
1115 if (Cast->getOpcode() == Instruction::Trunc) {
1116 // Op is truncated from a larger type, descale in the larger type.
1117 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1118 // trunc (Y * sext Scale) = (trunc Y) * Scale
1119 // always holds. However (trunc Y) * Scale may overflow even if
1120 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1121 // from this point up in the expression (see later).
1122 if (RequireNoSignedWrap)
1125 // Drill down through the cast.
1126 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1127 Parent = std::make_pair(Cast, 0);
1128 Scale = Scale.sext(LargeSize);
1129 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1131 assert(Scale.exactLogBase2() == logScale);
1136 // Unsupported expression, bail out.
1140 // If Op is zero then Val = Op * Scale.
1141 if (match(Op, m_Zero())) {
1142 NoSignedWrap = true;
1146 // We know that we can successfully descale, so from here on we can safely
1147 // modify the IR. Op holds the descaled version of the deepest term in the
1148 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1152 // The expression only had one term.
1155 // Rewrite the parent using the descaled version of its operand.
1156 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1157 assert(Op != Parent.first->getOperand(Parent.second) &&
1158 "Descaling was a no-op?");
1159 Parent.first->setOperand(Parent.second, Op);
1160 Worklist.Add(Parent.first);
1162 // Now work back up the expression correcting nsw flags. The logic is based
1163 // on the following observation: if X * Y is known not to overflow as a signed
1164 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1165 // then X * Z will not overflow as a signed multiplication either. As we work
1166 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1167 // current level has strictly smaller absolute value than the original.
1168 Instruction *Ancestor = Parent.first;
1170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1171 // If the multiplication wasn't nsw then we can't say anything about the
1172 // value of the descaled multiplication, and we have to clear nsw flags
1173 // from this point on up.
1174 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1175 NoSignedWrap &= OpNoSignedWrap;
1176 if (NoSignedWrap != OpNoSignedWrap) {
1177 BO->setHasNoSignedWrap(NoSignedWrap);
1178 Worklist.Add(Ancestor);
1180 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1181 // The fact that the descaled input to the trunc has smaller absolute
1182 // value than the original input doesn't tell us anything useful about
1183 // the absolute values of the truncations.
1184 NoSignedWrap = false;
1186 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1187 "Failed to keep proper track of nsw flags while drilling down?");
1189 if (Ancestor == Val)
1190 // Got to the top, all done!
1193 // Move up one level in the expression.
1194 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1195 Ancestor = Ancestor->user_back();
1199 /// \brief Creates node of binary operation with the same attributes as the
1200 /// specified one but with other operands.
1201 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1202 InstCombiner::BuilderTy *B) {
1203 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1204 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1205 if (isa<OverflowingBinaryOperator>(NewBO)) {
1206 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1207 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1209 if (isa<PossiblyExactOperator>(NewBO))
1210 NewBO->setIsExact(Inst.isExact());
1215 /// \brief Makes transformation of binary operation specific for vector types.
1216 /// \param Inst Binary operator to transform.
1217 /// \return Pointer to node that must replace the original binary operator, or
1218 /// null pointer if no transformation was made.
1219 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1220 if (!Inst.getType()->isVectorTy()) return nullptr;
1222 // It may not be safe to reorder shuffles and things like div, urem, etc.
1223 // because we may trap when executing those ops on unknown vector elements.
1225 if (!isSafeToSpeculativelyExecute(&Inst))
1228 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1229 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1230 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1231 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1233 // If both arguments of binary operation are shuffles, which use the same
1234 // mask and shuffle within a single vector, it is worthwhile to move the
1235 // shuffle after binary operation:
1236 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1237 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1238 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1239 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1240 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1241 isa<UndefValue>(RShuf->getOperand(1)) &&
1242 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1243 LShuf->getMask() == RShuf->getMask()) {
1244 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1245 RShuf->getOperand(0), Builder);
1246 Value *Res = Builder->CreateShuffleVector(NewBO,
1247 UndefValue::get(NewBO->getType()), LShuf->getMask());
1252 // If one argument is a shuffle within one vector, the other is a constant,
1253 // try moving the shuffle after the binary operation.
1254 ShuffleVectorInst *Shuffle = nullptr;
1255 Constant *C1 = nullptr;
1256 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1257 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1258 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1259 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1260 if (Shuffle && C1 &&
1261 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1262 isa<UndefValue>(Shuffle->getOperand(1)) &&
1263 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1264 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1265 // Find constant C2 that has property:
1266 // shuffle(C2, ShMask) = C1
1267 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1268 // reorder is not possible.
1269 SmallVector<Constant*, 16> C2M(VWidth,
1270 UndefValue::get(C1->getType()->getScalarType()));
1271 bool MayChange = true;
1272 for (unsigned I = 0; I < VWidth; ++I) {
1273 if (ShMask[I] >= 0) {
1274 assert(ShMask[I] < (int)VWidth);
1275 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1279 C2M[ShMask[I]] = C1->getAggregateElement(I);
1283 Constant *C2 = ConstantVector::get(C2M);
1284 Value *NewLHS, *NewRHS;
1285 if (isa<Constant>(LHS)) {
1287 NewRHS = Shuffle->getOperand(0);
1289 NewLHS = Shuffle->getOperand(0);
1292 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1293 Value *Res = Builder->CreateShuffleVector(NewBO,
1294 UndefValue::get(Inst.getType()), Shuffle->getMask());
1302 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1303 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1305 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1306 return ReplaceInstUsesWith(GEP, V);
1308 Value *PtrOp = GEP.getOperand(0);
1310 // Eliminate unneeded casts for indices, and replace indices which displace
1311 // by multiples of a zero size type with zero.
1312 bool MadeChange = false;
1313 Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
1315 gep_type_iterator GTI = gep_type_begin(GEP);
1316 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1318 // Skip indices into struct types.
1319 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1323 // If the element type has zero size then any index over it is equivalent
1324 // to an index of zero, so replace it with zero if it is not zero already.
1325 if (SeqTy->getElementType()->isSized() &&
1326 DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1327 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1328 *I = Constant::getNullValue(IntPtrTy);
1332 Type *IndexTy = (*I)->getType();
1333 if (IndexTy != IntPtrTy) {
1334 // If we are using a wider index than needed for this platform, shrink
1335 // it to what we need. If narrower, sign-extend it to what we need.
1336 // This explicit cast can make subsequent optimizations more obvious.
1337 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1344 // Check to see if the inputs to the PHI node are getelementptr instructions.
1345 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1346 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1350 // Don't fold a GEP into itself through a PHI node. This can only happen
1351 // through the back-edge of a loop. Folding a GEP into itself means that
1352 // the value of the previous iteration needs to be stored in the meantime,
1353 // thus requiring an additional register variable to be live, but not
1354 // actually achieving anything (the GEP still needs to be executed once per
1361 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1362 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1363 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1366 // As for Op1 above, don't try to fold a GEP into itself.
1370 // Keep track of the type as we walk the GEP.
1371 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1373 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1374 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1377 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1379 // We have not seen any differences yet in the GEPs feeding the
1380 // PHI yet, so we record this one if it is allowed to be a
1383 // The first two arguments can vary for any GEP, the rest have to be
1384 // static for struct slots
1385 if (J > 1 && CurTy->isStructTy())
1390 // The GEP is different by more than one input. While this could be
1391 // extended to support GEPs that vary by more than one variable it
1392 // doesn't make sense since it greatly increases the complexity and
1393 // would result in an R+R+R addressing mode which no backend
1394 // directly supports and would need to be broken into several
1395 // simpler instructions anyway.
1400 // Sink down a layer of the type for the next iteration.
1402 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1403 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1411 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1414 // All the GEPs feeding the PHI are identical. Clone one down into our
1415 // BB so that it can be merged with the current GEP.
1416 GEP.getParent()->getInstList().insert(
1417 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1419 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1420 // into the current block so it can be merged, and create a new PHI to
1422 Instruction *InsertPt = Builder->GetInsertPoint();
1423 Builder->SetInsertPoint(PN);
1424 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1425 PN->getNumOperands());
1426 Builder->SetInsertPoint(InsertPt);
1428 for (auto &I : PN->operands())
1429 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1430 PN->getIncomingBlock(I));
1432 NewGEP->setOperand(DI, NewPN);
1433 GEP.getParent()->getInstList().insert(
1434 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1435 NewGEP->setOperand(DI, NewPN);
1438 GEP.setOperand(0, NewGEP);
1442 // Combine Indices - If the source pointer to this getelementptr instruction
1443 // is a getelementptr instruction, combine the indices of the two
1444 // getelementptr instructions into a single instruction.
1446 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1447 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1450 // Note that if our source is a gep chain itself then we wait for that
1451 // chain to be resolved before we perform this transformation. This
1452 // avoids us creating a TON of code in some cases.
1453 if (GEPOperator *SrcGEP =
1454 dyn_cast<GEPOperator>(Src->getOperand(0)))
1455 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1456 return nullptr; // Wait until our source is folded to completion.
1458 SmallVector<Value*, 8> Indices;
1460 // Find out whether the last index in the source GEP is a sequential idx.
1461 bool EndsWithSequential = false;
1462 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1464 EndsWithSequential = !(*I)->isStructTy();
1466 // Can we combine the two pointer arithmetics offsets?
1467 if (EndsWithSequential) {
1468 // Replace: gep (gep %P, long B), long A, ...
1469 // With: T = long A+B; gep %P, T, ...
1472 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1473 Value *GO1 = GEP.getOperand(1);
1474 if (SO1 == Constant::getNullValue(SO1->getType())) {
1476 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1479 // If they aren't the same type, then the input hasn't been processed
1480 // by the loop above yet (which canonicalizes sequential index types to
1481 // intptr_t). Just avoid transforming this until the input has been
1483 if (SO1->getType() != GO1->getType())
1485 // Only do the combine when GO1 and SO1 are both constants. Only in
1486 // this case, we are sure the cost after the merge is never more than
1487 // that before the merge.
1488 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1490 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1493 // Update the GEP in place if possible.
1494 if (Src->getNumOperands() == 2) {
1495 GEP.setOperand(0, Src->getOperand(0));
1496 GEP.setOperand(1, Sum);
1499 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1500 Indices.push_back(Sum);
1501 Indices.append(GEP.op_begin()+2, GEP.op_end());
1502 } else if (isa<Constant>(*GEP.idx_begin()) &&
1503 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1504 Src->getNumOperands() != 1) {
1505 // Otherwise we can do the fold if the first index of the GEP is a zero
1506 Indices.append(Src->op_begin()+1, Src->op_end());
1507 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1510 if (!Indices.empty())
1511 return GEP.isInBounds() && Src->isInBounds()
1512 ? GetElementPtrInst::CreateInBounds(
1513 Src->getSourceElementType(), Src->getOperand(0), Indices,
1515 : GetElementPtrInst::Create(Src->getSourceElementType(),
1516 Src->getOperand(0), Indices,
1520 if (GEP.getNumIndices() == 1) {
1521 unsigned AS = GEP.getPointerAddressSpace();
1522 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1523 DL.getPointerSizeInBits(AS)) {
1524 Type *PtrTy = GEP.getPointerOperandType();
1525 Type *Ty = PtrTy->getPointerElementType();
1526 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1528 bool Matched = false;
1531 if (TyAllocSize == 1) {
1532 V = GEP.getOperand(1);
1534 } else if (match(GEP.getOperand(1),
1535 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1536 if (TyAllocSize == 1ULL << C)
1538 } else if (match(GEP.getOperand(1),
1539 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1540 if (TyAllocSize == C)
1545 // Canonicalize (gep i8* X, -(ptrtoint Y))
1546 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1547 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1548 // pointer arithmetic.
1549 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1550 Operator *Index = cast<Operator>(V);
1551 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1552 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1553 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1555 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1558 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1559 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1560 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1567 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1568 Value *StrippedPtr = PtrOp->stripPointerCasts();
1569 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1571 // We do not handle pointer-vector geps here.
1575 if (StrippedPtr != PtrOp) {
1576 bool HasZeroPointerIndex = false;
1577 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1578 HasZeroPointerIndex = C->isZero();
1580 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1581 // into : GEP [10 x i8]* X, i32 0, ...
1583 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1584 // into : GEP i8* X, ...
1586 // This occurs when the program declares an array extern like "int X[];"
1587 if (HasZeroPointerIndex) {
1588 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1589 if (ArrayType *CATy =
1590 dyn_cast<ArrayType>(CPTy->getElementType())) {
1591 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1592 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1593 // -> GEP i8* X, ...
1594 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1595 GetElementPtrInst *Res = GetElementPtrInst::Create(
1596 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1597 Res->setIsInBounds(GEP.isInBounds());
1598 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1600 // Insert Res, and create an addrspacecast.
1602 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1604 // %0 = GEP i8 addrspace(1)* X, ...
1605 // addrspacecast i8 addrspace(1)* %0 to i8*
1606 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1609 if (ArrayType *XATy =
1610 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1611 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1612 if (CATy->getElementType() == XATy->getElementType()) {
1613 // -> GEP [10 x i8]* X, i32 0, ...
1614 // At this point, we know that the cast source type is a pointer
1615 // to an array of the same type as the destination pointer
1616 // array. Because the array type is never stepped over (there
1617 // is a leading zero) we can fold the cast into this GEP.
1618 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1619 GEP.setOperand(0, StrippedPtr);
1620 GEP.setSourceElementType(XATy);
1623 // Cannot replace the base pointer directly because StrippedPtr's
1624 // address space is different. Instead, create a new GEP followed by
1625 // an addrspacecast.
1627 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1630 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1631 // addrspacecast i8 addrspace(1)* %0 to i8*
1632 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1633 Value *NewGEP = GEP.isInBounds()
1634 ? Builder->CreateInBoundsGEP(
1635 nullptr, StrippedPtr, Idx, GEP.getName())
1636 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1638 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1642 } else if (GEP.getNumOperands() == 2) {
1643 // Transform things like:
1644 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1645 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1646 Type *SrcElTy = StrippedPtrTy->getElementType();
1647 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1648 if (SrcElTy->isArrayTy() &&
1649 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1650 DL.getTypeAllocSize(ResElTy)) {
1651 Type *IdxType = DL.getIntPtrType(GEP.getType());
1652 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1655 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1657 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1659 // V and GEP are both pointer types --> BitCast
1660 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1664 // Transform things like:
1665 // %V = mul i64 %N, 4
1666 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1667 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1668 if (ResElTy->isSized() && SrcElTy->isSized()) {
1669 // Check that changing the type amounts to dividing the index by a scale
1671 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1672 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1673 if (ResSize && SrcSize % ResSize == 0) {
1674 Value *Idx = GEP.getOperand(1);
1675 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1676 uint64_t Scale = SrcSize / ResSize;
1678 // Earlier transforms ensure that the index has type IntPtrType, which
1679 // considerably simplifies the logic by eliminating implicit casts.
1680 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1681 "Index not cast to pointer width?");
1684 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1685 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1686 // If the multiplication NewIdx * Scale may overflow then the new
1687 // GEP may not be "inbounds".
1689 GEP.isInBounds() && NSW
1690 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1692 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1695 // The NewGEP must be pointer typed, so must the old one -> BitCast
1696 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1702 // Similarly, transform things like:
1703 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1704 // (where tmp = 8*tmp2) into:
1705 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1706 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1707 // Check that changing to the array element type amounts to dividing the
1708 // index by a scale factor.
1709 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1710 uint64_t ArrayEltSize =
1711 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1712 if (ResSize && ArrayEltSize % ResSize == 0) {
1713 Value *Idx = GEP.getOperand(1);
1714 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1715 uint64_t Scale = ArrayEltSize / ResSize;
1717 // Earlier transforms ensure that the index has type IntPtrType, which
1718 // considerably simplifies the logic by eliminating implicit casts.
1719 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1720 "Index not cast to pointer width?");
1723 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1724 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1725 // If the multiplication NewIdx * Scale may overflow then the new
1726 // GEP may not be "inbounds".
1728 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1731 Value *NewGEP = GEP.isInBounds() && NSW
1732 ? Builder->CreateInBoundsGEP(
1733 SrcElTy, StrippedPtr, Off, GEP.getName())
1734 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1736 // The NewGEP must be pointer typed, so must the old one -> BitCast
1737 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1745 // addrspacecast between types is canonicalized as a bitcast, then an
1746 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1747 // through the addrspacecast.
1748 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1749 // X = bitcast A addrspace(1)* to B addrspace(1)*
1750 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1751 // Z = gep Y, <...constant indices...>
1752 // Into an addrspacecasted GEP of the struct.
1753 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1757 /// See if we can simplify:
1758 /// X = bitcast A* to B*
1759 /// Y = gep X, <...constant indices...>
1760 /// into a gep of the original struct. This is important for SROA and alias
1761 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1762 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1763 Value *Operand = BCI->getOperand(0);
1764 PointerType *OpType = cast<PointerType>(Operand->getType());
1765 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1766 APInt Offset(OffsetBits, 0);
1767 if (!isa<BitCastInst>(Operand) &&
1768 GEP.accumulateConstantOffset(DL, Offset)) {
1770 // If this GEP instruction doesn't move the pointer, just replace the GEP
1771 // with a bitcast of the real input to the dest type.
1773 // If the bitcast is of an allocation, and the allocation will be
1774 // converted to match the type of the cast, don't touch this.
1775 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1776 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1777 if (Instruction *I = visitBitCast(*BCI)) {
1780 BCI->getParent()->getInstList().insert(BCI, I);
1781 ReplaceInstUsesWith(*BCI, I);
1787 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1788 return new AddrSpaceCastInst(Operand, GEP.getType());
1789 return new BitCastInst(Operand, GEP.getType());
1792 // Otherwise, if the offset is non-zero, we need to find out if there is a
1793 // field at Offset in 'A's type. If so, we can pull the cast through the
1795 SmallVector<Value*, 8> NewIndices;
1796 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1799 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1800 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1802 if (NGEP->getType() == GEP.getType())
1803 return ReplaceInstUsesWith(GEP, NGEP);
1804 NGEP->takeName(&GEP);
1806 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1807 return new AddrSpaceCastInst(NGEP, GEP.getType());
1808 return new BitCastInst(NGEP, GEP.getType());
1817 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1818 const TargetLibraryInfo *TLI) {
1819 SmallVector<Instruction*, 4> Worklist;
1820 Worklist.push_back(AI);
1823 Instruction *PI = Worklist.pop_back_val();
1824 for (User *U : PI->users()) {
1825 Instruction *I = cast<Instruction>(U);
1826 switch (I->getOpcode()) {
1828 // Give up the moment we see something we can't handle.
1831 case Instruction::BitCast:
1832 case Instruction::GetElementPtr:
1834 Worklist.push_back(I);
1837 case Instruction::ICmp: {
1838 ICmpInst *ICI = cast<ICmpInst>(I);
1839 // We can fold eq/ne comparisons with null to false/true, respectively.
1840 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1846 case Instruction::Call:
1847 // Ignore no-op and store intrinsics.
1848 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1849 switch (II->getIntrinsicID()) {
1853 case Intrinsic::memmove:
1854 case Intrinsic::memcpy:
1855 case Intrinsic::memset: {
1856 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1857 if (MI->isVolatile() || MI->getRawDest() != PI)
1861 case Intrinsic::dbg_declare:
1862 case Intrinsic::dbg_value:
1863 case Intrinsic::invariant_start:
1864 case Intrinsic::invariant_end:
1865 case Intrinsic::lifetime_start:
1866 case Intrinsic::lifetime_end:
1867 case Intrinsic::objectsize:
1873 if (isFreeCall(I, TLI)) {
1879 case Instruction::Store: {
1880 StoreInst *SI = cast<StoreInst>(I);
1881 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1887 llvm_unreachable("missing a return?");
1889 } while (!Worklist.empty());
1893 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1894 // If we have a malloc call which is only used in any amount of comparisons
1895 // to null and free calls, delete the calls and replace the comparisons with
1896 // true or false as appropriate.
1897 SmallVector<WeakVH, 64> Users;
1898 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1899 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1900 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1903 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1904 ReplaceInstUsesWith(*C,
1905 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1906 C->isFalseWhenEqual()));
1907 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1908 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1909 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1910 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1911 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1912 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1913 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1916 EraseInstFromFunction(*I);
1919 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1920 // Replace invoke with a NOP intrinsic to maintain the original CFG
1921 Module *M = II->getParent()->getParent()->getParent();
1922 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1923 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1924 None, "", II->getParent());
1926 return EraseInstFromFunction(MI);
1931 /// \brief Move the call to free before a NULL test.
1933 /// Check if this free is accessed after its argument has been test
1934 /// against NULL (property 0).
1935 /// If yes, it is legal to move this call in its predecessor block.
1937 /// The move is performed only if the block containing the call to free
1938 /// will be removed, i.e.:
1939 /// 1. it has only one predecessor P, and P has two successors
1940 /// 2. it contains the call and an unconditional branch
1941 /// 3. its successor is the same as its predecessor's successor
1943 /// The profitability is out-of concern here and this function should
1944 /// be called only if the caller knows this transformation would be
1945 /// profitable (e.g., for code size).
1946 static Instruction *
1947 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1948 Value *Op = FI.getArgOperand(0);
1949 BasicBlock *FreeInstrBB = FI.getParent();
1950 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1952 // Validate part of constraint #1: Only one predecessor
1953 // FIXME: We can extend the number of predecessor, but in that case, we
1954 // would duplicate the call to free in each predecessor and it may
1955 // not be profitable even for code size.
1959 // Validate constraint #2: Does this block contains only the call to
1960 // free and an unconditional branch?
1961 // FIXME: We could check if we can speculate everything in the
1962 // predecessor block
1963 if (FreeInstrBB->size() != 2)
1966 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1969 // Validate the rest of constraint #1 by matching on the pred branch.
1970 TerminatorInst *TI = PredBB->getTerminator();
1971 BasicBlock *TrueBB, *FalseBB;
1972 ICmpInst::Predicate Pred;
1973 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1975 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1978 // Validate constraint #3: Ensure the null case just falls through.
1979 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1981 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1982 "Broken CFG: missing edge from predecessor to successor");
1989 Instruction *InstCombiner::visitFree(CallInst &FI) {
1990 Value *Op = FI.getArgOperand(0);
1992 // free undef -> unreachable.
1993 if (isa<UndefValue>(Op)) {
1994 // Insert a new store to null because we cannot modify the CFG here.
1995 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1996 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1997 return EraseInstFromFunction(FI);
2000 // If we have 'free null' delete the instruction. This can happen in stl code
2001 // when lots of inlining happens.
2002 if (isa<ConstantPointerNull>(Op))
2003 return EraseInstFromFunction(FI);
2005 // If we optimize for code size, try to move the call to free before the null
2006 // test so that simplify cfg can remove the empty block and dead code
2007 // elimination the branch. I.e., helps to turn something like:
2008 // if (foo) free(foo);
2012 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2018 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2019 if (RI.getNumOperands() == 0) // ret void
2022 Value *ResultOp = RI.getOperand(0);
2023 Type *VTy = ResultOp->getType();
2024 if (!VTy->isIntegerTy())
2027 // There might be assume intrinsics dominating this return that completely
2028 // determine the value. If so, constant fold it.
2029 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2030 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2031 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2032 if ((KnownZero|KnownOne).isAllOnesValue())
2033 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2038 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2039 // Change br (not X), label True, label False to: br X, label False, True
2041 BasicBlock *TrueDest;
2042 BasicBlock *FalseDest;
2043 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2044 !isa<Constant>(X)) {
2045 // Swap Destinations and condition...
2047 BI.swapSuccessors();
2051 // If the condition is irrelevant, remove the use so that other
2052 // transforms on the condition become more effective.
2053 if (BI.isConditional() &&
2054 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2055 !isa<UndefValue>(BI.getCondition())) {
2056 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2060 // Canonicalize fcmp_one -> fcmp_oeq
2061 FCmpInst::Predicate FPred; Value *Y;
2062 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2063 TrueDest, FalseDest)) &&
2064 BI.getCondition()->hasOneUse())
2065 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2066 FPred == FCmpInst::FCMP_OGE) {
2067 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2068 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2070 // Swap Destinations and condition.
2071 BI.swapSuccessors();
2076 // Canonicalize icmp_ne -> icmp_eq
2077 ICmpInst::Predicate IPred;
2078 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2079 TrueDest, FalseDest)) &&
2080 BI.getCondition()->hasOneUse())
2081 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2082 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2083 IPred == ICmpInst::ICMP_SGE) {
2084 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2085 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2086 // Swap Destinations and condition.
2087 BI.swapSuccessors();
2095 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2096 Value *Cond = SI.getCondition();
2097 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2098 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2099 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2100 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2101 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2103 // Compute the number of leading bits we can ignore.
2104 for (auto &C : SI.cases()) {
2105 LeadingKnownZeros = std::min(
2106 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2107 LeadingKnownOnes = std::min(
2108 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2111 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2113 // Truncate the condition operand if the new type is equal to or larger than
2114 // the largest legal integer type. We need to be conservative here since
2115 // x86 generates redundant zero-extenstion instructions if the operand is
2116 // truncated to i8 or i16.
2117 bool TruncCond = false;
2118 if (NewWidth > 0 && BitWidth > NewWidth &&
2119 NewWidth >= DL.getLargestLegalIntTypeSize()) {
2121 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2122 Builder->SetInsertPoint(&SI);
2123 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2124 SI.setCondition(NewCond);
2126 for (auto &C : SI.cases())
2127 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2128 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2131 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2132 if (I->getOpcode() == Instruction::Add)
2133 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2134 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2135 // Skip the first item since that's the default case.
2136 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2138 ConstantInt* CaseVal = i.getCaseValue();
2139 Constant *LHS = CaseVal;
2141 LHS = LeadingKnownZeros
2142 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2143 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2144 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2145 assert(isa<ConstantInt>(NewCaseVal) &&
2146 "Result of expression should be constant");
2147 i.setValue(cast<ConstantInt>(NewCaseVal));
2149 SI.setCondition(I->getOperand(0));
2155 return TruncCond ? &SI : nullptr;
2158 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2159 Value *Agg = EV.getAggregateOperand();
2161 if (!EV.hasIndices())
2162 return ReplaceInstUsesWith(EV, Agg);
2164 if (Constant *C = dyn_cast<Constant>(Agg)) {
2165 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2166 if (EV.getNumIndices() == 0)
2167 return ReplaceInstUsesWith(EV, C2);
2168 // Extract the remaining indices out of the constant indexed by the
2170 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2172 return nullptr; // Can't handle other constants
2175 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2176 // We're extracting from an insertvalue instruction, compare the indices
2177 const unsigned *exti, *exte, *insi, *inse;
2178 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2179 exte = EV.idx_end(), inse = IV->idx_end();
2180 exti != exte && insi != inse;
2183 // The insert and extract both reference distinctly different elements.
2184 // This means the extract is not influenced by the insert, and we can
2185 // replace the aggregate operand of the extract with the aggregate
2186 // operand of the insert. i.e., replace
2187 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2188 // %E = extractvalue { i32, { i32 } } %I, 0
2190 // %E = extractvalue { i32, { i32 } } %A, 0
2191 return ExtractValueInst::Create(IV->getAggregateOperand(),
2194 if (exti == exte && insi == inse)
2195 // Both iterators are at the end: Index lists are identical. Replace
2196 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2197 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2199 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2201 // The extract list is a prefix of the insert list. i.e. replace
2202 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2203 // %E = extractvalue { i32, { i32 } } %I, 1
2205 // %X = extractvalue { i32, { i32 } } %A, 1
2206 // %E = insertvalue { i32 } %X, i32 42, 0
2207 // by switching the order of the insert and extract (though the
2208 // insertvalue should be left in, since it may have other uses).
2209 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2211 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2212 makeArrayRef(insi, inse));
2215 // The insert list is a prefix of the extract list
2216 // We can simply remove the common indices from the extract and make it
2217 // operate on the inserted value instead of the insertvalue result.
2219 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2220 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2222 // %E extractvalue { i32 } { i32 42 }, 0
2223 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2224 makeArrayRef(exti, exte));
2226 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2227 // We're extracting from an intrinsic, see if we're the only user, which
2228 // allows us to simplify multiple result intrinsics to simpler things that
2229 // just get one value.
2230 if (II->hasOneUse()) {
2231 // Check if we're grabbing the overflow bit or the result of a 'with
2232 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2233 // and replace it with a traditional binary instruction.
2234 switch (II->getIntrinsicID()) {
2235 case Intrinsic::uadd_with_overflow:
2236 case Intrinsic::sadd_with_overflow:
2237 if (*EV.idx_begin() == 0) { // Normal result.
2238 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2239 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2240 EraseInstFromFunction(*II);
2241 return BinaryOperator::CreateAdd(LHS, RHS);
2244 // If the normal result of the add is dead, and the RHS is a constant,
2245 // we can transform this into a range comparison.
2246 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2247 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2248 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2249 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2250 ConstantExpr::getNot(CI));
2252 case Intrinsic::usub_with_overflow:
2253 case Intrinsic::ssub_with_overflow:
2254 if (*EV.idx_begin() == 0) { // Normal result.
2255 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2256 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2257 EraseInstFromFunction(*II);
2258 return BinaryOperator::CreateSub(LHS, RHS);
2261 case Intrinsic::umul_with_overflow:
2262 case Intrinsic::smul_with_overflow:
2263 if (*EV.idx_begin() == 0) { // Normal result.
2264 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2265 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2266 EraseInstFromFunction(*II);
2267 return BinaryOperator::CreateMul(LHS, RHS);
2275 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2276 // If the (non-volatile) load only has one use, we can rewrite this to a
2277 // load from a GEP. This reduces the size of the load.
2278 // FIXME: If a load is used only by extractvalue instructions then this
2279 // could be done regardless of having multiple uses.
2280 if (L->isSimple() && L->hasOneUse()) {
2281 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2282 SmallVector<Value*, 4> Indices;
2283 // Prefix an i32 0 since we need the first element.
2284 Indices.push_back(Builder->getInt32(0));
2285 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2287 Indices.push_back(Builder->getInt32(*I));
2289 // We need to insert these at the location of the old load, not at that of
2290 // the extractvalue.
2291 Builder->SetInsertPoint(L->getParent(), L);
2292 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2293 L->getPointerOperand(), Indices);
2294 // Returning the load directly will cause the main loop to insert it in
2295 // the wrong spot, so use ReplaceInstUsesWith().
2296 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2298 // We could simplify extracts from other values. Note that nested extracts may
2299 // already be simplified implicitly by the above: extract (extract (insert) )
2300 // will be translated into extract ( insert ( extract ) ) first and then just
2301 // the value inserted, if appropriate. Similarly for extracts from single-use
2302 // loads: extract (extract (load)) will be translated to extract (load (gep))
2303 // and if again single-use then via load (gep (gep)) to load (gep).
2304 // However, double extracts from e.g. function arguments or return values
2305 // aren't handled yet.
2309 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2310 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2311 switch (Personality) {
2312 case EHPersonality::GNU_C:
2313 // The GCC C EH personality only exists to support cleanups, so it's not
2314 // clear what the semantics of catch clauses are.
2316 case EHPersonality::Unknown:
2318 case EHPersonality::GNU_Ada:
2319 // While __gnat_all_others_value will match any Ada exception, it doesn't
2320 // match foreign exceptions (or didn't, before gcc-4.7).
2322 case EHPersonality::GNU_CXX:
2323 case EHPersonality::GNU_ObjC:
2324 case EHPersonality::MSVC_X86SEH:
2325 case EHPersonality::MSVC_Win64SEH:
2326 case EHPersonality::MSVC_CXX:
2327 return TypeInfo->isNullValue();
2329 llvm_unreachable("invalid enum");
2332 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2334 cast<ArrayType>(LHS->getType())->getNumElements()
2336 cast<ArrayType>(RHS->getType())->getNumElements();
2339 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2340 // The logic here should be correct for any real-world personality function.
2341 // However if that turns out not to be true, the offending logic can always
2342 // be conditioned on the personality function, like the catch-all logic is.
2343 EHPersonality Personality = classifyEHPersonality(LI.getPersonalityFn());
2345 // Simplify the list of clauses, eg by removing repeated catch clauses
2346 // (these are often created by inlining).
2347 bool MakeNewInstruction = false; // If true, recreate using the following:
2348 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2349 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2351 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2352 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2353 bool isLastClause = i + 1 == e;
2354 if (LI.isCatch(i)) {
2356 Constant *CatchClause = LI.getClause(i);
2357 Constant *TypeInfo = CatchClause->stripPointerCasts();
2359 // If we already saw this clause, there is no point in having a second
2361 if (AlreadyCaught.insert(TypeInfo).second) {
2362 // This catch clause was not already seen.
2363 NewClauses.push_back(CatchClause);
2365 // Repeated catch clause - drop the redundant copy.
2366 MakeNewInstruction = true;
2369 // If this is a catch-all then there is no point in keeping any following
2370 // clauses or marking the landingpad as having a cleanup.
2371 if (isCatchAll(Personality, TypeInfo)) {
2373 MakeNewInstruction = true;
2374 CleanupFlag = false;
2378 // A filter clause. If any of the filter elements were already caught
2379 // then they can be dropped from the filter. It is tempting to try to
2380 // exploit the filter further by saying that any typeinfo that does not
2381 // occur in the filter can't be caught later (and thus can be dropped).
2382 // However this would be wrong, since typeinfos can match without being
2383 // equal (for example if one represents a C++ class, and the other some
2384 // class derived from it).
2385 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2386 Constant *FilterClause = LI.getClause(i);
2387 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2388 unsigned NumTypeInfos = FilterType->getNumElements();
2390 // An empty filter catches everything, so there is no point in keeping any
2391 // following clauses or marking the landingpad as having a cleanup. By
2392 // dealing with this case here the following code is made a bit simpler.
2393 if (!NumTypeInfos) {
2394 NewClauses.push_back(FilterClause);
2396 MakeNewInstruction = true;
2397 CleanupFlag = false;
2401 bool MakeNewFilter = false; // If true, make a new filter.
2402 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2403 if (isa<ConstantAggregateZero>(FilterClause)) {
2404 // Not an empty filter - it contains at least one null typeinfo.
2405 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2406 Constant *TypeInfo =
2407 Constant::getNullValue(FilterType->getElementType());
2408 // If this typeinfo is a catch-all then the filter can never match.
2409 if (isCatchAll(Personality, TypeInfo)) {
2410 // Throw the filter away.
2411 MakeNewInstruction = true;
2415 // There is no point in having multiple copies of this typeinfo, so
2416 // discard all but the first copy if there is more than one.
2417 NewFilterElts.push_back(TypeInfo);
2418 if (NumTypeInfos > 1)
2419 MakeNewFilter = true;
2421 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2422 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2423 NewFilterElts.reserve(NumTypeInfos);
2425 // Remove any filter elements that were already caught or that already
2426 // occurred in the filter. While there, see if any of the elements are
2427 // catch-alls. If so, the filter can be discarded.
2428 bool SawCatchAll = false;
2429 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2430 Constant *Elt = Filter->getOperand(j);
2431 Constant *TypeInfo = Elt->stripPointerCasts();
2432 if (isCatchAll(Personality, TypeInfo)) {
2433 // This element is a catch-all. Bail out, noting this fact.
2437 if (AlreadyCaught.count(TypeInfo))
2438 // Already caught by an earlier clause, so having it in the filter
2441 // There is no point in having multiple copies of the same typeinfo in
2442 // a filter, so only add it if we didn't already.
2443 if (SeenInFilter.insert(TypeInfo).second)
2444 NewFilterElts.push_back(cast<Constant>(Elt));
2446 // A filter containing a catch-all cannot match anything by definition.
2448 // Throw the filter away.
2449 MakeNewInstruction = true;
2453 // If we dropped something from the filter, make a new one.
2454 if (NewFilterElts.size() < NumTypeInfos)
2455 MakeNewFilter = true;
2457 if (MakeNewFilter) {
2458 FilterType = ArrayType::get(FilterType->getElementType(),
2459 NewFilterElts.size());
2460 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2461 MakeNewInstruction = true;
2464 NewClauses.push_back(FilterClause);
2466 // If the new filter is empty then it will catch everything so there is
2467 // no point in keeping any following clauses or marking the landingpad
2468 // as having a cleanup. The case of the original filter being empty was
2469 // already handled above.
2470 if (MakeNewFilter && !NewFilterElts.size()) {
2471 assert(MakeNewInstruction && "New filter but not a new instruction!");
2472 CleanupFlag = false;
2478 // If several filters occur in a row then reorder them so that the shortest
2479 // filters come first (those with the smallest number of elements). This is
2480 // advantageous because shorter filters are more likely to match, speeding up
2481 // unwinding, but mostly because it increases the effectiveness of the other
2482 // filter optimizations below.
2483 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2485 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2486 for (j = i; j != e; ++j)
2487 if (!isa<ArrayType>(NewClauses[j]->getType()))
2490 // Check whether the filters are already sorted by length. We need to know
2491 // if sorting them is actually going to do anything so that we only make a
2492 // new landingpad instruction if it does.
2493 for (unsigned k = i; k + 1 < j; ++k)
2494 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2495 // Not sorted, so sort the filters now. Doing an unstable sort would be
2496 // correct too but reordering filters pointlessly might confuse users.
2497 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2499 MakeNewInstruction = true;
2503 // Look for the next batch of filters.
2507 // If typeinfos matched if and only if equal, then the elements of a filter L
2508 // that occurs later than a filter F could be replaced by the intersection of
2509 // the elements of F and L. In reality two typeinfos can match without being
2510 // equal (for example if one represents a C++ class, and the other some class
2511 // derived from it) so it would be wrong to perform this transform in general.
2512 // However the transform is correct and useful if F is a subset of L. In that
2513 // case L can be replaced by F, and thus removed altogether since repeating a
2514 // filter is pointless. So here we look at all pairs of filters F and L where
2515 // L follows F in the list of clauses, and remove L if every element of F is
2516 // an element of L. This can occur when inlining C++ functions with exception
2518 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2519 // Examine each filter in turn.
2520 Value *Filter = NewClauses[i];
2521 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2523 // Not a filter - skip it.
2525 unsigned FElts = FTy->getNumElements();
2526 // Examine each filter following this one. Doing this backwards means that
2527 // we don't have to worry about filters disappearing under us when removed.
2528 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2529 Value *LFilter = NewClauses[j];
2530 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2532 // Not a filter - skip it.
2534 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2535 // an element of LFilter, then discard LFilter.
2536 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2537 // If Filter is empty then it is a subset of LFilter.
2540 NewClauses.erase(J);
2541 MakeNewInstruction = true;
2542 // Move on to the next filter.
2545 unsigned LElts = LTy->getNumElements();
2546 // If Filter is longer than LFilter then it cannot be a subset of it.
2548 // Move on to the next filter.
2550 // At this point we know that LFilter has at least one element.
2551 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2552 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2553 // already know that Filter is not longer than LFilter).
2554 if (isa<ConstantAggregateZero>(Filter)) {
2555 assert(FElts <= LElts && "Should have handled this case earlier!");
2557 NewClauses.erase(J);
2558 MakeNewInstruction = true;
2560 // Move on to the next filter.
2563 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2564 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2565 // Since Filter is non-empty and contains only zeros, it is a subset of
2566 // LFilter iff LFilter contains a zero.
2567 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2568 for (unsigned l = 0; l != LElts; ++l)
2569 if (LArray->getOperand(l)->isNullValue()) {
2570 // LFilter contains a zero - discard it.
2571 NewClauses.erase(J);
2572 MakeNewInstruction = true;
2575 // Move on to the next filter.
2578 // At this point we know that both filters are ConstantArrays. Loop over
2579 // operands to see whether every element of Filter is also an element of
2580 // LFilter. Since filters tend to be short this is probably faster than
2581 // using a method that scales nicely.
2582 ConstantArray *FArray = cast<ConstantArray>(Filter);
2583 bool AllFound = true;
2584 for (unsigned f = 0; f != FElts; ++f) {
2585 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2587 for (unsigned l = 0; l != LElts; ++l) {
2588 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2589 if (LTypeInfo == FTypeInfo) {
2599 NewClauses.erase(J);
2600 MakeNewInstruction = true;
2602 // Move on to the next filter.
2606 // If we changed any of the clauses, replace the old landingpad instruction
2608 if (MakeNewInstruction) {
2609 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2610 LI.getPersonalityFn(),
2612 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2613 NLI->addClause(NewClauses[i]);
2614 // A landing pad with no clauses must have the cleanup flag set. It is
2615 // theoretically possible, though highly unlikely, that we eliminated all
2616 // clauses. If so, force the cleanup flag to true.
2617 if (NewClauses.empty())
2619 NLI->setCleanup(CleanupFlag);
2623 // Even if none of the clauses changed, we may nonetheless have understood
2624 // that the cleanup flag is pointless. Clear it if so.
2625 if (LI.isCleanup() != CleanupFlag) {
2626 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2627 LI.setCleanup(CleanupFlag);
2634 /// TryToSinkInstruction - Try to move the specified instruction from its
2635 /// current block into the beginning of DestBlock, which can only happen if it's
2636 /// safe to move the instruction past all of the instructions between it and the
2637 /// end of its block.
2638 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2639 assert(I->hasOneUse() && "Invariants didn't hold!");
2641 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2642 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2643 isa<TerminatorInst>(I))
2646 // Do not sink alloca instructions out of the entry block.
2647 if (isa<AllocaInst>(I) && I->getParent() ==
2648 &DestBlock->getParent()->getEntryBlock())
2651 // We can only sink load instructions if there is nothing between the load and
2652 // the end of block that could change the value.
2653 if (I->mayReadFromMemory()) {
2654 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2656 if (Scan->mayWriteToMemory())
2660 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2661 I->moveBefore(InsertPos);
2666 bool InstCombiner::run() {
2667 while (!Worklist.isEmpty()) {
2668 Instruction *I = Worklist.RemoveOne();
2669 if (I == nullptr) continue; // skip null values.
2671 // Check to see if we can DCE the instruction.
2672 if (isInstructionTriviallyDead(I, TLI)) {
2673 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2674 EraseInstFromFunction(*I);
2676 MadeIRChange = true;
2680 // Instruction isn't dead, see if we can constant propagate it.
2681 if (!I->use_empty() && isa<Constant>(I->getOperand(0))) {
2682 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2683 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2685 // Add operands to the worklist.
2686 ReplaceInstUsesWith(*I, C);
2688 EraseInstFromFunction(*I);
2689 MadeIRChange = true;
2694 // See if we can trivially sink this instruction to a successor basic block.
2695 if (I->hasOneUse()) {
2696 BasicBlock *BB = I->getParent();
2697 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2698 BasicBlock *UserParent;
2700 // Get the block the use occurs in.
2701 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2702 UserParent = PN->getIncomingBlock(*I->use_begin());
2704 UserParent = UserInst->getParent();
2706 if (UserParent != BB) {
2707 bool UserIsSuccessor = false;
2708 // See if the user is one of our successors.
2709 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2710 if (*SI == UserParent) {
2711 UserIsSuccessor = true;
2715 // If the user is one of our immediate successors, and if that successor
2716 // only has us as a predecessors (we'd have to split the critical edge
2717 // otherwise), we can keep going.
2718 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2719 // Okay, the CFG is simple enough, try to sink this instruction.
2720 if (TryToSinkInstruction(I, UserParent)) {
2721 MadeIRChange = true;
2722 // We'll add uses of the sunk instruction below, but since sinking
2723 // can expose opportunities for it's *operands* add them to the
2725 for (Use &U : I->operands())
2726 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2733 // Now that we have an instruction, try combining it to simplify it.
2734 Builder->SetInsertPoint(I->getParent(), I);
2735 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2740 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2741 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2743 if (Instruction *Result = visit(*I)) {
2745 // Should we replace the old instruction with a new one?
2747 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2748 << " New = " << *Result << '\n');
2750 if (I->getDebugLoc())
2751 Result->setDebugLoc(I->getDebugLoc());
2752 // Everything uses the new instruction now.
2753 I->replaceAllUsesWith(Result);
2755 // Move the name to the new instruction first.
2756 Result->takeName(I);
2758 // Push the new instruction and any users onto the worklist.
2759 Worklist.Add(Result);
2760 Worklist.AddUsersToWorkList(*Result);
2762 // Insert the new instruction into the basic block...
2763 BasicBlock *InstParent = I->getParent();
2764 BasicBlock::iterator InsertPos = I;
2766 // If we replace a PHI with something that isn't a PHI, fix up the
2768 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2769 InsertPos = InstParent->getFirstInsertionPt();
2771 InstParent->getInstList().insert(InsertPos, Result);
2773 EraseInstFromFunction(*I);
2776 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2777 << " New = " << *I << '\n');
2780 // If the instruction was modified, it's possible that it is now dead.
2781 // if so, remove it.
2782 if (isInstructionTriviallyDead(I, TLI)) {
2783 EraseInstFromFunction(*I);
2786 Worklist.AddUsersToWorkList(*I);
2789 MadeIRChange = true;
2794 return MadeIRChange;
2797 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2798 /// all reachable code to the worklist.
2800 /// This has a couple of tricks to make the code faster and more powerful. In
2801 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2802 /// them to the worklist (this significantly speeds up instcombine on code where
2803 /// many instructions are dead or constant). Additionally, if we find a branch
2804 /// whose condition is a known constant, we only visit the reachable successors.
2806 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2807 SmallPtrSetImpl<BasicBlock *> &Visited,
2808 InstCombineWorklist &ICWorklist,
2809 const TargetLibraryInfo *TLI) {
2810 bool MadeIRChange = false;
2811 SmallVector<BasicBlock*, 256> Worklist;
2812 Worklist.push_back(BB);
2814 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2815 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2818 BB = Worklist.pop_back_val();
2820 // We have now visited this block! If we've already been here, ignore it.
2821 if (!Visited.insert(BB).second)
2824 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2825 Instruction *Inst = BBI++;
2827 // DCE instruction if trivially dead.
2828 if (isInstructionTriviallyDead(Inst, TLI)) {
2830 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2831 Inst->eraseFromParent();
2835 // ConstantProp instruction if trivially constant.
2836 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2837 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2838 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2840 Inst->replaceAllUsesWith(C);
2842 Inst->eraseFromParent();
2846 // See if we can constant fold its operands.
2847 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2849 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2853 Constant *&FoldRes = FoldedConstants[CE];
2855 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2859 if (FoldRes != CE) {
2861 MadeIRChange = true;
2865 InstrsForInstCombineWorklist.push_back(Inst);
2868 // Recursively visit successors. If this is a branch or switch on a
2869 // constant, only visit the reachable successor.
2870 TerminatorInst *TI = BB->getTerminator();
2871 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2872 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2873 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2874 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2875 Worklist.push_back(ReachableBB);
2878 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2879 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2880 // See if this is an explicit destination.
2881 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2883 if (i.getCaseValue() == Cond) {
2884 BasicBlock *ReachableBB = i.getCaseSuccessor();
2885 Worklist.push_back(ReachableBB);
2889 // Otherwise it is the default destination.
2890 Worklist.push_back(SI->getDefaultDest());
2895 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2896 Worklist.push_back(TI->getSuccessor(i));
2897 } while (!Worklist.empty());
2899 // Once we've found all of the instructions to add to instcombine's worklist,
2900 // add them in reverse order. This way instcombine will visit from the top
2901 // of the function down. This jives well with the way that it adds all uses
2902 // of instructions to the worklist after doing a transformation, thus avoiding
2903 // some N^2 behavior in pathological cases.
2904 ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2905 InstrsForInstCombineWorklist.size());
2907 return MadeIRChange;
2910 /// \brief Populate the IC worklist from a function, and prune any dead basic
2911 /// blocks discovered in the process.
2913 /// This also does basic constant propagation and other forward fixing to make
2914 /// the combiner itself run much faster.
2915 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
2916 TargetLibraryInfo *TLI,
2917 InstCombineWorklist &ICWorklist) {
2918 bool MadeIRChange = false;
2920 // Do a depth-first traversal of the function, populate the worklist with
2921 // the reachable instructions. Ignore blocks that are not reachable. Keep
2922 // track of which blocks we visit.
2923 SmallPtrSet<BasicBlock *, 64> Visited;
2925 AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
2927 // Do a quick scan over the function. If we find any blocks that are
2928 // unreachable, remove any instructions inside of them. This prevents
2929 // the instcombine code from having to deal with some bad special cases.
2930 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2931 if (Visited.count(BB))
2934 // Delete the instructions backwards, as it has a reduced likelihood of
2935 // having to update as many def-use and use-def chains.
2936 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2937 while (EndInst != BB->begin()) {
2938 // Delete the next to last instruction.
2939 BasicBlock::iterator I = EndInst;
2940 Instruction *Inst = --I;
2941 if (!Inst->use_empty())
2942 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2943 if (isa<LandingPadInst>(Inst)) {
2947 if (!isa<DbgInfoIntrinsic>(Inst)) {
2949 MadeIRChange = true;
2951 Inst->eraseFromParent();
2955 return MadeIRChange;
2959 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
2960 AssumptionCache &AC, TargetLibraryInfo &TLI,
2961 DominatorTree &DT, LoopInfo *LI = nullptr) {
2963 bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
2964 auto &DL = F.getParent()->getDataLayout();
2966 /// Builder - This is an IRBuilder that automatically inserts new
2967 /// instructions into the worklist when they are created.
2968 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
2969 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
2971 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2973 bool DbgDeclaresChanged = LowerDbgDeclare(F);
2975 // Iterate while there is work to do.
2979 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2980 << F.getName() << "\n");
2982 bool Changed = false;
2983 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
2986 InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI);
2994 return DbgDeclaresChanged || Iteration > 1;
2997 PreservedAnalyses InstCombinePass::run(Function &F,
2998 AnalysisManager<Function> *AM) {
2999 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3000 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3001 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3003 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3005 if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI))
3006 // No changes, all analyses are preserved.
3007 return PreservedAnalyses::all();
3009 // Mark all the analyses that instcombine updates as preserved.
3010 // FIXME: Need a way to preserve CFG analyses here!
3011 PreservedAnalyses PA;
3012 PA.preserve<DominatorTreeAnalysis>();
3017 /// \brief The legacy pass manager's instcombine pass.
3019 /// This is a basic whole-function wrapper around the instcombine utility. It
3020 /// will try to combine all instructions in the function.
3021 class InstructionCombiningPass : public FunctionPass {
3022 InstCombineWorklist Worklist;
3025 static char ID; // Pass identification, replacement for typeid
3027 InstructionCombiningPass() : FunctionPass(ID) {
3028 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3031 void getAnalysisUsage(AnalysisUsage &AU) const override;
3032 bool runOnFunction(Function &F) override;
3036 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3037 AU.setPreservesCFG();
3038 AU.addRequired<AssumptionCacheTracker>();
3039 AU.addRequired<TargetLibraryInfoWrapperPass>();
3040 AU.addRequired<DominatorTreeWrapperPass>();
3041 AU.addPreserved<DominatorTreeWrapperPass>();
3044 bool InstructionCombiningPass::runOnFunction(Function &F) {
3045 if (skipOptnoneFunction(F))
3048 // Required analyses.
3049 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3050 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3051 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3053 // Optional analyses.
3054 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3055 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3057 return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI);
3060 char InstructionCombiningPass::ID = 0;
3061 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3062 "Combine redundant instructions", false, false)
3063 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3064 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3065 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3066 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3067 "Combine redundant instructions", false, false)
3069 // Initialization Routines
3070 void llvm::initializeInstCombine(PassRegistry &Registry) {
3071 initializeInstructionCombiningPassPass(Registry);
3074 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3075 initializeInstructionCombiningPassPass(*unwrap(R));
3078 FunctionPass *llvm::createInstructionCombiningPass() {
3079 return new InstructionCombiningPass();