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 #include "llvm/Analysis/Dominators.h"
18535d52c7SChandler Carruth #include "llvm/IR/DataLayout.h"
19*83628182STobias Grosser #include "llvm/IR/Module.h"
20609089f2SHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21609089f2SHongbin Zheng 
22609089f2SHongbin Zheng using namespace llvm;
234ac4e155SHongbin Zheng using namespace polly;
24609089f2SHongbin Zheng 
254ac4e155SHongbin Zheng Value *polly::createLoop(Value *LB, Value *UB, Value *Stride,
261bb59b0dSTobias Grosser                          IRBuilder<> &Builder, Pass *P, BasicBlock *&AfterBlock,
27c967d8e6STobias Grosser                          ICmpInst::Predicate Predicate) {
28609089f2SHongbin Zheng   DominatorTree &DT = P->getAnalysis<DominatorTree>();
294ac4e155SHongbin Zheng   Function *F = Builder.GetInsertBlock()->getParent();
30609089f2SHongbin Zheng   LLVMContext &Context = F->getContext();
31609089f2SHongbin Zheng 
324ac4e155SHongbin Zheng   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
33609089f2SHongbin Zheng   BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
34609089f2SHongbin Zheng   BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
354ac4e155SHongbin Zheng   BasicBlock *AfterBB = SplitBlock(PreheaderBB, Builder.GetInsertPoint()++, P);
36609089f2SHongbin Zheng   AfterBB->setName("polly.loop_after");
37609089f2SHongbin Zheng 
38609089f2SHongbin Zheng   PreheaderBB->getTerminator()->setSuccessor(0, HeaderBB);
39609089f2SHongbin Zheng   DT.addNewBlock(HeaderBB, PreheaderBB);
40609089f2SHongbin Zheng 
414ac4e155SHongbin Zheng   Builder.SetInsertPoint(HeaderBB);
42609089f2SHongbin Zheng 
43609089f2SHongbin Zheng   // Use the type of upper and lower bound.
44ae2d83ecSTobias Grosser   assert(LB->getType() == UB->getType() &&
45ae2d83ecSTobias Grosser          "Different types for upper and lower bound.");
46609089f2SHongbin Zheng 
47609089f2SHongbin Zheng   IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
48609089f2SHongbin Zheng   assert(LoopIVType && "UB is not integer?");
49609089f2SHongbin Zheng 
50609089f2SHongbin Zheng   // IV
514ac4e155SHongbin Zheng   PHINode *IV = Builder.CreatePHI(LoopIVType, 2, "polly.loopiv");
52609089f2SHongbin Zheng   IV->addIncoming(LB, PreheaderBB);
53609089f2SHongbin Zheng 
544ac4e155SHongbin Zheng   Stride = Builder.CreateZExtOrBitCast(Stride, LoopIVType);
55400a4ac6STobias Grosser   Value *IncrementedIV = Builder.CreateNSWAdd(IV, Stride, "polly.next_loopiv");
56609089f2SHongbin Zheng 
57609089f2SHongbin Zheng   // Exit condition.
58609089f2SHongbin Zheng   Value *CMP;
59c967d8e6STobias Grosser   CMP = Builder.CreateICmp(Predicate, IV, UB);
60609089f2SHongbin Zheng 
614ac4e155SHongbin Zheng   Builder.CreateCondBr(CMP, BodyBB, AfterBB);
62609089f2SHongbin Zheng   DT.addNewBlock(BodyBB, HeaderBB);
63609089f2SHongbin Zheng 
644ac4e155SHongbin Zheng   Builder.SetInsertPoint(BodyBB);
654ac4e155SHongbin Zheng   Builder.CreateBr(HeaderBB);
66609089f2SHongbin Zheng   IV->addIncoming(IncrementedIV, BodyBB);
67609089f2SHongbin Zheng   DT.changeImmediateDominator(AfterBB, HeaderBB);
68609089f2SHongbin Zheng 
694ac4e155SHongbin Zheng   Builder.SetInsertPoint(BodyBB->begin());
704ac4e155SHongbin Zheng   AfterBlock = AfterBB;
71609089f2SHongbin Zheng 
72609089f2SHongbin Zheng   return IV;
73609089f2SHongbin Zheng }
74609089f2SHongbin Zheng 
75c14582f2STobias Grosser void OMPGenerator::createCallParallelLoopStart(
76c14582f2STobias Grosser     Value *SubFunction, Value *SubfunctionParam, Value *NumberOfThreads,
77c14582f2STobias Grosser     Value *LowerBound, Value *UpperBound, Value *Stride) {
78609089f2SHongbin Zheng   Module *M = getModule();
79609089f2SHongbin Zheng   const char *Name = "GOMP_parallel_loop_runtime_start";
80609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
81609089f2SHongbin Zheng 
82609089f2SHongbin Zheng   // If F is not available, declare it.
83609089f2SHongbin Zheng   if (!F) {
84609089f2SHongbin Zheng     Type *LongTy = getIntPtrTy();
85609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
86609089f2SHongbin Zheng 
87c14582f2STobias Grosser     Type *Params[] = { PointerType::getUnqual(FunctionType::get(
88c14582f2STobias Grosser                            Builder.getVoidTy(), Builder.getInt8PtrTy(), false)),
89c14582f2STobias Grosser                        Builder.getInt8PtrTy(), Builder.getInt32Ty(), LongTy,
90c14582f2STobias Grosser                        LongTy, LongTy, };
91609089f2SHongbin Zheng 
92609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
93609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
94609089f2SHongbin Zheng   }
95609089f2SHongbin Zheng 
96c14582f2STobias Grosser   Value *Args[] = { SubFunction, SubfunctionParam, NumberOfThreads, LowerBound,
97c14582f2STobias Grosser                     UpperBound, Stride, };
98609089f2SHongbin Zheng 
99609089f2SHongbin Zheng   Builder.CreateCall(F, Args);
100609089f2SHongbin Zheng }
101609089f2SHongbin Zheng 
102e602a076STobias Grosser Value *OMPGenerator::createCallLoopNext(Value *LowerBoundPtr,
103e602a076STobias Grosser                                         Value *UpperBoundPtr) {
104609089f2SHongbin Zheng   Module *M = getModule();
105609089f2SHongbin Zheng   const char *Name = "GOMP_loop_runtime_next";
106609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
107609089f2SHongbin Zheng 
108609089f2SHongbin Zheng   // If F is not available, declare it.
109609089f2SHongbin Zheng   if (!F) {
110609089f2SHongbin Zheng     Type *LongPtrTy = PointerType::getUnqual(getIntPtrTy());
111609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
112609089f2SHongbin Zheng 
113c14582f2STobias Grosser     Type *Params[] = { LongPtrTy, LongPtrTy, };
114609089f2SHongbin Zheng 
115609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
116609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
117609089f2SHongbin Zheng   }
118609089f2SHongbin Zheng 
119c14582f2STobias Grosser   Value *Args[] = { LowerBoundPtr, UpperBoundPtr, };
120609089f2SHongbin Zheng 
121609089f2SHongbin Zheng   Value *Return = Builder.CreateCall(F, Args);
122c14582f2STobias Grosser   Return = Builder.CreateICmpNE(
123c14582f2STobias Grosser       Return, Builder.CreateZExt(Builder.getFalse(), Return->getType()));
124609089f2SHongbin Zheng   return Return;
125609089f2SHongbin Zheng }
126609089f2SHongbin Zheng 
127609089f2SHongbin Zheng void OMPGenerator::createCallParallelEnd() {
128609089f2SHongbin Zheng   const char *Name = "GOMP_parallel_end";
129609089f2SHongbin Zheng   Module *M = getModule();
130609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
131609089f2SHongbin Zheng 
132609089f2SHongbin Zheng   // If F is not available, declare it.
133609089f2SHongbin Zheng   if (!F) {
134609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
135609089f2SHongbin Zheng 
136609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
137609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
138609089f2SHongbin Zheng   }
139609089f2SHongbin Zheng 
140609089f2SHongbin Zheng   Builder.CreateCall(F);
141609089f2SHongbin Zheng }
142609089f2SHongbin Zheng 
143609089f2SHongbin Zheng void OMPGenerator::createCallLoopEndNowait() {
144609089f2SHongbin Zheng   const char *Name = "GOMP_loop_end_nowait";
145609089f2SHongbin Zheng   Module *M = getModule();
146609089f2SHongbin Zheng   Function *F = M->getFunction(Name);
147609089f2SHongbin Zheng 
148609089f2SHongbin Zheng   // If F is not available, declare it.
149609089f2SHongbin Zheng   if (!F) {
150609089f2SHongbin Zheng     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
151609089f2SHongbin Zheng 
152609089f2SHongbin Zheng     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
153609089f2SHongbin Zheng     F = Function::Create(Ty, Linkage, Name, M);
154609089f2SHongbin Zheng   }
155609089f2SHongbin Zheng 
156609089f2SHongbin Zheng   Builder.CreateCall(F);
157609089f2SHongbin Zheng }
158609089f2SHongbin Zheng 
159609089f2SHongbin Zheng IntegerType *OMPGenerator::getIntPtrTy() {
1605d01691dSTobias Grosser   return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
161609089f2SHongbin Zheng }
162609089f2SHongbin Zheng 
163609089f2SHongbin Zheng Module *OMPGenerator::getModule() {
164609089f2SHongbin Zheng   return Builder.GetInsertBlock()->getParent()->getParent();
165609089f2SHongbin Zheng }
166609089f2SHongbin Zheng 
167609089f2SHongbin Zheng Function *OMPGenerator::createSubfunctionDefinition() {
168609089f2SHongbin Zheng   Module *M = getModule();
169609089f2SHongbin Zheng   Function *F = Builder.GetInsertBlock()->getParent();
170609089f2SHongbin Zheng   std::vector<Type *> Arguments(1, Builder.getInt8PtrTy());
171609089f2SHongbin Zheng   FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
172609089f2SHongbin Zheng   Function *FN = Function::Create(FT, Function::InternalLinkage,
173609089f2SHongbin Zheng                                   F->getName() + ".omp_subfn", M);
174609089f2SHongbin Zheng   // Do not run any polly pass on the new function.
175609089f2SHongbin Zheng   P->getAnalysis<polly::ScopDetection>().markFunctionAsInvalid(FN);
176609089f2SHongbin Zheng 
177609089f2SHongbin Zheng   Function::arg_iterator AI = FN->arg_begin();
178609089f2SHongbin Zheng   AI->setName("omp.userContext");
179609089f2SHongbin Zheng 
180609089f2SHongbin Zheng   return FN;
181609089f2SHongbin Zheng }
182609089f2SHongbin Zheng 
183609089f2SHongbin Zheng Value *OMPGenerator::loadValuesIntoStruct(SetVector<Value *> &Values) {
184609089f2SHongbin Zheng   std::vector<Type *> Members;
185609089f2SHongbin Zheng 
186609089f2SHongbin Zheng   for (unsigned i = 0; i < Values.size(); i++)
187609089f2SHongbin Zheng     Members.push_back(Values[i]->getType());
188609089f2SHongbin Zheng 
189609089f2SHongbin Zheng   StructType *Ty = StructType::get(Builder.getContext(), Members);
190609089f2SHongbin Zheng   Value *Struct = Builder.CreateAlloca(Ty, 0, "omp.userContext");
191609089f2SHongbin Zheng 
192609089f2SHongbin Zheng   for (unsigned i = 0; i < Values.size(); i++) {
193609089f2SHongbin Zheng     Value *Address = Builder.CreateStructGEP(Struct, i);
194609089f2SHongbin Zheng     Builder.CreateStore(Values[i], Address);
195609089f2SHongbin Zheng   }
196609089f2SHongbin Zheng 
197609089f2SHongbin Zheng   return Struct;
198609089f2SHongbin Zheng }
199609089f2SHongbin Zheng 
200e602a076STobias Grosser void OMPGenerator::extractValuesFromStruct(SetVector<Value *> OldValues,
201e602a076STobias Grosser                                            Value *Struct,
202e602a076STobias Grosser                                            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);
20636e6ca01SAndy Gibbs     Map.insert(std::make_pair(OldValues[i], NewValue));
207609089f2SHongbin Zheng   }
208609089f2SHongbin Zheng }
209609089f2SHongbin Zheng 
210e602a076STobias Grosser Value *OMPGenerator::createSubfunction(Value *Stride, Value *StructData,
211e602a076STobias Grosser                                        SetVector<Value *> Data,
212e602a076STobias Grosser                                        ValueToValueMapTy &Map,
213e602a076STobias Grosser                                        Function **SubFunction) {
214609089f2SHongbin Zheng   Function *FN = createSubfunctionDefinition();
215609089f2SHongbin Zheng 
216609089f2SHongbin Zheng   BasicBlock *PrevBB, *HeaderBB, *ExitBB, *CheckNextBB, *LoadIVBoundsBB,
217609089f2SHongbin Zheng       *AfterBB;
218609089f2SHongbin Zheng   Value *LowerBoundPtr, *UpperBoundPtr, *UserContext, *Ret1, *HasNextSchedule,
219609089f2SHongbin Zheng       *LowerBound, *UpperBound, *IV;
220609089f2SHongbin Zheng   Type *IntPtrTy = getIntPtrTy();
221609089f2SHongbin Zheng   LLVMContext &Context = FN->getContext();
222609089f2SHongbin Zheng 
223609089f2SHongbin Zheng   // Store the previous basic block.
224609089f2SHongbin Zheng   PrevBB = Builder.GetInsertBlock();
225609089f2SHongbin Zheng 
226609089f2SHongbin Zheng   // Create basic blocks.
227609089f2SHongbin Zheng   HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
228609089f2SHongbin Zheng   ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
229609089f2SHongbin Zheng   CheckNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
230609089f2SHongbin Zheng   LoadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds", FN);
231609089f2SHongbin Zheng 
232609089f2SHongbin Zheng   DominatorTree &DT = P->getAnalysis<DominatorTree>();
233609089f2SHongbin Zheng   DT.addNewBlock(HeaderBB, PrevBB);
234609089f2SHongbin Zheng   DT.addNewBlock(ExitBB, HeaderBB);
235609089f2SHongbin Zheng   DT.addNewBlock(CheckNextBB, HeaderBB);
236609089f2SHongbin Zheng   DT.addNewBlock(LoadIVBoundsBB, HeaderBB);
237609089f2SHongbin Zheng 
238609089f2SHongbin Zheng   // Fill up basic block HeaderBB.
239609089f2SHongbin Zheng   Builder.SetInsertPoint(HeaderBB);
240609089f2SHongbin Zheng   LowerBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.lowerBoundPtr");
241609089f2SHongbin Zheng   UpperBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.upperBoundPtr");
242609089f2SHongbin Zheng   UserContext = Builder.CreateBitCast(FN->arg_begin(), StructData->getType(),
243609089f2SHongbin Zheng                                       "omp.userContext");
244609089f2SHongbin Zheng 
245609089f2SHongbin Zheng   extractValuesFromStruct(Data, UserContext, Map);
246609089f2SHongbin Zheng   Builder.CreateBr(CheckNextBB);
247609089f2SHongbin Zheng 
248609089f2SHongbin Zheng   // Add code to check if another set of iterations will be executed.
249609089f2SHongbin Zheng   Builder.SetInsertPoint(CheckNextBB);
250609089f2SHongbin Zheng   Ret1 = createCallLoopNext(LowerBoundPtr, UpperBoundPtr);
251609089f2SHongbin Zheng   HasNextSchedule = Builder.CreateTrunc(Ret1, Builder.getInt1Ty(),
252609089f2SHongbin Zheng                                         "omp.hasNextScheduleBlock");
253609089f2SHongbin Zheng   Builder.CreateCondBr(HasNextSchedule, LoadIVBoundsBB, ExitBB);
254609089f2SHongbin Zheng 
255609089f2SHongbin Zheng   // Add code to to load the iv bounds for this set of iterations.
256609089f2SHongbin Zheng   Builder.SetInsertPoint(LoadIVBoundsBB);
257609089f2SHongbin Zheng   LowerBound = Builder.CreateLoad(LowerBoundPtr, "omp.lowerBound");
258609089f2SHongbin Zheng   UpperBound = Builder.CreateLoad(UpperBoundPtr, "omp.upperBound");
259609089f2SHongbin Zheng 
260609089f2SHongbin Zheng   // Subtract one as the upper bound provided by openmp is a < comparison
261609089f2SHongbin Zheng   // whereas the codegenForSequential function creates a <= comparison.
262609089f2SHongbin Zheng   UpperBound = Builder.CreateSub(UpperBound, ConstantInt::get(IntPtrTy, 1),
263609089f2SHongbin Zheng                                  "omp.upperBoundAdjusted");
264609089f2SHongbin Zheng 
265609089f2SHongbin Zheng   Builder.CreateBr(CheckNextBB);
266609089f2SHongbin Zheng   Builder.SetInsertPoint(--Builder.GetInsertPoint());
267c967d8e6STobias Grosser   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
268c967d8e6STobias Grosser                   ICmpInst::ICMP_SLE);
269609089f2SHongbin Zheng 
270609089f2SHongbin Zheng   BasicBlock::iterator LoopBody = Builder.GetInsertPoint();
271609089f2SHongbin Zheng   Builder.SetInsertPoint(AfterBB->begin());
272609089f2SHongbin Zheng 
273609089f2SHongbin Zheng   // Add code to terminate this openmp subfunction.
274609089f2SHongbin Zheng   Builder.SetInsertPoint(ExitBB);
275609089f2SHongbin Zheng   createCallLoopEndNowait();
276609089f2SHongbin Zheng   Builder.CreateRetVoid();
277609089f2SHongbin Zheng 
278609089f2SHongbin Zheng   Builder.SetInsertPoint(LoopBody);
279609089f2SHongbin Zheng   *SubFunction = FN;
280609089f2SHongbin Zheng 
281609089f2SHongbin Zheng   return IV;
282609089f2SHongbin Zheng }
283609089f2SHongbin Zheng 
284e602a076STobias Grosser Value *OMPGenerator::createParallelLoop(Value *LowerBound, Value *UpperBound,
285e602a076STobias Grosser                                         Value *Stride,
286e602a076STobias Grosser                                         SetVector<Value *> &Values,
287e602a076STobias Grosser                                         ValueToValueMapTy &Map,
288609089f2SHongbin Zheng                                         BasicBlock::iterator *LoopBody) {
289609089f2SHongbin Zheng   Value *Struct, *IV, *SubfunctionParam, *NumberOfThreads;
290609089f2SHongbin Zheng   Function *SubFunction;
291609089f2SHongbin Zheng 
292609089f2SHongbin Zheng   Struct = loadValuesIntoStruct(Values);
293609089f2SHongbin Zheng 
294609089f2SHongbin Zheng   BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
295609089f2SHongbin Zheng   IV = createSubfunction(Stride, Struct, Values, Map, &SubFunction);
296609089f2SHongbin Zheng   *LoopBody = Builder.GetInsertPoint();
297609089f2SHongbin Zheng   Builder.SetInsertPoint(PrevInsertPoint);
298609089f2SHongbin Zheng 
299609089f2SHongbin Zheng   // Create call for GOMP_parallel_loop_runtime_start.
300c14582f2STobias Grosser   SubfunctionParam =
301c14582f2STobias Grosser       Builder.CreateBitCast(Struct, Builder.getInt8PtrTy(), "omp_data");
302609089f2SHongbin Zheng 
303609089f2SHongbin Zheng   NumberOfThreads = Builder.getInt32(0);
304609089f2SHongbin Zheng 
305609089f2SHongbin Zheng   // Add one as the upper bound provided by openmp is a < comparison
306609089f2SHongbin Zheng   // whereas the codegenForSequential function creates a <= comparison.
307c14582f2STobias Grosser   UpperBound =
308c14582f2STobias Grosser       Builder.CreateAdd(UpperBound, ConstantInt::get(getIntPtrTy(), 1));
309609089f2SHongbin Zheng 
310609089f2SHongbin Zheng   createCallParallelLoopStart(SubFunction, SubfunctionParam, NumberOfThreads,
311609089f2SHongbin Zheng                               LowerBound, UpperBound, Stride);
312609089f2SHongbin Zheng   Builder.CreateCall(SubFunction, SubfunctionParam);
313609089f2SHongbin Zheng   createCallParallelEnd();
314609089f2SHongbin Zheng 
315609089f2SHongbin Zheng   return IV;
316609089f2SHongbin Zheng }
317