blob: 153fedf2c370513079dc11127b39ecab0fb5bb80 [file] [log] [blame]
Chris Lattnere6bb6492010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
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 pass implements an idiom recognizer that transforms simple loops into a
11// non-loop form. In cases that this kicks in, it can be a significant
12// performance win.
13//
14//===----------------------------------------------------------------------===//
Chris Lattnerbdce5722011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
Chandler Carrutha8647482012-11-02 08:33:25 +000019// memcmp, memmove, strlen, etc.
Chris Lattnerbdce5722011-01-02 18:32:09 +000020// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
25// Beware that isel's default lowering for ctpop is highly inefficient for
26// i64 and larger types when i64 is legal and the value has few bits set. It
27// would be good to enhance isel to emit a loop for ctpop in this case.
28//
29// We should enhance the memset/memcpy recognition to handle multiple stores in
30// the loop. This would handle things like:
31// void foo(_Complex float *P)
32// for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
Chris Lattner91139cc2011-01-02 23:19:45 +000033//
Chris Lattner408b5342011-02-21 02:08:54 +000034// We should enhance this to handle negative strides through memory.
35// Alternatively (and perhaps better) we could rely on an earlier pass to force
36// forward iteration through memory, which is generally better for cache
37// behavior. Negative strides *do* happen for memset/memcpy loops.
38//
Chris Lattnerd957c712011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner91139cc2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattnerbdce5722011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000043
44#define DEBUG_TYPE "loop-idiom"
45#include "llvm/Transforms/Scalar.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000046#include "llvm/ADT/Statistic.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000047#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000049#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000050#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner22920b52010-12-26 20:45:45 +000051#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000052#include "llvm/DataLayout.h"
53#include "llvm/IRBuilder.h"
54#include "llvm/IntrinsicInst.h"
55#include "llvm/Module.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000056#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
Chris Lattnerc19175c2011-02-18 22:22:15 +000058#include "llvm/Target/TargetLibraryInfo.h"
Shuxin Yang84fca612012-11-29 19:38:54 +000059#include "llvm/TargetTransformInfo.h"
Chris Lattner9f391882010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000061using namespace llvm;
62
Chandler Carrutha8647482012-11-02 08:33:25 +000063STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000065
66namespace {
Shuxin Yang84fca612012-11-29 19:38:54 +000067
68 class LoopIdiomRecognize;
69
70 /// This class defines some utility functions for loop idiom recognization.
71 class LIRUtil {
72 public:
73 /// Return true iff the block contains nothing but an uncondition branch
74 /// (aka goto instruction).
75 static bool isAlmostEmpty(BasicBlock *);
76
77 static BranchInst *getBranch(BasicBlock *BB) {
78 return dyn_cast<BranchInst>(BB->getTerminator());
79 }
80
81 /// Return the condition of the branch terminating the given basic block.
82 static Value *getBrCondtion(BasicBlock *);
83
84 /// Derive the precondition block (i.e the block that guards the loop
85 /// preheader) from the given preheader.
86 static BasicBlock *getPrecondBb(BasicBlock *PreHead);
87 };
88
89 /// This class is to recoginize idioms of population-count conducted in
90 /// a noncountable loop. Currently it only recognizes this pattern:
91 /// \code
92 /// while(x) {cnt++; ...; x &= x - 1; ...}
93 /// \endcode
94 class NclPopcountRecognize {
95 LoopIdiomRecognize &LIR;
96 Loop *CurLoop;
97 BasicBlock *PreCondBB;
98
99 typedef IRBuilder<> IRBuilderTy;
100
101 public:
102 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
103 bool recognize();
104
105 private:
106 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
107 /// the idiom.
108 bool preliminaryScreen();
109
110 /// Check if the given conditional branch is based on the comparison
111 /// beween a variable and zero, and if the variable is non-zero, the
112 /// control yeilds to the loop entry. If the branch matches the behavior,
113 /// the variable involved in the comparion is returned. This function will
114 /// be called to see if the precondition and postcondition of the loop
115 /// are in desirable form.
116 Value *matchCondition (BranchInst *Br, BasicBlock *NonZeroTarget) const;
117
118 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
119 /// is set to the instruction counting the pupulation bit. 2) \p CntPhi
120 /// is set to the corresponding phi node. 3) \p Var is set to the value
121 /// whose population bits are being counted.
122 bool detectIdiom
123 (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
124
125 /// Insert ctpop intrinsic function and some obviously dead instructions.
126 void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var);
127
128 /// Create llvm.ctpop.* intrinsic function.
129 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
130 };
131
Chris Lattnere6bb6492010-12-26 19:39:38 +0000132 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +0000133 Loop *CurLoop;
Micah Villmow3574eca2012-10-08 16:38:25 +0000134 const DataLayout *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +0000135 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +0000136 ScalarEvolution *SE;
Chris Lattnerc19175c2011-02-18 22:22:15 +0000137 TargetLibraryInfo *TLI;
Shuxin Yang84fca612012-11-29 19:38:54 +0000138 const ScalarTargetTransformInfo *STTI;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000139 public:
140 static char ID;
141 explicit LoopIdiomRecognize() : LoopPass(ID) {
142 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Shuxin Yang84fca612012-11-29 19:38:54 +0000143 TD = 0; DT = 0; SE = 0; TLI = 0; STTI = 0;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000144 }
145
146 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +0000147 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
148 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +0000149
Chris Lattner22920b52010-12-26 20:45:45 +0000150 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000151 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000152
Chris Lattner3a393722011-02-19 19:31:39 +0000153 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
154 unsigned StoreAlignment,
155 Value *SplatValue, Instruction *TheStore,
156 const SCEVAddRecExpr *Ev,
157 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +0000158 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
159 const SCEVAddRecExpr *StoreEv,
160 const SCEVAddRecExpr *LoadEv,
161 const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000162
Chris Lattnere6bb6492010-12-26 19:39:38 +0000163 /// This transformation requires natural loop information & requires that
164 /// loop preheaders be inserted into the CFG.
165 ///
166 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.addRequired<LoopInfo>();
168 AU.addPreserved<LoopInfo>();
169 AU.addRequiredID(LoopSimplifyID);
170 AU.addPreservedID(LoopSimplifyID);
171 AU.addRequiredID(LCSSAID);
172 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000173 AU.addRequired<AliasAnalysis>();
174 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000175 AU.addRequired<ScalarEvolution>();
176 AU.addPreserved<ScalarEvolution>();
177 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000178 AU.addRequired<DominatorTree>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000179 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000180 }
Shuxin Yang84fca612012-11-29 19:38:54 +0000181
182 const DataLayout *getDataLayout() {
183 return TD ? TD : TD=getAnalysisIfAvailable<DataLayout>();
184 }
185
186 DominatorTree *getDominatorTree() {
187 return DT ? DT : (DT=&getAnalysis<DominatorTree>());
188 }
189
190 ScalarEvolution *getScalarEvolution() {
191 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
192 }
193
194 TargetLibraryInfo *getTargetLibraryInfo() {
195 return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
196 }
197
198 const ScalarTargetTransformInfo *getScalarTargetTransformInfo() {
199 if (!STTI) {
200 TargetTransformInfo *TTI = getAnalysisIfAvailable<TargetTransformInfo>();
201 if (TTI) STTI = TTI->getScalarTargetTransformInfo();
202 }
203 return STTI;
204 }
205
206 Loop *getLoop() const { return CurLoop; }
207
208 private:
209 bool runOnNoncountableLoop();
210 bool runOnCountableLoop();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000211 };
212}
213
214char LoopIdiomRecognize::ID = 0;
215INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
216 false, false)
217INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000218INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000219INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
220INITIALIZE_PASS_DEPENDENCY(LCSSA)
221INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnerc19175c2011-02-18 22:22:15 +0000222INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000223INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000224INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
225 false, false)
226
227Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
228
Chris Lattner4f81b542011-05-22 17:39:56 +0000229/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattner9f391882010-12-27 00:03:23 +0000230/// and zero out all the operands of this instruction. If any of them become
231/// dead, delete them and the computation tree that feeds them.
232///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000233static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
234 const TargetLibraryInfo *TLI) {
Chris Lattner9f391882010-12-27 00:03:23 +0000235 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000236
Chris Lattner9f391882010-12-27 00:03:23 +0000237 NowDeadInsts.push_back(I);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000238
Chris Lattner9f391882010-12-27 00:03:23 +0000239 // Before we touch this instruction, remove it from SE!
240 do {
241 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000242
Chris Lattner9f391882010-12-27 00:03:23 +0000243 // This instruction is dead, zap it, in stages. Start by removing it from
244 // SCEV.
245 SE.forgetValue(DeadInst);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000246
Chris Lattner9f391882010-12-27 00:03:23 +0000247 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
248 Value *Op = DeadInst->getOperand(op);
249 DeadInst->setOperand(op, 0);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000250
Chris Lattner9f391882010-12-27 00:03:23 +0000251 // If this operand just became dead, add it to the NowDeadInsts list.
252 if (!Op->use_empty()) continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000253
Chris Lattner9f391882010-12-27 00:03:23 +0000254 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000255 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattner9f391882010-12-27 00:03:23 +0000256 NowDeadInsts.push_back(OpI);
257 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000258
Chris Lattner9f391882010-12-27 00:03:23 +0000259 DeadInst->eraseFromParent();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000260
Chris Lattner9f391882010-12-27 00:03:23 +0000261 } while (!NowDeadInsts.empty());
262}
263
Chandler Carrutha8647482012-11-02 08:33:25 +0000264/// deleteIfDeadInstruction - If the specified value is a dead instruction,
265/// delete it and any recursively used instructions.
266static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
267 const TargetLibraryInfo *TLI) {
268 if (Instruction *I = dyn_cast<Instruction>(V))
269 if (isInstructionTriviallyDead(I, TLI))
270 deleteDeadInstruction(I, SE, TLI);
271}
272
Shuxin Yang84fca612012-11-29 19:38:54 +0000273//===----------------------------------------------------------------------===//
274//
275// Implementation of LIRUtil
276//
277//===----------------------------------------------------------------------===//
278
279// This fucntion will return true iff the given block contains nothing but goto.
280// A typical usage of this function is to check if the preheader fucntion is
281// "almost" empty such that generated intrinsic function can be moved across
282// preheader and to be placed at the end of the preconditiona block without
283// concerning of breaking data dependence.
284bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
285 if (BranchInst *Br = getBranch(BB)) {
286 return Br->isUnconditional() && BB->size() == 1;
287 }
288 return false;
289}
290
291Value *LIRUtil::getBrCondtion(BasicBlock *BB) {
292 BranchInst *Br = getBranch(BB);
293 return Br ? Br->getCondition() : 0;
294}
295
296BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
297 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
298 BranchInst *Br = getBranch(BB);
299 return Br && Br->isConditional() ? BB : 0;
300 }
301 return 0;
302}
303
304//===----------------------------------------------------------------------===//
305//
306// Implementation of NclPopcountRecognize
307//
308//===----------------------------------------------------------------------===//
309
310NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
311 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(0) {
312}
313
314bool NclPopcountRecognize::preliminaryScreen() {
315 const ScalarTargetTransformInfo *STTI = LIR.getScalarTargetTransformInfo();
316 if (STTI->getPopcntHwSupport(32) != ScalarTargetTransformInfo::Fast)
317 return false;
318
319 // Counting population are usually conducted by few arithmetic instrutions.
320 // Such instructions can be easilly "absorbed" by vacant slots in a
321 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
322 // in a compact loop.
323
324 // Give up if the loop has multiple blocks or multiple backedges.
325 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
326 return false;
327
328 BasicBlock *LoopBody = *(CurLoop->block_begin());
329 if (LoopBody->size() >= 20) {
330 // The loop is too big, bail out.
331 return false;
332 }
333
334 // It should have a preheader containing nothing but a goto instruction.
335 BasicBlock *PreHead = CurLoop->getLoopPreheader();
336 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
337 return false;
338
339 // It should have a precondition block where the generated popcount instrinsic
340 // function will be inserted.
341 PreCondBB = LIRUtil::getPrecondBb(PreHead);
342 if (!PreCondBB)
343 return false;
344
345 return true;
346}
347
348Value *NclPopcountRecognize::matchCondition (BranchInst *Br,
349 BasicBlock *LoopEntry) const {
350 if (!Br || !Br->isConditional())
351 return 0;
352
353 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
354 if (!Cond)
355 return 0;
356
357 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
358 if (!CmpZero || !CmpZero->isZero())
359 return 0;
360
361 ICmpInst::Predicate Pred = Cond->getPredicate();
362 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
363 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
364 return Cond->getOperand(0);
365
366 return 0;
367}
368
369bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
370 PHINode *&CntPhi,
371 Value *&Var) const {
372 // Following code tries to detect this idiom:
373 //
374 // if (x0 != 0)
375 // goto loop-exit // the precondition of the loop
376 // cnt0 = init-val;
377 // do {
378 // x1 = phi (x0, x2);
379 // cnt1 = phi(cnt0, cnt2);
380 //
381 // cnt2 = cnt1 + 1;
382 // ...
383 // x2 = x1 & (x1 - 1);
384 // ...
385 // } while(x != 0);
386 //
387 // loop-exit:
388 //
389
390 // step 1: Check to see if the look-back branch match this pattern:
391 // "if (a!=0) goto loop-entry".
392 BasicBlock *LoopEntry;
393 Instruction *DefX2, *CountInst;
394 Value *VarX1, *VarX0;
395 PHINode *PhiX, *CountPhi;
396
397 DefX2 = CountInst = 0;
398 VarX1 = VarX0 = 0;
399 PhiX = CountPhi = 0;
400 LoopEntry = *(CurLoop->block_begin());
401
402 // step 1: Check if the loop-back branch is in desirable form.
403 {
404 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
405 DefX2 = dyn_cast<Instruction>(T);
406 else
407 return false;
408 }
409
410 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
411 {
412 if (DefX2->getOpcode() != Instruction::And)
413 return false;
414
415 BinaryOperator *SubOneOp;
416
417 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
418 VarX1 = DefX2->getOperand(1);
419 else {
420 VarX1 = DefX2->getOperand(0);
421 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
422 }
423 if (!SubOneOp)
424 return false;
425
426 Instruction *SubInst = cast<Instruction>(SubOneOp);
427 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
428 if (!Dec ||
429 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
430 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
431 return false;
432 }
433 }
434
435 // step 3: Check the recurrence of variable X
436 {
437 PhiX = dyn_cast<PHINode>(VarX1);
438 if (!PhiX ||
439 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
440 return false;
441 }
442 }
443
444 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
445 {
446 CountInst = NULL;
447 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
448 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
449 Instruction *Inst = Iter;
450 if (Inst->getOpcode() != Instruction::Add)
451 continue;
452
453 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
454 if (!Inc || !Inc->isOne())
455 continue;
456
457 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
458 if (!Phi && Phi->getParent() != LoopEntry)
459 continue;
460
461 // Check if the result of the instruction is live of the loop.
462 bool LiveOutLoop = false;
463 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
464 I != E; I++) {
465 if ((cast<Instruction>(*I))->getParent() != LoopEntry) {
466 LiveOutLoop = true; break;
467 }
468 }
469
470 if (LiveOutLoop) {
471 CountInst = Inst;
472 CountPhi = Phi;
473 break;
474 }
475 }
476
477 if (!CountInst)
478 return false;
479 }
480
481 // step 5: check if the precondition is in this form:
482 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
483 {
484 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
485 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
486 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
487 return false;
488
489 CntInst = CountInst;
490 CntPhi = CountPhi;
491 Var = T;
492 }
493
494 return true;
495}
496
497void NclPopcountRecognize::transform(Instruction *CntInst,
498 PHINode *CntPhi, Value *Var) {
499
500 ScalarEvolution *SE = LIR.getScalarEvolution();
501 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
502 BasicBlock *PreHead = CurLoop->getLoopPreheader();
503 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
504 const DebugLoc DL = CntInst->getDebugLoc();
505
506 // Assuming before transformation, the loop is following:
507 // if (x) // the precondition
508 // do { cnt++; x &= x - 1; } while(x);
509
510 // Step 1: Insert the ctpop instruction at the end of the precondition block
511 IRBuilderTy Builder(PreCondBr);
512 Value *PopCnt, *PopCntZext, *NewCount;
513 {
514 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
515 NewCount = PopCntZext =
516 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
517
518 if (NewCount != PopCnt)
519 (cast<Instruction>(NewCount))->setDebugLoc(DL);
520
521 // If the popoulation counter's initial value is not zero, insert Add Inst.
522 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
523 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
524 if (!InitConst || !InitConst->isZero()) {
525 NewCount = Builder.CreateAdd(PopCnt, InitConst);
526 (cast<Instruction>(NewCount))->setDebugLoc(DL);
527 }
528 }
529
530 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
531 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
532 // function would be partial dead code, and downstream passes will drag
533 // it back from the precondition block to the preheader.
534 {
535 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
536
537 Value *Opnd0 = PopCntZext;
538 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
539 if (PreCond->getOperand(0) != Var)
540 std::swap(Opnd0, Opnd1);
541
542 ICmpInst *NewPreCond =
543 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
544 PreCond->replaceAllUsesWith(NewPreCond);
545
546 deleteDeadInstruction(PreCond, *SE, TLI);
547 }
548
549 // Step 3: Note that the population count is exactly the trip count of the
550 // loop in question, which enble us to to convert the loop from noncountable
551 // loop into a countable one. The benefit is twofold:
552 //
553 // - If the loop only counts population, the entire loop become dead after
554 // the transformation. It is lots easier to prove a countable loop dead
555 // than to prove a noncountable one. (In some C dialects, a infite loop
556 // isn't dead even if it computes nothing useful. In general, DCE needs
557 // to prove a noncountable loop finite before safely delete it.)
558 //
559 // - If the loop also performs something else, it remains alive.
560 // Since it is transformed to countable form, it can be aggressively
561 // optimized by some optimizations which are in general not applicable
562 // to a noncountable loop.
563 //
564 // After this step, this loop (conceptually) would look like following:
565 // newcnt = __builtin_ctpop(x);
566 // t = newcnt;
567 // if (x)
568 // do { cnt++; x &= x-1; t--) } while (t > 0);
569 BasicBlock *Body = *(CurLoop->block_begin());
570 {
571 BranchInst *LbBr = LIRUtil::getBranch(Body);
572 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
573 Type *Ty = NewCount->getType();
574
575 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
576
577 Builder.SetInsertPoint(LbCond);
578 Value *Opnd1 = cast<Value>(TcPhi);
579 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
580 Instruction *TcDec =
581 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
582
583 TcPhi->addIncoming(NewCount, PreHead);
584 TcPhi->addIncoming(TcDec, Body);
585
586 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
587 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
588 LbCond->setPredicate(Pred);
589 LbCond->setOperand(0, TcDec);
590 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
591 }
592
593 // Step 4: All the references to the original population counter outside
594 // the loop are replaced with the NewCount -- the value returned from
595 // __builtin_ctpop().
596 {
597 SmallVector<Value *, 4> CntUses;
598 for (Value::use_iterator I = CntInst->use_begin(), E = CntInst->use_end();
599 I != E; I++) {
600 if (cast<Instruction>(*I)->getParent() != Body)
601 CntUses.push_back(*I);
602 }
603 for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
604 (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
605 }
606 }
607
608 // step 5: Forget the "non-computable" trip-count SCEV associated with the
609 // loop. The loop would otherwise not be deleted even if it becomes empty.
610 SE->forgetLoop(CurLoop);
611}
612
613CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
614 Value *Val, DebugLoc DL) {
615 Value *Ops[] = { Val };
616 Type *Tys[] = { Val->getType() };
617
618 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
619 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
620 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
621 CI->setDebugLoc(DL);
622
623 return CI;
624}
625
626/// recognize - detect population count idiom in a non-countable loop. If
627/// detected, transform the relevant code to popcount intrinsic function
628/// call, and return true; otherwise, return false.
629bool NclPopcountRecognize::recognize() {
630
631 if (!LIR.getScalarTargetTransformInfo())
632 return false;
633
634 LIR.getScalarEvolution();
635
636 if (!preliminaryScreen())
637 return false;
638
639 Instruction *CntInst;
640 PHINode *CntPhi;
641 Value *Val;
642 if (!detectIdiom(CntInst, CntPhi, Val))
643 return false;
644
645 transform(CntInst, CntPhi, Val);
646 return true;
647}
648
649//===----------------------------------------------------------------------===//
650//
651// Implementation of LoopIdiomRecognize
652//
653//===----------------------------------------------------------------------===//
654
655bool LoopIdiomRecognize::runOnCountableLoop() {
656 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
657 if (isa<SCEVCouldNotCompute>(BECount)) return false;
658
659 // If this loop executes exactly one time, then it should be peeled, not
660 // optimized by this pass.
661 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
662 if (BECst->getValue()->getValue() == 0)
663 return false;
664
665 // We require target data for now.
666 if (!getDataLayout())
667 return false;
668
669 getDominatorTree();
670
671 LoopInfo &LI = getAnalysis<LoopInfo>();
672 TLI = &getAnalysis<TargetLibraryInfo>();
673
674 getTargetLibraryInfo();
675
676 SmallVector<BasicBlock*, 8> ExitBlocks;
677 CurLoop->getUniqueExitBlocks(ExitBlocks);
678
679 DEBUG(dbgs() << "loop-idiom Scanning: F["
680 << CurLoop->getHeader()->getParent()->getName()
681 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
682
683 bool MadeChange = false;
684 // Scan all the blocks in the loop that are not in subloops.
685 for (Loop::block_iterator BI = CurLoop->block_begin(),
686 E = CurLoop->block_end(); BI != E; ++BI) {
687 // Ignore blocks in subloops.
688 if (LI.getLoopFor(*BI) != CurLoop)
689 continue;
690
691 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
692 }
693 return MadeChange;
694}
695
696bool LoopIdiomRecognize::runOnNoncountableLoop() {
697 NclPopcountRecognize Popcount(*this);
698 if (Popcount.recognize())
699 return true;
700
701 return false;
702}
703
Chris Lattnere6bb6492010-12-26 19:39:38 +0000704bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000705 CurLoop = L;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000706
Benjamin Kramer28aff842012-09-21 17:27:23 +0000707 // If the loop could not be converted to canonical form, it must have an
708 // indirectbr in it, just give up.
709 if (!L->getLoopPreheader())
710 return false;
711
Nadav Rotema94d6e82012-07-24 10:51:42 +0000712 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosier71400b62011-07-15 18:25:04 +0000713 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carrutha8647482012-11-02 08:33:25 +0000714 if (Name == "memset" || Name == "memcpy")
Chad Rosier71400b62011-07-15 18:25:04 +0000715 return false;
716
Chris Lattner22920b52010-12-26 20:45:45 +0000717 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang84fca612012-11-29 19:38:54 +0000718 if (SE->hasLoopInvariantBackedgeTakenCount(L))
719 return runOnCountableLoop();
720 return runOnNoncountableLoop();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000721}
722
723/// runOnLoopBlock - Process the specified block, which lives in a counted loop
724/// with the specified backedge count. This block is known to be in the current
725/// loop and not in any subloops.
726bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
727 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
728 // We can only promote stores in this block if they are unconditionally
729 // executed in the loop. For a block to be unconditionally executed, it has
730 // to dominate all the exit blocks of the loop. Verify this now.
731 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
732 if (!DT->dominates(BB, ExitBlocks[i]))
733 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000734
Chris Lattner22920b52010-12-26 20:45:45 +0000735 bool MadeChange = false;
736 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000737 Instruction *Inst = I++;
738 // Look for store instructions, which may be optimized to memset/memcpy.
739 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000740 WeakVH InstPtr(I);
741 if (!processLoopStore(SI, BECount)) continue;
742 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000743
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000744 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000745 // top of the block.
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000746 if (InstPtr == 0)
747 I = BB->begin();
748 continue;
749 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000750
Chris Lattnere41d3c02011-01-04 07:46:33 +0000751 // Look for memset instructions, which may be optimized to a larger memset.
752 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
753 WeakVH InstPtr(I);
754 if (!processLoopMemSet(MSI, BECount)) continue;
755 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000756
Chris Lattnere41d3c02011-01-04 07:46:33 +0000757 // If processing the memset invalidated our iterator, start over from the
758 // top of the block.
759 if (InstPtr == 0)
760 I = BB->begin();
761 continue;
762 }
Chris Lattner22920b52010-12-26 20:45:45 +0000763 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000764
Chris Lattner22920b52010-12-26 20:45:45 +0000765 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000766}
767
Chris Lattner62c50fd2011-01-02 19:01:03 +0000768
Chris Lattnere41d3c02011-01-04 07:46:33 +0000769/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000770bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman2bc3d522011-09-12 20:23:13 +0000771 if (!SI->isSimple()) return false;
Chris Lattnere41d3c02011-01-04 07:46:33 +0000772
Chris Lattner22920b52010-12-26 20:45:45 +0000773 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000774 Value *StorePtr = SI->getPointerOperand();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000775
Chris Lattner95ae6762010-12-28 18:53:48 +0000776 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000777 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000778 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000779 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000780
Chris Lattner22920b52010-12-26 20:45:45 +0000781 // See if the pointer expression is an AddRec like {base,+,1} on the current
782 // loop, which indicates a strided store. If we have something else, it's a
783 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000784 const SCEVAddRecExpr *StoreEv =
785 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
786 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000787 return false;
788
789 // Check to see if the stride matches the size of the store. If so, then we
790 // know that every byte is touched in the loop.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000791 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000792 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000793
Chris Lattner408b5342011-02-21 02:08:54 +0000794 if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
795 // TODO: Could also handle negative stride here someday, that will require
796 // the validity check in mayLoopAccessLocation to be updated though.
797 // Enable this to print exact negative strides.
Chris Lattner0e68cee2011-02-21 17:02:55 +0000798 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattner408b5342011-02-21 02:08:54 +0000799 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
800 dbgs() << "BB: " << *SI->getParent();
801 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000802
Chris Lattner22920b52010-12-26 20:45:45 +0000803 return false;
Chris Lattner408b5342011-02-21 02:08:54 +0000804 }
Chris Lattner3a393722011-02-19 19:31:39 +0000805
806 // See if we can optimize just this store in isolation.
807 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
808 StoredVal, SI, StoreEv, BECount))
809 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000810
Chris Lattnere2c43922011-01-02 03:37:56 +0000811 // If the stored value is a strided load in the same loop with the same stride
812 // this this may be transformable into a memcpy. This kicks in for stuff like
813 // for (i) A[i] = B[i];
814 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
815 const SCEVAddRecExpr *LoadEv =
816 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
817 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman2bc3d522011-09-12 20:23:13 +0000818 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattnere2c43922011-01-02 03:37:56 +0000819 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
820 return true;
821 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000822 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000823
Chris Lattnere6bb6492010-12-26 19:39:38 +0000824 return false;
825}
826
Chris Lattnere41d3c02011-01-04 07:46:33 +0000827/// processLoopMemSet - See if this memset can be promoted to a large memset.
828bool LoopIdiomRecognize::
829processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
830 // We can only handle non-volatile memsets with a constant size.
831 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
832
Chris Lattnerc19175c2011-02-18 22:22:15 +0000833 // If we're not allowed to hack on memset, we fail.
834 if (!TLI->has(LibFunc::memset))
835 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000836
Chris Lattnere41d3c02011-01-04 07:46:33 +0000837 Value *Pointer = MSI->getDest();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000838
Chris Lattnere41d3c02011-01-04 07:46:33 +0000839 // See if the pointer expression is an AddRec like {base,+,1} on the current
840 // loop, which indicates a strided store. If we have something else, it's a
841 // random store we can't handle.
842 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
843 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
844 return false;
845
846 // Reject memsets that are so large that they overflow an unsigned.
847 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
848 if ((SizeInBytes >> 32) != 0)
849 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000850
Chris Lattnere41d3c02011-01-04 07:46:33 +0000851 // Check to see if the stride matches the size of the memset. If so, then we
852 // know that every byte is touched in the loop.
853 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000854
Chris Lattnere41d3c02011-01-04 07:46:33 +0000855 // TODO: Could also handle negative stride here someday, that will require the
856 // validity check in mayLoopAccessLocation to be updated though.
857 if (Stride == 0 || MSI->getLength() != Stride->getValue())
858 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000859
Chris Lattner3a393722011-02-19 19:31:39 +0000860 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
861 MSI->getAlignment(), MSI->getValue(),
862 MSI, Ev, BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000863}
864
Chandler Carrutha8647482012-11-02 08:33:25 +0000865
866/// mayLoopAccessLocation - Return true if the specified loop might access the
867/// specified pointer location, which is a loop-strided access. The 'Access'
868/// argument specifies what the verboten forms of access are (read or write).
869static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
870 Loop *L, const SCEV *BECount,
871 unsigned StoreSize, AliasAnalysis &AA,
872 Instruction *IgnoredStore) {
873 // Get the location that may be stored across the loop. Since the access is
874 // strided positively through memory, we say that the modified location starts
875 // at the pointer and has infinite size.
876 uint64_t AccessSize = AliasAnalysis::UnknownSize;
877
878 // If the loop iterates a fixed number of times, we can refine the access size
879 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
880 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
881 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
882
883 // TODO: For this to be really effective, we have to dive into the pointer
884 // operand in the store. Store to &A[i] of 100 will always return may alias
885 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
886 // which will then no-alias a store to &A[100].
887 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
888
889 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
890 ++BI)
891 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
892 if (&*I != IgnoredStore &&
893 (AA.getModRefInfo(I, StoreLoc) & Access))
894 return true;
895
896 return false;
897}
898
Chris Lattner3a393722011-02-19 19:31:39 +0000899/// getMemSetPatternValue - If a strided store of the specified value is safe to
900/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
901/// be passed in. Otherwise, return null.
902///
903/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
904/// just replicate their input array and then pass on to memset_pattern16.
Micah Villmow3574eca2012-10-08 16:38:25 +0000905static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) {
Chris Lattner3a393722011-02-19 19:31:39 +0000906 // If the value isn't a constant, we can't promote it to being in a constant
907 // array. We could theoretically do a store to an alloca or something, but
908 // that doesn't seem worthwhile.
909 Constant *C = dyn_cast<Constant>(V);
910 if (C == 0) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000911
Chris Lattner3a393722011-02-19 19:31:39 +0000912 // Only handle simple values that are a power of two bytes in size.
913 uint64_t Size = TD.getTypeSizeInBits(V->getType());
914 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
915 return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000916
Chris Lattner80e8b502011-02-19 19:56:44 +0000917 // Don't care enough about darwin/ppc to implement this.
918 if (TD.isBigEndian())
919 return 0;
Chris Lattner3a393722011-02-19 19:31:39 +0000920
921 // Convert to size in bytes.
922 Size /= 8;
Chris Lattner3a393722011-02-19 19:31:39 +0000923
Chris Lattner3a393722011-02-19 19:31:39 +0000924 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner80e8b502011-02-19 19:56:44 +0000925 // if the top and bottom are the same (e.g. for vectors and large integers).
Chris Lattner3a393722011-02-19 19:31:39 +0000926 if (Size > 16) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000927
Chris Lattner80e8b502011-02-19 19:56:44 +0000928 // If the constant is exactly 16 bytes, just use it.
929 if (Size == 16) return C;
Chris Lattner3a393722011-02-19 19:31:39 +0000930
Chris Lattner80e8b502011-02-19 19:56:44 +0000931 // Otherwise, we'll use an array of the constants.
932 unsigned ArraySize = 16/Size;
933 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
934 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner3a393722011-02-19 19:31:39 +0000935}
936
937
938/// processLoopStridedStore - We see a strided store of some value. If we can
939/// transform this into a memset or memset_pattern in the loop preheader, do so.
940bool LoopIdiomRecognize::
941processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
942 unsigned StoreAlignment, Value *StoredVal,
943 Instruction *TheStore, const SCEVAddRecExpr *Ev,
944 const SCEV *BECount) {
Andrew Trickd99b39e2011-03-14 16:48:10 +0000945
Chris Lattner3a393722011-02-19 19:31:39 +0000946 // If the stored value is a byte-wise value (like i32 -1), then it may be
947 // turned into a memset of i8 -1, assuming that all the consecutive bytes
948 // are stored. A store of i32 0x01020304 can never be turned into a memset,
949 // but it can be turned into memset_pattern if the target supports it.
950 Value *SplatValue = isBytewiseValue(StoredVal);
951 Constant *PatternValue = 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000952
Chris Lattner3a393722011-02-19 19:31:39 +0000953 // If we're allowed to form a memset, and the stored value would be acceptable
954 // for memset, use it.
955 if (SplatValue && TLI->has(LibFunc::memset) &&
956 // Verify that the stored value is loop invariant. If not, we can't
957 // promote the memset.
958 CurLoop->isLoopInvariant(SplatValue)) {
959 // Keep and use SplatValue.
960 PatternValue = 0;
961 } else if (TLI->has(LibFunc::memset_pattern16) &&
962 (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
963 // It looks like we can use PatternValue!
964 SplatValue = 0;
965 } else {
966 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedman5ac7c7d2011-09-13 00:44:16 +0000967 // do anything with a 3-byte store.
Chris Lattnerbafa1172011-01-01 20:12:04 +0000968 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000969 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000970
Chris Lattner4f81b542011-05-22 17:39:56 +0000971 // The trip count of the loop and the base pointer of the addrec SCEV is
972 // guaranteed to be loop invariant, which means that it should dominate the
973 // header. This allows us to insert code for it in the preheader.
974 BasicBlock *Preheader = CurLoop->getLoopPreheader();
975 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000976 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000977
Chris Lattnera92ff912010-12-26 23:42:51 +0000978 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramer3740e792012-10-21 19:31:16 +0000979 // this into a memset in the loop preheader now if we want. However, this
980 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000981 // or write to the aliased location. Check for any overlap by generating the
982 // base pointer and checking the region.
983 unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000984 Value *BasePtr =
Chris Lattnera92ff912010-12-26 23:42:51 +0000985 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
986 Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000987
Chris Lattner4f81b542011-05-22 17:39:56 +0000988
Chandler Carrutha8647482012-11-02 08:33:25 +0000989 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
990 CurLoop, BECount,
991 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)){
992 Expander.clear();
993 // If we generated new code for the base pointer, clean up.
994 deleteIfDeadInstruction(BasePtr, *SE, TLI);
995 return false;
996 }
997
Chris Lattner4f81b542011-05-22 17:39:56 +0000998 // Okay, everything looks good, insert the memset.
999
Chris Lattnera92ff912010-12-26 23:42:51 +00001000 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1001 // pointer size if it isn't already.
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001002 Type *IntPtr = TD->getIntPtrType(DestPtr->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +00001003 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001004
Chris Lattnera92ff912010-12-26 23:42:51 +00001005 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +00001006 SCEV::FlagNUW);
Chris Lattnera92ff912010-12-26 23:42:51 +00001007 if (StoreSize != 1)
1008 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +00001009 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001010
1011 Value *NumBytes =
Chris Lattnera92ff912010-12-26 23:42:51 +00001012 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001013
Devang Patelcd77a502011-03-07 22:43:45 +00001014 CallInst *NewCall;
Chris Lattner3a393722011-02-19 19:31:39 +00001015 if (SplatValue)
1016 NewCall = Builder.CreateMemSet(BasePtr, SplatValue,NumBytes,StoreAlignment);
1017 else {
1018 Module *M = TheStore->getParent()->getParent()->getParent();
1019 Value *MSP = M->getOrInsertFunction("memset_pattern16",
1020 Builder.getVoidTy(),
Andrew Trickd99b39e2011-03-14 16:48:10 +00001021 Builder.getInt8PtrTy(),
Chris Lattner3a393722011-02-19 19:31:39 +00001022 Builder.getInt8PtrTy(), IntPtr,
1023 (void*)0);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001024
Chris Lattner3a393722011-02-19 19:31:39 +00001025 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1026 // an constant array of 16-bytes. Plop the value into a mergable global.
1027 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1028 GlobalValue::InternalLinkage,
1029 PatternValue, ".memset_pattern");
1030 GV->setUnnamedAddr(true); // Ok to merge these.
1031 GV->setAlignment(16);
Chris Lattner80e8b502011-02-19 19:56:44 +00001032 Value *PatternPtr = ConstantExpr::getBitCast(GV, Builder.getInt8PtrTy());
Chris Lattner3a393722011-02-19 19:31:39 +00001033 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1034 }
Andrew Trickd99b39e2011-03-14 16:48:10 +00001035
Chris Lattnera92ff912010-12-26 23:42:51 +00001036 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +00001037 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Patelcd77a502011-03-07 22:43:45 +00001038 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001039
Chris Lattner9f391882010-12-27 00:03:23 +00001040 // Okay, the memset has been formed. Zap the original store and anything that
1041 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001042 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner4ce31fb2011-01-02 07:36:44 +00001043 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +00001044 return true;
1045}
1046
Chris Lattnere2c43922011-01-02 03:37:56 +00001047/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1048/// same-strided load.
1049bool LoopIdiomRecognize::
1050processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1051 const SCEVAddRecExpr *StoreEv,
1052 const SCEVAddRecExpr *LoadEv,
1053 const SCEV *BECount) {
Chris Lattnerc19175c2011-02-18 22:22:15 +00001054 // If we're not allowed to form memcpy, we fail.
Chandler Carrutha8647482012-11-02 08:33:25 +00001055 if (!TLI->has(LibFunc::memcpy))
Chris Lattnerc19175c2011-02-18 22:22:15 +00001056 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +00001057
Chris Lattnere2c43922011-01-02 03:37:56 +00001058 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001059
Chris Lattner4f81b542011-05-22 17:39:56 +00001060 // The trip count of the loop and the base pointer of the addrec SCEV is
1061 // guaranteed to be loop invariant, which means that it should dominate the
1062 // header. This allows us to insert code for it in the preheader.
1063 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1064 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +00001065 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +00001066
Chris Lattnere2c43922011-01-02 03:37:56 +00001067 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carrutha8647482012-11-02 08:33:25 +00001068 // this into a memcpy in the loop preheader now if we want. However, this
1069 // would be unsafe to do if there is anything else in the loop that may read
1070 // or write the memory region we're storing to. This includes the load that
1071 // feeds the stores. Check for an alias by generating the base address and
1072 // checking everything.
Andrew Trickd99b39e2011-03-14 16:48:10 +00001073 Value *StoreBasePtr =
Chris Lattnere2c43922011-01-02 03:37:56 +00001074 Expander.expandCodeFor(StoreEv->getStart(),
1075 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1076 Preheader->getTerminator());
Chandler Carrutha8647482012-11-02 08:33:25 +00001077
1078 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1079 CurLoop, BECount, StoreSize,
1080 getAnalysis<AliasAnalysis>(), SI)) {
1081 Expander.clear();
1082 // If we generated new code for the base pointer, clean up.
1083 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1084 return false;
1085 }
1086
1087 // For a memcpy, we have to make sure that the input array is not being
1088 // mutated by the loop.
Chris Lattner4f81b542011-05-22 17:39:56 +00001089 Value *LoadBasePtr =
1090 Expander.expandCodeFor(LoadEv->getStart(),
1091 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1092 Preheader->getTerminator());
1093
Chandler Carrutha8647482012-11-02 08:33:25 +00001094 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1095 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1096 Expander.clear();
1097 // If we generated new code for the base pointer, clean up.
1098 deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1099 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1100 return false;
1101 }
1102
Chris Lattner4f81b542011-05-22 17:39:56 +00001103 // Okay, everything is safe, we can transform this!
Andrew Tricka5d950f2011-06-28 05:04:16 +00001104
Andrew Trickd99b39e2011-03-14 16:48:10 +00001105
Chris Lattnere2c43922011-01-02 03:37:56 +00001106 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1107 // pointer size if it isn't already.
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001108 Type *IntPtr = TD->getIntPtrType(SI->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +00001109 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001110
Chris Lattnere2c43922011-01-02 03:37:56 +00001111 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +00001112 SCEV::FlagNUW);
Chris Lattnere2c43922011-01-02 03:37:56 +00001113 if (StoreSize != 1)
1114 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +00001115 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001116
Chris Lattnere2c43922011-01-02 03:37:56 +00001117 Value *NumBytes =
1118 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001119
Chandler Carrutha8647482012-11-02 08:33:25 +00001120 CallInst *NewCall =
1121 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1122 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patelaf358412011-05-04 21:37:05 +00001123 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001124
Chandler Carrutha8647482012-11-02 08:33:25 +00001125 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattnere2c43922011-01-02 03:37:56 +00001126 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1127 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Tricka5d950f2011-06-28 05:04:16 +00001128
Andrew Trickd99b39e2011-03-14 16:48:10 +00001129
Chris Lattnere2c43922011-01-02 03:37:56 +00001130 // Okay, the memset has been formed. Zap the original store and anything that
1131 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001132 deleteDeadInstruction(SI, *SE, TLI);
Chandler Carrutha8647482012-11-02 08:33:25 +00001133 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +00001134 return true;
1135}