Util.cpp 16.6 KB
Newer Older
1
#include <llvm/ADT/SmallVector.h>
guruhegde's avatar
guruhegde committed
2
#include <llvm/Bitcode/BitcodeWriter.h>
guruhegde's avatar
guruhegde committed
3
#include <llvm/IR/BasicBlock.h>
guruhegde's avatar
guruhegde committed
4
#include <llvm/IR/Function.h>
5
#include <llvm/IR/Instruction.h>
guruhegde's avatar
guruhegde committed
6
#include <llvm/IR/Instructions.h>
7
#include <llvm/IR/InstIterator.h>
8
#include <llvm/IR/IRBuilder.h>
guruhegde's avatar
guruhegde committed
9
#include <llvm/IR/Module.h>
guruhegde's avatar
guruhegde committed
10
#include <llvm/IRReader/IRReader.h>
11
#include <llvm/Support/Debug.h>
guruhegde's avatar
guruhegde committed
12
#include <llvm/Support/SourceMgr.h>
guruhegde's avatar
guruhegde committed
13
#include <llvm/Transforms/Utils/Cloning.h>
guruhegde's avatar
guruhegde committed
14

guruhegde's avatar
guruhegde committed
15 16 17 18 19
#include <llvm/Analysis/DominanceFrontier.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/Analysis/RegionInfo.h>


guruhegde's avatar
guruhegde committed
20
#include <memory.h>
21 22
#include <string>

guruhegde's avatar
guruhegde committed
23 24 25
#include "Util.h"

using namespace llvm;
guruhegde's avatar
guruhegde committed
26
using namespace std;
guruhegde's avatar
guruhegde committed
27 28 29

