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