1//===- NVPTXLowerAggrCopies.cpp - ------------------------------*- C++ -*--===//
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// Lower aggregate copies, memset, memcpy, memmov intrinsics into loops when
10// the size is large or is not a compile-time constant.
11//
12//===----------------------------------------------------------------------===//
13
14#include "NVPTXLowerAggrCopies.h"
15#include "llvm/Constants.h"
16#include "llvm/Function.h"
17#include "llvm/IRBuilder.h"
18#include "llvm/Instructions.h"
19#include "llvm/IntrinsicInst.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Support/InstIterator.h"
24#include "llvm/Target/TargetData.h"
25
26using namespace llvm;
27
28namespace llvm {
29FunctionPass *createLowerAggrCopies();
30}
31
32char NVPTXLowerAggrCopies::ID = 0;
33
34// Lower MemTransferInst or load-store pair to loop
35static void convertTransferToLoop(Instruction *splitAt, Value *srcAddr,
36                                  Value *dstAddr, Value *len,
37                                  //unsigned numLoads,
38                                  bool srcVolatile, bool dstVolatile,
39                                  LLVMContext &Context, Function &F) {
40  Type *indType = len->getType();
41
42  BasicBlock *origBB = splitAt->getParent();
43  BasicBlock *newBB = splitAt->getParent()->splitBasicBlock(splitAt, "split");
44  BasicBlock *loopBB = BasicBlock::Create(Context, "loadstoreloop", &F, newBB);
45
46  origBB->getTerminator()->setSuccessor(0, loopBB);
47  IRBuilder<> builder(origBB, origBB->getTerminator());
48
49  // srcAddr and dstAddr are expected to be pointer types,
50  // so no check is made here.
51  unsigned srcAS =
52      dyn_cast<PointerType>(srcAddr->getType())->getAddressSpace();
53  unsigned dstAS =
54      dyn_cast<PointerType>(dstAddr->getType())->getAddressSpace();
55
56  // Cast pointers to (char *)
57  srcAddr = builder.CreateBitCast(srcAddr, Type::getInt8PtrTy(Context, srcAS));
58  dstAddr = builder.CreateBitCast(dstAddr, Type::getInt8PtrTy(Context, dstAS));
59
60  IRBuilder<> loop(loopBB);
61  // The loop index (ind) is a phi node.
62  PHINode *ind = loop.CreatePHI(indType, 0);
63  // Incoming value for ind is 0
64  ind->addIncoming(ConstantInt::get(indType, 0), origBB);
65
66  // load from srcAddr+ind
67  Value *val = loop.CreateLoad(loop.CreateGEP(srcAddr, ind), srcVolatile);
68  // store at dstAddr+ind
69  loop.CreateStore(val, loop.CreateGEP(dstAddr, ind), dstVolatile);
70
71  // The value for ind coming from backedge is (ind + 1)
72  Value *newind = loop.CreateAdd(ind, ConstantInt::get(indType, 1));
73  ind->addIncoming(newind, loopBB);
74
75  loop.CreateCondBr(loop.CreateICmpULT(newind, len), loopBB, newBB);
76}
77
78// Lower MemSetInst to loop
79static void convertMemSetToLoop(Instruction *splitAt, Value *dstAddr,
80                                Value *len, Value *val, LLVMContext &Context,
81                                Function &F) {
82  BasicBlock *origBB = splitAt->getParent();
83  BasicBlock *newBB = splitAt->getParent()->splitBasicBlock(splitAt, "split");
84  BasicBlock *loopBB = BasicBlock::Create(Context, "loadstoreloop", &F, newBB);
85
86  origBB->getTerminator()->setSuccessor(0, loopBB);
87  IRBuilder<> builder(origBB, origBB->getTerminator());
88
89  unsigned dstAS =
90      dyn_cast<PointerType>(dstAddr->getType())->getAddressSpace();
91
92  // Cast pointer to the type of value getting stored
93  dstAddr = builder.CreateBitCast(dstAddr,
94                                  PointerType::get(val->getType(), dstAS));
95
96  IRBuilder<> loop(loopBB);
97  PHINode *ind = loop.CreatePHI(len->getType(), 0);
98  ind->addIncoming(ConstantInt::get(len->getType(), 0), origBB);
99
100  loop.CreateStore(val, loop.CreateGEP(dstAddr, ind), false);
101
102  Value *newind = loop.CreateAdd(ind, ConstantInt::get(len->getType(), 1));
103  ind->addIncoming(newind, loopBB);
104
105  loop.CreateCondBr(loop.CreateICmpULT(newind, len), loopBB, newBB);
106}
107
108bool NVPTXLowerAggrCopies::runOnFunction(Function &F) {
109  SmallVector<LoadInst *, 4> aggrLoads;
110  SmallVector<MemTransferInst *, 4> aggrMemcpys;
111  SmallVector<MemSetInst *, 4> aggrMemsets;
112
113  TargetData *TD = &getAnalysis<TargetData>();
114  LLVMContext &Context = F.getParent()->getContext();
115
116  //
117  // Collect all the aggrLoads, aggrMemcpys and addrMemsets.
118  //
119  //const BasicBlock *firstBB = &F.front();  // first BB in F
120  for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
121    //BasicBlock *bb = BI;
122    for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
123        ++II) {
124      if (LoadInst * load = dyn_cast<LoadInst>(II)) {
125
126        if (load->hasOneUse() == false) continue;
127
128        if (TD->getTypeStoreSize(load->getType()) < MaxAggrCopySize) continue;
129
130        User *use = *(load->use_begin());
131        if (StoreInst * store = dyn_cast<StoreInst>(use)) {
132          if (store->getOperand(0) != load) //getValueOperand
133          continue;
134          aggrLoads.push_back(load);
135        }
136      } else if (MemTransferInst * intr = dyn_cast<MemTransferInst>(II)) {
137        Value *len = intr->getLength();
138        // If the number of elements being copied is greater
139        // than MaxAggrCopySize, lower it to a loop
140        if (ConstantInt * len_int = dyn_cast < ConstantInt > (len)) {
141          if (len_int->getZExtValue() >= MaxAggrCopySize) {
142            aggrMemcpys.push_back(intr);
143          }
144        } else {
145          // turn variable length memcpy/memmov into loop
146          aggrMemcpys.push_back(intr);
147        }
148      } else if (MemSetInst * memsetintr = dyn_cast<MemSetInst>(II)) {
149        Value *len = memsetintr->getLength();
150        if (ConstantInt * len_int = dyn_cast<ConstantInt>(len)) {
151          if (len_int->getZExtValue() >= MaxAggrCopySize) {
152            aggrMemsets.push_back(memsetintr);
153          }
154        } else {
155          // turn variable length memset into loop
156          aggrMemsets.push_back(memsetintr);
157        }
158      }
159    }
160  }
161  if ((aggrLoads.size() == 0) && (aggrMemcpys.size() == 0)
162      && (aggrMemsets.size() == 0)) return false;
163
164  //
165  // Do the transformation of an aggr load/copy/set to a loop
166  //
167  for (unsigned i = 0, e = aggrLoads.size(); i != e; ++i) {
168    LoadInst *load = aggrLoads[i];
169    StoreInst *store = dyn_cast<StoreInst>(*load->use_begin());
170    Value *srcAddr = load->getOperand(0);
171    Value *dstAddr = store->getOperand(1);
172    unsigned numLoads = TD->getTypeStoreSize(load->getType());
173    Value *len = ConstantInt::get(Type::getInt32Ty(Context), numLoads);
174
175    convertTransferToLoop(store, srcAddr, dstAddr, len, load->isVolatile(),
176                          store->isVolatile(), Context, F);
177
178    store->eraseFromParent();
179    load->eraseFromParent();
180  }
181
182  for (unsigned i = 0, e = aggrMemcpys.size(); i != e; ++i) {
183    MemTransferInst *cpy = aggrMemcpys[i];
184    Value *len = cpy->getLength();
185    // llvm 2.7 version of memcpy does not have volatile
186    // operand yet. So always making it non-volatile
187    // optimistically, so that we don't see unnecessary
188    // st.volatile in ptx
189    convertTransferToLoop(cpy, cpy->getSource(), cpy->getDest(), len, false,
190                          false, Context, F);
191    cpy->eraseFromParent();
192  }
193
194  for (unsigned i = 0, e = aggrMemsets.size(); i != e; ++i) {
195    MemSetInst *memsetinst = aggrMemsets[i];
196    Value *len = memsetinst->getLength();
197    Value *val = memsetinst->getValue();
198    convertMemSetToLoop(memsetinst, memsetinst->getDest(), len, val, Context,
199                        F);
200    memsetinst->eraseFromParent();
201  }
202
203  return true;
204}
205
206FunctionPass *llvm::createLowerAggrCopies() {
207  return new NVPTXLowerAggrCopies();
208}
209