LLVM 17.0.0git
InstructionCombining.cpp
Go to the documentation of this file.
1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// InstructionCombining - Combine instructions to form fewer, simple
10// instructions. This pass does not modify the CFG. This pass is where
11// algebraic simplification happens.
12//
13// This pass combines things like:
14// %Y = add i32 %X, 1
15// %Z = add i32 %Y, 1
16// into:
17// %Z = add i32 %X, 2
18//
19// This is a simple worklist driven algorithm.
20//
21// This pass guarantees that the following canonicalizations are performed on
22// the program:
23// 1. If a binary operator has a constant operand, it is moved to the RHS
24// 2. Bitwise operators with constant operands are always grouped so that
25// shifts are performed first, then or's, then and's, then xor's.
26// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27// 4. All cmp instructions on boolean values are replaced with logical ops
28// 5. add X, X is represented as (X*2) => (X << 1)
29// 6. Multiplies with a power-of-two constant argument are transformed into
30// shifts.
31// ... etc.
32//
33//===----------------------------------------------------------------------===//
34
35#include "InstCombineInternal.h"
37#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/Statistic.h"
47#include "llvm/Analysis/CFG.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CFG.h"
64#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DIBuilder.h"
67#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/DebugInfo.h"
70#include "llvm/IR/Dominators.h"
72#include "llvm/IR/Function.h"
74#include "llvm/IR/IRBuilder.h"
75#include "llvm/IR/InstrTypes.h"
76#include "llvm/IR/Instruction.h"
79#include "llvm/IR/Intrinsics.h"
81#include "llvm/IR/Metadata.h"
82#include "llvm/IR/Operator.h"
83#include "llvm/IR/PassManager.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/Use.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
89#include "llvm/IR/ValueHandle.h"
94#include "llvm/Support/Debug.h"
102#include <algorithm>
103#include <cassert>
104#include <cstdint>
105#include <memory>
106#include <optional>
107#include <string>
108#include <utility>
109
110#define DEBUG_TYPE "instcombine"
112#include <optional>
113
114using namespace llvm;
115using namespace llvm::PatternMatch;
116
117STATISTIC(NumWorklistIterations,
118 "Number of instruction combining iterations performed");
119
120STATISTIC(NumCombined , "Number of insts combined");
121STATISTIC(NumConstProp, "Number of constant folds");
122STATISTIC(NumDeadInst , "Number of dead inst eliminated");
123STATISTIC(NumSunkInst , "Number of instructions sunk");
124STATISTIC(NumExpand, "Number of expansions");
125STATISTIC(NumFactor , "Number of factorizations");
126STATISTIC(NumReassoc , "Number of reassociations");
127DEBUG_COUNTER(VisitCounter, "instcombine-visit",
128 "Controls which instructions are visited");
129
130// FIXME: these limits eventually should be as low as 2.
131#ifndef NDEBUG
132static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 100;
133#else
134static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 1000;
135#endif
136
137static cl::opt<bool>
138EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
139 cl::init(true));
140
142 "instcombine-max-sink-users", cl::init(32),
143 cl::desc("Maximum number of undroppable users for instruction sinking"));
144
146 "instcombine-infinite-loop-threshold",
147 cl::desc("Number of instruction combining iterations considered an "
148 "infinite loop"),
150
152MaxArraySize("instcombine-maxarray-size", cl::init(1024),
153 cl::desc("Maximum array size considered when doing a combine"));
154
155// FIXME: Remove this flag when it is no longer necessary to convert
156// llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
157// increases variable availability at the cost of accuracy. Variables that
158// cannot be promoted by mem2reg or SROA will be described as living in memory
159// for their entire lifetime. However, passes like DSE and instcombine can
160// delete stores to the alloca, leading to misleading and inaccurate debug
161// information. This flag can be removed when those passes are fixed.
162static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
163 cl::Hidden, cl::init(true));
164
165std::optional<Instruction *>
167 // Handle target specific intrinsics
169 return TTI.instCombineIntrinsic(*this, II);
170 }
171 return std::nullopt;
172}
173
175 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
176 bool &KnownBitsComputed) {
177 // Handle target specific intrinsics
179 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known,
180 KnownBitsComputed);
181 }
182 return std::nullopt;
183}
184
186 IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2,
187 APInt &UndefElts3,
188 std::function<void(Instruction *, unsigned, APInt, APInt &)>
189 SimplifyAndSetOp) {
190 // Handle target specific intrinsics
193 *this, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
194 SimplifyAndSetOp);
195 }
196 return std::nullopt;
197}
198
199Value *InstCombinerImpl::EmitGEPOffset(User *GEP) {
201}
202
203/// Legal integers and common types are considered desirable. This is used to
204/// avoid creating instructions with types that may not be supported well by the
205/// the backend.
206/// NOTE: This treats i8, i16 and i32 specially because they are common
207/// types in frontend languages.
208bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {
209 switch (BitWidth) {
210 case 8:
211 case 16:
212 case 32:
213 return true;
214 default:
215 return DL.isLegalInteger(BitWidth);
216 }
217}
218
219/// Return true if it is desirable to convert an integer computation from a
220/// given bit width to a new bit width.
221/// We don't want to convert from a legal or desirable type (like i8) to an
222/// illegal type or from a smaller to a larger illegal type. A width of '1'
223/// is always treated as a desirable type because i1 is a fundamental type in
224/// IR, and there are many specialized optimizations for i1 types.
225/// Common/desirable widths are equally treated as legal to convert to, in
226/// order to open up more combining opportunities.
227bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
228 unsigned ToWidth) const {
229 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
230 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
231
232 // Convert to desirable widths even if they are not legal types.
233 // Only shrink types, to prevent infinite loops.
234 if (ToWidth < FromWidth && isDesirableIntType(ToWidth))
235 return true;
236
237 // If this is a legal or desiable integer from type, and the result would be
238 // an illegal type, don't do the transformation.
239 if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)
240 return false;
241
242 // Otherwise, if both are illegal, do not increase the size of the result. We
243 // do allow things like i160 -> i64, but not i64 -> i160.
244 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
245 return false;
246
247 return true;
248}
249
250/// Return true if it is desirable to convert a computation from 'From' to 'To'.
251/// We don't want to convert from a legal to an illegal type or from a smaller
252/// to a larger illegal type. i1 is always treated as a legal type because it is
253/// a fundamental type in IR, and there are many specialized optimizations for
254/// i1 types.
255bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
256 // TODO: This could be extended to allow vectors. Datalayout changes might be
257 // needed to properly support that.
258 if (!From->isIntegerTy() || !To->isIntegerTy())
259 return false;
260
261 unsigned FromWidth = From->getPrimitiveSizeInBits();
262 unsigned ToWidth = To->getPrimitiveSizeInBits();
263 return shouldChangeType(FromWidth, ToWidth);
264}
265
266// Return true, if No Signed Wrap should be maintained for I.
267// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
268// where both B and C should be ConstantInts, results in a constant that does
269// not overflow. This function only handles the Add and Sub opcodes. For
270// all other opcodes, the function conservatively returns false.
272 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
273 if (!OBO || !OBO->hasNoSignedWrap())
274 return false;
275
276 // We reason about Add and Sub Only.
277 Instruction::BinaryOps Opcode = I.getOpcode();
278 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
279 return false;
280
281 const APInt *BVal, *CVal;
282 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
283 return false;
284
285 bool Overflow = false;
286 if (Opcode == Instruction::Add)
287 (void)BVal->sadd_ov(*CVal, Overflow);
288 else
289 (void)BVal->ssub_ov(*CVal, Overflow);
290
291 return !Overflow;
292}
293
295 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
296 return OBO && OBO->hasNoUnsignedWrap();
297}
298
300 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
301 return OBO && OBO->hasNoSignedWrap();
302}
303
304/// Conservatively clears subclassOptionalData after a reassociation or
305/// commutation. We preserve fast-math flags when applicable as they can be
306/// preserved.
308 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
309 if (!FPMO) {
310 I.clearSubclassOptionalData();
311 return;
312 }
313
314 FastMathFlags FMF = I.getFastMathFlags();
315 I.clearSubclassOptionalData();
316 I.setFastMathFlags(FMF);
317}
318
319/// Combine constant operands of associative operations either before or after a
320/// cast to eliminate one of the associative operations:
321/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
322/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
324 InstCombinerImpl &IC) {
325 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
326 if (!Cast || !Cast->hasOneUse())
327 return false;
328
329 // TODO: Enhance logic for other casts and remove this check.
330 auto CastOpcode = Cast->getOpcode();
331 if (CastOpcode != Instruction::ZExt)
332 return false;
333
334 // TODO: Enhance logic for other BinOps and remove this check.
335 if (!BinOp1->isBitwiseLogicOp())
336 return false;
337
338 auto AssocOpcode = BinOp1->getOpcode();
339 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
340 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
341 return false;
342
343 Constant *C1, *C2;
344 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
345 !match(BinOp2->getOperand(1), m_Constant(C2)))
346 return false;
347
348 // TODO: This assumes a zext cast.
349 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
350 // to the destination type might lose bits.
351
352 // Fold the constants together in the destination type:
353 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
354 Type *DestTy = C1->getType();
355 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
356 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
357 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));
358 IC.replaceOperand(*BinOp1, 1, FoldedC);
359 return true;
360}
361
362// Simplifies IntToPtr/PtrToInt RoundTrip Cast To BitCast.
363// inttoptr ( ptrtoint (x) ) --> x
364Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
365 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
366 if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==
367 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
368 auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));
369 Type *CastTy = IntToPtr->getDestTy();
370 if (PtrToInt &&
371 CastTy->getPointerAddressSpace() ==
372 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
373 DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==
374 DL.getTypeSizeInBits(PtrToInt->getDestTy())) {
375 return CastInst::CreateBitOrPointerCast(PtrToInt->getOperand(0), CastTy,
376 "", PtrToInt);
377 }
378 }
379 return nullptr;
380}
381
382/// This performs a few simplifications for operators that are associative or
383/// commutative:
384///
385/// Commutative operators:
386///
387/// 1. Order operands such that they are listed from right (least complex) to
388/// left (most complex). This puts constants before unary operators before
389/// binary operators.
390///
391/// Associative operators:
392///
393/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
394/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
395///
396/// Associative and commutative operators:
397///
398/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
399/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
400/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
401/// if C1 and C2 are constants.
403 Instruction::BinaryOps Opcode = I.getOpcode();
404 bool Changed = false;
405
406 do {
407 // Order operands such that they are listed from right (least complex) to
408 // left (most complex). This puts constants before unary operators before
409 // binary operators.
410 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
411 getComplexity(I.getOperand(1)))
412 Changed = !I.swapOperands();
413
414 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
415 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
416
417 if (I.isAssociative()) {
418 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
419 if (Op0 && Op0->getOpcode() == Opcode) {
420 Value *A = Op0->getOperand(0);
421 Value *B = Op0->getOperand(1);
422 Value *C = I.getOperand(1);
423
424 // Does "B op C" simplify?
425 if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
426 // It simplifies to V. Form "A op V".
427 replaceOperand(I, 0, A);
428 replaceOperand(I, 1, V);
429 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
430 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
431
432 // Conservatively clear all optional flags since they may not be
433 // preserved by the reassociation. Reset nsw/nuw based on the above
434 // analysis.
436
437 // Note: this is only valid because SimplifyBinOp doesn't look at
438 // the operands to Op0.
439 if (IsNUW)
440 I.setHasNoUnsignedWrap(true);
441
442 if (IsNSW)
443 I.setHasNoSignedWrap(true);
444
445 Changed = true;
446 ++NumReassoc;
447 continue;
448 }
449 }
450
451 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
452 if (Op1 && Op1->getOpcode() == Opcode) {
453 Value *A = I.getOperand(0);
454 Value *B = Op1->getOperand(0);
455 Value *C = Op1->getOperand(1);
456
457 // Does "A op B" simplify?
458 if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
459 // It simplifies to V. Form "V op C".
460 replaceOperand(I, 0, V);
461 replaceOperand(I, 1, C);
462 // Conservatively clear the optional flags, since they may not be
463 // preserved by the reassociation.
465 Changed = true;
466 ++NumReassoc;
467 continue;
468 }
469 }
470 }
471
472 if (I.isAssociative() && I.isCommutative()) {
473 if (simplifyAssocCastAssoc(&I, *this)) {
474 Changed = true;
475 ++NumReassoc;
476 continue;
477 }
478
479 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
480 if (Op0 && Op0->getOpcode() == Opcode) {
481 Value *A = Op0->getOperand(0);
482 Value *B = Op0->getOperand(1);
483 Value *C = I.getOperand(1);
484
485 // Does "C op A" simplify?
486 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
487 // It simplifies to V. Form "V op B".
488 replaceOperand(I, 0, V);
489 replaceOperand(I, 1, B);
490 // Conservatively clear the optional flags, since they may not be
491 // preserved by the reassociation.
493 Changed = true;
494 ++NumReassoc;
495 continue;
496 }
497 }
498
499 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
500 if (Op1 && Op1->getOpcode() == Opcode) {
501 Value *A = I.getOperand(0);
502 Value *B = Op1->getOperand(0);
503 Value *C = Op1->getOperand(1);
504
505 // Does "C op A" simplify?
506 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
507 // It simplifies to V. Form "B op V".
508 replaceOperand(I, 0, B);
509 replaceOperand(I, 1, V);
510 // Conservatively clear the optional flags, since they may not be
511 // preserved by the reassociation.
513 Changed = true;
514 ++NumReassoc;
515 continue;
516 }
517 }
518
519 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
520 // if C1 and C2 are constants.
521 Value *A, *B;
522 Constant *C1, *C2, *CRes;
523 if (Op0 && Op1 &&
524 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
525 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
526 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) &&
527 (CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) {
528 bool IsNUW = hasNoUnsignedWrap(I) &&
529 hasNoUnsignedWrap(*Op0) &&
530 hasNoUnsignedWrap(*Op1);
531 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
532 BinaryOperator::CreateNUW(Opcode, A, B) :
533 BinaryOperator::Create(Opcode, A, B);
534
535 if (isa<FPMathOperator>(NewBO)) {
536 FastMathFlags Flags = I.getFastMathFlags();
537 Flags &= Op0->getFastMathFlags();
538 Flags &= Op1->getFastMathFlags();
539 NewBO->setFastMathFlags(Flags);
540 }
541 InsertNewInstWith(NewBO, I);
542 NewBO->takeName(Op1);
543 replaceOperand(I, 0, NewBO);
544 replaceOperand(I, 1, CRes);
545 // Conservatively clear the optional flags, since they may not be
546 // preserved by the reassociation.
548 if (IsNUW)
549 I.setHasNoUnsignedWrap(true);
550
551 Changed = true;
552 continue;
553 }
554 }
555
556 // No further simplifications.
557 return Changed;
558 } while (true);
559}
560
561/// Return whether "X LOp (Y ROp Z)" is always equal to
562/// "(X LOp Y) ROp (X LOp Z)".
565 // X & (Y | Z) <--> (X & Y) | (X & Z)
566 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
567 if (LOp == Instruction::And)
568 return ROp == Instruction::Or || ROp == Instruction::Xor;
569
570 // X | (Y & Z) <--> (X | Y) & (X | Z)
571 if (LOp == Instruction::Or)
572 return ROp == Instruction::And;
573
574 // X * (Y + Z) <--> (X * Y) + (X * Z)
575 // X * (Y - Z) <--> (X * Y) - (X * Z)
576 if (LOp == Instruction::Mul)
577 return ROp == Instruction::Add || ROp == Instruction::Sub;
578
579 return false;
580}
581
582/// Return whether "(X LOp Y) ROp Z" is always equal to
583/// "(X ROp Z) LOp (Y ROp Z)".
587 return leftDistributesOverRight(ROp, LOp);
588
589 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
591
592 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
593 // but this requires knowing that the addition does not overflow and other
594 // such subtleties.
595}
596
597/// This function returns identity value for given opcode, which can be used to
598/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
600 if (isa<Constant>(V))
601 return nullptr;
602
603 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
604}
605
606/// This function predicates factorization using distributive laws. By default,
607/// it just returns the 'Op' inputs. But for special-cases like
608/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
609/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
610/// allow more factorization opportunities.
613 Value *&LHS, Value *&RHS) {
614 assert(Op && "Expected a binary operator");
615 LHS = Op->getOperand(0);
616 RHS = Op->getOperand(1);
617 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
618 Constant *C;
619 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) {
620 // X << C --> X * (1 << C)
621 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C);
622 return Instruction::Mul;
623 }
624 // TODO: We can add other conversions e.g. shr => div etc.
625 }
626 return Op->getOpcode();
627}
628
629/// This tries to simplify binary operations by factorizing out common terms
630/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
633 Instruction::BinaryOps InnerOpcode, Value *A,
634 Value *B, Value *C, Value *D) {
635 assert(A && B && C && D && "All values must be provided");
636
637 Value *V = nullptr;
638 Value *RetVal = nullptr;
639 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
640 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
641
642 // Does "X op' Y" always equal "Y op' X"?
643 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
644
645 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
646 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) {
647 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
648 // commutative case, "(A op' B) op (C op' A)"?
649 if (A == C || (InnerCommutative && A == D)) {
650 if (A != C)
651 std::swap(C, D);
652 // Consider forming "A op' (B op D)".
653 // If "B op D" simplifies then it can be formed with no cost.
654 V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
655
656 // If "B op D" doesn't simplify then only go on if one of the existing
657 // operations "A op' B" and "C op' D" will be zapped as no longer used.
658 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
659 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
660 if (V)
661 RetVal = Builder.CreateBinOp(InnerOpcode, A, V);
662 }
663 }
664
665 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
666 if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) {
667 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
668 // commutative case, "(A op' B) op (B op' D)"?
669 if (B == D || (InnerCommutative && B == C)) {
670 if (B != D)
671 std::swap(C, D);
672 // Consider forming "(A op C) op' B".
673 // If "A op C" simplifies then it can be formed with no cost.
674 V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
675
676 // If "A op C" doesn't simplify then only go on if one of the existing
677 // operations "A op' B" and "C op' D" will be zapped as no longer used.
678 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
679 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
680 if (V)
681 RetVal = Builder.CreateBinOp(InnerOpcode, V, B);
682 }
683 }
684
685 if (!RetVal)
686 return nullptr;
687
688 ++NumFactor;
689 RetVal->takeName(&I);
690
691 // Try to add no-overflow flags to the final value.
692 if (isa<OverflowingBinaryOperator>(RetVal)) {
693 bool HasNSW = false;
694 bool HasNUW = false;
695 if (isa<OverflowingBinaryOperator>(&I)) {
696 HasNSW = I.hasNoSignedWrap();
697 HasNUW = I.hasNoUnsignedWrap();
698 }
699 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
700 HasNSW &= LOBO->hasNoSignedWrap();
701 HasNUW &= LOBO->hasNoUnsignedWrap();
702 }
703
704 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
705 HasNSW &= ROBO->hasNoSignedWrap();
706 HasNUW &= ROBO->hasNoUnsignedWrap();
707 }
708
709 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
710 // We can propagate 'nsw' if we know that
711 // %Y = mul nsw i16 %X, C
712 // %Z = add nsw i16 %Y, %X
713 // =>
714 // %Z = mul nsw i16 %X, C+1
715 //
716 // iff C+1 isn't INT_MIN
717 const APInt *CInt;
718 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
719 cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW);
720
721 // nuw can be propagated with any constant or nuw value.
722 cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW);
723 }
724 }
725 return RetVal;
726}
727
729 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
730 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
731 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
732 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
733 Value *A, *B, *C, *D;
734 Instruction::BinaryOps LHSOpcode, RHSOpcode;
735
736 if (Op0)
737 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
738 if (Op1)
739 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
740
741 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
742 // a common term.
743 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
744 if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D))
745 return V;
746
747 // The instruction has the form "(A op' B) op (C)". Try to factorize common
748 // term.
749 if (Op0)
750 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
751 if (Value *V =
752 tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident))
753 return V;
754
755 // The instruction has the form "(B) op (C op' D)". Try to factorize common
756 // term.
757 if (Op1)
758 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
759 if (Value *V =
760 tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D))
761 return V;
762
763 return nullptr;
764}
765
766/// This tries to simplify binary operations which some other binary operation
767/// distributes over either by factorizing out common terms
768/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
769/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
770/// Returns the simplified value, or null if it didn't simplify.
772 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
773 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
774 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
775 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
776
777 // Factorization.
778 if (Value *R = tryFactorizationFolds(I))
779 return R;
780
781 // Expansion.
782 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
783 // The instruction has the form "(A op' B) op C". See if expanding it out
784 // to "(A op C) op' (B op C)" results in simplifications.
785 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
786 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
787
788 // Disable the use of undef because it's not safe to distribute undef.
789 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
790 Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
791 Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive);
792
793 // Do "A op C" and "B op C" both simplify?
794 if (L && R) {
795 // They do! Return "L op' R".
796 ++NumExpand;
797 C = Builder.CreateBinOp(InnerOpcode, L, R);
798 C->takeName(&I);
799 return C;
800 }
801
802 // Does "A op C" simplify to the identity value for the inner opcode?
803 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
804 // They do! Return "B op C".
805 ++NumExpand;
806 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
807 C->takeName(&I);
808 return C;
809 }
810
811 // Does "B op C" simplify to the identity value for the inner opcode?
812 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
813 // They do! Return "A op C".
814 ++NumExpand;
815 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
816 C->takeName(&I);
817 return C;
818 }
819 }
820
821 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
822 // The instruction has the form "A op (B op' C)". See if expanding it out
823 // to "(A op B) op' (A op C)" results in simplifications.
824 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
825 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
826
827 // Disable the use of undef because it's not safe to distribute undef.
828 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
829 Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive);
830 Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
831
832 // Do "A op B" and "A op C" both simplify?
833 if (L && R) {
834 // They do! Return "L op' R".
835 ++NumExpand;
836 A = Builder.CreateBinOp(InnerOpcode, L, R);
837 A->takeName(&I);
838 return A;
839 }
840
841 // Does "A op B" simplify to the identity value for the inner opcode?
842 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
843 // They do! Return "A op C".
844 ++NumExpand;
845 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
846 A->takeName(&I);
847 return A;
848 }
849
850 // Does "A op C" simplify to the identity value for the inner opcode?
851 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
852 // They do! Return "A op B".
853 ++NumExpand;
854 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
855 A->takeName(&I);
856 return A;
857 }
858 }
859
861}
862
864 Value *LHS,
865 Value *RHS) {
866 Value *A, *B, *C, *D, *E, *F;
867 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
868 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
869 if (!LHSIsSelect && !RHSIsSelect)
870 return nullptr;
871
872 FastMathFlags FMF;
874 if (isa<FPMathOperator>(&I)) {
875 FMF = I.getFastMathFlags();
877 }
878
879 Instruction::BinaryOps Opcode = I.getOpcode();
881
882 Value *Cond, *True = nullptr, *False = nullptr;
883
884 // Special-case for add/negate combination. Replace the zero in the negation
885 // with the trailing add operand:
886 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
887 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
888 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
889 // We need an 'add' and exactly 1 arm of the select to have been simplified.
890 if (Opcode != Instruction::Add || (!True && !False) || (True && False))
891 return nullptr;
892
893 Value *N;
894 if (True && match(FVal, m_Neg(m_Value(N)))) {
895 Value *Sub = Builder.CreateSub(Z, N);
896 return Builder.CreateSelect(Cond, True, Sub, I.getName());
897 }
898 if (False && match(TVal, m_Neg(m_Value(N)))) {
899 Value *Sub = Builder.CreateSub(Z, N);
900 return Builder.CreateSelect(Cond, Sub, False, I.getName());
901 }
902 return nullptr;
903 };
904
905 if (LHSIsSelect && RHSIsSelect && A == D) {
906 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
907 Cond = A;
908 True = simplifyBinOp(Opcode, B, E, FMF, Q);
909 False = simplifyBinOp(Opcode, C, F, FMF, Q);
910
911 if (LHS->hasOneUse() && RHS->hasOneUse()) {
912 if (False && !True)
913 True = Builder.CreateBinOp(Opcode, B, E);
914 else if (True && !False)
915 False = Builder.CreateBinOp(Opcode, C, F);
916 }
917 } else if (LHSIsSelect && LHS->hasOneUse()) {
918 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
919 Cond = A;
920 True = simplifyBinOp(Opcode, B, RHS, FMF, Q);
921 False = simplifyBinOp(Opcode, C, RHS, FMF, Q);
922 if (Value *NewSel = foldAddNegate(B, C, RHS))
923 return NewSel;
924 } else if (RHSIsSelect && RHS->hasOneUse()) {
925 // X op (D ? E : F) -> D ? (X op E) : (X op F)
926 Cond = D;
927 True = simplifyBinOp(Opcode, LHS, E, FMF, Q);
928 False = simplifyBinOp(Opcode, LHS, F, FMF, Q);
929 if (Value *NewSel = foldAddNegate(E, F, LHS))
930 return NewSel;
931 }
932
933 if (!True || !False)
934 return nullptr;
935
936 Value *SI = Builder.CreateSelect(Cond, True, False);
937 SI->takeName(&I);
938 return SI;
939}
940
941/// Freely adapt every user of V as-if V was changed to !V.
942/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
943void InstCombinerImpl::freelyInvertAllUsersOf(Value *I, Value *IgnoredUser) {
944 for (User *U : make_early_inc_range(I->users())) {
945 if (U == IgnoredUser)
946 continue; // Don't consider this user.
947 switch (cast<Instruction>(U)->getOpcode()) {
948 case Instruction::Select: {
949 auto *SI = cast<SelectInst>(U);
950 SI->swapValues();
951 SI->swapProfMetadata();
952 break;
953 }
954 case Instruction::Br:
955 cast<BranchInst>(U)->swapSuccessors(); // swaps prof metadata too
956 break;
957 case Instruction::Xor:
958 replaceInstUsesWith(cast<Instruction>(*U), I);
959 break;
960 default:
961 llvm_unreachable("Got unexpected user - out of sync with "
962 "canFreelyInvertAllUsersOf() ?");
963 }
964 }
965}
966
967/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
968/// constant zero (which is the 'negate' form).
969Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
970 Value *NegV;
971 if (match(V, m_Neg(m_Value(NegV))))
972 return NegV;
973
974 // Constants can be considered to be negated values if they can be folded.
975 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
976 return ConstantExpr::getNeg(C);
977
978 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
979 if (C->getType()->getElementType()->isIntegerTy())
980 return ConstantExpr::getNeg(C);
981
982 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
983 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
984 Constant *Elt = CV->getAggregateElement(i);
985 if (!Elt)
986 return nullptr;
987
988 if (isa<UndefValue>(Elt))
989 continue;
990
991 if (!isa<ConstantInt>(Elt))
992 return nullptr;
993 }
994 return ConstantExpr::getNeg(CV);
995 }
996
997 // Negate integer vector splats.
998 if (auto *CV = dyn_cast<Constant>(V))
999 if (CV->getType()->isVectorTy() &&
1000 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1001 return ConstantExpr::getNeg(CV);
1002
1003 return nullptr;
1004}
1005
1006/// A binop with a constant operand and a sign-extended boolean operand may be
1007/// converted into a select of constants by applying the binary operation to
1008/// the constant with the two possible values of the extended boolean (0 or -1).
1009Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
1010 // TODO: Handle non-commutative binop (constant is operand 0).
1011 // TODO: Handle zext.
1012 // TODO: Peek through 'not' of cast.
1013 Value *BO0 = BO.getOperand(0);
1014 Value *BO1 = BO.getOperand(1);
1015 Value *X;
1016 Constant *C;
1017 if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||
1018 !X->getType()->isIntOrIntVectorTy(1))
1019 return nullptr;
1020
1021 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
1024 Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);
1025 Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);
1026 return SelectInst::Create(X, TVal, FVal);
1027}
1028
1030 Instruction &I, SelectInst *SI, Value *SO) {
1031 auto *ConstSO = dyn_cast<Constant>(SO);
1032 if (!ConstSO)
1033 return nullptr;
1034
1035 SmallVector<Constant *> ConstOps;
1036 for (Value *Op : I.operands()) {
1037 if (Op == SI)
1038 ConstOps.push_back(ConstSO);
1039 else if (auto *C = dyn_cast<Constant>(Op))
1040 ConstOps.push_back(C);
1041 else
1042 llvm_unreachable("Operands should be select or constant");
1043 }
1044 return ConstantFoldInstOperands(&I, ConstOps, I.getModule()->getDataLayout());
1045}
1046
1048 Value *NewOp, InstCombiner &IC) {
1049 Instruction *Clone = I.clone();
1050 Clone->replaceUsesOfWith(SI, NewOp);
1051 IC.InsertNewInstBefore(Clone, *SI);
1052 return Clone;
1053}
1054
1056 bool FoldWithMultiUse) {
1057 // Don't modify shared select instructions unless set FoldWithMultiUse
1058 if (!SI->hasOneUse() && !FoldWithMultiUse)
1059 return nullptr;
1060
1061 Value *TV = SI->getTrueValue();
1062 Value *FV = SI->getFalseValue();
1063 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
1064 return nullptr;
1065
1066 // Bool selects with constant operands can be folded to logical ops.
1067 if (SI->getType()->isIntOrIntVectorTy(1))
1068 return nullptr;
1069
1070 // If it's a bitcast involving vectors, make sure it has the same number of
1071 // elements on both sides.
1072 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
1073 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
1074 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
1075
1076 // Verify that either both or neither are vectors.
1077 if ((SrcTy == nullptr) != (DestTy == nullptr))
1078 return nullptr;
1079
1080 // If vectors, verify that they have the same number of elements.
1081 if (SrcTy && SrcTy->getElementCount() != DestTy->getElementCount())
1082 return nullptr;
1083 }
1084
1085 // Test if a CmpInst instruction is used exclusively by a select as
1086 // part of a minimum or maximum operation. If so, refrain from doing
1087 // any other folding. This helps out other analyses which understand
1088 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
1089 // and CodeGen. And in this case, at least one of the comparison
1090 // operands has at least one user besides the compare (the select),
1091 // which would often largely negate the benefit of folding anyway.
1092 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
1093 if (CI->hasOneUse()) {
1094 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1095
1096 // FIXME: This is a hack to avoid infinite looping with min/max patterns.
1097 // We have to ensure that vector constants that only differ with
1098 // undef elements are treated as equivalent.
1099 auto areLooselyEqual = [](Value *A, Value *B) {
1100 if (A == B)
1101 return true;
1102
1103 // Test for vector constants.
1104 Constant *ConstA, *ConstB;
1105 if (!match(A, m_Constant(ConstA)) || !match(B, m_Constant(ConstB)))
1106 return false;
1107
1108 // TODO: Deal with FP constants?
1109 if (!A->getType()->isIntOrIntVectorTy() || A->getType() != B->getType())
1110 return false;
1111
1112 // Compare for equality including undefs as equal.
1113 auto *Cmp = ConstantExpr::getCompare(ICmpInst::ICMP_EQ, ConstA, ConstB);
1114 const APInt *C;
1115 return match(Cmp, m_APIntAllowUndef(C)) && C->isOne();
1116 };
1117
1118 if ((areLooselyEqual(TV, Op0) && areLooselyEqual(FV, Op1)) ||
1119 (areLooselyEqual(FV, Op0) && areLooselyEqual(TV, Op1)))
1120 return nullptr;
1121 }
1122 }
1123
1124 // Make sure that one of the select arms constant folds successfully.
1127 if (!NewTV && !NewFV)
1128 return nullptr;
1129
1130 // Create an instruction for the arm that did not fold.
1131 if (!NewTV)
1132 NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);
1133 if (!NewFV)
1134 NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);
1135 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
1136}
1137
1139 unsigned NumPHIValues = PN->getNumIncomingValues();
1140 if (NumPHIValues == 0)
1141 return nullptr;
1142
1143 // We normally only transform phis with a single use. However, if a PHI has
1144 // multiple uses and they are all the same operation, we can fold *all* of the
1145 // uses into the PHI.
1146 if (!PN->hasOneUse()) {
1147 // Walk the use list for the instruction, comparing them to I.
1148 for (User *U : PN->users()) {
1149 Instruction *UI = cast<Instruction>(U);
1150 if (UI != &I && !I.isIdenticalTo(UI))
1151 return nullptr;
1152 }
1153 // Otherwise, we can replace *all* users with the new PHI we form.
1154 }
1155
1156 // Check to see whether the instruction can be folded into each phi operand.
1157 // If there is one operand that does not fold, remember the BB it is in.
1158 // If there is more than one or if *it* is a PHI, bail out.
1159 SmallVector<Value *> NewPhiValues;
1160 BasicBlock *NonSimplifiedBB = nullptr;
1161 Value *NonSimplifiedInVal = nullptr;
1162 for (unsigned i = 0; i != NumPHIValues; ++i) {
1163 Value *InVal = PN->getIncomingValue(i);
1164 BasicBlock *InBB = PN->getIncomingBlock(i);
1165
1166 // NB: It is a precondition of this transform that the operands be
1167 // phi translatable! This is usually trivially satisfied by limiting it
1168 // to constant ops, and for selects we do a more sophisticated check.
1170 for (Value *Op : I.operands()) {
1171 if (Op == PN)
1172 Ops.push_back(InVal);
1173 else
1174 Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));
1175 }
1176
1177 // Don't consider the simplification successful if we get back a constant
1178 // expression. That's just an instruction in hiding.
1179 // Also reject the case where we simplify back to the phi node. We wouldn't
1180 // be able to remove it in that case.
1182 &I, Ops, SQ.getWithInstruction(InBB->getTerminator()));
1183 if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr())) {
1184 NewPhiValues.push_back(NewVal);
1185 continue;
1186 }
1187
1188 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
1189 if (NonSimplifiedBB) return nullptr; // More than one non-simplified value.
1190
1191 NonSimplifiedBB = InBB;
1192 NonSimplifiedInVal = InVal;
1193 NewPhiValues.push_back(nullptr);
1194
1195 // If the InVal is an invoke at the end of the pred block, then we can't
1196 // insert a computation after it without breaking the edge.
1197 if (isa<InvokeInst>(InVal))
1198 if (cast<Instruction>(InVal)->getParent() == NonSimplifiedBB)
1199 return nullptr;
1200
1201 // If the incoming non-constant value is reachable from the phis block,
1202 // we'll push the operation across a loop backedge. This could result in
1203 // an infinite combine loop, and is generally non-profitable (especially
1204 // if the operation was originally outside the loop).
1205 if (isPotentiallyReachable(PN->getParent(), NonSimplifiedBB, nullptr, &DT,
1206 LI))
1207 return nullptr;
1208 }
1209
1210 // If there is exactly one non-simplified value, we can insert a copy of the
1211 // operation in that block. However, if this is a critical edge, we would be
1212 // inserting the computation on some other paths (e.g. inside a loop). Only
1213 // do this if the pred block is unconditionally branching into the phi block.
1214 // Also, make sure that the pred block is not dead code.
1215 if (NonSimplifiedBB != nullptr) {
1216 BranchInst *BI = dyn_cast<BranchInst>(NonSimplifiedBB->getTerminator());
1217 if (!BI || !BI->isUnconditional() ||
1218 !DT.isReachableFromEntry(NonSimplifiedBB))
1219 return nullptr;
1220 }
1221
1222 // Okay, we can do the transformation: create the new PHI node.
1223 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
1224 InsertNewInstBefore(NewPN, *PN);
1225 NewPN->takeName(PN);
1226
1227 // If we are going to have to insert a new computation, do so right before the
1228 // predecessor's terminator.
1229 Instruction *Clone = nullptr;
1230 if (NonSimplifiedBB) {
1231 Clone = I.clone();
1232 for (Use &U : Clone->operands()) {
1233 if (U == PN)
1234 U = NonSimplifiedInVal;
1235 else
1236 U = U->DoPHITranslation(PN->getParent(), NonSimplifiedBB);
1237 }
1238 InsertNewInstBefore(Clone, *NonSimplifiedBB->getTerminator());
1239 }
1240
1241 for (unsigned i = 0; i != NumPHIValues; ++i) {
1242 if (NewPhiValues[i])
1243 NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));
1244 else
1245 NewPN->addIncoming(Clone, PN->getIncomingBlock(i));
1246 }
1247
1248 for (User *U : make_early_inc_range(PN->users())) {
1249 Instruction *User = cast<Instruction>(U);
1250 if (User == &I) continue;
1251 replaceInstUsesWith(*User, NewPN);
1253 }
1254 return replaceInstUsesWith(I, NewPN);
1255}
1256
1258 // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
1259 // we are guarding against replicating the binop in >1 predecessor.
1260 // This could miss matching a phi with 2 constant incoming values.
1261 auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));
1262 auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));
1263 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
1264 Phi0->getNumOperands() != Phi1->getNumOperands())
1265 return nullptr;
1266
1267 // TODO: Remove the restriction for binop being in the same block as the phis.
1268 if (BO.getParent() != Phi0->getParent() ||
1269 BO.getParent() != Phi1->getParent())
1270 return nullptr;
1271
1272 // Fold if there is at least one specific constant value in phi0 or phi1's
1273 // incoming values that comes from the same block and this specific constant
1274 // value can be used to do optimization for specific binary operator.
1275 // For example:
1276 // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
1277 // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
1278 // %add = add i32 %phi0, %phi1
1279 // ==>
1280 // %add = phi i32 [%j, %bb0], [%i, %bb1]
1282 /*AllowRHSConstant*/ false);
1283 if (C) {
1284 SmallVector<Value *, 4> NewIncomingValues;
1285 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
1286 auto &Phi0Use = std::get<0>(T);
1287 auto &Phi1Use = std::get<1>(T);
1288 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
1289 return false;
1290 Value *Phi0UseV = Phi0Use.get();
1291 Value *Phi1UseV = Phi1Use.get();
1292 if (Phi0UseV == C)
1293 NewIncomingValues.push_back(Phi1UseV);
1294 else if (Phi1UseV == C)
1295 NewIncomingValues.push_back(Phi0UseV);
1296 else
1297 return false;
1298 return true;
1299 };
1300
1301 if (all_of(zip(Phi0->operands(), Phi1->operands()),
1302 CanFoldIncomingValuePair)) {
1303 PHINode *NewPhi =
1304 PHINode::Create(Phi0->getType(), Phi0->getNumOperands());
1305 assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
1306 "The number of collected incoming values should equal the number "
1307 "of the original PHINode operands!");
1308 for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
1309 NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));
1310 return NewPhi;
1311 }
1312 }
1313
1314 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
1315 return nullptr;
1316
1317 // Match a pair of incoming constants for one of the predecessor blocks.
1318 BasicBlock *ConstBB, *OtherBB;
1319 Constant *C0, *C1;
1320 if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {
1321 ConstBB = Phi0->getIncomingBlock(0);
1322 OtherBB = Phi0->getIncomingBlock(1);
1323 } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {
1324 ConstBB = Phi0->getIncomingBlock(1);
1325 OtherBB = Phi0->getIncomingBlock(0);
1326 } else {
1327 return nullptr;
1328 }
1329 if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))
1330 return nullptr;
1331
1332 // The block that we are hoisting to must reach here unconditionally.
1333 // Otherwise, we could be speculatively executing an expensive or
1334 // non-speculative op.
1335 auto *PredBlockBranch = dyn_cast<BranchInst>(OtherBB->getTerminator());
1336 if (!PredBlockBranch || PredBlockBranch->isConditional() ||
1337 !DT.isReachableFromEntry(OtherBB))
1338 return nullptr;
1339
1340 // TODO: This check could be tightened to only apply to binops (div/rem) that
1341 // are not safe to speculatively execute. But that could allow hoisting
1342 // potentially expensive instructions (fdiv for example).
1343 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
1345 return nullptr;
1346
1347 // Fold constants for the predecessor block with constant incoming values.
1348 Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL);
1349 if (!NewC)
1350 return nullptr;
1351
1352 // Make a new binop in the predecessor block with the non-constant incoming
1353 // values.
1354 Builder.SetInsertPoint(PredBlockBranch);
1355 Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),
1356 Phi0->getIncomingValueForBlock(OtherBB),
1357 Phi1->getIncomingValueForBlock(OtherBB));
1358 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))
1359 NotFoldedNewBO->copyIRFlags(&BO);
1360
1361 // Replace the binop with a phi of the new values. The old phis are dead.
1362 PHINode *NewPhi = PHINode::Create(BO.getType(), 2);
1363 NewPhi->addIncoming(NewBO, OtherBB);
1364 NewPhi->addIncoming(NewC, ConstBB);
1365 return NewPhi;
1366}
1367
1369 if (!isa<Constant>(I.getOperand(1)))
1370 return nullptr;
1371
1372 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1373 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1374 return NewSel;
1375 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1376 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1377 return NewPhi;
1378 }
1379 return nullptr;
1380}
1381
1382/// Given a pointer type and a constant offset, determine whether or not there
1383/// is a sequence of GEP indices into the pointed type that will land us at the
1384/// specified offset. If so, fill them into NewIndices and return the resultant
1385/// element type, otherwise return null.
1386static Type *findElementAtOffset(PointerType *PtrTy, int64_t IntOffset,
1387 SmallVectorImpl<Value *> &NewIndices,
1388 const DataLayout &DL) {
1389 // Only used by visitGEPOfBitcast(), which is skipped for opaque pointers.
1390 Type *Ty = PtrTy->getNonOpaquePointerElementType();
1391 if (!Ty->isSized())
1392 return nullptr;
1393
1394 APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), IntOffset);
1395 SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(Ty, Offset);
1396 if (!Offset.isZero())
1397 return nullptr;
1398
1399 for (const APInt &Index : Indices)
1400 NewIndices.push_back(ConstantInt::get(PtrTy->getContext(), Index));
1401 return Ty;
1402}
1403
1405 // If this GEP has only 0 indices, it is the same pointer as
1406 // Src. If Src is not a trivial GEP too, don't combine
1407 // the indices.
1408 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1409 !Src.hasOneUse())
1410 return false;
1411 return true;
1412}
1413
1414/// Return a value X such that Val = X * Scale, or null if none.
1415/// If the multiplication is known not to overflow, then NoSignedWrap is set.
1416Value *InstCombinerImpl::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1417 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1418 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1419 Scale.getBitWidth() && "Scale not compatible with value!");
1420
1421 // If Val is zero or Scale is one then Val = Val * Scale.
1422 if (match(Val, m_Zero()) || Scale == 1) {
1423 NoSignedWrap = true;
1424 return Val;
1425 }
1426
1427 // If Scale is zero then it does not divide Val.
1428 if (Scale.isMinValue())
1429 return nullptr;
1430
1431 // Look through chains of multiplications, searching for a constant that is
1432 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1433 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1434 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1435 // down from Val:
1436 //
1437 // Val = M1 * X || Analysis starts here and works down
1438 // M1 = M2 * Y || Doesn't descend into terms with more
1439 // M2 = Z * 4 \/ than one use
1440 //
1441 // Then to modify a term at the bottom:
1442 //
1443 // Val = M1 * X
1444 // M1 = Z * Y || Replaced M2 with Z
1445 //
1446 // Then to work back up correcting nsw flags.
1447
1448 // Op - the term we are currently analyzing. Starts at Val then drills down.
1449 // Replaced with its descaled value before exiting from the drill down loop.
1450 Value *Op = Val;
1451
1452 // Parent - initially null, but after drilling down notes where Op came from.
1453 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1454 // 0'th operand of Val.
1455 std::pair<Instruction *, unsigned> Parent;
1456
1457 // Set if the transform requires a descaling at deeper levels that doesn't
1458 // overflow.
1459 bool RequireNoSignedWrap = false;
1460
1461 // Log base 2 of the scale. Negative if not a power of 2.
1462 int32_t logScale = Scale.exactLogBase2();
1463
1464 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1466 // If Op is a constant divisible by Scale then descale to the quotient.
1467 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1468 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1469 if (!Remainder.isMinValue())
1470 // Not divisible by Scale.
1471 return nullptr;
1472 // Replace with the quotient in the parent.
1473 Op = ConstantInt::get(CI->getType(), Quotient);
1474 NoSignedWrap = true;
1475 break;
1476 }
1477
1478 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1479 if (BO->getOpcode() == Instruction::Mul) {
1480 // Multiplication.
1481 NoSignedWrap = BO->hasNoSignedWrap();
1482 if (RequireNoSignedWrap && !NoSignedWrap)
1483 return nullptr;
1484
1485 // There are three cases for multiplication: multiplication by exactly
1486 // the scale, multiplication by a constant different to the scale, and
1487 // multiplication by something else.
1488 Value *LHS = BO->getOperand(0);
1489 Value *RHS = BO->getOperand(1);
1490
1491 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1492 // Multiplication by a constant.
1493 if (CI->getValue() == Scale) {
1494 // Multiplication by exactly the scale, replace the multiplication
1495 // by its left-hand side in the parent.
1496 Op = LHS;
1497 break;
1498 }
1499
1500 // Otherwise drill down into the constant.
1501 if (!Op->hasOneUse())
1502 return nullptr;
1503
1504 Parent = std::make_pair(BO, 1);
1505 continue;
1506 }
1507
1508 // Multiplication by something else. Drill down into the left-hand side
1509 // since that's where the reassociate pass puts the good stuff.
1510 if (!Op->hasOneUse())
1511 return nullptr;
1512
1513 Parent = std::make_pair(BO, 0);
1514 continue;
1515 }
1516
1517 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1518 isa<ConstantInt>(BO->getOperand(1))) {
1519 // Multiplication by a power of 2.
1520 NoSignedWrap = BO->hasNoSignedWrap();
1521 if (RequireNoSignedWrap && !NoSignedWrap)
1522 return nullptr;
1523
1524 Value *LHS = BO->getOperand(0);
1525 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1526 getLimitedValue(Scale.getBitWidth());
1527 // Op = LHS << Amt.
1528
1529 if (Amt == logScale) {
1530 // Multiplication by exactly the scale, replace the multiplication
1531 // by its left-hand side in the parent.
1532 Op = LHS;
1533 break;
1534 }
1535 if (Amt < logScale || !Op->hasOneUse())
1536 return nullptr;
1537
1538 // Multiplication by more than the scale. Reduce the multiplying amount
1539 // by the scale in the parent.
1540 Parent = std::make_pair(BO, 1);
1541 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1542 break;
1543 }
1544 }
1545
1546 if (!Op->hasOneUse())
1547 return nullptr;
1548
1549 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1550 if (Cast->getOpcode() == Instruction::SExt) {
1551 // Op is sign-extended from a smaller type, descale in the smaller type.
1552 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1553 APInt SmallScale = Scale.trunc(SmallSize);
1554 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1555 // descale Op as (sext Y) * Scale. In order to have
1556 // sext (Y * SmallScale) = (sext Y) * Scale
1557 // some conditions need to hold however: SmallScale must sign-extend to
1558 // Scale and the multiplication Y * SmallScale should not overflow.
1559 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1560 // SmallScale does not sign-extend to Scale.
1561 return nullptr;
1562 assert(SmallScale.exactLogBase2() == logScale);
1563 // Require that Y * SmallScale must not overflow.
1564 RequireNoSignedWrap = true;
1565
1566 // Drill down through the cast.
1567 Parent = std::make_pair(Cast, 0);
1568 Scale = SmallScale;
1569 continue;
1570 }
1571
1572 if (Cast->getOpcode() == Instruction::Trunc) {
1573 // Op is truncated from a larger type, descale in the larger type.
1574 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1575 // trunc (Y * sext Scale) = (trunc Y) * Scale
1576 // always holds. However (trunc Y) * Scale may overflow even if
1577 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1578 // from this point up in the expression (see later).
1579 if (RequireNoSignedWrap)
1580 return nullptr;
1581
1582 // Drill down through the cast.
1583 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1584 Parent = std::make_pair(Cast, 0);
1585 Scale = Scale.sext(LargeSize);
1586 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1587 logScale = -1;
1588 assert(Scale.exactLogBase2() == logScale);
1589 continue;
1590 }
1591 }
1592
1593 // Unsupported expression, bail out.
1594 return nullptr;
1595 }
1596
1597 // If Op is zero then Val = Op * Scale.
1598 if (match(Op, m_Zero())) {
1599 NoSignedWrap = true;
1600 return Op;
1601 }
1602
1603 // We know that we can successfully descale, so from here on we can safely
1604 // modify the IR. Op holds the descaled version of the deepest term in the
1605 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1606 // not to overflow.
1607
1608 if (!Parent.first)
1609 // The expression only had one term.
1610 return Op;
1611
1612 // Rewrite the parent using the descaled version of its operand.
1613 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1614 assert(Op != Parent.first->getOperand(Parent.second) &&
1615 "Descaling was a no-op?");
1616 replaceOperand(*Parent.first, Parent.second, Op);
1617 Worklist.push(Parent.first);
1618
1619 // Now work back up the expression correcting nsw flags. The logic is based
1620 // on the following observation: if X * Y is known not to overflow as a signed
1621 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1622 // then X * Z will not overflow as a signed multiplication either. As we work
1623 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1624 // current level has strictly smaller absolute value than the original.
1625 Instruction *Ancestor = Parent.first;
1626 do {
1627 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1628 // If the multiplication wasn't nsw then we can't say anything about the
1629 // value of the descaled multiplication, and we have to clear nsw flags
1630 // from this point on up.
1631 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1632 NoSignedWrap &= OpNoSignedWrap;
1633 if (NoSignedWrap != OpNoSignedWrap) {
1634 BO->setHasNoSignedWrap(NoSignedWrap);
1635 Worklist.push(Ancestor);
1636 }
1637 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1638 // The fact that the descaled input to the trunc has smaller absolute
1639 // value than the original input doesn't tell us anything useful about
1640 // the absolute values of the truncations.
1641 NoSignedWrap = false;
1642 }
1643 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1644 "Failed to keep proper track of nsw flags while drilling down?");
1645
1646 if (Ancestor == Val)
1647 // Got to the top, all done!
1648 return Val;
1649
1650 // Move up one level in the expression.
1651 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1652 Ancestor = Ancestor->user_back();
1653 } while (true);
1654}
1655
1657 if (!isa<VectorType>(Inst.getType()))
1658 return nullptr;
1659
1660 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1661 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1662 assert(cast<VectorType>(LHS->getType())->getElementCount() ==
1663 cast<VectorType>(Inst.getType())->getElementCount());
1664 assert(cast<VectorType>(RHS->getType())->getElementCount() ==
1665 cast<VectorType>(Inst.getType())->getElementCount());
1666
1667 // If both operands of the binop are vector concatenations, then perform the
1668 // narrow binop on each pair of the source operands followed by concatenation
1669 // of the results.
1670 Value *L0, *L1, *R0, *R1;
1671 ArrayRef<int> Mask;
1672 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&
1673 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&
1674 LHS->hasOneUse() && RHS->hasOneUse() &&
1675 cast<ShuffleVectorInst>(LHS)->isConcat() &&
1676 cast<ShuffleVectorInst>(RHS)->isConcat()) {
1677 // This transform does not have the speculative execution constraint as
1678 // below because the shuffle is a concatenation. The new binops are
1679 // operating on exactly the same elements as the existing binop.
1680 // TODO: We could ease the mask requirement to allow different undef lanes,
1681 // but that requires an analysis of the binop-with-undef output value.
1682 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1683 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1684 BO->copyIRFlags(&Inst);
1685 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1686 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1687 BO->copyIRFlags(&Inst);
1688 return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1689 }
1690
1691 auto createBinOpReverse = [&](Value *X, Value *Y) {
1692 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
1693 if (auto *BO = dyn_cast<BinaryOperator>(V))
1694 BO->copyIRFlags(&Inst);
1695 Module *M = Inst.getModule();
1697 M, Intrinsic::experimental_vector_reverse, V->getType());
1698 return CallInst::Create(F, V);
1699 };
1700
1701 // NOTE: Reverse shuffles don't require the speculative execution protection
1702 // below because they don't affect which lanes take part in the computation.
1703
1704 Value *V1, *V2;
1705 if (match(LHS, m_VecReverse(m_Value(V1)))) {
1706 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
1707 if (match(RHS, m_VecReverse(m_Value(V2))) &&
1708 (LHS->hasOneUse() || RHS->hasOneUse() ||
1709 (LHS == RHS && LHS->hasNUses(2))))
1710 return createBinOpReverse(V1, V2);
1711
1712 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
1713 if (LHS->hasOneUse() && isSplatValue(RHS))
1714 return createBinOpReverse(V1, RHS);
1715 }
1716 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
1717 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
1718 return createBinOpReverse(LHS, V2);
1719
1720 // It may not be safe to reorder shuffles and things like div, urem, etc.
1721 // because we may trap when executing those ops on unknown vector elements.
1722 // See PR20059.
1723 if (!isSafeToSpeculativelyExecute(&Inst))
1724 return nullptr;
1725
1726 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
1727 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1728 if (auto *BO = dyn_cast<BinaryOperator>(XY))
1729 BO->copyIRFlags(&Inst);
1730 return new ShuffleVectorInst(XY, M);
1731 };
1732
1733 // If both arguments of the binary operation are shuffles that use the same
1734 // mask and shuffle within a single vector, move the shuffle after the binop.
1735 if (match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))) &&
1736 match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) &&
1737 V1->getType() == V2->getType() &&
1738 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1739 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1740 return createBinOpShuffle(V1, V2, Mask);
1741 }
1742
1743 // If both arguments of a commutative binop are select-shuffles that use the
1744 // same mask with commuted operands, the shuffles are unnecessary.
1745 if (Inst.isCommutative() &&
1746 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
1747 match(RHS,
1748 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) {
1749 auto *LShuf = cast<ShuffleVectorInst>(LHS);
1750 auto *RShuf = cast<ShuffleVectorInst>(RHS);
1751 // TODO: Allow shuffles that contain undefs in the mask?
1752 // That is legal, but it reduces undef knowledge.
1753 // TODO: Allow arbitrary shuffles by shuffling after binop?
1754 // That might be legal, but we have to deal with poison.
1755 if (LShuf->isSelect() &&
1756 !is_contained(LShuf->getShuffleMask(), UndefMaskElem) &&
1757 RShuf->isSelect() &&
1758 !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) {
1759 // Example:
1760 // LHS = shuffle V1, V2, <0, 5, 6, 3>
1761 // RHS = shuffle V2, V1, <0, 5, 6, 3>
1762 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
1763 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
1764 NewBO->copyIRFlags(&Inst);
1765 return NewBO;
1766 }
1767 }
1768
1769 // If one argument is a shuffle within one vector and the other is a constant,
1770 // try moving the shuffle after the binary operation. This canonicalization
1771 // intends to move shuffles closer to other shuffles and binops closer to
1772 // other binops, so they can be folded. It may also enable demanded elements
1773 // transforms.
1774 Constant *C;
1775 auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType());
1776 if (InstVTy &&
1777 match(&Inst,
1779 m_ImmConstant(C))) &&
1780 cast<FixedVectorType>(V1->getType())->getNumElements() <=
1781 InstVTy->getNumElements()) {
1782 assert(InstVTy->getScalarType() == V1->getType()->getScalarType() &&
1783 "Shuffle should not change scalar type");
1784
1785 // Find constant NewC that has property:
1786 // shuffle(NewC, ShMask) = C
1787 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1788 // reorder is not possible. A 1-to-1 mapping is not required. Example:
1789 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1790 bool ConstOp1 = isa<Constant>(RHS);
1791 ArrayRef<int> ShMask = Mask;
1792 unsigned SrcVecNumElts =
1793 cast<FixedVectorType>(V1->getType())->getNumElements();
1794 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType());
1795 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar);
1796 bool MayChange = true;
1797 unsigned NumElts = InstVTy->getNumElements();
1798 for (unsigned I = 0; I < NumElts; ++I) {
1799 Constant *CElt = C->getAggregateElement(I);
1800 if (ShMask[I] >= 0) {
1801 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
1802 Constant *NewCElt = NewVecC[ShMask[I]];
1803 // Bail out if:
1804 // 1. The constant vector contains a constant expression.
1805 // 2. The shuffle needs an element of the constant vector that can't
1806 // be mapped to a new constant vector.
1807 // 3. This is a widening shuffle that copies elements of V1 into the
1808 // extended elements (extending with undef is allowed).
1809 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1810 I >= SrcVecNumElts) {
1811 MayChange = false;
1812 break;
1813 }
1814 NewVecC[ShMask[I]] = CElt;
1815 }
1816 // If this is a widening shuffle, we must be able to extend with undef
1817 // elements. If the original binop does not produce an undef in the high
1818 // lanes, then this transform is not safe.
1819 // Similarly for undef lanes due to the shuffle mask, we can only
1820 // transform binops that preserve undef.
1821 // TODO: We could shuffle those non-undef constant values into the
1822 // result by using a constant vector (rather than an undef vector)
1823 // as operand 1 of the new binop, but that might be too aggressive
1824 // for target-independent shuffle creation.
1825 if (I >= SrcVecNumElts || ShMask[I] < 0) {
1826 Constant *MaybeUndef =
1827 ConstOp1
1828 ? ConstantFoldBinaryOpOperands(Opcode, UndefScalar, CElt, DL)
1829 : ConstantFoldBinaryOpOperands(Opcode, CElt, UndefScalar, DL);
1830 if (!MaybeUndef || !match(MaybeUndef, m_Undef())) {
1831 MayChange = false;
1832 break;
1833 }
1834 }
1835 }
1836 if (MayChange) {
1837 Constant *NewC = ConstantVector::get(NewVecC);
1838 // It may not be safe to execute a binop on a vector with undef elements
1839 // because the entire instruction can be folded to undef or create poison
1840 // that did not exist in the original code.
1841 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1842 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1843
1844 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1845 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1846 Value *NewLHS = ConstOp1 ? V1 : NewC;
1847 Value *NewRHS = ConstOp1 ? NewC : V1;
1848 return createBinOpShuffle(NewLHS, NewRHS, Mask);
1849 }
1850 }
1851
1852 // Try to reassociate to sink a splat shuffle after a binary operation.
1853 if (Inst.isAssociative() && Inst.isCommutative()) {
1854 // Canonicalize shuffle operand as LHS.
1855 if (isa<ShuffleVectorInst>(RHS))
1856 std::swap(LHS, RHS);
1857
1858 Value *X;
1859 ArrayRef<int> MaskC;
1860 int SplatIndex;
1861 Value *Y, *OtherOp;
1862 if (!match(LHS,
1863 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
1864 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) ||
1865 X->getType() != Inst.getType() ||
1866 !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))
1867 return nullptr;
1868
1869 // FIXME: This may not be safe if the analysis allows undef elements. By
1870 // moving 'Y' before the splat shuffle, we are implicitly assuming
1871 // that it is not undef/poison at the splat index.
1872 if (isSplatValue(OtherOp, SplatIndex)) {
1873 std::swap(Y, OtherOp);
1874 } else if (!isSplatValue(Y, SplatIndex)) {
1875 return nullptr;
1876 }
1877
1878 // X and Y are splatted values, so perform the binary operation on those
1879 // values followed by a splat followed by the 2nd binary operation:
1880 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
1881 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
1882 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
1883 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
1884 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
1885
1886 // Intersect FMF on both new binops. Other (poison-generating) flags are
1887 // dropped to be safe.
1888 if (isa<FPMathOperator>(R)) {
1889 R->copyFastMathFlags(&Inst);
1890 R->andIRFlags(RHS);
1891 }
1892 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
1893 NewInstBO->copyIRFlags(R);
1894 return R;
1895 }
1896
1897 return nullptr;
1898}
1899
1900/// Try to narrow the width of a binop if at least 1 operand is an extend of
1901/// of a value. This requires a potentially expensive known bits check to make
1902/// sure the narrow op does not overflow.
1903Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
1904 // We need at least one extended operand.
1905 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1906
1907 // If this is a sub, we swap the operands since we always want an extension
1908 // on the RHS. The LHS can be an extension or a constant.
1909 if (BO.getOpcode() == Instruction::Sub)
1910 std::swap(Op0, Op1);
1911
1912 Value *X;
1913 bool IsSext = match(Op0, m_SExt(m_Value(X)));
1914 if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1915 return nullptr;
1916
1917 // If both operands are the same extension from the same source type and we
1918 // can eliminate at least one (hasOneUse), this might work.
1919 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1920 Value *Y;
1921 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1922 cast<Operator>(Op1)->getOpcode() == CastOpc &&
1923 (Op0->hasOneUse() || Op1->hasOneUse()))) {
1924 // If that did not match, see if we have a suitable constant operand.
1925 // Truncating and extending must produce the same constant.
1926 Constant *WideC;
1927 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1928 return nullptr;
1929 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1930 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1931 return nullptr;
1932 Y = NarrowC;
1933 }
1934
1935 // Swap back now that we found our operands.
1936 if (BO.getOpcode() == Instruction::Sub)
1937 std::swap(X, Y);
1938
1939 // Both operands have narrow versions. Last step: the math must not overflow
1940 // in the narrow width.
1941 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1942 return nullptr;
1943
1944 // bo (ext X), (ext Y) --> ext (bo X, Y)
1945 // bo (ext X), C --> ext (bo X, C')
1946 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1947 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1948 if (IsSext)
1949 NewBinOp->setHasNoSignedWrap();
1950 else
1951 NewBinOp->setHasNoUnsignedWrap();
1952 }
1953 return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1954}
1955
1957 // At least one GEP must be inbounds.
1958 if (!GEP1.isInBounds() && !GEP2.isInBounds())
1959 return false;
1960
1961 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) &&
1962 (GEP2.isInBounds() || GEP2.hasAllZeroIndices());
1963}
1964
1965/// Thread a GEP operation with constant indices through the constant true/false
1966/// arms of a select.
1968 InstCombiner::BuilderTy &Builder) {
1969 if (!GEP.hasAllConstantIndices())
1970 return nullptr;
1971
1972 Instruction *Sel;
1973 Value *Cond;
1974 Constant *TrueC, *FalseC;
1975 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
1976 !match(Sel,
1977 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
1978 return nullptr;
1979
1980 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
1981 // Propagate 'inbounds' and metadata from existing instructions.
1982 // Note: using IRBuilder to create the constants for efficiency.
1983 SmallVector<Value *, 4> IndexC(GEP.indices());
1984 bool IsInBounds = GEP.isInBounds();
1985 Type *Ty = GEP.getSourceElementType();
1986 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", IsInBounds);
1987 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", IsInBounds);
1988 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
1989}
1990
1992 GEPOperator *Src) {
1993 // Combine Indices - If the source pointer to this getelementptr instruction
1994 // is a getelementptr instruction with matching element type, combine the
1995 // indices of the two getelementptr instructions into a single instruction.
1996 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1997 return nullptr;
1998
1999 if (Src->getResultElementType() == GEP.getSourceElementType() &&
2000 Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
2001 Src->hasOneUse()) {
2002 Value *GO1 = GEP.getOperand(1);
2003 Value *SO1 = Src->getOperand(1);
2004
2005 if (LI) {
2006 // Try to reassociate loop invariant GEP chains to enable LICM.
2007 if (Loop *L = LI->getLoopFor(GEP.getParent())) {
2008 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
2009 // invariant: this breaks the dependence between GEPs and allows LICM
2010 // to hoist the invariant part out of the loop.
2011 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
2012 // The swapped GEPs are inbounds if both original GEPs are inbounds
2013 // and the sign of the offsets is the same. For simplicity, only
2014 // handle both offsets being non-negative.
2015 bool IsInBounds = Src->isInBounds() && GEP.isInBounds() &&
2016 isKnownNonNegative(SO1, DL, 0, &AC, &GEP, &DT) &&
2017 isKnownNonNegative(GO1, DL, 0, &AC, &GEP, &DT);
2018 // Put NewSrc at same location as %src.
2019 Builder.SetInsertPoint(cast<Instruction>(Src));
2020 Value *NewSrc = Builder.CreateGEP(GEP.getSourceElementType(),
2021 Src->getPointerOperand(), GO1,
2022 Src->getName(), IsInBounds);
2024 GEP.getSourceElementType(), NewSrc, {SO1});
2025 NewGEP->setIsInBounds(IsInBounds);
2026 return NewGEP;
2027 }
2028 }
2029 }
2030 }
2031
2032 // Note that if our source is a gep chain itself then we wait for that
2033 // chain to be resolved before we perform this transformation. This
2034 // avoids us creating a TON of code in some cases.
2035 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
2036 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
2037 return nullptr; // Wait until our source is folded to completion.
2038
2039 // For constant GEPs, use a more general offset-based folding approach.
2040 // Only do this for opaque pointers, as the result element type may change.
2041 Type *PtrTy = Src->getType()->getScalarType();
2042 if (PtrTy->isOpaquePointerTy() && GEP.hasAllConstantIndices() &&
2043 (Src->hasOneUse() || Src->hasAllConstantIndices())) {
2044 // Split Src into a variable part and a constant suffix.
2046 Type *BaseType = GTI.getIndexedType();
2047 bool IsFirstType = true;
2048 unsigned NumVarIndices = 0;
2049 for (auto Pair : enumerate(Src->indices())) {
2050 if (!isa<ConstantInt>(Pair.value())) {
2051 BaseType = GTI.getIndexedType();
2052 IsFirstType = false;
2053 NumVarIndices = Pair.index() + 1;
2054 }
2055 ++GTI;
2056 }
2057
2058 // Determine the offset for the constant suffix of Src.
2060 if (NumVarIndices != Src->getNumIndices()) {
2061 // FIXME: getIndexedOffsetInType() does not handled scalable vectors.
2062 if (isa<ScalableVectorType>(BaseType))
2063 return nullptr;
2064
2065 SmallVector<Value *> ConstantIndices;
2066 if (!IsFirstType)
2067 ConstantIndices.push_back(
2069 append_range(ConstantIndices, drop_begin(Src->indices(), NumVarIndices));
2070 Offset += DL.getIndexedOffsetInType(BaseType, ConstantIndices);
2071 }
2072
2073 // Add the offset for GEP (which is fully constant).
2074 if (!GEP.accumulateConstantOffset(DL, Offset))
2075 return nullptr;
2076
2077 APInt OffsetOld = Offset;
2078 // Convert the total offset back into indices.
2079 SmallVector<APInt> ConstIndices =
2081 if (!Offset.isZero() || (!IsFirstType && !ConstIndices[0].isZero())) {
2082 // If both GEP are constant-indexed, and cannot be merged in either way,
2083 // convert them to a GEP of i8.
2084 if (Src->hasAllConstantIndices())
2085 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2087 Builder.getInt8Ty(), Src->getOperand(0),
2088 Builder.getInt(OffsetOld), GEP.getName())
2090 Builder.getInt8Ty(), Src->getOperand(0),
2091 Builder.getInt(OffsetOld), GEP.getName());
2092 return nullptr;
2093 }
2094
2095 bool IsInBounds = isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP));
2096 SmallVector<Value *> Indices;
2097 append_range(Indices, drop_end(Src->indices(),
2098 Src->getNumIndices() - NumVarIndices));
2099 for (const APInt &Idx : drop_begin(ConstIndices, !IsFirstType)) {
2100 Indices.push_back(ConstantInt::get(GEP.getContext(), Idx));
2101 // Even if the total offset is inbounds, we may end up representing it
2102 // by first performing a larger negative offset, and then a smaller
2103 // positive one. The large negative offset might go out of bounds. Only
2104 // preserve inbounds if all signs are the same.
2105 IsInBounds &= Idx.isNonNegative() == ConstIndices[0].isNonNegative();
2106 }
2107
2108 return IsInBounds
2109 ? GetElementPtrInst::CreateInBounds(Src->getSourceElementType(),
2110 Src->getOperand(0), Indices,
2111 GEP.getName())
2112 : GetElementPtrInst::Create(Src->getSourceElementType(),
2113 Src->getOperand(0), Indices,
2114 GEP.getName());
2115 }
2116
2117 if (Src->getResultElementType() != GEP.getSourceElementType())
2118 return nullptr;
2119
2120 SmallVector<Value*, 8> Indices;
2121
2122 // Find out whether the last index in the source GEP is a sequential idx.
2123 bool EndsWithSequential = false;
2124 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2125 I != E; ++I)
2126 EndsWithSequential = I.isSequential();
2127
2128 // Can we combine the two pointer arithmetics offsets?
2129 if (EndsWithSequential) {
2130 // Replace: gep (gep %P, long B), long A, ...
2131 // With: T = long A+B; gep %P, T, ...
2132 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2133 Value *GO1 = GEP.getOperand(1);
2134
2135 // If they aren't the same type, then the input hasn't been processed
2136 // by the loop above yet (which canonicalizes sequential index types to
2137 // intptr_t). Just avoid transforming this until the input has been
2138 // normalized.
2139 if (SO1->getType() != GO1->getType())
2140 return nullptr;
2141
2142 Value *Sum =
2143 simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2144 // Only do the combine when we are sure the cost after the
2145 // merge is never more than that before the merge.
2146 if (Sum == nullptr)
2147 return nullptr;
2148
2149 // Update the GEP in place if possible.
2150 if (Src->getNumOperands() == 2) {
2151 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2152 replaceOperand(GEP, 0, Src->getOperand(0));
2153 replaceOperand(GEP, 1, Sum);
2154 return &GEP;
2155 }
2156 Indices.append(Src->op_begin()+1, Src->op_end()-1);
2157 Indices.push_back(Sum);
2158 Indices.append(GEP.op_begin()+2, GEP.op_end());
2159 } else if (isa<Constant>(*GEP.idx_begin()) &&
2160 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2161 Src->getNumOperands() != 1) {
2162 // Otherwise we can do the fold if the first index of the GEP is a zero
2163 Indices.append(Src->op_begin()+1, Src->op_end());
2164 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2165 }
2166
2167 if (!Indices.empty())
2168 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2170 Src->getSourceElementType(), Src->getOperand(0), Indices,
2171 GEP.getName())
2172 : GetElementPtrInst::Create(Src->getSourceElementType(),
2173 Src->getOperand(0), Indices,
2174 GEP.getName());
2175
2176 return nullptr;
2177}
2178
2179// Note that we may have also stripped an address space cast in between.
2182 // With opaque pointers, there is no pointer element type we can use to
2183 // adjust the GEP type.
2184 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2185 if (SrcType->isOpaque())
2186 return nullptr;
2187
2188 Type *GEPEltType = GEP.getSourceElementType();
2189 Type *SrcEltType = SrcType->getNonOpaquePointerElementType();
2190 Value *SrcOp = BCI->getOperand(0);
2191
2192 // GEP directly using the source operand if this GEP is accessing an element
2193 // of a bitcasted pointer to vector or array of the same dimensions:
2194 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2195 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2196 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy,
2197 const DataLayout &DL) {
2198 auto *VecVTy = cast<FixedVectorType>(VecTy);
2199 return ArrTy->getArrayElementType() == VecVTy->getElementType() &&
2200 ArrTy->getArrayNumElements() == VecVTy->getNumElements() &&
2201 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2202 };
2203 if (GEP.getNumOperands() == 3 &&
2204 ((GEPEltType->isArrayTy() && isa<FixedVectorType>(SrcEltType) &&
2205 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2206 (isa<FixedVectorType>(GEPEltType) && SrcEltType->isArrayTy() &&
2207 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2208
2209 // Create a new GEP here, as using `setOperand()` followed by
2210 // `setSourceElementType()` won't actually update the type of the
2211 // existing GEP Value. Causing issues if this Value is accessed when
2212 // constructing an AddrSpaceCastInst
2213 SmallVector<Value *, 8> Indices(GEP.indices());
2214 Value *NGEP =
2215 Builder.CreateGEP(SrcEltType, SrcOp, Indices, "", GEP.isInBounds());
2216 NGEP->takeName(&GEP);
2217
2218 // Preserve GEP address space to satisfy users
2219 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2220 return new AddrSpaceCastInst(NGEP, GEP.getType());
2221
2222 return replaceInstUsesWith(GEP, NGEP);
2223 }
2224
2225 // See if we can simplify:
2226 // X = bitcast A* to B*
2227 // Y = gep X, <...constant indices...>
2228 // into a gep of the original struct. This is important for SROA and alias
2229 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2230 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEP.getType());
2231 APInt Offset(OffsetBits, 0);
2232
2233 // If the bitcast argument is an allocation, The bitcast is for convertion
2234 // to actual type of allocation. Removing such bitcasts, results in having
2235 // GEPs with i8* base and pure byte offsets. That means GEP is not aware of
2236 // struct or array hierarchy.
2237 // By avoiding such GEPs, phi translation and MemoryDependencyAnalysis have
2238 // a better chance to succeed.
2239 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset) &&
2240 !isAllocationFn(SrcOp, &TLI)) {
2241 // If this GEP instruction doesn't move the pointer, just replace the GEP
2242 // with a bitcast of the real input to the dest type.
2243 if (!Offset) {
2244 // If the bitcast is of an allocation, and the allocation will be
2245 // converted to match the type of the cast, don't touch this.
2246 if (isa<AllocaInst>(SrcOp)) {
2247 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2248 if (Instruction *I = visitBitCast(*BCI)) {
2249 if (I != BCI) {
2250 I->takeName(BCI);
2251 I->insertInto(BCI->getParent(), BCI->getIterator());
2252 replaceInstUsesWith(*BCI, I);
2253 }
2254 return &GEP;
2255 }
2256 }
2257
2258 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2259 return new AddrSpaceCastInst(SrcOp, GEP.getType());
2260 return new BitCastInst(SrcOp, GEP.getType());
2261 }
2262
2263 // Otherwise, if the offset is non-zero, we need to find out if there is a
2264 // field at Offset in 'A's type. If so, we can pull the cast through the
2265 // GEP.
2266 SmallVector<Value *, 8> NewIndices;
2267 if (findElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices, DL)) {
2268 Value *NGEP = Builder.CreateGEP(SrcEltType, SrcOp, NewIndices, "",
2269 GEP.isInBounds());
2270
2271 if (NGEP->getType() == GEP.getType())
2272 return replaceInstUsesWith(GEP, NGEP);
2273 NGEP->takeName(&GEP);
2274
2275 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2276 return new AddrSpaceCastInst(NGEP, GEP.getType());
2277 return new BitCastInst(NGEP, GEP.getType());
2278 }
2279 }
2280
2281 return nullptr;
2282}
2283
2285 Value *PtrOp = GEP.getOperand(0);
2286 SmallVector<Value *, 8> Indices(GEP.indices());
2287 Type *GEPType = GEP.getType();
2288 Type *GEPEltType = GEP.getSourceElementType();
2289 bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType);
2290 if (Value *V = simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.isInBounds(),
2292 return replaceInstUsesWith(GEP, V);
2293
2294 // For vector geps, use the generic demanded vector support.
2295 // Skip if GEP return type is scalable. The number of elements is unknown at
2296 // compile-time.
2297 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
2298 auto VWidth = GEPFVTy->getNumElements();
2299 APInt UndefElts(VWidth, 0);
2300 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
2301 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
2302 UndefElts)) {
2303 if (V != &GEP)
2304 return replaceInstUsesWith(GEP, V);
2305 return &GEP;
2306 }
2307
2308 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
2309 // possible (decide on canonical form for pointer broadcast), 3) exploit
2310 // undef elements to decrease demanded bits
2311 }
2312
2313 // Eliminate unneeded casts for indices, and replace indices which displace
2314 // by multiples of a zero size type with zero.
2315 bool MadeChange = false;
2316
2317 // Index width may not be the same width as pointer width.
2318 // Data layout chooses the right type based on supported integer types.
2319 Type *NewScalarIndexTy =
2320 DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
2321
2323 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
2324 ++I, ++GTI) {
2325 // Skip indices into struct types.
2326 if (GTI.isStruct())
2327 continue;
2328
2329 Type *IndexTy = (*I)->getType();
2330 Type *NewIndexType =
2331 IndexTy->isVectorTy()
2332 ? VectorType::get(NewScalarIndexTy,
2333 cast<VectorType>(IndexTy)->getElementCount())
2334 : NewScalarIndexTy;
2335
2336 // If the element type has zero size then any index over it is equivalent
2337 // to an index of zero, so replace it with zero if it is not zero already.
2338 Type *EltTy = GTI.getIndexedType();
2339 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
2340 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
2341 *I = Constant::getNullValue(NewIndexType);
2342 MadeChange = true;
2343 }
2344
2345 if (IndexTy != NewIndexType) {
2346 // If we are using a wider index than needed for this platform, shrink
2347 // it to what we need. If narrower, sign-extend it to what we need.
2348 // This explicit cast can make subsequent optimizations more obvious.
2349 *I = Builder.CreateIntCast(*I, NewIndexType, true);
2350 MadeChange = true;
2351 }
2352 }
2353 if (MadeChange)
2354 return &GEP;
2355
2356 // Check to see if the inputs to the PHI node are getelementptr instructions.
2357 if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
2358 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
2359 if (!Op1)
2360 return nullptr;
2361
2362 // Don't fold a GEP into itself through a PHI node. This can only happen
2363 // through the back-edge of a loop. Folding a GEP into itself means that
2364 // the value of the previous iteration needs to be stored in the meantime,
2365 // thus requiring an additional register variable to be live, but not
2366 // actually achieving anything (the GEP still needs to be executed once per
2367 // loop iteration).
2368 if (Op1 == &GEP)
2369 return nullptr;
2370
2371 int DI = -1;
2372
2373 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
2374 auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
2375 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
2376 Op1->getSourceElementType() != Op2->getSourceElementType())
2377 return nullptr;
2378
2379 // As for Op1 above, don't try to fold a GEP into itself.
2380 if (Op2 == &GEP)
2381 return nullptr;
2382
2383 // Keep track of the type as we walk the GEP.
2384 Type *CurTy = nullptr;
2385
2386 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
2387 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
2388 return nullptr;
2389
2390 if (Op1->getOperand(J) != Op2->getOperand(J)) {
2391 if (DI == -1) {
2392 // We have not seen any differences yet in the GEPs feeding the
2393 // PHI yet, so we record this one if it is allowed to be a
2394 // variable.
2395
2396 // The first two arguments can vary for any GEP, the rest have to be
2397 // static for struct slots
2398 if (J > 1) {
2399 assert(CurTy && "No current type?");
2400 if (CurTy->isStructTy())
2401 return nullptr;
2402 }
2403
2404 DI = J;
2405 } else {
2406 // The GEP is different by more than one input. While this could be
2407 // extended to support GEPs that vary by more than one variable it
2408 // doesn't make sense since it greatly increases the complexity and
2409 // would result in an R+R+R addressing mode which no backend
2410 // directly supports and would need to be broken into several
2411 // simpler instructions anyway.
2412 return nullptr;
2413 }
2414 }
2415
2416 // Sink down a layer of the type for the next iteration.
2417 if (J > 0) {
2418 if (J == 1) {
2419 CurTy = Op1->getSourceElementType();
2420 } else {
2421 CurTy =
2422 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
2423 }
2424 }
2425 }
2426 }
2427
2428 // If not all GEPs are identical we'll have to create a new PHI node.
2429 // Check that the old PHI node has only one use so that it will get
2430 // removed.
2431 if (DI != -1 && !PN->hasOneUse())
2432 return nullptr;
2433
2434 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
2435 if (DI == -1) {
2436 // All the GEPs feeding the PHI are identical. Clone one down into our
2437 // BB so that it can be merged with the current GEP.
2438 } else {
2439 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
2440 // into the current block so it can be merged, and create a new PHI to
2441 // set that index.
2442 PHINode *NewPN;
2443 {
2446 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
2447 PN->getNumOperands());
2448 }
2449
2450 for (auto &I : PN->operands())
2451 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
2452 PN->getIncomingBlock(I));
2453
2454 NewGEP->setOperand(DI, NewPN);
2455 }
2456
2457 NewGEP->insertInto(GEP.getParent(), GEP.getParent()->getFirstInsertionPt());
2458 return replaceOperand(GEP, 0, NewGEP);
2459 }
2460
2461 if (auto *Src = dyn_cast<GEPOperator>(PtrOp))
2462 if (Instruction *I = visitGEPOfGEP(GEP, Src))
2463 return I;
2464
2465 // Skip if GEP source element type is scalable. The type alloc size is unknown
2466 // at compile-time.
2467 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) {
2468 unsigned AS = GEP.getPointerAddressSpace();
2469 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2470 DL.getIndexSizeInBits(AS)) {
2471 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
2472
2473 bool Matched = false;
2474 uint64_t C;
2475 Value *V = nullptr;
2476 if (TyAllocSize == 1) {
2477 V = GEP.getOperand(1);
2478 Matched = true;
2479 } else if (match(GEP.getOperand(1),
2480 m_AShr(m_Value(V), m_ConstantInt(C)))) {
2481 if (TyAllocSize == 1ULL << C)
2482 Matched = true;
2483 } else if (match(GEP.getOperand(1),
2484 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
2485 if (TyAllocSize == C)
2486 Matched = true;
2487 }
2488
2489 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y), but
2490 // only if both point to the same underlying object (otherwise provenance
2491 // is not necessarily retained).
2492 Value *Y;
2493 Value *X = GEP.getOperand(0);
2494 if (Matched &&
2498 }
2499 }
2500
2501 // We do not handle pointer-vector geps here.
2502 if (GEPType->isVectorTy())
2503 return nullptr;
2504
2505 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2506 Value *StrippedPtr = PtrOp->stripPointerCasts();
2507 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
2508
2509 // TODO: The basic approach of these folds is not compatible with opaque
2510 // pointers, because we can't use bitcasts as a hint for a desirable GEP
2511 // type. Instead, we should perform canonicalization directly on the GEP
2512 // type. For now, skip these.
2513 if (StrippedPtr != PtrOp && !StrippedPtrTy->isOpaque()) {
2514 bool HasZeroPointerIndex = false;
2515 Type *StrippedPtrEltTy = StrippedPtrTy->getNonOpaquePointerElementType();
2516
2517 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2518 HasZeroPointerIndex = C->isZero();
2519
2520 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2521 // into : GEP [10 x i8]* X, i32 0, ...
2522 //
2523 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2524 // into : GEP i8* X, ...
2525 //
2526 // This occurs when the program declares an array extern like "int X[];"
2527 if (HasZeroPointerIndex) {
2528 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2529 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2530 if (CATy->getElementType() == StrippedPtrEltTy) {
2531 // -> GEP i8* X, ...
2534 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
2535 Res->setIsInBounds(GEP.isInBounds());
2536 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
2537 return Res;
2538 // Insert Res, and create an addrspacecast.
2539 // e.g.,
2540 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2541 // ->
2542 // %0 = GEP i8 addrspace(1)* X, ...
2543 // addrspacecast i8 addrspace(1)* %0 to i8*
2544 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
2545 }
2546
2547 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2548 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2549 if (CATy->getElementType() == XATy->getElementType()) {
2550 // -> GEP [10 x i8]* X, i32 0, ...
2551 // At this point, we know that the cast source type is a pointer
2552 // to an array of the same type as the destination pointer
2553 // array. Because the array type is never stepped over (there
2554 // is a leading zero) we can fold the cast into this GEP.
2555 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2556 GEP.setSourceElementType(XATy);
2557 return replaceOperand(GEP, 0, StrippedPtr);
2558 }
2559 // Cannot replace the base pointer directly because StrippedPtr's
2560 // address space is different. Instead, create a new GEP followed by
2561 // an addrspacecast.
2562 // e.g.,
2563 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2564 // i32 0, ...
2565 // ->
2566 // %0 = GEP [10 x i8] addrspace(1)* X, ...
2567 // addrspacecast i8 addrspace(1)* %0 to i8*
2568 SmallVector<Value *, 8> Idx(GEP.indices());
2569 Value *NewGEP =
2570 Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2571 GEP.getName(), GEP.isInBounds());
2572 return new AddrSpaceCastInst(NewGEP, GEPType);
2573 }
2574 }
2575 }
2576 } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) {
2577 // Skip if GEP source element type is scalable. The type alloc size is
2578 // unknown at compile-time.
2579 // Transform things like: %t = getelementptr i32*
2580 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2
2581 // x i32]* %str, i32 0, i32 %V; bitcast
2582 if (StrippedPtrEltTy->isArrayTy() &&
2583 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2584 DL.getTypeAllocSize(GEPEltType)) {
2585 Type *IdxType = DL.getIndexType(GEPType);
2586 Value *Idx[2] = {Constant::getNullValue(IdxType), GEP.getOperand(1)};
2587 Value *NewGEP = Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2588 GEP.getName(), GEP.isInBounds());
2589
2590 // V and GEP are both pointer types --> BitCast
2591 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2592 }
2593
2594 // Transform things like:
2595 // %V = mul i64 %N, 4
2596 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2597 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
2598 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2599 // Check that changing the type amounts to dividing the index by a scale
2600 // factor.
2601 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
2602 uint64_t SrcSize =
2603 DL.getTypeAllocSize(StrippedPtrEltTy).getFixedValue();
2604 if (ResSize && SrcSize % ResSize == 0) {
2605 Value *Idx = GEP.getOperand(1);
2606 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2607 uint64_t Scale = SrcSize / ResSize;
2608
2609 // Earlier transforms ensure that the index has the right type
2610 // according to Data Layout, which considerably simplifies the
2611 // logic by eliminating implicit casts.
2612 assert(Idx->getType() == DL.getIndexType(GEPType) &&
2613 "Index type does not match the Data Layout preferences");
2614
2615 bool NSW;
2616 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2617 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2618 // If the multiplication NewIdx * Scale may overflow then the new
2619 // GEP may not be "inbounds".
2620 Value *NewGEP =
2621 Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2622 GEP.getName(), GEP.isInBounds() && NSW);
2623
2624 // The NewGEP must be pointer typed, so must the old one -> BitCast
2626 GEPType);
2627 }
2628 }
2629 }
2630
2631 // Similarly, transform things like:
2632 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2633 // (where tmp = 8*tmp2) into:
2634 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2635 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2636 StrippedPtrEltTy->isArrayTy()) {
2637 // Check that changing to the array element type amounts to dividing the
2638 // index by a scale factor.
2639 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
2640 uint64_t ArrayEltSize =
2641 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType())
2642 .getFixedValue();
2643 if (ResSize && ArrayEltSize % ResSize == 0) {
2644 Value *Idx = GEP.getOperand(1);
2645 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2646 uint64_t Scale = ArrayEltSize / ResSize;
2647
2648 // Earlier transforms ensure that the index has the right type
2649 // according to the Data Layout, which considerably simplifies
2650 // the logic by eliminating implicit casts.
2651 assert(Idx->getType() == DL.getIndexType(GEPType) &&
2652 "Index type does not match the Data Layout preferences");
2653
2654 bool NSW;
2655 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2656 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2657 // If the multiplication NewIdx * Scale may overflow then the new
2658 // GEP may not be "inbounds".
2659 Type *IndTy = DL.getIndexType(GEPType);
2660 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2661
2662 Value *NewGEP =
2663 Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2664 GEP.getName(), GEP.isInBounds() && NSW);
2665 // The NewGEP must be pointer typed, so must the old one -> BitCast
2667 GEPType);
2668 }
2669 }
2670 }
2671 }
2672 }
2673
2674 // addrspacecast between types is canonicalized as a bitcast, then an
2675 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2676 // through the addrspacecast.
2677 Value *ASCStrippedPtrOp = PtrOp;
2678 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2679 // X = bitcast A addrspace(1)* to B addrspace(1)*
2680 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2681 // Z = gep Y, <...constant indices...>
2682 // Into an addrspacecasted GEP of the struct.
2683 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2684 ASCStrippedPtrOp = BC;
2685 }
2686
2687 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp))
2688 if (Instruction *I = visitGEPOfBitcast(BCI, GEP))
2689 return I;
2690
2691 if (!GEP.isInBounds()) {
2692 unsigned IdxWidth =
2694 APInt BasePtrOffset(IdxWidth, 0);
2695 Value *UnderlyingPtrOp =
2697 BasePtrOffset);
2698 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2699 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2700 BasePtrOffset.isNonNegative()) {
2701 APInt AllocSize(
2702 IdxWidth,
2703 DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinValue());
2704 if (BasePtrOffset.ule(AllocSize)) {
2706 GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());
2707 }
2708 }
2709 }
2710 }
2711
2713 return R;
2714
2715 return nullptr;
2716}
2717
2719 Instruction *AI) {
2720 if (isa<ConstantPointerNull>(V))
2721 return true;
2722 if (auto *LI = dyn_cast<LoadInst>(V))
2723 return isa<GlobalVariable>(LI->getPointerOperand());
2724 // Two distinct allocations will never be equal.
2725 return isAllocLikeFn(V, &TLI) && V != AI;
2726}
2727
2728/// Given a call CB which uses an address UsedV, return true if we can prove the
2729/// call's only possible effect is storing to V.
2730static bool isRemovableWrite(CallBase &CB, Value *UsedV,
2731 const TargetLibraryInfo &TLI) {
2732 if (!CB.use_empty())
2733 // TODO: add recursion if returned attribute is present
2734 return false;
2735
2736 if (CB.isTerminator())
2737 // TODO: remove implementation restriction
2738 return false;
2739
2740 if (!CB.willReturn() || !CB.doesNotThrow())
2741 return false;
2742
2743 // If the only possible side effect of the call is writing to the alloca,
2744 // and the result isn't used, we can safely remove any reads implied by the
2745 // call including those which might read the alloca itself.
2746 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);
2747 return Dest && Dest->Ptr == UsedV;
2748}
2749
2752 const TargetLibraryInfo &TLI) {
2754 const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI);
2755 Worklist.push_back(AI);
2756
2757 do {
2758 Instruction *PI = Worklist.pop_back_val();
2759 for (User *U : PI->users()) {
2760 Instruction *I = cast<Instruction>(U);
2761 switch (I->getOpcode()) {
2762 default:
2763 // Give up the moment we see something we can't handle.
2764 return false;
2765
2766 case Instruction::AddrSpaceCast:
2767 case Instruction::BitCast:
2768 case Instruction::GetElementPtr:
2769 Users.emplace_back(I);
2770 Worklist.push_back(I);
2771 continue;
2772
2773 case Instruction::ICmp: {
2774 ICmpInst *ICI = cast<ICmpInst>(I);
2775 // We can fold eq/ne comparisons with null to false/true, respectively.
2776 // We also fold comparisons in some conditions provided the alloc has
2777 // not escaped (see isNeverEqualToUnescapedAlloc).
2778 if (!ICI->isEquality())
2779 return false;
2780 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2781 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2782 return false;
2783 Users.emplace_back(I);
2784 continue;
2785 }
2786
2787 case Instruction::Call:
2788 // Ignore no-op and store intrinsics.
2789 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2790 switch (II->getIntrinsicID()) {
2791 default:
2792 return false;
2793
2794 case Intrinsic::memmove:
2795 case Intrinsic::memcpy:
2796 case Intrinsic::memset: {
2797 MemIntrinsic *MI = cast<MemIntrinsic>(II);
2798 if (MI->isVolatile() || MI->getRawDest() != PI)
2799 return false;
2800 [[fallthrough]];
2801 }
2802 case Intrinsic::assume:
2803 case Intrinsic::invariant_start:
2804 case Intrinsic::invariant_end:
2805 case Intrinsic::lifetime_start:
2806 case Intrinsic::lifetime_end:
2807 case Intrinsic::objectsize:
2808 Users.emplace_back(I);
2809 continue;
2810 case Intrinsic::launder_invariant_group:
2811 case Intrinsic::strip_invariant_group:
2812 Users.emplace_back(I);
2813 Worklist.push_back(I);
2814 continue;
2815 }
2816 }
2817
2818 if (isRemovableWrite(*cast<CallBase>(I), PI, TLI)) {
2819 Users.emplace_back(I);
2820 continue;
2821 }
2822
2823 if (getFreedOperand(cast<CallBase>(I), &TLI) == PI &&
2824 getAllocationFamily(I, &TLI) == Family) {
2825 assert(Family);
2826 Users.emplace_back(I);
2827 continue;
2828 }
2829
2830 if (getReallocatedOperand(cast<CallBase>(I)) == PI &&
2831 getAllocationFamily(I, &TLI) == Family) {
2832 assert(Family);
2833 Users.emplace_back(I);
2834 Worklist.push_back(I);
2835 continue;
2836 }
2837
2838 return false;
2839
2840 case Instruction::Store: {
2841 StoreInst *SI = cast<StoreInst>(I);
2842 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2843 return false;
2844 Users.emplace_back(I);
2845 continue;
2846 }
2847 }
2848 llvm_unreachable("missing a return?");
2849 }
2850 } while (!Worklist.empty());
2851 return true;
2852}
2853
2855 assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI));
2856
2857 // If we have a malloc call which is only used in any amount of comparisons to
2858 // null and free calls, delete the calls and replace the comparisons with true
2859 // or false as appropriate.
2860
2861 // This is based on the principle that we can substitute our own allocation
2862 // function (which will never return null) rather than knowledge of the
2863 // specific function being called. In some sense this can change the permitted
2864 // outputs of a program (when we convert a malloc to an alloca, the fact that
2865 // the allocation is now on the stack is potentially visible, for example),
2866 // but we believe in a permissible manner.
2868
2869 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2870 // before each store.
2872 std::unique_ptr<DIBuilder> DIB;
2873 if (isa<AllocaInst>(MI)) {
2874 findDbgUsers(DVIs, &MI);
2875 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2876 }
2877
2878 if (isAllocSiteRemovable(&MI, Users, TLI)) {
2879 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2880 // Lowering all @llvm.objectsize calls first because they may
2881 // use a bitcast/GEP of the alloca we are removing.
2882 if (!Users[i])
2883 continue;
2884
2885 Instruction *I = cast<Instruction>(&*Users[i]);
2886
2887 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2888 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2889 Value *Result =
2890 lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/true);
2891 replaceInstUsesWith(*I, Result);
2893 Users[i] = nullptr; // Skip examining in the next loop.
2894 }
2895 }
2896 }
2897 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2898 if (!Users[i])
2899 continue;
2900
2901 Instruction *I = cast<Instruction>(&*Users[i]);
2902
2903 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2905 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2906 C->isFalseWhenEqual()));
2907 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2908 for (auto *DVI : DVIs)
2909 if (DVI->isAddressOfVariable())
2911 } else {
2912 // Casts, GEP, or anything else: we're about to delete this instruction,
2913 // so it can not have any valid uses.
2914 replaceInstUsesWith(*I, PoisonValue::get(I->getType()));
2915 }
2917 }
2918
2919 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2920 // Replace invoke with a NOP intrinsic to maintain the original CFG
2921 Module *M = II->getModule();
2922 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2923 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2924 std::nullopt, "", II->getParent());
2925 }
2926
2927 // Remove debug intrinsics which describe the value contained within the
2928 // alloca. In addition to removing dbg.{declare,addr} which simply point to
2929 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
2930 //
2931 // ```
2932 // define void @foo(i32 %0) {
2933 // %a = alloca i32 ; Deleted.
2934 // store i32 %0, i32* %a
2935 // dbg.value(i32 %0, "arg0") ; Not deleted.
2936 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
2937 // call void @trivially_inlinable_no_op(i32* %a)
2938 // ret void
2939 // }
2940 // ```
2941 //
2942 // This may not be required if we stop describing the contents of allocas
2943 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
2944 // the LowerDbgDeclare utility.
2945 //
2946 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
2947 // "arg0" dbg.value may be stale after the call. However, failing to remove
2948 // the DW_OP_deref dbg.value causes large gaps in location coverage.
2949 for (auto *DVI : DVIs)
2950 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref())
2951 DVI->eraseFromParent();
2952
2953 return eraseInstFromFunction(MI);
2954 }
2955 return nullptr;
2956}
2957
2958/// Move the call to free before a NULL test.
2959///
2960/// Check if this free is accessed after its argument has been test
2961/// against NULL (property 0).
2962/// If yes, it is legal to move this call in its predecessor block.
2963///
2964/// The move is performed only if the block containing the call to free
2965/// will be removed, i.e.:
2966/// 1. it has only one predecessor P, and P has two successors
2967/// 2. it contains the call, noops, and an unconditional branch
2968/// 3. its successor is the same as its predecessor's successor
2969///
2970/// The profitability is out-of concern here and this function should
2971/// be called only if the caller knows this transformation would be
2972/// profitable (e.g., for code size).
2974 const DataLayout &DL) {
2975 Value *Op = FI.getArgOperand(0);
2976 BasicBlock *FreeInstrBB = FI.getParent();
2977 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2978
2979 // Validate part of constraint #1: Only one predecessor
2980 // FIXME: We can extend the number of predecessor, but in that case, we
2981 // would duplicate the call to free in each predecessor and it may
2982 // not be profitable even for code size.
2983 if (!PredBB)
2984 return nullptr;
2985
2986 // Validate constraint #2: Does this block contains only the call to
2987 // free, noops, and an unconditional branch?
2988 BasicBlock *SuccBB;
2989 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2990 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2991 return nullptr;
2992
2993 // If there are only 2 instructions in the block, at this point,
2994 // this is the call to free and unconditional.
2995 // If there are more than 2 instructions, check that they are noops
2996 // i.e., they won't hurt the performance of the generated code.
2997 if (FreeInstrBB->size() != 2) {
2998 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
2999 if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
3000 continue;
3001 auto *Cast = dyn_cast<CastInst>(&Inst);
3002 if (!Cast || !Cast->isNoopCast(DL))
3003 return nullptr;
3004 }
3005 }
3006 // Validate the rest of constraint #1 by matching on the pred branch.
3007 Instruction *TI = PredBB->getTerminator();
3008 BasicBlock *TrueBB, *FalseBB;
3010 if (!match(TI, m_Br(m_ICmp(Pred,
3012 m_Specific(Op->stripPointerCasts())),
3013 m_Zero()),
3014 TrueBB, FalseBB)))
3015 return nullptr;
3016 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
3017 return nullptr;
3018
3019 // Validate constraint #3: Ensure the null case just falls through.
3020 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
3021 return nullptr;
3022 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
3023 "Broken CFG: missing edge from predecessor to successor");
3024
3025 // At this point, we know that everything in FreeInstrBB can be moved
3026 // before TI.
3027 for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {
3028 if (&Instr == FreeInstrBBTerminator)
3029 break;
3030 Instr.moveBefore(TI);
3031 }
3032 assert(FreeInstrBB->size() == 1 &&
3033 "Only the branch instruction should remain");
3034
3035 // Now that we've moved the call to free before the NULL check, we have to
3036 // remove any attributes on its parameter that imply it's non-null, because
3037 // those attributes might have only been valid because of the NULL check, and
3038 // we can get miscompiles if we keep them. This is conservative if non-null is
3039 // also implied by something other than the NULL check, but it's guaranteed to
3040 // be correct, and the conservativeness won't matter in practice, since the
3041 // attributes are irrelevant for the call to free itself and the pointer
3042 // shouldn't be used after the call.
3043 AttributeList Attrs = FI.getAttributes();
3044 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);
3045 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
3046 if (Dereferenceable.isValid()) {
3047 uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
3048 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,
3049 Attribute::Dereferenceable);
3050 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);
3051 }
3052 FI.setAttributes(Attrs);
3053
3054 return &FI;
3055}
3056
3058 // free undef -> unreachable.
3059 if (isa<UndefValue>(Op)) {
3060 // Leave a marker since we can't modify the CFG here.
3062 return eraseInstFromFunction(FI);
3063 }
3064
3065 // If we have 'free null' delete the instruction. This can happen in stl code
3066 // when lots of inlining happens.
3067 if (isa<ConstantPointerNull>(Op))
3068 return eraseInstFromFunction(FI);
3069
3070 // If we had free(realloc(...)) with no intervening uses, then eliminate the
3071 // realloc() entirely.
3072 CallInst *CI = dyn_cast<CallInst>(Op);
3073 if (CI && CI->hasOneUse())
3074 if (Value *ReallocatedOp = getReallocatedOperand(CI))
3075 return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));
3076
3077 // If we optimize for code size, try to move the call to free before the null
3078 // test so that simplify cfg can remove the empty block and dead code
3079 // elimination the branch. I.e., helps to turn something like:
3080 // if (foo) free(foo);
3081 // into
3082 // free(foo);
3083 //
3084 // Note that we can only do this for 'free' and not for any flavor of
3085 // 'operator delete'; there is no 'operator delete' symbol for which we are
3086 // permitted to invent a call, even if we're passing in a null pointer.
3087 if (MinimizeSize) {
3088 LibFunc Func;
3089 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)
3091 return I;
3092 }
3093
3094 return nullptr;
3095}
3096
3097static bool isMustTailCall(Value *V) {
3098 if (auto *CI = dyn_cast<CallInst>(V))
3099 return CI->isMustTailCall();
3100 return false;
3101}
3102
3104 if (RI.getNumOperands() == 0) // ret void
3105 return nullptr;
3106
3107 Value *ResultOp = RI.getOperand(0);
3108 Type *VTy = ResultOp->getType();
3109 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp))
3110 return nullptr;
3111
3112 // Don't replace result of musttail calls.
3113 if (isMustTailCall(ResultOp))
3114 return nullptr;
3115
3116 // There might be assume intrinsics dominating this return that completely
3117 // determine the value. If so, constant fold it.
3118 KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
3119 if (Known.isConstant())
3120 return replaceOperand(RI, 0,
3122
3123 return nullptr;
3124}
3125
3126// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
3128 // Try to remove the previous instruction if it must lead to unreachable.
3129 // This includes instructions like stores and "llvm.assume" that may not get
3130 // removed by simple dead code elimination.
3131 while (Instruction *Prev = I.getPrevNonDebugInstruction()) {
3132 // While we theoretically can erase EH, that would result in a block that
3133 // used to start with an EH no longer starting with EH, which is invalid.
3134 // To make it valid, we'd need to fixup predecessors to no longer refer to
3135 // this block, but that changes CFG, which is not allowed in InstCombine.
3136 if (Prev->isEHPad())
3137 return nullptr; // Can not drop any more instructions. We're done here.
3138
3140 return nullptr; // Can not drop any more instructions. We're done here.
3141 // Otherwise, this instruction can be freely erased,
3142 // even if it is not side-effect free.
3143
3144 // A value may still have uses before we process it here (for example, in
3145 // another unreachable block), so convert those to poison.
3146 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
3147 eraseInstFromFunction(*Prev);
3148 }
3149 assert(I.getParent()->sizeWithoutDebug() == 1 && "The block is now empty.");
3150 // FIXME: recurse into unconditional predecessors?
3151 return nullptr;
3152}
3153
3155 assert(BI.isUnconditional() && "Only for unconditional branches.");
3156
3157 // If this store is the second-to-last instruction in the basic block
3158 // (excluding debug info and bitcasts of pointers) and if the block ends with
3159 // an unconditional branch, try to move the store to the successor block.
3160
3161 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
3162 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {
3163 return BBI->isDebugOrPseudoInst() ||
3164 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());
3165 };
3166
3167 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
3168 do {
3169 if (BBI != FirstInstr)
3170 --BBI;
3171 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));
3172
3173 return dyn_cast<StoreInst>(BBI);
3174 };
3175
3176 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
3178 return &BI;
3179
3180 return nullptr;
3181}
3182
3184 if (BI.isUnconditional())
3186
3187 // Change br (not X), label True, label False to: br X, label False, True
3188 Value *Cond = BI.getCondition();
3189 Value *X;
3190 if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {
3191 // Swap Destinations and condition...
3192 BI.swapSuccessors();
3193 return replaceOperand(BI, 0, X);
3194 }
3195
3196 // Canonicalize logical-and-with-invert as logical-or-with-invert.
3197 // This is done by inverting the condition and swapping successors:
3198 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
3199 Value *Y;
3200 if (isa<SelectInst>(Cond) &&
3201 match(Cond,
3203 Value *NotX = Builder.CreateNot(X, "not." + X->getName());
3204 Value *Or = Builder.CreateLogicalOr(NotX, Y);
3205 BI.swapSuccessors();
3206 return replaceOperand(BI, 0, Or);
3207 }
3208
3209 // If the condition is irrelevant, remove the use so that other
3210 // transforms on the condition become more effective.
3211 if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))
3212 return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));
3213
3214 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
3215 CmpInst::Predicate Pred;
3216 if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&
3217 !isCanonicalPredicate(Pred)) {
3218 // Swap destinations and condition.
3219 auto *Cmp = cast<CmpInst>(Cond);
3220 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
3221 BI.swapSuccessors();
3222 Worklist.push(Cmp);
3223 return &BI;
3224 }
3225
3226 return nullptr;
3227}
3228
3230 Value *Cond = SI.getCondition();
3231 Value *Op0;
3232 ConstantInt *AddRHS;
3233 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
3234 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
3235 for (auto Case : SI.cases()) {
3236 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
3237 assert(isa<ConstantInt>(NewCase) &&
3238 "Result of expression should be constant");
3239 Case.setValue(cast<ConstantInt>(NewCase));
3240 }
3241 return replaceOperand(SI, 0, Op0);
3242 }
3243
3244 KnownBits Known = computeKnownBits(Cond, 0, &SI);
3245 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
3246 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
3247
3248 // Compute the number of leading bits we can ignore.
3249 // TODO: A better way to determine this would use ComputeNumSignBits().
3250 for (const auto &C : SI.cases()) {
3251 LeadingKnownZeros =
3252 std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());
3253 LeadingKnownOnes =
3254 std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());
3255 }
3256
3257 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
3258
3259 // Shrink the condition operand if the new type is smaller than the old type.
3260 // But do not shrink to a non-standard type, because backend can't generate
3261 // good code for that yet.
3262 // TODO: We can make it aggressive again after fixing PR39569.
3263 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
3264 shouldChangeType(Known.getBitWidth(), NewWidth)) {
3265 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
3267 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
3268
3269 for (auto Case : SI.cases()) {
3270 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
3271 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
3272 }
3273 return replaceOperand(SI, 0, NewCond);
3274 }
3275
3276 return nullptr;
3277}
3278
3280InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
3281 auto *WO = dyn_cast<WithOverflowInst>(EV.getAggregateOperand());
3282 if (!WO)
3283 return nullptr;
3284
3285 Intrinsic::ID OvID = WO->getIntrinsicID();
3286 const APInt *C = nullptr;
3287 if (match(WO->getRHS(), m_APIntAllowUndef(C))) {
3288 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
3289 OvID == Intrinsic::umul_with_overflow)) {
3290 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
3291 if (C->isAllOnes())
3292 return BinaryOperator::CreateNeg(WO->getLHS());
3293 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
3294 if (C->isPowerOf2()) {
3295 return BinaryOperator::CreateShl(
3296 WO->getLHS(),
3297 ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));
3298 }
3299 }
3300 }
3301
3302 // We're extracting from an overflow intrinsic. See if we're the only user.
3303 // That allows us to simplify multiple result intrinsics to simpler things
3304 // that just get one value.
3305 if (!WO->hasOneUse())
3306 return nullptr;
3307
3308 // Check if we're grabbing only the result of a 'with overflow' intrinsic
3309 // and replace it with a traditional binary instruction.
3310 if (*EV.idx_begin() == 0) {
3311 Instruction::BinaryOps BinOp = WO->getBinaryOp();
3312 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
3313 // Replace the old instruction's uses with poison.
3314 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
3316 return BinaryOperator::Create(BinOp, LHS, RHS);
3317 }
3318
3319 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
3320
3321 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
3322 if (OvID == Intrinsic::usub_with_overflow)
3323 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
3324
3325 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
3326 // +1 is not possible because we assume signed values.
3327 if (OvID == Intrinsic::smul_with_overflow &&
3328 WO->getLHS()->getType()->isIntOrIntVectorTy(1))
3329 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
3330
3331 // If only the overflow result is used, and the right hand side is a
3332 // constant (or constant splat), we can remove the intrinsic by directly
3333 // checking for overflow.
3334 if (C) {
3335 // Compute the no-wrap range for LHS given RHS=C, then construct an
3336 // equivalent icmp, potentially using an offset.
3338 WO->getBinaryOp(), *C, WO->getNoWrapKind());
3339
3340 CmpInst::Predicate Pred;
3341 APInt NewRHSC, Offset;
3342 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
3343 auto *OpTy = WO->getRHS()->getType();
3344 auto *NewLHS = WO->getLHS();
3345 if (Offset != 0)
3346 NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));
3347 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
3348 ConstantInt::get(OpTy, NewRHSC));
3349 }
3350
3351 return nullptr;
3352}
3353
3355 Value *Agg = EV.getAggregateOperand();
3356
3357 if (!EV.hasIndices())
3358 return replaceInstUsesWith(EV, Agg);
3359
3360 if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),
3361 SQ.getWithInstruction(&EV)))
3362 return replaceInstUsesWith(EV, V);
3363
3364 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3365 // We're extracting from an insertvalue instruction, compare the indices
3366 const unsigned *exti, *exte, *insi, *inse;
3367 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3368 exte = EV.idx_end(), inse = IV->idx_end();
3369 exti != exte && insi != inse;
3370 ++exti, ++insi) {
3371 if (*insi != *exti)
3372 // The insert and extract both reference distinctly different elements.
3373 // This means the extract is not influenced by the insert, and we can
3374 // replace the aggregate operand of the extract with the aggregate
3375 // operand of the insert. i.e., replace
3376 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3377 // %E = extractvalue { i32, { i32 } } %I, 0
3378 // with
3379 // %E = extractvalue { i32, { i32 } } %A, 0
3380 return ExtractValueInst::Create(IV->getAggregateOperand(),
3381 EV.getIndices());
3382 }
3383 if (exti == exte && insi == inse)
3384 // Both iterators are at the end: Index lists are identical. Replace
3385 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3386 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3387 // with "i32 42"
3388 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
3389 if (exti == exte) {
3390 // The extract list is a prefix of the insert list. i.e. replace
3391 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3392 // %E = extractvalue { i32, { i32 } } %I, 1
3393 // with
3394 // %X = extractvalue { i32, { i32 } } %A, 1
3395 // %E = insertvalue { i32 } %X, i32 42, 0
3396 // by switching the order of the insert and extract (though the
3397 // insertvalue should be left in, since it may have other uses).
3398 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
3399 EV.getIndices());
3400 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3401 ArrayRef(insi, inse));
3402 }
3403 if (insi == inse)
3404 // The insert list is a prefix of the extract list
3405 // We can simply remove the common indices from the extract and make it
3406 // operate on the inserted value instead of the insertvalue result.
3407 // i.e., replace
3408 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3409 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3410 // with
3411 // %E extractvalue { i32 } { i32 42 }, 0
3412 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
3413 ArrayRef(exti, exte));
3414 }
3415
3416 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
3417 return R;
3418
3419 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {
3420 // If the (non-volatile) load only has one use, we can rewrite this to a
3421 // load from a GEP. This reduces the size of the load. If a load is used
3422 // only by extractvalue instructions then this either must have been
3423 // optimized before, or it is a struct with padding, in which case we
3424 // don't want to do the transformation as it loses padding knowledge.
3425 if (L->isSimple() && L->hasOneUse()) {
3426 // extractvalue has integer indices, getelementptr has Value*s. Convert.
3427 SmallVector<Value*, 4> Indices;
3428 // Prefix an i32 0 since we need the first element.
3429 Indices.push_back(Builder.getInt32(0));
3430 for (unsigned Idx : EV.indices())
3431 Indices.push_back(Builder.getInt32(Idx));
3432
3433 // We need to insert these at the location of the old load, not at that of
3434 // the extractvalue.
3436 Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
3437 L->getPointerOperand(), Indices);
3439 // Whatever aliasing information we had for the orignal load must also
3440 // hold for the smaller load, so propagate the annotations.
3441 NL->setAAMetadata(L->getAAMetadata());
3442 // Returning the load directly will cause the main loop to insert it in
3443 // the wrong spot, so use replaceInstUsesWith().
3444 return replaceInstUsesWith(EV, NL);
3445 }
3446 }
3447
3448 if (auto *PN = dyn_cast<PHINode>(Agg))
3449 if (Instruction *Res = foldOpIntoPhi(EV, PN))
3450 return Res;
3451
3452 // We could simplify extracts from other values. Note that nested extracts may
3453 // already be simplified implicitly by the above: extract (extract (insert) )
3454 // will be translated into extract ( insert ( extract ) ) first and then just
3455 // the value inserted, if appropriate. Similarly for extracts from single-use
3456 // loads: extract (extract (load)) will be translated to extract (load (gep))
3457 // and if again single-use then via load (gep (gep)) to load (gep).
3458 // However, double extracts from e.g. function arguments or return values
3459 // aren't handled yet.
3460 return nullptr;
3461}
3462
3463/// Return 'true' if the given typeinfo will match anything.
3464static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
3465 switch (Personality) {
3469 // The GCC C EH and Rust personality only exists to support cleanups, so
3470 // it's not clear what the semantics of catch clauses are.
3471 return false;
3473 return false;
3475 // While __gnat_all_others_value will match any Ada exception, it doesn't
3476 // match foreign exceptions (or didn't, before gcc-4.7).
3477 return false;
3487 return TypeInfo->isNullValue();
3488 }
3489 llvm_unreachable("invalid enum");
3490}
3491
3492static bool shorter_filter(const Value *LHS, const Value *RHS) {
3493 return
3494 cast<ArrayType>(LHS->getType())->getNumElements()
3495 <
3496 cast<ArrayType>(RHS->getType())->getNumElements();
3497}
3498
3500 // The logic here should be correct for any real-world personality function.
3501 // However if that turns out not to be true, the offending logic can always
3502 // be conditioned on the personality function, like the catch-all logic is.
3503 EHPersonality Personality =
3504 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
3505
3506 // Simplify the list of clauses, eg by removing repeated catch clauses
3507 // (these are often created by inlining).
3508 bool MakeNewInstruction = false; // If true, recreate using the following:
3509 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
3510 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
3511
3512 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
3513 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
3514 bool isLastClause = i + 1 == e;
3515 if (LI.isCatch(i)) {
3516 // A catch clause.
3517 Constant *CatchClause = LI.getClause(i);
3518 Constant *TypeInfo = CatchClause->stripPointerCasts();
3519
3520 // If we already saw this clause, there is no point in having a second
3521 // copy of it.
3522 if (AlreadyCaught.insert(TypeInfo).second) {
3523 // This catch clause was not already seen.
3524 NewClauses.push_back(CatchClause);
3525 } else {
3526 // Repeated catch clause - drop the redundant copy.
3527 MakeNewInstruction = true;
3528 }
3529
3530 // If this is a catch-all then there is no point in keeping any following
3531 // clauses or marking the landingpad as having a cleanup.
3532 if (isCatchAll(Personality, TypeInfo)) {
3533 if (!isLastClause)
3534 MakeNewInstruction = true;
3535 CleanupFlag = false;
3536 break;
3537 }
3538 } else {
3539 // A filter clause. If any of the filter elements were already caught
3540 // then they can be dropped from the filter. It is tempting to try to
3541 // exploit the filter further by saying that any typeinfo that does not
3542 // occur in the filter can't be caught later (and thus can be dropped).
3543 // However this would be wrong, since typeinfos can match without being
3544 // equal (for example if one represents a C++ class, and the other some
3545 // class derived from it).
3546 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
3547 Constant *FilterClause = LI.getClause(i);
3548 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3549 unsigned NumTypeInfos = FilterType->getNumElements();
3550
3551 // An empty filter catches everything, so there is no point in keeping any
3552 // following clauses or marking the landingpad as having a cleanup. By
3553 // dealing with this case here the following code is made a bit simpler.
3554 if (!NumTypeInfos) {
3555 NewClauses.push_back(FilterClause);
3556 if (!isLastClause)
3557 MakeNewInstruction = true;
3558 CleanupFlag = false;
3559 break;
3560 }
3561
3562 bool MakeNewFilter = false; // If true, make a new filter.
3563 SmallVector<Constant *, 16> NewFilterElts; // New elements.
3564 if (isa<ConstantAggregateZero>(FilterClause)) {
3565 // Not an empty filter - it contains at least one null typeinfo.
3566 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
3567 Constant *TypeInfo =
3569 // If this typeinfo is a catch-all then the filter can never match.
3570 if (isCatchAll(Personality, TypeInfo)) {
3571 // Throw the filter away.
3572 MakeNewInstruction = true;
3573 continue;
3574 }
3575
3576 // There is no point in having multiple copies of this typeinfo, so
3577 // discard all but the first copy if there is more than one.
3578 NewFilterElts.push_back(TypeInfo);
3579 if (NumTypeInfos > 1)
3580 MakeNewFilter = true;
3581 } else {
3582 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3583 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3584 NewFilterElts.reserve(NumTypeInfos);
3585
3586 // Remove any filter elements that were already caught or that already
3587 // occurred in the filter. While there, see if any of the elements are
3588 // catch-alls. If so, the filter can be discarded.
3589 bool SawCatchAll = false;
3590 for (unsigned j = 0; j != NumTypeInfos; ++j) {
3591 Constant *Elt = Filter->getOperand(j);
3592 Constant *TypeInfo = Elt->stripPointerCasts();
3593 if (isCatchAll(Personality, TypeInfo)) {
3594 // This element is a catch-all. Bail out, noting this fact.
3595 SawCatchAll = true;
3596 break;
3597 }
3598
3599 // Even if we've seen a type in a catch clause, we don't want to
3600 // remove it from the filter. An unexpected type handler may be
3601 // set up for a call site which throws an exception of the same
3602 // type caught. In order for the exception thrown by the unexpected
3603 // handler to propagate correctly, the filter must be correctly
3604 // described for the call site.
3605 //
3606 // Example:
3607 //
3608 // void unexpected() { throw 1;}
3609 // void foo() throw (int) {
3610 // std::set_unexpected(unexpected);
3611 // try {
3612 // throw 2.0;
3613 // } catch (int i) {}
3614 // }
3615
3616 // There is no point in having multiple copies of the same typeinfo in
3617 // a filter, so only add it if we didn't already.
3618 if (SeenInFilter.insert(TypeInfo).second)
3619 NewFilterElts.push_back(cast<Constant>(Elt));
3620 }
3621 // A filter containing a catch-all cannot match anything by definition.
3622 if (SawCatchAll) {
3623 // Throw the filter away.
3624 MakeNewInstruction = true;
3625 continue;
3626 }
3627
3628 // If we dropped something from the filter, make a new one.
3629 if (NewFilterElts.size() < NumTypeInfos)
3630 MakeNewFilter = true;
3631 }
3632 if (MakeNewFilter) {
3633 FilterType = ArrayType::get(FilterType->getElementType(),
3634 NewFilterElts.size());
3635 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3636 MakeNewInstruction = true;
3637 }
3638
3639 NewClauses.push_back(FilterClause);
3640
3641 // If the new filter is empty then it will catch everything so there is
3642 // no point in keeping any following clauses or marking the landingpad
3643 // as having a cleanup. The case of the original filter being empty was
3644 // already handled above.
3645 if (MakeNewFilter && !NewFilterElts.size()) {
3646 assert(MakeNewInstruction && "New filter but not a new instruction!");
3647 CleanupFlag = false;
3648 break;
3649 }
3650 }
3651 }
3652
3653 // If several filters occur in a row then reorder them so that the shortest
3654 // filters come first (those with the smallest number of elements). This is
3655 // advantageous because shorter filters are more likely to match, speeding up
3656 // unwinding, but mostly because it increases the effectiveness of the other
3657 // filter optimizations below.
3658 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3659 unsigned j;
3660 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3661 for (j = i; j != e; ++j)
3662 if (!isa<ArrayType>(NewClauses[j]->getType()))
3663 break;
3664
3665 // Check whether the filters are already sorted by length. We need to know
3666 // if sorting them is actually going to do anything so that we only make a
3667 // new landingpad instruction if it does.
3668 for (unsigned k = i; k + 1 < j; ++k)
3669 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3670 // Not sorted, so sort the filters now. Doing an unstable sort would be
3671 // correct too but reordering filters pointlessly might confuse users.
3672 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3674 MakeNewInstruction = true;
3675 break;
3676 }
3677
3678 // Look for the next batch of filters.
3679 i = j + 1;
3680 }
3681
3682 // If typeinfos matched if and only if equal, then the elements of a filter L
3683 // that occurs later than a filter F could be replaced by the intersection of
3684 // the elements of F and L. In reality two typeinfos can match without being
3685 // equal (for example if one represents a C++ class, and the other some class
3686 // derived from it) so it would be wrong to perform this transform in general.
3687 // However the transform is correct and useful if F is a subset of L. In that
3688 // case L can be replaced by F, and thus removed altogether since repeating a
3689 // filter is pointless. So here we look at all pairs of filters F and L where
3690 // L follows F in the list of clauses, and remove L if every element of F is
3691 // an element of L. This can occur when inlining C++ functions with exception
3692 // specifications.
3693 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3694 // Examine each filter in turn.
3695 Value *Filter = NewClauses[i];
3696 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3697 if (!FTy)
3698 // Not a filter - skip it.
3699 continue;
3700 unsigned FElts = FTy->getNumElements();
3701 // Examine each filter following this one. Doing this backwards means that
3702 // we don't have to worry about filters disappearing under us when removed.
3703 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3704 Value *LFilter = NewClauses[j];
3705 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3706 if (!LTy)
3707 // Not a filter - skip it.
3708 continue;
3709 // If Filter is a subset of LFilter, i.e. every element of Filter is also
3710 // an element of LFilter, then discard LFilter.
3711 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3712 // If Filter is empty then it is a subset of LFilter.
3713 if (!FElts) {
3714 // Discard LFilter.
3715 NewClauses.erase(J);
3716 MakeNewInstruction = true;
3717 // Move on to the next filter.
3718 continue;
3719 }
3720 unsigned LElts = LTy->getNumElements();
3721 // If Filter is longer than LFilter then it cannot be a subset of it.
3722 if (FElts > LElts)
3723 // Move on to the next filter.
3724 continue;
3725 // At this point we know that LFilter has at least one element.
3726 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3727 // Filter is a subset of LFilter iff Filter contains only zeros (as we
3728 // already know that Filter is not longer than LFilter).
3729 if (isa<ConstantAggregateZero>(Filter)) {
3730 assert(FElts <= LElts && "Should have handled this case earlier!");
3731 // Discard LFilter.
3732 NewClauses.erase(J);
3733 MakeNewInstruction = true;
3734 }
3735 // Move on to the next filter.
3736 continue;
3737 }
3738 ConstantArray *LArray = cast<ConstantArray>(LFilter);
3739 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3740 // Since Filter is non-empty and contains only zeros, it is a subset of
3741 // LFilter iff LFilter contains a zero.
3742 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3743 for (unsigned l = 0; l != LElts; ++l)
3744 if (LArray->getOperand(l)->isNullValue()) {
3745 // LFilter contains a zero - discard it.
3746 NewClauses.erase(J);
3747 MakeNewInstruction = true;
3748 break;
3749 }
3750 // Move on to the next filter.
3751 continue;
3752 }
3753 // At this point we know that both filters are ConstantArrays. Loop over
3754 // operands to see whether every element of Filter is also an element of
3755 // LFilter. Since filters tend to be short this is probably faster than
3756 // using a method that scales nicely.
3757 ConstantArray *FArray = cast<ConstantArray>(Filter);
3758 bool AllFound = true;
3759 for (unsigned f = 0; f != FElts; ++f) {
3760 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3761 AllFound = false;
3762 for (unsigned l = 0; l != LElts; ++l) {
3763 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3764 if (LTypeInfo == FTypeInfo) {
3765 AllFound = true;
3766 break;
3767 }
3768 }
3769 if (!AllFound)
3770 break;
3771 }
3772 if (AllFound) {
3773 // Discard LFilter.
3774 NewClauses.erase(J);
3775 MakeNewInstruction = true;
3776 }
3777 // Move on to the next filter.
3778 }
3779 }
3780
3781 // If we changed any of the clauses, replace the old landingpad instruction
3782 // with a new one.
3783 if (MakeNewInstruction) {
3784 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3785 NewClauses.size());
3786 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3787 NLI->addClause(NewClauses[i]);
3788 // A landing pad with no clauses must have the cleanup flag set. It is
3789 // theoretically possible, though highly unlikely, that we eliminated all
3790 // clauses. If so, force the cleanup flag to true.
3791 if (NewClauses.empty())
3792 CleanupFlag = true;
3793 NLI->setCleanup(CleanupFlag);
3794 return NLI;
3795 }
3796
3797 // Even if none of the clauses changed, we may nonetheless have understood
3798 // that the cleanup flag is pointless. Clear it if so.
3799 if (LI.isCleanup() != CleanupFlag) {
3800 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3801 LI.setCleanup(CleanupFlag);
3802 return &LI;
3803 }
3804
3805 return nullptr;
3806}
3807
3808Value *
3810 // Try to push freeze through instructions that propagate but don't produce
3811 // poison as far as possible. If an operand of freeze follows three
3812 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
3813 // guaranteed-non-poison operands then push the freeze through to the one
3814 // operand that is not guaranteed non-poison. The actual transform is as
3815 // follows.
3816 // Op1 = ... ; Op1 can be posion
3817 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
3818 // ; single guaranteed-non-poison operands
3819 // ... = Freeze(Op0)
3820 // =>
3821 // Op1 = ...
3822 // Op1.fr = Freeze(Op1)
3823 // ... = Inst(Op1.fr, NonPoisonOps...)
3824 auto *OrigOp = OrigFI.getOperand(0);
3825 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
3826
3827 // While we could change the other users of OrigOp to use freeze(OrigOp), that
3828 // potentially reduces their optimization potential, so let's only do this iff
3829 // the OrigOp is only used by the freeze.
3830 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))
3831 return nullptr;
3832
3833 // We can't push the freeze through an instruction which can itself create
3834 // poison. If the only source of new poison is flags, we can simply
3835 // strip them (since we know the only use is the freeze and nothing can
3836 // benefit from them.)
3837 if (canCreateUndefOrPoison(cast<Operator>(OrigOp),
3838 /*ConsiderFlagsAndMetadata*/ false))
3839 return nullptr;
3840
3841 // If operand is guaranteed not to be poison, there is no need to add freeze
3842 // to the operand. So we first find the operand that is not guaranteed to be
3843 // poison.
3844 Use *MaybePoisonOperand = nullptr;
3845 for (Use &U : OrigOpInst->operands()) {
3846 if (isa<MetadataAsValue>(U.get()) ||
3848 continue;
3849 if (!MaybePoisonOperand)
3850 MaybePoisonOperand = &U;
3851 else
3852 return nullptr;
3853 }
3854
3855 OrigOpInst->dropPoisonGeneratingFlagsAndMetadata();
3856
3857 // If all operands are guaranteed to be non-poison, we can drop freeze.
3858 if (!MaybePoisonOperand)
3859 return OrigOp;
3860
3861 Builder.SetInsertPoint(OrigOpInst);
3862 auto *FrozenMaybePoisonOperand = Builder.CreateFreeze(
3863 MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr");
3864
3865 replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand);
3866 return OrigOp;
3867}
3868
3870 PHINode *PN) {
3871 // Detect whether this is a recurrence with a start value and some number of
3872 // backedge values. We'll check whether we can push the freeze through the
3873 // backedge values (possibly dropping poison flags along the way) until we
3874 // reach the phi again. In that case, we can move the freeze to the start
3875 // value.
3876 Use *StartU = nullptr;
3878 for (Use &U : PN->incoming_values()) {
3879 if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {
3880 // Add backedge value to worklist.
3881 Worklist.push_back(U.get());
3882 continue;
3883 }
3884
3885 // Don't bother handling multiple start values.
3886 if (StartU)
3887 return nullptr;
3888 StartU = &U;
3889 }
3890
3891 if (!StartU || Worklist.empty())
3892 return nullptr; // Not a recurrence.
3893
3894 Value *StartV = StartU->get();
3895 BasicBlock *StartBB = PN->getIncomingBlock(*StartU);
3896 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);
3897 // We can't insert freeze if the the start value is the result of the
3898 // terminator (e.g. an invoke).
3899 if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
3900 return nullptr;
3901
3904 while (!Worklist.empty()) {
3905 Value *V = Worklist.pop_back_val();
3906 if (!Visited.insert(V).second)
3907 continue;
3908
3909 if (Visited.size() > 32)
3910 return nullptr; // Limit the total number of values we inspect.
3911
3912 // Assume that PN is non-poison, because it will be after the transform.
3913 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
3914 continue;
3915
3916 Instruction *I = dyn_cast<Instruction>(V);
3917 if (!I || canCreateUndefOrPoison(cast<Operator>(I),
3918 /*ConsiderFlagsAndMetadata*/ false))
3919 return nullptr;
3920
3921 DropFlags.push_back(I);
3922 append_range(Worklist, I->operands());
3923 }
3924
3925 for (Instruction *I : DropFlags)
3926 I->dropPoisonGeneratingFlagsAndMetadata();
3927
3928 if (StartNeedsFreeze) {
3930 Value *FrozenStartV = Builder.CreateFreeze(StartV,
3931 StartV->getName() + ".fr");
3932 replaceUse(*StartU, FrozenStartV);
3933 }
3934 return replaceInstUsesWith(FI, PN);
3935}
3936
3938 Value *Op = FI.getOperand(0);
3939
3940 if (isa<Constant>(Op) || Op->hasOneUse())
3941 return false;
3942
3943 // Move the freeze directly after the definition of its operand, so that
3944 // it dominates the maximum number of uses. Note that it may not dominate
3945 // *all* uses if the operand is an invoke/callbr and the use is in a phi on
3946 // the normal/default destination. This is why the domination check in the
3947 // replacement below is still necessary.
3948 Instruction *MoveBefore;
3949 if (isa<Argument>(Op)) {
3950 MoveBefore =
3952 } else {
3953 MoveBefore = cast<Instruction>(Op)->getInsertionPointAfterDef();
3954 if (!MoveBefore)
3955 return false;
3956 }
3957
3958 bool Changed = false;
3959 if (&FI != MoveBefore) {
3960 FI.moveBefore(MoveBefore);
3961 Changed = true;
3962 }
3963
3964 Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {
3965 bool Dominates = DT.dominates(&FI, U);
3966 Changed |= Dominates;
3967 return Dominates;
3968 });
3969
3970 return Changed;
3971}
3972
3973// Check if any direct or bitcast user of this value is a shuffle instruction.
3975 for (auto *U : V->users()) {
3976 if (isa<ShuffleVectorInst>(U))
3977 return true;
3978 else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U))
3979 return true;
3980 }
3981 return false;
3982}
3983
3985 Value *Op0 = I.getOperand(0);
3986
3988 return replaceInstUsesWith(I, V);
3989
3990 // freeze (phi const, x) --> phi const, (freeze x)
3991 if (auto *PN = dyn_cast<PHINode>(Op0)) {
3992 if (Instruction *NV = foldOpIntoPhi(I, PN))
3993 return NV;
3994 if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))
3995 return NV;
3996 }
3997
3999 return replaceInstUsesWith(I, NI);
4000
4001 // If I is freeze(undef), check its uses and fold it to a fixed constant.
4002 // - or: pick -1
4003 // - select's condition: if the true value is constant, choose it by making
4004 // the condition true.
4005 // - default: pick 0
4006 //
4007 // Note that this transform is intentionally done here rather than
4008 // via an analysis in InstSimplify or at individual user sites. That is
4009 // because we must produce the same value for all uses of the freeze -
4010 // it's the reason "freeze" exists!
4011 //
4012 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
4013 // duplicating logic for binops at least.
4014 auto getUndefReplacement = [&I](Type *Ty) {
4015 Constant *BestValue = nullptr;
4016 Constant *NullValue = Constant::getNullValue(Ty);
4017 for (const auto *U : I.users()) {
4018 Constant *C = NullValue;
4019 if (match(U, m_Or(m_Value(), m_Value())))
4021 else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))
4022 C = ConstantInt::getTrue(Ty);
4023
4024 if (!BestValue)
4025 BestValue = C;
4026 else if (BestValue != C)
4027 BestValue = NullValue;
4028 }
4029 assert(BestValue && "Must have at least one use");
4030 return BestValue;
4031 };
4032
4033 if (match(Op0, m_Undef())) {
4034 // Don't fold freeze(undef/poison) if it's used as a vector operand in
4035 // a shuffle. This may improve codegen for shuffles that allow
4036 // unspecified inputs.
4038 return nullptr;
4039 return replaceInstUsesWith(I, getUndefReplacement(I.getType()));
4040 }
4041
4042 Constant *C;
4043 if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement()) {
4044 Constant *ReplaceC = getUndefReplacement(I.getType()->getScalarType());
4046 }
4047
4048 // Replace uses of Op with freeze(Op).
4049 if (freezeOtherUses(I))
4050 return &I;
4051
4052 return nullptr;
4053}
4054
4055/// Check for case where the call writes to an otherwise dead alloca. This
4056/// shows up for unused out-params in idiomatic C/C++ code. Note that this
4057/// helper *only* analyzes the write; doesn't check any other legality aspect.
4059 auto *CB = dyn_cast<CallBase>(I);
4060 if (!CB)
4061 // TODO: handle e.g. store to alloca here - only worth doing if we extend
4062 // to allow reload along used path as described below. Otherwise, this
4063 // is simply a store to a dead allocation which will be removed.
4064 return false;
4065 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);
4066 if (!Dest)
4067 return false;
4068 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));
4069 if (!AI)
4070 // TODO: allow malloc?
4071 return false;
4072 // TODO: allow memory access dominated by move point? Note that since AI
4073 // could have a reference to itself captured by the call, we would need to
4074 // account for cycles in doing so.
4075 SmallVector<const User *> AllocaUsers;
4077 auto pushUsers = [&](const Instruction &I) {
4078 for (const User *U : I.users()) {
4079 if (Visited.insert(U).second)
4080 AllocaUsers.push_back(U);
4081 }
4082 };
4083 pushUsers(*AI);
4084 while (!AllocaUsers.empty()) {
4085 auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());
4086 if (isa<BitCastInst>(UserI) || isa<GetElementPtrInst>(UserI) ||
4087 isa<AddrSpaceCastInst>(UserI)) {
4088 pushUsers(*UserI);
4089 continue;
4090 }
4091 if (UserI == CB)
4092 continue;
4093 // TODO: support lifetime.start/end here
4094 return false;
4095 }
4096 return true;
4097}
4098
4099/// Try to move the specified instruction from its current block into the
4100/// beginning of DestBlock, which can only happen if it's safe to move the
4101/// instruction past all of the instructions between it and the end of its
4102/// block.
4104 TargetLibraryInfo &TLI) {
4105 BasicBlock *SrcBlock = I->getParent();
4106
4107 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
4108 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
4109 I->isTerminator())
4110 return false;
4111
4112 // Do not sink static or dynamic alloca instructions. Static allocas must
4113 // remain in the entry block, and dynamic allocas must not be sunk in between
4114 // a stacksave / stackrestore pair, which would incorrectly shorten its
4115 // lifetime.
4116 if (isa<AllocaInst>(I))
4117 return false;
4118
4119 // Do not sink into catchswitch blocks.
4120 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
4121 return false;
4122
4123 // Do not sink convergent call instructions.
4124 if (auto *CI = dyn_cast<CallInst>(I)) {
4125 if (CI->isConvergent())
4126 return false;
4127 }
4128
4129 // Unless we can prove that the memory write isn't visibile except on the
4130 // path we're sinking to, we must bail.
4131 if (I->mayWriteToMemory()) {
4132 if (!SoleWriteToDeadLocal(I, TLI))
4133 return false;
4134 }
4135
4136 // We can only sink load instructions if there is nothing between the load and
4137 // the end of block that could change the value.
4138 if (I->mayReadFromMemory()) {
4139 // We don't want to do any sophisticated alias analysis, so we only check
4140 // the instructions after I in I's parent block if we try to sink to its
4141 // successor block.
4142 if (DestBlock->getUniquePredecessor() != I->getParent())
4143 return false;
4144 for (BasicBlock::iterator Scan = std::next(I->getIterator()),
4145 E = I->getParent()->end();
4146 Scan != E; ++Scan)
4147 if (Scan->mayWriteToMemory())
4148 return false;
4149 }
4150
4151 I->dropDroppableUses([DestBlock](const Use *U) {
4152 if (auto *I = dyn_cast<Instruction>(U->getUser()))
4153 return I->getParent() != DestBlock;
4154 return true;
4155 });
4156 /// FIXME: We could remove droppable uses that are not dominated by
4157 /// the new position.
4158
4159 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
4160 I->moveBefore(&*InsertPos);
4161 ++NumSunkInst;
4162
4163 // Also sink all related debug uses from the source basic block. Otherwise we
4164 // get debug use before the def. Attempt to salvage debug uses first, to
4165 // maximise the range variables have location for. If we cannot salvage, then
4166 // mark the location undef: we know it was supposed to receive a new location
4167 // here, but that computation has been sunk.
4169 findDbgUsers(DbgUsers, I);
4170 // Process the sinking DbgUsers in reverse order, as we only want to clone the
4171 // last appearing debug intrinsic for each given variable.
4173 for (DbgVariableIntrinsic *DVI : DbgUsers)
4174 if (DVI->getParent() == SrcBlock)
4175 DbgUsersToSink.push_back(DVI);
4176 llvm::sort(DbgUsersToSink,
4177 [](auto *A, auto *B) { return B->comesBefore(A); });
4178
4180 SmallSet<DebugVariable, 4> SunkVariables;
4181 for (auto *User : DbgUsersToSink) {
4182 // A dbg.declare instruction should not be cloned, since there can only be
4183 // one per variable fragment. It should be left in the original place
4184 // because the sunk instruction is not an alloca (otherwise we could not be
4185 // here).
4186 if (isa<DbgDeclareInst>(User))
4187 continue;
4188
4189 DebugVariable DbgUserVariable =
4190 DebugVariable(User->getVariable(), User->getExpression(),
4191 User->getDebugLoc()->getInlinedAt());
4192
4193 if (!SunkVariables.insert(DbgUserVariable).second)
4194 continue;
4195
4196 // Leave dbg.assign intrinsics in their original positions and there should
4197 // be no need to insert a clone.
4198 if (isa<DbgAssignIntrinsic>(User))
4199 continue;
4200
4201 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));
4202 if (isa<DbgDeclareInst>(User) && isa<CastInst>(I))
4203 DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0));
4204 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n');
4205 }
4206
4207 // Perform salvaging without the clones, then sink the clones.
4208 if (!DIIClones.empty()) {
4209 salvageDebugInfoForDbgValues(*I, DbgUsers);
4210 // The clones are in reverse order of original appearance, reverse again to
4211 // maintain the original order.
4212 for (auto &DIIClone : llvm::reverse(DIIClones)) {
4213 DIIClone->insertBefore(&*InsertPos);
4214 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n');
4215 }
4216 }
4217
4218 return true;
4219}
4220
4222 while (!Worklist.isEmpty()) {
4223 // Walk deferred instructions in reverse order, and push them to the
4224 // worklist, which means they'll end up popped from the worklist in-order.
4225 while (Instruction *I = Worklist.popDeferred()) {
4226 // Check to see if we can DCE the instruction. We do this already here to
4227 // reduce the number of uses and thus allow other folds to trigger.
4228 // Note that eraseInstFromFunction() may push additional instructions on
4229 // the deferred worklist, so this will DCE whole instruction chains.
4232 ++NumDeadInst;
4233 continue;
4234 }
4235
4236 Worklist.push(I);
4237 }
4238
4240 if (I == nullptr) continue; // skip null values.
4241
4242 // Check to see if we can DCE the instruction.
4245 ++NumDeadInst;
4246 continue;
4247 }
4248
4249 if (!DebugCounter::shouldExecute(VisitCounter))
4250 continue;
4251
4252 // See if we can trivially sink this instruction to its user if we can
4253 // prove that the successor is not executed more frequently than our block.
4254 // Return the UserBlock if successful.
4255 auto getOptionalSinkBlockForInst =
4256 [this](Instruction *I) -> std::optional<BasicBlock *> {
4257 if (!EnableCodeSinking)
4258 return std::nullopt;
4259
4260 BasicBlock *BB = I->getParent();
4261 BasicBlock *UserParent = nullptr;
4262 unsigned NumUsers = 0;
4263
4264 for (auto *U : I->users()) {
4265 if (U->isDroppable())
4266 continue;
4267 if (NumUsers > MaxSinkNumUsers)
4268 return std::nullopt;
4269
4270 Instruction *UserInst = cast<Instruction>(U);
4271 // Special handling for Phi nodes - get the block the use occurs in.
4272 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) {
4273 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
4274 if (PN->getIncomingValue(i) == I) {
4275 // Bail out if we have uses in different blocks. We don't do any
4276 // sophisticated analysis (i.e finding NearestCommonDominator of
4277 // these use blocks).
4278 if (UserParent && UserParent != PN->getIncomingBlock(i))
4279 return std::nullopt;
4280 UserParent = PN->getIncomingBlock(i);
4281 }
4282 }
4283 assert(UserParent && "expected to find user block!");
4284 } else {
4285 if (UserParent && UserParent != UserInst->getParent())
4286 return std::nullopt;
4287 UserParent = UserInst->getParent();
4288 }
4289
4290 // Make sure these checks are done only once, naturally we do the checks
4291 // the first time we get the userparent, this will save compile time.
4292 if (NumUsers == 0) {
4293 // Try sinking to another block. If that block is unreachable, then do
4294 // not bother. SimplifyCFG should handle it.
4295 if (UserParent == BB || !DT.isReachableFromEntry(UserParent))
4296 return std::nullopt;
4297
4298 auto *Term = UserParent->getTerminator();
4299 // See if the user is one of our successors that has only one
4300 // predecessor, so that we don't have to split the critical edge.
4301 // Another option where we can sink is a block that ends with a
4302 // terminator that does not pass control to other block (such as
4303 // return or unreachable or resume). In this case:
4304 // - I dominates the User (by SSA form);
4305 // - the User will be executed at most once.
4306 // So sinking I down to User is always profitable or neutral.
4307 if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term))
4308 return std::nullopt;
4309
4310 assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");
4311 }
4312
4313 NumUsers++;
4314 }
4315
4316 // No user or only has droppable users.
4317 if (!UserParent)
4318 return std::nullopt;
4319
4320 return UserParent;
4321 };
4322
4323 auto OptBB = getOptionalSinkBlockForInst(I);
4324 if (OptBB) {
4325 auto *UserParent = *OptBB;
4326 // Okay, the CFG is simple enough, try to sink this instruction.
4327 if (TryToSinkInstruction(I, UserParent, TLI)) {
4328 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
4329 MadeIRChange = true;
4330 // We'll add uses of the sunk instruction below, but since
4331 // sinking can expose opportunities for it's *operands* add
4332 // them to the worklist
4333 for (Use &U : I->operands())
4334 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
4335 Worklist.push(OpI);
4336 }
4337 }
4338
4339 // Now that we have an instruction, try combining it to simplify it.
4342 I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
4343
4344#ifndef NDEBUG
4345 std::string OrigI;
4346#endif
4347 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
4348 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
4349
4350 if (Instruction *Result = visit(*I)) {
4351 ++NumCombined;
4352 // Should we replace the old instruction with a new one?
4353 if (Result != I) {
4354 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
4355 << " New = " << *Result << '\n');
4356
4357 Result->copyMetadata(*I,
4358 {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
4359 // Everything uses the new instruction now.
4360 I->replaceAllUsesWith(Result);
4361
4362 // Move the name to the new instruction first.
4363 Result->takeName(I);
4364
4365 // Insert the new instruction into the basic block...
4366 BasicBlock *InstParent = I->getParent();
4367 BasicBlock::iterator InsertPos = I->getIterator();
4368
4369 // Are we replace a PHI with something that isn't a PHI, or vice versa?
4370 if (isa<PHINode>(Result) != isa<PHINode>(I)) {
4371 // We need to fix up the insertion point.
4372 if (isa<PHINode>(I)) // PHI -> Non-PHI
4373 InsertPos = InstParent->getFirstInsertionPt();
4374 else // Non-PHI -> PHI
4375 InsertPos = InstParent->getFirstNonPHI()->getIterator();
4376 }
4377
4378 Result->insertInto(InstParent, InsertPos);
4379
4380 // Push the new instruction and any users onto the worklist.
4382 Worklist.push(Result);
4383
4385 } else {
4386 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
4387 << " New = " << *I << '\n');
4388
4389 // If the instruction was modified, it's possible that it is now dead.
4390 // if so, remove it.
4393 } else {
4395 Worklist.push(I);
4396 }
4397 }
4398 MadeIRChange = true;
4399 }
4400 }
4401
4402 Worklist.zap();
4403 return MadeIRChange;
4404}
4405
4406// Track the scopes used by !alias.scope and !noalias. In a function, a
4407// @llvm.experimental.noalias.scope.decl is only useful if that scope is used
4408// by both sets. If not, the declaration of the scope can be safely omitted.
4409// The MDNode of the scope can be omitted as well for the instructions that are
4410// part of this function. We do not do that at this point, as this might become
4411// too time consuming to do.
4413 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
4414 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
4415
4416public:
4418 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
4419 if (!I->hasMetadataOtherThanDebugLoc())
4420 return;
4421
4422 auto Track = [](Metadata *ScopeList, auto &Container) {
4423 const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
4424 if (!MDScopeList || !Container.insert(MDScopeList).second)
4425 return;
4426 for (const auto &MDOperand : MDScopeList->operands())
4427 if (auto *MDScope = dyn_cast<MDNode>(MDOperand))
4428 Container.insert(MDScope);
4429 };
4430
4431 Track(I->getMetadata(LLVMContext::MD_alias_scope), UsedAliasScopesAndLists);
4432 Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
4433 }
4434
4436 NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Inst);
4437 if (!Decl)
4438 return false;
4439
4440 assert(Decl->use_empty() &&
4441 "llvm.experimental.noalias.scope.decl in use ?");
4442 const MDNode *MDSL = Decl->getScopeList();
4443 assert(MDSL->getNumOperands() == 1 &&
4444 "llvm.experimental.noalias.scope should refer to a single scope");
4445 auto &MDOperand = MDSL->getOperand(0);
4446 if (auto *MD = dyn_cast<MDNode>(MDOperand))
4447 return !UsedAliasScopesAndLists.contains(MD) ||
4448 !UsedNoAliasScopesAndLists.contains(MD);
4449
4450 // Not an MDNode ? throw away.
4451 return true;
4452 }
4453};
4454
4455/// Populate the IC worklist from a function, by walking it in depth-first
4456/// order and adding all reachable code to the worklist.
4457///
4458/// This has a couple of tricks to make the code faster and more powerful. In
4459/// particular, we constant fold and DCE instructions as we go, to avoid adding
4460/// them to the worklist (this significantly speeds up instcombine on code where
4461/// many instructions are dead or constant). Additionally, if we find a branch
4462/// whose condition is a known constant, we only visit the reachable successors.
4464 const TargetLibraryInfo *TLI,
4465 InstructionWorklist &ICWorklist) {
4466 bool MadeIRChange = false;
4469 Worklist.push_back(&F.front());
4470
4471 SmallVector<Instruction *, 128> InstrsForInstructionWorklist;
4472 DenseMap<Constant *, Constant *> FoldedConstants;
4473 AliasScopeTracker SeenAliasScopes;
4474
4475 do {
4476 BasicBlock *BB = Worklist.pop_back_val();
4477
4478 // We have now visited this block! If we've already been here, ignore it.
4479 if (!Visited.insert(BB).second)
4480 continue;
4481
4482 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
4483 // ConstantProp instruction if trivially constant.
4484 if (!Inst.use_empty() &&
4485 (Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0))))
4486 if (Constant *C = ConstantFoldInstruction(&Inst, DL, TLI)) {
4487 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst
4488 << '\n');
4489 Inst.replaceAllUsesWith(C);
4490 ++NumConstProp;
4491 if (isInstructionTriviallyDead(&Inst, TLI))
4492 Inst.eraseFromParent();
4493 MadeIRChange = true;
4494 continue;
4495 }
4496
4497 // See if we can constant fold its operands.
4498 for (Use &U : Inst.operands()) {
4499 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
4500 continue;
4501
4502 auto *C = cast<Constant>(U);
4503 Constant *&FoldRes = FoldedConstants[C];
4504 if (!FoldRes)
4505 FoldRes = ConstantFoldConstant(C, DL, TLI);
4506
4507 if (FoldRes != C) {
4508 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst
4509 << "\n Old = " << *C
4510 << "\n New = " << *FoldRes << '\n');
4511 U = FoldRes;
4512 MadeIRChange = true;
4513 }
4514 }
4515
4516 // Skip processing debug and pseudo intrinsics in InstCombine. Processing
4517 // these call instructions consumes non-trivial amount of time and
4518 // provides no value for the optimization.
4519 if (!Inst.isDebugOrPseudoInst()) {
4520 InstrsForInstructionWorklist.push_back(&Inst);
4521 SeenAliasScopes.analyse(&Inst);
4522 }
4523 }
4524
4525 // Recursively visit successors. If this is a branch or switch on a
4526 // constant, only visit the reachable successor.
4527 Instruction *TI = BB->getTerminator();
4528 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
4529 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
4530 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
4531 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
4532 Worklist.push_back(ReachableBB);
4533 continue;
4534 }
4535 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
4536 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
4537 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
4538 continue;
4539 }
4540 }
4541
4542 append_range(Worklist, successors(TI));
4543 } while (!Worklist.empty());
4544
4545 // Remove instructions inside unreachable blocks. This prevents the
4546 // instcombine code from having to deal with some bad special cases, and
4547 // reduces use counts of instructions.
4548 for (BasicBlock &BB : F) {
4549 if (Visited.count(&BB))
4550 continue;
4551
4552 unsigned NumDeadInstInBB;
4553 unsigned NumDeadDbgInstInBB;
4554 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) =
4556
4557 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0;
4558 NumDeadInst += NumDeadInstInBB;
4559 }
4560
4561 // Once we've found all of the instructions to add to instcombine's worklist,
4562 // add them in reverse order. This way instcombine will visit from the top
4563 // of the function down. This jives well with the way that it adds all uses
4564 // of instructions to the worklist after doing a transformation, thus avoiding
4565 // some N^2 behavior in pathological cases.
4566 ICWorklist.reserve(InstrsForInstructionWorklist.size());
4567 for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) {
4568 // DCE instruction if trivially dead. As we iterate in reverse program
4569 // order here, we will clean up whole chains of dead instructions.
4570 if (isInstructionTriviallyDead(Inst, TLI) ||
4571 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
4572 ++NumDeadInst;
4573 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
4574 salvageDebugInfo(*Inst);
4575 Inst->eraseFromParent();
4576 MadeIRChange = true;
4577 continue;
4578 }
4579
4580 ICWorklist.push(Inst);
4581 }
4582
4583 return MadeIRChange;
4584}
4585
4590 ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) {
4591 auto &DL = F.getParent()->getDataLayout();
4592
4593 /// Builder - This is an IRBuilder that automatically inserts new
4594 /// instructions into the worklist when they are created.
4596 F.getContext(), TargetFolder(DL),
4597 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
4598 Worklist.add(I);
4599 if (auto *Assume = dyn_cast<AssumeInst>(I))
4600 AC.registerAssumption(Assume);
4601 }));
4602
4603 // Lower dbg.declare intrinsics otherwise their value may be clobbered
4604 // by instcombiner.
4605 bool MadeIRChange = false;
4607 MadeIRChange = LowerDbgDeclare(F);
4608
4609 // Iterate while there is work to do.
4610 unsigned Iteration = 0;
4611 while (true) {
4612 ++NumWorklistIterations;
4613 ++Iteration;
4614
4615 if (Iteration > InfiniteLoopDetectionThreshold) {
4617 "Instruction Combining seems stuck in an infinite loop after " +
4618 Twine(InfiniteLoopDetectionThreshold) + " iterations.");
4619 }
4620
4621 if (Iteration > MaxIterations) {
4622 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations
4623 << " on " << F.getName()
4624 << " reached; stopping before reaching a fixpoint\n");
4625 break;
4626 }
4627
4628 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
4629 << F.getName() << "\n");
4630
4631 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
4632
4633 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT,
4634 ORE, BFI, PSI, DL, LI);
4636
4637 if (!IC.run())
4638 break;
4639
4640 MadeIRChange = true;
4641 }
4642
4643 return MadeIRChange;
4644}
4645
4647
4649 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
4650 static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(
4651 OS, MapClassName2PassName);
4652 OS << '<';
4653 OS << "max-iterations=" << Options.MaxIterations << ";";
4654 OS << (Options.UseLoopInfo ? "" : "no-") << "use-loop-info";
4655 OS << '>';
4656}
4657
4660 auto &AC = AM.getResult<AssumptionAnalysis>(F);
4661 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
4662 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
4664 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
4665
4666 // TODO: Only use LoopInfo when the option is set. This requires that the
4667 // callers in the pass pipeline explicitly set the option.
4668 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
4669 if (!LI && Options.UseLoopInfo)
4670 LI = &AM.getResult<LoopAnalysis>(F);
4671
4672 auto *AA = &AM.getResult<AAManager>(F);
4673 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
4674 ProfileSummaryInfo *PSI =
4675 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
4676 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
4677 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
4678
4679 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
4680 BFI, PSI, Options.MaxIterations, LI))
4681 // No changes, all analyses are preserved.
4682 return PreservedAnalyses::all();
4683
4684 // Mark all the analyses that instcombine updates as preserved.
4687 return PA;
4688}
4689
4691 AU.setPreservesCFG();
4704}
4705
4707 if (skipFunction(F))
4708 return false;
4709
4710 // Required analyses.
4711 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4712 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(