LLVM 23.0.0git
ExpandIRInsts.cpp
Go to the documentation of this file.
1//===--- ExpandIRInsts.cpp - Expand IR instructions -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8// This pass expands certain instructions at the IR level.
9//
10// The following expansions are implemented:
11// - Expansion of ‘fptoui .. to’, ‘fptosi .. to’, ‘uitofp .. to’, ‘sitofp
12// .. to’ instructions with a bitwidth above a threshold. This is
13// useful for targets like x86_64 that cannot lower fp convertions
14// with more than 128 bits.
15//
16// - Expansion of ‘frem‘ for types MVT::f16, MVT::f32, and MVT::f64 for
17// targets which use "Expand" as the legalization action for the
18// corresponding type.
19//
20// - Expansion of ‘udiv‘, ‘sdiv‘, ‘urem‘, and ‘srem‘ instructions with
21// a bitwidth above a threshold into a call to auto-generated
22// functions. This is useful for targets like x86_64 that cannot
23// lower divisions with more than 128 bits or targets like x86_32 that
24// cannot lower divisions with more than 64 bits.
25//
26// Instructions with vector types are scalarized first if their scalar
27// types can be expanded. Scalable vector types are not supported.
28//===----------------------------------------------------------------------===//
29
37#include "llvm/CodeGen/Passes.h"
41#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/PassManager.h"
47#include "llvm/Pass.h"
54#include <optional>
55
56#define DEBUG_TYPE "expand-ir-insts"
57
58using namespace llvm;
59
61 ExpandFpConvertBits("expand-fp-convert-bits", cl::Hidden,
63 cl::desc("fp convert instructions on integers with "
64 "more than <N> bits are expanded."));
65
67 ExpandDivRemBits("expand-div-rem-bits", cl::Hidden,
69 cl::desc("div and rem instructions on integers with "
70 "more than <N> bits are expanded."));
71
72static bool isConstantPowerOfTwo(Value *V, bool SignedOp) {
73 auto *C = dyn_cast<ConstantInt>(V);
74 if (!C)
75 return false;
76
77 APInt Val = C->getValue();
78 if (SignedOp && Val.isNegative())
79 Val = -Val;
80 return Val.isPowerOf2();
81}
82
83static bool isSigned(unsigned Opcode) {
84 return Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
85}
86
87/// For signed div/rem by a power of 2, compute the bias-adjusted dividend:
88/// Sign = ashr X, (BitWidth - 1) -- 0 or -1
89/// Bias = lshr Sign, (BitWidth - ShiftAmt) -- 0 or 2^ShiftAmt - 1
90/// Adjusted = add X, Bias
91/// The bias adds (2^ShiftAmt - 1) for negative X, correcting rounding towards
92/// zero (instead of towards -inf that a plain ashr would give).
93/// The lshr form is used instead of 'and' to avoid large immediate constants.
94static Value *addSignedBias(IRBuilder<> &Builder, Value *X, unsigned BitWidth,
95 unsigned ShiftAmt) {
96 assert(ShiftAmt > 0 && ShiftAmt < BitWidth &&
97 "ShiftAmt out of range; callers should handle ShiftAmt == 0");
98 Value *Sign = Builder.CreateAShr(X, BitWidth - 1, "sign");
99 Value *Bias = Builder.CreateLShr(Sign, BitWidth - ShiftAmt, "bias");
100 return Builder.CreateAdd(X, Bias, "adjusted");
101}
102
103/// Expand division or remainder by a power-of-2 constant.
104/// Division (let C = log2(|divisor|)):
105/// udiv X, 2^C -> lshr X, C
106/// sdiv X, 2^C -> ashr (add X, Bias), C (Bias corrects rounding)
107/// sdiv exact X, 2^C -> ashr exact X, C (no bias needed)
108/// For negative power-of-2 divisors, the division result is negated.
109/// Remainder (let C = log2(|divisor|)):
110/// urem X, 2^C -> and X, (2^C - 1)
111/// srem X, 2^C -> sub X, (shl (ashr (add X, Bias), C), C)
113 LLVM_DEBUG(dbgs() << "Expanding instruction: " << *BO << '\n');
114
115 unsigned Opcode = BO->getOpcode();
116 bool IsDiv = (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv);
117 bool IsSigned = isSigned(Opcode);
118 // isExact() is only valid for div.
119 bool IsExact = IsDiv && BO->isExact();
120
121 assert(isConstantPowerOfTwo(BO->getOperand(1), IsSigned) &&
122 "Expected power-of-2 constant divisor");
123
124 Value *X = BO->getOperand(0);
125 auto *C = cast<ConstantInt>(BO->getOperand(1));
126 Type *Ty = BO->getType();
127 unsigned BitWidth = Ty->getIntegerBitWidth();
128
129 APInt DivisorVal = C->getValue();
130 bool IsNegativeDivisor = IsSigned && DivisorVal.isNegative();
131 // Use countr_zero() to get the shift amount directly from the bit pattern.
132 // This works correctly for both positive and negative powers of 2, including
133 // INT_MIN, without needing to negate the value first.
134 unsigned ShiftAmt = DivisorVal.countr_zero();
135
136 IRBuilder<> Builder(BO);
137 Value *Result;
138
139 if (ShiftAmt == 0) {
140 // Div by 1/-1: X / 1 = X, X / -1 = -X.
141 // Rem by 1/-1: always 0.
142 if (IsDiv)
143 Result = IsNegativeDivisor ? Builder.CreateNeg(X) : X;
144 else
145 Result = ConstantInt::get(Ty, 0);
146 } else if (IsSigned) {
147 // The signed expansion uses X multiple times (bias computation, shift,
148 // and sub for remainder). Freeze X to ensure consistent behavior if it is
149 // undef/poison. For exact division, no bias is needed and X is used only
150 // once, so freeze is unnecessary.
151 if (!IsExact && !isGuaranteedNotToBeUndefOrPoison(X))
152 X = Builder.CreateFreeze(X, X->getName() + ".fr");
153 // For exact division, no bias is needed since there's no rounding.
154 Value *Dividend =
155 IsExact ? X : addSignedBias(Builder, X, BitWidth, ShiftAmt);
156 Value *Quotient = Builder.CreateAShr(
157 Dividend, ShiftAmt, IsDiv && IsNegativeDivisor ? "pre.neg" : "shifted",
158 IsExact);
159 if (IsDiv) {
160 Result = IsNegativeDivisor ? Builder.CreateNeg(Quotient) : Quotient;
161 } else {
162 // Rem = X - (Quotient << ShiftAmt):
163 // clear lower ShiftAmt bits via round-trip shift, then subtract.
164 Value *Truncated = Builder.CreateShl(Quotient, ShiftAmt, "truncated");
165 Result = Builder.CreateSub(X, Truncated);
166 }
167 } else {
168 if (IsDiv) {
169 Result = Builder.CreateLShr(X, ShiftAmt, "", IsExact);
170 } else {
171 APInt Mask = APInt::getLowBitsSet(BitWidth, ShiftAmt);
172 Result = Builder.CreateAnd(X, ConstantInt::get(Ty, Mask));
173 }
174 }
175
176 BO->replaceAllUsesWith(Result);
177 if (Result != X)
178 if (auto *RI = dyn_cast<Instruction>(Result))
179 RI->takeName(BO);
180 BO->dropAllReferences();
181 BO->eraseFromParent();
182}
183
184/// This class implements a precise expansion of the frem instruction.
185/// The generated code is based on the fmod implementation in the AMD device
186/// libs.
187namespace {
188class FRemExpander {
189 /// The IRBuilder to use for the expansion.
190 IRBuilder<> &B;
191
192 /// Floating point type of the return value and the arguments of the FRem
193 /// instructions that should be expanded.
194 Type *FremTy;
195
196 /// Floating point type to use for the computation. This may be
197 /// wider than the \p FremTy.
198 Type *ComputeFpTy;
199
200 /// Integer type used to hold the exponents returned by frexp.
201 Type *ExTy;
202
203 /// How many bits of the quotient to compute per iteration of the
204 /// algorithm, stored as a value of type \p ExTy.
205 Value *Bits;
206
207 /// Constant 1 of type \p ExTy.
208 Value *One;
209
210 /// The frem argument/return types that can be expanded by this class.
211 // TODO: The expansion could work for other floating point types
212 // as well, but this would require additional testing.
213 static constexpr std::array<MVT, 3> ExpandableTypes{MVT::f16, MVT::f32,
214 MVT::f64};
215
216public:
217 static bool canExpandType(Type *Ty) {
218 EVT VT = EVT::getEVT(Ty);
219 assert(VT.isSimple() && "Can expand only simple types");
220
221 return is_contained(ExpandableTypes, VT.getSimpleVT());
222 }
223
224 static bool shouldExpandFremType(const TargetLowering &TLI, EVT VT) {
225 assert(!VT.isVector() && "Cannot handle vector type; must scalarize first");
226 return TLI.getOperationAction(ISD::FREM, VT) ==
227 TargetLowering::LegalizeAction::Expand;
228 }
229
230 static bool shouldExpandFremType(const TargetLowering &TLI, Type *Ty) {
231 // Consider scalar type for simplicity. It seems unlikely that a
232 // vector type can be legalized without expansion if the scalar
233 // type cannot.
234 return shouldExpandFremType(TLI, EVT::getEVT(Ty->getScalarType()));
235 }
236
237 /// Return true if the pass should expand frem instructions of any type
238 /// for the target represented by \p TLI.
239 static bool shouldExpandAnyFremType(const TargetLowering &TLI) {
240 return any_of(ExpandableTypes,
241 [&](MVT V) { return shouldExpandFremType(TLI, EVT(V)); });
242 }
243
244 static FRemExpander create(IRBuilder<> &B, Type *Ty) {
245 assert(canExpandType(Ty) && "Expected supported floating point type");
246
247 // The type to use for the computation of the remainder. This may be
248 // wider than the input/result type which affects the ...
249 Type *ComputeTy = Ty;
250 // ... maximum number of iterations of the remainder computation loop
251 // to use. This value is for the case in which the computation
252 // uses the same input/result type.
253 unsigned MaxIter = 2;
254
255 if (Ty->isHalfTy()) {
256 // Use the wider type and less iterations.
257 ComputeTy = B.getFloatTy();
258 MaxIter = 1;
259 }
260
261 unsigned Precision = APFloat::semanticsPrecision(Ty->getFltSemantics());
262 return FRemExpander{B, Ty, Precision / MaxIter, ComputeTy};
263 }
264
265 /// Build the FRem expansion for the numerator \p X and the
266 /// denumerator \p Y. The type of X and Y must match \p FremTy. The
267 /// code will be generated at the insertion point of \p B and the
268 /// insertion point will be reset at exit.
269 Value *buildFRem(Value *X, Value *Y, std::optional<SimplifyQuery> &SQ) const;
270
271 /// Build an approximate FRem expansion for the numerator \p X and
272 /// the denumerator \p Y at the insertion point of builder \p B.
273 /// The type of X and Y must match \p FremTy.
274 Value *buildApproxFRem(Value *X, Value *Y) const;
275
276private:
277 FRemExpander(IRBuilder<> &B, Type *FremTy, unsigned Bits, Type *ComputeFpTy)
278 : B(B), FremTy(FremTy), ComputeFpTy(ComputeFpTy), ExTy(B.getInt32Ty()),
279 Bits(ConstantInt::get(ExTy, Bits)), One(ConstantInt::get(ExTy, 1)) {}
280
281 Value *createRcp(Value *V, const Twine &Name) const {
282 // Leave it to later optimizations to turn this into an rcp
283 // instruction if available.
284 return B.CreateFDiv(ConstantFP::get(ComputeFpTy, 1.0), V, Name);
285 }
286
287 // Helper function to build the UPDATE_AX code which is common to the
288 // loop body and the "final iteration".
289 Value *buildUpdateAx(Value *Ax, Value *Ay, Value *Ayinv) const {
290 // Build:
291 // float q = rint(ax * ayinv);
292 // ax = fma(-q, ay, ax);
293 // int clt = ax < 0.0f;
294 // float axp = ax + ay;
295 // ax = clt ? axp : ax;
296 Value *Q = B.CreateUnaryIntrinsic(Intrinsic::rint, B.CreateFMul(Ax, Ayinv),
297 {}, "q");
298 Value *AxUpdate = B.CreateFMA(B.CreateFNeg(Q), Ay, Ax, {}, "ax");
299 Value *Clt = B.CreateFCmp(CmpInst::FCMP_OLT, AxUpdate,
300 ConstantFP::getZero(ComputeFpTy), "clt");
301 Value *Axp = B.CreateFAdd(AxUpdate, Ay, "axp");
302 return B.CreateSelect(Clt, Axp, AxUpdate, "ax");
303 }
304
305 /// Build code to extract the exponent and mantissa of \p Src.
306 /// Return the exponent minus one for use as a loop bound and
307 /// the mantissa taken to the given \p NewExp power.
308 std::pair<Value *, Value *> buildExpAndPower(Value *Src, Value *NewExp,
309 const Twine &ExName,
310 const Twine &PowName) const {
311 // Build:
312 // ExName = frexp_exp(Src) - 1;
313 // PowName = fldexp(frexp_mant(ExName), NewExp);
314 Type *Ty = Src->getType();
315 Type *ExTy = B.getInt32Ty();
316 Value *Frexp = B.CreateIntrinsic(Intrinsic::frexp, {Ty, ExTy}, Src);
317 Value *Mant = B.CreateExtractValue(Frexp, {0});
318 Value *Exp = B.CreateExtractValue(Frexp, {1});
319
320 Exp = B.CreateSub(Exp, One, ExName);
321 Value *Pow = B.CreateLdexp(Mant, NewExp, {}, PowName);
322
323 return {Pow, Exp};
324 }
325
326 /// Build the main computation of the remainder for the case in which
327 /// Ax > Ay, where Ax = |X|, Ay = |Y|, and X is the numerator and Y the
328 /// denumerator. Add the incoming edge from the computation result
329 /// to \p RetPhi.
330 void buildRemainderComputation(Value *AxInitial, Value *AyInitial, Value *X,
331 PHINode *RetPhi, FastMathFlags FMF) const {
332 IRBuilder<>::FastMathFlagGuard Guard(B);
333 B.setFastMathFlags(FMF);
334
335 // Build:
336 // ex = frexp_exp(ax) - 1;
337 // ax = fldexp(frexp_mant(ax), bits);
338 // ey = frexp_exp(ay) - 1;
339 // ay = fledxp(frexp_mant(ay), 1);
340 auto [Ax, Ex] = buildExpAndPower(AxInitial, Bits, "ex", "ax");
341 auto [Ay, Ey] = buildExpAndPower(AyInitial, One, "ey", "ay");
342
343 // Build:
344 // int nb = ex - ey;
345 // float ayinv = 1.0/ay;
346 Value *Nb = B.CreateSub(Ex, Ey, "nb");
347 Value *Ayinv = createRcp(Ay, "ayinv");
348
349 // Build: while (nb > bits)
350 BasicBlock *PreheaderBB = B.GetInsertBlock();
351 Function *Fun = PreheaderBB->getParent();
352 auto *LoopBB = BasicBlock::Create(B.getContext(), "frem.loop_body", Fun);
353 auto *ExitBB = BasicBlock::Create(B.getContext(), "frem.loop_exit", Fun);
354
355 B.CreateCondBr(B.CreateICmp(CmpInst::ICMP_SGT, Nb, Bits), LoopBB, ExitBB);
356
357 // Build loop body:
358 // UPDATE_AX
359 // ax = fldexp(ax, bits);
360 // nb -= bits;
361 // One iteration of the loop is factored out. The code shared by
362 // the loop and this "iteration" is denoted by UPDATE_AX.
363 B.SetInsertPoint(LoopBB);
364 PHINode *NbIv = B.CreatePHI(Nb->getType(), 2, "nb_iv");
365 NbIv->addIncoming(Nb, PreheaderBB);
366
367 auto *AxPhi = B.CreatePHI(ComputeFpTy, 2, "ax_loop_phi");
368 AxPhi->addIncoming(Ax, PreheaderBB);
369
370 Value *AxPhiUpdate = buildUpdateAx(AxPhi, Ay, Ayinv);
371 AxPhiUpdate = B.CreateLdexp(AxPhiUpdate, Bits, {}, "ax_update");
372 AxPhi->addIncoming(AxPhiUpdate, LoopBB);
373 NbIv->addIncoming(B.CreateSub(NbIv, Bits, "nb_update"), LoopBB);
374
375 B.CreateCondBr(B.CreateICmp(CmpInst::ICMP_SGT, NbIv, Bits), LoopBB, ExitBB);
376
377 // Build final iteration
378 // ax = fldexp(ax, nb - bits + 1);
379 // UPDATE_AX
380 B.SetInsertPoint(ExitBB);
381
382 auto *AxPhiExit = B.CreatePHI(ComputeFpTy, 2, "ax_exit_phi");
383 AxPhiExit->addIncoming(Ax, PreheaderBB);
384 AxPhiExit->addIncoming(AxPhi, LoopBB);
385 auto *NbExitPhi = B.CreatePHI(Nb->getType(), 2, "nb_exit_phi");
386 NbExitPhi->addIncoming(NbIv, LoopBB);
387 NbExitPhi->addIncoming(Nb, PreheaderBB);
388
389 Value *AxFinal = B.CreateLdexp(
390 AxPhiExit, B.CreateAdd(B.CreateSub(NbExitPhi, Bits), One), {}, "ax");
391 AxFinal = buildUpdateAx(AxFinal, Ay, Ayinv);
392
393 // Build:
394 // ax = fldexp(ax, ey);
395 // ret = copysign(ax,x);
396 AxFinal = B.CreateLdexp(AxFinal, Ey, {}, "ax");
397 if (ComputeFpTy != FremTy)
398 AxFinal = B.CreateFPTrunc(AxFinal, FremTy);
399 Value *Ret = B.CreateCopySign(AxFinal, X);
400
401 RetPhi->addIncoming(Ret, ExitBB);
402 }
403
404 /// Build the else-branch of the conditional in the FRem
405 /// expansion, i.e. the case in wich Ax <= Ay, where Ax = |X|, Ay
406 /// = |Y|, and X is the numerator and Y the denumerator. Add the
407 /// incoming edge from the result to \p RetPhi.
408 void buildElseBranch(Value *Ax, Value *Ay, Value *X, PHINode *RetPhi) const {
409 // Build:
410 // ret = ax == ay ? copysign(0.0f, x) : x;
411 Value *ZeroWithXSign = B.CreateCopySign(ConstantFP::getZero(FremTy), X);
412 Value *Ret = B.CreateSelect(B.CreateFCmpOEQ(Ax, Ay), ZeroWithXSign, X);
413
414 RetPhi->addIncoming(Ret, B.GetInsertBlock());
415 }
416
417 /// Return a value that is NaN if one of the corner cases concerning
418 /// the inputs \p X and \p Y is detected, and \p Ret otherwise.
419 Value *handleInputCornerCases(Value *Ret, Value *X, Value *Y,
420 std::optional<SimplifyQuery> &SQ,
421 bool NoInfs) const {
422 // Build:
423 // ret = (y == 0.0f || isnan(y)) ? QNAN : ret;
424 // ret = isfinite(x) ? ret : QNAN;
425 Value *Nan = ConstantFP::getQNaN(FremTy);
426 Ret = B.CreateSelect(B.CreateFCmpUEQ(Y, ConstantFP::getZero(FremTy)), Nan,
427 Ret);
428 Value *XFinite =
429 NoInfs || (SQ && isKnownNeverInfinity(X, *SQ))
430 ? B.getTrue()
431 : B.CreateFCmpULT(B.CreateFAbs(X), ConstantFP::getInfinity(FremTy));
432 Ret = B.CreateSelect(XFinite, Ret, Nan);
433
434 return Ret;
435 }
436};
437} // namespace
438
439Value *FRemExpander::buildApproxFRem(Value *X, Value *Y) const {
440 IRBuilder<>::FastMathFlagGuard Guard(B);
441 // Propagating the approximate functions flag to the
442 // division leads to an unacceptable drop in precision
443 // on AMDGPU.
444 // TODO Find out if any flags might be worth propagating.
445 B.clearFastMathFlags();
446
447 Value *Quot = B.CreateFDiv(X, Y);
448 Value *Trunc = B.CreateUnaryIntrinsic(Intrinsic::trunc, Quot, {});
449 Value *Neg = B.CreateFNeg(Trunc);
450
451 return B.CreateFMA(Neg, Y, X);
452}
453
454Value *FRemExpander::buildFRem(Value *X, Value *Y,
455 std::optional<SimplifyQuery> &SQ) const {
456 assert(X->getType() == FremTy && Y->getType() == FremTy);
457
458 FastMathFlags FMF = B.getFastMathFlags();
459
460 // This function generates the following code structure:
461 // if (abs(x) > abs(y))
462 // { ret = compute remainder }
463 // else
464 // { ret = x or 0 with sign of x }
465 // Adjust ret to NaN/inf in input
466 // return ret
467 Value *Ax = B.CreateFAbs(X, {}, "ax");
468 Value *Ay = B.CreateFAbs(Y, {}, "ay");
469 if (ComputeFpTy != X->getType()) {
470 Ax = B.CreateFPExt(Ax, ComputeFpTy, "ax");
471 Ay = B.CreateFPExt(Ay, ComputeFpTy, "ay");
472 }
473 Value *AxAyCmp = B.CreateFCmpOGT(Ax, Ay);
474
475 PHINode *RetPhi = B.CreatePHI(FremTy, 2, "ret");
476 Value *Ret = RetPhi;
477
478 // We would return NaN in all corner cases handled here.
479 // Hence, if NaNs are excluded, keep the result as it is.
480 if (!FMF.noNaNs())
481 Ret = handleInputCornerCases(Ret, X, Y, SQ, FMF.noInfs());
482
483 Function *Fun = B.GetInsertBlock()->getParent();
484 auto *ThenBB = BasicBlock::Create(B.getContext(), "frem.compute", Fun);
485 auto *ElseBB = BasicBlock::Create(B.getContext(), "frem.else", Fun);
486 SplitBlockAndInsertIfThenElse(AxAyCmp, RetPhi, &ThenBB, &ElseBB);
487
488 auto SavedInsertPt = B.GetInsertPoint();
489
490 // Build remainder computation for "then" branch
491 //
492 // The ordered comparison ensures that ax and ay are not NaNs
493 // in the then-branch. Furthermore, y cannot be an infinity and the
494 // check at the end of the function ensures that the result will not
495 // be used if x is an infinity.
496 FastMathFlags ComputeFMF = FMF;
497 ComputeFMF.setNoInfs();
498 ComputeFMF.setNoNaNs();
499
500 B.SetInsertPoint(ThenBB);
501 buildRemainderComputation(Ax, Ay, X, RetPhi, FMF);
502 B.CreateBr(RetPhi->getParent());
503
504 // Build "else"-branch
505 B.SetInsertPoint(ElseBB);
506 buildElseBranch(Ax, Ay, X, RetPhi);
507 B.CreateBr(RetPhi->getParent());
508
509 B.SetInsertPoint(SavedInsertPt);
510
511 return Ret;
512}
513
514static bool expandFRem(BinaryOperator &I, std::optional<SimplifyQuery> &SQ) {
515 LLVM_DEBUG(dbgs() << "Expanding instruction: " << I << '\n');
516
517 Type *Ty = I.getType();
518 assert(FRemExpander::canExpandType(Ty) &&
519 "Expected supported floating point type");
520
521 FastMathFlags FMF = I.getFastMathFlags();
522 // TODO Make use of those flags for optimization?
523 FMF.setAllowReciprocal(false);
524 FMF.setAllowContract(false);
525
526 IRBuilder<> B(&I);
527 B.setFastMathFlags(FMF);
528 B.SetCurrentDebugLocation(I.getDebugLoc());
529
530 const FRemExpander Expander = FRemExpander::create(B, Ty);
531 Value *Ret = FMF.approxFunc()
532 ? Expander.buildApproxFRem(I.getOperand(0), I.getOperand(1))
533 : Expander.buildFRem(I.getOperand(0), I.getOperand(1), SQ);
534
535 I.replaceAllUsesWith(Ret);
536 Ret->takeName(&I);
537 I.eraseFromParent();
538
539 return true;
540}
541// clang-format off: preserve formatting of the following example
542
543/// Generate code to convert a fp number to integer, replacing FPToS(U)I with
544/// the generated code. This currently generates code similarly to compiler-rt's
545/// implementations.
546///
547/// An example IR generated from compiler-rt/fixsfdi.c looks like below:
548/// define dso_local i64 @foo(float noundef %a) local_unnamed_addr #0 {
549/// entry:
550/// %0 = bitcast float %a to i32
551/// %conv.i = zext i32 %0 to i64
552/// %tobool.not = icmp sgt i32 %0, -1
553/// %conv = select i1 %tobool.not, i64 1, i64 -1
554/// %and = lshr i64 %conv.i, 23
555/// %shr = and i64 %and, 255
556/// %and2 = and i64 %conv.i, 8388607
557/// %or = or i64 %and2, 8388608
558/// %cmp = icmp ult i64 %shr, 127
559/// br i1 %cmp, label %cleanup, label %if.end
560///
561/// if.end: ; preds = %entry
562/// %sub = add nuw nsw i64 %shr, 4294967169
563/// %conv5 = and i64 %sub, 4294967232
564/// %cmp6.not = icmp eq i64 %conv5, 0
565/// br i1 %cmp6.not, label %if.end12, label %if.then8
566///
567/// if.then8: ; preds = %if.end
568/// %cond11 = select i1 %tobool.not, i64 9223372036854775807, i64
569/// -9223372036854775808 br label %cleanup
570///
571/// if.end12: ; preds = %if.end
572/// %cmp13 = icmp ult i64 %shr, 150
573/// br i1 %cmp13, label %if.then15, label %if.else
574///
575/// if.then15: ; preds = %if.end12
576/// %sub16 = sub nuw nsw i64 150, %shr
577/// %shr17 = lshr i64 %or, %sub16
578/// %mul = mul nsw i64 %shr17, %conv
579/// br label %cleanup
580///
581/// if.else: ; preds = %if.end12
582/// %sub18 = add nsw i64 %shr, -150
583/// %shl = shl i64 %or, %sub18
584/// %mul19 = mul nsw i64 %shl, %conv
585/// br label %cleanup
586///
587/// cleanup: ; preds = %entry,
588/// %if.else, %if.then15, %if.then8
589/// %retval.0 = phi i64 [ %cond11, %if.then8 ], [ %mul, %if.then15 ], [
590/// %mul19, %if.else ], [ 0, %entry ] ret i64 %retval.0
591/// }
592///
593/// Replace fp to integer with generated code.
594static void expandFPToI(Instruction *FPToI, bool IsSaturating, bool IsSigned) {
595 // clang-format on
596 IRBuilder<> Builder(FPToI);
597 auto *FloatVal = FPToI->getOperand(0);
598 IntegerType *IntTy = cast<IntegerType>(FPToI->getType());
599
600 unsigned BitWidth = FPToI->getType()->getIntegerBitWidth();
601 unsigned FPMantissaWidth = FloatVal->getType()->getFPMantissaWidth() - 1;
602
603 // FIXME: fp16's range is covered by i32. So `fptoi half` can convert
604 // to i32 first following a sext/zext to target integer type.
605 Value *A1 = nullptr;
606 if (FloatVal->getType()->isHalfTy() && BitWidth >= 32) {
607 if (FPToI->getOpcode() == Instruction::FPToUI) {
608 Value *A0 = Builder.CreateFPToUI(FloatVal, Builder.getInt32Ty());
609 A1 = Builder.CreateZExt(A0, IntTy);
610 } else { // FPToSI
611 Value *A0 = Builder.CreateFPToSI(FloatVal, Builder.getInt32Ty());
612 A1 = Builder.CreateSExt(A0, IntTy);
613 }
614 FPToI->replaceAllUsesWith(A1);
615 FPToI->dropAllReferences();
616 FPToI->eraseFromParent();
617 return;
618 }
619
620 // fp80 conversion is implemented by fpext to fp128 first then do the
621 // conversion.
622 FPMantissaWidth = FPMantissaWidth == 63 ? 112 : FPMantissaWidth;
623 unsigned FloatWidth =
624 PowerOf2Ceil(FloatVal->getType()->getScalarSizeInBits());
625 unsigned ExponentWidth = FloatWidth - FPMantissaWidth - 1;
626 unsigned ExponentBias = (1 << (ExponentWidth - 1)) - 1;
627 IntegerType *FloatIntTy = Builder.getIntNTy(FloatWidth);
628 Value *ImplicitBit = ConstantInt::get(
629 FloatIntTy, APInt::getOneBitSet(FloatWidth, FPMantissaWidth));
630 Value *SignificandMask = ConstantInt::get(
631 FloatIntTy, APInt::getLowBitsSet(FloatWidth, FPMantissaWidth));
632
633 BasicBlock *Entry = Builder.GetInsertBlock();
634 Function *F = Entry->getParent();
635 Entry->setName(Twine(Entry->getName(), "fp-to-i-entry"));
636 BasicBlock *CheckSaturateBB, *SaturateBB;
637 BasicBlock *End =
638 Entry->splitBasicBlock(Builder.GetInsertPoint(), "fp-to-i-cleanup");
639 if (IsSaturating) {
640 CheckSaturateBB = BasicBlock::Create(Builder.getContext(),
641 "fp-to-i-if-check.saturate", F, End);
642 SaturateBB =
643 BasicBlock::Create(Builder.getContext(), "fp-to-i-if-saturate", F, End);
644 }
645 BasicBlock *CheckExpSizeBB = BasicBlock::Create(
646 Builder.getContext(), "fp-to-i-if-check.exp.size", F, End);
647 BasicBlock *ExpSmallBB =
648 BasicBlock::Create(Builder.getContext(), "fp-to-i-if-exp.small", F, End);
649 BasicBlock *ExpLargeBB =
650 BasicBlock::Create(Builder.getContext(), "fp-to-i-if-exp.large", F, End);
651
652 Entry->getTerminator()->eraseFromParent();
653
654 // entry:
655 Builder.SetInsertPoint(Entry);
656 // We're going to introduce branches on the value, so freeze it.
658 FloatVal = Builder.CreateFreeze(FloatVal);
659 // fp80 conversion is implemented by fpext to fp128 first then do the
660 // conversion.
661 if (FloatVal->getType()->isX86_FP80Ty())
662 FloatVal =
663 Builder.CreateFPExt(FloatVal, Type::getFP128Ty(Builder.getContext()));
664 Value *ARep = Builder.CreateBitCast(FloatVal, FloatIntTy);
665 Value *PosOrNeg, *Sign;
666 if (IsSigned) {
667 PosOrNeg =
668 Builder.CreateICmpSGT(ARep, ConstantInt::getSigned(FloatIntTy, -1));
669 Sign = Builder.CreateSelect(PosOrNeg, ConstantInt::getSigned(IntTy, 1),
670 ConstantInt::getSigned(IntTy, -1), "sign");
671 }
672 Value *And =
673 Builder.CreateLShr(ARep, Builder.getIntN(FloatWidth, FPMantissaWidth));
674 Value *BiasedExp = Builder.CreateAnd(
675 And, Builder.getIntN(FloatWidth, (1 << ExponentWidth) - 1), "biased.exp");
676 Value *Abs = Builder.CreateAnd(ARep, SignificandMask);
677 Value *Significand = Builder.CreateOr(Abs, ImplicitBit, "significand");
678 Value *ZeroResultCond = Builder.CreateICmpULT(
679 BiasedExp, Builder.getIntN(FloatWidth, ExponentBias), "exp.is.negative");
680 if (IsSaturating) {
681 Value *IsNaN = Builder.CreateFCmpUNO(FloatVal, FloatVal, "is.nan");
682 ZeroResultCond = Builder.CreateOr(ZeroResultCond, IsNaN);
683 if (!IsSigned) {
684 Value *IsNeg = Builder.CreateIsNeg(ARep);
685 ZeroResultCond = Builder.CreateOr(ZeroResultCond, IsNeg);
686 }
687 }
688 Builder.CreateCondBr(ZeroResultCond, End,
689 IsSaturating ? CheckSaturateBB : CheckExpSizeBB);
690
691 Value *Saturated;
692 if (IsSaturating) {
693 // check.saturate:
694 Builder.SetInsertPoint(CheckSaturateBB);
695 Value *Cmp3 = Builder.CreateICmpUGE(
696 BiasedExp, ConstantInt::getSigned(
697 FloatIntTy, static_cast<int64_t>(ExponentBias +
698 BitWidth - IsSigned)));
699 Builder.CreateCondBr(Cmp3, SaturateBB, CheckExpSizeBB);
700
701 // saturate:
702 Builder.SetInsertPoint(SaturateBB);
703 if (IsSigned) {
704 Value *SignedMax =
705 ConstantInt::get(IntTy, APInt::getSignedMaxValue(BitWidth));
706 Value *SignedMin =
707 ConstantInt::get(IntTy, APInt::getSignedMinValue(BitWidth));
708 Saturated =
709 Builder.CreateSelect(PosOrNeg, SignedMax, SignedMin, "saturated");
710 } else {
711 Saturated = ConstantInt::getAllOnesValue(IntTy);
712 }
713 Builder.CreateBr(End);
714 }
715
716 // if.end9:
717 Builder.SetInsertPoint(CheckExpSizeBB);
718 Value *ExpSmallerMantissaWidth = Builder.CreateICmpULT(
719 BiasedExp, Builder.getIntN(FloatWidth, ExponentBias + FPMantissaWidth),
720 "exp.smaller.mantissa.width");
721 Builder.CreateCondBr(ExpSmallerMantissaWidth, ExpSmallBB, ExpLargeBB);
722
723 // exp.small:
724 Builder.SetInsertPoint(ExpSmallBB);
725 Value *Sub13 = Builder.CreateSub(
726 Builder.getIntN(FloatWidth, ExponentBias + FPMantissaWidth), BiasedExp);
727 Value *ExpSmallRes =
728 Builder.CreateZExtOrTrunc(Builder.CreateLShr(Significand, Sub13), IntTy);
729 if (IsSigned)
730 ExpSmallRes = Builder.CreateMul(ExpSmallRes, Sign);
731 Builder.CreateBr(End);
732
733 // exp.large:
734 Builder.SetInsertPoint(ExpLargeBB);
735 Value *Sub15 = Builder.CreateAdd(
736 BiasedExp,
738 FloatIntTy, -static_cast<int64_t>(ExponentBias + FPMantissaWidth)));
739 Value *SignificandCast = Builder.CreateZExtOrTrunc(Significand, IntTy);
740 Value *ExpLargeRes = Builder.CreateShl(
741 SignificandCast, Builder.CreateZExtOrTrunc(Sub15, IntTy));
742 if (IsSigned)
743 ExpLargeRes = Builder.CreateMul(ExpLargeRes, Sign);
744 Builder.CreateBr(End);
745
746 // cleanup:
747 Builder.SetInsertPoint(End, End->begin());
748 PHINode *Retval0 = Builder.CreatePHI(FPToI->getType(), 3 + IsSaturating);
749
750 if (IsSaturating)
751 Retval0->addIncoming(Saturated, SaturateBB);
752 Retval0->addIncoming(ExpSmallRes, ExpSmallBB);
753 Retval0->addIncoming(ExpLargeRes, ExpLargeBB);
754 Retval0->addIncoming(Builder.getIntN(BitWidth, 0), Entry);
755
756 FPToI->replaceAllUsesWith(Retval0);
757 FPToI->dropAllReferences();
758 FPToI->eraseFromParent();
759}
760
761// clang-format off: preserve formatting of the following example
762
763/// Generate code to convert a fp number to integer, replacing S(U)IToFP with
764/// the generated code. This currently generates code similarly to compiler-rt's
765/// implementations. This implementation has an implicit assumption that integer
766/// width is larger than fp.
767///
768/// An example IR generated from compiler-rt/floatdisf.c looks like below:
769/// define dso_local float @__floatdisf(i64 noundef %a) local_unnamed_addr #0 {
770/// entry:
771/// %cmp = icmp eq i64 %a, 0
772/// br i1 %cmp, label %return, label %if.end
773///
774/// if.end: ; preds = %entry
775/// %shr = ashr i64 %a, 63
776/// %xor = xor i64 %shr, %a
777/// %sub = sub nsw i64 %xor, %shr
778/// %0 = tail call i64 @llvm.ctlz.i64(i64 %sub, i1 true), !range !5
779/// %cast = trunc i64 %0 to i32
780/// %sub1 = sub nuw nsw i32 64, %cast
781/// %sub2 = xor i32 %cast, 63
782/// %cmp3 = icmp ult i32 %cast, 40
783/// br i1 %cmp3, label %if.then4, label %if.else
784///
785/// if.then4: ; preds = %if.end
786/// switch i32 %sub1, label %sw.default [
787/// i32 25, label %sw.bb
788/// i32 26, label %sw.epilog
789/// ]
790///
791/// sw.bb: ; preds = %if.then4
792/// %shl = shl i64 %sub, 1
793/// br label %sw.epilog
794///
795/// sw.default: ; preds = %if.then4
796/// %sub5 = sub nsw i64 38, %0
797/// %sh_prom = and i64 %sub5, 4294967295
798/// %shr6 = lshr i64 %sub, %sh_prom
799/// %shr9 = lshr i64 274877906943, %0
800/// %and = and i64 %shr9, %sub
801/// %cmp10 = icmp ne i64 %and, 0
802/// %conv11 = zext i1 %cmp10 to i64
803/// %or = or i64 %shr6, %conv11
804/// br label %sw.epilog
805///
806/// sw.epilog: ; preds = %sw.default,
807/// %if.then4, %sw.bb
808/// %a.addr.0 = phi i64 [ %or, %sw.default ], [ %sub, %if.then4 ], [ %shl,
809/// %sw.bb ] %1 = lshr i64 %a.addr.0, 2 %2 = and i64 %1, 1 %or16 = or i64 %2,
810/// %a.addr.0 %inc = add nsw i64 %or16, 1 %3 = and i64 %inc, 67108864
811/// %tobool.not = icmp eq i64 %3, 0
812/// %spec.select.v = select i1 %tobool.not, i64 2, i64 3
813/// %spec.select = ashr i64 %inc, %spec.select.v
814/// %spec.select56 = select i1 %tobool.not, i32 %sub2, i32 %sub1
815/// br label %if.end26
816///
817/// if.else: ; preds = %if.end
818/// %sub23 = add nuw nsw i64 %0, 4294967256
819/// %sh_prom24 = and i64 %sub23, 4294967295
820/// %shl25 = shl i64 %sub, %sh_prom24
821/// br label %if.end26
822///
823/// if.end26: ; preds = %sw.epilog,
824/// %if.else
825/// %a.addr.1 = phi i64 [ %shl25, %if.else ], [ %spec.select, %sw.epilog ]
826/// %e.0 = phi i32 [ %sub2, %if.else ], [ %spec.select56, %sw.epilog ]
827/// %conv27 = trunc i64 %shr to i32
828/// %and28 = and i32 %conv27, -2147483648
829/// %add = shl nuw nsw i32 %e.0, 23
830/// %shl29 = add nuw nsw i32 %add, 1065353216
831/// %conv31 = trunc i64 %a.addr.1 to i32
832/// %and32 = and i32 %conv31, 8388607
833/// %or30 = or i32 %and32, %and28
834/// %or33 = or i32 %or30, %shl29
835/// %4 = bitcast i32 %or33 to float
836/// br label %return
837///
838/// return: ; preds = %entry,
839/// %if.end26
840/// %retval.0 = phi float [ %4, %if.end26 ], [ 0.000000e+00, %entry ]
841/// ret float %retval.0
842/// }
843///
844/// Replace integer to fp with generated code.
845static void expandIToFP(Instruction *IToFP) {
846 // clang-format on
847 IRBuilder<> Builder(IToFP);
848 auto *IntVal = IToFP->getOperand(0);
849 IntegerType *IntTy = cast<IntegerType>(IntVal->getType());
850
851 unsigned BitWidth = IntVal->getType()->getIntegerBitWidth();
852 unsigned FPMantissaWidth = IToFP->getType()->getFPMantissaWidth() - 1;
853 // fp80 conversion is implemented by conversion tp fp128 first following
854 // a fptrunc to fp80.
855 FPMantissaWidth = FPMantissaWidth == 63 ? 112 : FPMantissaWidth;
856 // FIXME: As there is no related builtins added in compliler-rt,
857 // here currently utilized the fp32 <-> fp16 lib calls to implement.
858 FPMantissaWidth = FPMantissaWidth == 10 ? 23 : FPMantissaWidth;
859 FPMantissaWidth = FPMantissaWidth == 7 ? 23 : FPMantissaWidth;
860 unsigned FloatWidth = PowerOf2Ceil(FPMantissaWidth);
861 bool IsSigned = IToFP->getOpcode() == Instruction::SIToFP;
862
863 // We're going to introduce branches on the value, so freeze it.
865 IntVal = Builder.CreateFreeze(IntVal);
866
867 // The expansion below assumes that int width >= float width. Zero or sign
868 // extend the integer accordingly.
869 if (BitWidth < FloatWidth) {
870 BitWidth = FloatWidth;
871 IntTy = Builder.getIntNTy(BitWidth);
872 IntVal = Builder.CreateIntCast(IntVal, IntTy, IsSigned);
873 }
874
875 Value *Temp1 =
876 Builder.CreateShl(Builder.getIntN(BitWidth, 1),
877 Builder.getIntN(BitWidth, FPMantissaWidth + 3));
878
879 BasicBlock *Entry = Builder.GetInsertBlock();
880 Function *F = Entry->getParent();
881 Entry->setName(Twine(Entry->getName(), "itofp-entry"));
882 BasicBlock *End =
883 Entry->splitBasicBlock(Builder.GetInsertPoint(), "itofp-return");
884 BasicBlock *IfEnd =
885 BasicBlock::Create(Builder.getContext(), "itofp-if-end", F, End);
886 BasicBlock *IfThen4 =
887 BasicBlock::Create(Builder.getContext(), "itofp-if-then4", F, End);
888 BasicBlock *SwBB =
889 BasicBlock::Create(Builder.getContext(), "itofp-sw-bb", F, End);
890 BasicBlock *SwDefault =
891 BasicBlock::Create(Builder.getContext(), "itofp-sw-default", F, End);
892 BasicBlock *SwEpilog =
893 BasicBlock::Create(Builder.getContext(), "itofp-sw-epilog", F, End);
894 BasicBlock *IfThen20 =
895 BasicBlock::Create(Builder.getContext(), "itofp-if-then20", F, End);
896 BasicBlock *IfElse =
897 BasicBlock::Create(Builder.getContext(), "itofp-if-else", F, End);
898 BasicBlock *IfEnd26 =
899 BasicBlock::Create(Builder.getContext(), "itofp-if-end26", F, End);
900
901 Entry->getTerminator()->eraseFromParent();
902
903 Function *CTLZ =
904 Intrinsic::getOrInsertDeclaration(F->getParent(), Intrinsic::ctlz, IntTy);
905 ConstantInt *True = Builder.getTrue();
906
907 // entry:
908 Builder.SetInsertPoint(Entry);
909 Value *Cmp = Builder.CreateICmpEQ(IntVal, ConstantInt::getSigned(IntTy, 0));
910 Builder.CreateCondBr(Cmp, End, IfEnd);
911
912 // if.end:
913 Builder.SetInsertPoint(IfEnd);
914 Value *Shr =
915 Builder.CreateAShr(IntVal, Builder.getIntN(BitWidth, BitWidth - 1));
916 Value *Xor = Builder.CreateXor(Shr, IntVal);
917 Value *Sub = Builder.CreateSub(Xor, Shr);
918 Value *Call = Builder.CreateCall(CTLZ, {IsSigned ? Sub : IntVal, True});
919 Value *Cast = Builder.CreateTrunc(Call, Builder.getInt32Ty());
920 int BitWidthNew = FloatWidth == 128 ? BitWidth : 32;
921 Value *Sub1 = Builder.CreateSub(Builder.getIntN(BitWidthNew, BitWidth),
922 FloatWidth == 128 ? Call : Cast);
923 Value *Sub2 = Builder.CreateSub(Builder.getIntN(BitWidthNew, BitWidth - 1),
924 FloatWidth == 128 ? Call : Cast);
925 Value *Cmp3 = Builder.CreateICmpSGT(
926 Sub1, Builder.getIntN(BitWidthNew, FPMantissaWidth + 1));
927 Builder.CreateCondBr(Cmp3, IfThen4, IfElse);
928
929 // if.then4:
930 Builder.SetInsertPoint(IfThen4);
931 SwitchInst *SI = Builder.CreateSwitch(Sub1, SwDefault);
932 SI->addCase(Builder.getIntN(BitWidthNew, FPMantissaWidth + 2), SwBB);
933 SI->addCase(Builder.getIntN(BitWidthNew, FPMantissaWidth + 3), SwEpilog);
934
935 // sw.bb:
936 Builder.SetInsertPoint(SwBB);
937 Value *Shl =
938 Builder.CreateShl(IsSigned ? Sub : IntVal, Builder.getIntN(BitWidth, 1));
939 Builder.CreateBr(SwEpilog);
940
941 // sw.default:
942 Builder.SetInsertPoint(SwDefault);
943 Value *Sub5 = Builder.CreateSub(
944 Builder.getIntN(BitWidthNew, BitWidth - FPMantissaWidth - 3),
945 FloatWidth == 128 ? Call : Cast);
946 Value *ShProm = Builder.CreateZExt(Sub5, IntTy);
947 Value *Shr6 = Builder.CreateLShr(IsSigned ? Sub : IntVal,
948 FloatWidth == 128 ? Sub5 : ShProm);
949 Value *Sub8 =
950 Builder.CreateAdd(FloatWidth == 128 ? Call : Cast,
951 Builder.getIntN(BitWidthNew, FPMantissaWidth + 3));
952 Value *ShProm9 = Builder.CreateZExt(Sub8, IntTy);
953 Value *Shr9 = Builder.CreateLShr(ConstantInt::getSigned(IntTy, -1),
954 FloatWidth == 128 ? Sub8 : ShProm9);
955 Value *And = Builder.CreateAnd(Shr9, IsSigned ? Sub : IntVal);
956 Value *Cmp10 = Builder.CreateICmpNE(And, Builder.getIntN(BitWidth, 0));
957 Value *Conv11 = Builder.CreateZExt(Cmp10, IntTy);
958 Value *Or = Builder.CreateOr(Shr6, Conv11);
959 Builder.CreateBr(SwEpilog);
960
961 // sw.epilog:
962 Builder.SetInsertPoint(SwEpilog);
963 PHINode *AAddr0 = Builder.CreatePHI(IntTy, 3);
964 AAddr0->addIncoming(Or, SwDefault);
965 AAddr0->addIncoming(IsSigned ? Sub : IntVal, IfThen4);
966 AAddr0->addIncoming(Shl, SwBB);
967 Value *A0 = Builder.CreateTrunc(AAddr0, Builder.getInt32Ty());
968 Value *A1 = Builder.CreateLShr(A0, Builder.getInt32(2));
969 Value *A2 = Builder.CreateAnd(A1, Builder.getInt32(1));
970 Value *Conv16 = Builder.CreateZExt(A2, IntTy);
971 Value *Or17 = Builder.CreateOr(AAddr0, Conv16);
972 Value *Inc = Builder.CreateAdd(Or17, Builder.getIntN(BitWidth, 1));
973 Value *Shr18 = nullptr;
974 if (IsSigned)
975 Shr18 = Builder.CreateAShr(Inc, Builder.getIntN(BitWidth, 2));
976 else
977 Shr18 = Builder.CreateLShr(Inc, Builder.getIntN(BitWidth, 2));
978 Value *A3 = Builder.CreateAnd(Inc, Temp1, "a3");
979 Value *PosOrNeg = Builder.CreateICmpEQ(A3, Builder.getIntN(BitWidth, 0));
980 Value *ExtractT60 = Builder.CreateTrunc(Shr18, Builder.getIntNTy(FloatWidth));
981 Value *Extract63 = Builder.CreateLShr(Shr18, Builder.getIntN(BitWidth, 32));
982 Value *ExtractT64 = nullptr;
983 if (FloatWidth > 80)
984 ExtractT64 = Builder.CreateTrunc(Sub2, Builder.getInt64Ty());
985 else
986 ExtractT64 = Builder.CreateTrunc(Extract63, Builder.getInt32Ty());
987 Builder.CreateCondBr(PosOrNeg, IfEnd26, IfThen20);
988
989 // if.then20
990 Builder.SetInsertPoint(IfThen20);
991 Value *Shr21 = nullptr;
992 if (IsSigned)
993 Shr21 = Builder.CreateAShr(Inc, Builder.getIntN(BitWidth, 3));
994 else
995 Shr21 = Builder.CreateLShr(Inc, Builder.getIntN(BitWidth, 3));
996 Value *ExtractT = Builder.CreateTrunc(Shr21, Builder.getIntNTy(FloatWidth));
997 Value *Extract = Builder.CreateLShr(Shr21, Builder.getIntN(BitWidth, 32));
998 Value *ExtractT62 = nullptr;
999 if (FloatWidth > 80)
1000 ExtractT62 = Builder.CreateTrunc(Sub1, Builder.getInt64Ty());
1001 else
1002 ExtractT62 = Builder.CreateTrunc(Extract, Builder.getInt32Ty());
1003 Builder.CreateBr(IfEnd26);
1004
1005 // if.else:
1006 Builder.SetInsertPoint(IfElse);
1007 Value *Sub24 = Builder.CreateAdd(
1008 FloatWidth == 128 ? Call : Cast,
1009 ConstantInt::getSigned(Builder.getIntNTy(BitWidthNew),
1010 -(int)(BitWidth - FPMantissaWidth - 1)));
1011 Value *ShProm25 = Builder.CreateZExt(Sub24, IntTy);
1012 Value *Shl26 = Builder.CreateShl(IsSigned ? Sub : IntVal,
1013 FloatWidth == 128 ? Sub24 : ShProm25);
1014 Value *ExtractT61 = Builder.CreateTrunc(Shl26, Builder.getIntNTy(FloatWidth));
1015 Value *Extract65 = Builder.CreateLShr(Shl26, Builder.getIntN(BitWidth, 32));
1016 Value *ExtractT66 = nullptr;
1017 if (FloatWidth > 80)
1018 ExtractT66 = Builder.CreateTrunc(Sub2, Builder.getInt64Ty());
1019 else
1020 ExtractT66 = Builder.CreateTrunc(Extract65, Builder.getInt32Ty());
1021 Builder.CreateBr(IfEnd26);
1022
1023 // if.end26:
1024 Builder.SetInsertPoint(IfEnd26);
1025 PHINode *AAddr1Off0 = Builder.CreatePHI(Builder.getIntNTy(FloatWidth), 3);
1026 AAddr1Off0->addIncoming(ExtractT, IfThen20);
1027 AAddr1Off0->addIncoming(ExtractT60, SwEpilog);
1028 AAddr1Off0->addIncoming(ExtractT61, IfElse);
1029 PHINode *AAddr1Off32 = nullptr;
1030 if (FloatWidth > 32) {
1031 AAddr1Off32 =
1032 Builder.CreatePHI(Builder.getIntNTy(FloatWidth > 80 ? 64 : 32), 3);
1033 AAddr1Off32->addIncoming(ExtractT62, IfThen20);
1034 AAddr1Off32->addIncoming(ExtractT64, SwEpilog);
1035 AAddr1Off32->addIncoming(ExtractT66, IfElse);
1036 }
1037 PHINode *E0 = nullptr;
1038 if (FloatWidth <= 80) {
1039 E0 = Builder.CreatePHI(Builder.getIntNTy(BitWidthNew), 3);
1040 E0->addIncoming(Sub1, IfThen20);
1041 E0->addIncoming(Sub2, SwEpilog);
1042 E0->addIncoming(Sub2, IfElse);
1043 }
1044 Value *And29 = nullptr;
1045 if (FloatWidth > 80) {
1046 Value *Temp2 = Builder.CreateShl(Builder.getIntN(BitWidth, 1),
1047 Builder.getIntN(BitWidth, 63));
1048 And29 = Builder.CreateAnd(Shr, Temp2, "and29");
1049 } else {
1050 Value *Conv28 = Builder.CreateTrunc(Shr, Builder.getInt32Ty());
1051 And29 = Builder.CreateAnd(
1052 Conv28, ConstantInt::get(Builder.getContext(), APInt::getSignMask(32)));
1053 }
1054 unsigned TempMod = FPMantissaWidth % 32;
1055 Value *And34 = nullptr;
1056 Value *Shl30 = nullptr;
1057 if (FloatWidth > 80) {
1058 TempMod += 32;
1059 Value *Add = Builder.CreateShl(AAddr1Off32, Builder.getInt64(TempMod));
1060 Shl30 = Builder.CreateAdd(
1061 Add, Builder.getInt64(((1ull << (62ull - TempMod)) - 1ull) << TempMod));
1062 And34 = Builder.CreateZExt(Shl30, Builder.getInt128Ty());
1063 } else {
1064 Value *Add = Builder.CreateShl(E0, Builder.getInt32(TempMod));
1065 Shl30 = Builder.CreateAdd(
1066 Add, Builder.getInt32(((1 << (30 - TempMod)) - 1) << TempMod));
1067 And34 = Builder.CreateAnd(FloatWidth > 32 ? AAddr1Off32 : AAddr1Off0,
1068 Builder.getInt32((1 << TempMod) - 1));
1069 }
1070 Value *Or35 = nullptr;
1071 if (FloatWidth > 80) {
1072 Value *And29Trunc = Builder.CreateTrunc(And29, Builder.getInt128Ty());
1073 Value *Or31 = Builder.CreateOr(And29Trunc, And34);
1074 Value *Or34 = Builder.CreateShl(Or31, Builder.getIntN(128, 64));
1075 Value *Temp3 = Builder.CreateShl(Builder.getIntN(128, 1),
1076 Builder.getIntN(128, FPMantissaWidth));
1077 Value *Temp4 = Builder.CreateSub(Temp3, Builder.getIntN(128, 1));
1078 Value *A6 = Builder.CreateAnd(AAddr1Off0, Temp4);
1079 Or35 = Builder.CreateOr(Or34, A6);
1080 } else {
1081 Value *Or31 = Builder.CreateOr(And34, And29);
1082 Or35 = Builder.CreateOr(IsSigned ? Or31 : And34, Shl30);
1083 }
1084 Value *A4 = nullptr;
1085 if (IToFP->getType()->isDoubleTy()) {
1086 Value *ZExt1 = Builder.CreateZExt(Or35, Builder.getIntNTy(FloatWidth));
1087 Value *Shl1 = Builder.CreateShl(ZExt1, Builder.getIntN(FloatWidth, 32));
1088 Value *And1 =
1089 Builder.CreateAnd(AAddr1Off0, Builder.getIntN(FloatWidth, 0xFFFFFFFF));
1090 Value *Or1 = Builder.CreateOr(Shl1, And1);
1091 A4 = Builder.CreateBitCast(Or1, IToFP->getType());
1092 } else if (IToFP->getType()->isX86_FP80Ty()) {
1093 Value *A40 =
1094 Builder.CreateBitCast(Or35, Type::getFP128Ty(Builder.getContext()));
1095 A4 = Builder.CreateFPTrunc(A40, IToFP->getType());
1096 } else if (IToFP->getType()->isHalfTy() || IToFP->getType()->isBFloatTy()) {
1097 // Deal with "half" situation. This is a workaround since we don't have
1098 // floattihf.c currently as referring.
1099 Value *A40 =
1100 Builder.CreateBitCast(Or35, Type::getFloatTy(Builder.getContext()));
1101 A4 = Builder.CreateFPTrunc(A40, IToFP->getType());
1102 } else // float type
1103 A4 = Builder.CreateBitCast(Or35, IToFP->getType());
1104 Builder.CreateBr(End);
1105
1106 // return:
1107 Builder.SetInsertPoint(End, End->begin());
1108 PHINode *Retval0 = Builder.CreatePHI(IToFP->getType(), 2);
1109 Retval0->addIncoming(A4, IfEnd26);
1110 Retval0->addIncoming(ConstantFP::getZero(IToFP->getType(), false), Entry);
1111
1112 IToFP->replaceAllUsesWith(Retval0);
1113 IToFP->dropAllReferences();
1114 IToFP->eraseFromParent();
1115}
1116
1119 VectorType *VTy = cast<FixedVectorType>(I->getType());
1120
1121 IRBuilder<> Builder(I);
1122
1123 unsigned NumElements = VTy->getElementCount().getFixedValue();
1124 Value *Result = PoisonValue::get(VTy);
1125 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1126 Value *Ext = Builder.CreateExtractElement(I->getOperand(0), Idx);
1127
1128 Value *NewOp = nullptr;
1129 if (auto *BinOp = dyn_cast<BinaryOperator>(I))
1130 NewOp = Builder.CreateBinOp(
1131 BinOp->getOpcode(), Ext,
1132 Builder.CreateExtractElement(I->getOperand(1), Idx));
1133 else if (auto *CastI = dyn_cast<CastInst>(I))
1134 NewOp = Builder.CreateCast(CastI->getOpcode(), Ext,
1135 I->getType()->getScalarType());
1136 else
1137 llvm_unreachable("Unsupported instruction type");
1138
1139 Result = Builder.CreateInsertElement(Result, NewOp, Idx);
1140 if (auto *ScalarizedI = dyn_cast<Instruction>(NewOp)) {
1141 ScalarizedI->copyIRFlags(I, true);
1142 Worklist.push_back(ScalarizedI);
1143 }
1144 }
1145
1146 I->replaceAllUsesWith(Result);
1147 I->dropAllReferences();
1148 I->eraseFromParent();
1149}
1150
1153 if (I.getOperand(0)->getType()->isVectorTy())
1154 scalarize(&I, Worklist);
1155 else
1156 Worklist.push_back(&I);
1157}
1158
1159static bool runImpl(Function &F, const TargetLowering &TLI,
1160 const LibcallLoweringInfo &Libcalls, AssumptionCache *AC) {
1162
1163 unsigned MaxLegalFpConvertBitWidth =
1166 MaxLegalFpConvertBitWidth = ExpandFpConvertBits;
1167
1168 unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();
1170 MaxLegalDivRemBitWidth = ExpandDivRemBits;
1171
1172 bool DisableExpandLargeFp =
1173 MaxLegalFpConvertBitWidth >= IntegerType::MAX_INT_BITS;
1174 bool DisableExpandLargeDivRem =
1175 MaxLegalDivRemBitWidth >= IntegerType::MAX_INT_BITS;
1176 bool DisableFrem = !FRemExpander::shouldExpandAnyFremType(TLI);
1177
1178 if (DisableExpandLargeFp && DisableFrem && DisableExpandLargeDivRem)
1179 return false;
1180
1181 auto ShouldHandleInst = [&](Instruction &I) {
1182 Type *Ty = I.getType();
1183 // TODO: This pass doesn't handle scalable vectors.
1184 if (Ty->isScalableTy())
1185 return false;
1186
1187 switch (I.getOpcode()) {
1188 case Instruction::FRem:
1189 return !DisableFrem && FRemExpander::shouldExpandFremType(TLI, Ty);
1190 case Instruction::FPToUI:
1191 case Instruction::FPToSI:
1192 return !DisableExpandLargeFp &&
1193 cast<IntegerType>(Ty->getScalarType())->getIntegerBitWidth() >
1194 MaxLegalFpConvertBitWidth;
1195 case Instruction::UIToFP:
1196 case Instruction::SIToFP:
1197 return !DisableExpandLargeFp &&
1198 cast<IntegerType>(I.getOperand(0)->getType()->getScalarType())
1199 ->getIntegerBitWidth() > MaxLegalFpConvertBitWidth;
1200 case Instruction::UDiv:
1201 case Instruction::SDiv:
1202 case Instruction::URem:
1203 case Instruction::SRem:
1204 // Power-of-2 divisors are handled inside the expansion (via efficient
1205 // shift/mask sequences) rather than being excluded here, so that
1206 // backends that cannot lower wide div/rem even for powers of two
1207 // (e.g. when DAGCombiner is disabled) still get valid lowered code.
1208 return !DisableExpandLargeDivRem &&
1209 cast<IntegerType>(Ty->getScalarType())->getIntegerBitWidth() >
1210 MaxLegalDivRemBitWidth;
1211 case Instruction::Call: {
1212 auto *II = dyn_cast<IntrinsicInst>(&I);
1213 if (II && (II->getIntrinsicID() == Intrinsic::fptoui_sat ||
1214 II->getIntrinsicID() == Intrinsic::fptosi_sat)) {
1215 return !DisableExpandLargeFp &&
1216 cast<IntegerType>(Ty->getScalarType())->getIntegerBitWidth() >
1217 MaxLegalFpConvertBitWidth;
1218 }
1219 return false;
1220 }
1221 }
1222
1223 return false;
1224 };
1225
1226 bool Modified = false;
1227 for (auto It = inst_begin(&F), End = inst_end(F); It != End;) {
1228 Instruction &I = *It++;
1229 if (!ShouldHandleInst(I))
1230 continue;
1231
1232 addToWorklist(I, Worklist);
1233 Modified = true;
1234 }
1235
1236 while (!Worklist.empty()) {
1237 Instruction *I = Worklist.pop_back_val();
1238
1239 switch (I->getOpcode()) {
1240 case Instruction::FRem: {
1241 auto SQ = [&]() -> std::optional<SimplifyQuery> {
1242 if (AC) {
1243 auto Res = std::make_optional<SimplifyQuery>(
1244 I->getModule()->getDataLayout(), I);
1245 Res->AC = AC;
1246 return Res;
1247 }
1248 return {};
1249 }();
1250
1252 break;
1253 }
1254
1255 case Instruction::FPToUI:
1256 expandFPToI(I, /*IsSaturating=*/false, /*IsSigned=*/false);
1257 break;
1258 case Instruction::FPToSI:
1259 expandFPToI(I, /*IsSaturating=*/false, /*IsSigned=*/true);
1260 break;
1261
1262 case Instruction::UIToFP:
1263 case Instruction::SIToFP:
1264 expandIToFP(I);
1265 break;
1266
1267 case Instruction::UDiv:
1268 case Instruction::SDiv:
1269 case Instruction::URem:
1270 case Instruction::SRem: {
1271 auto *BO = cast<BinaryOperator>(I);
1272 // TODO: isConstantPowerOfTwo does not handle vector constants, so
1273 // vector div/rem by a power-of-2 splat goes through the generic path.
1274 if (isConstantPowerOfTwo(BO->getOperand(1), isSigned(BO->getOpcode()))) {
1275 expandPow2DivRem(BO);
1276 } else {
1277 unsigned Opc = BO->getOpcode();
1278 if (Opc == Instruction::UDiv || Opc == Instruction::SDiv)
1279 expandDivision(BO);
1280 else
1281 expandRemainder(BO);
1282 }
1283 break;
1284 }
1285 case Instruction::Call: {
1286 auto *II = cast<IntrinsicInst>(I);
1287 assert(II->getIntrinsicID() == Intrinsic::fptoui_sat ||
1288 II->getIntrinsicID() == Intrinsic::fptosi_sat);
1289 expandFPToI(I, /*IsSaturating=*/true,
1290 /*IsSigned=*/II->getIntrinsicID() == Intrinsic::fptosi_sat);
1291 break;
1292 }
1293 }
1294 }
1295
1296 return Modified;
1297}
1298
1299namespace {
1300class ExpandIRInstsLegacyPass : public FunctionPass {
1301 CodeGenOptLevel OptLevel;
1302
1303public:
1304 static char ID;
1305
1306 ExpandIRInstsLegacyPass(CodeGenOptLevel OptLevel)
1307 : FunctionPass(ID), OptLevel(OptLevel) {}
1308
1309 ExpandIRInstsLegacyPass() : ExpandIRInstsLegacyPass(CodeGenOptLevel::None) {}
1310
1311 bool runOnFunction(Function &F) override {
1312 auto *TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1313 const TargetSubtargetInfo *Subtarget = TM->getSubtargetImpl(F);
1314 auto *TLI = Subtarget->getTargetLowering();
1315 AssumptionCache *AC = nullptr;
1316
1317 const LibcallLoweringInfo &Libcalls =
1318 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
1319 *F.getParent(), *Subtarget);
1320
1321 if (OptLevel != CodeGenOptLevel::None && !F.hasOptNone())
1322 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1323 return runImpl(F, *TLI, Libcalls, AC);
1324 }
1325
1326 void getAnalysisUsage(AnalysisUsage &AU) const override {
1327 AU.addRequired<LibcallLoweringInfoWrapper>();
1328 AU.addRequired<TargetPassConfig>();
1329 if (OptLevel != CodeGenOptLevel::None)
1330 AU.addRequired<AssumptionCacheTracker>();
1331 AU.addPreserved<AAResultsWrapperPass>();
1332 AU.addPreserved<GlobalsAAWrapperPass>();
1333 AU.addRequired<LibcallLoweringInfoWrapper>();
1334 }
1335};
1336} // namespace
1337
1339 CodeGenOptLevel OptLevel)
1340 : TM(&TM), OptLevel(OptLevel) {}
1341
1343 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1344 static_cast<PassInfoMixin<ExpandIRInstsPass> *>(this)->printPipeline(
1345 OS, MapClassName2PassName);
1346 OS << '<';
1347 OS << "O" << (int)OptLevel;
1348 OS << '>';
1349}
1350
1353 const TargetSubtargetInfo *STI = TM->getSubtargetImpl(F);
1354 auto &TLI = *STI->getTargetLowering();
1355 AssumptionCache *AC = nullptr;
1356 if (OptLevel != CodeGenOptLevel::None)
1357 AC = &FAM.getResult<AssumptionAnalysis>(F);
1358
1359 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1360
1361 const LibcallLoweringModuleAnalysisResult *LibcallLowering =
1362 MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(*F.getParent());
1363
1364 if (!LibcallLowering) {
1365 F.getContext().emitError("'" + LibcallLoweringModuleAnalysis::name() +
1366 "' analysis required");
1367 return PreservedAnalyses::all();
1368 }
1369
1370 const LibcallLoweringInfo &Libcalls =
1371 LibcallLowering->getLibcallLowering(*STI);
1372
1373 return runImpl(F, TLI, Libcalls, AC) ? PreservedAnalyses::none()
1375}
1376
1377char ExpandIRInstsLegacyPass::ID = 0;
1378INITIALIZE_PASS_BEGIN(ExpandIRInstsLegacyPass, "expand-ir-insts",
1379 "Expand certain fp instructions", false, false)
1381INITIALIZE_PASS_END(ExpandIRInstsLegacyPass, "expand-ir-insts",
1382 "Expand IR instructions", false, false)
1383
1385 return new ExpandIRInstsLegacyPass(OptLevel);
1386}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
static bool expandFRem(BinaryOperator &I, std::optional< SimplifyQuery > &SQ)
static void expandIToFP(Instruction *IToFP)
Generate code to convert a fp number to integer, replacing S(U)IToFP with the generated code.
static cl::opt< unsigned > ExpandDivRemBits("expand-div-rem-bits", cl::Hidden, cl::init(IntegerType::MAX_INT_BITS), cl::desc("div and rem instructions on integers with " "more than <N> bits are expanded."))
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
static void expandPow2DivRem(BinaryOperator *BO)
Expand division or remainder by a power-of-2 constant.
static bool isSigned(unsigned Opcode)
static void addToWorklist(Instruction &I, SmallVector< Instruction *, 4 > &Worklist)
static Value * addSignedBias(IRBuilder<> &Builder, Value *X, unsigned BitWidth, unsigned ShiftAmt)
For signed div/rem by a power of 2, compute the bias-adjusted dividend: Sign = ashr X,...
static cl::opt< unsigned > ExpandFpConvertBits("expand-fp-convert-bits", cl::Hidden, cl::init(IntegerType::MAX_INT_BITS), cl::desc("fp convert instructions on integers with " "more than <N> bits are expanded."))
static void expandFPToI(Instruction *FPToI, bool IsSaturating, bool IsSigned)
Generate code to convert a fp number to integer, replacing FPToS(U)I with the generated code.
static bool isConstantPowerOfTwo(Value *V, bool SignedOp)
static void scalarize(Instruction *I, SmallVectorImpl< Instruction * > &Worklist)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
Function * Fun
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1662
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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:461
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
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
BinaryOps getOpcode() const
Definition InstrTypes.h:374
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
static LLVM_ABI Constant * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
ExpandIRInstsPass(const TargetMachine &TM, CodeGenOptLevel OptLevel)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
void setAllowContract(bool B=true)
Definition FMF.h:93
bool noInfs() const
Definition FMF.h:69
void setAllowReciprocal(bool B=true)
Definition FMF.h:90
bool approxFunc() const
Definition FMF.h:73
void setNoNaNs(bool B=true)
Definition FMF.h:81
bool noNaNs() const
Definition FMF.h:68
void setNoInfs(bool B=true)
Definition FMF.h:84
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Module * getParent()
Get the module that this global value is contained inside of...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2847
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
Tracks which library functions to use for a particular subtarget.
Record a mapping from subtarget to LibcallLoweringInfo.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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 none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Multiway switch.
unsigned getMaxDivRemBitWidthSupported() const
Returns the size in bits of the maximum div/rem the backend supports.
unsigned getMaxLargeFPConvertBitWidthSupported() const
Returns the size in bits of the maximum fp to/from int conversion the backend supports.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
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
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition Type.h:161
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:317
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:290
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:241
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:110
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:399
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI bool expandDivision(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
inst_iterator inst_begin(Function *F)
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:385
LLVM_ABI FunctionPass * createExpandIRInstsPass(CodeGenOptLevel)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
inst_iterator inst_end(Function *F)
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
LLVM_ABI bool expandRemainder(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:324
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
Matching combinators.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70