LLVM 24.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"
31#include "llvm/IR/Instruction.h"
33#include "llvm/IR/MDBuilder.h"
42
43using namespace llvm;
44using namespace PatternMatch;
45
46#define DEBUG_TYPE "aggressive-instcombine"
47
48STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
49STATISTIC(NumGuardedRotates,
50 "Number of guarded rotates transformed into funnel shifts");
51STATISTIC(NumGuardedFunnelShifts,
52 "Number of guarded funnel shifts transformed into funnel shifts");
53STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
54STATISTIC(NumSelectCTTZFolded,
55 "Number of select-based split cttz patterns folded");
56STATISTIC(NumSelectCTLZFolded,
57 "Number of select-based split ctlz patterns folded");
58STATISTIC(NumMemSetsGuarded, "Number of memsets guarded for a zero length");
59STATISTIC(NumTableBasedLowBitsMask,
60 "Number of low-bits mask table loads folded to (1 << i) - 1");
61
63 "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
64 cl::desc("Max number of instructions to scan for aggressive instcombine."));
65
67 "strncmp-inline-threshold", cl::init(3), cl::Hidden,
68 cl::desc("The maximum length of a constant string for a builtin string cmp "
69 "call eligible for inlining. The default value is 3."));
70
72 MemChrInlineThreshold("memchr-inline-threshold", cl::init(3), cl::Hidden,
73 cl::desc("The maximum length of a constant string to "
74 "inline a memchr call."));
75
76namespace llvm {
78} // namespace llvm
79
80/// Try to fold a select-based split cttz pattern into a single full-width cttz.
81///
82/// %lo = trunc iN %val to i(N/2)
83/// %cmp = icmp eq i(N/2) %lo, 0
84/// %shr = lshr iN %val, N/2
85/// %hi = trunc iN %shr to i(N/2)
86/// %cttz_hi = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %hi, ...)
87/// %hi_plus = add/or_disjoint i(N/2) %cttz_hi, N/2
88/// %cttz_lo = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %lo, ...)
89/// %result = select i1 %cmp, i(N/2) %hi_plus, i(N/2) %cttz_lo
90/// -->
91/// %cttz_wide = call iN @llvm.cttz.iN(iN %val, i1 false)
92/// %result = trunc iN %cttz_wide to i(N/2)
93/// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/-s14-s
94// TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases.
95static bool foldSelectSplitCTTZ(Instruction &I, Value *LoTrunc, Value *HiResult,
96 Value *LoResult, Type *HalfTy) {
97 unsigned HalfWidth = HalfTy->getIntegerBitWidth();
98 unsigned FullWidth = HalfWidth * 2;
99
100 // LoTrunc: trunc iN SrcVal to i(N/2)
101 Value *SrcVal;
102 if (!match(LoTrunc, m_Trunc(m_Value(SrcVal))))
103 return false;
104 if (!SrcVal->getType()->isIntegerTy(FullWidth))
105 return false;
106
107 // LoResult: cttz(trunc(SrcVal), _), must use same truncated value
108 if (!match(LoResult, m_OneUse(m_Cttz(m_Specific(LoTrunc), m_Value()))))
109 return false;
110
111 // HiResult: add/or_disjoint(cttz(trunc(lshr(SrcVal, N/2)), _), N/2)
112 Value *CttzHiCall;
113 if (!match(HiResult, m_OneUse(m_AddLike(m_Value(CttzHiCall),
114 m_SpecificInt(HalfWidth)))))
115 return false;
116
117 Value *HiCttzArg;
118 if (!match(CttzHiCall, m_OneUse(m_Cttz(m_Value(HiCttzArg), m_Value()))))
119 return false;
120
121 if (!match(HiCttzArg,
122 m_Trunc(m_LShr(m_Specific(SrcVal), m_SpecificInt(HalfWidth)))))
123 return false;
124
125 // Match successful.
126 IRBuilder<> Builder(&I);
127 Value *CttzWide = Builder.CreateIntrinsic(
128 Intrinsic::cttz, {SrcVal->getType()}, {SrcVal, Builder.getFalse()});
129 Value *Trunc = Builder.CreateTrunc(CttzWide, HalfTy);
130
131 I.replaceAllUsesWith(Trunc);
132 ++NumSelectCTTZFolded;
133 return true;
134}
135
136/// Same as foldSelectSplitCTTZ but for leading zeros (ctlz).
137///
138/// %shr = lshr iN %val, N/2
139/// %hi = trunc iN %shr to i(N/2)
140/// %cmp = icmp eq i(N/2) %hi, 0 (or icmp eq iN %shr, 0)
141/// %lo = trunc iN %val to i(N/2)
142/// %ctlz_lo = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %lo, ...)
143/// %lo_plus = add/or_disjoint i(N/2) %ctlz_lo, N/2
144/// %ctlz_hi = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %hi, ...)
145/// %result = select i1 %cmp, i(N/2) %lo_plus, i(N/2) %ctlz_hi
146/// -->
147/// %ctlz_wide = call iN @llvm.ctlz.iN(iN %val, i1 false)
148/// %result = trunc iN %ctlz_wide to i(N/2)
149///
150/// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/WfQepH
151// TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases.
152static bool foldSelectSplitCTLZ(Instruction &I, Value *HiPart, Value *LoResult,
153 Value *HiResult, Type *HalfTy) {
154 unsigned HalfWidth = HalfTy->getIntegerBitWidth();
155 unsigned FullWidth = HalfWidth * 2;
156
157 // Extract SrcVal from HiPart: either trunc(lshr(SrcVal, N/2)) or
158 // lshr(SrcVal, N/2)
159 Value *SrcVal;
160 if (match(HiPart, m_Trunc(m_Value(SrcVal))))
161 HiPart = SrcVal;
162
163 if (!match(HiPart, m_LShr(m_Value(SrcVal), m_SpecificInt(HalfWidth))))
164 return false;
165 if (!SrcVal->getType()->isIntegerTy(FullWidth))
166 return false;
167
168 // HiResult: ctlz(trunc(lshr(SrcVal, N/2)), _)
169 Value *HiCtlzArg;
170 if (!match(HiResult, m_OneUse(m_Ctlz(m_Value(HiCtlzArg), m_Value()))))
171 return false;
172
173 if (!match(HiCtlzArg,
174 m_Trunc(m_LShr(m_Specific(SrcVal), m_SpecificInt(HalfWidth)))))
175 return false;
176
177 // LoResult: add/or_disjoint(ctlz(trunc(SrcVal), _), N/2)
178 Value *CtlzLoCall;
179 if (!match(LoResult, m_OneUse(m_AddLike(m_Value(CtlzLoCall),
180 m_SpecificInt(HalfWidth)))))
181 return false;
182
183 Value *LoCtlzArg;
184 if (!match(CtlzLoCall, m_OneUse(m_Ctlz(m_Value(LoCtlzArg), m_Value()))))
185 return false;
186
187 if (!match(LoCtlzArg, m_Trunc(m_Specific(SrcVal))))
188 return false;
189
190 // Match successful.
191 IRBuilder<> Builder(&I);
192 Value *CtlzWide = Builder.CreateIntrinsic(
193 Intrinsic::ctlz, {SrcVal->getType()}, {SrcVal, Builder.getFalse()});
194 Value *Trunc = Builder.CreateTrunc(CtlzWide, HalfTy);
195
196 I.replaceAllUsesWith(Trunc);
197 ++NumSelectCTLZFolded;
198 return true;
199}
200
201/// Common entry point for folding select-based split cttz/ctlz patterns.
202/// Performs the initial select and type matching shared by both transforms,
203/// then delegates to foldSelectSplitCTTZ and foldSelectSplitCTLZ.
205 Value *Cond, *TrueVal, *FalseVal;
206 if (!match(&I, m_Select(m_Value(Cond), m_Value(TrueVal), m_Value(FalseVal))))
207 return false;
208
209 Type *Ty = I.getType();
210 if (!Ty->isIntegerTy())
211 return false;
212
213 // Bail out on very small types (i1, i2): the full-width cttz/ctlz can return
214 // values not representable in the half type (e.g., cttz.i4 can return 4,
215 // which doesn't fit in i2).
216 if (Ty->getIntegerBitWidth() <= 2)
217 return false;
218
220 Value *CmpOp;
221 if (!match(Cond, m_ICmp(Pred, m_Value(CmpOp), m_ZeroInt())) ||
223 return false;
224
225 // Canonicalize select operands.
226 if (Pred == CmpInst::ICMP_NE)
227 std::swap(TrueVal, FalseVal);
228
229 return foldSelectSplitCTTZ(I, CmpOp, TrueVal, FalseVal, Ty) ||
230 foldSelectSplitCTLZ(I, CmpOp, TrueVal, FalseVal, Ty);
231}
232
233/// Match a pattern for a bitwise funnel/rotate operation that partially guards
234/// against undefined behavior by branching around the funnel-shift/rotation
235/// when the shift amount is 0.
237 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
238 return false;
239
240 // As with the one-use checks below, this is not strictly necessary, but we
241 // are being cautious to avoid potential perf regressions on targets that
242 // do not actually have a funnel/rotate instruction (where the funnel shift
243 // would be expanded back into math/shift/logic ops).
244 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
245 return false;
246
247 // Match V to funnel shift left/right and capture the source operands and
248 // shift amount.
249 auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
250 Value *&ShAmt) {
251 unsigned Width = V->getType()->getScalarSizeInBits();
252
253 // fshl(ShVal0, ShVal1, ShAmt)
254 // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
255 if (match(V, m_OneUse(m_c_Or(
256 m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
257 m_LShr(m_Value(ShVal1), m_Sub(m_SpecificInt(Width),
258 m_Deferred(ShAmt))))))) {
259 return Intrinsic::fshl;
260 }
261
262 // fshr(ShVal0, ShVal1, ShAmt)
263 // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
264 if (match(V,
266 m_Value(ShAmt))),
267 m_LShr(m_Value(ShVal1), m_Deferred(ShAmt)))))) {
268 return Intrinsic::fshr;
269 }
270
272 };
273
274 // One phi operand must be a funnel/rotate operation, and the other phi
275 // operand must be the source value of that funnel/rotate operation:
276 // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
277 // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
278 // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
279 PHINode &Phi = cast<PHINode>(I);
280 unsigned FunnelOp = 0, GuardOp = 1;
281 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
282 Value *ShVal0, *ShVal1, *ShAmt;
283 Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
284 if (IID == Intrinsic::not_intrinsic ||
285 (IID == Intrinsic::fshl && ShVal0 != P1) ||
286 (IID == Intrinsic::fshr && ShVal1 != P1)) {
287 IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
288 if (IID == Intrinsic::not_intrinsic ||
289 (IID == Intrinsic::fshl && ShVal0 != P0) ||
290 (IID == Intrinsic::fshr && ShVal1 != P0))
291 return false;
292 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
293 "Pattern must match funnel shift left or right");
294 std::swap(FunnelOp, GuardOp);
295 }
296
297 // The incoming block with our source operand must be the "guard" block.
298 // That must contain a cmp+branch to avoid the funnel/rotate when the shift
299 // amount is equal to 0. The other incoming block is the block with the
300 // funnel/rotate.
301 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
302 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
303 Instruction *TermI = GuardBB->getTerminator();
304
305 // Ensure that the shift values dominate each block.
306 if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
307 return false;
308
309 BasicBlock *PhiBB = Phi.getParent();
311 m_ZeroInt()),
312 m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
313 return false;
314
315 IRBuilder<> Builder(PhiBB->getFirstInsertionPt());
316
317 if (ShVal0 == ShVal1)
318 ++NumGuardedRotates;
319 else
320 ++NumGuardedFunnelShifts;
321
322 // If this is not a rotate then the select was blocking poison from the
323 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
324 bool IsFshl = IID == Intrinsic::fshl;
325 if (ShVal0 != ShVal1) {
326 if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
327 ShVal1 = Builder.CreateFreeze(ShVal1);
328 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
329 ShVal0 = Builder.CreateFreeze(ShVal0);
330 }
331
332 // We matched a variation of this IR pattern:
333 // GuardBB:
334 // %cmp = icmp eq i32 %ShAmt, 0
335 // br i1 %cmp, label %PhiBB, label %FunnelBB
336 // FunnelBB:
337 // %sub = sub i32 32, %ShAmt
338 // %shr = lshr i32 %ShVal1, %sub
339 // %shl = shl i32 %ShVal0, %ShAmt
340 // %fsh = or i32 %shr, %shl
341 // br label %PhiBB
342 // PhiBB:
343 // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
344 // -->
345 // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
346 Phi.replaceAllUsesWith(
347 Builder.CreateIntrinsic(IID, Phi.getType(), {ShVal0, ShVal1, ShAmt}));
348 return true;
349}
350
351/// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
352/// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
353/// of 'and' ops, then we also need to capture the fact that we saw an
354/// "and X, 1", so that's an extra return value for that case.
355namespace {
356struct MaskOps {
357 Value *Root = nullptr;
358 APInt Mask;
359 bool MatchAndChain;
360 bool FoundAnd1 = false;
361
362 MaskOps(unsigned BitWidth, bool MatchAnds)
363 : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
364};
365} // namespace
366
367/// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
368/// chain of 'and' or 'or' instructions looking for shift ops of a common source
369/// value. Examples:
370/// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
371/// returns { X, 0x129 }
372/// and (and (X >> 1), 1), (X >> 4)
373/// returns { X, 0x12 }
374static bool matchAndOrChain(Value *V, MaskOps &MOps) {
375 Value *Op0, *Op1;
376 if (MOps.MatchAndChain) {
377 // Recurse through a chain of 'and' operands. This requires an extra check
378 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
379 // in the chain to know that all of the high bits are cleared.
380 if (match(V, m_And(m_Value(Op0), m_One()))) {
381 MOps.FoundAnd1 = true;
382 return matchAndOrChain(Op0, MOps);
383 }
384 if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
385 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
386 } else {
387 // Recurse through a chain of 'or' operands.
388 if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
389 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
390 }
391
392 // We need a shift-right or a bare value representing a compare of bit 0 of
393 // the original source operand.
394 Value *Candidate;
395 const APInt *BitIndex = nullptr;
396 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
397 Candidate = V;
398
399 // Initialize result source operand.
400 if (!MOps.Root)
401 MOps.Root = Candidate;
402
403 // The shift constant is out-of-range? This code hasn't been simplified.
404 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
405 return false;
406
407 // Fill in the mask bit derived from the shift constant.
408 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
409 return MOps.Root == Candidate;
410}
411
412/// Match patterns that correspond to "any-bits-set" and "all-bits-set".
413/// These will include a chain of 'or' or 'and'-shifted bits from a
414/// common source value:
415/// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
416/// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
417/// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
418/// that differ only with a final 'not' of the result. We expect that final
419/// 'not' to be folded with the compare that we create here (invert predicate).
421 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
422 // final "and X, 1" instruction must be the final op in the sequence.
423 bool MatchAllBitsSet;
424 bool MatchTrunc;
425 Value *X;
426 if (I.getType()->isIntOrIntVectorTy(1)) {
427 if (match(&I, m_Trunc(m_OneUse(m_And(m_Value(), m_Value())))))
428 MatchAllBitsSet = true;
429 else if (match(&I, m_Trunc(m_OneUse(m_Or(m_Value(), m_Value())))))
430 MatchAllBitsSet = false;
431 else
432 return false;
433 MatchTrunc = true;
434 X = I.getOperand(0);
435 } else {
436 if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value()))) {
437 X = &I;
438 MatchAllBitsSet = true;
439 } else if (match(&I,
440 m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One()))) {
441 X = I.getOperand(0);
442 MatchAllBitsSet = false;
443 } else
444 return false;
445 MatchTrunc = false;
446 }
447 Type *Ty = X->getType();
448
449 MaskOps MOps(Ty->getScalarSizeInBits(), MatchAllBitsSet);
450 if (!matchAndOrChain(X, MOps) ||
451 (MatchAllBitsSet && !MatchTrunc && !MOps.FoundAnd1))
452 return false;
453
454 // The pattern was found. Create a masked compare that replaces all of the
455 // shift and logic ops.
456 IRBuilder<> Builder(&I);
457 Constant *Mask = ConstantInt::get(Ty, MOps.Mask);
458 Value *And = Builder.CreateAnd(MOps.Root, Mask);
459 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
460 : Builder.CreateIsNotNull(And);
461 Value *Zext = MatchTrunc ? Cmp : Builder.CreateZExt(Cmp, Ty);
462 I.replaceAllUsesWith(Zext);
463 ++NumAnyOrAllBitsSet;
464 return true;
465}
466
467/// Helper function to replace an instruction with a popcount intrinsic.
468/// This creates the ctpop intrinsic with an optional zero-extension or
469/// truncation appended at the end, and replaces all uses of the instruction.
471 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
472 IRBuilder<> Builder(&I);
473 Value *NewVal =
474 Builder.CreateIntrinsic(Intrinsic::ctpop, Root->getType(), {Root});
475 I.replaceAllUsesWith(Builder.CreateZExtOrTrunc(NewVal, I.getType()));
476 ++NumPopCountRecognized;
477}
478
479// Matches the common innermost steps of the Hacker's Delight popcount idiom:
480// V = ((x + (x >> 4)) & 0x0F...)
481// x = (y & 0x33...) + ((y >> 2) & 0x33...) [or y - 3*((y>>2)&0x33...)]
482// y = Root - ((Root >> 1) & 0x55...)
483// This computes the popcount for each byte.
484// Returns Root on success, nullptr on failure.
485static Value *matchPopCountBytes(Value *V, unsigned Len, const DataLayout &DL) {
486 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
487 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
488 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
489
490 Value *Add2;
491 // Matching "((x + (x >> 4)) & 0x0F...)".
493 m_Deferred(Add2)),
494 m_SpecificInt(Mask0F))))
495 return nullptr;
496
497 Value *Sub1;
498 APInt NegThree(Len, -3, /*isSigned=*/true);
499 // Match
500 // x = (x & 0x33333333) + ((x >> 2) & 0x33333333)"
501 // Or
502 // x = x - 3*((x >> 2) & 0x33333333)
503 if (!match(Add2, m_c_Add(m_And(m_LShr(m_Value(Sub1), m_SpecificInt(2)),
504 m_SpecificInt(Mask33)),
505 m_And(m_Deferred(Sub1), m_SpecificInt(Mask33)))) &&
507 m_SpecificInt(Mask33)),
508 m_SpecificInt(NegThree)),
509 m_Deferred(Sub1))))
510 return nullptr;
511
512 Value *Root, *LShr;
513 const APInt *AndMask;
514 // Matching "x - ((x >> 1) & 0x55...)".
515 if (!match(Sub1,
516 m_Sub(m_Value(Root), m_And(m_Value(LShr, m_LShr(m_Deferred(Root),
517 m_SpecificInt(1))),
518 m_APInt(AndMask)))))
519 return nullptr;
520
521 if (*AndMask != Mask55) {
522 // Accept a narrowed mask if missing bits are known zero in Root>>1.
523 if (!AndMask->isSubsetOf(Mask55))
524 return nullptr;
525 APInt NeededMask = Mask55 & ~*AndMask;
526 if (!MaskedValueIsZero(LShr, NeededMask, SimplifyQuery(DL)))
527 return nullptr;
528 }
529
530 return Root;
531}
532
533// Try to recognize below function as popcount intrinsic.
534// This is the "best" algorithm from
535// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
536// Also used in TargetLowering::expandCTPOP().
537//
538// int popcount(unsigned int i) {
539// i = i - ((i >> 1) & 0x55555555);
540// i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
541// i = ((i + (i >> 4)) & 0x0F0F0F0F);
542// return (i * 0x01010101) >> 24;
543// }
545 if (I.getOpcode() != Instruction::LShr)
546 return false;
547
548 Type *Ty = I.getType();
549 if (!Ty->isIntOrIntVectorTy())
550 return false;
551
552 unsigned Len = Ty->getScalarSizeInBits();
553 // Len==8 is handled by tryToRecognizePopCount2n3.
554 // FIXME: other irregular type lengths.
555 if (Len > 128 || Len <= 8 || Len % 8 != 0)
556 return false;
557
558 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
559
560 Value *Op0 = I.getOperand(0);
561 Value *Op1 = I.getOperand(1);
562 Value *MulOp0;
563 // Matching "(i * 0x01010101...) >> 24".
564 if (!match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01))) ||
565 !match(Op1, m_SpecificInt(Len - 8)))
566 return false;
567
568 Value *Root = matchPopCountBytes(MulOp0, Len, I.getDataLayout());
569 if (!Root)
570 return false;
571
572 replaceWithPopCount(I, Root);
573 return true;
574}
575
576// Try to recognize below function as popcount intrinsic.
577// Ref. Hacker Delights
578// int popcount32(unsigned int i) {
579// uWord = (uWord & 0x55555555) + ((uWord>>1) & 0x55555555);
580// uWord = (uWord & 0x33333333) + ((uWord>>2) & 0x33333333);
581// uWord = (uWord & 0x0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F);
582// uWord = (uWord & 0x00FF00FF) + ((uWord>>8) & 0x00FF00FF);
583// return (uWord & 0x0000FFFF) + (uWord>>16);
584// }
585// int popcount64(unsigned long i) {
586// uWord = (uWord & 0x5555555555555555) + ((uWord>>1) & 0x5555555555555555);
587// uWord = (uWord & 0x3333333333333333) + ((uWord>>2) & 0x3333333333333333);
588// uWord = (uWord & 0x0F0F0F0F0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F0F0F0F0F);
589// uWord = (uWord & 0x00FF00FF00FF00FF) + ((uWord>>8) & 0x00FF00FF00FF00FF);
590// uWord = (uWord & 0x0000FFFF0000FFFF) + ((uWord>>16) & 0x0000FFFF0000FFFF);
591// return (uWord & 0x00000000FFFFFFFF) + (uWord>>32) & 0x00000000FFFFFFFF;
592// }
593//
594// InstCombine may narrow AND masks when it can prove the removed bits are
595// known zero (e.g. 0x0F0F0F0F -> 0x07070707). We accept such narrowed masks
596// by checking they are subsets of the expected masks and verifying the missing
597// bits are known zero via MaskedValueIsZero.
599 if (I.getOpcode() != Instruction::Add)
600 return false;
601
602 Type *Ty = I.getType();
603 if (!Ty->isIntOrIntVectorTy())
604 return false;
605
606 unsigned Len = Ty->getScalarSizeInBits();
607 if (Len > 64 || Len <= 8 || Len % 8 != 0)
608 return false;
609
610 // Len should be a power of 2 for the loop to work correctly
611 if (!isPowerOf2_32(Len))
612 return false;
613
614 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
615 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
616
617 SimplifyQuery SQ(I.getDataLayout());
618
619 // Check if CapturedMask is a valid (possibly narrowed) version of
620 // ExpectedMask for the given Operand. Returns true if the masks match
621 // exactly, or if CapturedMask is a subset and the missing bits are
622 // known zero in the Operand.
623 auto isValidNarrowedMask = [&](const APInt &CapturedMask,
624 const APInt &ExpectedMask,
625 Value *Operand) -> bool {
626 if (CapturedMask == ExpectedMask)
627 return true;
628 if (!CapturedMask.isSubsetOf(ExpectedMask))
629 return false;
630 APInt NeededMask = ExpectedMask & ~CapturedMask;
631 return MaskedValueIsZero(Operand, NeededMask, SQ);
632 };
633
634 // For "(x & M) + ((x >> S) & M)" patterns, both AND masks may be narrowed.
635 // Require subsets of BaseMask and prove any implied missing bits are zero.
636 auto narrowAddPairMasksOk = [&](const APInt &BaseMask, unsigned ShiftAmt,
637 Value *Val, const APInt &AndMask1,
638 const APInt &AndMask2) -> bool {
639 if (!AndMask1.isSubsetOf(BaseMask) || !AndMask2.isSubsetOf(BaseMask))
640 return false;
641 APInt NeededShifted = (BaseMask & ~AndMask1).shl(ShiftAmt);
642 APInt NeededUnshifted = BaseMask & ~AndMask2;
643 APInt AllNeeded = NeededShifted | NeededUnshifted;
644 return AllNeeded.isZero() || MaskedValueIsZero(Val, AllNeeded, SQ);
645 };
646
647 Value *ShiftOp;
648 Value *Start = &I;
649 for (unsigned I = Len; I >= 8; I = I / 2) {
650 APInt Mask = APInt::getSplat(Len, APInt::getLowBitsSet(I, I / 2));
651 const APInt *AndMask1 = nullptr, *AndMask2 = nullptr;
652
653 // Matching "(uWord & Mask) + ((uWord>>I/2) & Mask)".
654 // Both masks might have been narrowed by InstCombine.
655 if (match(Start,
656 m_c_Add(m_And(m_LShr(m_Value(ShiftOp), m_SpecificInt(I / 2)),
657 m_APInt(AndMask1)),
658 m_And(m_Deferred(ShiftOp), m_APInt(AndMask2))))) {
659 if (!narrowAddPairMasksOk(Mask, I / 2, ShiftOp, *AndMask1, *AndMask2))
660 return false;
661 }
662 // Matching "(uWord & Mask) + (uWord>>I/2)".
663 // The mask might have been narrowed by InstCombine.
664 else if (match(Start,
665 m_c_Add(m_LShr(m_Value(ShiftOp), m_SpecificInt(I / 2)),
666 m_And(m_Deferred(ShiftOp), m_APInt(AndMask1))))) {
667 if (!isValidNarrowedMask(*AndMask1, Mask, ShiftOp))
668 return false;
669 } else
670 return false;
671 Start = ShiftOp;
672 }
673
674 // Matching "uWord = (uWord & Mask33) + ((uWord>>2) & Mask33)".
675 const APInt *AndMask1 = nullptr, *AndMask2 = nullptr;
676 if (!match(Start, m_c_Add(m_And(m_LShr(m_Value(ShiftOp), m_SpecificInt(2)),
677 m_APInt(AndMask1)),
678 m_And(m_Deferred(ShiftOp), m_APInt(AndMask2)))))
679 return false;
680 if (!narrowAddPairMasksOk(Mask33, 2, ShiftOp, *AndMask1, *AndMask2))
681 return false;
682
683 Start = ShiftOp;
684 Value *Root;
685 // Matching "uWord = (uWord & Mask55) + ((uWord>>1) & Mask55)".
686 AndMask1 = nullptr;
687 AndMask2 = nullptr;
688 if (!match(Start, m_c_Add(m_And(m_LShr(m_Value(Root), m_SpecificInt(1)),
689 m_APInt(AndMask1)),
690 m_And(m_Deferred(Root), m_APInt(AndMask2)))))
691 return false;
692 if (!narrowAddPairMasksOk(Mask55, 1, Root, *AndMask1, *AndMask2))
693 return false;
694
695 replaceWithPopCount(I, Root);
696 return true;
697}
698
699// Try to recognize below function as popcount intrinsic.
700// Ref. Hackers Delight
701// int popcnt(unsigned x) {
702// x = x - ((x >> 1) & 0x55555555);
703// x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
704// x = (x + (x >> 4)) & 0x0F0F0F0F;
705// x = x + (x >> 8);
706// x = x + (x >> 16);
707// return x & 0x0000003F;
708// }
709
710// int popcnt(unsigned x) {
711// x = x - ((x >> 1) & 0x55555555);
712// x = x - 3*((x >> 2) & 0x33333333);
713// x = (x + (x >> 4)) & 0x0F0F0F0F;
714// x = x + (x >> 8);
715// x = x + (x >> 16);
716// return x & 0x0000003F;
717// }
719 if (I.getOpcode() != Instruction::And)
720 return false;
721
722 Type *Ty = I.getType();
723 if (!Ty->isIntOrIntVectorTy())
724 return false;
725
726 unsigned Len = Ty->getScalarSizeInBits();
727 Value *Add1;
728 if (Len == 8) {
729 // Special case for Len == 8, we only need to match the And at the end of
730 // matchPopCountBytes.
731 Add1 = &I;
732 } else {
733 const APInt *MaskRes;
734 if (!match(&I, m_And(m_Value(Add1), m_APInt(MaskRes))))
735 return false;
736
737 // Since `(trunc (and x, C))` might be canonicalized into `(and (trunc x),
738 // C)` we might loose the opportunity to recognize `(trunc (popcount y))`.
739 // The following block tries to capture such truncation, update `Len`, and
740 // append the truncation at the end of the emitting popcount, if there is
741 // any.
742 Value *TruncSrc;
743 if (match(Add1, m_OneUse(m_Trunc(m_Value(TruncSrc))))) {
744 Add1 = TruncSrc;
745 Len = Add1->getType()->getScalarSizeInBits();
746 }
747
748 if (Len > 64 || Len <= 8 || Len % 8 != 0)
749 return false;
750
751 // Len should be a power of 2 for the loop to work correctly
752 if (!isPowerOf2_32(Len))
753 return false;
754
755 // Number of bits needed to represent Len.
756 unsigned NumLenBits = Log2_32(Len) + 1;
757 // The "mask" here really only needs to fulfill two conditions:
758 // (1) All ones for the lower NumLenBits-bits
759 // (2) Zeros from bit 8 and onward.
760 // Condition (1) is straightforward. The reason behind condition
761 // (2) is that we don't care any 8-bit chunks but the first one
762 // in the original divide-and-conquer algorithm.
763 if (MaskRes->countTrailingOnes() < NumLenBits ||
764 MaskRes->getActiveBits() > 8)
765 return false;
766
767 for (unsigned I = Len; I >= 16; I = I / 2) {
768 Value *Add2;
769 // Matching "x = x + (x >> I/2)" for I-bit.
770 if (!match(Add1, m_c_Add(m_LShr(m_Value(Add2), m_SpecificInt(I / 2)),
771 m_Deferred(Add2))))
772 return false;
773 Add1 = Add2;
774 }
775 }
776
777 Value *Root = matchPopCountBytes(Add1, Len, I.getDataLayout());
778 if (!Root)
779 return false;
780
781 replaceWithPopCount(I, Root);
782 return true;
783}
784
785/// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
786/// C2 saturate the value of the fp conversion. The transform is not reversable
787/// as the fptosi.sat is more defined than the input - all values produce a
788/// valid value for the fptosi.sat, where as some produce poison for original
789/// that were out of range of the integer conversion. The reversed pattern may
790/// use fmax and fmin instead. As we cannot directly reverse the transform, and
791/// it is not always profitable, we make it conditional on the cost being
792/// reported as lower by TTI.
794 // Look for min(max(fptosi, converting to fptosi_sat.
795 Value *In;
796 const APInt *MinC, *MaxC;
798 m_APInt(MinC))),
799 m_APInt(MaxC))) &&
801 m_APInt(MaxC))),
802 m_APInt(MinC))))
803 return false;
804
805 // Check that the constants clamp a saturate.
806 if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
807 return false;
808
809 Type *IntTy = I.getType();
810 Type *FpTy = In->getType();
811 Type *SatTy =
812 IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
813 if (auto *VecTy = dyn_cast<VectorType>(IntTy))
814 SatTy = VectorType::get(SatTy, VecTy->getElementCount());
815
816 // Get the cost of the intrinsic, and check that against the cost of
817 // fptosi+smin+smax
818 InstructionCost SatCost = TTI.getIntrinsicInstrCost(
819 IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
821 SatCost += TTI.getCastInstrCost(Instruction::SExt, IntTy, SatTy,
824
825 InstructionCost MinMaxCost = TTI.getCastInstrCost(
826 Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
828 MinMaxCost += TTI.getIntrinsicInstrCost(
829 IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
831 MinMaxCost += TTI.getIntrinsicInstrCost(
832 IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
834
835 if (SatCost >= MinMaxCost)
836 return false;
837
838 IRBuilder<> Builder(&I);
839 Value *Sat =
840 Builder.CreateIntrinsic(Intrinsic::fptosi_sat, {SatTy, FpTy}, In);
841 I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
842 return true;
843}
844
845/// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
846/// pessimistic codegen that has to account for setting errno and can enable
847/// vectorization.
848static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI,
850 DominatorTree &DT) {
851 // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
852 // (because NNAN or the operand arg must not be less than -0.0) and (2) we
853 // would not end up lowering to a libcall anyway (which could change the value
854 // of errno), then:
855 // (1) errno won't be set.
856 // (2) it is safe to convert this to an intrinsic call.
857 Type *Ty = Call->getType();
858 Value *Arg = Call->getArgOperand(0);
859 if (TTI.haveFastSqrt(Ty) &&
860 (Call->hasNoNaNs() ||
862 Arg, SimplifyQuery(Call->getDataLayout(), &TLI, &DT, &AC, Call)))) {
863 IRBuilder<> Builder(Call);
864 Value *NewSqrt =
865 Builder.CreateIntrinsic(Intrinsic::sqrt, Ty, Arg, Call, "sqrt");
866 Call->replaceAllUsesWith(NewSqrt);
867
868 // Explicitly erase the old call because a call with side effects is not
869 // trivially dead.
870 Call->eraseFromParent();
871 return true;
872 }
873
874 return false;
875}
876
877// Check if this array of constants represents a cttz table.
878// Iterate over the elements from \p Table by trying to find/match all
879// the numbers from 0 to \p InputBits that should represent cttz results.
880static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift,
881 const APInt &AndMask, Type *AccessTy,
882 unsigned InputBits, const APInt &GEPIdxFactor,
883 const DataLayout &DL) {
884 for (unsigned Idx = 0; Idx < InputBits; Idx++) {
885 APInt Index =
886 (APInt::getOneBitSet(InputBits, Idx) * Mul).lshr(Shift) & AndMask;
888 ConstantFoldLoadFromConst(Table, AccessTy, Index * GEPIdxFactor, DL));
889 if (!C || C->getValue() != Idx)
890 return false;
891 }
892
893 return true;
894}
895
896// Try to recognize table-based ctz implementation.
897// E.g., an example in C (for more cases please see the llvm/tests):
898// int f(unsigned x) {
899// static const char table[32] =
900// {0, 1, 28, 2, 29, 14, 24, 3, 30,
901// 22, 20, 15, 25, 17, 4, 8, 31, 27,
902// 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
903// return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
904// }
905// this can be lowered to `cttz` instruction.
906// There is also a special case when the element is 0.
907//
908// The (x & -x) sets the lowest non-zero bit to 1. The multiply is a de-bruijn
909// sequence that contains each pattern of bits in it. The shift extracts
910// the top bits after the multiply, and that index into the table should
911// represent the number of trailing zeros in the original number.
912//
913// Here are some examples or LLVM IR for a 64-bit target:
914//
915// CASE 1:
916// %sub = sub i32 0, %x
917// %and = and i32 %sub, %x
918// %mul = mul i32 %and, 125613361
919// %shr = lshr i32 %mul, 27
920// %idxprom = zext i32 %shr to i64
921// %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
922// i64 %idxprom
923// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
924//
925// CASE 2:
926// %sub = sub i32 0, %x
927// %and = and i32 %sub, %x
928// %mul = mul i32 %and, 72416175
929// %shr = lshr i32 %mul, 26
930// %idxprom = zext i32 %shr to i64
931// %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table,
932// i64 0, i64 %idxprom
933// %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
934//
935// CASE 3:
936// %sub = sub i32 0, %x
937// %and = and i32 %sub, %x
938// %mul = mul i32 %and, 81224991
939// %shr = lshr i32 %mul, 27
940// %idxprom = zext i32 %shr to i64
941// %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table,
942// i64 0, i64 %idxprom
943// %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
944//
945// CASE 4:
946// %sub = sub i64 0, %x
947// %and = and i64 %sub, %x
948// %mul = mul i64 %and, 283881067100198605
949// %shr = lshr i64 %mul, 58
950// %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0,
951// i64 %shr
952// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
953//
954// All these can be lowered to @llvm.cttz.i32/64 intrinsics.
955//
956// This shares its initial match (load from a GEP into a constant table with
957// a single variable index) with tryToRecognizeTableBasedLog2() below; see
958// tryToRecognizeTableBasedPatterns().
959static bool tryToRecognizeTableBasedCttz(LoadInst *LI, Type *AccessType,
960 GlobalVariable *GVTable, Value *GepIdx,
961 const APInt &GEPScale,
962 const DataLayout &DL) {
963 Value *X1;
964 const APInt *MulConst, *ShiftConst, *AndCst = nullptr;
965 // Check that the gep variable index is ((x & -x) * MulConst) >> ShiftConst.
966 // This might be extended to the pointer index type, and if the gep index type
967 // has been replaced with an i8 then a new And (and different ShiftConst) will
968 // be present.
969 auto MatchInner = m_LShr(
970 m_Mul(m_c_And(m_Neg(m_Value(X1)), m_Deferred(X1)), m_APInt(MulConst)),
971 m_APInt(ShiftConst));
972 if (!match(GepIdx, m_CastOrSelf(MatchInner)) &&
973 !match(GepIdx, m_CastOrSelf(m_And(MatchInner, m_APInt(AndCst)))))
974 return false;
975
976 unsigned InputBits = X1->getType()->getScalarSizeInBits();
977 if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128)
978 return false;
979
980 if (!GEPScale.isIntN(InputBits) ||
981 !isCTTZTable(GVTable->getInitializer(), *MulConst, *ShiftConst,
982 AndCst ? *AndCst : APInt::getAllOnes(InputBits), AccessType,
983 InputBits, GEPScale.zextOrTrunc(InputBits), DL))
984 return false;
985
986 ConstantInt *ZeroTableElem = cast<ConstantInt>(
987 ConstantFoldLoadFromConst(GVTable->getInitializer(), AccessType, DL));
988 bool DefinedForZero = ZeroTableElem->equalsInt(InputBits);
989
990 IRBuilder<> B(LI);
991 ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
992 Type *XType = X1->getType();
993 auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
994 Value *Res = B.CreateZExtOrTrunc(Cttz, AccessType);
995
996 if (!DefinedForZero) {
997 // If the value in elem 0 isn't the same as InputBits, we still want to
998 // produce the value from the table. Emit the select in AccessType with elem
999 // 0 unchanged, as the table's element type may be wider than the input
1000 // type (and directly truncating ZeroTableElem into the input type could
1001 // incorrectly drop bits).
1002 auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
1003 Res = B.CreateSelect(Cmp, ZeroTableElem, Res);
1004
1005 // The true branch of select handles the cttz(0) case, which is rare.
1006 if (Instruction *SelectI = dyn_cast<Instruction>(Res))
1007 SelectI->setMetadata(
1008 LLVMContext::MD_prof,
1009 MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights());
1010
1011 // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
1012 // it should be handled as: `cttz(x) & (typeSize - 1)`.
1013 }
1014
1015 LI->replaceAllUsesWith(Res);
1016
1017 return true;
1018}
1019
1020// Recognise ctpop table lookups:
1021//
1022// %gep = getelementptr [256 x i8], ptr @ctpop.table, i32 0, i8 %x
1023// %ctpop = load i8, ptr %gep
1024// ->
1025// %ctpop = call i8 llvm.ctpop(i8 %x)
1026static bool tryToRecognizeTableBasedCtpop(LoadInst *LI, Type *AccessType,
1027 GlobalVariable *GVTable,
1028 Value *GepIdx, const APInt &GEPScale,
1029 const DataLayout &DL,
1030 const TargetTransformInfo &TTI) {
1031 Type *IdxTy = GepIdx->getType();
1032 unsigned IdxBits = IdxTy->getIntegerBitWidth();
1033 if (!LI->isSimple() || !isPowerOf2_32(IdxBits))
1034 return false;
1035
1036 // Only replace the table lookup if the popcount costs no more than it.
1037 constexpr auto CostKind = TargetTransformInfo::TCK_SizeAndLatency;
1039 InstructionCost TableCost = TTI.getInstructionCost(GEP, CostKind) +
1040 TTI.getInstructionCost(LI, CostKind);
1041 IntrinsicCostAttributes Attrs(Intrinsic::ctpop, IdxTy, {IdxTy});
1042 InstructionCost CtpopCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
1043 if (IdxTy != AccessType)
1044 CtpopCost += TTI.getCastInstrCost(
1045 IdxBits < AccessType->getIntegerBitWidth() ? Instruction::ZExt
1046 : Instruction::Trunc,
1047 AccessType, IdxTy, TTI::CastContextHint::None, CostKind);
1048 if (CtpopCost > TableCost)
1049 return false;
1050
1051 uint64_t TableSize = DL.getTypeAllocSize(GVTable->getValueType());
1052 unsigned AccessSize = DL.getTypeStoreSize(AccessType);
1053 if (GEPScale != AccessSize)
1054 return false;
1055 uint64_t NumEntries = TableSize / AccessSize;
1056 for (uint64_t I = 0; I < NumEntries; I++) {
1058 GVTable->getInitializer(), AccessType, I * GEPScale, DL));
1059 if (!C || C->getValue() != popcount(I))
1060 return false;
1061 }
1062
1063 replaceWithPopCount(*LI, GepIdx);
1064 return true;
1065}
1066
1067// Check if this array of constants represents a log2 table.
1068// Iterate over the elements from \p Table by trying to find/match all
1069// the numbers from 0 to \p InputBits that should represent log2 results.
1070static bool isLog2Table(Constant *Table, const APInt &Mul, const APInt &Shift,
1071 Type *AccessTy, unsigned InputBits,
1072 const APInt &GEPIdxFactor, const DataLayout &DL) {
1073 for (unsigned Idx = 0; Idx < InputBits; Idx++) {
1074 APInt Index = (APInt::getLowBitsSet(InputBits, Idx + 1) * Mul).lshr(Shift);
1076 ConstantFoldLoadFromConst(Table, AccessTy, Index * GEPIdxFactor, DL));
1077 if (!C || C->getValue() != Idx)
1078 return false;
1079 }
1080
1081 // Verify that an input of zero will select table index 0.
1082 APInt ZeroIndex = Mul.lshr(Shift);
1083 if (!ZeroIndex.isZero())
1084 return false;
1085
1086 return true;
1087}
1088
1089// Try to recognize table-based log2 implementation.
1090// E.g., an example in C (for more cases please the llvm/tests):
1091// int f(unsigned v) {
1092// static const char table[32] =
1093// {0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
1094// 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31};
1095//
1096// v |= v >> 1; // first round down to one less than a power of 2
1097// v |= v >> 2;
1098// v |= v >> 4;
1099// v |= v >> 8;
1100// v |= v >> 16;
1101//
1102// return table[(unsigned)(v * 0x07C4ACDDU) >> 27];
1103// }
1104// this can be lowered to `ctlz` instruction.
1105// There is also a special case when the element is 0.
1106//
1107// The >> and |= sequence sets all bits below the most significant set bit. The
1108// multiply is a de-bruijn sequence that contains each pattern of bits in it.
1109// The shift extracts the top bits after the multiply, and that index into the
1110// table should represent the floor log base 2 of the original number.
1111//
1112// Here are some examples of LLVM IR for a 64-bit target.
1113//
1114// CASE 1:
1115// %shr = lshr i32 %v, 1
1116// %or = or i32 %shr, %v
1117// %shr1 = lshr i32 %or, 2
1118// %or2 = or i32 %shr1, %or
1119// %shr3 = lshr i32 %or2, 4
1120// %or4 = or i32 %shr3, %or2
1121// %shr5 = lshr i32 %or4, 8
1122// %or6 = or i32 %shr5, %or4
1123// %shr7 = lshr i32 %or6, 16
1124// %or8 = or i32 %shr7, %or6
1125// %mul = mul i32 %or8, 130329821
1126// %shr9 = lshr i32 %mul, 27
1127// %idxprom = zext nneg i32 %shr9 to i64
1128// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %idxprom
1129// %0 = load i8, ptr %arrayidx, align 1
1130//
1131// CASE 2:
1132// %shr = lshr i64 %v, 1
1133// %or = or i64 %shr, %v
1134// %shr1 = lshr i64 %or, 2
1135// %or2 = or i64 %shr1, %or
1136// %shr3 = lshr i64 %or2, 4
1137// %or4 = or i64 %shr3, %or2
1138// %shr5 = lshr i64 %or4, 8
1139// %or6 = or i64 %shr5, %or4
1140// %shr7 = lshr i64 %or6, 16
1141// %or8 = or i64 %shr7, %or6
1142// %shr9 = lshr i64 %or8, 32
1143// %or10 = or i64 %shr9, %or8
1144// %mul = mul i64 %or10, 285870213051386505
1145// %shr11 = lshr i64 %mul, 58
1146// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr11
1147// %0 = load i8, ptr %arrayidx, align 1
1148//
1149// CASE 3:
1150// A variant where the most-significant set bit of the OR-cascade result is
1151// isolated via subtraction before the multiply, i.e.
1152// table[((v - (v >> 1)) * MulConst) >> ShiftConst], analogous to how the
1153// cttz pattern isolates the least-significant set bit via `x & -x`:
1154//
1155// %shr = lshr i64 %v, 1
1156// %or = or i64 %shr, %v
1157// ... (rest of the OR-cascade, as above) ...
1158// %shr11 = lshr i64 %or10, 1
1159// %sub = sub i64 %or10, %shr11
1160// %mul = mul i64 %sub, 571347909858961602
1161// %shr12 = lshr i64 %mul, 58
1162// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr12
1163// %0 = load i8, ptr %arrayidx, align 1
1164//
1165// All these can be lowered to @llvm.ctlz.i32/64 intrinsics and a subtract.
1166//
1167// This shares its initial match (load from a GEP into a constant table with
1168// a single variable index) with tryToRecognizeTableBasedCttz() above; see
1169// tryToRecognizeTableBasedPatterns().
1170static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType,
1171 GlobalVariable *GVTable, Value *GepIdx,
1172 const APInt &GEPScale,
1173 const DataLayout &DL,
1175 Value *X;
1176 const APInt *MulConst, *ShiftConst;
1177 // Check that the gep variable index is (x * MulConst) >> ShiftConst.
1178 auto MatchInner =
1179 m_LShr(m_Mul(m_Value(X), m_APInt(MulConst)), m_APInt(ShiftConst));
1180 if (!match(GepIdx, m_CastOrSelf(MatchInner)))
1181 return false;
1182
1183 // The multiplied value may instead be the OR-cascade result with its
1184 // most-significant set bit isolated first via `v - (v >> 1)`: since every
1185 // bit below the MSB of an OR-cascade result is 1, this subtraction leaves
1186 // just the MSB, mirroring how tryToRecognizeTableBasedCttz() isolates the
1187 // least-significant set bit via `x & -x`.
1188 bool IsolatedMSB = false;
1189 Value *V;
1191 IsolatedMSB = true;
1192 X = V;
1193 }
1194
1195 unsigned InputBits = X->getType()->getScalarSizeInBits();
1196 if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128)
1197 return false;
1198
1199 // Verify shift amount.
1200 // TODO: Allow other shift amounts when we have proper test coverage.
1201 if (*ShiftConst != InputBits - Log2_32(InputBits))
1202 return false;
1203
1204 // Match the sequence of OR operations with right shifts by powers of 2.
1205 for (unsigned ShiftAmt = InputBits / 2; ShiftAmt != 0; ShiftAmt /= 2) {
1206 Value *Y;
1207 if (!match(X, m_c_Or(m_LShr(m_Value(Y), m_SpecificInt(ShiftAmt)),
1208 m_Deferred(Y))))
1209 return false;
1210 X = Y;
1211 }
1212
1213 if (!GEPScale.isIntN(InputBits))
1214 return false;
1215
1216 if (IsolatedMSB) {
1217 // With the MSB isolated, the multiplicand for an input whose MSB is at bit
1218 // Idx is a single set bit rather than a run of low bits, which is exactly
1219 // what isCTTZTable() checks for (there is no additional masking here, so
1220 // pass an all-ones mask).
1221 if (!isCTTZTable(GVTable->getInitializer(), *MulConst, *ShiftConst,
1222 APInt::getAllOnes(InputBits), AccessType, InputBits,
1223 GEPScale.zextOrTrunc(InputBits), DL))
1224 return false;
1225 } else {
1226 if (!isLog2Table(GVTable->getInitializer(), *MulConst, *ShiftConst,
1227 AccessType, InputBits, GEPScale.zextOrTrunc(InputBits),
1228 DL))
1229 return false;
1230 }
1231
1232 ConstantInt *ZeroTableElem = cast<ConstantInt>(
1233 ConstantFoldLoadFromConst(GVTable->getInitializer(), AccessType, DL));
1234
1235 // Use InputBits - 1 - ctlz(X) to compute log2(X).
1236 IRBuilder<> B(LI);
1237 ConstantInt *BoolConst = B.getTrue();
1238 Type *XType = X->getType();
1239
1240 // Check the the backend has an efficient ctlz instruction.
1241 // FIXME: Teach the backend to emit the original code when ctlz isn't
1242 // supported like we do for cttz.
1244 Intrinsic::ctlz, XType,
1245 {PoisonValue::get(XType), /*is_zero_poison=*/BoolConst});
1246 InstructionCost Cost =
1247 TTI.getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
1249 return false;
1250
1251 Constant *InputBitsM1 = ConstantInt::get(XType, InputBits - 1);
1252
1253 Value *Result;
1254 if (ZeroTableElem->getZExtValue() == InputBits - 1) {
1255 Value *Ctlz =
1256 B.CreateIntrinsic(Intrinsic::ctlz, {XType}, {X, B.getFalse()});
1257 Result = B.CreateAnd(B.CreateNot(Ctlz), InputBitsM1);
1258 } else {
1259 Value *Ctlz = B.CreateIntrinsic(Intrinsic::ctlz, {XType}, {X, BoolConst});
1260 Value *Sub = B.CreateSub(InputBitsM1, Ctlz);
1261
1262 // The table won't produce a sensible result for 0.
1263 Value *Cmp = B.CreateICmpEQ(X, ConstantInt::get(XType, 0));
1264 Value *Select =
1265 B.CreateSelect(Cmp, B.CreateZExt(ZeroTableElem, XType), Sub);
1266
1267 // The true branch of select handles the log2(0) case, which is rare.
1269 SelectI->setMetadata(
1270 LLVMContext::MD_prof,
1271 MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights());
1272
1273 Result = Select;
1274 }
1275
1276 Value *ZExtOrTrunc = B.CreateZExtOrTrunc(Result, AccessType);
1277
1278 LI->replaceAllUsesWith(ZExtOrTrunc);
1279
1280 return true;
1281}
1282
1283// Recognize a load from a "low bits mask" table, tbl[j] == (1 << j) - 1:
1284//
1285// static const uintN_t tbl[K] = { 0, 1, 3, 7, ... };
1286// ... x & tbl[i] ...
1287//
1288// The loaded value equals the arithmetic mask (1 << i) - 1, so replace the load
1289// with that expression and drop the table. On X86+BMI2 a surrounding `and` then
1290// selects to a single `bzhi`; on other targets it is a shift and a decrement.
1291//
1292// Shares the load/GEP/offset match with the cttz and log2 recognizers above;
1293// see tryToRecognizeTableBasedPatterns().
1295 GlobalVariable *GVTable,
1296 Value *GepIdx,
1297 const APInt &GEPScale,
1298 const DataLayout &DL) {
1299 // The value must be exactly the table element; refuse volatile/atomic loads.
1300 if (!LI->isSimple())
1301 return false;
1302
1303 // The table must be [K x AccessType] of integers; a narrower load would read
1304 // only part of an element.
1305 auto *ArrTy = dyn_cast<ArrayType>(GVTable->getValueType());
1306 if (!ArrTy || ArrTy->getElementType() != AccessType ||
1307 !AccessType->isIntegerTy())
1308 return false;
1309
1310 unsigned EltBits = AccessType->getIntegerBitWidth();
1311 uint64_t EltBytes = DL.getTypeAllocSize(AccessType).getFixedValue();
1312 uint64_t K = ArrTy->getNumElements();
1313
1314 // Only fire when the element type fits in a legal integer, so the emitted
1315 // shift is a cheap (possibly promoted) instruction rather than a runtime
1316 // libcall (e.g. __ashlti3 for i128) -- which would be worse than the load
1317 // and is unavailable in freestanding environments that do not link a
1318 // runtime library.
1319 if (!DL.fitsInLegalInteger(EltBits))
1320 return false;
1321
1322 // The rewrite is only valid for indices inside the table. The nusw the
1323 // shared matcher requires keeps the address computation from wrapping but
1324 // does not keep it inside the object: a nusw-only GEP with i >= K is a
1325 // well-defined pointer past the table, and a load through it (into
1326 // whatever follows) is not (1 << i) - 1. With inbounds such a GEP is poison
1327 // and the load is UB, so every executed load has 0 <= i < K.
1329 if (!GEP->isInBounds())
1330 return false;
1331
1332 // K <= EltBits then guarantees i < EltBits, so the emitted `1 << i` never
1333 // shifts by >= bitwidth (no poison). A table with EltBits + 1 entries (whose
1334 // last element is the all-ones mask, needing a shift by EltBits) is
1335 // therefore rejected.
1336 if (K == 0 || K > EltBits)
1337 return false;
1338
1339 // The index must step by exactly one element, so the runtime index value is
1340 // the shift amount; a different scale would load tbl[c * i].
1341 if (GEPScale != EltBytes)
1342 return false;
1343
1344 // Every element must be the low-bits mask for its position.
1345 for (uint64_t J = 0; J < K; ++J) {
1347 GVTable->getInitializer(), AccessType,
1348 APInt(GEPScale.getBitWidth(), J) * GEPScale, DL);
1349 auto *CI = dyn_cast_or_null<ConstantInt>(Elt);
1350 if (!CI || CI->getValue() != APInt::getLowBitsSet(EltBits, J))
1351 return false;
1352 }
1353
1354 // Emit (1 << i) - 1 in the element type and replace the load. A later
1355 // InstCombine canonicalizes this to ~(-1 << i); X86 lowers both to bzhi.
1356 IRBuilder<> Builder(LI);
1357 Value *Idx = Builder.CreateZExtOrTrunc(GepIdx, AccessType);
1358 Value *Mask =
1359 Builder.CreateSub(Builder.CreateShl(ConstantInt::get(AccessType, 1), Idx),
1360 ConstantInt::get(AccessType, 1));
1361 LI->replaceAllUsesWith(Mask);
1362 ++NumTableBasedLowBitsMask;
1363 return true;
1364}
1365
1366// Match a table-based cttz, log2, or low-bits-mask implementation. These
1367// patterns share a load from a global table that we match first; then we
1368// try the specific matches.
1370 const DataLayout &DL,
1373 if (!LI)
1374 return false;
1375
1376 Type *AccessType = LI->getType();
1377 if (!AccessType->isIntegerTy())
1378 return false;
1379
1381 if (!GEP || !GEP->hasNoUnsignedSignedWrap())
1382 return false;
1383
1384 GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1385 if (!GVTable || !GVTable->isConstant() ||
1386 !GVTable->hasDefinitiveInitializer())
1387 return false;
1388
1389 unsigned BW = DL.getIndexTypeSizeInBits(GEP->getType());
1390 APInt ModOffset(BW, 0);
1392 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset) ||
1393 VarOffsets.size() != 1 || ModOffset != 0)
1394 return false;
1395 auto [GepIdx, GEPScale] = VarOffsets.front();
1396
1397 if (tryToRecognizeTableBasedCttz(LI, AccessType, GVTable, GepIdx, GEPScale,
1398 DL))
1399 return true;
1400
1401 if (tryToRecognizeTableBasedCtpop(LI, AccessType, GVTable, GepIdx, GEPScale,
1402 DL, TTI))
1403 return true;
1404
1405 if (tryToRecognizeTableBasedLog2(LI, AccessType, GVTable, GepIdx, GEPScale,
1406 DL, TTI))
1407 return true;
1408
1409 return tryToRecognizeTableBasedLowBitsMask(LI, AccessType, GVTable, GepIdx,
1410 GEPScale, DL);
1411}
1412
1413/// This is used by foldLoadsRecursive() to capture a Root Load node which is
1414/// of type or(load, load) and recursively build the wide load. Also capture the
1415/// shift amount, zero extend type and loadSize.
1416struct LoadOps {
1417 LoadInst *Root = nullptr;
1419 bool FoundRoot = false;
1420 uint64_t LoadSize = 0;
1421 uint64_t Shift = 0;
1424};
1425
1426// Identify and Merge consecutive loads recursively which is of the form
1427// (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
1428// (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
1429static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
1430 AliasAnalysis &AA, bool IsRoot = false) {
1431 uint64_t ShAmt2;
1432 Value *X;
1433 Instruction *L1, *L2;
1434
1435 // For the root instruction, allow multiple uses since the final result
1436 // may legitimately be used in multiple places. For intermediate values,
1437 // require single use to avoid creating duplicate loads.
1438 if (!IsRoot && !V->hasOneUse())
1439 return false;
1440
1441 if (!match(V, m_c_Or(m_Value(X),
1443 ShAmt2)))))
1444 return false;
1445
1446 if (!foldLoadsRecursive(X, LOps, DL, AA, /*IsRoot=*/false) && LOps.FoundRoot)
1447 // Avoid Partial chain merge.
1448 return false;
1449
1450 // Check if the pattern has loads
1451 LoadInst *LI1 = LOps.Root;
1452 uint64_t ShAmt1 = LOps.Shift;
1453 if (LOps.FoundRoot == false &&
1454 match(X, m_OneUse(
1455 m_ShlOrSelf(m_OneUse(m_ZExt(m_Instruction(L1))), ShAmt1)))) {
1456 LI1 = dyn_cast<LoadInst>(L1);
1457 }
1458 LoadInst *LI2 = dyn_cast<LoadInst>(L2);
1459
1460 // Check if loads are same, atomic, volatile and having same address space.
1461 if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
1463 return false;
1464
1465 // Check if Loads come from same BB.
1466 if (LI1->getParent() != LI2->getParent())
1467 return false;
1468
1469 // Find the data layout
1470 bool IsBigEndian = DL.isBigEndian();
1471
1472 // Check if loads are consecutive and same size.
1473 Value *Load1Ptr = LI1->getPointerOperand();
1474 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
1475 Load1Ptr =
1476 Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
1477 /* AllowNonInbounds */ true);
1478
1479 Value *Load2Ptr = LI2->getPointerOperand();
1480 APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
1481 Load2Ptr =
1482 Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
1483 /* AllowNonInbounds */ true);
1484
1485 // Verify if both loads have same base pointers
1486 uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
1487 uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
1488 if (Load1Ptr != Load2Ptr)
1489 return false;
1490
1491 // Make sure that there are no padding bits.
1492 if (!DL.typeSizeEqualsStoreSize(LI1->getType()) ||
1493 !DL.typeSizeEqualsStoreSize(LI2->getType()))
1494 return false;
1495
1496 // Alias Analysis to check for stores b/w the loads.
1497 LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
1499 if (!Start->comesBefore(End)) {
1500 std::swap(Start, End);
1501 // If LOps.RootInsert comes after LI2, since we use LI2 as the new insert
1502 // point, we should make sure whether the memory region accessed by LOps
1503 // isn't modified.
1504 if (LOps.FoundRoot)
1506 LOps.Root->getPointerOperand(),
1507 LocationSize::precise(DL.getTypeStoreSize(
1508 IntegerType::get(LI1->getContext(), LOps.LoadSize))),
1509 LOps.AATags);
1510 else
1512 } else
1514 unsigned NumScanned = 0;
1515 for (Instruction &Inst :
1516 make_range(Start->getIterator(), End->getIterator())) {
1517 if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
1518 return false;
1519
1520 if (++NumScanned > MaxInstrsToScan)
1521 return false;
1522 }
1523
1524 // Make sure Load with lower Offset is at LI1
1525 bool Reverse = false;
1526 if (Offset2.slt(Offset1)) {
1527 std::swap(LI1, LI2);
1528 std::swap(ShAmt1, ShAmt2);
1529 std::swap(Offset1, Offset2);
1530 std::swap(Load1Ptr, Load2Ptr);
1531 std::swap(LoadSize1, LoadSize2);
1532 Reverse = true;
1533 }
1534
1535 // Big endian swap the shifts
1536 if (IsBigEndian)
1537 std::swap(ShAmt1, ShAmt2);
1538
1539 // First load is always LI1. This is where we put the new load.
1540 // Use the merged load size available from LI1 for forward loads.
1541 if (LOps.FoundRoot) {
1542 if (!Reverse)
1543 LoadSize1 = LOps.LoadSize;
1544 else
1545 LoadSize2 = LOps.LoadSize;
1546 }
1547
1548 // Verify if shift amount and load index aligns and verifies that loads
1549 // are consecutive.
1550 uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
1551 uint64_t PrevSize =
1552 DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
1553 if ((ShAmt2 - ShAmt1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
1554 return false;
1555
1556 // Reject if the combined size of the loads exceeds the target type size.
1557 // This avoids attempting to emit an invalid ZExt (from wider to narrower
1558 // type) when out-of-bounds shifts lead to matching too many loads.
1559 if (LoadSize1 + LoadSize2 > X->getType()->getScalarSizeInBits())
1560 return false;
1561
1562 // Update LOps
1563 AAMDNodes AATags1 = LOps.AATags;
1564 AAMDNodes AATags2 = LI2->getAAMetadata();
1565 if (LOps.FoundRoot == false) {
1566 LOps.FoundRoot = true;
1567 AATags1 = LI1->getAAMetadata();
1568 }
1569 LOps.LoadSize = LoadSize1 + LoadSize2;
1570 LOps.RootInsert = Start;
1571
1572 // Concatenate the AATags of the Merged Loads.
1573 LOps.AATags = AATags1.concat(AATags2);
1574
1575 LOps.Root = LI1;
1576 LOps.Shift = ShAmt1;
1577 LOps.ZextType = X->getType();
1578 return true;
1579}
1580
1581// For a given BB instruction, evaluate all loads in the chain that form a
1582// pattern which suggests that the loads can be combined. The one and only use
1583// of the loads is to form a wider load.
1586 const DominatorTree &DT) {
1587 // Only consider load chains of scalar values.
1588 if (isa<VectorType>(I.getType()))
1589 return false;
1590
1591 LoadOps LOps;
1592 if (!foldLoadsRecursive(&I, LOps, DL, AA, /*IsRoot=*/true) || !LOps.FoundRoot)
1593 return false;
1594
1595 IRBuilder<> Builder(&I);
1596 LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
1597
1598 // Allow a power of 2 number of bytes that fit in a legal integer type.
1599 bool Allowed = LOps.LoadSize >= 16 && isPowerOf2_64(LOps.LoadSize) &&
1600 DL.fitsInLegalInteger(LOps.LoadSize);
1601 if (!Allowed)
1602 return false;
1603
1604 unsigned AS = LI1->getPointerAddressSpace();
1605 unsigned Fast = 0;
1606 Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
1607 AS, LI1->getAlign(), &Fast);
1608 if (!Allowed || !Fast)
1609 return false;
1610
1611 // Get the Index and Ptr for the new GEP.
1612 Value *Load1Ptr = LI1->getPointerOperand();
1613 Builder.SetInsertPoint(LOps.RootInsert);
1614 if (!DT.dominates(Load1Ptr, LOps.RootInsert)) {
1615 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
1616 Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets(
1617 DL, Offset1, /* AllowNonInbounds */ true);
1618 Load1Ptr = Builder.CreatePtrAdd(Load1Ptr, Builder.getInt(Offset1));
1619 }
1620 // Generate wider load.
1621 IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
1622 NewLoad = Builder.CreateAlignedLoad(WiderType, Load1Ptr, LI1->getAlign(),
1623 LI1->isVolatile(), "");
1624 NewLoad->takeName(LI1);
1625 // Set the New Load AATags Metadata.
1626 if (LOps.AATags)
1627 NewLoad->setAAMetadata(LOps.AATags);
1628
1629 Value *NewOp = NewLoad;
1630 // Zero extend if needed.
1631 NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
1632
1633 // Check if shift needed. We need to shift with the amount of load1
1634 // shift if not zero.
1635 if (LOps.Shift)
1636 NewOp = Builder.CreateShl(NewOp, LOps.Shift);
1637 I.replaceAllUsesWith(NewOp);
1638
1639 return true;
1640}
1641
1642/// ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset.
1647 uint64_t ValOffset;
1648 uint64_t ValWidth;
1650
1651 bool isCompatibleWith(const PartStore &Other) const {
1652 // Offset stripping looks through addrspacecasts, so an equal PtrBase does
1653 // not imply an equal address space, and thus not an equal PtrOffset width.
1654 return PtrBase == Other.PtrBase && Val == Other.Val &&
1655 Store->getPointerAddressSpace() ==
1656 Other.Store->getPointerAddressSpace();
1657 }
1658
1659 bool operator<(const PartStore &Other) const {
1660 return PtrOffset.slt(Other.PtrOffset);
1661 }
1662};
1663
1664static std::optional<PartStore> matchPartStore(Instruction &I,
1665 const DataLayout &DL) {
1666 auto *Store = dyn_cast<StoreInst>(&I);
1667 if (!Store || !Store->isSimple())
1668 return std::nullopt;
1669
1670 Value *StoredVal = Store->getValueOperand();
1671 Type *StoredTy = StoredVal->getType();
1672 if (!StoredTy->isIntegerTy() || !DL.typeSizeEqualsStoreSize(StoredTy))
1673 return std::nullopt;
1674
1675 uint64_t ValWidth = StoredTy->getPrimitiveSizeInBits();
1676 uint64_t ValOffset;
1677 Value *Val;
1678 if (!match(StoredVal, m_Trunc(m_LShrOrSelf(m_Value(Val), ValOffset))))
1679 return std::nullopt;
1680
1681 Value *Ptr = Store->getPointerOperand();
1682 APInt PtrOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
1684 DL, PtrOffset, /*AllowNonInbounds=*/true);
1685 return {{PtrBase, PtrOffset, Val, ValOffset, ValWidth, Store}};
1686}
1687
1689 unsigned Width, const DataLayout &DL,
1691 if (Parts.size() < 2)
1692 return false;
1693
1694 // Check whether combining the stores is profitable.
1695 // FIXME: We could generate smaller stores if we can't produce a large one.
1696 const PartStore &First = Parts.front();
1697 LLVMContext &Ctx = First.Store->getContext();
1698 unsigned Fast = 0;
1699 bool Allowed =
1700 Width >= 16 && isPowerOf2_64(Width) && DL.fitsInLegalInteger(Width);
1701 if (!Allowed ||
1702 !TTI.allowsMisalignedMemoryAccesses(Ctx, Width,
1703 First.Store->getPointerAddressSpace(),
1704 First.Store->getAlign(), &Fast) ||
1705 !Fast)
1706 return false;
1707
1708 // Generate the combined store.
1709 IRBuilder<> Builder(First.Store);
1710 Type *NewTy = Type::getIntNTy(Ctx, Width);
1711 Value *Val = First.Val;
1712 if (First.ValOffset != 0)
1713 Val = Builder.CreateLShr(Val, First.ValOffset);
1714 Val = Builder.CreateZExtOrTrunc(Val, NewTy);
1715 StoreInst *Store = Builder.CreateAlignedStore(
1716 Val, First.Store->getPointerOperand(), First.Store->getAlign());
1717
1718 // Merge various metadata onto the new store.
1719 AAMDNodes AATags = First.Store->getAAMetadata();
1720 SmallVector<Instruction *> Stores = {First.Store};
1721 Stores.reserve(Parts.size());
1722 SmallVector<DebugLoc> DbgLocs = {First.Store->getDebugLoc()};
1723 DbgLocs.reserve(Parts.size());
1724 for (const PartStore &Part : drop_begin(Parts)) {
1725 AATags = AATags.concat(Part.Store->getAAMetadata());
1726 Stores.push_back(Part.Store);
1727 DbgLocs.push_back(Part.Store->getDebugLoc());
1728 }
1729 Store->setAAMetadata(AATags);
1730 Store->mergeDIAssignID(Stores);
1731 Store->setDebugLoc(DebugLoc::getMergedLocations(DbgLocs));
1732
1733 // Remove the old stores.
1734 for (const PartStore &Part : Parts)
1735 Part.Store->eraseFromParent();
1736
1737 return true;
1738}
1739
1742 if (Parts.size() < 2)
1743 return false;
1744
1745 // We now have multiple parts of the same value stored to the same pointer.
1746 // Sort the parts by pointer offset, and make sure they are consistent with
1747 // the value offsets. Also check that the value is fully covered without
1748 // overlaps.
1749 bool Changed = false;
1750 llvm::sort(Parts);
1751 int64_t LastEndOffsetFromFirst = 0;
1752 const PartStore *First = &Parts[0];
1753 for (const PartStore &Part : Parts) {
1754 APInt PtrOffsetFromFirst = Part.PtrOffset - First->PtrOffset;
1755 int64_t ValOffsetFromFirst = Part.ValOffset - First->ValOffset;
1756 if (PtrOffsetFromFirst * 8 != ValOffsetFromFirst ||
1757 LastEndOffsetFromFirst != ValOffsetFromFirst) {
1759 LastEndOffsetFromFirst, DL, TTI);
1760 First = &Part;
1761 LastEndOffsetFromFirst = Part.ValWidth;
1762 continue;
1763 }
1764
1765 LastEndOffsetFromFirst = ValOffsetFromFirst + Part.ValWidth;
1766 }
1767
1769 LastEndOffsetFromFirst, DL, TTI);
1770 return Changed;
1771}
1772
1775 // FIXME: Add big endian support.
1776 if (DL.isBigEndian())
1777 return false;
1778
1779 BatchAAResults BatchAA(AA);
1781 bool MadeChange = false;
1782 for (Instruction &I : make_early_inc_range(BB)) {
1783 if (std::optional<PartStore> Part = matchPartStore(I, DL)) {
1784 if (Parts.empty() || Part->isCompatibleWith(Parts[0])) {
1785 Parts.push_back(std::move(*Part));
1786 continue;
1787 }
1788
1789 MadeChange |= mergePartStores(Parts, DL, TTI);
1790 Parts.clear();
1791 Parts.push_back(std::move(*Part));
1792 continue;
1793 }
1794
1795 if (Parts.empty())
1796 continue;
1797
1798 if (I.mayThrow() ||
1799 (I.mayReadOrWriteMemory() &&
1801 &I, MemoryLocation::getBeforeOrAfter(Parts[0].PtrBase))))) {
1802 MadeChange |= mergePartStores(Parts, DL, TTI);
1803 Parts.clear();
1804 continue;
1805 }
1806 }
1807
1808 MadeChange |= mergePartStores(Parts, DL, TTI);
1809 return MadeChange;
1810}
1811
1812/// Combine away instructions providing they are still equivalent when compared
1813/// against 0. i.e do they have any bits set.
1815 auto *I = dyn_cast<Instruction>(V);
1816 if (!I || I->getOpcode() != Instruction::Or || !I->hasOneUse())
1817 return nullptr;
1818
1819 Value *A;
1820
1821 // Look deeper into the chain of or's, combining away shl (so long as they are
1822 // nuw or nsw).
1823 Value *Op0 = I->getOperand(0);
1824 if (match(Op0, m_CombineOr(m_NSWShl(m_Value(A), m_Value()),
1825 m_NUWShl(m_Value(A), m_Value()))))
1826 Op0 = A;
1827 else if (auto *NOp = optimizeShiftInOrChain(Op0, Builder))
1828 Op0 = NOp;
1829
1830 Value *Op1 = I->getOperand(1);
1831 if (match(Op1, m_CombineOr(m_NSWShl(m_Value(A), m_Value()),
1832 m_NUWShl(m_Value(A), m_Value()))))
1833 Op1 = A;
1834 else if (auto *NOp = optimizeShiftInOrChain(Op1, Builder))
1835 Op1 = NOp;
1836
1837 if (Op0 != I->getOperand(0) || Op1 != I->getOperand(1))
1838 return Builder.CreateOr(Op0, Op1);
1839 return nullptr;
1840}
1841
1844 const DominatorTree &DT) {
1846 Value *Op0;
1847 if (!match(&I, m_ICmp(Pred, m_Value(Op0), m_Zero())) ||
1849 return false;
1850
1851 // If the chain or or's matches a load, combine to that before attempting to
1852 // remove shifts.
1853 if (auto OpI = dyn_cast<Instruction>(Op0))
1854 if (OpI->getOpcode() == Instruction::Or)
1855 if (foldConsecutiveLoads(*OpI, DL, TTI, AA, DT))
1856 return true;
1857
1858 IRBuilder<> Builder(&I);
1859 // icmp eq/ne or(shl(a), b), 0 -> icmp eq/ne or(a, b), 0
1860 if (auto *Res = optimizeShiftInOrChain(Op0, Builder)) {
1861 I.replaceAllUsesWith(Builder.CreateICmp(Pred, Res, I.getOperand(1)));
1862 return true;
1863 }
1864
1865 return false;
1866}
1867
1868// Calculate GEP Stride and accumulated const ModOffset. Return Stride and
1869// ModOffset
1870static std::pair<APInt, APInt>
1872 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
1873 std::optional<APInt> Stride;
1874 APInt ModOffset(BW, 0);
1875 // Return a minimum gep stride, greatest common divisor of consective gep
1876 // index scales(c.f. Bézout's identity).
1877 while (auto *GEP = dyn_cast<GEPOperator>(PtrOp)) {
1879 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset))
1880 break;
1881
1882 for (auto [V, Scale] : VarOffsets) {
1883 // Only keep a power of two factor for non-inbounds
1884 if (!GEP->hasNoUnsignedSignedWrap())
1885 Scale = APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
1886
1887 if (!Stride)
1888 Stride = Scale;
1889 else
1890 Stride = APIntOps::GreatestCommonDivisor(*Stride, Scale);
1891 }
1892
1893 PtrOp = GEP->getPointerOperand();
1894 }
1895
1896 // Check whether pointer arrives back at Global Variable via at least one GEP.
1897 // Even if it doesn't, we can check by alignment.
1898 if (!isa<GlobalVariable>(PtrOp) || !Stride)
1899 return {APInt(BW, 1), APInt(BW, 0)};
1900
1901 // In consideration of signed GEP indices, non-negligible offset become
1902 // remainder of division by minimum GEP stride.
1903 ModOffset = ModOffset.srem(*Stride);
1904 if (ModOffset.isNegative())
1905 ModOffset += *Stride;
1906
1907 return {*Stride, ModOffset};
1908}
1909
1910/// If C is a constant patterned array and all valid loaded results for given
1911/// alignment are same to a constant, return that constant.
1913 auto *LI = dyn_cast<LoadInst>(&I);
1914 if (!LI || LI->isVolatile())
1915 return false;
1916
1917 // We can only fold the load if it is from a constant global with definitive
1918 // initializer. Skip expensive logic if this is not the case.
1919 auto *PtrOp = LI->getPointerOperand();
1921 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1922 return false;
1923
1924 // Bail for large initializers in excess of 4K to avoid too many scans.
1925 Constant *C = GV->getInitializer();
1926 uint64_t GVSize = DL.getTypeAllocSize(C->getType());
1927 if (!GVSize || 4096 < GVSize)
1928 return false;
1929
1930 Type *LoadTy = LI->getType();
1931 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
1932 auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL);
1933
1934 // Any possible offset could be multiple of GEP stride. And any valid
1935 // offset is multiple of load alignment, so checking only multiples of bigger
1936 // one is sufficient to say results' equality.
1937 if (auto LA = LI->getAlign();
1938 LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
1939 ConstOffset = APInt(BW, 0);
1940 Stride = APInt(BW, LA.value());
1941 }
1942
1943 Constant *Ca = ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL);
1944 if (!Ca)
1945 return false;
1946
1947 unsigned E = GVSize - DL.getTypeStoreSize(LoadTy);
1948 for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
1949 if (Ca != ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL))
1950 return false;
1951
1952 I.replaceAllUsesWith(Ca);
1953
1954 return true;
1955}
1956
1957namespace {
1958class StrNCmpInliner {
1959public:
1960 StrNCmpInliner(CallInst *CI, LibFunc Func, DomTreeUpdater *DTU,
1961 const DataLayout &DL)
1962 : CI(CI), Func(Func), DTU(DTU), DL(DL) {}
1963
1964 bool optimizeStrNCmp();
1965
1966private:
1967 void inlineCompare(Value *LHS, StringRef RHS, uint64_t N, bool Swapped);
1968
1969 CallInst *CI;
1970 LibFunc Func;
1971 DomTreeUpdater *DTU;
1972 const DataLayout &DL;
1973};
1974
1975} // namespace
1976
1977/// First we normalize calls to strncmp/strcmp to the form of
1978/// compare(s1, s2, N), which means comparing first N bytes of s1 and s2
1979/// (without considering '\0').
1980///
1981/// Examples:
1982///
1983/// \code
1984/// strncmp(s, "a", 3) -> compare(s, "a", 2)
1985/// strncmp(s, "abc", 3) -> compare(s, "abc", 3)
1986/// strncmp(s, "a\0b", 3) -> compare(s, "a\0b", 2)
1987/// strcmp(s, "a") -> compare(s, "a", 2)
1988///
1989/// char s2[] = {'a'}
1990/// strncmp(s, s2, 3) -> compare(s, s2, 3)
1991///
1992/// char s2[] = {'a', 'b', 'c', 'd'}
1993/// strncmp(s, s2, 3) -> compare(s, s2, 3)
1994/// \endcode
1995///
1996/// We only handle cases where N and exactly one of s1 and s2 are constant.
1997/// Cases that s1 and s2 are both constant are already handled by the
1998/// instcombine pass.
1999///
2000/// We do not handle cases where N > StrNCmpInlineThreshold.
2001///
2002/// We also do not handles cases where N < 2, which are already
2003/// handled by the instcombine pass.
2004///
2005bool StrNCmpInliner::optimizeStrNCmp() {
2006 if (StrNCmpInlineThreshold < 2)
2007 return false;
2008
2010 return false;
2011
2012 Value *Str1P = CI->getArgOperand(0);
2013 Value *Str2P = CI->getArgOperand(1);
2014 // Should be handled elsewhere.
2015 if (Str1P == Str2P)
2016 return false;
2017
2018 StringRef Str1, Str2;
2019 bool HasStr1 = getConstantStringInfo(Str1P, Str1, /*TrimAtNul=*/false);
2020 bool HasStr2 = getConstantStringInfo(Str2P, Str2, /*TrimAtNul=*/false);
2021 if (HasStr1 == HasStr2)
2022 return false;
2023
2024 // Note that '\0' and characters after it are not trimmed.
2025 StringRef Str = HasStr1 ? Str1 : Str2;
2026 Value *StrP = HasStr1 ? Str2P : Str1P;
2027
2028 size_t Idx = Str.find('\0');
2030 if (Func == LibFunc_strncmp) {
2031 if (auto *ConstInt = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
2032 N = std::min(N, ConstInt->getZExtValue());
2033 else
2034 return false;
2035 }
2036 // Now N means how many bytes we need to compare at most.
2037 if (N > Str.size() || N < 2 || N > StrNCmpInlineThreshold)
2038 return false;
2039
2040 // Cases where StrP has two or more dereferenceable bytes might be better
2041 // optimized elsewhere.
2042 bool CanBeNull = false;
2043 if (StrP->getPointerDereferenceableBytes(DL, CanBeNull,
2044 /*CanBeFreed=*/nullptr) > 1)
2045 return false;
2046 inlineCompare(StrP, Str, N, HasStr1);
2047 return true;
2048}
2049
2050/// Convert
2051///
2052/// \code
2053/// ret = compare(s1, s2, N)
2054/// \endcode
2055///
2056/// into
2057///
2058/// \code
2059/// ret = (int)s1[0] - (int)s2[0]
2060/// if (ret != 0)
2061/// goto NE
2062/// ...
2063/// ret = (int)s1[N-2] - (int)s2[N-2]
2064/// if (ret != 0)
2065/// goto NE
2066/// ret = (int)s1[N-1] - (int)s2[N-1]
2067/// NE:
2068/// \endcode
2069///
2070/// CFG before and after the transformation:
2071///
2072/// (before)
2073/// BBCI
2074///
2075/// (after)
2076/// BBCI -> BBSubs[0] (sub,icmp) --NE-> BBNE -> BBTail
2077/// | ^
2078/// E |
2079/// | |
2080/// BBSubs[1] (sub,icmp) --NE-----+
2081/// ... |
2082/// BBSubs[N-1] (sub) ---------+
2083///
2084void StrNCmpInliner::inlineCompare(Value *LHS, StringRef RHS, uint64_t N,
2085 bool Swapped) {
2086 auto &Ctx = CI->getContext();
2087 IRBuilder<> B(*CI->getModule());
2088 // We want these instructions to be recognized as inlined instructions for the
2089 // compare call, but we don't have a source location for the definition of
2090 // that function, since we're generating that code now. Because the generated
2091 // code is a viable point for a memory access error, we make the pragmatic
2092 // choice here to directly use CI's location so that we have useful
2093 // attribution for the generated code.
2094 B.SetCurrentDebugLocation(CI->getDebugLoc());
2095
2096 BasicBlock *BBCI = CI->getParent();
2097 BasicBlock *BBTail =
2098 SplitBlock(BBCI, CI, DTU, nullptr, nullptr, BBCI->getName() + ".tail");
2099
2101 for (uint64_t I = 0; I < N; ++I)
2102 BBSubs.push_back(
2103 BasicBlock::Create(Ctx, "sub_" + Twine(I), BBCI->getParent(), BBTail));
2104 BasicBlock *BBNE = BasicBlock::Create(Ctx, "ne", BBCI->getParent(), BBTail);
2105
2106 cast<UncondBrInst>(BBCI->getTerminator())->setSuccessor(BBSubs[0]);
2107
2108 B.SetInsertPoint(BBNE);
2109 PHINode *Phi = B.CreatePHI(CI->getType(), N);
2110 B.CreateBr(BBTail);
2111
2112 Value *Base = LHS;
2113 for (uint64_t i = 0; i < N; ++i) {
2114 B.SetInsertPoint(BBSubs[i]);
2115 Value *VL =
2116 B.CreateZExt(B.CreateLoad(B.getInt8Ty(),
2117 B.CreatePtrAddWithUnsignedOffset(
2118 Base, i, "", GEPNoWrapFlags::inBounds())),
2119 CI->getType());
2120 Value *VR =
2121 ConstantInt::get(CI->getType(), static_cast<unsigned char>(RHS[i]));
2122 Value *Sub = Swapped ? B.CreateSub(VR, VL) : B.CreateSub(VL, VR);
2123 if (i < N - 1) {
2124 CondBrInst *CondBrInst = B.CreateCondBr(
2125 B.CreateICmpNE(Sub, ConstantInt::get(CI->getType(), 0)), BBNE,
2126 BBSubs[i + 1]);
2127
2128 Function *F = CI->getFunction();
2129 assert(F && "Instruction does not belong to a function!");
2130 std::optional<uint64_t> EC = F->getEntryCount();
2131 if (EC && *EC > 0)
2133 } else {
2134 B.CreateBr(BBNE);
2135 }
2136
2137 Phi->addIncoming(Sub, BBSubs[i]);
2138 }
2139
2140 CI->replaceAllUsesWith(Phi);
2141 CI->eraseFromParent();
2142
2143 if (DTU) {
2145 Updates.push_back({DominatorTree::Insert, BBCI, BBSubs[0]});
2146 for (uint64_t i = 0; i < N; ++i) {
2147 if (i < N - 1)
2148 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBSubs[i + 1]});
2149 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBNE});
2150 }
2151 Updates.push_back({DominatorTree::Insert, BBNE, BBTail});
2152 Updates.push_back({DominatorTree::Delete, BBCI, BBTail});
2153 DTU->applyUpdates(Updates);
2154 }
2155}
2156
2157/// Convert memchr with a small constant string into a switch
2159 const DataLayout &DL) {
2160 if (isa<Constant>(Call->getArgOperand(1)))
2161 return false;
2162
2163 StringRef Str;
2164 Value *Base = Call->getArgOperand(0);
2165 if (!getConstantStringInfo(Base, Str, /*TrimAtNul=*/false))
2166 return false;
2167
2168 uint64_t N = Str.size();
2169 if (auto *ConstInt = dyn_cast<ConstantInt>(Call->getArgOperand(2))) {
2170 uint64_t Val = ConstInt->getZExtValue();
2171 // Ignore the case that n is larger than the size of string.
2172 if (Val > N)
2173 return false;
2174 N = Val;
2175 } else
2176 return false;
2177
2179 return false;
2180
2181 BasicBlock *BB = Call->getParent();
2182 BasicBlock *BBNext = SplitBlock(BB, Call, DTU);
2183 IRBuilder<> IRB(BB);
2184 IRB.SetCurrentDebugLocation(Call->getDebugLoc());
2185 IntegerType *ByteTy = IRB.getInt8Ty();
2187 SwitchInst *SI = IRB.CreateSwitch(
2188 IRB.CreateTrunc(Call->getArgOperand(1), ByteTy), BBNext, N);
2189 // We can't know the precise weights here, as they would depend on the value
2190 // distribution of Call->getArgOperand(1). So we just mark it as "unknown".
2192 Type *IndexTy = DL.getIndexType(Call->getType());
2194
2195 BasicBlock *BBSuccess = BasicBlock::Create(
2196 Call->getContext(), "memchr.success", BB->getParent(), BBNext);
2197 IRB.SetInsertPoint(BBSuccess);
2198 PHINode *IndexPHI = IRB.CreatePHI(IndexTy, N, "memchr.idx");
2199 Value *FirstOccursLocation = IRB.CreateInBoundsPtrAdd(Base, IndexPHI);
2200 IRB.CreateBr(BBNext);
2201 if (DTU)
2202 Updates.push_back({DominatorTree::Insert, BBSuccess, BBNext});
2203
2205 for (uint64_t I = 0; I < N; ++I) {
2206 ConstantInt *CaseVal =
2207 ConstantInt::get(ByteTy, static_cast<unsigned char>(Str[I]));
2208 if (!Cases.insert(CaseVal).second)
2209 continue;
2210
2211 BasicBlock *BBCase = BasicBlock::Create(Call->getContext(), "memchr.case",
2212 BB->getParent(), BBSuccess);
2213 SI->addCase(CaseVal, BBCase);
2214 IRB.SetInsertPoint(BBCase);
2215 IndexPHI->addIncoming(ConstantInt::get(IndexTy, I), BBCase);
2216 IRB.CreateBr(BBSuccess);
2217 if (DTU) {
2218 Updates.push_back({DominatorTree::Insert, BB, BBCase});
2219 Updates.push_back({DominatorTree::Insert, BBCase, BBSuccess});
2220 }
2221 }
2222
2223 PHINode *PHI =
2224 PHINode::Create(Call->getType(), 2, Call->getName(), BBNext->begin());
2225 PHI->addIncoming(Constant::getNullValue(Call->getType()), BB);
2226 PHI->addIncoming(FirstOccursLocation, BBSuccess);
2227
2228 Call->replaceAllUsesWith(PHI);
2229 Call->eraseFromParent();
2230
2231 if (DTU)
2232 DTU->applyUpdates(Updates);
2233
2234 return true;
2235}
2236
2239 DominatorTree &DT, const DataLayout &DL,
2240 bool &MadeCFGChange) {
2241
2242 auto *CI = dyn_cast<CallInst>(&I);
2243 if (!CI || CI->isNoBuiltin())
2244 return false;
2245
2246 Function *CalledFunc = CI->getCalledFunction();
2247 if (!CalledFunc)
2248 return false;
2249
2250 LibFunc LF = TLI.getLibFunc(*CalledFunc);
2251 if (!isLibFuncEmittable(CI->getModule(), &TLI, LF))
2252 return false;
2253
2254 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
2255
2256 switch (LF) {
2257 case LibFunc_sqrt:
2258 case LibFunc_sqrtf:
2259 case LibFunc_sqrtl:
2260 return foldSqrt(CI, LF, TTI, TLI, AC, DT);
2261 case LibFunc_strcmp:
2262 case LibFunc_strncmp:
2263 if (StrNCmpInliner(CI, LF, &DTU, DL).optimizeStrNCmp()) {
2264 MadeCFGChange = true;
2265 return true;
2266 }
2267 break;
2268 case LibFunc_memchr:
2269 if (foldMemChr(CI, &DTU, DL)) {
2270 MadeCFGChange = true;
2271 return true;
2272 }
2273 break;
2274 default:;
2275 }
2276 return false;
2277}
2278
2279/// Match high part of long multiplication.
2280///
2281/// Considering a multiply made up of high and low parts, we can split the
2282/// multiply into:
2283/// x * y == (xh*T + xl) * (yh*T + yl)
2284/// where xh == x>>32 and xl == x & 0xffffffff. T = 2^32.
2285/// This expands to
2286/// xh*yh*T*T + xh*yl*T + xl*yh*T + xl*yl
2287/// which can be drawn as
2288/// [ xh*yh ]
2289/// [ xh*yl ]
2290/// [ xl*yh ]
2291/// [ xl*yl ]
2292/// We are looking for the "high" half, which is xh*yh + xh*yl>>32 + xl*yh>>32 +
2293/// some carrys. The carry makes this difficult and there are multiple ways of
2294/// representing it. The ones we attempt to support here are:
2295/// Carry: xh*yh + carry + lowsum
2296/// carry = lowsum < xh*yl ? 0x1000000 : 0
2297/// lowsum = xh*yl + xl*yh + (xl*yl>>32)
2298/// Ladder: xh*yh + c2>>32 + c3>>32
2299/// c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh
2300/// or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xl*yh
2301/// Carry4: xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32
2302/// crosssum = xh*yl + xl*yh
2303/// carry = crosssum < xh*yl ? 0x1000000 : 0
2304/// Ladder4: xh*yh + (xl*yh)>>32 + (xh*yl)>>32 + low>>32;
2305/// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff
2306///
2307/// They all start by matching xh*yh + 2 or 3 other operands. The bottom of the
2308/// tree is xh*yh, xh*yl, xl*yh and xl*yl.
2310 Type *Ty = I.getType();
2311 if (!Ty->isIntOrIntVectorTy())
2312 return false;
2313
2314 unsigned BitWidth = Ty->getScalarSizeInBits();
2316 if (BitWidth % 2 != 0)
2317 return false;
2318
2319 auto CreateMulHigh = [&](Value *X, Value *Y) {
2320 IRBuilder<> Builder(&I);
2321 Type *NTy = Ty->getWithNewBitWidth(BitWidth * 2);
2322 Value *XExt = Builder.CreateZExt(X, NTy);
2323 Value *YExt = Builder.CreateZExt(Y, NTy);
2324 Value *Mul = Builder.CreateMul(XExt, YExt, "", /*HasNUW=*/true);
2325 Value *High = Builder.CreateLShr(Mul, BitWidth);
2326 Value *Res = Builder.CreateTrunc(High, Ty, "", /*HasNUW=*/true);
2327 Res->takeName(&I);
2328 I.replaceAllUsesWith(Res);
2329 LLVM_DEBUG(dbgs() << "Created long multiply from parts of " << *X << " and "
2330 << *Y << "\n");
2331 return true;
2332 };
2333
2334 // Common check routines for X_lo*Y_lo and X_hi*Y_lo
2335 auto CheckLoLo = [&](Value *XlYl, Value *X, Value *Y) {
2336 return match(XlYl, m_c_Mul(m_And(m_Specific(X), m_SpecificInt(LowMask)),
2337 m_And(m_Specific(Y), m_SpecificInt(LowMask))));
2338 };
2339 auto CheckHiLo = [&](Value *XhYl, Value *X, Value *Y) {
2340 return match(XhYl,
2342 m_And(m_Specific(Y), m_SpecificInt(LowMask))));
2343 };
2344
2345 auto FoldMulHighCarry = [&](Value *X, Value *Y, Instruction *Carry,
2346 Instruction *B) {
2347 // Looking for LowSum >> 32 and carry (select)
2348 if (Carry->getOpcode() != Instruction::Select)
2349 std::swap(Carry, B);
2350
2351 // Carry = LowSum < XhYl ? 0x100000000 : 0
2352 Value *LowSum, *XhYl;
2353 if (!match(Carry,
2356 m_Value(XhYl))),
2358 m_Zero()))))
2359 return false;
2360
2361 // XhYl can be Xh*Yl or Xl*Yh
2362 if (!CheckHiLo(XhYl, X, Y)) {
2363 if (CheckHiLo(XhYl, Y, X))
2364 std::swap(X, Y);
2365 else
2366 return false;
2367 }
2368 if (XhYl->hasNUsesOrMore(3))
2369 return false;
2370
2371 // B = LowSum >> 32
2372 if (!match(B, m_OneUse(m_LShr(m_Specific(LowSum),
2373 m_SpecificInt(BitWidth / 2)))) ||
2374 LowSum->hasNUsesOrMore(3))
2375 return false;
2376
2377 // LowSum = XhYl + XlYh + XlYl>>32
2378 Value *XlYh, *XlYl;
2379 auto XlYlHi = m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2));
2380 if (!match(LowSum,
2381 m_c_Add(m_Specific(XhYl),
2382 m_OneUse(m_c_Add(m_OneUse(m_Value(XlYh)), XlYlHi)))) &&
2383 !match(LowSum, m_c_Add(m_OneUse(m_Value(XlYh)),
2384 m_OneUse(m_c_Add(m_Specific(XhYl), XlYlHi)))) &&
2385 !match(LowSum,
2386 m_c_Add(XlYlHi, m_OneUse(m_c_Add(m_Specific(XhYl),
2387 m_OneUse(m_Value(XlYh)))))))
2388 return false;
2389
2390 // Check XlYl and XlYh
2391 if (!CheckLoLo(XlYl, X, Y))
2392 return false;
2393 if (!CheckHiLo(XlYh, Y, X))
2394 return false;
2395
2396 return CreateMulHigh(X, Y);
2397 };
2398
2399 auto FoldMulHighLadder = [&](Value *X, Value *Y, Instruction *A,
2400 Instruction *B) {
2401 // xh*yh + c2>>32 + c3>>32
2402 // c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh
2403 // or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xh*yl
2404 Value *XlYh, *XhYl, *XlYl, *C2, *C3;
2405 // Strip off the two expected shifts.
2406 if (!match(A, m_LShr(m_Value(C2), m_SpecificInt(BitWidth / 2))) ||
2408 return false;
2409
2410 if (match(C3, m_c_Add(m_Add(m_Value(), m_Value()), m_Value())))
2411 std::swap(C2, C3);
2412 // Try to match c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32)
2413 if (match(C2,
2415 m_Value(XlYh)),
2416 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2)))) ||
2418 m_LShr(m_Value(XlYl),
2419 m_SpecificInt(BitWidth / 2))),
2420 m_Value(XlYh))) ||
2422 m_SpecificInt(BitWidth / 2)),
2423 m_Value(XlYh)),
2424 m_And(m_Specific(C3), m_SpecificInt(LowMask))))) {
2425 XhYl = C3;
2426 } else {
2427 // Match c3 = c2&0xffffffff + xl*yh
2428 if (!match(C3, m_c_Add(m_And(m_Specific(C2), m_SpecificInt(LowMask)),
2429 m_Value(XlYh))))
2430 std::swap(C2, C3);
2431 if (!match(C3, m_c_Add(m_OneUse(
2432 m_And(m_Specific(C2), m_SpecificInt(LowMask))),
2433 m_Value(XlYh))) ||
2434 !C3->hasOneUse() || C2->hasNUsesOrMore(3))
2435 return false;
2436
2437 // Match c2 = xh*yl + (xl*yl >> 32)
2438 if (!match(C2, m_c_Add(m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2)),
2439 m_Value(XhYl))))
2440 return false;
2441 }
2442
2443 // Match XhYl and XlYh - they can appear either way around.
2444 if (!CheckHiLo(XlYh, Y, X))
2445 std::swap(XlYh, XhYl);
2446 if (!CheckHiLo(XlYh, Y, X))
2447 return false;
2448 if (!CheckHiLo(XhYl, X, Y))
2449 return false;
2450 if (!CheckLoLo(XlYl, X, Y))
2451 return false;
2452
2453 return CreateMulHigh(X, Y);
2454 };
2455
2456 auto FoldMulHighLadder4 = [&](Value *X, Value *Y, Instruction *A,
2458 /// Ladder4: xh*yh + (xl*yh)>>32 + (xh+yl)>>32 + low>>32;
2459 /// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff
2460
2461 // Find A = Low >> 32 and B/C = XhYl>>32, XlYh>>32.
2462 auto ShiftAdd =
2464 if (!match(A, ShiftAdd))
2465 std::swap(A, B);
2466 if (!match(A, ShiftAdd))
2467 std::swap(A, C);
2468 Value *Low;
2470 return false;
2471
2472 // Match B == XhYl>>32 and C == XlYh>>32
2473 Value *XhYl, *XlYh;
2474 if (!match(B, m_LShr(m_Value(XhYl), m_SpecificInt(BitWidth / 2))) ||
2475 !match(C, m_LShr(m_Value(XlYh), m_SpecificInt(BitWidth / 2))))
2476 return false;
2477 if (!CheckHiLo(XhYl, X, Y))
2478 std::swap(XhYl, XlYh);
2479 if (!CheckHiLo(XhYl, X, Y) || XhYl->hasNUsesOrMore(3))
2480 return false;
2481 if (!CheckHiLo(XlYh, Y, X) || XlYh->hasNUsesOrMore(3))
2482 return false;
2483
2484 // Match Low as XlYl>>32 + XhYl&0xffffffff + XlYh&0xffffffff
2485 Value *XlYl;
2486 if (!match(
2487 Low,
2488 m_c_Add(
2490 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))),
2491 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))))),
2492 m_OneUse(
2493 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))) &&
2494 !match(
2495 Low,
2496 m_c_Add(
2498 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))),
2499 m_OneUse(
2500 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))),
2501 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))))) &&
2502 !match(
2503 Low,
2504 m_c_Add(
2506 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))),
2507 m_OneUse(
2508 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))),
2509 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))))))
2510 return false;
2511 if (!CheckLoLo(XlYl, X, Y))
2512 return false;
2513
2514 return CreateMulHigh(X, Y);
2515 };
2516
2517 auto FoldMulHighCarry4 = [&](Value *X, Value *Y, Instruction *Carry,
2519 // xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32
2520 // crosssum = xh*yl+xl*yh
2521 // carry = crosssum < xh*yl ? 0x1000000 : 0
2522 if (Carry->getOpcode() != Instruction::Select)
2523 std::swap(Carry, B);
2524 if (Carry->getOpcode() != Instruction::Select)
2525 std::swap(Carry, C);
2526
2527 // Carry = CrossSum < XhYl ? 0x100000000 : 0
2528 Value *CrossSum, *XhYl;
2529 if (!match(Carry,
2532 m_Value(CrossSum), m_Value(XhYl))),
2534 m_Zero()))))
2535 return false;
2536
2537 if (!match(B, m_LShr(m_Specific(CrossSum), m_SpecificInt(BitWidth / 2))))
2538 std::swap(B, C);
2539 if (!match(B, m_LShr(m_Specific(CrossSum), m_SpecificInt(BitWidth / 2))))
2540 return false;
2541
2542 Value *XlYl, *LowAccum;
2543 if (!match(C, m_LShr(m_Value(LowAccum), m_SpecificInt(BitWidth / 2))) ||
2544 !match(LowAccum, m_c_Add(m_OneUse(m_LShr(m_Value(XlYl),
2545 m_SpecificInt(BitWidth / 2))),
2546 m_OneUse(m_And(m_Specific(CrossSum),
2547 m_SpecificInt(LowMask))))) ||
2548 LowAccum->hasNUsesOrMore(3))
2549 return false;
2550 if (!CheckLoLo(XlYl, X, Y))
2551 return false;
2552
2553 if (!CheckHiLo(XhYl, X, Y))
2554 std::swap(X, Y);
2555 if (!CheckHiLo(XhYl, X, Y))
2556 return false;
2557 Value *XlYh;
2558 if (!match(CrossSum, m_c_Add(m_Specific(XhYl), m_OneUse(m_Value(XlYh)))) ||
2559 !CheckHiLo(XlYh, Y, X) || CrossSum->hasNUsesOrMore(4) ||
2560 XhYl->hasNUsesOrMore(3))
2561 return false;
2562
2563 return CreateMulHigh(X, Y);
2564 };
2565
2566 // X and Y are the two inputs, A, B and C are other parts of the pattern
2567 // (crosssum>>32, carry, etc).
2568 Value *X, *Y;
2569 Instruction *A, *B, *C;
2570 auto HiHi = m_OneUse(m_Mul(m_LShr(m_Value(X), m_SpecificInt(BitWidth / 2)),
2573 m_Instruction(B))))) ||
2575 m_OneUse(m_c_Add(HiHi, m_Instruction(B)))))) &&
2576 A->hasOneUse() && B->hasOneUse())
2577 if (FoldMulHighCarry(X, Y, A, B) || FoldMulHighLadder(X, Y, A, B))
2578 return true;
2579
2580 if ((match(&I, m_c_Add(HiHi, m_OneUse(m_c_Add(
2583 m_Instruction(C))))))) ||
2587 m_Instruction(C))))))) ||
2591 m_OneUse(m_c_Add(HiHi, m_Instruction(C))))))) ||
2594 m_Instruction(C)))))) &&
2595 A->hasOneUse() && B->hasOneUse() && C->hasOneUse())
2596 return FoldMulHighCarry4(X, Y, A, B, C) ||
2597 FoldMulHighLadder4(X, Y, A, B, C);
2598
2599 return false;
2600}
2601
2602/// Guard a memset whose nonconstant length is known to be in [0, 1].
2603/// Inserts a conditional branch around the memset and specialises the
2604/// executed path to a one-byte store.
2608 bool &MadeCFGChange) {
2609 auto *MI = dyn_cast<MemSetInst>(&I);
2610 if (!MI || isa<ConstantInt>(MI->getLength()))
2611 return false;
2612
2613 SimplifyQuery SQ(DL, &TLI, &DT, &AC, MI);
2614 KnownBits KnownLen = computeKnownBits(MI->getLength(), SQ);
2615 if (!KnownLen.getMaxValue().isOne())
2616 return false;
2617
2618 uint64_t TotalCount;
2620 I, InstrProfValueKind::IPVK_MemOPSize, 2, TotalCount);
2621 std::optional<uint64_t> ZeroCount = std::nullopt;
2622 std::optional<uint64_t> OneCount = std::nullopt;
2623 for (const auto [MemOpSize, SizeFrequency] : MemsetVPMetadata) {
2624 if (MemOpSize == 0)
2625 ZeroCount = SizeFrequency;
2626 else if (MemOpSize == 1)
2627 OneCount = SizeFrequency;
2628 }
2629 // If we only have one value in the profile, we assume that the other is zero.
2630 if (MemsetVPMetadata.size() == 1) {
2631 if (ZeroCount.has_value())
2632 OneCount = 0;
2633 else if (OneCount.has_value())
2634 ZeroCount = 0;
2635 }
2636
2637 BasicBlock *HeadBlock = MI->getIterator()->getParent();
2638 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2639 IRBuilder<> B(MI);
2640 Value *IsNonZero = B.CreateIsNotNull(MI->getLength(), "memset.notzero");
2642 IsNonZero, MI->getIterator(), /*Unreachable=*/false,
2643 /*BranchWeights=*/nullptr, &DTU);
2644
2645 Instruction &IsNonZeroBranch = *HeadBlock->getTerminator();
2646 if (!ProfcheckDisableMetadataFixes && OneCount.has_value() &&
2647 ZeroCount.has_value() && (*OneCount + *ZeroCount > 0))
2648 setFittedBranchWeights(IsNonZeroBranch, {*OneCount, *ZeroCount}, false);
2649 else
2651
2652 IRBuilder<> StoreBuilder(ThenTerm);
2653 StoreInst *Store = StoreBuilder.CreateAlignedStore(
2654 MI->getValue(), MI->getDest(), MI->getDestAlign(), MI->isVolatile());
2655 Store->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
2656 MI->eraseFromParent();
2657 ++NumMemSetsGuarded;
2658 MadeCFGChange = true;
2659 return true;
2660}
2661
2662/// This is the entry point for folds that could be implemented in regular
2663/// InstCombine, but they are separated because they are not expected to
2664/// occur frequently and/or have more than a constant-length pattern match.
2668 AssumptionCache &AC, bool &MadeCFGChange) {
2669 bool MadeChange = false;
2670 for (BasicBlock &BB : F) {
2671 // Ignore unreachable basic blocks.
2672 if (!DT.isReachableFromEntry(&BB))
2673 continue;
2674
2675 const DataLayout &DL = F.getDataLayout();
2676
2677 // Walk the block backwards for efficiency. We're matching a chain of
2678 // use->defs, so we're more likely to succeed by starting from the bottom.
2679 // Also, we want to avoid matching partial patterns.
2680 // TODO: It would be more efficient if we removed dead instructions
2681 // iteratively in this loop rather than waiting until the end.
2683 switch (I.getOpcode()) {
2684 case Instruction::And:
2685 MadeChange |= foldAnyOrAllBitsSet(I);
2686 MadeChange |= tryToRecognizePopCount2n3(I);
2687 break;
2688 case Instruction::Trunc:
2689 MadeChange |= foldAnyOrAllBitsSet(I);
2690 break;
2691 case Instruction::PHI:
2692 MadeChange |= foldGuardedFunnelShift(I, DT);
2693 break;
2694 case Instruction::Select:
2695 MadeChange |= foldSelectSplitCTLZCTTZ(I);
2696 break;
2697 case Instruction::LShr:
2698 MadeChange |= tryToRecognizePopCount(I);
2699 break;
2700 case Instruction::Add:
2701 MadeChange |= tryToRecognizePopCount1(I);
2702 MadeChange |= foldMulHigh(I);
2703 break;
2704 case Instruction::Load:
2705 MadeChange |= tryToRecognizeTableBasedPatterns(I, DL, TTI);
2706 MadeChange |= foldPatternedLoads(I, DL);
2707 break;
2708 case Instruction::Or:
2709 MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT);
2710 break;
2711 case Instruction::ICmp:
2712 MadeChange |= foldICmpOrChain(I, DL, TTI, AA, DT);
2713 break;
2714 case Instruction::Call:
2715 MadeChange |= tryToFPToSat(I, TTI);
2716 // These folds can erase the instruction `I`, so they need to be called
2717 // at the end of this sequence.
2718 if (foldLibCalls(I, TTI, TLI, AC, DT, DL, MadeCFGChange)) {
2719 MadeChange = true;
2720 break;
2721 }
2722 if (foldMemSetZeroOrOneLength(I, DL, TLI, AC, DT, MadeCFGChange))
2723 MadeChange = true;
2724 break;
2725 default:;
2726 }
2727 }
2728
2729 // Do this separately to avoid redundantly scanning stores multiple times.
2730 MadeChange |= foldConsecutiveStores(BB, DL, TTI, AA);
2731 }
2732
2733 // We're done with transforms, so remove dead instructions.
2734 if (MadeChange)
2735 for (BasicBlock &BB : F)
2737
2738 return MadeChange;
2739}
2740
2741/// This is the entry point for all transforms. Pass manager differences are
2742/// handled in the callers of this function.
2745 AliasAnalysis &AA, bool &MadeCFGChange) {
2746 bool MadeChange = false;
2747 const DataLayout &DL = F.getDataLayout();
2748 TruncInstCombine TIC(AC, TLI, DL, DT);
2749 MadeChange |= TIC.run(F);
2750 MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA, AC, MadeCFGChange);
2751 return MadeChange;
2752}
2753
2756 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2757 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2758 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2759 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
2760 auto &AA = AM.getResult<AAManager>(F);
2761 bool MadeCFGChange = false;
2762 if (!runImpl(F, AC, TTI, TLI, DT, AA, MadeCFGChange)) {
2763 // No changes, all analyses are preserved.
2764 return PreservedAnalyses::all();
2765 }
2766 // Mark all the analyses that instcombine updates as preserved.
2768 if (MadeCFGChange)
2770 else
2772 return PA;
2773}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void replaceWithPopCount(Instruction &I, Value *Root)
Helper function to replace an instruction with a popcount intrinsic.
static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL, TargetTransformInfo &TTI)
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 isLog2Table(Constant *Table, const APInt &Mul, const APInt &Shift, Type *AccessTy, unsigned InputBits, const APInt &GEPIdxFactor, const DataLayout &DL)
static bool tryToRecognizeTableBasedLowBitsMask(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL)
static bool foldAnyOrAllBitsSet(Instruction &I)
Match patterns that correspond to "any-bits-set" and "all-bits-set".
static cl::opt< unsigned > MemChrInlineThreshold("memchr-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string to " "inline a memchr call."))
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 foldSelectSplitCTLZ(Instruction &I, Value *HiPart, Value *LoResult, Value *HiResult, Type *HalfTy)
Same as foldSelectSplitCTTZ but for leading zeros (ctlz).
static bool foldMemChr(CallInst *Call, DomTreeUpdater *DTU, const DataLayout &DL)
Convert memchr with a small constant string into a switch.
static Value * matchPopCountBytes(Value *V, unsigned Len, const DataLayout &DL)
static bool tryToRecognizePopCount2n3(Instruction &I)
static Value * optimizeShiftInOrChain(Value *V, IRBuilder<> &Builder)
Combine away instructions providing they are still equivalent when compared against 0.
static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool tryToRecognizeTableBasedPatterns(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI)
static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT)
Match a pattern for a bitwise funnel/rotate operation that partially guards against undefined behavio...
static bool mergePartStores(SmallVectorImpl< PartStore > &Parts, const DataLayout &DL, TargetTransformInfo &TTI)
static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, AliasAnalysis &AA, bool IsRoot=false)
static bool mergeConsecutivePartStores(ArrayRef< PartStore > Parts, unsigned Width, const DataLayout &DL, TargetTransformInfo &TTI)
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 tryToRecognizeTableBasedCttz(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL)
static bool foldSelectSplitCTLZCTTZ(Instruction &I)
Common entry point for folding select-based split cttz/ctlz patterns.
static bool tryToRecognizePopCount1(Instruction &I)
static bool foldICmpOrChain(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift, const APInt &AndMask, Type *AccessTy, unsigned InputBits, const APInt &GEPIdxFactor, const DataLayout &DL)
static std::optional< PartStore > matchPartStore(Instruction &I, const DataLayout &DL)
static bool foldConsecutiveStores(BasicBlock &BB, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA)
static std::pair< APInt, APInt > getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL)
static bool foldSelectSplitCTTZ(Instruction &I, Value *LoTrunc, Value *HiResult, Value *LoResult, Type *HalfTy)
Try to fold a select-based split cttz pattern into a single full-width cttz.
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 tryToRecognizeTableBasedCtpop(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool foldMemSetZeroOrOneLength(Instruction &I, const DataLayout &DL, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, bool &MadeCFGChange)
Guard a memset whose nonconstant length is known to be in [0, 1].
static bool foldLibCalls(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, const DataLayout &DL, bool &MadeCFGChange)
static bool foldMulHigh(Instruction &I)
Match high part of long multiplication.
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.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
IRTranslator LLVM IR MI
static Instruction * matchFunnelShift(Instruction &Or, InstCombinerImpl &IC)
Match UB-safe variants of the funnel shift intrinsic.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t High
This file contains the declarations for profiling metadata utility functions.
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
unsigned countTrailingOnes() const
Definition APInt.h:1682
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
bool equalsInt(uint64_t V) const
A helper method that can be used to determine if the constant contained within is equal to a constant...
Definition Constants.h:194
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:173
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static GEPNoWrapFlags inBounds()
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1212
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition IRBuilder.h:1241
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2105
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isSimple() const
static LocationSize precise(uint64_t Value)
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
size_type size() const
Definition MapVector.h:59
std::pair< KeyT, ValueT > & front()
Definition MapVector.h:82
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Basic
The cost of a typical 'add' instruction.
bool run(Function &F)
Perform TruncInst pattern optimization on given function.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:150
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
LLVM_ABI 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:913
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
ShiftLike_match< LHS, Instruction::LShr > m_LShrOrSelf(const LHS &L, uint64_t &R)
Matches lshr L, ConstShAmt or L itself (R will be set to zero in this case).
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, CastInst >, OpTy > m_CastOrSelf(const OpTy &Op)
Matches any cast or self. Used to ignore casts.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< 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()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
ShiftLike_match< LHS, Instruction::Shl > m_ShlOrSelf(const LHS &L, uint64_t &R)
Matches shl L, ConstShAmt or L itself (R will be set to zero in this case).
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
specific_bbval m_SpecificBB(BasicBlock *BB)
Match a specific basic block value.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, FPToSIInst > m_FPToSI(const OpTy &Op)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
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::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
auto m_Cttz(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI 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.
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI 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:716
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI 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...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
@ Fast
Assign the register banks as fast as possible (default).
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset.
bool operator<(const PartStore &Other) const
bool isCompatibleWith(const PartStore &Other) const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344