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