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