Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1 | //===------ CodeGeneration.cpp - Code generate the Scops. -----------------===// |
| 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 | // The CodeGeneration pass takes a Scop created by ScopInfo and translates it |
| 11 | // back to LLVM-IR using Cloog. |
| 12 | // |
| 13 | // The Scop describes the high level memory behaviour of a control flow region. |
| 14 | // Transformation passes can update the schedule (execution order) of statements |
| 15 | // in the Scop. Cloog is used to generate an abstract syntax tree (clast) that |
| 16 | // reflects the updated execution order. This clast is used to create new |
| 17 | // LLVM-IR that is computational equivalent to the original control flow region, |
| 18 | // but executes its code in the new execution order defined by the changed |
| 19 | // scattering. |
| 20 | // |
| 21 | //===----------------------------------------------------------------------===// |
| 22 | |
| 23 | #define DEBUG_TYPE "polly-codegen" |
| 24 | |
| 25 | #include "polly/LinkAllPasses.h" |
| 26 | #include "polly/Support/GICHelper.h" |
| 27 | #include "polly/Support/ScopHelper.h" |
| 28 | #include "polly/Cloog.h" |
| 29 | #include "polly/Dependences.h" |
| 30 | #include "polly/ScopInfo.h" |
| 31 | #include "polly/TempScopInfo.h" |
| 32 | #include "llvm/Support/CommandLine.h" |
| 33 | #include "llvm/Support/Debug.h" |
| 34 | #include "llvm/Support/IRBuilder.h" |
| 35 | #include "llvm/Analysis/LoopInfo.h" |
| 36 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 38 | #include "llvm/Target/TargetData.h" |
| 39 | #include "llvm/Module.h" |
| 40 | #include "llvm/ADT/SetVector.h" |
| 41 | |
| 42 | #define CLOOG_INT_GMP 1 |
| 43 | #include "cloog/cloog.h" |
| 44 | #include "cloog/isl/cloog.h" |
| 45 | |
| 46 | #include <vector> |
| 47 | #include <utility> |
| 48 | |
| 49 | using namespace polly; |
| 50 | using namespace llvm; |
| 51 | |
| 52 | struct isl_set; |
| 53 | |
| 54 | namespace polly { |
| 55 | |
| 56 | static cl::opt<bool> |
| 57 | Vector("enable-polly-vector", |
| 58 | cl::desc("Enable polly vector code generation"), cl::Hidden, |
| 59 | cl::value_desc("Vector code generation enabled if true"), |
| 60 | cl::init(false)); |
| 61 | |
| 62 | static cl::opt<bool> |
| 63 | OpenMP("enable-polly-openmp", |
| 64 | cl::desc("Generate OpenMP parallel code"), cl::Hidden, |
| 65 | cl::value_desc("OpenMP code generation enabled if true"), |
| 66 | cl::init(false)); |
| 67 | |
| 68 | static cl::opt<bool> |
| 69 | AtLeastOnce("enable-polly-atLeastOnce", |
| 70 | cl::desc("Give polly the hint, that every loop is executed at least" |
| 71 | "once"), cl::Hidden, |
| 72 | cl::value_desc("OpenMP code generation enabled if true"), |
| 73 | cl::init(false)); |
| 74 | |
| 75 | static cl::opt<bool> |
| 76 | Aligned("enable-polly-aligned", |
| 77 | cl::desc("Assumed aligned memory accesses."), cl::Hidden, |
| 78 | cl::value_desc("OpenMP code generation enabled if true"), |
| 79 | cl::init(false)); |
| 80 | |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 81 | typedef DenseMap<const Value*, Value*> ValueMapT; |
| 82 | typedef DenseMap<const char*, Value*> CharMapT; |
| 83 | typedef std::vector<ValueMapT> VectorValueMapT; |
| 84 | |
| 85 | // Create a new loop. |
| 86 | // |
| 87 | // @param Builder The builder used to create the loop. It also defines the |
| 88 | // place where to create the loop. |
| 89 | // @param UB The upper bound of the loop iv. |
| 90 | // @param Stride The number by which the loop iv is incremented after every |
| 91 | // iteration. |
| 92 | static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride, |
| 93 | PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV, |
| 94 | DominatorTree *DT) { |
| 95 | Function *F = Builder->GetInsertBlock()->getParent(); |
| 96 | LLVMContext &Context = F->getContext(); |
| 97 | |
| 98 | BasicBlock *PreheaderBB = Builder->GetInsertBlock(); |
| 99 | BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F); |
| 100 | BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F); |
| 101 | AfterBB = BasicBlock::Create(Context, "polly.after_loop", F); |
| 102 | |
| 103 | Builder->CreateBr(HeaderBB); |
| 104 | DT->addNewBlock(HeaderBB, PreheaderBB); |
| 105 | |
| 106 | Builder->SetInsertPoint(BodyBB); |
| 107 | |
| 108 | Builder->SetInsertPoint(HeaderBB); |
| 109 | |
| 110 | // Use the type of upper and lower bound. |
| 111 | assert(LB->getType() == UB->getType() |
| 112 | && "Different types for upper and lower bound."); |
| 113 | |
| 114 | const IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType()); |
| 115 | assert(LoopIVType && "UB is not integer?"); |
| 116 | |
| 117 | // IV |
| 118 | IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv"); |
| 119 | IV->addIncoming(LB, PreheaderBB); |
| 120 | |
| 121 | // IV increment. |
| 122 | Value *StrideValue = ConstantInt::get(LoopIVType, |
| 123 | Stride.zext(LoopIVType->getBitWidth())); |
| 124 | IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv"); |
| 125 | |
| 126 | // Exit condition. |
| 127 | if (AtLeastOnce) { // At least on iteration. |
| 128 | UB = Builder->CreateAdd(UB, Builder->getInt64(1)); |
| 129 | Value *CMP = Builder->CreateICmpEQ(IV, UB); |
| 130 | Builder->CreateCondBr(CMP, AfterBB, BodyBB); |
| 131 | } else { // Maybe not executed at all. |
| 132 | Value *CMP = Builder->CreateICmpSLE(IV, UB); |
| 133 | Builder->CreateCondBr(CMP, BodyBB, AfterBB); |
| 134 | } |
| 135 | DT->addNewBlock(BodyBB, HeaderBB); |
| 136 | DT->addNewBlock(AfterBB, HeaderBB); |
| 137 | |
| 138 | Builder->SetInsertPoint(BodyBB); |
| 139 | } |
| 140 | |
| 141 | class BlockGenerator { |
| 142 | IRBuilder<> &Builder; |
| 143 | ValueMapT &VMap; |
| 144 | VectorValueMapT &ValueMaps; |
| 145 | Scop &S; |
| 146 | ScopStmt &statement; |
| 147 | isl_set *scatteringDomain; |
| 148 | |
| 149 | public: |
| 150 | BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps, |
| 151 | ScopStmt &Stmt, isl_set *domain) |
| 152 | : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()), |
| 153 | statement(Stmt), scatteringDomain(domain) {} |
| 154 | |
| 155 | const Region &getRegion() { |
| 156 | return S.getRegion(); |
| 157 | } |
| 158 | |
| 159 | Value* makeVectorOperand(Value *operand, int vectorWidth) { |
| 160 | if (operand->getType()->isVectorTy()) |
| 161 | return operand; |
| 162 | |
| 163 | VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth); |
| 164 | Value *vector = UndefValue::get(vectorType); |
| 165 | vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0)); |
| 166 | |
| 167 | std::vector<Constant*> splat; |
| 168 | |
| 169 | for (int i = 0; i < vectorWidth; i++) |
| 170 | splat.push_back (Builder.getInt32(0)); |
| 171 | |
| 172 | Constant *splatVector = ConstantVector::get(splat); |
| 173 | |
| 174 | return Builder.CreateShuffleVector(vector, vector, splatVector); |
| 175 | } |
| 176 | |
| 177 | Value* getOperand(const Value *OldOperand, ValueMapT &BBMap, |
| 178 | ValueMapT *VectorMap = 0) { |
| 179 | const Instruction *OpInst = dyn_cast<Instruction>(OldOperand); |
| 180 | |
| 181 | if (!OpInst) |
| 182 | return const_cast<Value*>(OldOperand); |
| 183 | |
| 184 | if (VectorMap && VectorMap->count(OldOperand)) |
| 185 | return (*VectorMap)[OldOperand]; |
| 186 | |
| 187 | // IVS and Parameters. |
| 188 | if (VMap.count(OldOperand)) { |
| 189 | Value *NewOperand = VMap[OldOperand]; |
| 190 | |
| 191 | // Insert a cast if types are different |
| 192 | if (OldOperand->getType()->getScalarSizeInBits() |
| 193 | < NewOperand->getType()->getScalarSizeInBits()) |
| 194 | NewOperand = Builder.CreateTruncOrBitCast(NewOperand, |
| 195 | OldOperand->getType()); |
| 196 | |
| 197 | return NewOperand; |
| 198 | } |
| 199 | |
| 200 | // Instructions calculated in the current BB. |
| 201 | if (BBMap.count(OldOperand)) { |
| 202 | return BBMap[OldOperand]; |
| 203 | } |
| 204 | |
| 205 | // Ignore instructions that are referencing ops in the old BB. These |
| 206 | // instructions are unused. They where replace by new ones during |
| 207 | // createIndependentBlocks(). |
| 208 | if (getRegion().contains(OpInst->getParent())) |
| 209 | return NULL; |
| 210 | |
| 211 | return const_cast<Value*>(OldOperand); |
| 212 | } |
| 213 | |
| 214 | const Type *getVectorPtrTy(const Value *V, int vectorWidth) { |
| 215 | const PointerType *pointerType = dyn_cast<PointerType>(V->getType()); |
| 216 | assert(pointerType && "PointerType expected"); |
| 217 | |
| 218 | const Type *scalarType = pointerType->getElementType(); |
| 219 | VectorType *vectorType = VectorType::get(scalarType, vectorWidth); |
| 220 | |
| 221 | return PointerType::getUnqual(vectorType); |
| 222 | } |
| 223 | |
| 224 | /// @brief Load a vector from a set of adjacent scalars |
| 225 | /// |
| 226 | /// In case a set of scalars is known to be next to each other in memory, |
| 227 | /// create a vector load that loads those scalars |
| 228 | /// |
| 229 | /// %vector_ptr= bitcast double* %p to <4 x double>* |
| 230 | /// %vec_full = load <4 x double>* %vector_ptr |
| 231 | /// |
| 232 | Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap, |
| 233 | int size) { |
| 234 | const Value *pointer = load->getPointerOperand(); |
| 235 | const Type *vectorPtrType = getVectorPtrTy(pointer, size); |
| 236 | Value *newPointer = getOperand(pointer, BBMap); |
| 237 | Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType, |
| 238 | "vector_ptr"); |
| 239 | LoadInst *VecLoad = Builder.CreateLoad(VectorPtr, |
| 240 | load->getNameStr() |
| 241 | + "_p_vec_full"); |
| 242 | if (!Aligned) |
| 243 | VecLoad->setAlignment(8); |
| 244 | |
| 245 | return VecLoad; |
| 246 | } |
| 247 | |
| 248 | /// @brief Load a vector initialized from a single scalar in memory |
| 249 | /// |
| 250 | /// In case all elements of a vector are initialized to the same |
| 251 | /// scalar value, this value is loaded and shuffeled into all elements |
| 252 | /// of the vector. |
| 253 | /// |
| 254 | /// %splat_one = load <1 x double>* %p |
| 255 | /// %splat = shufflevector <1 x double> %splat_one, <1 x |
| 256 | /// double> %splat_one, <4 x i32> zeroinitializer |
| 257 | /// |
| 258 | Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap, |
| 259 | int size) { |
| 260 | const Value *pointer = load->getPointerOperand(); |
| 261 | const Type *vectorPtrType = getVectorPtrTy(pointer, 1); |
| 262 | Value *newPointer = getOperand(pointer, BBMap); |
| 263 | Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType, |
| 264 | load->getNameStr() + "_p_vec_p"); |
| 265 | LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr, |
| 266 | load->getNameStr() + "_p_splat_one"); |
| 267 | |
| 268 | if (!Aligned) |
| 269 | scalarLoad->setAlignment(8); |
| 270 | |
| 271 | std::vector<Constant*> splat; |
| 272 | |
| 273 | for (int i = 0; i < size; i++) |
| 274 | splat.push_back (Builder.getInt32(0)); |
| 275 | |
| 276 | Constant *splatVector = ConstantVector::get(splat); |
| 277 | |
| 278 | Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad, |
| 279 | splatVector, |
| 280 | load->getNameStr() |
| 281 | + "_p_splat"); |
| 282 | return vectorLoad; |
| 283 | } |
| 284 | |
| 285 | /// @Load a vector from scalars distributed in memory |
| 286 | /// |
| 287 | /// In case some scalars a distributed randomly in memory. Create a vector |
| 288 | /// by loading each scalar and by inserting one after the other into the |
| 289 | /// vector. |
| 290 | /// |
| 291 | /// %scalar_1= load double* %p_1 |
| 292 | /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0 |
| 293 | /// %scalar 2 = load double* %p_2 |
| 294 | /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1 |
| 295 | /// |
| 296 | Value *generateUnknownStrideLoad(const LoadInst *load, |
| 297 | VectorValueMapT &scalarMaps, |
| 298 | int size) { |
| 299 | const Value *pointer = load->getPointerOperand(); |
| 300 | VectorType *vectorType = VectorType::get( |
| 301 | dyn_cast<PointerType>(pointer->getType())->getElementType(), size); |
| 302 | |
| 303 | Value *vector = UndefValue::get(vectorType); |
| 304 | |
| 305 | for (int i = 0; i < size; i++) { |
| 306 | Value *newPointer = getOperand(pointer, scalarMaps[i]); |
| 307 | Value *scalarLoad = Builder.CreateLoad(newPointer, |
| 308 | load->getNameStr() + "_p_scalar_"); |
| 309 | vector = Builder.CreateInsertElement(vector, scalarLoad, |
| 310 | Builder.getInt32(i), |
| 311 | load->getNameStr() + "_p_vec_"); |
| 312 | } |
| 313 | |
| 314 | return vector; |
| 315 | } |
| 316 | |
| 317 | Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) { |
| 318 | const Value *pointer = load->getPointerOperand(); |
| 319 | Value *newPointer = getOperand(pointer, BBMap); |
| 320 | Value *scalarLoad = Builder.CreateLoad(newPointer, |
| 321 | load->getNameStr() + "_p_scalar_"); |
| 322 | return scalarLoad; |
| 323 | } |
| 324 | |
| 325 | /// @brief Load a value (or several values as a vector) from memory. |
| 326 | void generateLoad(const LoadInst *load, ValueMapT &vectorMap, |
| 327 | VectorValueMapT &scalarMaps, int vectorWidth) { |
| 328 | |
| 329 | if (scalarMaps.size() == 1) { |
| 330 | scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]); |
| 331 | return; |
| 332 | } |
| 333 | |
| 334 | Value *newLoad; |
| 335 | |
| 336 | MemoryAccess &Access = statement.getAccessFor(load); |
| 337 | |
| 338 | assert(scatteringDomain && "No scattering domain available"); |
| 339 | |
| 340 | if (Access.isStrideZero(scatteringDomain)) |
| 341 | newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth); |
| 342 | else if (Access.isStrideOne(scatteringDomain)) |
| 343 | newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth); |
| 344 | else |
| 345 | newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth); |
| 346 | |
| 347 | vectorMap[load] = newLoad; |
| 348 | } |
| 349 | |
| 350 | void copyInstruction(const Instruction *Inst, ValueMapT &BBMap, |
| 351 | ValueMapT &vectorMap, VectorValueMapT &scalarMaps, |
| 352 | int vectorDimension, int vectorWidth) { |
| 353 | // If this instruction is already in the vectorMap, a vector instruction |
| 354 | // was already issued, that calculates the values of all dimensions. No |
| 355 | // need to create any more instructions. |
| 356 | if (vectorMap.count(Inst)) |
| 357 | return; |
| 358 | |
| 359 | // Terminator instructions control the control flow. They are explicitally |
| 360 | // expressed in the clast and do not need to be copied. |
| 361 | if (Inst->isTerminator()) |
| 362 | return; |
| 363 | |
| 364 | if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) { |
| 365 | generateLoad(load, vectorMap, scalarMaps, vectorWidth); |
| 366 | return; |
| 367 | } |
| 368 | |
| 369 | if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst)) { |
| 370 | Value *opZero = Inst->getOperand(0); |
| 371 | Value *opOne = Inst->getOperand(1); |
| 372 | |
| 373 | // This is an old instruction that can be ignored. |
| 374 | if (!opZero && !opOne) |
| 375 | return; |
| 376 | |
| 377 | bool isVectorOp = vectorMap.count(opZero) || vectorMap.count(opOne); |
| 378 | |
| 379 | if (isVectorOp && vectorDimension > 0) |
| 380 | return; |
| 381 | |
| 382 | Value *newOpZero, *newOpOne; |
| 383 | newOpZero = getOperand(opZero, BBMap, &vectorMap); |
| 384 | newOpOne = getOperand(opOne, BBMap, &vectorMap); |
| 385 | |
| 386 | |
| 387 | std::string name; |
| 388 | if (isVectorOp) { |
| 389 | newOpZero = makeVectorOperand(newOpZero, vectorWidth); |
| 390 | newOpOne = makeVectorOperand(newOpOne, vectorWidth); |
| 391 | name = Inst->getNameStr() + "p_vec"; |
| 392 | } else |
| 393 | name = Inst->getNameStr() + "p_sca"; |
| 394 | |
| 395 | Value *newInst = Builder.CreateBinOp(binaryInst->getOpcode(), newOpZero, |
| 396 | newOpOne, name); |
| 397 | if (isVectorOp) |
| 398 | vectorMap[Inst] = newInst; |
| 399 | else |
| 400 | BBMap[Inst] = newInst; |
| 401 | |
| 402 | return; |
| 403 | } |
| 404 | |
| 405 | if (const StoreInst *store = dyn_cast<StoreInst>(Inst)) { |
| 406 | if (vectorMap.count(store->getValueOperand()) > 0) { |
| 407 | |
| 408 | // We only need to generate one store if we are in vector mode. |
| 409 | if (vectorDimension > 0) |
| 410 | return; |
| 411 | |
| 412 | MemoryAccess &Access = statement.getAccessFor(store); |
| 413 | |
| 414 | assert(scatteringDomain && "No scattering domain available"); |
| 415 | |
| 416 | const Value *pointer = store->getPointerOperand(); |
| 417 | Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap); |
| 418 | |
| 419 | if (Access.isStrideOne(scatteringDomain)) { |
| 420 | const Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth); |
| 421 | Value *newPointer = getOperand(pointer, BBMap, &vectorMap); |
| 422 | |
| 423 | Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType, |
| 424 | "vector_ptr"); |
| 425 | StoreInst *Store = Builder.CreateStore(vector, VectorPtr); |
| 426 | |
| 427 | if (!Aligned) |
| 428 | Store->setAlignment(8); |
| 429 | } else { |
| 430 | for (unsigned i = 0; i < scalarMaps.size(); i++) { |
| 431 | Value *scalar = Builder.CreateExtractElement(vector, |
| 432 | Builder.getInt32(i)); |
| 433 | Value *newPointer = getOperand(pointer, scalarMaps[i]); |
| 434 | Builder.CreateStore(scalar, newPointer); |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | return; |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | Instruction *NewInst = Inst->clone(); |
| 443 | |
| 444 | // Copy the operands in temporary vector, as an in place update |
| 445 | // fails if an instruction is referencing the same operand twice. |
| 446 | std::vector<Value*> Operands(NewInst->op_begin(), NewInst->op_end()); |
| 447 | |
| 448 | // Replace old operands with the new ones. |
| 449 | for (std::vector<Value*>::iterator UI = Operands.begin(), |
| 450 | UE = Operands.end(); UI != UE; ++UI) { |
| 451 | Value *newOperand = getOperand(*UI, BBMap); |
| 452 | |
| 453 | if (!newOperand) { |
| 454 | assert(!isa<StoreInst>(NewInst) |
| 455 | && "Store instructions are always needed!"); |
| 456 | delete NewInst; |
| 457 | return; |
| 458 | } |
| 459 | |
| 460 | NewInst->replaceUsesOfWith(*UI, newOperand); |
| 461 | } |
| 462 | |
| 463 | Builder.Insert(NewInst); |
| 464 | BBMap[Inst] = NewInst; |
| 465 | |
| 466 | if (!NewInst->getType()->isVoidTy()) |
| 467 | NewInst->setName("p_" + Inst->getName()); |
| 468 | } |
| 469 | |
| 470 | int getVectorSize() { |
| 471 | return ValueMaps.size(); |
| 472 | } |
| 473 | |
| 474 | bool isVectorBlock() { |
| 475 | return getVectorSize() > 1; |
| 476 | } |
| 477 | |
| 478 | // Insert a copy of a basic block in the newly generated code. |
| 479 | // |
| 480 | // @param Builder The builder used to insert the code. It also specifies |
| 481 | // where to insert the code. |
| 482 | // @param BB The basic block to copy |
| 483 | // @param VMap A map returning for any old value its new equivalent. This |
| 484 | // is used to update the operands of the statements. |
| 485 | // For new statements a relation old->new is inserted in this |
| 486 | // map. |
| 487 | void copyBB(BasicBlock *BB, DominatorTree *DT) { |
| 488 | Function *F = Builder.GetInsertBlock()->getParent(); |
| 489 | LLVMContext &Context = F->getContext(); |
| 490 | BasicBlock *CopyBB = BasicBlock::Create(Context, |
| 491 | "polly.stmt_" + BB->getNameStr(), |
| 492 | F); |
| 493 | Builder.CreateBr(CopyBB); |
| 494 | DT->addNewBlock(CopyBB, Builder.GetInsertBlock()); |
| 495 | Builder.SetInsertPoint(CopyBB); |
| 496 | |
| 497 | // Create two maps that store the mapping from the original instructions of |
| 498 | // the old basic block to their copies in the new basic block. Those maps |
| 499 | // are basic block local. |
| 500 | // |
| 501 | // As vector code generation is supported there is one map for scalar values |
| 502 | // and one for vector values. |
| 503 | // |
| 504 | // In case we just do scalar code generation, the vectorMap is not used and |
| 505 | // the scalarMap has just one dimension, which contains the mapping. |
| 506 | // |
| 507 | // In case vector code generation is done, an instruction may either appear |
| 508 | // in the vector map once (as it is calculating >vectorwidth< values at a |
| 509 | // time. Or (if the values are calculated using scalar operations), it |
| 510 | // appears once in every dimension of the scalarMap. |
| 511 | VectorValueMapT scalarBlockMap(getVectorSize()); |
| 512 | ValueMapT vectorBlockMap; |
| 513 | |
| 514 | for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); |
| 515 | II != IE; ++II) |
| 516 | for (int i = 0; i < getVectorSize(); i++) { |
| 517 | if (isVectorBlock()) |
| 518 | VMap = ValueMaps[i]; |
| 519 | |
| 520 | copyInstruction(II, scalarBlockMap[i], vectorBlockMap, |
| 521 | scalarBlockMap, i, getVectorSize()); |
| 522 | } |
| 523 | } |
| 524 | }; |
| 525 | |
| 526 | /// Class to generate LLVM-IR that calculates the value of a clast_expr. |
| 527 | class ClastExpCodeGen { |
| 528 | IRBuilder<> &Builder; |
| 529 | const CharMapT *IVS; |
| 530 | |
| 531 | Value *codegen(const clast_name *e, const Type *Ty) { |
| 532 | CharMapT::const_iterator I = IVS->find(e->name); |
| 533 | |
| 534 | if (I != IVS->end()) |
| 535 | return Builder.CreateSExtOrBitCast(I->second, Ty); |
| 536 | else |
| 537 | llvm_unreachable("Clast name not found"); |
| 538 | } |
| 539 | |
| 540 | Value *codegen(const clast_term *e, const Type *Ty) { |
| 541 | APInt a = APInt_from_MPZ(e->val); |
| 542 | |
| 543 | Value *ConstOne = ConstantInt::get(Builder.getContext(), a); |
| 544 | ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty); |
| 545 | |
| 546 | if (e->var) { |
| 547 | Value *var = codegen(e->var, Ty); |
| 548 | return Builder.CreateMul(ConstOne, var); |
| 549 | } |
| 550 | |
| 551 | return ConstOne; |
| 552 | } |
| 553 | |
| 554 | Value *codegen(const clast_binary *e, const Type *Ty) { |
| 555 | Value *LHS = codegen(e->LHS, Ty); |
| 556 | |
| 557 | APInt RHS_AP = APInt_from_MPZ(e->RHS); |
| 558 | |
| 559 | Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP); |
| 560 | RHS = Builder.CreateSExtOrBitCast(RHS, Ty); |
| 561 | |
| 562 | switch (e->type) { |
| 563 | case clast_bin_mod: |
| 564 | return Builder.CreateSRem(LHS, RHS); |
| 565 | case clast_bin_fdiv: |
| 566 | { |
| 567 | // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d |
| 568 | Value *One = ConstantInt::get(Builder.getInt1Ty(), 1); |
| 569 | Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0); |
| 570 | One = Builder.CreateZExtOrBitCast(One, Ty); |
| 571 | Zero = Builder.CreateZExtOrBitCast(Zero, Ty); |
| 572 | Value *Sum1 = Builder.CreateSub(LHS, RHS); |
| 573 | Value *Sum2 = Builder.CreateAdd(Sum1, One); |
| 574 | Value *isNegative = Builder.CreateICmpSLT(LHS, Zero); |
| 575 | Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS); |
| 576 | return Builder.CreateSDiv(Dividend, RHS); |
| 577 | } |
| 578 | case clast_bin_cdiv: |
| 579 | { |
| 580 | // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d |
| 581 | Value *One = ConstantInt::get(Builder.getInt1Ty(), 1); |
| 582 | Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0); |
| 583 | One = Builder.CreateZExtOrBitCast(One, Ty); |
| 584 | Zero = Builder.CreateZExtOrBitCast(Zero, Ty); |
| 585 | Value *Sum1 = Builder.CreateAdd(LHS, RHS); |
| 586 | Value *Sum2 = Builder.CreateSub(Sum1, One); |
| 587 | Value *isNegative = Builder.CreateICmpSLT(LHS, Zero); |
| 588 | Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2); |
| 589 | return Builder.CreateSDiv(Dividend, RHS); |
| 590 | } |
| 591 | case clast_bin_div: |
| 592 | return Builder.CreateSDiv(LHS, RHS); |
| 593 | default: |
| 594 | llvm_unreachable("Unknown clast binary expression type"); |
| 595 | }; |
| 596 | } |
| 597 | |
| 598 | Value *codegen(const clast_reduction *r, const Type *Ty) { |
| 599 | assert(( r->type == clast_red_min |
| 600 | || r->type == clast_red_max |
| 601 | || r->type == clast_red_sum) |
| 602 | && "Clast reduction type not supported"); |
| 603 | Value *old = codegen(r->elts[0], Ty); |
| 604 | |
| 605 | for (int i=1; i < r->n; ++i) { |
| 606 | Value *exprValue = codegen(r->elts[i], Ty); |
| 607 | |
| 608 | switch (r->type) { |
| 609 | case clast_red_min: |
| 610 | { |
| 611 | Value *cmp = Builder.CreateICmpSLT(old, exprValue); |
| 612 | old = Builder.CreateSelect(cmp, old, exprValue); |
| 613 | break; |
| 614 | } |
| 615 | case clast_red_max: |
| 616 | { |
| 617 | Value *cmp = Builder.CreateICmpSGT(old, exprValue); |
| 618 | old = Builder.CreateSelect(cmp, old, exprValue); |
| 619 | break; |
| 620 | } |
| 621 | case clast_red_sum: |
| 622 | old = Builder.CreateAdd(old, exprValue); |
| 623 | break; |
| 624 | default: |
| 625 | llvm_unreachable("Clast unknown reduction type"); |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | return old; |
| 630 | } |
| 631 | |
| 632 | public: |
| 633 | |
| 634 | // A generator for clast expressions. |
| 635 | // |
| 636 | // @param B The IRBuilder that defines where the code to calculate the |
| 637 | // clast expressions should be inserted. |
| 638 | // @param IVMAP A Map that translates strings describing the induction |
| 639 | // variables to the Values* that represent these variables |
| 640 | // on the LLVM side. |
| 641 | ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {} |
| 642 | |
| 643 | // Generates code to calculate a given clast expression. |
| 644 | // |
| 645 | // @param e The expression to calculate. |
| 646 | // @return The Value that holds the result. |
| 647 | Value *codegen(const clast_expr *e, const Type *Ty) { |
| 648 | switch(e->type) { |
| 649 | case clast_expr_name: |
| 650 | return codegen((const clast_name *)e, Ty); |
| 651 | case clast_expr_term: |
| 652 | return codegen((const clast_term *)e, Ty); |
| 653 | case clast_expr_bin: |
| 654 | return codegen((const clast_binary *)e, Ty); |
| 655 | case clast_expr_red: |
| 656 | return codegen((const clast_reduction *)e, Ty); |
| 657 | default: |
| 658 | llvm_unreachable("Unknown clast expression!"); |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | // @brief Reset the CharMap. |
| 663 | // |
| 664 | // This function is called to reset the CharMap to new one, while generating |
| 665 | // OpenMP code. |
| 666 | void setIVS(CharMapT *IVSNew) { |
| 667 | IVS = IVSNew; |
| 668 | } |
| 669 | |
| 670 | }; |
| 671 | |
| 672 | class ClastStmtCodeGen { |
| 673 | // The Scop we code generate. |
| 674 | Scop *S; |
| 675 | ScalarEvolution &SE; |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 676 | DominatorTree *DT; |
Hongbin Zheng | 94c5df1 | 2011-05-06 02:38:20 +0000 | [diff] [blame] | 677 | ScopDetection *SD; |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 678 | Dependences *DP; |
| 679 | TargetData *TD; |
| 680 | |
| 681 | // The Builder specifies the current location to code generate at. |
| 682 | IRBuilder<> &Builder; |
| 683 | |
| 684 | // Map the Values from the old code to their counterparts in the new code. |
| 685 | ValueMapT ValueMap; |
| 686 | |
| 687 | // clastVars maps from the textual representation of a clast variable to its |
| 688 | // current *Value. clast variables are scheduling variables, original |
| 689 | // induction variables or parameters. They are used either in loop bounds or |
| 690 | // to define the statement instance that is executed. |
| 691 | // |
| 692 | // for (s = 0; s < n + 3; ++i) |
| 693 | // for (t = s; t < m; ++j) |
| 694 | // Stmt(i = s + 3 * m, j = t); |
| 695 | // |
| 696 | // {s,t,i,j,n,m} is the set of clast variables in this clast. |
| 697 | CharMapT *clastVars; |
| 698 | |
| 699 | // Codegenerator for clast expressions. |
| 700 | ClastExpCodeGen ExpGen; |
| 701 | |
| 702 | // Do we currently generate parallel code? |
| 703 | bool parallelCodeGeneration; |
| 704 | |
| 705 | std::vector<std::string> parallelLoops; |
| 706 | |
| 707 | public: |
| 708 | |
| 709 | const std::vector<std::string> &getParallelLoops() { |
| 710 | return parallelLoops; |
| 711 | } |
| 712 | |
| 713 | protected: |
| 714 | void codegen(const clast_assignment *a) { |
| 715 | (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS, |
| 716 | TD->getIntPtrType(Builder.getContext())); |
| 717 | } |
| 718 | |
| 719 | void codegen(const clast_assignment *a, ScopStmt *Statement, |
| 720 | unsigned Dimension, int vectorDim, |
| 721 | std::vector<ValueMapT> *VectorVMap = 0) { |
| 722 | Value *RHS = ExpGen.codegen(a->RHS, |
| 723 | TD->getIntPtrType(Builder.getContext())); |
| 724 | |
| 725 | assert(!a->LHS && "Statement assignments do not have left hand side"); |
| 726 | const PHINode *PN; |
| 727 | PN = Statement->getInductionVariableForDimension(Dimension); |
| 728 | const Value *V = PN; |
| 729 | |
| 730 | if (PN->getNumOperands() == 2) |
| 731 | V = *(PN->use_begin()); |
| 732 | |
| 733 | if (VectorVMap) |
| 734 | (*VectorVMap)[vectorDim][V] = RHS; |
| 735 | |
| 736 | ValueMap[V] = RHS; |
| 737 | } |
| 738 | |
| 739 | void codegenSubstitutions(const clast_stmt *Assignment, |
| 740 | ScopStmt *Statement, int vectorDim = 0, |
| 741 | std::vector<ValueMapT> *VectorVMap = 0) { |
| 742 | int Dimension = 0; |
| 743 | |
| 744 | while (Assignment) { |
| 745 | assert(CLAST_STMT_IS_A(Assignment, stmt_ass) |
| 746 | && "Substitions are expected to be assignments"); |
| 747 | codegen((const clast_assignment *)Assignment, Statement, Dimension, |
| 748 | vectorDim, VectorVMap); |
| 749 | Assignment = Assignment->next; |
| 750 | Dimension++; |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL, |
| 755 | const char *iterator = NULL, isl_set *scatteringDomain = 0) { |
| 756 | ScopStmt *Statement = (ScopStmt *)u->statement->usr; |
| 757 | BasicBlock *BB = Statement->getBasicBlock(); |
| 758 | |
| 759 | if (u->substitutions) |
| 760 | codegenSubstitutions(u->substitutions, Statement); |
| 761 | |
| 762 | int vectorDimensions = IVS ? IVS->size() : 1; |
| 763 | |
| 764 | VectorValueMapT VectorValueMap(vectorDimensions); |
| 765 | |
| 766 | if (IVS) { |
| 767 | assert (u->substitutions && "Substitutions expected!"); |
| 768 | int i = 0; |
| 769 | for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end(); |
| 770 | II != IE; ++II) { |
| 771 | (*clastVars)[iterator] = *II; |
| 772 | codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap); |
| 773 | i++; |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement, |
| 778 | scatteringDomain); |
| 779 | Generator.copyBB(BB, DT); |
| 780 | } |
| 781 | |
| 782 | void codegen(const clast_block *b) { |
| 783 | if (b->body) |
| 784 | codegen(b->body); |
| 785 | } |
| 786 | |
| 787 | /// @brief Create a classical sequential loop. |
| 788 | void codegenForSequential(const clast_for *f, Value *lowerBound = 0, |
| 789 | Value *upperBound = 0) { |
| 790 | APInt Stride = APInt_from_MPZ(f->stride); |
| 791 | PHINode *IV; |
| 792 | Value *IncrementedIV; |
| 793 | BasicBlock *AfterBB; |
| 794 | // The value of lowerbound and upperbound will be supplied, if this |
| 795 | // function is called while generating OpenMP code. Otherwise get |
| 796 | // the values. |
| 797 | assert(((lowerBound && upperBound) || (!lowerBound && !upperBound)) |
| 798 | && "Either give both bounds or none"); |
| 799 | if (lowerBound == 0 || upperBound == 0) { |
| 800 | lowerBound = ExpGen.codegen(f->LB, |
| 801 | TD->getIntPtrType(Builder.getContext())); |
| 802 | upperBound = ExpGen.codegen(f->UB, |
| 803 | TD->getIntPtrType(Builder.getContext())); |
| 804 | } |
| 805 | createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB, |
| 806 | IncrementedIV, DT); |
| 807 | |
| 808 | // Add loop iv to symbols. |
| 809 | (*clastVars)[f->iterator] = IV; |
| 810 | |
| 811 | if (f->body) |
| 812 | codegen(f->body); |
| 813 | |
| 814 | // Loop is finished, so remove its iv from the live symbols. |
| 815 | clastVars->erase(f->iterator); |
| 816 | |
| 817 | BasicBlock *HeaderBB = *pred_begin(AfterBB); |
| 818 | BasicBlock *LastBodyBB = Builder.GetInsertBlock(); |
| 819 | Builder.CreateBr(HeaderBB); |
| 820 | IV->addIncoming(IncrementedIV, LastBodyBB); |
| 821 | Builder.SetInsertPoint(AfterBB); |
| 822 | } |
| 823 | |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 824 | /// @brief Add a new definition of an openmp subfunction. |
| 825 | Function* addOpenMPSubfunction(Module *M) { |
| 826 | Function *F = Builder.GetInsertBlock()->getParent(); |
| 827 | const std::string &Name = F->getNameStr() + ".omp_subfn"; |
| 828 | |
| 829 | std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy()); |
| 830 | FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false); |
| 831 | Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M); |
Hongbin Zheng | 94c5df1 | 2011-05-06 02:38:20 +0000 | [diff] [blame] | 832 | // Do not run any polly pass on the new function. |
| 833 | SD->markFunctionAsInvalid(FN); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 834 | |
| 835 | Function::arg_iterator AI = FN->arg_begin(); |
| 836 | AI->setName("omp.userContext"); |
| 837 | |
| 838 | return FN; |
| 839 | } |
| 840 | |
| 841 | /// @brief Add values to the OpenMP structure. |
| 842 | /// |
| 843 | /// Create the subfunction structure and add the values from the list. |
| 844 | Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals, |
| 845 | Function *SubFunction) { |
| 846 | Module *M = Builder.GetInsertBlock()->getParent()->getParent(); |
| 847 | std::vector<const Type*> structMembers; |
| 848 | |
| 849 | // Create the structure. |
| 850 | for (unsigned i = 0; i < OMPDataVals.size(); i++) |
| 851 | structMembers.push_back(OMPDataVals[i]->getType()); |
| 852 | |
| 853 | const std::string &Name = SubFunction->getNameStr() + ".omp.userContext"; |
| 854 | StructType *structTy = StructType::get(Builder.getContext(), |
| 855 | structMembers); |
| 856 | M->addTypeName(Name, structTy); |
| 857 | |
| 858 | // Store the values into the structure. |
| 859 | Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext"); |
| 860 | for (unsigned i = 0; i < OMPDataVals.size(); i++) { |
| 861 | Value *storeAddr = Builder.CreateStructGEP(structData, i); |
| 862 | Builder.CreateStore(OMPDataVals[i], storeAddr); |
| 863 | } |
| 864 | |
| 865 | return structData; |
| 866 | } |
| 867 | |
| 868 | /// @brief Create OpenMP structure values. |
| 869 | /// |
| 870 | /// Create a list of values that has to be stored into the subfuncition |
| 871 | /// structure. |
| 872 | SetVector<Value*> createOpenMPStructValues() { |
| 873 | SetVector<Value*> OMPDataVals; |
| 874 | |
| 875 | // Push the clast variables available in the clastVars. |
| 876 | for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end(); |
| 877 | I != E; I++) |
| 878 | OMPDataVals.insert(I->second); |
| 879 | |
| 880 | // Push the base addresses of memory references. |
| 881 | for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) { |
| 882 | ScopStmt *Stmt = *SI; |
| 883 | for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(), |
| 884 | E = Stmt->memacc_end(); I != E; ++I) { |
| 885 | Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr()); |
| 886 | OMPDataVals.insert((BaseAddr)); |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | return OMPDataVals; |
| 891 | } |
| 892 | |
| 893 | /// @brief Extract the values from the subfunction parameter. |
| 894 | /// |
| 895 | /// Extract the values from the subfunction parameter and update the clast |
| 896 | /// variables to point to the new values. |
| 897 | void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP, |
| 898 | SetVector<Value*> OMPDataVals, |
| 899 | Value *userContext) { |
| 900 | // Extract the clast variables. |
| 901 | unsigned i = 0; |
| 902 | for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end(); |
| 903 | I != E; I++) { |
| 904 | Value *loadAddr = Builder.CreateStructGEP(userContext, i); |
| 905 | (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr); |
| 906 | i++; |
| 907 | } |
| 908 | |
| 909 | // Extract the base addresses of memory references. |
| 910 | for (unsigned j = i; j < OMPDataVals.size(); j++) { |
| 911 | Value *loadAddr = Builder.CreateStructGEP(userContext, j); |
| 912 | Value *baseAddr = OMPDataVals[j]; |
| 913 | ValueMap[baseAddr] = Builder.CreateLoad(loadAddr); |
| 914 | } |
| 915 | |
| 916 | } |
| 917 | |
| 918 | /// @brief Add body to the subfunction. |
| 919 | void addOpenMPSubfunctionBody(Function *FN, const clast_for *f, |
| 920 | Value *structData, |
| 921 | SetVector<Value*> OMPDataVals) { |
| 922 | Module *M = Builder.GetInsertBlock()->getParent()->getParent(); |
| 923 | LLVMContext &Context = FN->getContext(); |
| 924 | const IntegerType *intPtrTy = TD->getIntPtrType(Context); |
| 925 | |
| 926 | // Store the previous basic block. |
| 927 | BasicBlock *PrevBB = Builder.GetInsertBlock(); |
| 928 | |
| 929 | // Create basic blocks. |
| 930 | BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN); |
| 931 | BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN); |
| 932 | BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN); |
| 933 | BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds", |
| 934 | FN); |
| 935 | |
| 936 | DT->addNewBlock(HeaderBB, PrevBB); |
| 937 | DT->addNewBlock(ExitBB, HeaderBB); |
| 938 | DT->addNewBlock(checkNextBB, HeaderBB); |
| 939 | DT->addNewBlock(loadIVBoundsBB, HeaderBB); |
| 940 | |
| 941 | // Fill up basic block HeaderBB. |
| 942 | Builder.SetInsertPoint(HeaderBB); |
| 943 | Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0, |
| 944 | "omp.lowerBoundPtr"); |
| 945 | Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0, |
| 946 | "omp.upperBoundPtr"); |
| 947 | Value *userContext = Builder.CreateBitCast(FN->arg_begin(), |
| 948 | structData->getType(), |
| 949 | "omp.userContext"); |
| 950 | |
| 951 | CharMapT clastVarsOMP; |
| 952 | extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext); |
| 953 | |
| 954 | Builder.CreateBr(checkNextBB); |
| 955 | |
| 956 | // Add code to check if another set of iterations will be executed. |
| 957 | Builder.SetInsertPoint(checkNextBB); |
| 958 | Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next"); |
| 959 | Value *ret1 = Builder.CreateCall2(runtimeNextFunction, |
| 960 | lowerBoundPtr, upperBoundPtr); |
| 961 | Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(), |
| 962 | "omp.hasNextScheduleBlock"); |
| 963 | Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB); |
| 964 | |
| 965 | // Add code to to load the iv bounds for this set of iterations. |
| 966 | Builder.SetInsertPoint(loadIVBoundsBB); |
| 967 | Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound"); |
| 968 | Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound"); |
| 969 | |
| 970 | // Subtract one as the upper bound provided by openmp is a < comparison |
| 971 | // whereas the codegenForSequential function creates a <= comparison. |
| 972 | upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1), |
| 973 | "omp.upperBoundAdjusted"); |
| 974 | |
| 975 | // Use clastVarsOMP during code generation of the OpenMP subfunction. |
| 976 | CharMapT *oldClastVars = clastVars; |
| 977 | clastVars = &clastVarsOMP; |
| 978 | ExpGen.setIVS(&clastVarsOMP); |
| 979 | |
| 980 | codegenForSequential(f, lowerBound, upperBound); |
| 981 | |
| 982 | // Restore the old clastVars. |
| 983 | clastVars = oldClastVars; |
| 984 | ExpGen.setIVS(oldClastVars); |
| 985 | |
| 986 | Builder.CreateBr(checkNextBB); |
| 987 | |
| 988 | // Add code to terminate this openmp subfunction. |
| 989 | Builder.SetInsertPoint(ExitBB); |
| 990 | Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait"); |
| 991 | Builder.CreateCall(endnowaitFunction); |
| 992 | Builder.CreateRetVoid(); |
| 993 | |
| 994 | // Restore the builder back to previous basic block. |
| 995 | Builder.SetInsertPoint(PrevBB); |
| 996 | } |
| 997 | |
| 998 | /// @brief Create an OpenMP parallel for loop. |
| 999 | /// |
| 1000 | /// This loop reflects a loop as if it would have been created by an OpenMP |
| 1001 | /// statement. |
| 1002 | void codegenForOpenMP(const clast_for *f) { |
| 1003 | Module *M = Builder.GetInsertBlock()->getParent()->getParent(); |
| 1004 | const IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext()); |
| 1005 | |
| 1006 | Function *SubFunction = addOpenMPSubfunction(M); |
| 1007 | SetVector<Value*> OMPDataVals = createOpenMPStructValues(); |
| 1008 | Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction); |
| 1009 | |
| 1010 | addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals); |
| 1011 | |
| 1012 | // Create call for GOMP_parallel_loop_runtime_start. |
| 1013 | Value *subfunctionParam = Builder.CreateBitCast(structData, |
| 1014 | Builder.getInt8PtrTy(), |
| 1015 | "omp_data"); |
| 1016 | |
| 1017 | Value *numberOfThreads = Builder.getInt32(0); |
| 1018 | Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy); |
| 1019 | Value *upperBound = ExpGen.codegen(f->UB, intPtrTy); |
| 1020 | |
| 1021 | // Add one as the upper bound provided by openmp is a < comparison |
| 1022 | // whereas the codegenForSequential function creates a <= comparison. |
| 1023 | upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1)); |
| 1024 | APInt APStride = APInt_from_MPZ(f->stride); |
| 1025 | Value *stride = ConstantInt::get(intPtrTy, |
| 1026 | APStride.zext(intPtrTy->getBitWidth())); |
| 1027 | |
| 1028 | SmallVector<Value *, 6> Arguments; |
| 1029 | Arguments.push_back(SubFunction); |
| 1030 | Arguments.push_back(subfunctionParam); |
| 1031 | Arguments.push_back(numberOfThreads); |
| 1032 | Arguments.push_back(lowerBound); |
| 1033 | Arguments.push_back(upperBound); |
| 1034 | Arguments.push_back(stride); |
| 1035 | |
| 1036 | Function *parallelStartFunction = |
| 1037 | M->getFunction("GOMP_parallel_loop_runtime_start"); |
| 1038 | Builder.CreateCall(parallelStartFunction, Arguments.begin(), |
| 1039 | Arguments.end()); |
| 1040 | |
| 1041 | // Create call to the subfunction. |
| 1042 | Builder.CreateCall(SubFunction, subfunctionParam); |
| 1043 | |
| 1044 | // Create call for GOMP_parallel_end. |
| 1045 | Function *FN = M->getFunction("GOMP_parallel_end"); |
| 1046 | Builder.CreateCall(FN); |
| 1047 | } |
| 1048 | |
| 1049 | bool isInnermostLoop(const clast_for *f) { |
| 1050 | const clast_stmt *stmt = f->body; |
| 1051 | |
| 1052 | while (stmt) { |
| 1053 | if (!CLAST_STMT_IS_A(stmt, stmt_user)) |
| 1054 | return false; |
| 1055 | |
| 1056 | stmt = stmt->next; |
| 1057 | } |
| 1058 | |
| 1059 | return true; |
| 1060 | } |
| 1061 | |
| 1062 | /// @brief Get the number of loop iterations for this loop. |
| 1063 | /// @param f The clast for loop to check. |
| 1064 | int getNumberOfIterations(const clast_for *f) { |
| 1065 | isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain)); |
| 1066 | isl_set *tmp = isl_set_copy(loopDomain); |
| 1067 | |
| 1068 | // Calculate a map similar to the identity map, but with the last input |
| 1069 | // and output dimension not related. |
| 1070 | // [i0, i1, i2, i3] -> [i0, i1, i2, o0] |
| 1071 | isl_dim *dim = isl_set_get_dim(loopDomain); |
| 1072 | dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1); |
| 1073 | dim = isl_dim_map_from_set(dim); |
| 1074 | isl_map *identity = isl_map_identity(dim); |
| 1075 | identity = isl_map_add_dims(identity, isl_dim_in, 1); |
| 1076 | identity = isl_map_add_dims(identity, isl_dim_out, 1); |
| 1077 | |
| 1078 | isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain); |
| 1079 | map = isl_map_intersect(map, identity); |
| 1080 | |
| 1081 | isl_map *lexmax = isl_map_lexmax(isl_map_copy(map)); |
| 1082 | isl_map *lexmin = isl_map_lexmin(isl_map_copy(map)); |
| 1083 | isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin)); |
| 1084 | |
| 1085 | isl_set *elements = isl_map_range(sub); |
| 1086 | |
| 1087 | if (!isl_set_is_singleton(elements)) |
| 1088 | return -1; |
| 1089 | |
| 1090 | isl_point *p = isl_set_sample_point(elements); |
| 1091 | |
| 1092 | isl_int v; |
| 1093 | isl_int_init(v); |
| 1094 | isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v); |
| 1095 | int numberIterations = isl_int_get_si(v); |
| 1096 | isl_int_clear(v); |
| 1097 | |
| 1098 | return (numberIterations) / isl_int_get_si(f->stride) + 1; |
| 1099 | } |
| 1100 | |
| 1101 | /// @brief Create vector instructions for this loop. |
| 1102 | void codegenForVector(const clast_for *f) { |
| 1103 | DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";); |
| 1104 | int vectorWidth = getNumberOfIterations(f); |
| 1105 | |
| 1106 | Value *LB = ExpGen.codegen(f->LB, |
| 1107 | TD->getIntPtrType(Builder.getContext())); |
| 1108 | |
| 1109 | APInt Stride = APInt_from_MPZ(f->stride); |
| 1110 | const IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType()); |
| 1111 | Stride = Stride.zext(LoopIVType->getBitWidth()); |
| 1112 | Value *StrideValue = ConstantInt::get(LoopIVType, Stride); |
| 1113 | |
| 1114 | std::vector<Value*> IVS(vectorWidth); |
| 1115 | IVS[0] = LB; |
| 1116 | |
| 1117 | for (int i = 1; i < vectorWidth; i++) |
| 1118 | IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv"); |
| 1119 | |
| 1120 | isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain); |
| 1121 | |
| 1122 | // Add loop iv to symbols. |
| 1123 | (*clastVars)[f->iterator] = LB; |
| 1124 | |
| 1125 | const clast_stmt *stmt = f->body; |
| 1126 | |
| 1127 | while (stmt) { |
| 1128 | codegen((const clast_user_stmt *)stmt, &IVS, f->iterator, |
| 1129 | scatteringDomain); |
| 1130 | stmt = stmt->next; |
| 1131 | } |
| 1132 | |
| 1133 | // Loop is finished, so remove its iv from the live symbols. |
| 1134 | clastVars->erase(f->iterator); |
| 1135 | } |
| 1136 | |
| 1137 | void codegen(const clast_for *f) { |
Hongbin Zheng | dbdebe2 | 2011-05-03 13:46:58 +0000 | [diff] [blame] | 1138 | if (Vector && isInnermostLoop(f) && DP->isParallelFor(f) |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1139 | && (-1 != getNumberOfIterations(f)) |
| 1140 | && (getNumberOfIterations(f) <= 16)) { |
| 1141 | codegenForVector(f); |
Hongbin Zheng | dbdebe2 | 2011-05-03 13:46:58 +0000 | [diff] [blame] | 1142 | } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) { |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1143 | parallelCodeGeneration = true; |
| 1144 | parallelLoops.push_back(f->iterator); |
| 1145 | codegenForOpenMP(f); |
| 1146 | parallelCodeGeneration = false; |
| 1147 | } else |
| 1148 | codegenForSequential(f); |
| 1149 | } |
| 1150 | |
| 1151 | Value *codegen(const clast_equation *eq) { |
| 1152 | Value *LHS = ExpGen.codegen(eq->LHS, |
| 1153 | TD->getIntPtrType(Builder.getContext())); |
| 1154 | Value *RHS = ExpGen.codegen(eq->RHS, |
| 1155 | TD->getIntPtrType(Builder.getContext())); |
| 1156 | CmpInst::Predicate P; |
| 1157 | |
| 1158 | if (eq->sign == 0) |
| 1159 | P = ICmpInst::ICMP_EQ; |
| 1160 | else if (eq->sign > 0) |
| 1161 | P = ICmpInst::ICMP_SGE; |
| 1162 | else |
| 1163 | P = ICmpInst::ICMP_SLE; |
| 1164 | |
| 1165 | return Builder.CreateICmp(P, LHS, RHS); |
| 1166 | } |
| 1167 | |
| 1168 | void codegen(const clast_guard *g) { |
| 1169 | Function *F = Builder.GetInsertBlock()->getParent(); |
| 1170 | LLVMContext &Context = F->getContext(); |
| 1171 | BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F); |
| 1172 | BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F); |
| 1173 | DT->addNewBlock(ThenBB, Builder.GetInsertBlock()); |
| 1174 | DT->addNewBlock(MergeBB, Builder.GetInsertBlock()); |
| 1175 | |
| 1176 | Value *Predicate = codegen(&(g->eq[0])); |
| 1177 | |
| 1178 | for (int i = 1; i < g->n; ++i) { |
| 1179 | Value *TmpPredicate = codegen(&(g->eq[i])); |
| 1180 | Predicate = Builder.CreateAnd(Predicate, TmpPredicate); |
| 1181 | } |
| 1182 | |
| 1183 | Builder.CreateCondBr(Predicate, ThenBB, MergeBB); |
| 1184 | Builder.SetInsertPoint(ThenBB); |
| 1185 | |
| 1186 | codegen(g->then); |
| 1187 | |
| 1188 | Builder.CreateBr(MergeBB); |
| 1189 | Builder.SetInsertPoint(MergeBB); |
| 1190 | } |
| 1191 | |
| 1192 | void codegen(const clast_stmt *stmt) { |
| 1193 | if (CLAST_STMT_IS_A(stmt, stmt_root)) |
| 1194 | assert(false && "No second root statement expected"); |
| 1195 | else if (CLAST_STMT_IS_A(stmt, stmt_ass)) |
| 1196 | codegen((const clast_assignment *)stmt); |
| 1197 | else if (CLAST_STMT_IS_A(stmt, stmt_user)) |
| 1198 | codegen((const clast_user_stmt *)stmt); |
| 1199 | else if (CLAST_STMT_IS_A(stmt, stmt_block)) |
| 1200 | codegen((const clast_block *)stmt); |
| 1201 | else if (CLAST_STMT_IS_A(stmt, stmt_for)) |
| 1202 | codegen((const clast_for *)stmt); |
| 1203 | else if (CLAST_STMT_IS_A(stmt, stmt_guard)) |
| 1204 | codegen((const clast_guard *)stmt); |
| 1205 | |
| 1206 | if (stmt->next) |
| 1207 | codegen(stmt->next); |
| 1208 | } |
| 1209 | |
| 1210 | void addParameters(const CloogNames *names) { |
| 1211 | SCEVExpander Rewriter(SE); |
| 1212 | |
| 1213 | // Create an instruction that specifies the location where the parameters |
| 1214 | // are expanded. |
| 1215 | CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()), |
| 1216 | Builder.getInt16Ty(), false, "insertInst", |
| 1217 | Builder.GetInsertBlock()); |
| 1218 | |
| 1219 | int i = 0; |
| 1220 | for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end(); |
| 1221 | PI != PE; ++PI) { |
| 1222 | assert(i < names->nb_parameters && "Not enough parameter names"); |
| 1223 | |
| 1224 | const SCEV *Param = *PI; |
| 1225 | const Type *Ty = Param->getType(); |
| 1226 | |
| 1227 | Instruction *insertLocation = --(Builder.GetInsertBlock()->end()); |
| 1228 | Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation); |
| 1229 | (*clastVars)[names->parameters[i]] = V; |
| 1230 | |
| 1231 | ++i; |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | public: |
| 1236 | void codegen(const clast_root *r) { |
| 1237 | clastVars = new CharMapT(); |
| 1238 | addParameters(r->names); |
| 1239 | ExpGen.setIVS(clastVars); |
| 1240 | |
| 1241 | parallelCodeGeneration = false; |
| 1242 | |
| 1243 | const clast_stmt *stmt = (const clast_stmt*) r; |
| 1244 | if (stmt->next) |
| 1245 | codegen(stmt->next); |
| 1246 | |
| 1247 | delete clastVars; |
| 1248 | } |
| 1249 | |
| 1250 | ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt, |
Hongbin Zheng | 94c5df1 | 2011-05-06 02:38:20 +0000 | [diff] [blame] | 1251 | ScopDetection *sd, Dependences *dp, TargetData *td, |
| 1252 | IRBuilder<> &B) : |
| 1253 | S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B), |
| 1254 | ExpGen(Builder, NULL) {} |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1255 | |
| 1256 | }; |
| 1257 | } |
| 1258 | |
| 1259 | namespace { |
| 1260 | class CodeGeneration : public ScopPass { |
| 1261 | Region *region; |
| 1262 | Scop *S; |
| 1263 | DominatorTree *DT; |
| 1264 | ScalarEvolution *SE; |
| 1265 | ScopDetection *SD; |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1266 | LoopInfo *LI; |
| 1267 | TargetData *TD; |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1268 | RegionInfo *RI; |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1269 | |
| 1270 | std::vector<std::string> parallelLoops; |
| 1271 | |
| 1272 | public: |
| 1273 | static char ID; |
| 1274 | |
| 1275 | CodeGeneration() : ScopPass(ID) {} |
| 1276 | |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1277 | // Adding prototypes required if OpenMP is enabled. |
| 1278 | void addOpenMPDefinitions(IRBuilder<> &Builder) |
| 1279 | { |
| 1280 | Module *M = Builder.GetInsertBlock()->getParent()->getParent(); |
| 1281 | LLVMContext &Context = Builder.getContext(); |
| 1282 | const IntegerType *intPtrTy = TD->getIntPtrType(Context); |
| 1283 | |
| 1284 | if (!M->getFunction("GOMP_parallel_end")) { |
| 1285 | FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false); |
| 1286 | Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M); |
| 1287 | } |
| 1288 | |
| 1289 | if (!M->getFunction("GOMP_parallel_loop_runtime_start")) { |
| 1290 | // Type of first argument. |
| 1291 | std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy()); |
| 1292 | FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments, |
| 1293 | false); |
| 1294 | PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy); |
| 1295 | |
| 1296 | std::vector<const Type*> args; |
| 1297 | args.push_back(FnPtrTy); |
| 1298 | args.push_back(Builder.getInt8PtrTy()); |
| 1299 | args.push_back(Builder.getInt32Ty()); |
| 1300 | args.push_back(intPtrTy); |
| 1301 | args.push_back(intPtrTy); |
| 1302 | args.push_back(intPtrTy); |
| 1303 | |
| 1304 | FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false); |
| 1305 | Function::Create(type, Function::ExternalLinkage, |
| 1306 | "GOMP_parallel_loop_runtime_start", M); |
| 1307 | } |
| 1308 | |
| 1309 | if (!M->getFunction("GOMP_loop_runtime_next")) { |
| 1310 | PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy); |
| 1311 | |
| 1312 | std::vector<const Type*> args; |
| 1313 | args.push_back(intLongPtrTy); |
| 1314 | args.push_back(intLongPtrTy); |
| 1315 | |
| 1316 | FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false); |
| 1317 | Function::Create(type, Function::ExternalLinkage, |
| 1318 | "GOMP_loop_runtime_next", M); |
| 1319 | } |
| 1320 | |
| 1321 | if (!M->getFunction("GOMP_loop_end_nowait")) { |
| 1322 | FunctionType *FT = FunctionType::get(Builder.getVoidTy(), |
| 1323 | std::vector<const Type*>(), false); |
| 1324 | Function::Create(FT, Function::ExternalLinkage, |
| 1325 | "GOMP_loop_end_nowait", M); |
| 1326 | } |
| 1327 | } |
| 1328 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1329 | // Split the entry edge of the region and generate a new basic block on this |
| 1330 | // edge. This function also updates ScopInfo and RegionInfo. |
| 1331 | // |
| 1332 | // @param region The region where the entry edge will be splitted. |
| 1333 | BasicBlock *splitEdgeAdvanced(Region *region) { |
| 1334 | BasicBlock *newBlock; |
| 1335 | BasicBlock *splitBlock; |
| 1336 | |
| 1337 | newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this); |
| 1338 | |
| 1339 | if (DT->dominates(region->getEntry(), newBlock)) { |
| 1340 | // Update ScopInfo. |
| 1341 | for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) |
| 1342 | if ((*SI)->getBasicBlock() == newBlock) { |
| 1343 | (*SI)->setBasicBlock(newBlock); |
| 1344 | break; |
| 1345 | } |
| 1346 | |
| 1347 | // Update RegionInfo. |
| 1348 | splitBlock = region->getEntry(); |
| 1349 | region->replaceEntry(newBlock); |
Tobias Grosser | 7a16c89 | 2011-05-14 19:01:55 +0000 | [diff] [blame] | 1350 | RI->setRegionFor(newBlock, region); |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1351 | } else { |
| 1352 | RI->setRegionFor(newBlock, region->getParent()); |
| 1353 | splitBlock = newBlock; |
| 1354 | } |
| 1355 | |
| 1356 | return splitBlock; |
| 1357 | } |
| 1358 | |
| 1359 | // Create a split block that branches either to the old code or to a new basic |
| 1360 | // block where the new code can be inserted. |
| 1361 | // |
| 1362 | // @param builder A builder that will be set to point to a basic block, where |
| 1363 | // the new code can be generated. |
| 1364 | // @return The split basic block. |
| 1365 | BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) { |
| 1366 | BasicBlock *splitBlock = splitEdgeAdvanced(region); |
| 1367 | |
| 1368 | splitBlock->setName("polly.enterScop"); |
| 1369 | |
| 1370 | Function *function = splitBlock->getParent(); |
| 1371 | BasicBlock *startBlock = BasicBlock::Create(function->getContext(), |
| 1372 | "polly.start", function); |
| 1373 | splitBlock->getTerminator()->eraseFromParent(); |
| 1374 | builder->SetInsertPoint(splitBlock); |
| 1375 | builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry()); |
| 1376 | DT->addNewBlock(startBlock, splitBlock); |
| 1377 | |
| 1378 | // Start code generation here. |
| 1379 | builder->SetInsertPoint(startBlock); |
| 1380 | return splitBlock; |
| 1381 | } |
| 1382 | |
| 1383 | // Merge the control flow of the newly generated code with the existing code. |
| 1384 | // |
| 1385 | // @param splitBlock The basic block where the control flow was split between |
| 1386 | // old and new version of the Scop. |
| 1387 | // @param builder An IRBuilder that points to the last instruction of the |
| 1388 | // newly generated code. |
| 1389 | void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) { |
| 1390 | BasicBlock *mergeBlock; |
| 1391 | Region *R = region; |
| 1392 | |
| 1393 | if (R->getExit()->getSinglePredecessor()) |
| 1394 | // No splitEdge required. A block with a single predecessor cannot have |
| 1395 | // PHI nodes that would complicate life. |
| 1396 | mergeBlock = R->getExit(); |
| 1397 | else { |
| 1398 | mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this); |
| 1399 | // SplitEdge will never split R->getExit(), as R->getExit() has more than |
| 1400 | // one predecessor. Hence, mergeBlock is always a newly generated block. |
| 1401 | mergeBlock->setName("polly.finalMerge"); |
| 1402 | R->replaceExit(mergeBlock); |
| 1403 | } |
| 1404 | |
| 1405 | builder->CreateBr(mergeBlock); |
| 1406 | |
| 1407 | if (DT->dominates(splitBlock, mergeBlock)) |
| 1408 | DT->changeImmediateDominator(mergeBlock, splitBlock); |
| 1409 | } |
| 1410 | |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1411 | bool runOnScop(Scop &scop) { |
| 1412 | S = &scop; |
| 1413 | region = &S->getRegion(); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1414 | DT = &getAnalysis<DominatorTree>(); |
| 1415 | Dependences *DP = &getAnalysis<Dependences>(); |
| 1416 | SE = &getAnalysis<ScalarEvolution>(); |
| 1417 | LI = &getAnalysis<LoopInfo>(); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1418 | SD = &getAnalysis<ScopDetection>(); |
| 1419 | TD = &getAnalysis<TargetData>(); |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1420 | RI = &getAnalysis<RegionInfo>(); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1421 | |
| 1422 | parallelLoops.clear(); |
| 1423 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1424 | assert(region->isSimple() && "Only simple regions are supported"); |
Tobias Grosser | 76d7c52 | 2011-05-14 19:01:37 +0000 | [diff] [blame] | 1425 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1426 | // In the CFG and we generate next to original code of the Scop the |
| 1427 | // optimized version. Both the new and the original version of the code |
| 1428 | // remain in the CFG. A branch statement decides which version is executed. |
| 1429 | // At the moment, we always execute the newly generated version (the old one |
| 1430 | // is dead code eliminated by the cleanup passes). Later we may decide to |
| 1431 | // execute the new version only under certain conditions. This will be the |
| 1432 | // case if we support constructs for which we cannot prove all assumptions |
| 1433 | // at compile time. |
| 1434 | // |
| 1435 | // Before transformation: |
| 1436 | // |
| 1437 | // bb0 |
| 1438 | // | |
| 1439 | // orig_scop |
| 1440 | // | |
| 1441 | // bb1 |
| 1442 | // |
| 1443 | // After transformation: |
| 1444 | // bb0 |
| 1445 | // | |
| 1446 | // polly.splitBlock |
| 1447 | // / \ |
| 1448 | // | startBlock |
| 1449 | // | | |
| 1450 | // orig_scop new_scop |
| 1451 | // \ / |
| 1452 | // \ / |
| 1453 | // bb1 (joinBlock) |
| 1454 | IRBuilder<> builder(region->getEntry()); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1455 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1456 | // The builder will be set to startBlock. |
| 1457 | BasicBlock *splitBlock = addSplitAndStartBlock(&builder); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1458 | |
| 1459 | if (OpenMP) |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1460 | addOpenMPDefinitions(builder); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1461 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1462 | ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder); |
Tobias Grosser | 3fdecae | 2011-05-14 19:02:39 +0000 | [diff] [blame^] | 1463 | CloogInfo &C = getAnalysis<CloogInfo>(); |
| 1464 | CodeGen.codegen(C.getClast()); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1465 | |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1466 | parallelLoops.insert(parallelLoops.begin(), |
| 1467 | CodeGen.getParallelLoops().begin(), |
| 1468 | CodeGen.getParallelLoops().end()); |
| 1469 | |
Tobias Grosser | 8c4cfc32 | 2011-05-14 19:01:49 +0000 | [diff] [blame] | 1470 | mergeControlFlow(splitBlock, &builder); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1471 | |
Tobias Grosser | abb6dcd | 2011-05-14 19:02:34 +0000 | [diff] [blame] | 1472 | return true; |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1473 | } |
| 1474 | |
| 1475 | virtual void printScop(raw_ostream &OS) const { |
| 1476 | for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(), |
| 1477 | PE = parallelLoops.end(); PI != PE; ++PI) |
| 1478 | OS << "Parallel loop with iterator '" << *PI << "' generated\n"; |
| 1479 | } |
| 1480 | |
| 1481 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 1482 | AU.addRequired<CloogInfo>(); |
| 1483 | AU.addRequired<Dependences>(); |
| 1484 | AU.addRequired<DominatorTree>(); |
| 1485 | AU.addRequired<ScalarEvolution>(); |
| 1486 | AU.addRequired<LoopInfo>(); |
| 1487 | AU.addRequired<RegionInfo>(); |
| 1488 | AU.addRequired<ScopDetection>(); |
| 1489 | AU.addRequired<ScopInfo>(); |
| 1490 | AU.addRequired<TargetData>(); |
| 1491 | |
| 1492 | AU.addPreserved<CloogInfo>(); |
| 1493 | AU.addPreserved<Dependences>(); |
| 1494 | AU.addPreserved<LoopInfo>(); |
| 1495 | AU.addPreserved<DominatorTree>(); |
Tobias Grosser | 7580537 | 2011-04-29 06:27:02 +0000 | [diff] [blame] | 1496 | AU.addPreserved<ScopDetection>(); |
| 1497 | AU.addPreserved<ScalarEvolution>(); |
| 1498 | AU.addPreserved<RegionInfo>(); |
| 1499 | AU.addPreserved<TempScopInfo>(); |
| 1500 | AU.addPreserved<ScopInfo>(); |
| 1501 | AU.addPreservedID(IndependentBlocksID); |
| 1502 | } |
| 1503 | }; |
| 1504 | } |
| 1505 | |
| 1506 | char CodeGeneration::ID = 1; |
| 1507 | |
| 1508 | static RegisterPass<CodeGeneration> |
| 1509 | Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information"); |
| 1510 | |
| 1511 | Pass* polly::createCodeGenerationPass() { |
| 1512 | return new CodeGeneration(); |
| 1513 | } |