LLVM 19.0.0git
AggressiveInstCombine.cpp
Go to the documentation of this file.
1//===- AggressiveInstCombine.cpp ------------------------------------------===//
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// This file implements the aggressive expression pattern combiner classes.
10// Currently, it handles expression patterns for:
11// * Truncate instruction
12//
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/Statistic.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Dominators.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
35
36using namespace llvm;
37using namespace PatternMatch;
38
39#define DEBUG_TYPE "aggressive-instcombine"
40
41STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
42STATISTIC(NumGuardedRotates,
43 "Number of guarded rotates transformed into funnel shifts");
44STATISTIC(NumGuardedFunnelShifts,
45 "Number of guarded funnel shifts transformed into funnel shifts");
46STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
47
49 "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
50 cl::desc("Max number of instructions to scan for aggressive instcombine."));
51
53 "strncmp-inline-threshold", cl::init(3), cl::Hidden,
54 cl::desc("The maximum length of a constant string for a builtin string cmp "
55 "call eligible for inlining. The default value is 3."));
56
57/// Match a pattern for a bitwise funnel/rotate operation that partially guards
58/// against undefined behavior by branching around the funnel-shift/rotation
59/// when the shift amount is 0.
61 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
62 return false;
63
64 // As with the one-use checks below, this is not strictly necessary, but we
65 // are being cautious to avoid potential perf regressions on targets that
66 // do not actually have a funnel/rotate instruction (where the funnel shift
67 // would be expanded back into math/shift/logic ops).
68 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
69 return false;
70
71 // Match V to funnel shift left/right and capture the source operands and
72 // shift amount.
73 auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
74 Value *&ShAmt) {
75 unsigned Width = V->getType()->getScalarSizeInBits();
76
77 // fshl(ShVal0, ShVal1, ShAmt)
78 // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
79 if (match(V, m_OneUse(m_c_Or(
80 m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
81 m_LShr(m_Value(ShVal1),
82 m_Sub(m_SpecificInt(Width), m_Deferred(ShAmt))))))) {
83 return Intrinsic::fshl;
84 }
85
86 // fshr(ShVal0, ShVal1, ShAmt)
87 // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
88 if (match(V,
90 m_Value(ShAmt))),
91 m_LShr(m_Value(ShVal1), m_Deferred(ShAmt)))))) {
92 return Intrinsic::fshr;
93 }
94
96 };
97
98 // One phi operand must be a funnel/rotate operation, and the other phi
99 // operand must be the source value of that funnel/rotate operation:
100 // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
101 // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
102 // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
103 PHINode &Phi = cast<PHINode>(I);
104 unsigned FunnelOp = 0, GuardOp = 1;
105 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
106 Value *ShVal0, *ShVal1, *ShAmt;
107 Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
108 if (IID == Intrinsic::not_intrinsic ||
109 (IID == Intrinsic::fshl && ShVal0 != P1) ||
110 (IID == Intrinsic::fshr && ShVal1 != P1)) {
111 IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
112 if (IID == Intrinsic::not_intrinsic ||
113 (IID == Intrinsic::fshl && ShVal0 != P0) ||
114 (IID == Intrinsic::fshr && ShVal1 != P0))
115 return false;
116 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
117 "Pattern must match funnel shift left or right");
118 std::swap(FunnelOp, GuardOp);
119 }
120
121 // The incoming block with our source operand must be the "guard" block.
122 // That must contain a cmp+branch to avoid the funnel/rotate when the shift
123 // amount is equal to 0. The other incoming block is the block with the
124 // funnel/rotate.
125 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
126 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
127 Instruction *TermI = GuardBB->getTerminator();
128
129 // Ensure that the shift values dominate each block.
130 if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
131 return false;
132
134 BasicBlock *PhiBB = Phi.getParent();
135 if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()),
136 m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
137 return false;
138
139 if (Pred != CmpInst::ICMP_EQ)
140 return false;
141
142 IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
143
144 if (ShVal0 == ShVal1)
145 ++NumGuardedRotates;
146 else
147 ++NumGuardedFunnelShifts;
148
149 // If this is not a rotate then the select was blocking poison from the
150 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
151 bool IsFshl = IID == Intrinsic::fshl;
152 if (ShVal0 != ShVal1) {
153 if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
154 ShVal1 = Builder.CreateFreeze(ShVal1);
155 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
156 ShVal0 = Builder.CreateFreeze(ShVal0);
157 }
158
159 // We matched a variation of this IR pattern:
160 // GuardBB:
161 // %cmp = icmp eq i32 %ShAmt, 0
162 // br i1 %cmp, label %PhiBB, label %FunnelBB
163 // FunnelBB:
164 // %sub = sub i32 32, %ShAmt
165 // %shr = lshr i32 %ShVal1, %sub
166 // %shl = shl i32 %ShVal0, %ShAmt
167 // %fsh = or i32 %shr, %shl
168 // br label %PhiBB
169 // PhiBB:
170 // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
171 // -->
172 // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
173 Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType());
174 Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt}));
175 return true;
176}
177
178/// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
179/// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
180/// of 'and' ops, then we also need to capture the fact that we saw an
181/// "and X, 1", so that's an extra return value for that case.
182struct MaskOps {
183 Value *Root = nullptr;
186 bool FoundAnd1 = false;
187
188 MaskOps(unsigned BitWidth, bool MatchAnds)
189 : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
190};
191
192/// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
193/// chain of 'and' or 'or' instructions looking for shift ops of a common source
194/// value. Examples:
195/// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
196/// returns { X, 0x129 }
197/// and (and (X >> 1), 1), (X >> 4)
198/// returns { X, 0x12 }
199static bool matchAndOrChain(Value *V, MaskOps &MOps) {
200 Value *Op0, *Op1;
201 if (MOps.MatchAndChain) {
202 // Recurse through a chain of 'and' operands. This requires an extra check
203 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
204 // in the chain to know that all of the high bits are cleared.
205 if (match(V, m_And(m_Value(Op0), m_One()))) {
206 MOps.FoundAnd1 = true;
207 return matchAndOrChain(Op0, MOps);
208 }
209 if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
210 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
211 } else {
212 // Recurse through a chain of 'or' operands.
213 if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
214 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
215 }
216
217 // We need a shift-right or a bare value representing a compare of bit 0 of
218 // the original source operand.
219 Value *Candidate;
220 const APInt *BitIndex = nullptr;
221 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
222 Candidate = V;
223
224 // Initialize result source operand.
225 if (!MOps.Root)
226 MOps.Root = Candidate;
227
228 // The shift constant is out-of-range? This code hasn't been simplified.
229 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
230 return false;
231
232 // Fill in the mask bit derived from the shift constant.
233 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
234 return MOps.Root == Candidate;
235}
236
237/// Match patterns that correspond to "any-bits-set" and "all-bits-set".
238/// These will include a chain of 'or' or 'and'-shifted bits from a
239/// common source value:
240/// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
241/// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
242/// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
243/// that differ only with a final 'not' of the result. We expect that final
244/// 'not' to be folded with the compare that we create here (invert predicate).
246 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
247 // final "and X, 1" instruction must be the final op in the sequence.
248 bool MatchAllBitsSet;
250 MatchAllBitsSet = true;
251 else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
252 MatchAllBitsSet = false;
253 else
254 return false;
255
256 MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
257 if (MatchAllBitsSet) {
258 if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
259 return false;
260 } else {
261 if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
262 return false;
263 }
264
265 // The pattern was found. Create a masked compare that replaces all of the
266 // shift and logic ops.
267 IRBuilder<> Builder(&I);
268 Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
269 Value *And = Builder.CreateAnd(MOps.Root, Mask);
270 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
271 : Builder.CreateIsNotNull(And);
272 Value *Zext = Builder.CreateZExt(Cmp, I.getType());
273 I.replaceAllUsesWith(Zext);
274 ++NumAnyOrAllBitsSet;
275 return true;
276}
277
278// Try to recognize below function as popcount intrinsic.
279// This is the "best" algorithm from
280// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
281// Also used in TargetLowering::expandCTPOP().
282//
283// int popcount(unsigned int i) {
284// i = i - ((i >> 1) & 0x55555555);
285// i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
286// i = ((i + (i >> 4)) & 0x0F0F0F0F);
287// return (i * 0x01010101) >> 24;
288// }
290 if (I.getOpcode() != Instruction::LShr)
291 return false;
292
293 Type *Ty = I.getType();
294 if (!Ty->isIntOrIntVectorTy())
295 return false;
296
297 unsigned Len = Ty->getScalarSizeInBits();
298 // FIXME: fix Len == 8 and other irregular type lengths.
299 if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
300 return false;
301
302 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
303 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
304 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
305 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
306 APInt MaskShift = APInt(Len, Len - 8);
307
308 Value *Op0 = I.getOperand(0);
309 Value *Op1 = I.getOperand(1);
310 Value *MulOp0;
311 // Matching "(i * 0x01010101...) >> 24".
312 if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) &&
313 match(Op1, m_SpecificInt(MaskShift))) {
314 Value *ShiftOp0;
315 // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)".
316 if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)),
317 m_Deferred(ShiftOp0)),
318 m_SpecificInt(Mask0F)))) {
319 Value *AndOp0;
320 // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)".
321 if (match(ShiftOp0,
322 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)),
324 m_SpecificInt(Mask33))))) {
325 Value *Root, *SubOp1;
326 // Matching "i - ((i >> 1) & 0x55555555...)".
327 if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) &&
328 match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)),
329 m_SpecificInt(Mask55)))) {
330 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
331 IRBuilder<> Builder(&I);
333 I.getModule(), Intrinsic::ctpop, I.getType());
334 I.replaceAllUsesWith(Builder.CreateCall(Func, {Root}));
335 ++NumPopCountRecognized;
336 return true;
337 }
338 }
339 }
340 }
341
342 return false;
343}
344
345/// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
346/// C2 saturate the value of the fp conversion. The transform is not reversable
347/// as the fptosi.sat is more defined than the input - all values produce a
348/// valid value for the fptosi.sat, where as some produce poison for original
349/// that were out of range of the integer conversion. The reversed pattern may
350/// use fmax and fmin instead. As we cannot directly reverse the transform, and
351/// it is not always profitable, we make it conditional on the cost being
352/// reported as lower by TTI.
354 // Look for min(max(fptosi, converting to fptosi_sat.
355 Value *In;
356 const APInt *MinC, *MaxC;
358 m_APInt(MinC))),
359 m_APInt(MaxC))) &&
361 m_APInt(MaxC))),
362 m_APInt(MinC))))
363 return false;
364
365 // Check that the constants clamp a saturate.
366 if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
367 return false;
368
369 Type *IntTy = I.getType();
370 Type *FpTy = In->getType();
371 Type *SatTy =
372 IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
373 if (auto *VecTy = dyn_cast<VectorType>(IntTy))
374 SatTy = VectorType::get(SatTy, VecTy->getElementCount());
375
376 // Get the cost of the intrinsic, and check that against the cost of
377 // fptosi+smin+smax
379 IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
381 SatCost += TTI.getCastInstrCost(Instruction::SExt, IntTy, SatTy,
384
386 Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
388 MinMaxCost += TTI.getIntrinsicInstrCost(
389 IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
391 MinMaxCost += TTI.getIntrinsicInstrCost(
392 IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
394
395 if (SatCost >= MinMaxCost)
396 return false;
397
398 IRBuilder<> Builder(&I);
399 Function *Fn = Intrinsic::getDeclaration(I.getModule(), Intrinsic::fptosi_sat,
400 {SatTy, FpTy});
401 Value *Sat = Builder.CreateCall(Fn, In);
402 I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
403 return true;
404}
405
406/// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
407/// pessimistic codegen that has to account for setting errno and can enable
408/// vectorization.
411 DominatorTree &DT) {
412
413 Module *M = Call->getModule();
414
415 // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
416 // (because NNAN or the operand arg must not be less than -0.0) and (2) we
417 // would not end up lowering to a libcall anyway (which could change the value
418 // of errno), then:
419 // (1) errno won't be set.
420 // (2) it is safe to convert this to an intrinsic call.
421 Type *Ty = Call->getType();
422 Value *Arg = Call->getArgOperand(0);
423 if (TTI.haveFastSqrt(Ty) &&
424 (Call->hasNoNaNs() ||
426 Arg, 0, SimplifyQuery(M->getDataLayout(), &TLI, &DT, &AC, Call)))) {
427 IRBuilder<> Builder(Call);
429 Builder.setFastMathFlags(Call->getFastMathFlags());
430
431 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, Ty);
432 Value *NewSqrt = Builder.CreateCall(Sqrt, Arg, "sqrt");
433 Call->replaceAllUsesWith(NewSqrt);
434
435 // Explicitly erase the old call because a call with side effects is not
436 // trivially dead.
437 Call->eraseFromParent();
438 return true;
439 }
440
441 return false;
442}
443
444// Check if this array of constants represents a cttz table.
445// Iterate over the elements from \p Table by trying to find/match all
446// the numbers from 0 to \p InputBits that should represent cttz results.
447static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul,
448 uint64_t Shift, uint64_t InputBits) {
449 unsigned Length = Table.getNumElements();
450 if (Length < InputBits || Length > InputBits * 2)
451 return false;
452
453 APInt Mask = APInt::getBitsSetFrom(InputBits, Shift);
454 unsigned Matched = 0;
455
456 for (unsigned i = 0; i < Length; i++) {
457 uint64_t Element = Table.getElementAsInteger(i);
458 if (Element >= InputBits)
459 continue;
460
461 // Check if \p Element matches a concrete answer. It could fail for some
462 // elements that are never accessed, so we keep iterating over each element
463 // from the table. The number of matched elements should be equal to the
464 // number of potential right answers which is \p InputBits actually.
465 if ((((Mul << Element) & Mask.getZExtValue()) >> Shift) == i)
466 Matched++;
467 }
468
469 return Matched == InputBits;
470}
471
472// Try to recognize table-based ctz implementation.
473// E.g., an example in C (for more cases please see the llvm/tests):
474// int f(unsigned x) {
475// static const char table[32] =
476// {0, 1, 28, 2, 29, 14, 24, 3, 30,
477// 22, 20, 15, 25, 17, 4, 8, 31, 27,
478// 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
479// return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
480// }
481// this can be lowered to `cttz` instruction.
482// There is also a special case when the element is 0.
483//
484// Here are some examples or LLVM IR for a 64-bit target:
485//
486// CASE 1:
487// %sub = sub i32 0, %x
488// %and = and i32 %sub, %x
489// %mul = mul i32 %and, 125613361
490// %shr = lshr i32 %mul, 27
491// %idxprom = zext i32 %shr to i64
492// %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
493// i64 %idxprom
494// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
495//
496// CASE 2:
497// %sub = sub i32 0, %x
498// %and = and i32 %sub, %x
499// %mul = mul i32 %and, 72416175
500// %shr = lshr i32 %mul, 26
501// %idxprom = zext i32 %shr to i64
502// %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table,
503// i64 0, i64 %idxprom
504// %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
505//
506// CASE 3:
507// %sub = sub i32 0, %x
508// %and = and i32 %sub, %x
509// %mul = mul i32 %and, 81224991
510// %shr = lshr i32 %mul, 27
511// %idxprom = zext i32 %shr to i64
512// %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table,
513// i64 0, i64 %idxprom
514// %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
515//
516// CASE 4:
517// %sub = sub i64 0, %x
518// %and = and i64 %sub, %x
519// %mul = mul i64 %and, 283881067100198605
520// %shr = lshr i64 %mul, 58
521// %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0,
522// i64 %shr
523// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
524//
525// All this can be lowered to @llvm.cttz.i32/64 intrinsic.
527 LoadInst *LI = dyn_cast<LoadInst>(&I);
528 if (!LI)
529 return false;
530
531 Type *AccessType = LI->getType();
532 if (!AccessType->isIntegerTy())
533 return false;
534
535 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
536 if (!GEP || !GEP->isInBounds() || GEP->getNumIndices() != 2)
537 return false;
538
539 if (!GEP->getSourceElementType()->isArrayTy())
540 return false;
541
542 uint64_t ArraySize = GEP->getSourceElementType()->getArrayNumElements();
543 if (ArraySize != 32 && ArraySize != 64)
544 return false;
545
546 GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
547 if (!GVTable || !GVTable->hasInitializer() || !GVTable->isConstant())
548 return false;
549
550 ConstantDataArray *ConstData =
551 dyn_cast<ConstantDataArray>(GVTable->getInitializer());
552 if (!ConstData)
553 return false;
554
555 if (!match(GEP->idx_begin()->get(), m_ZeroInt()))
556 return false;
557
558 Value *Idx2 = std::next(GEP->idx_begin())->get();
559 Value *X1;
560 uint64_t MulConst, ShiftConst;
561 // FIXME: 64-bit targets have `i64` type for the GEP index, so this match will
562 // probably fail for other (e.g. 32-bit) targets.
563 if (!match(Idx2, m_ZExtOrSelf(
565 m_ConstantInt(MulConst)),
566 m_ConstantInt(ShiftConst)))))
567 return false;
568
569 unsigned InputBits = X1->getType()->getScalarSizeInBits();
570 if (InputBits != 32 && InputBits != 64)
571 return false;
572
573 // Shift should extract top 5..7 bits.
574 if (InputBits - Log2_32(InputBits) != ShiftConst &&
575 InputBits - Log2_32(InputBits) - 1 != ShiftConst)
576 return false;
577
578 if (!isCTTZTable(*ConstData, MulConst, ShiftConst, InputBits))
579 return false;
580
581 auto ZeroTableElem = ConstData->getElementAsInteger(0);
582 bool DefinedForZero = ZeroTableElem == InputBits;
583
584 IRBuilder<> B(LI);
585 ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
586 Type *XType = X1->getType();
587 auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
588 Value *ZExtOrTrunc = nullptr;
589
590 if (DefinedForZero) {
591 ZExtOrTrunc = B.CreateZExtOrTrunc(Cttz, AccessType);
592 } else {
593 // If the value in elem 0 isn't the same as InputBits, we still want to
594 // produce the value from the table.
595 auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
596 auto Select =
597 B.CreateSelect(Cmp, ConstantInt::get(XType, ZeroTableElem), Cttz);
598
599 // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
600 // it should be handled as: `cttz(x) & (typeSize - 1)`.
601
602 ZExtOrTrunc = B.CreateZExtOrTrunc(Select, AccessType);
603 }
604
605 LI->replaceAllUsesWith(ZExtOrTrunc);
606
607 return true;
608}
609
610/// This is used by foldLoadsRecursive() to capture a Root Load node which is
611/// of type or(load, load) and recursively build the wide load. Also capture the
612/// shift amount, zero extend type and loadSize.
613struct LoadOps {
614 LoadInst *Root = nullptr;
616 bool FoundRoot = false;
618 const APInt *Shift = nullptr;
621};
622
623// Identify and Merge consecutive loads recursively which is of the form
624// (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
625// (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
626static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
627 AliasAnalysis &AA) {
628 const APInt *ShAmt2 = nullptr;
629 Value *X;
630 Instruction *L1, *L2;
631
632 // Go to the last node with loads.
633 if (match(V, m_OneUse(m_c_Or(
634 m_Value(X),
636 m_APInt(ShAmt2)))))) ||
639 if (!foldLoadsRecursive(X, LOps, DL, AA) && LOps.FoundRoot)
640 // Avoid Partial chain merge.
641 return false;
642 } else
643 return false;
644
645 // Check if the pattern has loads
646 LoadInst *LI1 = LOps.Root;
647 const APInt *ShAmt1 = LOps.Shift;
648 if (LOps.FoundRoot == false &&
651 m_APInt(ShAmt1)))))) {
652 LI1 = dyn_cast<LoadInst>(L1);
653 }
654 LoadInst *LI2 = dyn_cast<LoadInst>(L2);
655
656 // Check if loads are same, atomic, volatile and having same address space.
657 if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
659 return false;
660
661 // Check if Loads come from same BB.
662 if (LI1->getParent() != LI2->getParent())
663 return false;
664
665 // Find the data layout
666 bool IsBigEndian = DL.isBigEndian();
667
668 // Check if loads are consecutive and same size.
669 Value *Load1Ptr = LI1->getPointerOperand();
670 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
671 Load1Ptr =
672 Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
673 /* AllowNonInbounds */ true);
674
675 Value *Load2Ptr = LI2->getPointerOperand();
676 APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
677 Load2Ptr =
678 Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
679 /* AllowNonInbounds */ true);
680
681 // Verify if both loads have same base pointers and load sizes are same.
682 uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
683 uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
684 if (Load1Ptr != Load2Ptr || LoadSize1 != LoadSize2)
685 return false;
686
687 // Support Loadsizes greater or equal to 8bits and only power of 2.
688 if (LoadSize1 < 8 || !isPowerOf2_64(LoadSize1))
689 return false;
690
691 // Alias Analysis to check for stores b/w the loads.
692 LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
693 MemoryLocation Loc;
694 if (!Start->comesBefore(End)) {
695 std::swap(Start, End);
697 if (LOps.FoundRoot)
698 Loc = Loc.getWithNewSize(LOps.LoadSize);
699 } else
701 unsigned NumScanned = 0;
702 for (Instruction &Inst :
703 make_range(Start->getIterator(), End->getIterator())) {
704 if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
705 return false;
706
707 // Ignore debug info so that's not counted against MaxInstrsToScan.
708 // Otherwise debug info could affect codegen.
709 if (!isa<DbgInfoIntrinsic>(Inst) && ++NumScanned > MaxInstrsToScan)
710 return false;
711 }
712
713 // Make sure Load with lower Offset is at LI1
714 bool Reverse = false;
715 if (Offset2.slt(Offset1)) {
716 std::swap(LI1, LI2);
717 std::swap(ShAmt1, ShAmt2);
718 std::swap(Offset1, Offset2);
719 std::swap(Load1Ptr, Load2Ptr);
720 std::swap(LoadSize1, LoadSize2);
721 Reverse = true;
722 }
723
724 // Big endian swap the shifts
725 if (IsBigEndian)
726 std::swap(ShAmt1, ShAmt2);
727
728 // Find Shifts values.
729 uint64_t Shift1 = 0, Shift2 = 0;
730 if (ShAmt1)
731 Shift1 = ShAmt1->getZExtValue();
732 if (ShAmt2)
733 Shift2 = ShAmt2->getZExtValue();
734
735 // First load is always LI1. This is where we put the new load.
736 // Use the merged load size available from LI1 for forward loads.
737 if (LOps.FoundRoot) {
738 if (!Reverse)
739 LoadSize1 = LOps.LoadSize;
740 else
741 LoadSize2 = LOps.LoadSize;
742 }
743
744 // Verify if shift amount and load index aligns and verifies that loads
745 // are consecutive.
746 uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
747 uint64_t PrevSize =
748 DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
749 if ((Shift2 - Shift1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
750 return false;
751
752 // Update LOps
753 AAMDNodes AATags1 = LOps.AATags;
754 AAMDNodes AATags2 = LI2->getAAMetadata();
755 if (LOps.FoundRoot == false) {
756 LOps.FoundRoot = true;
757 AATags1 = LI1->getAAMetadata();
758 }
759 LOps.LoadSize = LoadSize1 + LoadSize2;
760 LOps.RootInsert = Start;
761
762 // Concatenate the AATags of the Merged Loads.
763 LOps.AATags = AATags1.concat(AATags2);
764
765 LOps.Root = LI1;
766 LOps.Shift = ShAmt1;
767 LOps.ZextType = X->getType();
768 return true;
769}
770
771// For a given BB instruction, evaluate all loads in the chain that form a
772// pattern which suggests that the loads can be combined. The one and only use
773// of the loads is to form a wider load.
776 const DominatorTree &DT) {
777 // Only consider load chains of scalar values.
778 if (isa<VectorType>(I.getType()))
779 return false;
780
781 LoadOps LOps;
782 if (!foldLoadsRecursive(&I, LOps, DL, AA) || !LOps.FoundRoot)
783 return false;
784
785 IRBuilder<> Builder(&I);
786 LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
787
788 IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
789 // TTI based checks if we want to proceed with wider load
790 bool Allowed = TTI.isTypeLegal(WiderType);
791 if (!Allowed)
792 return false;
793
794 unsigned AS = LI1->getPointerAddressSpace();
795 unsigned Fast = 0;
796 Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
797 AS, LI1->getAlign(), &Fast);
798 if (!Allowed || !Fast)
799 return false;
800
801 // Get the Index and Ptr for the new GEP.
802 Value *Load1Ptr = LI1->getPointerOperand();
803 Builder.SetInsertPoint(LOps.RootInsert);
804 if (!DT.dominates(Load1Ptr, LOps.RootInsert)) {
805 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
806 Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets(
807 DL, Offset1, /* AllowNonInbounds */ true);
808 Load1Ptr = Builder.CreatePtrAdd(Load1Ptr,
809 Builder.getInt32(Offset1.getZExtValue()));
810 }
811 // Generate wider load.
812 NewLoad = Builder.CreateAlignedLoad(WiderType, Load1Ptr, LI1->getAlign(),
813 LI1->isVolatile(), "");
814 NewLoad->takeName(LI1);
815 // Set the New Load AATags Metadata.
816 if (LOps.AATags)
817 NewLoad->setAAMetadata(LOps.AATags);
818
819 Value *NewOp = NewLoad;
820 // Check if zero extend needed.
821 if (LOps.ZextType)
822 NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
823
824 // Check if shift needed. We need to shift with the amount of load1
825 // shift if not zero.
826 if (LOps.Shift)
827 NewOp = Builder.CreateShl(NewOp, ConstantInt::get(I.getContext(), *LOps.Shift));
828 I.replaceAllUsesWith(NewOp);
829
830 return true;
831}
832
833// Calculate GEP Stride and accumulated const ModOffset. Return Stride and
834// ModOffset
835static std::pair<APInt, APInt>
837 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
838 std::optional<APInt> Stride;
839 APInt ModOffset(BW, 0);
840 // Return a minimum gep stride, greatest common divisor of consective gep
841 // index scales(c.f. Bézout's identity).
842 while (auto *GEP = dyn_cast<GEPOperator>(PtrOp)) {
843 MapVector<Value *, APInt> VarOffsets;
844 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset))
845 break;
846
847 for (auto [V, Scale] : VarOffsets) {
848 // Only keep a power of two factor for non-inbounds
849 if (!GEP->isInBounds())
850 Scale = APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
851
852 if (!Stride)
853 Stride = Scale;
854 else
855 Stride = APIntOps::GreatestCommonDivisor(*Stride, Scale);
856 }
857
858 PtrOp = GEP->getPointerOperand();
859 }
860
861 // Check whether pointer arrives back at Global Variable via at least one GEP.
862 // Even if it doesn't, we can check by alignment.
863 if (!isa<GlobalVariable>(PtrOp) || !Stride)
864 return {APInt(BW, 1), APInt(BW, 0)};
865
866 // In consideration of signed GEP indices, non-negligible offset become
867 // remainder of division by minimum GEP stride.
868 ModOffset = ModOffset.srem(*Stride);
869 if (ModOffset.isNegative())
870 ModOffset += *Stride;
871
872 return {*Stride, ModOffset};
873}
874
875/// If C is a constant patterned array and all valid loaded results for given
876/// alignment are same to a constant, return that constant.
878 auto *LI = dyn_cast<LoadInst>(&I);
879 if (!LI || LI->isVolatile())
880 return false;
881
882 // We can only fold the load if it is from a constant global with definitive
883 // initializer. Skip expensive logic if this is not the case.
884 auto *PtrOp = LI->getPointerOperand();
885 auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(PtrOp));
886 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
887 return false;
888
889 // Bail for large initializers in excess of 4K to avoid too many scans.
890 Constant *C = GV->getInitializer();
891 uint64_t GVSize = DL.getTypeAllocSize(C->getType());
892 if (!GVSize || 4096 < GVSize)
893 return false;
894
895 Type *LoadTy = LI->getType();
896 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
897 auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL);
898
899 // Any possible offset could be multiple of GEP stride. And any valid
900 // offset is multiple of load alignment, so checking only multiples of bigger
901 // one is sufficient to say results' equality.
902 if (auto LA = LI->getAlign();
903 LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
904 ConstOffset = APInt(BW, 0);
905 Stride = APInt(BW, LA.value());
906 }
907
908 Constant *Ca = ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL);
909 if (!Ca)
910 return false;
911
912 unsigned E = GVSize - DL.getTypeStoreSize(LoadTy);
913 for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
914 if (Ca != ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL))
915 return false;
916
917 I.replaceAllUsesWith(Ca);
918
919 return true;
920}
921
922namespace {
923class StrNCmpInliner {
924public:
925 StrNCmpInliner(CallInst *CI, LibFunc Func, DomTreeUpdater *DTU,
926 const DataLayout &DL)
927 : CI(CI), Func(Func), DTU(DTU), DL(DL) {}
928
929 bool optimizeStrNCmp();
930
931private:
932 void inlineCompare(Value *LHS, StringRef RHS, uint64_t N, bool Swapped);
933
934 CallInst *CI;
936 DomTreeUpdater *DTU;
937 const DataLayout &DL;
938};
939
940} // namespace
941
942/// First we normalize calls to strncmp/strcmp to the form of
943/// compare(s1, s2, N), which means comparing first N bytes of s1 and s2
944/// (without considering '\0').
945///
946/// Examples:
947///
948/// \code
949/// strncmp(s, "a", 3) -> compare(s, "a", 2)
950/// strncmp(s, "abc", 3) -> compare(s, "abc", 3)
951/// strncmp(s, "a\0b", 3) -> compare(s, "a\0b", 2)
952/// strcmp(s, "a") -> compare(s, "a", 2)
953///
954/// char s2[] = {'a'}
955/// strncmp(s, s2, 3) -> compare(s, s2, 3)
956///
957/// char s2[] = {'a', 'b', 'c', 'd'}
958/// strncmp(s, s2, 3) -> compare(s, s2, 3)
959/// \endcode
960///
961/// We only handle cases where N and exactly one of s1 and s2 are constant.
962/// Cases that s1 and s2 are both constant are already handled by the
963/// instcombine pass.
964///
965/// We do not handle cases where N > StrNCmpInlineThreshold.
966///
967/// We also do not handles cases where N < 2, which are already
968/// handled by the instcombine pass.
969///
970bool StrNCmpInliner::optimizeStrNCmp() {
972 return false;
973
975 return false;
976
977 Value *Str1P = CI->getArgOperand(0);
978 Value *Str2P = CI->getArgOperand(1);
979 // Should be handled elsewhere.
980 if (Str1P == Str2P)
981 return false;
982
983 StringRef Str1, Str2;
984 bool HasStr1 = getConstantStringInfo(Str1P, Str1, /*TrimAtNul=*/false);
985 bool HasStr2 = getConstantStringInfo(Str2P, Str2, /*TrimAtNul=*/false);
986 if (HasStr1 == HasStr2)
987 return false;
988
989 // Note that '\0' and characters after it are not trimmed.
990 StringRef Str = HasStr1 ? Str1 : Str2;
991 Value *StrP = HasStr1 ? Str2P : Str1P;
992
993 size_t Idx = Str.find('\0');
995 if (Func == LibFunc_strncmp) {
996 if (auto *ConstInt = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
997 N = std::min(N, ConstInt->getZExtValue());
998 else
999 return false;
1000 }
1001 // Now N means how many bytes we need to compare at most.
1002 if (N > Str.size() || N < 2 || N > StrNCmpInlineThreshold)
1003 return false;
1004
1005 // Cases where StrP has two or more dereferenceable bytes might be better
1006 // optimized elsewhere.
1007 bool CanBeNull = false, CanBeFreed = false;
1008 if (StrP->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed) > 1)
1009 return false;
1010 inlineCompare(StrP, Str, N, HasStr1);
1011 return true;
1012}
1013
1014/// Convert
1015///
1016/// \code
1017/// ret = compare(s1, s2, N)
1018/// \endcode
1019///
1020/// into
1021///
1022/// \code
1023/// ret = (int)s1[0] - (int)s2[0]
1024/// if (ret != 0)
1025/// goto NE
1026/// ...
1027/// ret = (int)s1[N-2] - (int)s2[N-2]
1028/// if (ret != 0)
1029/// goto NE
1030/// ret = (int)s1[N-1] - (int)s2[N-1]
1031/// NE:
1032/// \endcode
1033///
1034/// CFG before and after the transformation:
1035///
1036/// (before)
1037/// BBCI
1038///
1039/// (after)
1040/// BBCI -> BBSubs[0] (sub,icmp) --NE-> BBNE -> BBTail
1041/// | ^
1042/// E |
1043/// | |
1044/// BBSubs[1] (sub,icmp) --NE-----+
1045/// ... |
1046/// BBSubs[N-1] (sub) ---------+
1047///
1048void StrNCmpInliner::inlineCompare(Value *LHS, StringRef RHS, uint64_t N,
1049 bool Swapped) {
1050 auto &Ctx = CI->getContext();
1051 IRBuilder<> B(Ctx);
1052
1053 BasicBlock *BBCI = CI->getParent();
1054 BasicBlock *BBTail =
1055 SplitBlock(BBCI, CI, DTU, nullptr, nullptr, BBCI->getName() + ".tail");
1056
1058 for (uint64_t I = 0; I < N; ++I)
1059 BBSubs.push_back(
1060 BasicBlock::Create(Ctx, "sub_" + Twine(I), BBCI->getParent(), BBTail));
1061 BasicBlock *BBNE = BasicBlock::Create(Ctx, "ne", BBCI->getParent(), BBTail);
1062
1063 cast<BranchInst>(BBCI->getTerminator())->setSuccessor(0, BBSubs[0]);
1064
1065 B.SetInsertPoint(BBNE);
1066 PHINode *Phi = B.CreatePHI(CI->getType(), N);
1067 B.CreateBr(BBTail);
1068
1069 Value *Base = LHS;
1070 for (uint64_t i = 0; i < N; ++i) {
1071 B.SetInsertPoint(BBSubs[i]);
1072 Value *VL =
1073 B.CreateZExt(B.CreateLoad(B.getInt8Ty(),
1074 B.CreateInBoundsPtrAdd(Base, B.getInt64(i))),
1075 CI->getType());
1076 Value *VR = ConstantInt::get(CI->getType(), RHS[i]);
1077 Value *Sub = Swapped ? B.CreateSub(VR, VL) : B.CreateSub(VL, VR);
1078 if (i < N - 1)
1079 B.CreateCondBr(B.CreateICmpNE(Sub, ConstantInt::get(CI->getType(), 0)),
1080 BBNE, BBSubs[i + 1]);
1081 else
1082 B.CreateBr(BBNE);
1083
1084 Phi->addIncoming(Sub, BBSubs[i]);
1085 }
1086
1087 CI->replaceAllUsesWith(Phi);
1088 CI->eraseFromParent();
1089
1090 if (DTU) {
1092 Updates.push_back({DominatorTree::Insert, BBCI, BBSubs[0]});
1093 for (uint64_t i = 0; i < N; ++i) {
1094 if (i < N - 1)
1095 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBSubs[i + 1]});
1096 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBNE});
1097 }
1098 Updates.push_back({DominatorTree::Insert, BBNE, BBTail});
1099 Updates.push_back({DominatorTree::Delete, BBCI, BBTail});
1100 DTU->applyUpdates(Updates);
1101 }
1102}
1103
1106 DominatorTree &DT, const DataLayout &DL,
1107 bool &MadeCFGChange) {
1108
1109 auto *CI = dyn_cast<CallInst>(&I);
1110 if (!CI || CI->isNoBuiltin())
1111 return false;
1112
1113 Function *CalledFunc = CI->getCalledFunction();
1114 if (!CalledFunc)
1115 return false;
1116
1117 LibFunc LF;
1118 if (!TLI.getLibFunc(*CalledFunc, LF) ||
1119 !isLibFuncEmittable(CI->getModule(), &TLI, LF))
1120 return false;
1121
1122 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
1123
1124 switch (LF) {
1125 case LibFunc_sqrt:
1126 case LibFunc_sqrtf:
1127 case LibFunc_sqrtl:
1128 return foldSqrt(CI, LF, TTI, TLI, AC, DT);
1129 case LibFunc_strcmp:
1130 case LibFunc_strncmp:
1131 if (StrNCmpInliner(CI, LF, &DTU, DL).optimizeStrNCmp()) {
1132 MadeCFGChange = true;
1133 return true;
1134 }
1135 break;
1136 default:;
1137 }
1138 return false;
1139}
1140
1141/// This is the entry point for folds that could be implemented in regular
1142/// InstCombine, but they are separated because they are not expected to
1143/// occur frequently and/or have more than a constant-length pattern match.
1147 AssumptionCache &AC, bool &MadeCFGChange) {
1148 bool MadeChange = false;
1149 for (BasicBlock &BB : F) {
1150 // Ignore unreachable basic blocks.
1151 if (!DT.isReachableFromEntry(&BB))
1152 continue;
1153
1154 const DataLayout &DL = F.getParent()->getDataLayout();
1155
1156 // Walk the block backwards for efficiency. We're matching a chain of
1157 // use->defs, so we're more likely to succeed by starting from the bottom.
1158 // Also, we want to avoid matching partial patterns.
1159 // TODO: It would be more efficient if we removed dead instructions
1160 // iteratively in this loop rather than waiting until the end.
1162 MadeChange |= foldAnyOrAllBitsSet(I);
1163 MadeChange |= foldGuardedFunnelShift(I, DT);
1164 MadeChange |= tryToRecognizePopCount(I);
1165 MadeChange |= tryToFPToSat(I, TTI);
1166 MadeChange |= tryToRecognizeTableBasedCttz(I);
1167 MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT);
1168 MadeChange |= foldPatternedLoads(I, DL);
1169 // NOTE: This function introduces erasing of the instruction `I`, so it
1170 // needs to be called at the end of this sequence, otherwise we may make
1171 // bugs.
1172 MadeChange |= foldLibCalls(I, TTI, TLI, AC, DT, DL, MadeCFGChange);
1173 }
1174 }
1175
1176 // We're done with transforms, so remove dead instructions.
1177 if (MadeChange)
1178 for (BasicBlock &BB : F)
1180
1181 return MadeChange;
1182}
1183
1184/// This is the entry point for all transforms. Pass manager differences are
1185/// handled in the callers of this function.
1188 AliasAnalysis &AA, bool &MadeCFGChange) {
1189 bool MadeChange = false;
1190 const DataLayout &DL = F.getParent()->getDataLayout();
1191 TruncInstCombine TIC(AC, TLI, DL, DT);
1192 MadeChange |= TIC.run(F);
1193 MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA, AC, MadeCFGChange);
1194 return MadeChange;
1195}
1196
1199 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1200 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1201 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1202 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1203 auto &AA = AM.getResult<AAManager>(F);
1204 bool MadeCFGChange = false;
1205 if (!runImpl(F, AC, TTI, TLI, DT, AA, MadeCFGChange)) {
1206 // No changes, all analyses are preserved.
1207 return PreservedAnalyses::all();
1208 }
1209 // Mark all the analyses that instcombine updates as preserved.
1211 if (MadeCFGChange)
1213 else
1215 return PA;
1216}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
amdgpu AMDGPU Register Bank Select
static bool tryToRecognizePopCount(Instruction &I)
static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT)
Try to replace a mathlib call to sqrt with the LLVM intrinsic.
static bool foldAnyOrAllBitsSet(Instruction &I)
Match patterns that correspond to "any-bits-set" and "all-bits-set".
static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI)
Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and C2 saturate the value of t...
static cl::opt< unsigned > StrNCmpInlineThreshold("strncmp-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string for a builtin string cmp " "call eligible for inlining. The default value is 3."))
static bool matchAndOrChain(Value *V, MaskOps &MOps)
This is a recursive helper for foldAnyOrAllBitsSet() that walks through a chain of 'and' or 'or' inst...
static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, DominatorTree &DT, AliasAnalysis &AA, bool &MadeCFGChange)
This is the entry point for all transforms.
static bool tryToRecognizeTableBasedCttz(Instruction &I)
static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT)
Match a pattern for a bitwise funnel/rotate operation that partially guards against undefined behavio...
static cl::opt< unsigned > MaxInstrsToScan("aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden, cl::desc("Max number of instructions to scan for aggressive instcombine."))
static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, AliasAnalysis &AA)
static std::pair< APInt, APInt > getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL)
static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul, uint64_t Shift, uint64_t InputBits)
static bool foldPatternedLoads(Instruction &I, const DataLayout &DL)
If C is a constant patterned array and all valid loaded results for given alignment are same to a con...
static bool foldLibCalls(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, const DataLayout &DL, bool &MadeCFGChange)
static bool foldUnusualPatterns(Function &F, DominatorTree &DT, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AliasAnalysis &AA, AssumptionCache &AC, bool &MadeCFGChange)
This is the entry point for folds that could be implemented in regular InstCombine,...
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, const TargetLowering &TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
Definition: IRBuilder.cpp:530
static Instruction * matchFunnelShift(Instruction &Or, InstCombinerImpl &IC)
Match UB-safe variants of the funnel shift intrinsic.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This pass exposes codegen information to IR-level passes.
Value * LHS
BinaryOperator * Mul
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:76
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1308
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:307
static APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition: APInt.cpp:620
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition: APInt.cpp:1706
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1108
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:264
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1199
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:409
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:221
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
@ ICMP_EQ
equal
Definition: InstrTypes.h:1014
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:692
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:3005
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2748
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
This is an important base class in LLVM.
Definition: Constant.h:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", bool IsInBounds=false)
Definition: IRBuilder.h:1978
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1807
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2033
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2535
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:311
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:486
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2241
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1416
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2021
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1475
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2549
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2412
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1720
const BasicBlock * getParent() const
Definition: Instruction.h:152
AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1706
Class to represent integer types.
Definition: DerivedTypes.h:40
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:278
An instruction for reading from memory.
Definition: Instructions.h:184
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:286
Value * getPointerOperand()
Definition: Instructions.h:280
bool isSimple() const
Definition: Instructions.h:272
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:129
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
static constexpr size_t npos
Definition: StringRef.h:52
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
@ TCK_RecipThroughput
Reciprocal throughput.
bool isTypeLegal(Type *Ty) const
Return true if this type is legal.
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace=0, Align Alignment=Align(1), unsigned *Fast=nullptr) const
Determine if the target supports unaligned memory accesses.
bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
@ None
The cast is not used with a load/store of any kind.
bool run(Function &F)
Perform TruncInst pattern optimization on given function.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr) const
Accumulate the constant offset this value has compared to a base pointer.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool &CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition: Value.cpp:851
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
#define UINT64_MAX
Definition: DataTypes.h:77
APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition: APInt.cpp:767
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1471
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:966
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:810
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:869
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:586
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:887
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:593
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
specific_bbval m_SpecificBB(BasicBlock *BB)
Match a specific basic block value.
Definition: PatternMatch.h:999
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
CastInst_match< OpTy, FPToSIInst > m_FPToSI(const OpTy &Op)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:456
bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition: Local.cpp:731
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:280
bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:324
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:275
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
@ And
Bitwise or logical AND of integers.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
bool cannotBeOrderedLessThanZero(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
const APInt * Shift
LoadInst * RootInsert
This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and the bit indexes (Mask) nee...
MaskOps(unsigned BitWidth, bool MatchAnds)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.