namespace tas {

guruhegde's avatar
guruhegde committed
30 31 32 33 34 35 36 37 38 39
// Information to decode annotation fields:
// Custom annotations added to the source code is stored as global value
// in LLVM IR under the identifer "llvm.global.annotations".
// This function adds the annotation identifier to the attribute list of
// Function object of in-memory IR. This facilitates applying function level
// transformation to the function of interest to us.
//
// Annotation list structure in IR: stored as array of struct
// ConstantArray : [Size x struct]
// struct def: [Function  ptr, GlobalVariable ptr, GlobalVariable ptr, i32]
guruhegde's avatar
guruhegde committed
40
// @llvm.global.annotations = [N x {i8*, i8*, *, i32}]
guruhegde's avatar
guruhegde committed
41 42 43 44 45 46
// N - number of global annotations in a module
// Struct members details:
// i8* - Function pointer
// i8* - Pointer to annotation string
// i8* - Pointer to file name string
// i32 - line number of annotation in source file
47

guruhegde's avatar
guruhegde committed
48
/// This function returns a map of Function and annotated string in the module.
guruhegde's avatar
guruhegde committed
49 50 51

static std::string VarAnnotationStr = "llvm.var.annotation";

guruhegde's avatar
guruhegde committed
52
void getAnnotatedFnList(Module * M, map<Function *, string> & FnList) {
guruhegde's avatar
guruhegde committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66
  auto AnnotationList = M->getNamedGlobal("llvm.global.annotations");
  if (!AnnotationList) return;

  auto CA = cast<ConstantArray>(AnnotationList->getOperand(0));
  for (unsigned int i = 0; i < CA->getNumOperands(); ++i) {
    auto CAStruct = cast<ConstantStruct>(CA->getOperand(i));
    auto CAFunc = dyn_cast<Function>(CAStruct->getOperand(0)->getOperand(0));
    if (!CAFunc) continue;
    auto CAAnnotation = cast<ConstantDataArray>(
        cast<GlobalVariable>(CAStruct->getOperand(1)->getOperand(0))->getOperand(0));
    FnList[CAFunc] = CAAnnotation->getAsCString();
  }
}

67 68
SmallVector<Value *, 4> detectExpPtrVars(Function * F) {
  SmallVector<Value *, 4> ExpensivePointers;
guruhegde's avatar
guruhegde committed
69 70 71
  auto varAnnotationIntrinsic = Function::lookupIntrinsicID("llvm.var.annotation");
  // XXX Checking only entry basic block for annotated variables.
  for (auto & I : F->front()) {
guruhegde's avatar
guruhegde committed
72 73
    auto * CI = dyn_cast<CallInst>(&I);
    if (CI == nullptr) continue;
guruhegde's avatar
guruhegde committed
74

guruhegde's avatar
guruhegde committed
75 76
    // Check whether var.annotation or not
    auto * Callee = CI->getCalledFunction();
guruhegde's avatar
guruhegde committed
77 78
    if (!Callee->isIntrinsic() ||
        Callee->getIntrinsicID() != varAnnotationIntrinsic) continue;
guruhegde's avatar
guruhegde committed
79

guruhegde's avatar
guruhegde committed
80 81 82 83
    // Get annotation string literal
    auto StringTag = cast<ConstantDataArray>(
        cast<GlobalVariable>(
          CI->getOperand(1)->stripPointerCasts())->getOperand(0))->getAsCString();
guruhegde's avatar
guruhegde committed
84

guruhegde's avatar
guruhegde committed
85
    if (StringTag.compare("expensive") == 0) {
guruhegde's avatar
guruhegde committed
86 87
      ExpensivePointers.push_back(
                           cast<BitCastInst>(CI->getArgOperand(0))->getOperand(0));
guruhegde's avatar
guruhegde committed
88 89
    }
  }
90 91

  return ExpensivePointers;
guruhegde's avatar
guruhegde committed
92 93
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
const LoadInst * findEarliestPointerDerefInstruction(Value * V) {
  const LoadInst * LU = nullptr;
  auto matchLoadPattern = [&] (const auto * U)
  {
    if (llvm::isa<LoadInst>(U)) {
      auto NextI = cast<LoadInst>(U)->getNextNode();
      if (isa<llvm::GetElementPtrInst>(NextI) && NextI->getOperand(0) == U) {
        LU = cast<LoadInst>(U);
      } else if (isa<LoadInst>(NextI) && NextI->getOperand(0) == U) {
        LU = cast<LoadInst>(U);
      }
    }
  };

  for_each(V->users(), matchLoadPattern);
  return LU;
}

guruhegde's avatar
guruhegde committed
112 113
SmallVector<LoadInst *, 4> detectExpPtrUses(SmallVectorImpl<Value *> & AnnotatedVars) {
  SmallVector<LoadInst *, 4> VarUsePoints;
114
  
guruhegde's avatar
guruhegde committed
115 116
  for_each(AnnotatedVars, [&]
      (const auto & Var) { 
117
        auto FU = findEarliestPointerDerefInstruction(Var);
guruhegde's avatar
guruhegde committed
118
        if (!FU) return;
119
        VarUsePoints.push_back(const_cast<LoadInst *>(FU));
guruhegde's avatar
guruhegde committed
120 121 122 123
      });
  return VarUsePoints;
}

guruhegde's avatar
guruhegde committed
124
Instruction * findBatchBeginMarkerInstruction(Function * F) {
guruhegde's avatar
guruhegde committed
125
  auto varAnnotIntrinsic = Function::lookupIntrinsicID("llvm.var.annotation");
guruhegde's avatar
guruhegde committed
126 127 128 129 130 131 132
  // XXX Checking only entry basic block for annotated variables.
  for (auto I = inst_begin(*F), E = inst_end(*F); I != E; ++I) {
    auto * CI = dyn_cast<CallInst>(&*I);
    if (CI == nullptr) continue;

    // Check whether var.annotation or not
    auto * Callee = CI->getCalledFunction();
guruhegde's avatar
guruhegde committed
133 134
    if (!Callee->isIntrinsic() ||
        Callee->getIntrinsicID() != varAnnotIntrinsic) continue;
guruhegde's avatar
guruhegde committed
135 136 137 138 139 140 141 142 143 144 145 146 147

    // Get annotation string literal
    auto StringTag = cast<ConstantDataArray>(
        cast<GlobalVariable>(
          CI->getOperand(1)->stripPointerCasts())->getOperand(0))->getAsCString();

    if (StringTag.compare("batch_begin") == 0) {
      return CI;
    }
  }
  return nullptr;
}

guruhegde's avatar
guruhegde committed
148
void detectBatchParameters(Function * F, SmallPtrSet<Value *, 4> & BatchParameters) {
guruhegde's avatar
guruhegde committed
149 150 151
  auto varAnnotationIntrinsic = Function::lookupIntrinsicID("llvm.var.annotation");
  // XXX Checking only entry basic block for annotated variables.
  for (auto & I : F->front()) {
guruhegde's avatar
guruhegde committed
152 153 154 155 156
    auto * CI = dyn_cast<CallInst>(&I);
    if (CI == nullptr) continue;

    // Check whether var.annotation or not
    auto * Callee = CI->getCalledFunction();
guruhegde's avatar
guruhegde committed
157 158
    if (!Callee->isIntrinsic() ||
        Callee->getIntrinsicID() != varAnnotationIntrinsic) continue;
guruhegde's avatar
guruhegde committed
159 160 161 162 163 164 165 166 167 168 169 170

    // Get annotation string literal
    auto StringTag = cast<ConstantDataArray>(
        cast<GlobalVariable>(
          CI->getOperand(1)->stripPointerCasts())->getOperand(0))->getAsCString();

    if (StringTag.compare("batch_arg") == 0) {
      auto AllocaVar = cast<BitCastInst>(CI->getArgOperand(0))->getOperand(0);
      for (auto & I : F->front()) {
        if (auto * Store = dyn_cast<StoreInst>(&I)) {
          if (Store->getPointerOperand() == AllocaVar)
            BatchParameters.insert(Store->getValueOperand());
guruhegde's avatar
guruhegde committed
171 172 173 174 175 176
        }
      }
    }
  }
}

guruhegde's avatar
guruhegde committed
177
void setAnnotationInFunctionObject(Module * M) {
178 179 180 181 182
  auto AnnotationList = M->getNamedGlobal("llvm.global.annotations");
  if (!AnnotationList) return;

  auto CA = cast<ConstantArray>(AnnotationList->getOperand(0));
  for (unsigned int i = 0; i < CA->getNumOperands(); ++i) {
183
    auto CAStruct = cast<ConstantStruct>(CA->getOperand(i));
184 185 186 187 188
    auto CAFunc = dyn_cast<Function>(CAStruct->getOperand(0)->getOperand(0));
    if (!CAFunc) continue;
    auto CAAnnotation = cast<ConstantDataArray>(
        cast<GlobalVariable>(CAStruct->getOperand(1)->getOperand(0))->getOperand(0));
    CAFunc->addFnAttr(CAAnnotation->getAsCString());
guruhegde's avatar
guruhegde committed
189 190 191
  }
}

guruhegde's avatar
guruhegde committed
192 193 194
void cloneLoopBasicBlocks(Function * F, Loop * L, ValueToValueMapTy & VMap) {
  SmallVector<BasicBlock *, 16> ClonedBlocks;
  for (auto * BB : L->blocks()) {
195
    auto * ClonedBlock = CloneBasicBlock(BB, VMap, "_clone");
guruhegde's avatar
guruhegde committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    VMap[BB] = ClonedBlock;
    ClonedBlocks.push_back(ClonedBlock);

    auto ExitBlock = L->getExitBlock();
    assert(ExitBlock != nullptr && "Support only loop with single exit edge");

    ClonedBlock->insertInto(F, ExitBlock);
  }
  remapInstructionsInBlocks(ClonedBlocks, VMap);

  // Set cloned loop as successor of old loop
  auto LoopExitingBlock = L->getExitingBlock();
  assert(LoopExitingBlock != nullptr && "Support only loop with single exit edge");
  auto LoopTerminator = LoopExitingBlock->getTerminator();
  assert(LoopTerminator != nullptr && "Loop Basicblock is not well formed");
  LoopTerminator->setSuccessor(1, ClonedBlocks.front());
}
213

214 215 216 217
void insertLLVMPrefetchIntrinsic(Function * F, Instruction * PtrAllocaUse) {
  IRBuilder<> Builder(PtrAllocaUse);
  auto Ptr = Builder.CreateLoad(PtrAllocaUse->getOperand(0), "prefetch_load");
  auto CastI = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy(), "prefetch1");
218 219 220 221 222 223 224 225 226 227 228 229

  // Add llvm prefetch intrinsic call.
  Type *I32 = Type::getInt32Ty(F->getContext());
  Value *PrefetchFunc = Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch);
  Builder.CreateCall(
      PrefetchFunc,
      {CastI, // Pointer Value
      ConstantInt::get(I32, 0), // read (0) or write (1)
      ConstantInt::get(I32, 3), // no_locality (0) to extreme temporal locality (3)
      ConstantInt::get(I32, 1)} // data (1) or instruction (0)
      );
}
guruhegde's avatar
guruhegde committed
230

