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