1609089f2SHongbin Zheng //===------ LoopGenerators.cpp -  IR helper to create loops ---------------===//
2609089f2SHongbin Zheng //
3609089f2SHongbin Zheng //                     The LLVM Compiler Infrastructure
4609089f2SHongbin Zheng //
5609089f2SHongbin Zheng // This file is distributed under the University of Illinois Open Source
6609089f2SHongbin Zheng // License. See LICENSE.TXT for details.
7609089f2SHongbin Zheng //
8609089f2SHongbin Zheng //===----------------------------------------------------------------------===//
9609089f2SHongbin Zheng //
10609089f2SHongbin Zheng // This file contains functions to create scalar and OpenMP parallel loops
11609089f2SHongbin Zheng // as LLVM-IR.
12609089f2SHongbin Zheng //
13609089f2SHongbin Zheng //===----------------------------------------------------------------------===//
14609089f2SHongbin Zheng 
15609089f2SHongbin Zheng #include "polly/ScopDetection.h"
168a846610SHongbin Zheng #include "polly/CodeGen/LoopGenerators.h"
17609089f2SHongbin Zheng 
18535d52c7SChandler Carruth #include "llvm/IR/Module.h"
19609089f2SHongbin Zheng #include "llvm/Analysis/Dominators.h"
20535d52c7SChandler Carruth #include "llvm/IR/DataLayout.h"
21609089f2SHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22609089f2SHongbin Zheng 
23609089f2SHongbin Zheng using namespace llvm;
244ac4e155SHongbin Zheng using namespace polly;
25609089f2SHongbin Zheng 
264ac4e155SHongbin Zheng Value *polly::createLoop(Value *LB, Value *UB, Value *Stride,
271bb59b0dSTobias Grosser                          IRBuilder<> &Builder, Pass *P, BasicBlock *&AfterBlock,
28c967d8e6STobias Grosser                          ICmpInst::Predicate Predicate) {
29609089f2SHongbin Zheng   DominatorTree &DT = P->getAnalysis<DominatorTree>();
304ac4e155SHongbin Zheng   Function *F = Builder.GetInsertBlock()->getParent();
31609089f2SHongbin Zheng   LLVMContext &Context = F->getContext();
32609089f2SHongbin Zheng 
334ac4e155SHongbin Zheng   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
34609089f2SHongbin Zheng   BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
35609089f2SHongbin Zheng   BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
364ac4e155SHongbin Zheng   BasicBlock *AfterBB = SplitBlock(PreheaderBB, Builder.GetInsertPoint()++, P);
37609089f2SHongbin Zheng   AfterBB->setName("polly.loop_after");
38609089f2SHongbin Zheng 
39609089f2SHongbin Zheng   PreheaderBB->getTerminator()->setSuccessor(0, HeaderBB);
40609089f2SHongbin Zheng   DT.addNewBlock(HeaderBB, PreheaderBB);
41609089f2SHongbin Zheng 
424ac4e155SHongbin Zheng   Builder.SetInsertPoint(HeaderBB);
43609089f2SHongbin Zheng 
44609089f2SHongbin Zheng   // Use the type of upper and lower bound.
45ae2d83ecSTobias Grosser   assert(LB->getType() == UB->getType() &&
46ae2d83ecSTobias Grosser          "Different types for upper and lower bound.");
47609089f2SHongbin Zheng 
48609089f2SHongbin Zheng   IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
49609089f2SHongbin Zheng   assert(LoopIVType && "UB is not integer?");
50609089f2SHongbin Zheng 
51609089f2SHongbin Zheng   // IV
524ac4e155SHongbin Zheng   PHINode *IV = Builder.CreatePHI(LoopIVType, 2, "polly.loopiv");
53609089f2SHongbin Zheng   IV->addIncoming(LB, PreheaderBB);
54609089f2SHongbin Zheng 
554ac4e155SHongbin Zheng   Stride = Builder.CreateZExtOrBitCast(Stride, LoopIVType);
56400a4ac6STobias Grosser   Value *IncrementedIV = Builder.CreateNSWAdd(IV, Stride, "polly.next_loopiv");
57609089f2SHongbin Zheng 
58609089f2SHongbin Zheng   // Exit condition.
59609089f2SHongbin Zheng   Value *CMP;
60c967d8e6STobias Grosser   CMP = Builder.CreateICmp(Predicate, IV, UB);
61609089f2SHongbin Zheng 
624ac4e155SHongbin Zheng   Builder.CreateCondBr(CMP, BodyBB, AfterBB);
63609089f2SHongbin Zheng   DT.addNewBlock(BodyBB, HeaderBB);
64609089f2SHongbin Zheng 
654ac4e155SHongbin Zheng   Builder.SetInsertPoint(BodyBB);
664ac4e155SHongbin Zheng   Builder.CreateBr(HeaderBB);
67609089f2SHongbin Zheng   IV->addIncoming(IncrementedIV, BodyBB);
68609089f2SHongbin Zheng   DT.changeImmediateDominator(AfterBB, HeaderBB);
69609089f2SHongbin Zheng 
704ac4e155SHongbin Zheng   Builder.SetInsertPoint(BodyBB->begin());
714ac4e155SHongbin Zheng   AfterBlock = AfterBB;
72609089f2SHongbin Zheng 
73609089f2SHongbin Zheng   return IV;
74609089f2SHongbin Zheng }
75609089f2SHongbin Zheng 
76c14582f2STobias Grosser void OMPGenerator::createCallParallelLoopStart(
77c14582f2STobias Grosser     Value *SubFunction, Value *SubfunctionParam, Value *NumberOfThreads,
78c14582f2STobias Grosser     Value *LowerBound, Value *UpperBound, Value *Stride) {
79609089f2SHongbin Zheng   Module *M = getModule();
80609089f2SHongbin Zheng   const char *Name = "GOMP_parallel_loop_runtime_start";
81609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
82609089f2SHongbin Zheng 
83609089f2SHongbin Zheng   // If F is not available, declare it.
84609089f2SHongbin Zheng   if (!F) {
85609089f2SHongbin Zheng     Type *LongTy = getIntPtrTy();
86609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
87609089f2SHongbin Zheng 
88c14582f2STobias Grosser     Type *Params[] = { PointerType::getUnqual(FunctionType::get(
89c14582f2STobias Grosser                            Builder.getVoidTy(), Builder.getInt8PtrTy(), false)),
90c14582f2STobias Grosser                        Builder.getInt8PtrTy(), Builder.getInt32Ty(), LongTy,
91c14582f2STobias Grosser                        LongTy, LongTy, };
92609089f2SHongbin Zheng 
93609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
94609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
95609089f2SHongbin Zheng   }
96609089f2SHongbin Zheng 
97c14582f2STobias Grosser   Value *Args[] = { SubFunction, SubfunctionParam, NumberOfThreads, LowerBound,
98c14582f2STobias Grosser                     UpperBound, Stride, };
99609089f2SHongbin Zheng 
100609089f2SHongbin Zheng   Builder.CreateCall(F, Args);
101609089f2SHongbin Zheng }
102609089f2SHongbin Zheng 
103c14582f2STobias Grosser Value *
104c14582f2STobias Grosser OMPGenerator::createCallLoopNext(Value *LowerBoundPtr, Value *UpperBoundPtr) {
105609089f2SHongbin Zheng   Module *M = getModule();
106609089f2SHongbin Zheng   const char *Name = "GOMP_loop_runtime_next";
107609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
108609089f2SHongbin Zheng 
109609089f2SHongbin Zheng   // If F is not available, declare it.
110609089f2SHongbin Zheng   if (!F) {
111609089f2SHongbin Zheng     Type *LongPtrTy = PointerType::getUnqual(getIntPtrTy());
112609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
113609089f2SHongbin Zheng 
114c14582f2STobias Grosser     Type *Params[] = { LongPtrTy, LongPtrTy, };
115609089f2SHongbin Zheng 
116609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
117609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
118609089f2SHongbin Zheng   }
119609089f2SHongbin Zheng 
120c14582f2STobias Grosser   Value *Args[] = { LowerBoundPtr, UpperBoundPtr, };
121609089f2SHongbin Zheng 
122609089f2SHongbin Zheng   Value *Return = Builder.CreateCall(F, Args);
123c14582f2STobias Grosser   Return = Builder.CreateICmpNE(
124c14582f2STobias Grosser       Return, Builder.CreateZExt(Builder.getFalse(), Return->getType()));
125609089f2SHongbin Zheng   return Return;
126609089f2SHongbin Zheng }
127609089f2SHongbin Zheng 
128609089f2SHongbin Zheng void OMPGenerator::createCallParallelEnd() {
129609089f2SHongbin Zheng   const char *Name = "GOMP_parallel_end";
130609089f2SHongbin Zheng   Module *M = getModule();
131609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
132609089f2SHongbin Zheng 
133609089f2SHongbin Zheng   // If F is not available, declare it.
134609089f2SHongbin Zheng   if (!F) {
135609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
136609089f2SHongbin Zheng 
137609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
138609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
139609089f2SHongbin Zheng   }
140609089f2SHongbin Zheng 
141609089f2SHongbin Zheng   Builder.CreateCall(F);
142609089f2SHongbin Zheng }
143609089f2SHongbin Zheng 
144609089f2SHongbin Zheng void OMPGenerator::createCallLoopEndNowait() {
145609089f2SHongbin Zheng   const char *Name = "GOMP_loop_end_nowait";
146609089f2SHongbin Zheng   Module *M = getModule();
147609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
148609089f2SHongbin Zheng 
149609089f2SHongbin Zheng   // If F is not available, declare it.
150609089f2SHongbin Zheng   if (!F) {
151609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
152609089f2SHongbin Zheng 
153609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
154609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
155609089f2SHongbin Zheng   }
156609089f2SHongbin Zheng 
157609089f2SHongbin Zheng   Builder.CreateCall(F);
158609089f2SHongbin Zheng }
159609089f2SHongbin Zheng 
160609089f2SHongbin Zheng IntegerType *OMPGenerator::getIntPtrTy() {
1615d01691dSTobias Grosser   return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
162609089f2SHongbin Zheng }
163609089f2SHongbin Zheng 
164609089f2SHongbin Zheng Module *OMPGenerator::getModule() {
165609089f2SHongbin Zheng   return Builder.GetInsertBlock()->getParent()->getParent();
166609089f2SHongbin Zheng }
167609089f2SHongbin Zheng 
168609089f2SHongbin Zheng Function *OMPGenerator::createSubfunctionDefinition() {
169609089f2SHongbin Zheng   Module *M = getModule();
170609089f2SHongbin Zheng   Function *F = Builder.GetInsertBlock()->getParent();
171609089f2SHongbin Zheng   std::vector<Type *> Arguments(1, Builder.getInt8PtrTy());
172609089f2SHongbin Zheng   FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
173609089f2SHongbin Zheng   Function *FN = Function::Create(FT, Function::InternalLinkage,
174609089f2SHongbin Zheng                                   F->getName() + ".omp_subfn", M);
175609089f2SHongbin Zheng   // Do not run any polly pass on the new function.
176609089f2SHongbin Zheng   P->getAnalysis<polly::ScopDetection>().markFunctionAsInvalid(FN);
177609089f2SHongbin Zheng 
178609089f2SHongbin Zheng   Function::arg_iterator AI = FN->arg_begin();
179609089f2SHongbin Zheng   AI->setName("omp.userContext");
180609089f2SHongbin Zheng 
181609089f2SHongbin Zheng   return FN;
182609089f2SHongbin Zheng }
183609089f2SHongbin Zheng 
184609089f2SHongbin Zheng Value *OMPGenerator::loadValuesIntoStruct(SetVector<Value *> &Values) {
185609089f2SHongbin Zheng   std::vector<Type *> Members;
186609089f2SHongbin Zheng 
187609089f2SHongbin Zheng   for (unsigned i = 0; i < Values.size(); i++)
188609089f2SHongbin Zheng     Members.push_back(Values[i]->getType());
189609089f2SHongbin Zheng 
190609089f2SHongbin Zheng   StructType *Ty = StructType::get(Builder.getContext(), Members);
191609089f2SHongbin Zheng   Value *Struct = Builder.CreateAlloca(Ty, 0, "omp.userContext");
192609089f2SHongbin Zheng 
193609089f2SHongbin Zheng   for (unsigned i = 0; i < Values.size(); i++) {
194609089f2SHongbin Zheng     Value *Address = Builder.CreateStructGEP(Struct, i);
195609089f2SHongbin Zheng     Builder.CreateStore(Values[i], Address);
196609089f2SHongbin Zheng   }
197609089f2SHongbin Zheng 
198609089f2SHongbin Zheng   return Struct;
199609089f2SHongbin Zheng }
200609089f2SHongbin Zheng 
201c14582f2STobias Grosser void OMPGenerator::extractValuesFromStruct(
202c14582f2STobias Grosser     SetVector<Value *> OldValues, Value *Struct, ValueToValueMapTy &Map) {
203609089f2SHongbin Zheng   for (unsigned i = 0; i < OldValues.size(); i++) {
204609089f2SHongbin Zheng     Value *Address = Builder.CreateStructGEP(Struct, i);
205609089f2SHongbin Zheng     Value *NewValue = Builder.CreateLoad(Address);
206*36e6ca01SAndy Gibbs     Map.insert(std::make_pair(OldValues[i], NewValue));
207609089f2SHongbin Zheng   }
208609089f2SHongbin Zheng }
209609089f2SHongbin Zheng 
210c14582f2STobias Grosser Value *OMPGenerator::createSubfunction(
211c14582f2STobias Grosser     Value *Stride, Value *StructData, SetVector<Value *> Data,
212c14582f2STobias Grosser     ValueToValueMapTy &Map, Function **SubFunction) {
213609089f2SHongbin Zheng   Function *FN = createSubfunctionDefinition();
214609089f2SHongbin Zheng 
215609089f2SHongbin Zheng   BasicBlock *PrevBB, *HeaderBB, *ExitBB, *CheckNextBB, *LoadIVBoundsBB,
216609089f2SHongbin Zheng       *AfterBB;
217609089f2SHongbin Zheng   Value *LowerBoundPtr, *UpperBoundPtr, *UserContext, *Ret1, *HasNextSchedule,
218609089f2SHongbin Zheng       *LowerBound, *UpperBound, *IV;
219609089f2SHongbin Zheng   Type *IntPtrTy = getIntPtrTy();
220609089f2SHongbin Zheng   LLVMContext &Context = FN->getContext();
221609089f2SHongbin Zheng 
222609089f2SHongbin Zheng   // Store the previous basic block.
223609089f2SHongbin Zheng   PrevBB = Builder.GetInsertBlock();
224609089f2SHongbin Zheng 
225609089f2SHongbin Zheng   // Create basic blocks.
226609089f2SHongbin Zheng   HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
227609089f2SHongbin Zheng   ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
228609089f2SHongbin Zheng   CheckNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
229609089f2SHongbin Zheng   LoadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds", FN);
230609089f2SHongbin Zheng 
231609089f2SHongbin Zheng   DominatorTree &DT = P->getAnalysis<DominatorTree>();
232609089f2SHongbin Zheng   DT.addNewBlock(HeaderBB, PrevBB);
233609089f2SHongbin Zheng   DT.addNewBlock(ExitBB, HeaderBB);
234609089f2SHongbin Zheng   DT.addNewBlock(CheckNextBB, HeaderBB);
235609089f2SHongbin Zheng   DT.addNewBlock(LoadIVBoundsBB, HeaderBB);
236609089f2SHongbin Zheng 
237609089f2SHongbin Zheng   // Fill up basic block HeaderBB.
238609089f2SHongbin Zheng   Builder.SetInsertPoint(HeaderBB);
239609089f2SHongbin Zheng   LowerBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.lowerBoundPtr");
240609089f2SHongbin Zheng   UpperBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.upperBoundPtr");
241609089f2SHongbin Zheng   UserContext = Builder.CreateBitCast(FN->arg_begin(), StructData->getType(),
242609089f2SHongbin Zheng                                       "omp.userContext");
243609089f2SHongbin Zheng 
244609089f2SHongbin Zheng   extractValuesFromStruct(Data, UserContext, Map);
245609089f2SHongbin Zheng   Builder.CreateBr(CheckNextBB);
246609089f2SHongbin Zheng 
247609089f2SHongbin Zheng   // Add code to check if another set of iterations will be executed.
248609089f2SHongbin Zheng   Builder.SetInsertPoint(CheckNextBB);
249609089f2SHongbin Zheng   Ret1 = createCallLoopNext(LowerBoundPtr, UpperBoundPtr);
250609089f2SHongbin Zheng   HasNextSchedule = Builder.CreateTrunc(Ret1, Builder.getInt1Ty(),
251609089f2SHongbin Zheng                                         "omp.hasNextScheduleBlock");
252609089f2SHongbin Zheng   Builder.CreateCondBr(HasNextSchedule, LoadIVBoundsBB, ExitBB);
253609089f2SHongbin Zheng 
254609089f2SHongbin Zheng   // Add code to to load the iv bounds for this set of iterations.
255609089f2SHongbin Zheng   Builder.SetInsertPoint(LoadIVBoundsBB);
256609089f2SHongbin Zheng   LowerBound = Builder.CreateLoad(LowerBoundPtr, "omp.lowerBound");
257609089f2SHongbin Zheng   UpperBound = Builder.CreateLoad(UpperBoundPtr, "omp.upperBound");
258609089f2SHongbin Zheng 
259609089f2SHongbin Zheng   // Subtract one as the upper bound provided by openmp is a < comparison
260609089f2SHongbin Zheng   // whereas the codegenForSequential function creates a <= comparison.
261609089f2SHongbin Zheng   UpperBound = Builder.CreateSub(UpperBound, ConstantInt::get(IntPtrTy, 1),
262609089f2SHongbin Zheng                                  "omp.upperBoundAdjusted");
263609089f2SHongbin Zheng 
264609089f2SHongbin Zheng   Builder.CreateBr(CheckNextBB);
265609089f2SHongbin Zheng   Builder.SetInsertPoint(--Builder.GetInsertPoint());
266c967d8e6STobias Grosser   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
267c967d8e6STobias Grosser                   ICmpInst::ICMP_SLE);
268609089f2SHongbin Zheng 
269609089f2SHongbin Zheng   BasicBlock::iterator LoopBody = Builder.GetInsertPoint();
270609089f2SHongbin Zheng   Builder.SetInsertPoint(AfterBB->begin());
271609089f2SHongbin Zheng 
272609089f2SHongbin Zheng   // Add code to terminate this openmp subfunction.
273609089f2SHongbin Zheng   Builder.SetInsertPoint(ExitBB);
274609089f2SHongbin Zheng   createCallLoopEndNowait();
275609089f2SHongbin Zheng   Builder.CreateRetVoid();
276609089f2SHongbin Zheng 
277609089f2SHongbin Zheng   Builder.SetInsertPoint(LoopBody);
278609089f2SHongbin Zheng   *SubFunction = FN;
279609089f2SHongbin Zheng 
280609089f2SHongbin Zheng   return IV;
281609089f2SHongbin Zheng }
282609089f2SHongbin Zheng 
283c14582f2STobias Grosser Value *OMPGenerator::createParallelLoop(
284c14582f2STobias Grosser     Value *LowerBound, Value *UpperBound, Value *Stride,
285c14582f2STobias Grosser     SetVector<Value *> &Values, ValueToValueMapTy &Map,
286609089f2SHongbin Zheng     BasicBlock::iterator *LoopBody) {
287609089f2SHongbin Zheng   Value *Struct, *IV, *SubfunctionParam, *NumberOfThreads;
288609089f2SHongbin Zheng   Function *SubFunction;
289609089f2SHongbin Zheng 
290609089f2SHongbin Zheng   Struct = loadValuesIntoStruct(Values);
291609089f2SHongbin Zheng 
292609089f2SHongbin Zheng   BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
293609089f2SHongbin Zheng   IV = createSubfunction(Stride, Struct, Values, Map, &SubFunction);
294609089f2SHongbin Zheng   *LoopBody = Builder.GetInsertPoint();
295609089f2SHongbin Zheng   Builder.SetInsertPoint(PrevInsertPoint);
296609089f2SHongbin Zheng 
297609089f2SHongbin Zheng   // Create call for GOMP_parallel_loop_runtime_start.
298c14582f2STobias Grosser   SubfunctionParam =
299c14582f2STobias Grosser       Builder.CreateBitCast(Struct, Builder.getInt8PtrTy(), "omp_data");
300609089f2SHongbin Zheng 
301609089f2SHongbin Zheng   NumberOfThreads = Builder.getInt32(0);
302609089f2SHongbin Zheng 
303609089f2SHongbin Zheng   // Add one as the upper bound provided by openmp is a < comparison
304609089f2SHongbin Zheng   // whereas the codegenForSequential function creates a <= comparison.
305c14582f2STobias Grosser   UpperBound =
306c14582f2STobias Grosser       Builder.CreateAdd(UpperBound, ConstantInt::get(getIntPtrTy(), 1));
307609089f2SHongbin Zheng 
308609089f2SHongbin Zheng   createCallParallelLoopStart(SubFunction, SubfunctionParam, NumberOfThreads,
309609089f2SHongbin Zheng                               LowerBound, UpperBound, Stride);
310609089f2SHongbin Zheng   Builder.CreateCall(SubFunction, SubfunctionParam);
311609089f2SHongbin Zheng   createCallParallelEnd();
312609089f2SHongbin Zheng 
313609089f2SHongbin Zheng   return IV;
314609089f2SHongbin Zheng }
315