guruhegde's avatar
guruhegde committed
231
/// Replace old value with new value within basic block.
guruhegde's avatar
guruhegde committed
232
void replaceUsesWithinBB(Value * From, Value * To, BasicBlock * BB) {
233 234 235 236 237
  auto UI = From->use_begin();
  while (UI != From->use_end()) {
    auto * Usr = dyn_cast<Instruction>(UI->getUser());
    if (Usr && Usr->getParent() != BB) {
      ++UI;
guruhegde's avatar
guruhegde committed
238
      continue;
239
    }
guruhegde's avatar
guruhegde committed
240 241
    // We should advance iterator first, because changing user
    // modifies use list hence invalidates the iterator.
guruhegde's avatar
guruhegde committed
242
    auto * U = &*UI++;
243
    U->set(To);
guruhegde's avatar
guruhegde committed
244 245
  }
}
246

guruhegde's avatar
guruhegde committed
247
/// Recursively compute the size of the struct
248 249 250 251 252 253 254 255 256 257 258
unsigned getTypeSizeInBits(Type * Ty) {
  if (!Ty->isAggregateType())
    return Ty->getPrimitiveSizeInBits();

  unsigned Total = 0;
  for (auto & subT : Ty->subtypes()) {
    Total += getTypeSizeInBits(subT);
  }
  return Total;
}

