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