[AArch64] fix an invalid-iterator-use bug.
[oota-llvm.git] / lib / Target / AArch64 / AArch64PromoteConstant.cpp
1 //=- AArch64PromoteConstant.cpp --- Promote constant to global for AArch64 -==//
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 // This file implements the AArch64PromoteConstant pass which promotes constants
11 // to global variables when this is likely to be more efficient. Currently only
12 // types related to constant vector (i.e., constant vector, array of constant
13 // vectors, constant structure with a constant vector field, etc.) are promoted
14 // to global variables. Constant vectors are likely to be lowered in target
15 // constant pool during instruction selection already; therefore, the access
16 // will remain the same (memory load), but the structure types are not split
17 // into different constant pool accesses for each field. A bonus side effect is
18 // that created globals may be merged by the global merge pass.
19 //
20 // FIXME: This pass may be useful for other targets too.
21 //===----------------------------------------------------------------------===//
22
23 #include "AArch64.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41
42 using namespace llvm;
43
44 #define DEBUG_TYPE "aarch64-promote-const"
45
46 // Stress testing mode - disable heuristics.
47 static cl::opt<bool> Stress("aarch64-stress-promote-const", cl::Hidden,
48                             cl::desc("Promote all vector constants"));
49
50 STATISTIC(NumPromoted, "Number of promoted constants");
51 STATISTIC(NumPromotedUses, "Number of promoted constants uses");
52
53 //===----------------------------------------------------------------------===//
54 //                       AArch64PromoteConstant
55 //===----------------------------------------------------------------------===//
56
57 namespace {
58 /// Promotes interesting constant into global variables.
59 /// The motivating example is:
60 /// static const uint16_t TableA[32] = {
61 ///   41944, 40330, 38837, 37450, 36158, 34953, 33826, 32768,
62 ///   31776, 30841, 29960, 29128, 28340, 27595, 26887, 26215,
63 ///   25576, 24967, 24386, 23832, 23302, 22796, 22311, 21846,
64 ///   21400, 20972, 20561, 20165, 19785, 19419, 19066, 18725,
65 /// };
66 ///
67 /// uint8x16x4_t LoadStatic(void) {
68 ///   uint8x16x4_t ret;
69 ///   ret.val[0] = vld1q_u16(TableA +  0);
70 ///   ret.val[1] = vld1q_u16(TableA +  8);
71 ///   ret.val[2] = vld1q_u16(TableA + 16);
72 ///   ret.val[3] = vld1q_u16(TableA + 24);
73 ///   return ret;
74 /// }
75 ///
76 /// The constants in this example are folded into the uses. Thus, 4 different
77 /// constants are created.
78 ///
79 /// As their type is vector the cheapest way to create them is to load them
80 /// for the memory.
81 ///
82 /// Therefore the final assembly final has 4 different loads. With this pass
83 /// enabled, only one load is issued for the constants.
84 class AArch64PromoteConstant : public ModulePass {
85
86 public:
87   static char ID;
88   AArch64PromoteConstant() : ModulePass(ID) {}
89
90   const char *getPassName() const override { return "AArch64 Promote Constant"; }
91
92   /// Iterate over the functions and promote the interesting constants into
93   /// global variables with module scope.
94   bool runOnModule(Module &M) override {
95     DEBUG(dbgs() << getPassName() << '\n');
96     bool Changed = false;
97     for (auto &MF : M) {
98       Changed |= runOnFunction(MF);
99     }
100     return Changed;
101   }
102
103 private:
104   /// Look for interesting constants used within the given function.
105   /// Promote them into global variables, load these global variables within
106   /// the related function, so that the number of inserted load is minimal.
107   bool runOnFunction(Function &F);
108
109   // This transformation requires dominator info
110   void getAnalysisUsage(AnalysisUsage &AU) const override {
111     AU.setPreservesCFG();
112     AU.addRequired<DominatorTreeWrapperPass>();
113     AU.addPreserved<DominatorTreeWrapperPass>();
114   }
115
116   /// Type to store a list of Uses.
117   typedef SmallVector<Use *, 4> Uses;
118   /// Map an insertion point to all the uses it dominates.
119   typedef DenseMap<Instruction *, Uses> InsertionPoints;
120   /// Map a function to the required insertion point of load for a
121   /// global variable.
122   typedef DenseMap<Function *, InsertionPoints> InsertionPointsPerFunc;
123
124   /// Find the closest point that dominates the given Use.
125   Instruction *findInsertionPoint(Use &Use);
126
127   /// Check if the given insertion point is dominated by an existing
128   /// insertion point.
129   /// If true, the given use is added to the list of dominated uses for
130   /// the related existing point.
131   /// \param NewPt the insertion point to be checked
132   /// \param Use the use to be added into the list of dominated uses
133   /// \param InsertPts existing insertion points
134   /// \pre NewPt and all instruction in InsertPts belong to the same function
135   /// \return true if one of the insertion point in InsertPts dominates NewPt,
136   ///         false otherwise
137   bool isDominated(Instruction *NewPt, Use &Use, InsertionPoints &InsertPts);
138
139   /// Check if the given insertion point can be merged with an existing
140   /// insertion point in a common dominator.
141   /// If true, the given use is added to the list of the created insertion
142   /// point.
143   /// \param NewPt the insertion point to be checked
144   /// \param Use the use to be added into the list of dominated uses
145   /// \param InsertPts existing insertion points
146   /// \pre NewPt and all instruction in InsertPts belong to the same function
147   /// \pre isDominated returns false for the exact same parameters.
148   /// \return true if it exists an insertion point in InsertPts that could
149   ///         have been merged with NewPt in a common dominator,
150   ///         false otherwise
151   bool tryAndMerge(Instruction *NewPt, Use &Use, InsertionPoints &InsertPts);
152
153   /// Compute the minimal insertion points to dominates all the interesting
154   /// uses of value.
155   /// Insertion points are group per function and each insertion point
156   /// contains a list of all the uses it dominates within the related function
157   /// \param Val constant to be examined
158   /// \param[out] InsPtsPerFunc output storage of the analysis
159   void computeInsertionPoints(Constant *Val,
160                               InsertionPointsPerFunc &InsPtsPerFunc);
161
162   /// Insert a definition of a new global variable at each point contained in
163   /// InsPtsPerFunc and update the related uses (also contained in
164   /// InsPtsPerFunc).
165   bool insertDefinitions(Constant *Cst, InsertionPointsPerFunc &InsPtsPerFunc);
166
167   /// Compute the minimal insertion points to dominate all the interesting
168   /// uses of Val and insert a definition of a new global variable
169   /// at these points.
170   /// Also update the uses of Val accordingly.
171   /// Currently a use of Val is considered interesting if:
172   /// - Val is not UndefValue
173   /// - Val is not zeroinitialized
174   /// - Replacing Val per a load of a global variable is valid.
175   /// \see shouldConvert for more details
176   bool computeAndInsertDefinitions(Constant *Val);
177
178   /// Promote the given constant into a global variable if it is expected to
179   /// be profitable.
180   /// \return true if Cst has been promoted
181   bool promoteConstant(Constant *Cst);
182
183   /// Transfer the list of dominated uses of IPI to NewPt in InsertPts.
184   /// Append Use to this list and delete the entry of IPI in InsertPts.
185   static void appendAndTransferDominatedUses(Instruction *NewPt, Use &Use,
186                                              InsertionPoints::iterator &IPI,
187                                              InsertionPoints &InsertPts) {
188     // Record the dominated use.
189     IPI->second.push_back(&Use);
190     // Transfer the dominated uses of IPI to NewPt
191     // Inserting into the DenseMap may invalidate existing iterator.
192     // Keep a copy of the key to find the iterator to erase.  Keep a copy of the
193     // value so that we don't have to dereference IPI->second.
194     Instruction *OldInstr = IPI->first;
195     Uses OldUses = std::move(IPI->second);
196     InsertPts[NewPt] = std::move(OldUses);
197     // Erase IPI.
198     InsertPts.erase(OldInstr);
199   }
200 };
201 } // end anonymous namespace
202
203 char AArch64PromoteConstant::ID = 0;
204
205 namespace llvm {
206 void initializeAArch64PromoteConstantPass(PassRegistry &);
207 }
208
209 INITIALIZE_PASS_BEGIN(AArch64PromoteConstant, "aarch64-promote-const",
210                       "AArch64 Promote Constant Pass", false, false)
211 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
212 INITIALIZE_PASS_END(AArch64PromoteConstant, "aarch64-promote-const",
213                     "AArch64 Promote Constant Pass", false, false)
214
215 ModulePass *llvm::createAArch64PromoteConstantPass() {
216   return new AArch64PromoteConstant();
217 }
218
219 /// Check if the given type uses a vector type.
220 static bool isConstantUsingVectorTy(const Type *CstTy) {
221   if (CstTy->isVectorTy())
222     return true;
223   if (CstTy->isStructTy()) {
224     for (unsigned EltIdx = 0, EndEltIdx = CstTy->getStructNumElements();
225          EltIdx < EndEltIdx; ++EltIdx)
226       if (isConstantUsingVectorTy(CstTy->getStructElementType(EltIdx)))
227         return true;
228   } else if (CstTy->isArrayTy())
229     return isConstantUsingVectorTy(CstTy->getArrayElementType());
230   return false;
231 }
232
233 /// Check if the given use (Instruction + OpIdx) of Cst should be converted into
234 /// a load of a global variable initialized with Cst.
235 /// A use should be converted if it is legal to do so.
236 /// For instance, it is not legal to turn the mask operand of a shuffle vector
237 /// into a load of a global variable.
238 static bool shouldConvertUse(const Constant *Cst, const Instruction *Instr,
239                              unsigned OpIdx) {
240   // shufflevector instruction expects a const for the mask argument, i.e., the
241   // third argument. Do not promote this use in that case.
242   if (isa<const ShuffleVectorInst>(Instr) && OpIdx == 2)
243     return false;
244
245   // extractvalue instruction expects a const idx.
246   if (isa<const ExtractValueInst>(Instr) && OpIdx > 0)
247     return false;
248
249   // extractvalue instruction expects a const idx.
250   if (isa<const InsertValueInst>(Instr) && OpIdx > 1)
251     return false;
252
253   if (isa<const AllocaInst>(Instr) && OpIdx > 0)
254     return false;
255
256   // Alignment argument must be constant.
257   if (isa<const LoadInst>(Instr) && OpIdx > 0)
258     return false;
259
260   // Alignment argument must be constant.
261   if (isa<const StoreInst>(Instr) && OpIdx > 1)
262     return false;
263
264   // Index must be constant.
265   if (isa<const GetElementPtrInst>(Instr) && OpIdx > 0)
266     return false;
267
268   // Personality function and filters must be constant.
269   // Give up on that instruction.
270   if (isa<const LandingPadInst>(Instr))
271     return false;
272
273   // Switch instruction expects constants to compare to.
274   if (isa<const SwitchInst>(Instr))
275     return false;
276
277   // Expected address must be a constant.
278   if (isa<const IndirectBrInst>(Instr))
279     return false;
280
281   // Do not mess with intrinsics.
282   if (isa<const IntrinsicInst>(Instr))
283     return false;
284
285   // Do not mess with inline asm.
286   const CallInst *CI = dyn_cast<const CallInst>(Instr);
287   if (CI && isa<const InlineAsm>(CI->getCalledValue()))
288     return false;
289
290   return true;
291 }
292
293 /// Check if the given Cst should be converted into
294 /// a load of a global variable initialized with Cst.
295 /// A constant should be converted if it is likely that the materialization of
296 /// the constant will be tricky. Thus, we give up on zero or undef values.
297 ///
298 /// \todo Currently, accept only vector related types.
299 /// Also we give up on all simple vector type to keep the existing
300 /// behavior. Otherwise, we should push here all the check of the lowering of
301 /// BUILD_VECTOR. By giving up, we lose the potential benefit of merging
302 /// constant via global merge and the fact that the same constant is stored
303 /// only once with this method (versus, as many function that uses the constant
304 /// for the regular approach, even for float).
305 /// Again, the simplest solution would be to promote every
306 /// constant and rematerialize them when they are actually cheap to create.
307 static bool shouldConvert(const Constant *Cst) {
308   if (isa<const UndefValue>(Cst))
309     return false;
310
311   // FIXME: In some cases, it may be interesting to promote in memory
312   // a zero initialized constant.
313   // E.g., when the type of Cst require more instructions than the
314   // adrp/add/load sequence or when this sequence can be shared by several
315   // instances of Cst.
316   // Ideally, we could promote this into a global and rematerialize the constant
317   // when it was a bad idea.
318   if (Cst->isZeroValue())
319     return false;
320
321   if (Stress)
322     return true;
323
324   // FIXME: see function \todo
325   if (Cst->getType()->isVectorTy())
326     return false;
327   return isConstantUsingVectorTy(Cst->getType());
328 }
329
330 Instruction *AArch64PromoteConstant::findInsertionPoint(Use &Use) {
331   Instruction *User = cast<Instruction>(Use.getUser());
332
333   // If this user is a phi, the insertion point is in the related
334   // incoming basic block.
335   if (PHINode *PhiInst = dyn_cast<PHINode>(User))
336     return PhiInst->getIncomingBlock(Use.getOperandNo())->getTerminator();
337
338   return User;
339 }
340
341 bool AArch64PromoteConstant::isDominated(Instruction *NewPt, Use &Use,
342                                          InsertionPoints &InsertPts) {
343
344   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
345       *NewPt->getParent()->getParent()).getDomTree();
346
347   // Traverse all the existing insertion points and check if one is dominating
348   // NewPt. If it is, remember that.
349   for (auto &IPI : InsertPts) {
350     if (NewPt == IPI.first || DT.dominates(IPI.first, NewPt) ||
351         // When IPI.first is a terminator instruction, DT may think that
352         // the result is defined on the edge.
353         // Here we are testing the insertion point, not the definition.
354         (IPI.first->getParent() != NewPt->getParent() &&
355          DT.dominates(IPI.first->getParent(), NewPt->getParent()))) {
356       // No need to insert this point. Just record the dominated use.
357       DEBUG(dbgs() << "Insertion point dominated by:\n");
358       DEBUG(IPI.first->print(dbgs()));
359       DEBUG(dbgs() << '\n');
360       IPI.second.push_back(&Use);
361       return true;
362     }
363   }
364   return false;
365 }
366
367 bool AArch64PromoteConstant::tryAndMerge(Instruction *NewPt, Use &Use,
368                                          InsertionPoints &InsertPts) {
369   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
370       *NewPt->getParent()->getParent()).getDomTree();
371   BasicBlock *NewBB = NewPt->getParent();
372
373   // Traverse all the existing insertion point and check if one is dominated by
374   // NewPt and thus useless or can be combined with NewPt into a common
375   // dominator.
376   for (InsertionPoints::iterator IPI = InsertPts.begin(),
377                                  EndIPI = InsertPts.end();
378        IPI != EndIPI; ++IPI) {
379     BasicBlock *CurBB = IPI->first->getParent();
380     if (NewBB == CurBB) {
381       // Instructions are in the same block.
382       // By construction, NewPt is dominating the other.
383       // Indeed, isDominated returned false with the exact same arguments.
384       DEBUG(dbgs() << "Merge insertion point with:\n");
385       DEBUG(IPI->first->print(dbgs()));
386       DEBUG(dbgs() << "\nat considered insertion point.\n");
387       appendAndTransferDominatedUses(NewPt, Use, IPI, InsertPts);
388       return true;
389     }
390
391     // Look for a common dominator
392     BasicBlock *CommonDominator = DT.findNearestCommonDominator(NewBB, CurBB);
393     // If none exists, we cannot merge these two points.
394     if (!CommonDominator)
395       continue;
396
397     if (CommonDominator != NewBB) {
398       // By construction, the CommonDominator cannot be CurBB.
399       assert(CommonDominator != CurBB &&
400              "Instruction has not been rejected during isDominated check!");
401       // Take the last instruction of the CommonDominator as insertion point
402       NewPt = CommonDominator->getTerminator();
403     }
404     // else, CommonDominator is the block of NewBB, hence NewBB is the last
405     // possible insertion point in that block.
406     DEBUG(dbgs() << "Merge insertion point with:\n");
407     DEBUG(IPI->first->print(dbgs()));
408     DEBUG(dbgs() << '\n');
409     DEBUG(NewPt->print(dbgs()));
410     DEBUG(dbgs() << '\n');
411     appendAndTransferDominatedUses(NewPt, Use, IPI, InsertPts);
412     return true;
413   }
414   return false;
415 }
416
417 void AArch64PromoteConstant::computeInsertionPoints(
418     Constant *Val, InsertionPointsPerFunc &InsPtsPerFunc) {
419   DEBUG(dbgs() << "** Compute insertion points **\n");
420   for (Use &Use : Val->uses()) {
421     Instruction *User = dyn_cast<Instruction>(Use.getUser());
422
423     // If the user is not an Instruction, we cannot modify it.
424     if (!User)
425       continue;
426
427     // Filter out uses that should not be converted.
428     if (!shouldConvertUse(Val, User, Use.getOperandNo()))
429       continue;
430
431     DEBUG(dbgs() << "Considered use, opidx " << Use.getOperandNo() << ":\n");
432     DEBUG(User->print(dbgs()));
433     DEBUG(dbgs() << '\n');
434
435     Instruction *InsertionPoint = findInsertionPoint(Use);
436
437     DEBUG(dbgs() << "Considered insertion point:\n");
438     DEBUG(InsertionPoint->print(dbgs()));
439     DEBUG(dbgs() << '\n');
440
441     // Check if the current insertion point is useless, i.e., it is dominated
442     // by another one.
443     InsertionPoints &InsertPts =
444         InsPtsPerFunc[InsertionPoint->getParent()->getParent()];
445     if (isDominated(InsertionPoint, Use, InsertPts))
446       continue;
447     // This insertion point is useful, check if we can merge some insertion
448     // point in a common dominator or if NewPt dominates an existing one.
449     if (tryAndMerge(InsertionPoint, Use, InsertPts))
450       continue;
451
452     DEBUG(dbgs() << "Keep considered insertion point\n");
453
454     // It is definitely useful by its own
455     InsertPts[InsertionPoint].push_back(&Use);
456   }
457 }
458
459 bool AArch64PromoteConstant::insertDefinitions(
460     Constant *Cst, InsertionPointsPerFunc &InsPtsPerFunc) {
461   // We will create one global variable per Module.
462   DenseMap<Module *, GlobalVariable *> ModuleToMergedGV;
463   bool HasChanged = false;
464
465   // Traverse all insertion points in all the function.
466   for (const auto &FctToInstPtsIt : InsPtsPerFunc) {
467     const InsertionPoints &InsertPts = FctToInstPtsIt.second;
468 // Do more checking for debug purposes.
469 #ifndef NDEBUG
470     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
471                             *FctToInstPtsIt.first).getDomTree();
472 #endif
473     assert(!InsertPts.empty() && "Empty uses does not need a definition");
474
475     Module *M = FctToInstPtsIt.first->getParent();
476     GlobalVariable *&PromotedGV = ModuleToMergedGV[M];
477     if (!PromotedGV) {
478       PromotedGV = new GlobalVariable(
479           *M, Cst->getType(), true, GlobalValue::InternalLinkage, nullptr,
480           "_PromotedConst", nullptr, GlobalVariable::NotThreadLocal);
481       PromotedGV->setInitializer(Cst);
482       DEBUG(dbgs() << "Global replacement: ");
483       DEBUG(PromotedGV->print(dbgs()));
484       DEBUG(dbgs() << '\n');
485       ++NumPromoted;
486       HasChanged = true;
487     }
488
489     for (const auto &IPI : InsertPts) {
490       // Create the load of the global variable.
491       IRBuilder<> Builder(IPI.first->getParent(), IPI.first);
492       LoadInst *LoadedCst = Builder.CreateLoad(PromotedGV);
493       DEBUG(dbgs() << "**********\n");
494       DEBUG(dbgs() << "New def: ");
495       DEBUG(LoadedCst->print(dbgs()));
496       DEBUG(dbgs() << '\n');
497
498       // Update the dominated uses.
499       for (Use *Use : IPI.second) {
500 #ifndef NDEBUG
501         assert(DT.dominates(LoadedCst, findInsertionPoint(*Use)) &&
502                "Inserted definition does not dominate all its uses!");
503 #endif
504         DEBUG(dbgs() << "Use to update " << Use->getOperandNo() << ":");
505         DEBUG(Use->getUser()->print(dbgs()));
506         DEBUG(dbgs() << '\n');
507         Use->set(LoadedCst);
508         ++NumPromotedUses;
509       }
510     }
511   }
512   return HasChanged;
513 }
514
515 bool AArch64PromoteConstant::computeAndInsertDefinitions(Constant *Val) {
516   InsertionPointsPerFunc InsertPtsPerFunc;
517   computeInsertionPoints(Val, InsertPtsPerFunc);
518   return insertDefinitions(Val, InsertPtsPerFunc);
519 }
520
521 bool AArch64PromoteConstant::promoteConstant(Constant *Cst) {
522   assert(Cst && "Given variable is not a valid constant.");
523
524   if (!shouldConvert(Cst))
525     return false;
526
527   DEBUG(dbgs() << "******************************\n");
528   DEBUG(dbgs() << "Candidate constant: ");
529   DEBUG(Cst->print(dbgs()));
530   DEBUG(dbgs() << '\n');
531
532   return computeAndInsertDefinitions(Cst);
533 }
534
535 bool AArch64PromoteConstant::runOnFunction(Function &F) {
536   // Look for instructions using constant vector. Promote that constant to a
537   // global variable. Create as few loads of this variable as possible and
538   // update the uses accordingly.
539   bool LocalChange = false;
540   SmallPtrSet<Constant *, 8> AlreadyChecked;
541
542   for (Instruction &I : inst_range(&F)) {
543     // Traverse the operand, looking for constant vectors. Replace them by a
544     // load of a global variable of constant vector type.
545     for (Value *Op : I.operand_values()) {
546       Constant *Cst = dyn_cast<Constant>(Op);
547       // There is no point in promoting global values as they are already
548       // global. Do not promote constant expressions either, as they may
549       // require some code expansion.
550       if (Cst && !isa<GlobalValue>(Cst) && !isa<ConstantExpr>(Cst) &&
551           AlreadyChecked.insert(Cst).second)
552         LocalChange |= promoteConstant(Cst);
553     }
554   }
555   return LocalChange;
556 }