259 260 261 262 263 264 265 266 267
Value * createArray(Function * F, Type * Ty, unsigned size) {
  // Allocate temporary array
  IRBuilder<> Builder (F->getContext());
  auto BB = F->begin();
  auto TermI = (*BB).getTerminator();
  Builder.SetInsertPoint(TermI);
  return Builder.CreateAlloca(ArrayType::get(Ty, size));
}

268 269 270 271 272 273 274 275 276 277 278
template <typename InstType>
Instruction * findValueFirstUseInInstruction(Value * V) {
  InstType * FirstUse = nullptr;
  for (auto * U : V->users()) {
    if (auto * I = dyn_cast<InstType>(U)) {
      FirstUse = I;
    }
  }
  return FirstUse;
}

guruhegde's avatar
guruhegde committed
279 280
unsigned getGEPIndex(const GetElementPtrInst * GEP) {
  unsigned FieldIdx = 0;
guruhegde's avatar
guruhegde committed
281 282
  if (auto * CI = dyn_cast<ConstantInt>(
                   GEP->getOperand(GEP->getNumIndices()))) {
guruhegde's avatar
guruhegde committed
283 284 285 286 287 288 289
    FieldIdx = CI->getZExtValue();
  } else {
    assert (0 && "Value has to be constant expression!");
  }
  return FieldIdx;
}

guruhegde's avatar
guruhegde committed
290 291 292 293 294 295 296 297 298 299 300 301
StoreInst * findFirstUseInStoreInst(Value * V) {
  // User list is inverted, first user is at the end of the list.
  // Loop below finds first user which is StoreInst.
  StoreInst * SI = nullptr;
  for (auto * U : V->users()) {
    if (auto * I = dyn_cast<StoreInst>(U)) {
      SI = I;
    }
  }
  return SI;
}

guruhegde's avatar
guruhegde committed
302
void setSuccessor(BasicBlock * BB, BasicBlock * SuccBB, unsigned Idx) {
guruhegde's avatar
guruhegde committed
303
  auto TermI = BB->getTerminator();
guruhegde's avatar
guruhegde committed
304
  TermI->setSuccessor(Idx, SuccBB);
guruhegde's avatar
guruhegde committed
305 306
}

guruhegde's avatar
guruhegde committed
307 308 309 310 311 312 313 314 315 316 317
void cloneBasicBlocksInto(Function * From, Function * To) {
  // Store the mapping from old Value to new Value.
  ValueToValueMapTy VMap;
  auto ToArg = To->arg_begin();
  for (const Argument & FromArg : From->args()) {
    VMap[&FromArg] = &*ToArg++;
  }

  SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned
  CloneFunctionInto(To, From, VMap, From->getSubprogram() != nullptr, Returns);
}
318

