1 //===--- HexagonGenExtract.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/IR/Constants.h"
12 #include "llvm/IR/Dominators.h"
13 #include "llvm/IR/Function.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/IRBuilder.h"
17 #include "llvm/IR/PatternMatch.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 
26 static cl::opt<unsigned> ExtractCutoff("extract-cutoff", cl::init(~0U),
27   cl::Hidden, cl::desc("Cutoff for generating \"extract\""
28   " instructions"));
29 
30 // This prevents generating extract instructions that have the offset of 0.
31 // One of the reasons for "extract" is to put a sequence of bits in a regis-
32 // ter, starting at offset 0 (so that these bits can then be used by an
33 // "insert"). If the bits are already at offset 0, it is better not to gene-
34 // rate "extract", since logical bit operations can be merged into compound
35 // instructions (as opposed to "extract").
36 static cl::opt<bool> NoSR0("extract-nosr0", cl::init(true), cl::Hidden,
37   cl::desc("No extract instruction with offset 0"));
38 
39 static cl::opt<bool> NeedAnd("extract-needand", cl::init(true), cl::Hidden,
40   cl::desc("Require & in extract patterns"));
41 
42 namespace llvm {
43   void initializeHexagonGenExtractPass(PassRegistry&);
44   FunctionPass *createHexagonGenExtract();
45 }
46 
47 
48 namespace {
49   class HexagonGenExtract : public FunctionPass {
50   public:
51     static char ID;
52     HexagonGenExtract() : FunctionPass(ID), ExtractCount(0) {
53       initializeHexagonGenExtractPass(*PassRegistry::getPassRegistry());
54     }
55     virtual StringRef getPassName() const override {
56       return "Hexagon generate \"extract\" instructions";
57     }
58     virtual bool runOnFunction(Function &F) override;
59     virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
60       AU.addRequired<DominatorTreeWrapperPass>();
61       AU.addPreserved<DominatorTreeWrapperPass>();
62       FunctionPass::getAnalysisUsage(AU);
63     }
64   private:
65     bool visitBlock(BasicBlock *B);
66     bool convert(Instruction *In);
67 
68     unsigned ExtractCount;
69     DominatorTree *DT;
70   };
71 
72   char HexagonGenExtract::ID = 0;
73 }
74 
75 INITIALIZE_PASS_BEGIN(HexagonGenExtract, "hextract", "Hexagon generate "
76   "\"extract\" instructions", false, false)
77 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
78 INITIALIZE_PASS_END(HexagonGenExtract, "hextract", "Hexagon generate "
79   "\"extract\" instructions", false, false)
80 
81 
82 bool HexagonGenExtract::convert(Instruction *In) {
83   using namespace PatternMatch;
84   Value *BF = 0;
85   ConstantInt *CSL = 0, *CSR = 0, *CM = 0;
86   BasicBlock *BB = In->getParent();
87   LLVMContext &Ctx = BB->getContext();
88   bool LogicalSR;
89 
90   // (and (shl (lshr x, #sr), #sl), #m)
91   LogicalSR = true;
92   bool Match = match(In, m_And(m_Shl(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
93                                m_ConstantInt(CSL)),
94                          m_ConstantInt(CM)));
95 
96   if (!Match) {
97     // (and (shl (ashr x, #sr), #sl), #m)
98     LogicalSR = false;
99     Match = match(In, m_And(m_Shl(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
100                             m_ConstantInt(CSL)),
101                       m_ConstantInt(CM)));
102   }
103   if (!Match) {
104     // (and (shl x, #sl), #m)
105     LogicalSR = true;
106     CSR = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
107     Match = match(In, m_And(m_Shl(m_Value(BF), m_ConstantInt(CSL)),
108                       m_ConstantInt(CM)));
109     if (Match && NoSR0)
110       return false;
111   }
112   if (!Match) {
113     // (and (lshr x, #sr), #m)
114     LogicalSR = true;
115     CSL = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
116     Match = match(In, m_And(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
117                             m_ConstantInt(CM)));
118   }
119   if (!Match) {
120     // (and (ashr x, #sr), #m)
121     LogicalSR = false;
122     CSL = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
123     Match = match(In, m_And(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
124                             m_ConstantInt(CM)));
125   }
126   if (!Match) {
127     CM = 0;
128     // (shl (lshr x, #sr), #sl)
129     LogicalSR = true;
130     Match = match(In, m_Shl(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
131                             m_ConstantInt(CSL)));
132   }
133   if (!Match) {
134     CM = 0;
135     // (shl (ashr x, #sr), #sl)
136     LogicalSR = false;
137     Match = match(In, m_Shl(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
138                             m_ConstantInt(CSL)));
139   }
140   if (!Match)
141     return false;
142 
143   Type *Ty = BF->getType();
144   if (!Ty->isIntegerTy())
145     return false;
146   unsigned BW = Ty->getPrimitiveSizeInBits();
147   if (BW != 32 && BW != 64)
148     return false;
149 
150   uint32_t SR = CSR->getZExtValue();
151   uint32_t SL = CSL->getZExtValue();
152 
153   if (!CM) {
154     // If there was no and, and the shift left did not remove all potential
155     // sign bits created by the shift right, then extractu cannot reproduce
156     // this value.
157     if (!LogicalSR && (SR > SL))
158       return false;
159     APInt A = APInt(BW, ~0ULL).lshr(SR).shl(SL);
160     CM = ConstantInt::get(Ctx, A);
161   }
162 
163   // CM is the shifted-left mask. Shift it back right to remove the zero
164   // bits on least-significant positions.
165   APInt M = CM->getValue().lshr(SL);
166   uint32_t T = M.countTrailingOnes();
167 
168   // During the shifts some of the bits will be lost. Calculate how many
169   // of the original value will remain after shift right and then left.
170   uint32_t U = BW - std::max(SL, SR);
171   // The width of the extracted field is the minimum of the original bits
172   // that remain after the shifts and the number of contiguous 1s in the mask.
173   uint32_t W = std::min(U, T);
174   if (W == 0)
175     return false;
176 
177   // Check if the extracted bits are contained within the mask that it is
178   // and-ed with. The extract operation will copy these bits, and so the
179   // mask cannot any holes in it that would clear any of the bits of the
180   // extracted field.
181   if (!LogicalSR) {
182     // If the shift right was arithmetic, it could have included some 1 bits.
183     // It is still ok to generate extract, but only if the mask eliminates
184     // those bits (i.e. M does not have any bits set beyond U).
185     APInt C = APInt::getHighBitsSet(BW, BW-U);
186     if (M.intersects(C) || !APIntOps::isMask(W, M))
187       return false;
188   } else {
189     // Check if M starts with a contiguous sequence of W times 1 bits. Get
190     // the low U bits of M (which eliminates the 0 bits shifted in on the
191     // left), and check if the result is APInt's "mask":
192     if (!APIntOps::isMask(W, M.getLoBits(U)))
193       return false;
194   }
195 
196   IRBuilder<> IRB(In);
197   Intrinsic::ID IntId = (BW == 32) ? Intrinsic::hexagon_S2_extractu
198                                    : Intrinsic::hexagon_S2_extractup;
199   Module *Mod = BB->getParent()->getParent();
200   Value *ExtF = Intrinsic::getDeclaration(Mod, IntId);
201   Value *NewIn = IRB.CreateCall(ExtF, {BF, IRB.getInt32(W), IRB.getInt32(SR)});
202   if (SL != 0)
203     NewIn = IRB.CreateShl(NewIn, SL, CSL->getName());
204   In->replaceAllUsesWith(NewIn);
205   return true;
206 }
207 
208 
209 bool HexagonGenExtract::visitBlock(BasicBlock *B) {
210   // Depth-first, bottom-up traversal.
211   DomTreeNode *DTN = DT->getNode(B);
212   typedef GraphTraits<DomTreeNode*> GTN;
213   typedef GTN::ChildIteratorType Iter;
214   for (Iter I = GTN::child_begin(DTN), E = GTN::child_end(DTN); I != E; ++I)
215     visitBlock((*I)->getBlock());
216 
217   // Allow limiting the number of generated extracts for debugging purposes.
218   bool HasCutoff = ExtractCutoff.getPosition();
219   unsigned Cutoff = ExtractCutoff;
220 
221   bool Changed = false;
222   BasicBlock::iterator I = std::prev(B->end()), NextI, Begin = B->begin();
223   while (true) {
224     if (HasCutoff && (ExtractCount >= Cutoff))
225       return Changed;
226     bool Last = (I == Begin);
227     if (!Last)
228       NextI = std::prev(I);
229     Instruction *In = &*I;
230     bool Done = convert(In);
231     if (HasCutoff && Done)
232       ExtractCount++;
233     Changed |= Done;
234     if (Last)
235       break;
236     I = NextI;
237   }
238   return Changed;
239 }
240 
241 
242 bool HexagonGenExtract::runOnFunction(Function &F) {
243   if (skipFunction(F))
244     return false;
245 
246   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
247   bool Changed;
248 
249   // Traverse the function bottom-up, to see super-expressions before their
250   // sub-expressions.
251   BasicBlock *Entry = GraphTraits<Function*>::getEntryNode(&F);
252   Changed = visitBlock(Entry);
253 
254   return Changed;
255 }
256 
257 
258 FunctionPass *llvm::createHexagonGenExtract() {
259   return new HexagonGenExtract();
260 }
261