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(MFI.getObjectAlign(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   const LLT Ty = MRI.getType(R);
69   APInt DemandedElts =
70       Ty.isVector() ? APInt::getAllOnesValue(Ty.getNumElements()) : APInt(1, 1);
71   return getKnownBits(R, DemandedElts);
72 }
73 
74 KnownBits GISelKnownBits::getKnownBits(Register R, const APInt &DemandedElts,
75                                        unsigned Depth) {
76   // For now, we only maintain the cache during one request.
77   assert(ComputeKnownBitsCache.empty() && "Cache should have been cleared");
78 
79   KnownBits Known;
80   computeKnownBitsImpl(R, Known, DemandedElts);
81   ComputeKnownBitsCache.clear();
82   return Known;
83 }
84 
85 bool GISelKnownBits::signBitIsZero(Register R) {
86   LLT Ty = MRI.getType(R);
87   unsigned BitWidth = Ty.getScalarSizeInBits();
88   return maskedValueIsZero(R, APInt::getSignMask(BitWidth));
89 }
90 
91 APInt GISelKnownBits::getKnownZeroes(Register R) {
92   return getKnownBits(R).Zero;
93 }
94 
95 APInt GISelKnownBits::getKnownOnes(Register R) { return getKnownBits(R).One; }
96 
97 LLVM_ATTRIBUTE_UNUSED static void
98 dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth) {
99   dbgs() << "[" << Depth << "] Compute known bits: " << MI << "[" << Depth
100          << "] Computed for: " << MI << "[" << Depth << "] Known: 0x"
101          << (Known.Zero | Known.One).toString(16, false) << "\n"
102          << "[" << Depth << "] Zero: 0x" << Known.Zero.toString(16, false)
103          << "\n"
104          << "[" << Depth << "] One:  0x" << Known.One.toString(16, false)
105          << "\n";
106 }
107 
108 void GISelKnownBits::computeKnownBitsImpl(Register R, KnownBits &Known,
109                                           const APInt &DemandedElts,
110                                           unsigned Depth) {
111   MachineInstr &MI = *MRI.getVRegDef(R);
112   unsigned Opcode = MI.getOpcode();
113   LLT DstTy = MRI.getType(R);
114 
115   // Handle the case where this is called on a register that does not have a
116   // type constraint (i.e. it has a register class constraint instead). This is
117   // unlikely to occur except by looking through copies but it is possible for
118   // the initial register being queried to be in this state.
119   if (!DstTy.isValid()) {
120     Known = KnownBits();
121     return;
122   }
123 
124   unsigned BitWidth = DstTy.getSizeInBits();
125   auto CacheEntry = ComputeKnownBitsCache.find(R);
126   if (CacheEntry != ComputeKnownBitsCache.end()) {
127     Known = CacheEntry->second;
128     LLVM_DEBUG(dbgs() << "Cache hit at ");
129     LLVM_DEBUG(dumpResult(MI, Known, Depth));
130     assert(Known.getBitWidth() == BitWidth && "Cache entry size doesn't match");
131     return;
132   }
133   Known = KnownBits(BitWidth); // Don't know anything
134 
135   if (DstTy.isVector())
136     return; // TODO: Handle vectors.
137 
138   // Depth may get bigger than max depth if it gets passed to a different
139   // GISelKnownBits object.
140   // This may happen when say a generic part uses a GISelKnownBits object
141   // with some max depth, but then we hit TL.computeKnownBitsForTargetInstr
142   // which creates a new GISelKnownBits object with a different and smaller
143   // depth. If we just check for equality, we would never exit if the depth
144   // that is passed down to the target specific GISelKnownBits object is
145   // already bigger than its max depth.
146   if (Depth >= getMaxDepth())
147     return;
148 
149   if (!DemandedElts)
150     return; // No demanded elts, better to assume we don't know anything.
151 
152   KnownBits Known2;
153 
154   switch (Opcode) {
155   default:
156     TL.computeKnownBitsForTargetInstr(*this, R, Known, DemandedElts, MRI,
157                                       Depth);
158     break;
159   case TargetOpcode::COPY:
160   case TargetOpcode::G_PHI:
161   case TargetOpcode::PHI: {
162     Known.One = APInt::getAllOnesValue(BitWidth);
163     Known.Zero = APInt::getAllOnesValue(BitWidth);
164     // Destination registers should not have subregisters at this
165     // point of the pipeline, otherwise the main live-range will be
166     // defined more than once, which is against SSA.
167     assert(MI.getOperand(0).getSubReg() == 0 && "Is this code in SSA?");
168     // Record in the cache that we know nothing for MI.
169     // This will get updated later and in the meantime, if we reach that
170     // phi again, because of a loop, we will cut the search thanks to this
171     // cache entry.
172     // We could actually build up more information on the phi by not cutting
173     // the search, but that additional information is more a side effect
174     // than an intended choice.
175     // Therefore, for now, save on compile time until we derive a proper way
176     // to derive known bits for PHIs within loops.
177     ComputeKnownBitsCache[R] = KnownBits(BitWidth);
178     // PHI's operand are a mix of registers and basic blocks interleaved.
179     // We only care about the register ones.
180     for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
181       const MachineOperand &Src = MI.getOperand(Idx);
182       Register SrcReg = Src.getReg();
183       // Look through trivial copies and phis but don't look through trivial
184       // copies or phis of the form `%1:(s32) = OP %0:gpr32`, known-bits
185       // analysis is currently unable to determine the bit width of a
186       // register class.
187       //
188       // We can't use NoSubRegister by name as it's defined by each target but
189       // it's always defined to be 0 by tablegen.
190       if (SrcReg.isVirtual() && Src.getSubReg() == 0 /*NoSubRegister*/ &&
191           MRI.getType(SrcReg).isValid()) {
192         // For COPYs we don't do anything, don't increase the depth.
193         computeKnownBitsImpl(SrcReg, Known2, DemandedElts,
194                              Depth + (Opcode != TargetOpcode::COPY));
195         Known.One &= Known2.One;
196         Known.Zero &= Known2.Zero;
197         // If we reach a point where we don't know anything
198         // just stop looking through the operands.
199         if (Known.One == 0 && Known.Zero == 0)
200           break;
201       } else {
202         // We know nothing.
203         Known = KnownBits(BitWidth);
204         break;
205       }
206     }
207     break;
208   }
209   case TargetOpcode::G_CONSTANT: {
210     auto CstVal = getConstantVRegVal(R, MRI);
211     if (!CstVal)
212       break;
213     Known.One = *CstVal;
214     Known.Zero = ~Known.One;
215     break;
216   }
217   case TargetOpcode::G_FRAME_INDEX: {
218     computeKnownBitsForFrameIndex(R, Known, DemandedElts);
219     break;
220   }
221   case TargetOpcode::G_SUB: {
222     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
223                          Depth + 1);
224     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
225                          Depth + 1);
226     Known = KnownBits::computeForAddSub(/*Add*/ false, /*NSW*/ false, Known,
227                                         Known2);
228     break;
229   }
230   case TargetOpcode::G_XOR: {
231     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
232                          Depth + 1);
233     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
234                          Depth + 1);
235 
236     Known ^= Known2;
237     break;
238   }
239   case TargetOpcode::G_PTR_ADD: {
240     // G_PTR_ADD is like G_ADD. FIXME: Is this true for all targets?
241     LLT Ty = MRI.getType(MI.getOperand(1).getReg());
242     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
243       break;
244     LLVM_FALLTHROUGH;
245   }
246   case TargetOpcode::G_ADD: {
247     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
248                          Depth + 1);
249     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
250                          Depth + 1);
251     Known =
252         KnownBits::computeForAddSub(/*Add*/ true, /*NSW*/ false, Known, Known2);
253     break;
254   }
255   case TargetOpcode::G_AND: {
256     // If either the LHS or the RHS are Zero, the result is zero.
257     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
258                          Depth + 1);
259     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
260                          Depth + 1);
261 
262     Known &= Known2;
263     break;
264   }
265   case TargetOpcode::G_OR: {
266     // If either the LHS or the RHS are Zero, the result is zero.
267     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
268                          Depth + 1);
269     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
270                          Depth + 1);
271 
272     Known |= Known2;
273     break;
274   }
275   case TargetOpcode::G_MUL: {
276     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
277                          Depth + 1);
278     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
279                          Depth + 1);
280     // If low bits are zero in either operand, output low known-0 bits.
281     // Also compute a conservative estimate for high known-0 bits.
282     // More trickiness is possible, but this is sufficient for the
283     // interesting case of alignment computation.
284     unsigned TrailZ =
285         Known.countMinTrailingZeros() + Known2.countMinTrailingZeros();
286     unsigned LeadZ =
287         std::max(Known.countMinLeadingZeros() + Known2.countMinLeadingZeros(),
288                  BitWidth) -
289         BitWidth;
290 
291     Known.resetAll();
292     Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
293     Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
294     break;
295   }
296   case TargetOpcode::G_SELECT: {
297     computeKnownBitsImpl(MI.getOperand(3).getReg(), Known, DemandedElts,
298                          Depth + 1);
299     // If we don't know any bits, early out.
300     if (Known.isUnknown())
301       break;
302     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
303                          Depth + 1);
304     // Only known if known in both the LHS and RHS.
305     Known.One &= Known2.One;
306     Known.Zero &= Known2.Zero;
307     break;
308   }
309   case TargetOpcode::G_FCMP:
310   case TargetOpcode::G_ICMP: {
311     if (TL.getBooleanContents(DstTy.isVector(),
312                               Opcode == TargetOpcode::G_FCMP) ==
313             TargetLowering::ZeroOrOneBooleanContent &&
314         BitWidth > 1)
315       Known.Zero.setBitsFrom(1);
316     break;
317   }
318   case TargetOpcode::G_SEXT: {
319     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
320                          Depth + 1);
321     // If the sign bit is known to be zero or one, then sext will extend
322     // it to the top bits, else it will just zext.
323     Known = Known.sext(BitWidth);
324     break;
325   }
326   case TargetOpcode::G_ANYEXT: {
327     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
328                          Depth + 1);
329     Known = Known.zext(BitWidth);
330     break;
331   }
332   case TargetOpcode::G_LOAD: {
333     if (MI.hasOneMemOperand()) {
334       const MachineMemOperand *MMO = *MI.memoperands_begin();
335       if (const MDNode *Ranges = MMO->getRanges()) {
336         computeKnownBitsFromRangeMetadata(*Ranges, Known);
337       }
338     }
339     break;
340   }
341   case TargetOpcode::G_ZEXTLOAD: {
342     // Everything above the retrieved bits is zero
343     if (MI.hasOneMemOperand())
344       Known.Zero.setBitsFrom((*MI.memoperands_begin())->getSizeInBits());
345     break;
346   }
347   case TargetOpcode::G_ASHR:
348   case TargetOpcode::G_LSHR:
349   case TargetOpcode::G_SHL: {
350     KnownBits RHSKnown;
351     computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
352                          Depth + 1);
353     if (!RHSKnown.isConstant()) {
354       LLVM_DEBUG(
355           MachineInstr *RHSMI = MRI.getVRegDef(MI.getOperand(2).getReg());
356           dbgs() << '[' << Depth << "] Shift not known constant: " << *RHSMI);
357       break;
358     }
359     uint64_t Shift = RHSKnown.getConstant().getZExtValue();
360     LLVM_DEBUG(dbgs() << '[' << Depth << "] Shift is " << Shift << '\n');
361 
362     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
363                          Depth + 1);
364 
365     switch (Opcode) {
366     case TargetOpcode::G_ASHR:
367       Known.Zero = Known.Zero.ashr(Shift);
368       Known.One = Known.One.ashr(Shift);
369       break;
370     case TargetOpcode::G_LSHR:
371       Known.Zero = Known.Zero.lshr(Shift);
372       Known.One = Known.One.lshr(Shift);
373       Known.Zero.setBitsFrom(Known.Zero.getBitWidth() - Shift);
374       break;
375     case TargetOpcode::G_SHL:
376       Known.Zero = Known.Zero.shl(Shift);
377       Known.One = Known.One.shl(Shift);
378       Known.Zero.setBits(0, Shift);
379       break;
380     }
381     break;
382   }
383   case TargetOpcode::G_INTTOPTR:
384   case TargetOpcode::G_PTRTOINT:
385     // Fall through and handle them the same as zext/trunc.
386     LLVM_FALLTHROUGH;
387   case TargetOpcode::G_ZEXT:
388   case TargetOpcode::G_TRUNC: {
389     Register SrcReg = MI.getOperand(1).getReg();
390     LLT SrcTy = MRI.getType(SrcReg);
391     unsigned SrcBitWidth = SrcTy.isPointer()
392                                ? DL.getIndexSizeInBits(SrcTy.getAddressSpace())
393                                : SrcTy.getSizeInBits();
394     assert(SrcBitWidth && "SrcBitWidth can't be zero");
395     Known = Known.zextOrTrunc(SrcBitWidth);
396     computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
397     Known = Known.zextOrTrunc(BitWidth);
398     if (BitWidth > SrcBitWidth)
399       Known.Zero.setBitsFrom(SrcBitWidth);
400     break;
401   }
402   }
403 
404   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
405   LLVM_DEBUG(dumpResult(MI, Known, Depth));
406 
407   // Update the cache.
408   ComputeKnownBitsCache[R] = Known;
409 }
410 
411 unsigned GISelKnownBits::computeNumSignBits(Register R,
412                                             const APInt &DemandedElts,
413                                             unsigned Depth) {
414   MachineInstr &MI = *MRI.getVRegDef(R);
415   unsigned Opcode = MI.getOpcode();
416 
417   if (Opcode == TargetOpcode::G_CONSTANT)
418     return MI.getOperand(1).getCImm()->getValue().getNumSignBits();
419 
420   if (Depth == getMaxDepth())
421     return 1;
422 
423   if (!DemandedElts)
424     return 1; // No demanded elts, better to assume we don't know anything.
425 
426   LLT DstTy = MRI.getType(R);
427   const unsigned TyBits = DstTy.getScalarSizeInBits();
428 
429   // Handle the case where this is called on a register that does not have a
430   // type constraint. This is unlikely to occur except by looking through copies
431   // but it is possible for the initial register being queried to be in this
432   // state.
433   if (!DstTy.isValid())
434     return 1;
435 
436   unsigned FirstAnswer = 1;
437   switch (Opcode) {
438   case TargetOpcode::COPY: {
439     MachineOperand &Src = MI.getOperand(1);
440     if (Src.getReg().isVirtual() && Src.getSubReg() == 0 &&
441         MRI.getType(Src.getReg()).isValid()) {
442       // Don't increment Depth for this one since we didn't do any work.
443       return computeNumSignBits(Src.getReg(), DemandedElts, Depth);
444     }
445 
446     return 1;
447   }
448   case TargetOpcode::G_SEXT: {
449     Register Src = MI.getOperand(1).getReg();
450     LLT SrcTy = MRI.getType(Src);
451     unsigned Tmp = DstTy.getScalarSizeInBits() - SrcTy.getScalarSizeInBits();
452     return computeNumSignBits(Src, DemandedElts, Depth + 1) + Tmp;
453   }
454   case TargetOpcode::G_TRUNC: {
455     Register Src = MI.getOperand(1).getReg();
456     LLT SrcTy = MRI.getType(Src);
457 
458     // Check if the sign bits of source go down as far as the truncated value.
459     unsigned DstTyBits = DstTy.getScalarSizeInBits();
460     unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
461     unsigned NumSrcSignBits = computeNumSignBits(Src, DemandedElts, Depth + 1);
462     if (NumSrcSignBits > (NumSrcBits - DstTyBits))
463       return NumSrcSignBits - (NumSrcBits - DstTyBits);
464     break;
465   }
466   case TargetOpcode::G_INTRINSIC:
467   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
468   default: {
469     unsigned NumBits =
470       TL.computeNumSignBitsForTargetInstr(*this, R, DemandedElts, MRI, Depth);
471     if (NumBits > 1)
472       FirstAnswer = std::max(FirstAnswer, NumBits);
473     break;
474   }
475   }
476 
477   // Finally, if we can prove that the top bits of the result are 0's or 1's,
478   // use this information.
479   KnownBits Known = getKnownBits(R, DemandedElts, Depth);
480   APInt Mask;
481   if (Known.isNonNegative()) {        // sign bit is 0
482     Mask = Known.Zero;
483   } else if (Known.isNegative()) {  // sign bit is 1;
484     Mask = Known.One;
485   } else {
486     // Nothing known.
487     return FirstAnswer;
488   }
489 
490   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
491   // the number of identical bits in the top of the input value.
492   Mask <<= Mask.getBitWidth() - TyBits;
493   return std::max(FirstAnswer, Mask.countLeadingOnes());
494 }
495 
496 unsigned GISelKnownBits::computeNumSignBits(Register R, unsigned Depth) {
497   LLT Ty = MRI.getType(R);
498   APInt DemandedElts = Ty.isVector()
499                            ? APInt::getAllOnesValue(Ty.getNumElements())
500                            : APInt(1, 1);
501   return computeNumSignBits(R, DemandedElts, Depth);
502 }
503 
504 void GISelKnownBitsAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
505   AU.setPreservesAll();
506   MachineFunctionPass::getAnalysisUsage(AU);
507 }
508 
509 bool GISelKnownBitsAnalysis::runOnMachineFunction(MachineFunction &MF) {
510   return false;
511 }
512