319 320 321 322 323 324
void getReturnBlocks(Function * F, SmallVectorImpl<BasicBlock *> & Returns) {
  for (BasicBlock & BB : *F)
    if (isa<ReturnInst>(BB.getTerminator()))
      Returns.push_back(&BB);
}

325 326 327 328 329 330 331
void getReturnInstList(Function * F, SmallVectorImpl<ReturnInst *> & Result) {
  // Check all the return blocks.
  for (BasicBlock & BB : *F)
    if (isa<ReturnInst>(BB.getTerminator()))
      Result.push_back((cast<ReturnInst>(BB.getTerminator())));
}

guruhegde's avatar
guruhegde committed
332 333 334 335 336 337 338 339 340 341
string writeToBitCodeFile(Module & M) {
  // Write to bitcode file.
  std::error_code EC;
  auto Idx = M.getSourceFileName().find_last_of(".");
  auto OutFile = M.getSourceFileName().substr(0, Idx) + string(".bc");
  raw_fd_ostream OS(OutFile, EC, llvm::sys::fs::F_None);
  WriteBitcodeToFile(M, OS);
  OS.flush();
  return OutFile;
}
guruhegde's avatar
guruhegde committed
342 343 344 345 346 347 348 349 350 351 352

string writeToAsmFile(Module & M) {
  // Write to .ll file.
  std::error_code EC;
  auto Idx = M.getSourceFileName().find_last_of(".");
  auto OutFile = M.getSourceFileName().substr(0, Idx) + string(".ll");
  raw_fd_ostream OS(OutFile, EC, llvm::sys::fs::F_None);
  M.print(OS, nullptr);
  OS.flush();
  return OutFile;
}
353 354 355 356 357 358 359 360 361

Value * addIncrementIndexOp(AllocaInst * IdxPtr, Instruction * InsertBefore) {
  IRBuilder<> Builder(InsertBefore);
  auto LoadVal = Builder.CreateLoad(IdxPtr);
  auto Incr = Builder.CreateAdd(LoadVal, Builder.getInt32(1));
  Builder.CreateStore(Incr, IdxPtr);
  return Incr;
}

guruhegde's avatar
guruhegde committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
void printRegeionInfo(Function * F) {
  auto DT = DominatorTree(*F);
  auto PDT = PostDominatorTree(*F);
  auto DF = DominanceFrontier();
  DF.analyze(DT);
  RegionInfo RI;
  RI.recalculate(*F, &DT, &PDT, &DF);

  errs() << "\n" << F->getName() << "\n";
  auto * R = RI.getTopLevelRegion();
  errs() << "=========RegionInfo========\n";
  int i = 0;
  for (auto & E : *R) {
    errs() << "Region " << to_string(i++) << ":\n";
    // Exiting blocks
    SmallVector<BasicBlock *, 4> ExitingBlocks;
    E->getExitingBlocks(ExitingBlocks);
    errs() << "Exiting blocks: ";
    for (auto & EB : ExitingBlocks) {
      EB->printAsOperand(errs());
      errs() << "  ";
    }
    errs() << "\n";
    ExitingBlocks.clear();
  }
}

