13b11a16aSHongbin Zheng //===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
23b11a16aSHongbin Zheng //
33b11a16aSHongbin Zheng //                     The LLVM Compiler Infrastructure
43b11a16aSHongbin Zheng //
53b11a16aSHongbin Zheng // This file is distributed under the University of Illinois Open Source
63b11a16aSHongbin Zheng // License. See LICENSE.TXT for details.
73b11a16aSHongbin Zheng //
83b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
93b11a16aSHongbin Zheng //
103b11a16aSHongbin Zheng // This file implements the BlockGenerator and VectorBlockGenerator classes,
113b11a16aSHongbin Zheng // which generate sequential code and vectorized code for a polyhedral
123b11a16aSHongbin Zheng // statement, respectively.
133b11a16aSHongbin Zheng //
143b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
153b11a16aSHongbin Zheng 
163b11a16aSHongbin Zheng #include "polly/ScopInfo.h"
1783628182STobias Grosser #include "isl/aff.h"
18a63b2579SJohannes Doerfert #include "isl/ast.h"
19a63b2579SJohannes Doerfert #include "isl/ast_build.h"
2083628182STobias Grosser #include "isl/set.h"
218a846610SHongbin Zheng #include "polly/CodeGen/BlockGenerators.h"
2283628182STobias Grosser #include "polly/CodeGen/CodeGeneration.h"
23a63b2579SJohannes Doerfert #include "polly/CodeGen/IslExprBuilder.h"
24637bd631STobias Grosser #include "polly/Options.h"
253b11a16aSHongbin Zheng #include "polly/Support/GICHelper.h"
2697cb813cSSebastian Pop #include "polly/Support/SCEVValidator.h"
27ecfe21b7STobias Grosser #include "polly/Support/ScopHelper.h"
28e71c6ab5STobias Grosser #include "llvm/Analysis/LoopInfo.h"
29e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolution.h"
30e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolutionExpander.h"
31030237d0STobias Grosser #include "llvm/IR/IntrinsicInst.h"
323b11a16aSHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
333b11a16aSHongbin Zheng 
343b11a16aSHongbin Zheng using namespace llvm;
353b11a16aSHongbin Zheng using namespace polly;
363b11a16aSHongbin Zheng 
37878aba49STobias Grosser static cl::opt<bool> Aligned("enable-polly-aligned",
38878aba49STobias Grosser                              cl::desc("Assumed aligned memory accesses."),
39878aba49STobias Grosser                              cl::Hidden, cl::init(false), cl::ZeroOrMore,
40878aba49STobias Grosser                              cl::cat(PollyCategory));
413b11a16aSHongbin Zheng 
42ecfe21b7STobias Grosser bool polly::canSynthesize(const Instruction *I, const llvm::LoopInfo *LI,
43ecfe21b7STobias Grosser                           ScalarEvolution *SE, const Region *R) {
44ecfe21b7STobias Grosser   if (!I || !SE->isSCEVable(I->getType()))
45ecfe21b7STobias Grosser     return false;
46ecfe21b7STobias Grosser 
47ecfe21b7STobias Grosser   if (const SCEV *Scev = SE->getSCEV(const_cast<Instruction *>(I)))
48ecfe21b7STobias Grosser     if (!isa<SCEVCouldNotCompute>(Scev))
49ecfe21b7STobias Grosser       if (!hasScalarDepsInsideRegion(Scev, R))
50ecfe21b7STobias Grosser         return true;
51ecfe21b7STobias Grosser 
52ecfe21b7STobias Grosser   return false;
53ecfe21b7STobias Grosser }
54ecfe21b7STobias Grosser 
55a63b2579SJohannes Doerfert BlockGenerator::BlockGenerator(PollyIRBuilder &B, ScopStmt &Stmt, Pass *P,
562ef3f4fdSJohannes Doerfert                                LoopInfo &LI, ScalarEvolution &SE,
57a63b2579SJohannes Doerfert                                isl_ast_build *Build,
58a63b2579SJohannes Doerfert                                IslExprBuilder *ExprBuilder)
592ef3f4fdSJohannes Doerfert     : Builder(B), Statement(Stmt), P(P), LI(LI), SE(SE), Build(Build),
602ef3f4fdSJohannes Doerfert       ExprBuilder(ExprBuilder) {}
61e71c6ab5STobias Grosser 
62d213a8b8STobias Grosser Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
63d213a8b8STobias Grosser                                    ValueMapT &GlobalMap, LoopToScevMapT &LTS,
64d213a8b8STobias Grosser                                    Loop *L) const {
653b11a16aSHongbin Zheng   // We assume constants never change.
663b11a16aSHongbin Zheng   // This avoids map lookups for many calls to this function.
673b11a16aSHongbin Zheng   if (isa<Constant>(Old))
683b11a16aSHongbin Zheng     return const_cast<Value *>(Old);
693b11a16aSHongbin Zheng 
70fe11e287SHongbin Zheng   if (Value *New = GlobalMap.lookup(Old)) {
71c14582f2STobias Grosser     if (Old->getType()->getScalarSizeInBits() <
72c14582f2STobias Grosser         New->getType()->getScalarSizeInBits())
733b11a16aSHongbin Zheng       New = Builder.CreateTruncOrBitCast(New, Old->getType());
743b11a16aSHongbin Zheng 
753b11a16aSHongbin Zheng     return New;
763b11a16aSHongbin Zheng   }
773b11a16aSHongbin Zheng 
78fe11e287SHongbin Zheng   if (Value *New = BBMap.lookup(Old))
79fe11e287SHongbin Zheng     return New;
803b11a16aSHongbin Zheng 
81683b8e44STobias Grosser   if (SE.isSCEVable(Old->getType()))
82369430ffSTobias Grosser     if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
83e71c6ab5STobias Grosser       if (!isa<SCEVCouldNotCompute>(Scev)) {
84637b23dcSSebastian Pop         const SCEV *NewScev = apply(Scev, LTS, SE);
85637b23dcSSebastian Pop         ValueToValueMap VTV;
86637b23dcSSebastian Pop         VTV.insert(BBMap.begin(), BBMap.end());
87637b23dcSSebastian Pop         VTV.insert(GlobalMap.begin(), GlobalMap.end());
8847d4ee3eSSebastian Pop         NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
89e71c6ab5STobias Grosser         SCEVExpander Expander(SE, "polly");
90e71c6ab5STobias Grosser         Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
91e71c6ab5STobias Grosser                                                  Builder.GetInsertPoint());
92e71c6ab5STobias Grosser 
93e71c6ab5STobias Grosser         BBMap[Old] = Expanded;
94e71c6ab5STobias Grosser         return Expanded;
95e71c6ab5STobias Grosser       }
96369430ffSTobias Grosser     }
97e71c6ab5STobias Grosser 
9816371acdSTobias Grosser   // A scop-constant value defined by a global or a function parameter.
9916371acdSTobias Grosser   if (isa<GlobalValue>(Old) || isa<Argument>(Old))
10016371acdSTobias Grosser     return const_cast<Value *>(Old);
10116371acdSTobias Grosser 
10216371acdSTobias Grosser   // A scop-constant value defined by an instruction executed outside the scop.
10316371acdSTobias Grosser   if (const Instruction *Inst = dyn_cast<Instruction>(Old))
10416371acdSTobias Grosser     if (!Statement.getParent()->getRegion().contains(Inst->getParent()))
10516371acdSTobias Grosser       return const_cast<Value *>(Old);
10616371acdSTobias Grosser 
10716371acdSTobias Grosser   // The scalar dependence is neither available nor SCEVCodegenable.
1085b463ceaSHongbin Zheng   llvm_unreachable("Unexpected scalar dependence in region!");
1095a56cbf4STobias Grosser   return nullptr;
1103b11a16aSHongbin Zheng }
1113b11a16aSHongbin Zheng 
1123b11a16aSHongbin Zheng void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
1139d10fffaSSebastian Pop                                     ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
114030237d0STobias Grosser   // We do not generate debug intrinsics as we did not investigate how to
115030237d0STobias Grosser   // copy them correctly. At the current state, they just crash the code
116030237d0STobias Grosser   // generation as the meta-data operands are not correctly copied.
117030237d0STobias Grosser   if (isa<DbgInfoIntrinsic>(Inst))
118030237d0STobias Grosser     return;
119030237d0STobias Grosser 
1203b11a16aSHongbin Zheng   Instruction *NewInst = Inst->clone();
1213b11a16aSHongbin Zheng 
1223b11a16aSHongbin Zheng   // Replace old operands with the new ones.
12391f5b262STobias Grosser   for (Value *OldOperand : Inst->operands()) {
124369430ffSTobias Grosser     Value *NewOperand =
125369430ffSTobias Grosser         getNewValue(OldOperand, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
1263b11a16aSHongbin Zheng 
1273b11a16aSHongbin Zheng     if (!NewOperand) {
128c14582f2STobias Grosser       assert(!isa<StoreInst>(NewInst) &&
129c14582f2STobias Grosser              "Store instructions are always needed!");
1303b11a16aSHongbin Zheng       delete NewInst;
1313b11a16aSHongbin Zheng       return;
1323b11a16aSHongbin Zheng     }
1333b11a16aSHongbin Zheng 
1343b11a16aSHongbin Zheng     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
1353b11a16aSHongbin Zheng   }
1363b11a16aSHongbin Zheng 
1373b11a16aSHongbin Zheng   Builder.Insert(NewInst);
1383b11a16aSHongbin Zheng   BBMap[Inst] = NewInst;
1393b11a16aSHongbin Zheng 
1403b11a16aSHongbin Zheng   if (!NewInst->getType()->isVoidTy())
1413b11a16aSHongbin Zheng     NewInst->setName("p_" + Inst->getName());
1423b11a16aSHongbin Zheng }
1433b11a16aSHongbin Zheng 
144a63b2579SJohannes Doerfert Value *BlockGenerator::getNewAccessOperand(const MemoryAccess &MA) {
145a99130f0SJohannes Doerfert   isl_pw_multi_aff *PWAccRel;
146a99130f0SJohannes Doerfert   isl_union_map *Schedule;
147a63b2579SJohannes Doerfert   isl_ast_expr *Expr;
1483b11a16aSHongbin Zheng 
149a63b2579SJohannes Doerfert   assert(ExprBuilder && Build &&
150a63b2579SJohannes Doerfert          "Cannot generate new value without IslExprBuilder!");
1513b11a16aSHongbin Zheng 
152a99130f0SJohannes Doerfert   Schedule = isl_ast_build_get_schedule(Build);
153a99130f0SJohannes Doerfert   PWAccRel = MA.applyScheduleToAccessRelation(Schedule);
1543b11a16aSHongbin Zheng 
155a63b2579SJohannes Doerfert   Expr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
156dcb5f1dcSJohannes Doerfert   Expr = isl_ast_expr_address_of(Expr);
157a63b2579SJohannes Doerfert 
158a63b2579SJohannes Doerfert   return ExprBuilder->create(Expr);
1593b11a16aSHongbin Zheng }
1603b11a16aSHongbin Zheng 
161e602a076STobias Grosser Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
162e602a076STobias Grosser                                                 const Value *Pointer,
163e602a076STobias Grosser                                                 ValueMapT &BBMap,
164e602a076STobias Grosser                                                 ValueMapT &GlobalMap,
165e602a076STobias Grosser                                                 LoopToScevMapT &LTS) {
166a63b2579SJohannes Doerfert   const MemoryAccess &MA = Statement.getAccessFor(Inst);
1673b11a16aSHongbin Zheng 
1683b11a16aSHongbin Zheng   Value *NewPointer;
169a99130f0SJohannes Doerfert   if (MA.hasNewAccessRelation())
170a63b2579SJohannes Doerfert     NewPointer = getNewAccessOperand(MA);
171a63b2579SJohannes Doerfert   else
172369430ffSTobias Grosser     NewPointer =
173369430ffSTobias Grosser         getNewValue(Pointer, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
1743b11a16aSHongbin Zheng 
1753b11a16aSHongbin Zheng   return NewPointer;
1763b11a16aSHongbin Zheng }
1773b11a16aSHongbin Zheng 
1784d96c8d7STobias Grosser Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
1792ef3f4fdSJohannes Doerfert   return LI.getLoopFor(Inst->getParent());
180369430ffSTobias Grosser }
181369430ffSTobias Grosser 
182e602a076STobias Grosser Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
183e602a076STobias Grosser                                           ValueMapT &BBMap,
184e602a076STobias Grosser                                           ValueMapT &GlobalMap,
185e602a076STobias Grosser                                           LoopToScevMapT &LTS) {
1863b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
1877242ad92STobias Grosser   Value *NewPointer =
1881947f863SJohannes Doerfert       generateLocationAccessed(Load, Pointer, BBMap, GlobalMap, LTS);
18987901453SJohannes Doerfert   Value *ScalarLoad = Builder.CreateAlignedLoad(
19087901453SJohannes Doerfert       NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
1913b11a16aSHongbin Zheng   return ScalarLoad;
1923b11a16aSHongbin Zheng }
1933b11a16aSHongbin Zheng 
194e602a076STobias Grosser Value *BlockGenerator::generateScalarStore(const StoreInst *Store,
195e602a076STobias Grosser                                            ValueMapT &BBMap,
196e602a076STobias Grosser                                            ValueMapT &GlobalMap,
197e602a076STobias Grosser                                            LoopToScevMapT &LTS) {
1983b11a16aSHongbin Zheng   const Value *Pointer = Store->getPointerOperand();
199c14582f2STobias Grosser   Value *NewPointer =
2009d10fffaSSebastian Pop       generateLocationAccessed(Store, Pointer, BBMap, GlobalMap, LTS);
201369430ffSTobias Grosser   Value *ValueOperand = getNewValue(Store->getValueOperand(), BBMap, GlobalMap,
202369430ffSTobias Grosser                                     LTS, getLoopForInst(Store));
2033b11a16aSHongbin Zheng 
20487901453SJohannes Doerfert   Value *NewStore = Builder.CreateAlignedStore(ValueOperand, NewPointer,
20587901453SJohannes Doerfert                                                Store->getAlignment());
20687901453SJohannes Doerfert   return NewStore;
2073b11a16aSHongbin Zheng }
2083b11a16aSHongbin Zheng 
209e602a076STobias Grosser void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
210e602a076STobias Grosser                                      ValueMapT &GlobalMap,
211e602a076STobias Grosser                                      LoopToScevMapT &LTS) {
2123b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
2133b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
2143b11a16aSHongbin Zheng   if (Inst->isTerminator())
2153b11a16aSHongbin Zheng     return;
2163b11a16aSHongbin Zheng 
217f557987bSChandler Carruth   if (canSynthesize(Inst, &P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
218f557987bSChandler Carruth                     &SE, &Statement.getParent()->getRegion()))
219e71c6ab5STobias Grosser     return;
220e71c6ab5STobias Grosser 
2213b11a16aSHongbin Zheng   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
222753d43f9SSebastian Pop     Value *NewLoad = generateScalarLoad(Load, BBMap, GlobalMap, LTS);
2233d94fedfSSebastian Pop     // Compute NewLoad before its insertion in BBMap to make the insertion
2243d94fedfSSebastian Pop     // deterministic.
225753d43f9SSebastian Pop     BBMap[Load] = NewLoad;
2263b11a16aSHongbin Zheng     return;
2273b11a16aSHongbin Zheng   }
2283b11a16aSHongbin Zheng 
2293b11a16aSHongbin Zheng   if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
230753d43f9SSebastian Pop     Value *NewStore = generateScalarStore(Store, BBMap, GlobalMap, LTS);
2313d94fedfSSebastian Pop     // Compute NewStore before its insertion in BBMap to make the insertion
2323d94fedfSSebastian Pop     // deterministic.
233753d43f9SSebastian Pop     BBMap[Store] = NewStore;
2343b11a16aSHongbin Zheng     return;
2353b11a16aSHongbin Zheng   }
2363b11a16aSHongbin Zheng 
2379d10fffaSSebastian Pop   copyInstScalar(Inst, BBMap, GlobalMap, LTS);
2383b11a16aSHongbin Zheng }
2393b11a16aSHongbin Zheng 
2409d10fffaSSebastian Pop void BlockGenerator::copyBB(ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
2415ec3333dSChandler Carruth   auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2425ec3333dSChandler Carruth   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
2435ec3333dSChandler Carruth   auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
244*a8cd1524STobias Grosser   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
2455ec3333dSChandler Carruth 
2463b11a16aSHongbin Zheng   BasicBlock *BB = Statement.getBasicBlock();
247c14582f2STobias Grosser   BasicBlock *CopyBB =
2485ec3333dSChandler Carruth       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), DT, LI);
2493b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
2503b11a16aSHongbin Zheng   Builder.SetInsertPoint(CopyBB->begin());
2513b11a16aSHongbin Zheng 
2523b11a16aSHongbin Zheng   ValueMapT BBMap;
2533b11a16aSHongbin Zheng 
25491f5b262STobias Grosser   for (Instruction &Inst : *BB)
25591f5b262STobias Grosser     copyInstruction(&Inst, BBMap, GlobalMap, LTS);
2563b11a16aSHongbin Zheng }
2573b11a16aSHongbin Zheng 
2582ef3f4fdSJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(
2592ef3f4fdSJohannes Doerfert     PollyIRBuilder &B, VectorValueMapT &GlobalMaps,
2602ef3f4fdSJohannes Doerfert     std::vector<LoopToScevMapT> &VLTS, ScopStmt &Stmt,
261731685e6SJohannes Doerfert     __isl_keep isl_map *Schedule, Pass *P, LoopInfo &LI, ScalarEvolution &SE,
262731685e6SJohannes Doerfert     __isl_keep isl_ast_build *Build, IslExprBuilder *ExprBuilder)
263731685e6SJohannes Doerfert     : BlockGenerator(B, Stmt, P, LI, SE, Build, ExprBuilder),
2642ef3f4fdSJohannes Doerfert       GlobalMaps(GlobalMaps), VLTS(VLTS), Schedule(Schedule) {
2653b11a16aSHongbin Zheng   assert(GlobalMaps.size() > 1 && "Only one vector lane found");
266a00a0291SSebastian Pop   assert(Schedule && "No statement domain provided");
2673b11a16aSHongbin Zheng }
2683b11a16aSHongbin Zheng 
269e602a076STobias Grosser Value *VectorBlockGenerator::getVectorValue(const Value *Old,
270e602a076STobias Grosser                                             ValueMapT &VectorMap,
271e602a076STobias Grosser                                             VectorValueMapT &ScalarMaps,
272e602a076STobias Grosser                                             Loop *L) {
273fe11e287SHongbin Zheng   if (Value *NewValue = VectorMap.lookup(Old))
274fe11e287SHongbin Zheng     return NewValue;
2753b11a16aSHongbin Zheng 
2763b11a16aSHongbin Zheng   int Width = getVectorWidth();
2773b11a16aSHongbin Zheng 
2783b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
2793b11a16aSHongbin Zheng 
2803b11a16aSHongbin Zheng   for (int Lane = 0; Lane < Width; Lane++)
281c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
2827242ad92STobias Grosser         Vector,
283369430ffSTobias Grosser         getNewValue(Old, ScalarMaps[Lane], GlobalMaps[Lane], VLTS[Lane], L),
2847242ad92STobias Grosser         Builder.getInt32(Lane));
2853b11a16aSHongbin Zheng 
2863b11a16aSHongbin Zheng   VectorMap[Old] = Vector;
2873b11a16aSHongbin Zheng 
2883b11a16aSHongbin Zheng   return Vector;
2893b11a16aSHongbin Zheng }
2903b11a16aSHongbin Zheng 
2913b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
2923b11a16aSHongbin Zheng   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
2933b11a16aSHongbin Zheng   assert(PointerTy && "PointerType expected");
2943b11a16aSHongbin Zheng 
2953b11a16aSHongbin Zheng   Type *ScalarType = PointerTy->getElementType();
2963b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(ScalarType, Width);
2973b11a16aSHongbin Zheng 
2983b11a16aSHongbin Zheng   return PointerType::getUnqual(VectorType);
2993b11a16aSHongbin Zheng }
3003b11a16aSHongbin Zheng 
3010dd463faSTobias Grosser Value *
3020dd463faSTobias Grosser VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
3030dd463faSTobias Grosser                                             VectorValueMapT &ScalarMaps,
3040dd463faSTobias Grosser                                             bool NegativeStride = false) {
3050dd463faSTobias Grosser   unsigned VectorWidth = getVectorWidth();
3063b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
3070dd463faSTobias Grosser   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
3080dd463faSTobias Grosser   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
3090dd463faSTobias Grosser 
3105a56cbf4STobias Grosser   Value *NewPointer = nullptr;
311731685e6SJohannes Doerfert   NewPointer = generateLocationAccessed(Load, Pointer, ScalarMaps[Offset],
312731685e6SJohannes Doerfert                                         GlobalMaps[Offset], VLTS[Offset]);
313c14582f2STobias Grosser   Value *VectorPtr =
314c14582f2STobias Grosser       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
315c14582f2STobias Grosser   LoadInst *VecLoad =
316c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
3173b11a16aSHongbin Zheng   if (!Aligned)
3183b11a16aSHongbin Zheng     VecLoad->setAlignment(8);
3193b11a16aSHongbin Zheng 
3200dd463faSTobias Grosser   if (NegativeStride) {
3210dd463faSTobias Grosser     SmallVector<Constant *, 16> Indices;
3220dd463faSTobias Grosser     for (int i = VectorWidth - 1; i >= 0; i--)
3230dd463faSTobias Grosser       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
3240dd463faSTobias Grosser     Constant *SV = llvm::ConstantVector::get(Indices);
3250dd463faSTobias Grosser     Value *RevVecLoad = Builder.CreateShuffleVector(
3260dd463faSTobias Grosser         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
3270dd463faSTobias Grosser     return RevVecLoad;
3280dd463faSTobias Grosser   }
3290dd463faSTobias Grosser 
3303b11a16aSHongbin Zheng   return VecLoad;
3313b11a16aSHongbin Zheng }
3323b11a16aSHongbin Zheng 
3333b11a16aSHongbin Zheng Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
3343b11a16aSHongbin Zheng                                                     ValueMapT &BBMap) {
3353b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
3363b11a16aSHongbin Zheng   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
337369430ffSTobias Grosser   Value *NewPointer =
338731685e6SJohannes Doerfert       generateLocationAccessed(Load, Pointer, BBMap, GlobalMaps[0], VLTS[0]);
3393b11a16aSHongbin Zheng   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
3403b11a16aSHongbin Zheng                                            Load->getName() + "_p_vec_p");
341c14582f2STobias Grosser   LoadInst *ScalarLoad =
342c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
3433b11a16aSHongbin Zheng 
3443b11a16aSHongbin Zheng   if (!Aligned)
3453b11a16aSHongbin Zheng     ScalarLoad->setAlignment(8);
3463b11a16aSHongbin Zheng 
347c14582f2STobias Grosser   Constant *SplatVector = Constant::getNullValue(
348c14582f2STobias Grosser       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
3493b11a16aSHongbin Zheng 
350c14582f2STobias Grosser   Value *VectorLoad = Builder.CreateShuffleVector(
351c14582f2STobias Grosser       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
3523b11a16aSHongbin Zheng   return VectorLoad;
3533b11a16aSHongbin Zheng }
3543b11a16aSHongbin Zheng 
355e602a076STobias Grosser Value *
356e602a076STobias Grosser VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
357e602a076STobias Grosser                                                 VectorValueMapT &ScalarMaps) {
3583b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
3593b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
3603b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(
3613b11a16aSHongbin Zheng       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
3623b11a16aSHongbin Zheng 
3633b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
3643b11a16aSHongbin Zheng 
3653b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++) {
366731685e6SJohannes Doerfert     Value *NewPointer = generateLocationAccessed(Load, Pointer, ScalarMaps[i],
367731685e6SJohannes Doerfert                                                  GlobalMaps[i], VLTS[i]);
368c14582f2STobias Grosser     Value *ScalarLoad =
369c14582f2STobias Grosser         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
370c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
371c14582f2STobias Grosser         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
3723b11a16aSHongbin Zheng   }
3733b11a16aSHongbin Zheng 
3743b11a16aSHongbin Zheng   return Vector;
3753b11a16aSHongbin Zheng }
3763b11a16aSHongbin Zheng 
377e602a076STobias Grosser void VectorBlockGenerator::generateLoad(const LoadInst *Load,
378e602a076STobias Grosser                                         ValueMapT &VectorMap,
379e602a076STobias Grosser                                         VectorValueMapT &ScalarMaps) {
38068794217SHongbin Zheng   if (PollyVectorizerChoice >= VECTORIZER_FIRST_NEED_GROUPED_UNROLL ||
38168794217SHongbin Zheng       !VectorType::isValidElementType(Load->getType())) {
3823b11a16aSHongbin Zheng     for (int i = 0; i < getVectorWidth(); i++)
383c14582f2STobias Grosser       ScalarMaps[i][Load] =
3849d10fffaSSebastian Pop           generateScalarLoad(Load, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
3853b11a16aSHongbin Zheng     return;
3863b11a16aSHongbin Zheng   }
3873b11a16aSHongbin Zheng 
388b5f24a66SHongbin Zheng   const MemoryAccess &Access = Statement.getAccessFor(Load);
3893b11a16aSHongbin Zheng 
39095493984STobias Grosser   // Make sure we have scalar values available to access the pointer to
39195493984STobias Grosser   // the data location.
39295493984STobias Grosser   extractScalarValues(Load, VectorMap, ScalarMaps);
39395493984STobias Grosser 
3943b11a16aSHongbin Zheng   Value *NewLoad;
395a00a0291SSebastian Pop   if (Access.isStrideZero(isl_map_copy(Schedule)))
3963b11a16aSHongbin Zheng     NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
397a00a0291SSebastian Pop   else if (Access.isStrideOne(isl_map_copy(Schedule)))
3980dd463faSTobias Grosser     NewLoad = generateStrideOneLoad(Load, ScalarMaps);
3990dd463faSTobias Grosser   else if (Access.isStrideX(isl_map_copy(Schedule), -1))
4000dd463faSTobias Grosser     NewLoad = generateStrideOneLoad(Load, ScalarMaps, true);
4013b11a16aSHongbin Zheng   else
4023b11a16aSHongbin Zheng     NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
4033b11a16aSHongbin Zheng 
4043b11a16aSHongbin Zheng   VectorMap[Load] = NewLoad;
4053b11a16aSHongbin Zheng }
4063b11a16aSHongbin Zheng 
4073b11a16aSHongbin Zheng void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
4083b11a16aSHongbin Zheng                                          ValueMapT &VectorMap,
4093b11a16aSHongbin Zheng                                          VectorValueMapT &ScalarMaps) {
4103b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
411369430ffSTobias Grosser   Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap, ScalarMaps,
412369430ffSTobias Grosser                                      getLoopForInst(Inst));
4133b11a16aSHongbin Zheng 
4143b11a16aSHongbin Zheng   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
4153b11a16aSHongbin Zheng 
4163b11a16aSHongbin Zheng   const CastInst *Cast = dyn_cast<CastInst>(Inst);
4173b11a16aSHongbin Zheng   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
4183b11a16aSHongbin Zheng   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
4193b11a16aSHongbin Zheng }
4203b11a16aSHongbin Zheng 
4213b11a16aSHongbin Zheng void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
4223b11a16aSHongbin Zheng                                           ValueMapT &VectorMap,
4233b11a16aSHongbin Zheng                                           VectorValueMapT &ScalarMaps) {
424369430ffSTobias Grosser   Loop *L = getLoopForInst(Inst);
4253b11a16aSHongbin Zheng   Value *OpZero = Inst->getOperand(0);
4263b11a16aSHongbin Zheng   Value *OpOne = Inst->getOperand(1);
4273b11a16aSHongbin Zheng 
4283b11a16aSHongbin Zheng   Value *NewOpZero, *NewOpOne;
429369430ffSTobias Grosser   NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps, L);
430369430ffSTobias Grosser   NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps, L);
4313b11a16aSHongbin Zheng 
4321bb59b0dSTobias Grosser   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
4333b11a16aSHongbin Zheng                                        Inst->getName() + "p_vec");
4343b11a16aSHongbin Zheng   VectorMap[Inst] = NewInst;
4353b11a16aSHongbin Zheng }
4363b11a16aSHongbin Zheng 
437e602a076STobias Grosser void VectorBlockGenerator::copyStore(const StoreInst *Store,
438e602a076STobias Grosser                                      ValueMapT &VectorMap,
439e602a076STobias Grosser                                      VectorValueMapT &ScalarMaps) {
440b5f24a66SHongbin Zheng   const MemoryAccess &Access = Statement.getAccessFor(Store);
4413b11a16aSHongbin Zheng 
4423b11a16aSHongbin Zheng   const Value *Pointer = Store->getPointerOperand();
443369430ffSTobias Grosser   Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
444369430ffSTobias Grosser                                  ScalarMaps, getLoopForInst(Store));
4453b11a16aSHongbin Zheng 
44650fd7010STobias Grosser   // Make sure we have scalar values available to access the pointer to
44750fd7010STobias Grosser   // the data location.
44850fd7010STobias Grosser   extractScalarValues(Store, VectorMap, ScalarMaps);
44950fd7010STobias Grosser 
450a00a0291SSebastian Pop   if (Access.isStrideOne(isl_map_copy(Schedule))) {
4511947f863SJohannes Doerfert     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
452731685e6SJohannes Doerfert     Value *NewPointer = generateLocationAccessed(Store, Pointer, ScalarMaps[0],
453731685e6SJohannes Doerfert                                                  GlobalMaps[0], VLTS[0]);
4543b11a16aSHongbin Zheng 
455c14582f2STobias Grosser     Value *VectorPtr =
456c14582f2STobias Grosser         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
4573b11a16aSHongbin Zheng     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
4583b11a16aSHongbin Zheng 
4593b11a16aSHongbin Zheng     if (!Aligned)
4603b11a16aSHongbin Zheng       Store->setAlignment(8);
4613b11a16aSHongbin Zheng   } else {
4623b11a16aSHongbin Zheng     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
4631bb59b0dSTobias Grosser       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
464731685e6SJohannes Doerfert       Value *NewPointer = generateLocationAccessed(
465731685e6SJohannes Doerfert           Store, Pointer, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
4663b11a16aSHongbin Zheng       Builder.CreateStore(Scalar, NewPointer);
4673b11a16aSHongbin Zheng     }
4683b11a16aSHongbin Zheng   }
4693b11a16aSHongbin Zheng }
4703b11a16aSHongbin Zheng 
4713b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
4723b11a16aSHongbin Zheng                                              ValueMapT &VectorMap) {
47391f5b262STobias Grosser   for (Value *Operand : Inst->operands())
47491f5b262STobias Grosser     if (VectorMap.count(Operand))
4753b11a16aSHongbin Zheng       return true;
4763b11a16aSHongbin Zheng   return false;
4773b11a16aSHongbin Zheng }
4783b11a16aSHongbin Zheng 
4793b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
4803b11a16aSHongbin Zheng                                                ValueMapT &VectorMap,
4813b11a16aSHongbin Zheng                                                VectorValueMapT &ScalarMaps) {
4823b11a16aSHongbin Zheng   bool HasVectorOperand = false;
4833b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
4843b11a16aSHongbin Zheng 
48591f5b262STobias Grosser   for (Value *Operand : Inst->operands()) {
48691f5b262STobias Grosser     ValueMapT::iterator VecOp = VectorMap.find(Operand);
4873b11a16aSHongbin Zheng 
4883b11a16aSHongbin Zheng     if (VecOp == VectorMap.end())
4893b11a16aSHongbin Zheng       continue;
4903b11a16aSHongbin Zheng 
4913b11a16aSHongbin Zheng     HasVectorOperand = true;
4923b11a16aSHongbin Zheng     Value *NewVector = VecOp->second;
4933b11a16aSHongbin Zheng 
4943b11a16aSHongbin Zheng     for (int i = 0; i < VectorWidth; ++i) {
4953b11a16aSHongbin Zheng       ValueMapT &SM = ScalarMaps[i];
4963b11a16aSHongbin Zheng 
4973b11a16aSHongbin Zheng       // If there is one scalar extracted, all scalar elements should have
4983b11a16aSHongbin Zheng       // already been extracted by the code here. So no need to check for the
4993b11a16aSHongbin Zheng       // existance of all of them.
50091f5b262STobias Grosser       if (SM.count(Operand))
5013b11a16aSHongbin Zheng         break;
5023b11a16aSHongbin Zheng 
50391f5b262STobias Grosser       SM[Operand] =
50491f5b262STobias Grosser           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
5053b11a16aSHongbin Zheng     }
5063b11a16aSHongbin Zheng   }
5073b11a16aSHongbin Zheng 
5083b11a16aSHongbin Zheng   return HasVectorOperand;
5093b11a16aSHongbin Zheng }
5103b11a16aSHongbin Zheng 
5113b11a16aSHongbin Zheng void VectorBlockGenerator::copyInstScalarized(const Instruction *Inst,
5123b11a16aSHongbin Zheng                                               ValueMapT &VectorMap,
5133b11a16aSHongbin Zheng                                               VectorValueMapT &ScalarMaps) {
5143b11a16aSHongbin Zheng   bool HasVectorOperand;
5153b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
5163b11a16aSHongbin Zheng 
5173b11a16aSHongbin Zheng   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
5183b11a16aSHongbin Zheng 
5193b11a16aSHongbin Zheng   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
520731685e6SJohannes Doerfert     BlockGenerator::copyInstruction(Inst, ScalarMaps[VectorLane],
521731685e6SJohannes Doerfert                                     GlobalMaps[VectorLane], VLTS[VectorLane]);
5223b11a16aSHongbin Zheng 
5233b11a16aSHongbin Zheng   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
5243b11a16aSHongbin Zheng     return;
5253b11a16aSHongbin Zheng 
5263b11a16aSHongbin Zheng   // Make the result available as vector value.
5273b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
5283b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
5293b11a16aSHongbin Zheng 
5303b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++)
5313b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
5323b11a16aSHongbin Zheng                                          Builder.getInt32(i));
5333b11a16aSHongbin Zheng 
5343b11a16aSHongbin Zheng   VectorMap[Inst] = Vector;
5353b11a16aSHongbin Zheng }
5363b11a16aSHongbin Zheng 
537c14582f2STobias Grosser int VectorBlockGenerator::getVectorWidth() { return GlobalMaps.size(); }
5383b11a16aSHongbin Zheng 
5393b11a16aSHongbin Zheng void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
5403b11a16aSHongbin Zheng                                            ValueMapT &VectorMap,
5413b11a16aSHongbin Zheng                                            VectorValueMapT &ScalarMaps) {
5423b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
5433b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
5443b11a16aSHongbin Zheng   if (Inst->isTerminator())
5453b11a16aSHongbin Zheng     return;
5463b11a16aSHongbin Zheng 
547f557987bSChandler Carruth   if (canSynthesize(Inst, &P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
548f557987bSChandler Carruth                     &SE, &Statement.getParent()->getRegion()))
549e71c6ab5STobias Grosser     return;
550e71c6ab5STobias Grosser 
5513b11a16aSHongbin Zheng   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
5523b11a16aSHongbin Zheng     generateLoad(Load, VectorMap, ScalarMaps);
5533b11a16aSHongbin Zheng     return;
5543b11a16aSHongbin Zheng   }
5553b11a16aSHongbin Zheng 
5563b11a16aSHongbin Zheng   if (hasVectorOperands(Inst, VectorMap)) {
5573b11a16aSHongbin Zheng     if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
5583b11a16aSHongbin Zheng       copyStore(Store, VectorMap, ScalarMaps);
5593b11a16aSHongbin Zheng       return;
5603b11a16aSHongbin Zheng     }
5613b11a16aSHongbin Zheng 
5623b11a16aSHongbin Zheng     if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
5633b11a16aSHongbin Zheng       copyUnaryInst(Unary, VectorMap, ScalarMaps);
5643b11a16aSHongbin Zheng       return;
5653b11a16aSHongbin Zheng     }
5663b11a16aSHongbin Zheng 
5673b11a16aSHongbin Zheng     if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
5683b11a16aSHongbin Zheng       copyBinaryInst(Binary, VectorMap, ScalarMaps);
5693b11a16aSHongbin Zheng       return;
5703b11a16aSHongbin Zheng     }
5713b11a16aSHongbin Zheng 
5723b11a16aSHongbin Zheng     // Falltrough: We generate scalar instructions, if we don't know how to
5733b11a16aSHongbin Zheng     // generate vector code.
5743b11a16aSHongbin Zheng   }
5753b11a16aSHongbin Zheng 
5763b11a16aSHongbin Zheng   copyInstScalarized(Inst, VectorMap, ScalarMaps);
5773b11a16aSHongbin Zheng }
5783b11a16aSHongbin Zheng 
5793b11a16aSHongbin Zheng void VectorBlockGenerator::copyBB() {
5805ec3333dSChandler Carruth   auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5815ec3333dSChandler Carruth   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5825ec3333dSChandler Carruth   auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
583*a8cd1524STobias Grosser   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
5845ec3333dSChandler Carruth 
5853b11a16aSHongbin Zheng   BasicBlock *BB = Statement.getBasicBlock();
586c14582f2STobias Grosser   BasicBlock *CopyBB =
5875ec3333dSChandler Carruth       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), DT, LI);
5883b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
5893b11a16aSHongbin Zheng   Builder.SetInsertPoint(CopyBB->begin());
5903b11a16aSHongbin Zheng 
5913b11a16aSHongbin Zheng   // Create two maps that store the mapping from the original instructions of
5923b11a16aSHongbin Zheng   // the old basic block to their copies in the new basic block. Those maps
5933b11a16aSHongbin Zheng   // are basic block local.
5943b11a16aSHongbin Zheng   //
5953b11a16aSHongbin Zheng   // As vector code generation is supported there is one map for scalar values
5963b11a16aSHongbin Zheng   // and one for vector values.
5973b11a16aSHongbin Zheng   //
5983b11a16aSHongbin Zheng   // In case we just do scalar code generation, the vectorMap is not used and
5993b11a16aSHongbin Zheng   // the scalarMap has just one dimension, which contains the mapping.
6003b11a16aSHongbin Zheng   //
6013b11a16aSHongbin Zheng   // In case vector code generation is done, an instruction may either appear
6023b11a16aSHongbin Zheng   // in the vector map once (as it is calculating >vectorwidth< values at a
6033b11a16aSHongbin Zheng   // time. Or (if the values are calculated using scalar operations), it
6043b11a16aSHongbin Zheng   // appears once in every dimension of the scalarMap.
6053b11a16aSHongbin Zheng   VectorValueMapT ScalarBlockMap(getVectorWidth());
6063b11a16aSHongbin Zheng   ValueMapT VectorBlockMap;
6073b11a16aSHongbin Zheng 
60891f5b262STobias Grosser   for (Instruction &Inst : *BB)
60991f5b262STobias Grosser     copyInstruction(&Inst, VectorBlockMap, ScalarBlockMap);
6103b11a16aSHongbin Zheng }
611