blob: 0643fbe83d8191d51c2d66623031ce761e265dfe [file] [log] [blame]
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the BlockGenerator and VectorBlockGenerator classes,
11// which generate sequential code and vectorized code for a polyhedral
12// statement, respectively.
13//
14//===----------------------------------------------------------------------===//
15
16#include "polly/ScopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000017#include "isl/aff.h"
18#include "isl/set.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000019#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000020#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000021#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000022#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000023#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000024#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000025#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser030237d2014-02-21 15:06:05 +000028#include "llvm/IR/IntrinsicInst.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030
Hongbin Zheng3b11a162012-04-25 13:16:49 +000031using namespace llvm;
32using namespace polly;
33
34static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000035Aligned("enable-polly-aligned", cl::desc("Assumed aligned memory accesses."),
36 cl::Hidden, cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser637bd632013-05-07 07:31:10 +000037 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000038
Tobias Grossere602a072013-05-07 07:30:56 +000039static cl::opt<bool, true>
40SCEVCodegenF("polly-codegen-scev", cl::desc("Use SCEV based code generation."),
41 cl::Hidden, cl::location(SCEVCodegen), cl::init(false),
Tobias Grosser637bd632013-05-07 07:31:10 +000042 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosserecfe21b2013-03-20 18:03:18 +000043
44bool polly::SCEVCodegen;
45
46bool polly::canSynthesize(const Instruction *I, const llvm::LoopInfo *LI,
47 ScalarEvolution *SE, const Region *R) {
48 if (SCEVCodegen) {
49 if (!I || !SE->isSCEVable(I->getType()))
50 return false;
51
52 if (const SCEV *Scev = SE->getSCEV(const_cast<Instruction *>(I)))
53 if (!isa<SCEVCouldNotCompute>(Scev))
54 if (!hasScalarDepsInsideRegion(Scev, R))
55 return true;
56
57 return false;
58 }
59
60 Loop *L = LI->getLoopFor(I->getParent());
Tobias Grossere8df5bd2013-04-17 07:20:36 +000061 return L && I == L->getCanonicalInductionVariable() && R->contains(L);
Tobias Grosserecfe21b2013-03-20 18:03:18 +000062}
63
Hongbin Zheng3b11a162012-04-25 13:16:49 +000064// Helper class to generate memory location.
65namespace {
66class IslGenerator {
67public:
Tobias Grosser5103ba72014-03-04 14:58:49 +000068 IslGenerator(PollyIRBuilder &Builder, std::vector<Value *> &IVS)
Tobias Grosser7242ad92013-02-22 08:07:06 +000069 : Builder(Builder), IVS(IVS) {}
Tobias Grosseredab1352013-06-21 06:41:31 +000070 Value *generateIslVal(__isl_take isl_val *Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000071 Value *generateIslAff(__isl_take isl_aff *Aff);
72 Value *generateIslPwAff(__isl_take isl_pw_aff *PwAff);
73
74private:
75 typedef struct {
76 Value *Result;
77 class IslGenerator *Generator;
78 } IslGenInfo;
79
Tobias Grosser5103ba72014-03-04 14:58:49 +000080 PollyIRBuilder &Builder;
Hongbin Zheng3b11a162012-04-25 13:16:49 +000081 std::vector<Value *> &IVS;
Tobias Grosser1bb59b02012-12-29 23:47:38 +000082 static int mergeIslAffValues(__isl_take isl_set *Set, __isl_take isl_aff *Aff,
83 void *User);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000084};
85}
86
Tobias Grosseredab1352013-06-21 06:41:31 +000087Value *IslGenerator::generateIslVal(__isl_take isl_val *Val) {
88 Value *IntValue = Builder.getInt(APIntFromVal(Val));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000089 return IntValue;
90}
91
92Value *IslGenerator::generateIslAff(__isl_take isl_aff *Aff) {
93 Value *Result;
94 Value *ConstValue;
Tobias Grosseredab1352013-06-21 06:41:31 +000095 isl_val *Val;
Hongbin Zheng3b11a162012-04-25 13:16:49 +000096
Tobias Grosseredab1352013-06-21 06:41:31 +000097 Val = isl_aff_get_constant_val(Aff);
98 ConstValue = generateIslVal(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000099 Type *Ty = Builder.getInt64Ty();
100
101 // FIXME: We should give the constant and coefficients the right type. Here
102 // we force it into i64.
103 Result = Builder.CreateSExtOrBitCast(ConstValue, Ty);
104
105 unsigned int NbInputDims = isl_aff_dim(Aff, isl_dim_in);
106
Tobias Grosser7242ad92013-02-22 08:07:06 +0000107 assert((IVS.size() == NbInputDims) &&
108 "The Dimension of Induction Variables must match the dimension of the "
109 "affine space.");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000110
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000111 for (unsigned int i = 0; i < NbInputDims; ++i) {
112 Value *CoefficientValue;
Tobias Grosseredab1352013-06-21 06:41:31 +0000113 Val = isl_aff_get_coefficient_val(Aff, isl_dim_in, i);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000114
Tobias Grosseredab1352013-06-21 06:41:31 +0000115 if (isl_val_is_zero(Val)) {
116 isl_val_free(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000117 continue;
Tobias Grosseredab1352013-06-21 06:41:31 +0000118 }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000119
Tobias Grosseredab1352013-06-21 06:41:31 +0000120 CoefficientValue = generateIslVal(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000121 CoefficientValue = Builder.CreateIntCast(CoefficientValue, Ty, true);
122 Value *IV = Builder.CreateIntCast(IVS[i], Ty, true);
123 Value *PAdd = Builder.CreateMul(CoefficientValue, IV, "p_mul_coeff");
124 Result = Builder.CreateAdd(Result, PAdd, "p_sum_coeff");
125 }
126
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000127 isl_aff_free(Aff);
128
129 return Result;
130}
131
132int IslGenerator::mergeIslAffValues(__isl_take isl_set *Set,
133 __isl_take isl_aff *Aff, void *User) {
134 IslGenInfo *GenInfo = (IslGenInfo *)User;
135
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000136 assert((GenInfo->Result == nullptr) &&
Tobias Grosser7242ad92013-02-22 08:07:06 +0000137 "Result is already set. Currently only single isl_aff is supported");
138 assert(isl_set_plain_is_universe(Set) &&
139 "Code generation failed because the set is not universe");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000140
141 GenInfo->Result = GenInfo->Generator->generateIslAff(Aff);
142
143 isl_set_free(Set);
144 return 0;
145}
146
147Value *IslGenerator::generateIslPwAff(__isl_take isl_pw_aff *PwAff) {
148 IslGenInfo User;
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000149 User.Result = nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000150 User.Generator = this;
151 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &User);
152 assert(User.Result && "Code generation for isl_pw_aff failed");
153
154 isl_pw_aff_free(PwAff);
155 return User.Result;
156}
157
Tobias Grosser5103ba72014-03-04 14:58:49 +0000158BlockGenerator::BlockGenerator(PollyIRBuilder &B, ScopStmt &Stmt, Pass *P)
Tobias Grosser7242ad92013-02-22 08:07:06 +0000159 : Builder(B), Statement(Stmt), P(P), SE(P->getAnalysis<ScalarEvolution>()) {
160}
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000161
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000162Value *BlockGenerator::lookupAvailableValue(const Value *Old, ValueMapT &BBMap,
163 ValueMapT &GlobalMap) const {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000164 // We assume constants never change.
165 // This avoids map lookups for many calls to this function.
166 if (isa<Constant>(Old))
Tobias Grosserc14582f2013-02-05 18:01:29 +0000167 return const_cast<Value *>(Old);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000168
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000169 if (Value *New = GlobalMap.lookup(Old)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000170 if (Old->getType()->getScalarSizeInBits() <
Tobias Grosserd7e58642013-04-10 06:55:45 +0000171 New->getType()->getScalarSizeInBits())
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000172 New = Builder.CreateTruncOrBitCast(New, Old->getType());
173
174 return New;
175 }
176
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000177 // Or it is probably a scop-constant value defined as global, function
178 // parameter or an instruction not within the scop.
179 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
180 return const_cast<Value *>(Old);
181
182 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
183 if (!Statement.getParent()->getRegion().contains(Inst->getParent()))
184 return const_cast<Value *>(Old);
185
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000186 if (Value *New = BBMap.lookup(Old))
187 return New;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000188
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000189 return nullptr;
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000190}
191
192Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
193 ValueMapT &GlobalMap, LoopToScevMapT &LTS,
194 Loop *L) {
195 if (Value *New = lookupAvailableValue(Old, BBMap, GlobalMap))
196 return New;
197
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000198 if (SCEVCodegen && SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000199 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000200 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000201 const SCEV *NewScev = apply(Scev, LTS, SE);
202 ValueToValueMap VTV;
203 VTV.insert(BBMap.begin(), BBMap.end());
204 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Sebastian Pop47d4ee32013-02-15 21:26:53 +0000205 NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000206 SCEVExpander Expander(SE, "polly");
207 Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
208 Builder.GetInsertPoint());
209
210 BBMap[Old] = Expanded;
211 return Expanded;
212 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000213 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000214
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000215 // Now the scalar dependence is neither available nor SCEVCodegenable, this
216 // should never happen in the current code generator.
217 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000218 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000219}
220
221void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000222 ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000223 // We do not generate debug intrinsics as we did not investigate how to
224 // copy them correctly. At the current state, they just crash the code
225 // generation as the meta-data operands are not correctly copied.
226 if (isa<DbgInfoIntrinsic>(Inst))
227 return;
228
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000229 Instruction *NewInst = Inst->clone();
230
231 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000232 for (Value *OldOperand : Inst->operands()) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000233 Value *NewOperand =
234 getNewValue(OldOperand, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000235
236 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000237 assert(!isa<StoreInst>(NewInst) &&
238 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000239 delete NewInst;
240 return;
241 }
242
243 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
244 }
245
246 Builder.Insert(NewInst);
247 BBMap[Inst] = NewInst;
248
249 if (!NewInst->getType()->isVoidTy())
250 NewInst->setName("p_" + Inst->getName());
251}
252
Tobias Grosserc14582f2013-02-05 18:01:29 +0000253std::vector<Value *> BlockGenerator::getMemoryAccessIndex(
254 __isl_keep isl_map *AccessRelation, Value *BaseAddress, ValueMapT &BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000255 ValueMapT &GlobalMap, LoopToScevMapT &LTS, Loop *L) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000256 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1) &&
257 "Only single dimensional access functions supported");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000258
259 std::vector<Value *> IVS;
260 for (unsigned i = 0; i < Statement.getNumIterators(); ++i) {
261 const Value *OriginalIV = Statement.getInductionVariableForDimension(i);
Tobias Grosser369430f2013-03-22 23:42:53 +0000262 Value *NewIV = getNewValue(OriginalIV, BBMap, GlobalMap, LTS, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000263 IVS.push_back(NewIV);
264 }
265
266 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
267 IslGenerator IslGen(Builder, IVS);
268 Value *OffsetValue = IslGen.generateIslPwAff(PwAff);
269
270 Type *Ty = Builder.getInt64Ty();
271 OffsetValue = Builder.CreateIntCast(OffsetValue, Ty, true);
272
Tobias Grosserc14582f2013-02-05 18:01:29 +0000273 std::vector<Value *> IndexArray;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000274 Value *NullValue = Constant::getNullValue(Ty);
275 IndexArray.push_back(NullValue);
276 IndexArray.push_back(OffsetValue);
277 return IndexArray;
278}
279
280Value *BlockGenerator::getNewAccessOperand(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000281 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, ValueMapT &BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000282 ValueMapT &GlobalMap, LoopToScevMapT &LTS, Loop *L) {
Tobias Grosser7242ad92013-02-22 08:07:06 +0000283 std::vector<Value *> IndexArray = getMemoryAccessIndex(
Tobias Grosser369430f2013-03-22 23:42:53 +0000284 NewAccessRelation, BaseAddress, BBMap, GlobalMap, LTS, L);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000285 Value *NewOperand =
286 Builder.CreateGEP(BaseAddress, IndexArray, "p_newarrayidx_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000287 return NewOperand;
288}
289
Tobias Grossere602a072013-05-07 07:30:56 +0000290Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
291 const Value *Pointer,
292 ValueMapT &BBMap,
293 ValueMapT &GlobalMap,
294 LoopToScevMapT &LTS) {
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000295 const MemoryAccess &Access = Statement.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000296 isl_map *CurrentAccessRelation = Access.getAccessRelation();
297 isl_map *NewAccessRelation = Access.getNewAccessRelation();
298
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000299 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation) &&
300 "Current and new access function use different spaces");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000301
302 Value *NewPointer;
303
304 if (!NewAccessRelation) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000305 NewPointer =
306 getNewValue(Pointer, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000307 } else {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000308 Value *BaseAddress = const_cast<Value *>(Access.getBaseAddr());
Tobias Grosser7242ad92013-02-22 08:07:06 +0000309 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000310 GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000311 }
312
313 isl_map_free(CurrentAccessRelation);
314 isl_map_free(NewAccessRelation);
315 return NewPointer;
316}
317
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000318Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000319 return P->getAnalysis<LoopInfo>().getLoopFor(Inst->getParent());
320}
321
Tobias Grossere602a072013-05-07 07:30:56 +0000322Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
323 ValueMapT &BBMap,
324 ValueMapT &GlobalMap,
325 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000326 const Value *Pointer = Load->getPointerOperand();
327 const Instruction *Inst = dyn_cast<Instruction>(Load);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000328 Value *NewPointer =
329 generateLocationAccessed(Inst, Pointer, BBMap, GlobalMap, LTS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000330 Value *ScalarLoad =
331 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000332 return ScalarLoad;
333}
334
Tobias Grossere602a072013-05-07 07:30:56 +0000335Value *BlockGenerator::generateScalarStore(const StoreInst *Store,
336 ValueMapT &BBMap,
337 ValueMapT &GlobalMap,
338 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000339 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000340 Value *NewPointer =
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000341 generateLocationAccessed(Store, Pointer, BBMap, GlobalMap, LTS);
Tobias Grosser369430f2013-03-22 23:42:53 +0000342 Value *ValueOperand = getNewValue(Store->getValueOperand(), BBMap, GlobalMap,
343 LTS, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000344
345 return Builder.CreateStore(ValueOperand, NewPointer);
346}
347
Tobias Grossere602a072013-05-07 07:30:56 +0000348void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
349 ValueMapT &GlobalMap,
350 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000351 // Terminator instructions control the control flow. They are explicitly
352 // expressed in the clast and do not need to be copied.
353 if (Inst->isTerminator())
354 return;
355
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000356 if (canSynthesize(Inst, &P->getAnalysis<LoopInfo>(), &SE,
357 &Statement.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000358 return;
359
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000360 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Sebastian Pop753d43f2013-05-24 17:16:02 +0000361 Value *NewLoad = generateScalarLoad(Load, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000362 // Compute NewLoad before its insertion in BBMap to make the insertion
363 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000364 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000365 return;
366 }
367
368 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Sebastian Pop753d43f2013-05-24 17:16:02 +0000369 Value *NewStore = generateScalarStore(Store, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000370 // Compute NewStore before its insertion in BBMap to make the insertion
371 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000372 BBMap[Store] = NewStore;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000373 return;
374 }
375
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000376 copyInstScalar(Inst, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000377}
378
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000379void BlockGenerator::copyBB(ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000380 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000381 BasicBlock *CopyBB =
382 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000383 CopyBB->setName("polly.stmt." + BB->getName());
384 Builder.SetInsertPoint(CopyBB->begin());
385
386 ValueMapT BBMap;
387
Tobias Grosser91f5b262014-06-04 08:06:40 +0000388 for (Instruction &Inst : *BB)
389 copyInstruction(&Inst, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000390}
391
Tobias Grosser5103ba72014-03-04 14:58:49 +0000392VectorBlockGenerator::VectorBlockGenerator(PollyIRBuilder &B,
Tobias Grossere602a072013-05-07 07:30:56 +0000393 VectorValueMapT &GlobalMaps,
394 std::vector<LoopToScevMapT> &VLTS,
395 ScopStmt &Stmt,
396 __isl_keep isl_map *Schedule,
397 Pass *P)
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000398 : BlockGenerator(B, Stmt, P), GlobalMaps(GlobalMaps), VLTS(VLTS),
399 Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000400 assert(GlobalMaps.size() > 1 && "Only one vector lane found");
401 assert(Schedule && "No statement domain provided");
402}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000403
Tobias Grossere602a072013-05-07 07:30:56 +0000404Value *VectorBlockGenerator::getVectorValue(const Value *Old,
405 ValueMapT &VectorMap,
406 VectorValueMapT &ScalarMaps,
407 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000408 if (Value *NewValue = VectorMap.lookup(Old))
409 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000410
411 int Width = getVectorWidth();
412
413 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
414
415 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000416 Vector = Builder.CreateInsertElement(
Tobias Grosser7242ad92013-02-22 08:07:06 +0000417 Vector,
Tobias Grosser369430f2013-03-22 23:42:53 +0000418 getNewValue(Old, ScalarMaps[Lane], GlobalMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000419 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000420
421 VectorMap[Old] = Vector;
422
423 return Vector;
424}
425
426Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
427 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
428 assert(PointerTy && "PointerType expected");
429
430 Type *ScalarType = PointerTy->getElementType();
431 VectorType *VectorType = VectorType::get(ScalarType, Width);
432
433 return PointerType::getUnqual(VectorType);
434}
435
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000436Value *
437VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
438 VectorValueMapT &ScalarMaps,
439 bool NegativeStride = false) {
440 unsigned VectorWidth = getVectorWidth();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000441 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000442 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
443 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
444
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000445 Value *NewPointer = nullptr;
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000446 NewPointer = getNewValue(Pointer, ScalarMaps[Offset], GlobalMaps[Offset],
447 VLTS[Offset], getLoopForInst(Load));
Tobias Grosserc14582f2013-02-05 18:01:29 +0000448 Value *VectorPtr =
449 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
450 LoadInst *VecLoad =
451 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000452 if (!Aligned)
453 VecLoad->setAlignment(8);
454
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000455 if (NegativeStride) {
456 SmallVector<Constant *, 16> Indices;
457 for (int i = VectorWidth - 1; i >= 0; i--)
458 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
459 Constant *SV = llvm::ConstantVector::get(Indices);
460 Value *RevVecLoad = Builder.CreateShuffleVector(
461 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
462 return RevVecLoad;
463 }
464
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000465 return VecLoad;
466}
467
468Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
469 ValueMapT &BBMap) {
470 const Value *Pointer = Load->getPointerOperand();
471 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosser369430f2013-03-22 23:42:53 +0000472 Value *NewPointer =
473 getNewValue(Pointer, BBMap, GlobalMaps[0], VLTS[0], getLoopForInst(Load));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000474 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
475 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000476 LoadInst *ScalarLoad =
477 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000478
479 if (!Aligned)
480 ScalarLoad->setAlignment(8);
481
Tobias Grosserc14582f2013-02-05 18:01:29 +0000482 Constant *SplatVector = Constant::getNullValue(
483 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000484
Tobias Grosserc14582f2013-02-05 18:01:29 +0000485 Value *VectorLoad = Builder.CreateShuffleVector(
486 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000487 return VectorLoad;
488}
489
Tobias Grossere602a072013-05-07 07:30:56 +0000490Value *
491VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
492 VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000493 int VectorWidth = getVectorWidth();
494 const Value *Pointer = Load->getPointerOperand();
495 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000496 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000497
498 Value *Vector = UndefValue::get(VectorType);
499
500 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000501 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i],
502 VLTS[i], getLoopForInst(Load));
Tobias Grosserc14582f2013-02-05 18:01:29 +0000503 Value *ScalarLoad =
504 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
505 Vector = Builder.CreateInsertElement(
506 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000507 }
508
509 return Vector;
510}
511
Tobias Grossere602a072013-05-07 07:30:56 +0000512void VectorBlockGenerator::generateLoad(const LoadInst *Load,
513 ValueMapT &VectorMap,
514 VectorValueMapT &ScalarMaps) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000515 if (PollyVectorizerChoice >= VECTORIZER_FIRST_NEED_GROUPED_UNROLL ||
516 !VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000517 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000518 ScalarMaps[i][Load] =
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000519 generateScalarLoad(Load, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000520 return;
521 }
522
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000523 const MemoryAccess &Access = Statement.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000524
Tobias Grosser95493982014-04-18 09:46:35 +0000525 // Make sure we have scalar values available to access the pointer to
526 // the data location.
527 extractScalarValues(Load, VectorMap, ScalarMaps);
528
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000529 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000530 if (Access.isStrideZero(isl_map_copy(Schedule)))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000531 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Sebastian Popa00a0292012-12-18 07:46:06 +0000532 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000533 NewLoad = generateStrideOneLoad(Load, ScalarMaps);
534 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
535 NewLoad = generateStrideOneLoad(Load, ScalarMaps, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000536 else
537 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
538
539 VectorMap[Load] = NewLoad;
540}
541
542void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
543 ValueMapT &VectorMap,
544 VectorValueMapT &ScalarMaps) {
545 int VectorWidth = getVectorWidth();
Tobias Grosser369430f2013-03-22 23:42:53 +0000546 Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap, ScalarMaps,
547 getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000548
549 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
550
551 const CastInst *Cast = dyn_cast<CastInst>(Inst);
552 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
553 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
554}
555
556void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
557 ValueMapT &VectorMap,
558 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000559 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000560 Value *OpZero = Inst->getOperand(0);
561 Value *OpOne = Inst->getOperand(1);
562
563 Value *NewOpZero, *NewOpOne;
Tobias Grosser369430f2013-03-22 23:42:53 +0000564 NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps, L);
565 NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000566
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000567 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000568 Inst->getName() + "p_vec");
569 VectorMap[Inst] = NewInst;
570}
571
Tobias Grossere602a072013-05-07 07:30:56 +0000572void VectorBlockGenerator::copyStore(const StoreInst *Store,
573 ValueMapT &VectorMap,
574 VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000575 int VectorWidth = getVectorWidth();
576
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000577 const MemoryAccess &Access = Statement.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000578
579 const Value *Pointer = Store->getPointerOperand();
Tobias Grosser369430f2013-03-22 23:42:53 +0000580 Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
581 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000582
Tobias Grosser50fd7012014-04-17 23:13:49 +0000583 // Make sure we have scalar values available to access the pointer to
584 // the data location.
585 extractScalarValues(Store, VectorMap, ScalarMaps);
586
Sebastian Popa00a0292012-12-18 07:46:06 +0000587 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000588 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
Tobias Grosser369430f2013-03-22 23:42:53 +0000589 Value *NewPointer = getNewValue(Pointer, ScalarMaps[0], GlobalMaps[0],
590 VLTS[0], getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000591
Tobias Grosserc14582f2013-02-05 18:01:29 +0000592 Value *VectorPtr =
593 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000594 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
595
596 if (!Aligned)
597 Store->setAlignment(8);
598 } else {
599 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000600 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosser369430f2013-03-22 23:42:53 +0000601 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i],
602 VLTS[i], getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000603 Builder.CreateStore(Scalar, NewPointer);
604 }
605 }
606}
607
608bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
609 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000610 for (Value *Operand : Inst->operands())
611 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000612 return true;
613 return false;
614}
615
616bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
617 ValueMapT &VectorMap,
618 VectorValueMapT &ScalarMaps) {
619 bool HasVectorOperand = false;
620 int VectorWidth = getVectorWidth();
621
Tobias Grosser91f5b262014-06-04 08:06:40 +0000622 for (Value *Operand : Inst->operands()) {
623 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000624
625 if (VecOp == VectorMap.end())
626 continue;
627
628 HasVectorOperand = true;
629 Value *NewVector = VecOp->second;
630
631 for (int i = 0; i < VectorWidth; ++i) {
632 ValueMapT &SM = ScalarMaps[i];
633
634 // If there is one scalar extracted, all scalar elements should have
635 // already been extracted by the code here. So no need to check for the
636 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000637 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000638 break;
639
Tobias Grosser91f5b262014-06-04 08:06:40 +0000640 SM[Operand] =
641 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000642 }
643 }
644
645 return HasVectorOperand;
646}
647
648void VectorBlockGenerator::copyInstScalarized(const Instruction *Inst,
649 ValueMapT &VectorMap,
650 VectorValueMapT &ScalarMaps) {
651 bool HasVectorOperand;
652 int VectorWidth = getVectorWidth();
653
654 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
655
656 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000657 copyInstScalar(Inst, ScalarMaps[VectorLane], GlobalMaps[VectorLane],
658 VLTS[VectorLane]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000659
660 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
661 return;
662
663 // Make the result available as vector value.
664 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
665 Value *Vector = UndefValue::get(VectorType);
666
667 for (int i = 0; i < VectorWidth; i++)
668 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
669 Builder.getInt32(i));
670
671 VectorMap[Inst] = Vector;
672}
673
Tobias Grosserc14582f2013-02-05 18:01:29 +0000674int VectorBlockGenerator::getVectorWidth() { return GlobalMaps.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000675
676void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
677 ValueMapT &VectorMap,
678 VectorValueMapT &ScalarMaps) {
679 // Terminator instructions control the control flow. They are explicitly
680 // expressed in the clast and do not need to be copied.
681 if (Inst->isTerminator())
682 return;
683
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000684 if (canSynthesize(Inst, &P->getAnalysis<LoopInfo>(), &SE,
685 &Statement.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000686 return;
687
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000688 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
689 generateLoad(Load, VectorMap, ScalarMaps);
690 return;
691 }
692
693 if (hasVectorOperands(Inst, VectorMap)) {
694 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
695 copyStore(Store, VectorMap, ScalarMaps);
696 return;
697 }
698
699 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
700 copyUnaryInst(Unary, VectorMap, ScalarMaps);
701 return;
702 }
703
704 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
705 copyBinaryInst(Binary, VectorMap, ScalarMaps);
706 return;
707 }
708
709 // Falltrough: We generate scalar instructions, if we don't know how to
710 // generate vector code.
711 }
712
713 copyInstScalarized(Inst, VectorMap, ScalarMaps);
714}
715
716void VectorBlockGenerator::copyBB() {
717 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000718 BasicBlock *CopyBB =
719 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000720 CopyBB->setName("polly.stmt." + BB->getName());
721 Builder.SetInsertPoint(CopyBB->begin());
722
723 // Create two maps that store the mapping from the original instructions of
724 // the old basic block to their copies in the new basic block. Those maps
725 // are basic block local.
726 //
727 // As vector code generation is supported there is one map for scalar values
728 // and one for vector values.
729 //
730 // In case we just do scalar code generation, the vectorMap is not used and
731 // the scalarMap has just one dimension, which contains the mapping.
732 //
733 // In case vector code generation is done, an instruction may either appear
734 // in the vector map once (as it is calculating >vectorwidth< values at a
735 // time. Or (if the values are calculated using scalar operations), it
736 // appears once in every dimension of the scalarMap.
737 VectorValueMapT ScalarBlockMap(getVectorWidth());
738 ValueMapT VectorBlockMap;
739
Tobias Grosser91f5b262014-06-04 08:06:40 +0000740 for (Instruction &Inst : *BB)
741 copyInstruction(&Inst, VectorBlockMap, ScalarBlockMap);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000742}