389
pair<BasicBlock *, BasicBlock *> unifyFunctionExitNodes(Function &F) {
guruhegde's avatar
guruhegde committed
390
  vector<BasicBlock*> ReturningBlocks;
391
  vector<BasicBlock*> UnreachableBlocks;
guruhegde's avatar
guruhegde committed
392 393 394
  for (BasicBlock &I : F)
    if (isa<ReturnInst>(I.getTerminator()))
      ReturningBlocks.push_back(&I);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    else if (isa<UnreachableInst>(I.getTerminator()))
      UnreachableBlocks.push_back(&I);

  // Then unreachable blocks.
  BasicBlock * UnreachableBlock = nullptr;
  if (UnreachableBlocks.empty()) {
    UnreachableBlock = nullptr;
  } else if (UnreachableBlocks.size() == 1) {
    UnreachableBlock = UnreachableBlocks.front();
  } else {
    UnreachableBlock = BasicBlock::Create(F.getContext(),
                                          "UnifiedUnreachableBlock", &F);
    new UnreachableInst(F.getContext(), UnreachableBlock);

    for (BasicBlock *BB : UnreachableBlocks) {
      BB->getInstList().pop_back();  // Remove the unreachable inst.
      BranchInst::Create(UnreachableBlock, BB);
    }
  }
guruhegde's avatar
guruhegde committed
414 415 416

  // Now handle return blocks.
  if (ReturningBlocks.empty()) {
guruhegde's avatar
guruhegde committed
417
    return make_pair(nullptr, UnreachableBlock);            // No blocks return
guruhegde's avatar
guruhegde committed
418
  } else if (ReturningBlocks.size() == 1) {
419
    return make_pair(ReturningBlocks.front(), UnreachableBlock);
guruhegde's avatar
guruhegde committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  }

  // Otherwise, we need to insert a new basic block into the function, add a PHI
  // nodes (if the function returns values), and convert all of the return
  // instructions into unconditional branches.
  //
  BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(),
                                               "UnifiedReturnBlock", &F);

  PHINode *PN = nullptr;
  if (F.getReturnType()->isVoidTy()) {
    ReturnInst::Create(F.getContext(), nullptr, NewRetBlock);
  } else {
    // If the function doesn't return void... add a PHI node to the block...
    PN = PHINode::Create(F.getReturnType(), ReturningBlocks.size(),
                         "UnifiedRetVal");
    NewRetBlock->getInstList().push_back(PN);
    ReturnInst::Create(F.getContext(), PN, NewRetBlock);
  }

  // Loop over all of the blocks, replacing the return instruction with an
  // unconditional branch.
  //
  for (BasicBlock *BB : ReturningBlocks) {
    // Add an incoming element to the PHI node for every return instruction that
    // is merging into this new block...
    if (PN)
      PN->addIncoming(BB->getTerminator()->getOperand(0), BB);

    BB->getInstList().pop_back();  // Remove the return insn
    BranchInst::Create(NewRetBlock, BB);
  }

453
  return make_pair(NewRetBlock, UnreachableBlock);
guruhegde's avatar
guruhegde committed
454
}
guruhegde's avatar
guruhegde committed
455

guruhegde's avatar
guruhegde committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
AllocaInst * getLoopIndexVar(Loop * L) {
  AllocaInst * Index = nullptr;
  auto LatchBB = L->getLoopLatch();
  assert(LatchBB && "Latch block can't be null!");

  // Find index increment instruction.
  // XXX Assume latch block contains only one add instruction, verify it.
  auto It = find_if(*LatchBB,
          [&] (const Instruction & I) {
          return (isa<BinaryOperator>(I) &&
                  I.getOpcode() == Instruction::Add &&
                  cast<ConstantInt>(I.getOperand(1))->equalsInt(1)) ? true : false; });

  Index = cast<AllocaInst>(cast<LoadInst>(It->getOperand(0))->getOperand(0));
  return Index;
}

guruhegde's avatar
guruhegde committed
473 474 475 476 477 478 479 480 481
void visitSuccessor(SmallVectorImpl<BasicBlock *> & Blocks, BasicBlock * StartBlock,
                    BasicBlock * EndBlock) {
  for (auto * BB : successors(StartBlock)){
    if (BB == EndBlock) return;
    Blocks.push_back(BB);
    visitSuccessor(Blocks, BB, EndBlock);
  }
}

guruhegde's avatar
guruhegde committed
482
AllocaInst * getLoopTripCount(Loop * L0) {
guruhegde's avatar
guruhegde committed
483 484
  auto Header = L0->getHeader();
  auto Cond = cast<BranchInst>(Header->getTerminator())->getCondition();
guruhegde's avatar
guruhegde committed
485 486
  auto TCVal = cast<ICmpInst>(Cond)->getOperand(1);
  return cast<AllocaInst>(cast<LoadInst>(TCVal)->getOperand(0));
guruhegde's avatar
guruhegde committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500
}

BasicBlock * getPreLoopBlock(Loop * L) {
  BasicBlock * PreLoopBB = L->getLoopPreheader();
  if (!PreLoopBB) {
    for (auto * BB : predecessors(L->getHeader())) {
      if (BB == L->getLoopLatch()) continue;
      if (L->contains(BB)) continue;
      PreLoopBB = BB;
    }
  }
  return PreLoopBB;
}

guruhegde's avatar
guruhegde committed
501
} // namespace tas