1 //===------ LoopGenerators.cpp -  IR helper to create loops ---------------===//
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 contains functions to create scalar and parallel loops as LLVM-IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/CodeGen/LoopGenerators.h"
15 #include "polly/ScopDetection.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 
23 using namespace llvm;
24 using namespace polly;
25 
26 static cl::opt<int>
27     PollyNumThreads("polly-num-threads",
28                     cl::desc("Number of threads to use (0 = auto)"), cl::Hidden,
29                     cl::init(0));
30 
31 // We generate a loop of either of the following structures:
32 //
33 //              BeforeBB                      BeforeBB
34 //                 |                             |
35 //                 v                             v
36 //              GuardBB                      PreHeaderBB
37 //              /      |                         |   _____
38 //     __  PreHeaderBB  |                        v  \/    |
39 //    /  \    /         |                     HeaderBB  latch
40 // latch  HeaderBB      |                        |\       |
41 //    \  /    \         /                        | \------/
42 //     <       \       /                         |
43 //              \     /                          v
44 //              ExitBB                         ExitBB
45 //
46 // depending on whether or not we know that it is executed at least once. If
47 // not, GuardBB checks if the loop is executed at least once. If this is the
48 // case we branch to PreHeaderBB and subsequently to the HeaderBB, which
49 // contains the loop iv 'polly.indvar', the incremented loop iv
50 // 'polly.indvar_next' as well as the condition to check if we execute another
51 // iteration of the loop. After the loop has finished, we branch to ExitBB.
52 Value *polly::createLoop(Value *LB, Value *UB, Value *Stride,
53                          PollyIRBuilder &Builder, Pass *P, LoopInfo &LI,
54                          DominatorTree &DT, BasicBlock *&ExitBB,
55                          ICmpInst::Predicate Predicate,
56                          ScopAnnotator *Annotator, bool Parallel,
57                          bool UseGuard) {
58   Function *F = Builder.GetInsertBlock()->getParent();
59   LLVMContext &Context = F->getContext();
60 
61   assert(LB->getType() == UB->getType() && "Types of loop bounds do not match");
62   IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
63   assert(LoopIVType && "UB is not integer?");
64   assert((LoopIVType == LB->getType() && LoopIVType == Stride->getType()) &&
65          "LB, UB and Stride should have equal types.");
66 
67   BasicBlock *BeforeBB = Builder.GetInsertBlock();
68   BasicBlock *GuardBB =
69       UseGuard ? BasicBlock::Create(Context, "polly.loop_if", F) : nullptr;
70   BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
71   BasicBlock *PreHeaderBB =
72       BasicBlock::Create(Context, "polly.loop_preheader", F);
73 
74   // Update LoopInfo
75   Loop *OuterLoop = LI.getLoopFor(BeforeBB);
76   Loop *NewLoop = new Loop();
77 
78   if (OuterLoop)
79     OuterLoop->addChildLoop(NewLoop);
80   else
81     LI.addTopLevelLoop(NewLoop);
82 
83   if (OuterLoop) {
84     if (GuardBB)
85       OuterLoop->addBasicBlockToLoop(GuardBB, LI);
86     OuterLoop->addBasicBlockToLoop(PreHeaderBB, LI);
87   }
88 
89   NewLoop->addBasicBlockToLoop(HeaderBB, LI);
90 
91   // Notify the annotator (if present) that we have a new loop, but only
92   // after the header block is set.
93   if (Annotator)
94     Annotator->pushLoop(NewLoop, Parallel);
95 
96   // ExitBB
97   ExitBB = SplitBlock(BeforeBB, &*Builder.GetInsertPoint(), &DT, &LI);
98   ExitBB->setName("polly.loop_exit");
99 
100   // BeforeBB
101   if (GuardBB) {
102     BeforeBB->getTerminator()->setSuccessor(0, GuardBB);
103     DT.addNewBlock(GuardBB, BeforeBB);
104 
105     // GuardBB
106     Builder.SetInsertPoint(GuardBB);
107     Value *LoopGuard;
108     LoopGuard = Builder.CreateICmp(Predicate, LB, UB);
109     LoopGuard->setName("polly.loop_guard");
110     Builder.CreateCondBr(LoopGuard, PreHeaderBB, ExitBB);
111     DT.addNewBlock(PreHeaderBB, GuardBB);
112   } else {
113     BeforeBB->getTerminator()->setSuccessor(0, PreHeaderBB);
114     DT.addNewBlock(PreHeaderBB, BeforeBB);
115   }
116 
117   // PreHeaderBB
118   Builder.SetInsertPoint(PreHeaderBB);
119   Builder.CreateBr(HeaderBB);
120 
121   // HeaderBB
122   DT.addNewBlock(HeaderBB, PreHeaderBB);
123   Builder.SetInsertPoint(HeaderBB);
124   PHINode *IV = Builder.CreatePHI(LoopIVType, 2, "polly.indvar");
125   IV->addIncoming(LB, PreHeaderBB);
126   Value *IncrementedIV = Builder.CreateNSWAdd(IV, Stride, "polly.indvar_next");
127   Value *LoopCondition;
128   UB = Builder.CreateSub(UB, Stride, "polly.adjust_ub");
129   LoopCondition = Builder.CreateICmp(Predicate, IV, UB);
130   LoopCondition->setName("polly.loop_cond");
131 
132   // Create the loop latch and annotate it as such.
133   BranchInst *B = Builder.CreateCondBr(LoopCondition, HeaderBB, ExitBB);
134   if (Annotator)
135     Annotator->annotateLoopLatch(B, NewLoop, Parallel);
136 
137   IV->addIncoming(IncrementedIV, HeaderBB);
138   if (GuardBB)
139     DT.changeImmediateDominator(ExitBB, GuardBB);
140   else
141     DT.changeImmediateDominator(ExitBB, HeaderBB);
142 
143   // The loop body should be added here.
144   Builder.SetInsertPoint(HeaderBB->getFirstNonPHI());
145   return IV;
146 }
147 
148 Value *ParallelLoopGenerator::createParallelLoop(
149     Value *LB, Value *UB, Value *Stride, SetVector<Value *> &UsedValues,
150     ValueMapT &Map, BasicBlock::iterator *LoopBody) {
151 
152   // Adjust the types to match the GOMP API.
153   LB = Builder.CreateSExt(LB, LongType);
154   UB = Builder.CreateSExt(UB, LongType);
155   Stride = Builder.CreateSExt(Stride, LongType);
156 
157   Function *SubFn;
158 
159   AllocaInst *Struct = storeValuesIntoStruct(UsedValues);
160   BasicBlock::iterator BeforeLoop = Builder.GetInsertPoint();
161   Value *IV = createSubFn(Stride, Struct, UsedValues, Map, &SubFn);
162   *LoopBody = Builder.GetInsertPoint();
163   Builder.SetInsertPoint(&*BeforeLoop);
164 
165   Value *SubFnParam = Builder.CreateBitCast(Struct, Builder.getInt8PtrTy(),
166                                             "polly.par.userContext");
167 
168   // Add one as the upper bound provided by openmp is a < comparison
169   // whereas the codegenForSequential function creates a <= comparison.
170   UB = Builder.CreateAdd(UB, ConstantInt::get(LongType, 1));
171 
172   // Tell the runtime we start a parallel loop
173   createCallSpawnThreads(SubFn, SubFnParam, LB, UB, Stride);
174   Builder.CreateCall(SubFn, SubFnParam);
175   createCallJoinThreads();
176 
177   // Mark the end of the lifetime for the parameter struct.
178   Type *Ty = Struct->getType();
179   ConstantInt *SizeOf = Builder.getInt64(DL.getTypeAllocSize(Ty));
180   Builder.CreateLifetimeEnd(Struct, SizeOf);
181 
182   return IV;
183 }
184 
185 void ParallelLoopGenerator::createCallSpawnThreads(Value *SubFn,
186                                                    Value *SubFnParam, Value *LB,
187                                                    Value *UB, Value *Stride) {
188   const std::string Name = "GOMP_parallel_loop_runtime_start";
189 
190   Function *F = M->getFunction(Name);
191 
192   // If F is not available, declare it.
193   if (!F) {
194     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
195 
196     Type *Params[] = {PointerType::getUnqual(FunctionType::get(
197                           Builder.getVoidTy(), Builder.getInt8PtrTy(), false)),
198                       Builder.getInt8PtrTy(), Builder.getInt32Ty(), LongType,
199                       LongType, LongType};
200 
201     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
202     F = Function::Create(Ty, Linkage, Name, M);
203   }
204 
205   Value *NumberOfThreads = Builder.getInt32(PollyNumThreads);
206   Value *Args[] = {SubFn, SubFnParam, NumberOfThreads, LB, UB, Stride};
207 
208   Builder.CreateCall(F, Args);
209 }
210 
211 Value *ParallelLoopGenerator::createCallGetWorkItem(Value *LBPtr,
212                                                     Value *UBPtr) {
213   const std::string Name = "GOMP_loop_runtime_next";
214 
215   Function *F = M->getFunction(Name);
216 
217   // If F is not available, declare it.
218   if (!F) {
219     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
220     Type *Params[] = {LongType->getPointerTo(), LongType->getPointerTo()};
221     FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
222     F = Function::Create(Ty, Linkage, Name, M);
223   }
224 
225   Value *Args[] = {LBPtr, UBPtr};
226   Value *Return = Builder.CreateCall(F, Args);
227   Return = Builder.CreateICmpNE(
228       Return, Builder.CreateZExt(Builder.getFalse(), Return->getType()));
229   return Return;
230 }
231 
232 void ParallelLoopGenerator::createCallJoinThreads() {
233   const std::string Name = "GOMP_parallel_end";
234 
235   Function *F = M->getFunction(Name);
236 
237   // If F is not available, declare it.
238   if (!F) {
239     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
240 
241     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
242     F = Function::Create(Ty, Linkage, Name, M);
243   }
244 
245   Builder.CreateCall(F, {});
246 }
247 
248 void ParallelLoopGenerator::createCallCleanupThread() {
249   const std::string Name = "GOMP_loop_end_nowait";
250 
251   Function *F = M->getFunction(Name);
252 
253   // If F is not available, declare it.
254   if (!F) {
255     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
256 
257     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
258     F = Function::Create(Ty, Linkage, Name, M);
259   }
260 
261   Builder.CreateCall(F, {});
262 }
263 
264 Function *ParallelLoopGenerator::createSubFnDefinition() {
265   Function *F = Builder.GetInsertBlock()->getParent();
266   std::vector<Type *> Arguments(1, Builder.getInt8PtrTy());
267   FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
268   Function *SubFn = Function::Create(FT, Function::InternalLinkage,
269                                      F->getName() + "_polly_subfn", M);
270 
271   // Certain backends (e.g., NVPTX) do not support '.'s in function names.
272   // Hence, we ensure that all '.'s are replaced by '_'s.
273   std::string FunctionName = SubFn->getName();
274   std::replace(FunctionName.begin(), FunctionName.end(), '.', '_');
275   SubFn->setName(FunctionName);
276 
277   // Do not run any polly pass on the new function.
278   SubFn->addFnAttr(PollySkipFnAttr);
279 
280   Function::arg_iterator AI = SubFn->arg_begin();
281   AI->setName("polly.par.userContext");
282 
283   return SubFn;
284 }
285 
286 AllocaInst *
287 ParallelLoopGenerator::storeValuesIntoStruct(SetVector<Value *> &Values) {
288   SmallVector<Type *, 8> Members;
289 
290   for (Value *V : Values)
291     Members.push_back(V->getType());
292 
293   // We do not want to allocate the alloca inside any loop, thus we allocate it
294   // in the entry block of the function and use annotations to denote the actual
295   // live span (similar to clang).
296   BasicBlock &EntryBB = Builder.GetInsertBlock()->getParent()->getEntryBlock();
297   Instruction *IP = &*EntryBB.getFirstInsertionPt();
298   StructType *Ty = StructType::get(Builder.getContext(), Members);
299   AllocaInst *Struct = new AllocaInst(Ty, 0, "polly.par.userContext", IP);
300 
301   // Mark the start of the lifetime for the parameter struct.
302   ConstantInt *SizeOf = Builder.getInt64(DL.getTypeAllocSize(Ty));
303   Builder.CreateLifetimeStart(Struct, SizeOf);
304 
305   for (unsigned i = 0; i < Values.size(); i++) {
306     Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
307     Address->setName("polly.subfn.storeaddr." + Values[i]->getName());
308     Builder.CreateStore(Values[i], Address);
309   }
310 
311   return Struct;
312 }
313 
314 void ParallelLoopGenerator::extractValuesFromStruct(
315     SetVector<Value *> OldValues, Type *Ty, Value *Struct, ValueMapT &Map) {
316   for (unsigned i = 0; i < OldValues.size(); i++) {
317     Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
318     Value *NewValue = Builder.CreateLoad(Address);
319     NewValue->setName("polly.subfunc.arg." + OldValues[i]->getName());
320     Map[OldValues[i]] = NewValue;
321   }
322 }
323 
324 Value *ParallelLoopGenerator::createSubFn(Value *Stride, AllocaInst *StructData,
325                                           SetVector<Value *> Data,
326                                           ValueMapT &Map, Function **SubFnPtr) {
327   BasicBlock *PrevBB, *HeaderBB, *ExitBB, *CheckNextBB, *PreHeaderBB, *AfterBB;
328   Value *LBPtr, *UBPtr, *UserContext, *Ret1, *HasNextSchedule, *LB, *UB, *IV;
329   Function *SubFn = createSubFnDefinition();
330   LLVMContext &Context = SubFn->getContext();
331 
332   // Store the previous basic block.
333   PrevBB = Builder.GetInsertBlock();
334 
335   // Create basic blocks.
336   HeaderBB = BasicBlock::Create(Context, "polly.par.setup", SubFn);
337   ExitBB = BasicBlock::Create(Context, "polly.par.exit", SubFn);
338   CheckNextBB = BasicBlock::Create(Context, "polly.par.checkNext", SubFn);
339   PreHeaderBB = BasicBlock::Create(Context, "polly.par.loadIVBounds", SubFn);
340 
341   DT.addNewBlock(HeaderBB, PrevBB);
342   DT.addNewBlock(ExitBB, HeaderBB);
343   DT.addNewBlock(CheckNextBB, HeaderBB);
344   DT.addNewBlock(PreHeaderBB, HeaderBB);
345 
346   // Fill up basic block HeaderBB.
347   Builder.SetInsertPoint(HeaderBB);
348   LBPtr = Builder.CreateAlloca(LongType, 0, "polly.par.LBPtr");
349   UBPtr = Builder.CreateAlloca(LongType, 0, "polly.par.UBPtr");
350   UserContext = Builder.CreateBitCast(
351       &*SubFn->arg_begin(), StructData->getType(), "polly.par.userContext");
352 
353   extractValuesFromStruct(Data, StructData->getAllocatedType(), UserContext,
354                           Map);
355   Builder.CreateBr(CheckNextBB);
356 
357   // Add code to check if another set of iterations will be executed.
358   Builder.SetInsertPoint(CheckNextBB);
359   Ret1 = createCallGetWorkItem(LBPtr, UBPtr);
360   HasNextSchedule = Builder.CreateTrunc(Ret1, Builder.getInt1Ty(),
361                                         "polly.par.hasNextScheduleBlock");
362   Builder.CreateCondBr(HasNextSchedule, PreHeaderBB, ExitBB);
363 
364   // Add code to load the iv bounds for this set of iterations.
365   Builder.SetInsertPoint(PreHeaderBB);
366   LB = Builder.CreateLoad(LBPtr, "polly.par.LB");
367   UB = Builder.CreateLoad(UBPtr, "polly.par.UB");
368 
369   // Subtract one as the upper bound provided by openmp is a < comparison
370   // whereas the codegenForSequential function creates a <= comparison.
371   UB = Builder.CreateSub(UB, ConstantInt::get(LongType, 1),
372                          "polly.par.UBAdjusted");
373 
374   Builder.CreateBr(CheckNextBB);
375   Builder.SetInsertPoint(&*--Builder.GetInsertPoint());
376   IV = createLoop(LB, UB, Stride, Builder, P, LI, DT, AfterBB,
377                   ICmpInst::ICMP_SLE, nullptr, true, /* UseGuard */ false);
378 
379   BasicBlock::iterator LoopBody = Builder.GetInsertPoint();
380 
381   // Add code to terminate this subfunction.
382   Builder.SetInsertPoint(ExitBB);
383   createCallCleanupThread();
384   Builder.CreateRetVoid();
385 
386   Builder.SetInsertPoint(&*LoopBody);
387   *SubFnPtr = SubFn;
388 
389   return IV;
390 }
391