1 //===- lib/CodeGen/GlobalISel/GISelKnownBits.cpp --------------*- C++ *-===//
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 /// Provides analysis for querying information about KnownBits during GISel
10 /// passes.
11 //
12 //===------------------
13 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
14 #include "llvm/Analysis/ValueTracking.h"
15 #include "llvm/CodeGen/GlobalISel/Utils.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/CodeGen/TargetOpcodes.h"
20 
21 #define DEBUG_TYPE "gisel-known-bits"
22 
23 using namespace llvm;
24 
25 char llvm::GISelKnownBitsAnalysis::ID = 0;
26 
27 INITIALIZE_PASS(GISelKnownBitsAnalysis, DEBUG_TYPE,
28                 "Analysis for ComputingKnownBits", false, true)
29 
30 GISelKnownBits::GISelKnownBits(MachineFunction &MF, unsigned MaxDepth)
31     : MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
32       DL(MF.getFunction().getParent()->getDataLayout()), MaxDepth(MaxDepth) {}
33 
34 Align GISelKnownBits::inferAlignmentForFrameIdx(int FrameIdx, int Offset,
35                                                 const MachineFunction &MF) {
36   const MachineFrameInfo &MFI = MF.getFrameInfo();
37   return commonAlignment(Align(MFI.getObjectAlignment(FrameIdx)), Offset);
38   // TODO: How to handle cases with Base + Offset?
39 }
40 
41 MaybeAlign GISelKnownBits::inferPtrAlignment(const MachineInstr &MI) {
42   if (MI.getOpcode() == TargetOpcode::G_FRAME_INDEX) {
43     int FrameIdx = MI.getOperand(1).getIndex();
44     return inferAlignmentForFrameIdx(FrameIdx, 0, *MI.getMF());
45   }
46   return None;
47 }
48 
49 void GISelKnownBits::computeKnownBitsForFrameIndex(Register R, KnownBits &Known,
50                                                    const APInt &DemandedElts,
51                                                    unsigned Depth) {
52   const MachineInstr &MI = *MRI.getVRegDef(R);
53   computeKnownBitsForAlignment(Known, inferPtrAlignment(MI));
54 }
55 
56 void GISelKnownBits::computeKnownBitsForAlignment(KnownBits &Known,
57                                                   MaybeAlign Alignment) {
58   if (Alignment)
59     // The low bits are known zero if the pointer is aligned.
60     Known.Zero.setLowBits(Log2(Alignment));
61 }
62 
63 KnownBits GISelKnownBits::getKnownBits(MachineInstr &MI) {
64   return getKnownBits(MI.getOperand(0).getReg());
65 }
66 
67 KnownBits GISelKnownBits::getKnownBits(Register R) {
68   KnownBits Known;
69   LLT Ty = MRI.getType(R);
70   APInt DemandedElts =
71       Ty.isVector() ? APInt::getAllOnesValue(Ty.getNumElements()) : APInt(1, 1);
72   computeKnownBitsImpl(R, Known, DemandedElts);
73   return Known;
74 }
75 
76 bool GISelKnownBits::signBitIsZero(Register R) {
77   LLT Ty = MRI.getType(R);
78   unsigned BitWidth = Ty.getScalarSizeInBits();
79   return maskedValueIsZero(R, APInt::getSignMask(BitWidth));
80 }
81 
82 APInt GISelKnownBits::getKnownZeroes(Register R) {
83   return getKnownBits(R).Zero;
84 }
85 
86 APInt GISelKnownBits::getKnownOnes(Register R) { return getKnownBits(R).One; }
87 
88 void GISelKnownBits::computeKnownBitsImpl(Register R, KnownBits &Known,
89                                           const APInt &DemandedElts,
90                                           unsigned Depth) {
91   MachineInstr &MI = *MRI.getVRegDef(R);
92   unsigned Opcode = MI.getOpcode();
93   LLT DstTy = MRI.getType(R);
94 
95   // Handle the case where this is called on a register that does not have a
96   // type constraint (i.e. it has a register class constraint instead). This is
97   // unlikely to occur except by looking through copies but it is possible for
98   // the initial register being queried to be in this state.
99   if (!DstTy.isValid()) {
100     Known = KnownBits();
101     return;
102   }
103 
104   unsigned BitWidth = DstTy.getSizeInBits();
105   Known = KnownBits(BitWidth); // Don't know anything
106 
107   if (DstTy.isVector())
108     return; // TODO: Handle vectors.
109 
110   // Depth may get bigger than max depth if it gets passed to a different
111   // GISelKnownBits object.
112   // This may happen when say a generic part uses a GISelKnownBits object
113   // with some max depth, but then we hit TL.computeKnownBitsForTargetInstr
114   // which creates a new GISelKnownBits object with a different and smaller
115   // depth. If we just check for equality, we would never exit if the depth
116   // that is passed down to the target specific GISelKnownBits object is
117   // already bigger than its max depth.
118   if (Depth >= getMaxDepth())
119     return;
120 
121   if (!DemandedElts)
122     return; // No demanded elts, better to assume we don't know anything.
123 
124   KnownBits Known2;
125 
126   switch (Opcode) {
127   default:
128     TL.computeKnownBitsForTargetInstr(*this, R, Known, DemandedElts, MRI,
129                                       Depth);
130     break;
131   case TargetOpcode::COPY:
132   case TargetOpcode::G_PHI:
133   case TargetOpcode::PHI: {
134     Known.One = APInt::getAllOnesValue(BitWidth);
135     Known.Zero = APInt::getAllOnesValue(BitWidth);
136     // Destination registers should not have subregisters at this
137     // point of the pipeline, otherwise the main live-range will be
138     // defined more than once, which is against SSA.
139     assert(MI.getOperand(0).getSubReg() == 0 && "Is this code in SSA?");
140     // PHI's operand are a mix of registers and basic blocks interleaved.
141     // We only care about the register ones.
142     for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
143       const MachineOperand &Src = MI.getOperand(Idx);
144       Register SrcReg = Src.getReg();
145       // Look through trivial copies and phis but don't look through trivial
146       // copies or phis of the form `%1:(s32) = OP %0:gpr32`, known-bits
147       // analysis is currently unable to determine the bit width of a
148       // register class.
149       //
150       // We can't use NoSubRegister by name as it's defined by each target but
151       // it's always defined to be 0 by tablegen.
152       if (SrcReg.isVirtual() && Src.getSubReg() == 0 /*NoSubRegister*/ &&
153           MRI.getType(SrcReg).isValid()) {
154         // For COPYs we don't do anything, don't increase the depth.
155         computeKnownBitsImpl(SrcReg, Known2, DemandedElts,
156                              Depth + (Opcode != TargetOpcode::COPY));
157         Known.One &= Known2.One;
158         Known.Zero &= Known2.Zero;
159       } else {
160         // We know nothing.
161         Known = KnownBits(BitWidth);
162         break;
163       }
164     }
165     break;
166   }
167   case TargetOpcode::G_CONSTANT: {
168     auto CstVal = getConstantVRegVal(R, MRI);
169     if (!CstVal)
170       break;
171     Known.One = *CstVal;
172     Known.Zero = ~Known.One;
173     break;
174   }
175   case TargetOpcode::G_FRAME_INDEX: {
176     computeKnownBitsForFrameIndex(R, Known, DemandedElts);
177     break;
178   }
179   case TargetOpcode::G_SUB: {
180     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
181                          Depth + 1);
182     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
183                          Depth + 1);
184     Known = KnownBits::computeForAddSub(/*Add*/ false, /*NSW*/ false, Known,
185                                         Known2);
186     break;
187   }
188   case TargetOpcode::G_XOR: {
189     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
190                          Depth + 1);
191     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
192                          Depth + 1);
193 
194     // Output known-0 bits are known if clear or set in both the LHS & RHS.
195     APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
196     // Output known-1 are known to be set if set in only one of the LHS, RHS.
197     Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
198     Known.Zero = KnownZeroOut;
199     break;
200   }
201   case TargetOpcode::G_PTR_ADD: {
202     // G_PTR_ADD is like G_ADD. FIXME: Is this true for all targets?
203     LLT Ty = MRI.getType(MI.getOperand(1).getReg());
204     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
205       break;
206     LLVM_FALLTHROUGH;
207   }
208   case TargetOpcode::G_ADD: {
209     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
210                          Depth + 1);
211     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
212                          Depth + 1);
213     Known =
214         KnownBits::computeForAddSub(/*Add*/ true, /*NSW*/ false, Known, Known2);
215     break;
216   }
217   case TargetOpcode::G_AND: {
218     // If either the LHS or the RHS are Zero, the result is zero.
219     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
220                          Depth + 1);
221     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
222                          Depth + 1);
223 
224     // Output known-1 bits are only known if set in both the LHS & RHS.
225     Known.One &= Known2.One;
226     // Output known-0 are known to be clear if zero in either the LHS | RHS.
227     Known.Zero |= Known2.Zero;
228     break;
229   }
230   case TargetOpcode::G_OR: {
231     // If either the LHS or the RHS are Zero, the result is zero.
232     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
233                          Depth + 1);
234     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
235                          Depth + 1);
236 
237     // Output known-0 bits are only known if clear in both the LHS & RHS.
238     Known.Zero &= Known2.Zero;
239     // Output known-1 are known to be set if set in either the LHS | RHS.
240     Known.One |= Known2.One;
241     break;
242   }
243   case TargetOpcode::G_MUL: {
244     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
245                          Depth + 1);
246     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
247                          Depth + 1);
248     // If low bits are zero in either operand, output low known-0 bits.
249     // Also compute a conservative estimate for high known-0 bits.
250     // More trickiness is possible, but this is sufficient for the
251     // interesting case of alignment computation.
252     unsigned TrailZ =
253         Known.countMinTrailingZeros() + Known2.countMinTrailingZeros();
254     unsigned LeadZ =
255         std::max(Known.countMinLeadingZeros() + Known2.countMinLeadingZeros(),
256                  BitWidth) -
257         BitWidth;
258 
259     Known.resetAll();
260     Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
261     Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
262     break;
263   }
264   case TargetOpcode::G_SELECT: {
265     computeKnownBitsImpl(MI.getOperand(3).getReg(), Known, DemandedElts,
266                          Depth + 1);
267     // If we don't know any bits, early out.
268     if (Known.isUnknown())
269       break;
270     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
271                          Depth + 1);
272     // Only known if known in both the LHS and RHS.
273     Known.One &= Known2.One;
274     Known.Zero &= Known2.Zero;
275     break;
276   }
277   case TargetOpcode::G_FCMP:
278   case TargetOpcode::G_ICMP: {
279     if (TL.getBooleanContents(DstTy.isVector(),
280                               Opcode == TargetOpcode::G_FCMP) ==
281             TargetLowering::ZeroOrOneBooleanContent &&
282         BitWidth > 1)
283       Known.Zero.setBitsFrom(1);
284     break;
285   }
286   case TargetOpcode::G_SEXT: {
287     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
288                          Depth + 1);
289     // If the sign bit is known to be zero or one, then sext will extend
290     // it to the top bits, else it will just zext.
291     Known = Known.sext(BitWidth);
292     break;
293   }
294   case TargetOpcode::G_ANYEXT: {
295     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
296                          Depth + 1);
297     Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
298     break;
299   }
300   case TargetOpcode::G_LOAD: {
301     if (MI.hasOneMemOperand()) {
302       const MachineMemOperand *MMO = *MI.memoperands_begin();
303       if (const MDNode *Ranges = MMO->getRanges()) {
304         computeKnownBitsFromRangeMetadata(*Ranges, Known);
305       }
306     }
307     break;
308   }
309   case TargetOpcode::G_ZEXTLOAD: {
310     // Everything above the retrieved bits is zero
311     if (MI.hasOneMemOperand())
312       Known.Zero.setBitsFrom((*MI.memoperands_begin())->getSizeInBits());
313     break;
314   }
315   case TargetOpcode::G_ASHR:
316   case TargetOpcode::G_LSHR:
317   case TargetOpcode::G_SHL: {
318     KnownBits RHSKnown;
319     computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
320                          Depth + 1);
321     if (!RHSKnown.isConstant()) {
322       LLVM_DEBUG(
323           MachineInstr *RHSMI = MRI.getVRegDef(MI.getOperand(2).getReg());
324           dbgs() << '[' << Depth << "] Shift not known constant: " << *RHSMI);
325       break;
326     }
327     uint64_t Shift = RHSKnown.getConstant().getZExtValue();
328     LLVM_DEBUG(dbgs() << '[' << Depth << "] Shift is " << Shift << '\n');
329 
330     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
331                          Depth + 1);
332 
333     switch (Opcode) {
334     case TargetOpcode::G_ASHR:
335       Known.Zero = Known.Zero.ashr(Shift);
336       Known.One = Known.One.ashr(Shift);
337       break;
338     case TargetOpcode::G_LSHR:
339       Known.Zero = Known.Zero.lshr(Shift);
340       Known.One = Known.One.lshr(Shift);
341       Known.Zero.setBitsFrom(Known.Zero.getBitWidth() - Shift);
342       break;
343     case TargetOpcode::G_SHL:
344       Known.Zero = Known.Zero.shl(Shift);
345       Known.One = Known.One.shl(Shift);
346       Known.Zero.setBits(0, Shift);
347       break;
348     }
349     break;
350   }
351   case TargetOpcode::G_INTTOPTR:
352   case TargetOpcode::G_PTRTOINT:
353     // Fall through and handle them the same as zext/trunc.
354     LLVM_FALLTHROUGH;
355   case TargetOpcode::G_ZEXT:
356   case TargetOpcode::G_TRUNC: {
357     Register SrcReg = MI.getOperand(1).getReg();
358     LLT SrcTy = MRI.getType(SrcReg);
359     unsigned SrcBitWidth = SrcTy.isPointer()
360                                ? DL.getIndexSizeInBits(SrcTy.getAddressSpace())
361                                : SrcTy.getSizeInBits();
362     assert(SrcBitWidth && "SrcBitWidth can't be zero");
363     Known = Known.zextOrTrunc(SrcBitWidth, true);
364     computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
365     Known = Known.zextOrTrunc(BitWidth, true);
366     if (BitWidth > SrcBitWidth)
367       Known.Zero.setBitsFrom(SrcBitWidth);
368     break;
369   }
370   }
371 
372   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
373   LLVM_DEBUG(dbgs() << "[" << Depth << "] Compute known bits: " << MI << "["
374                     << Depth << "] Computed for: " << MI << "[" << Depth
375                     << "] Known: 0x"
376                     << (Known.Zero | Known.One).toString(16, false) << "\n"
377                     << "[" << Depth << "] Zero: 0x"
378                     << Known.Zero.toString(16, false) << "\n"
379                     << "[" << Depth << "] One:  0x"
380                     << Known.One.toString(16, false) << "\n");
381 }
382 
383 unsigned GISelKnownBits::computeNumSignBits(Register R,
384                                             const APInt &DemandedElts,
385                                             unsigned Depth) {
386   MachineInstr &MI = *MRI.getVRegDef(R);
387   unsigned Opcode = MI.getOpcode();
388 
389   if (Opcode == TargetOpcode::G_CONSTANT)
390     return MI.getOperand(1).getCImm()->getValue().getNumSignBits();
391 
392   if (Depth == getMaxDepth())
393     return 1;
394 
395   if (!DemandedElts)
396     return 1; // No demanded elts, better to assume we don't know anything.
397 
398   LLT DstTy = MRI.getType(R);
399 
400   // Handle the case where this is called on a register that does not have a
401   // type constraint. This is unlikely to occur except by looking through copies
402   // but it is possible for the initial register being queried to be in this
403   // state.
404   if (!DstTy.isValid())
405     return 1;
406 
407   switch (Opcode) {
408   case TargetOpcode::COPY: {
409     MachineOperand &Src = MI.getOperand(1);
410     if (Src.getReg().isVirtual() && Src.getSubReg() == 0 &&
411         MRI.getType(Src.getReg()).isValid()) {
412       // Don't increment Depth for this one since we didn't do any work.
413       return computeNumSignBits(Src.getReg(), DemandedElts, Depth);
414     }
415 
416     return 1;
417   }
418   case TargetOpcode::G_SEXT: {
419     Register Src = MI.getOperand(1).getReg();
420     LLT SrcTy = MRI.getType(Src);
421     unsigned Tmp = DstTy.getScalarSizeInBits() - SrcTy.getScalarSizeInBits();
422     return computeNumSignBits(Src, DemandedElts, Depth + 1) + Tmp;
423   }
424   case TargetOpcode::G_TRUNC: {
425     Register Src = MI.getOperand(1).getReg();
426     LLT SrcTy = MRI.getType(Src);
427 
428     // Check if the sign bits of source go down as far as the truncated value.
429     unsigned DstTyBits = DstTy.getScalarSizeInBits();
430     unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
431     unsigned NumSrcSignBits = computeNumSignBits(Src, DemandedElts, Depth + 1);
432     if (NumSrcSignBits > (NumSrcBits - DstTyBits))
433       return NumSrcSignBits - (NumSrcBits - DstTyBits);
434     break;
435   }
436   default:
437     break;
438   }
439 
440   // TODO: Handle target instructions
441   // TODO: Fall back to known bits
442   return 1;
443 }
444 
445 unsigned GISelKnownBits::computeNumSignBits(Register R, unsigned Depth) {
446   LLT Ty = MRI.getType(R);
447   APInt DemandedElts = Ty.isVector()
448                            ? APInt::getAllOnesValue(Ty.getNumElements())
449                            : APInt(1, 1);
450   return computeNumSignBits(R, DemandedElts, Depth);
451 }
452 
453 void GISelKnownBitsAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
454   AU.setPreservesAll();
455   MachineFunctionPass::getAnalysisUsage(AU);
456 }
457 
458 bool GISelKnownBitsAnalysis::runOnMachineFunction(MachineFunction &MF) {
459   return false;
460 }
461