1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- 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 /// \file
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
14 
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Type.h"
23 #include "llvm/IR/Value.h"
24 #include "llvm/Target/TargetLowering.h"
25 
26 #define DEBUG_TYPE "irtranslator"
27 
28 using namespace llvm;
29 
30 char IRTranslator::ID = 0;
31 INITIALIZE_PASS(IRTranslator, "irtranslator", "IRTranslator LLVM IR -> MI",
32                 false, false)
33 
34 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
35   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
36 }
37 
38 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
39   unsigned &ValReg = ValToVReg[&Val];
40   // Check if this is the first time we see Val.
41   if (!ValReg) {
42     // Fill ValRegsSequence with the sequence of registers
43     // we need to concat together to produce the value.
44     assert(Val.getType()->isSized() &&
45            "Don't know how to create an empty vreg");
46     assert(!Val.getType()->isAggregateType() && "Not yet implemented");
47     unsigned Size = DL->getTypeSizeInBits(Val.getType());
48     unsigned VReg = MRI->createGenericVirtualRegister(Size);
49     ValReg = VReg;
50     assert(!isa<Constant>(Val) && "Not yet implemented");
51   }
52   return ValReg;
53 }
54 
55 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
56   unsigned Alignment = 0;
57   Type *ValTy = nullptr;
58   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
59     Alignment = SI->getAlignment();
60     ValTy = SI->getValueOperand()->getType();
61   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
62     Alignment = LI->getAlignment();
63     ValTy = LI->getType();
64   } else
65     llvm_unreachable("unhandled memory instruction");
66 
67   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
68 }
69 
70 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
71   MachineBasicBlock *&MBB = BBToMBB[&BB];
72   if (!MBB) {
73     MachineFunction &MF = MIRBuilder.getMF();
74     MBB = MF.CreateMachineBasicBlock();
75     MF.push_back(MBB);
76   }
77   return *MBB;
78 }
79 
80 bool IRTranslator::translateBinaryOp(unsigned Opcode, const Instruction &Inst) {
81   // Get or create a virtual register for each value.
82   // Unless the value is a Constant => loadimm cst?
83   // or inline constant each time?
84   // Creation of a virtual register needs to have a size.
85   unsigned Op0 = getOrCreateVReg(*Inst.getOperand(0));
86   unsigned Op1 = getOrCreateVReg(*Inst.getOperand(1));
87   unsigned Res = getOrCreateVReg(Inst);
88   MIRBuilder.buildInstr(Opcode, LLT{*Inst.getType()}, Res, Op0, Op1);
89   return true;
90 }
91 
92 bool IRTranslator::translateReturn(const Instruction &Inst) {
93   assert(isa<ReturnInst>(Inst) && "Return expected");
94   const Value *Ret = cast<ReturnInst>(Inst).getReturnValue();
95   // The target may mess up with the insertion point, but
96   // this is not important as a return is the last instruction
97   // of the block anyway.
98   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
99 }
100 
101 bool IRTranslator::translateBr(const Instruction &Inst) {
102   assert(isa<BranchInst>(Inst) && "Branch expected");
103   const BranchInst &BrInst = *cast<BranchInst>(&Inst);
104   if (BrInst.isUnconditional()) {
105     const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getOperand(0));
106     MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
107     MIRBuilder.buildBr(TgtBB);
108   } else {
109     assert(0 && "Not yet implemented");
110   }
111   // Link successors.
112   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
113   for (const BasicBlock *Succ : BrInst.successors())
114     CurBB.addSuccessor(&getOrCreateBB(*Succ));
115   return true;
116 }
117 
118 bool IRTranslator::translateLoad(const LoadInst &LI) {
119   assert(LI.isSimple() && "only simple loads are supported at the moment");
120 
121   MachineFunction &MF = MIRBuilder.getMF();
122   unsigned Res = getOrCreateVReg(LI);
123   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
124   LLT VTy{*LI.getType()}, PTy{*LI.getPointerOperand()->getType()};
125 
126   MIRBuilder.buildLoad(
127       VTy, PTy, Res, Addr,
128       *MF.getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
129                                MachineMemOperand::MOLoad,
130                                VTy.getSizeInBits() / 8, getMemOpAlignment(LI)));
131   return true;
132 }
133 
134 bool IRTranslator::translateStore(const StoreInst &SI) {
135   assert(SI.isSimple() && "only simple loads are supported at the moment");
136 
137   MachineFunction &MF = MIRBuilder.getMF();
138   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
139   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
140   LLT VTy{*SI.getValueOperand()->getType()},
141       PTy{*SI.getPointerOperand()->getType()};
142 
143   MIRBuilder.buildStore(
144       VTy, PTy, Val, Addr,
145       *MF.getMachineMemOperand(MachinePointerInfo(SI.getPointerOperand()),
146                                MachineMemOperand::MOStore,
147                                VTy.getSizeInBits() / 8, getMemOpAlignment(SI)));
148   return true;
149 }
150 
151 bool IRTranslator::translateBitCast(const CastInst &CI) {
152   if (LLT{*CI.getDestTy()} == LLT{*CI.getSrcTy()}) {
153     MIRBuilder.buildCopy(getOrCreateVReg(CI),
154                          getOrCreateVReg(*CI.getOperand(0)));
155     return true;
156   }
157   return translateCast(TargetOpcode::G_BITCAST, CI);
158 }
159 
160 bool IRTranslator::translateCast(unsigned Opcode, const CastInst &CI) {
161   unsigned Op = getOrCreateVReg(*CI.getOperand(0));
162   unsigned Res = getOrCreateVReg(CI);
163   MIRBuilder.buildInstr(Opcode, {LLT{*CI.getDestTy()}, LLT{*CI.getSrcTy()}},
164                         Res, Op);
165   return true;
166 }
167 
168 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI) {
169   assert(AI.isStaticAlloca() && "only handle static allocas now");
170   MachineFunction &MF = MIRBuilder.getMF();
171   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
172   unsigned Size =
173       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
174 
175   unsigned Alignment = AI.getAlignment();
176   if (!Alignment)
177     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
178 
179   unsigned Res = getOrCreateVReg(AI);
180   int FI = MF.getFrameInfo()->CreateStackObject(Size, Alignment, false, &AI);
181   MIRBuilder.buildFrameIndex(LLT::pointer(0), Res, FI);
182   return true;
183 }
184 
185 bool IRTranslator::translate(const Instruction &Inst) {
186   MIRBuilder.setDebugLoc(Inst.getDebugLoc());
187   switch(Inst.getOpcode()) {
188   // Arithmetic operations.
189   case Instruction::Add:
190     return translateBinaryOp(TargetOpcode::G_ADD, Inst);
191   case Instruction::Sub:
192     return translateBinaryOp(TargetOpcode::G_SUB, Inst);
193 
194   // Bitwise operations.
195   case Instruction::And:
196     return translateBinaryOp(TargetOpcode::G_AND, Inst);
197   case Instruction::Or:
198     return translateBinaryOp(TargetOpcode::G_OR, Inst);
199 
200   // Branch operations.
201   case Instruction::Br:
202     return translateBr(Inst);
203   case Instruction::Ret:
204     return translateReturn(Inst);
205 
206   // Casts
207   case Instruction::BitCast:
208     return translateBitCast(cast<CastInst>(Inst));
209   case Instruction::IntToPtr:
210     return translateCast(TargetOpcode::G_INTTOPTR, cast<CastInst>(Inst));
211   case Instruction::PtrToInt:
212     return translateCast(TargetOpcode::G_PTRTOINT, cast<CastInst>(Inst));
213 
214   // Memory ops.
215   case Instruction::Load:
216     return translateLoad(cast<LoadInst>(Inst));
217   case Instruction::Store:
218     return translateStore(cast<StoreInst>(Inst));
219 
220   case Instruction::Alloca:
221     return translateStaticAlloca(cast<AllocaInst>(Inst));
222 
223   default:
224     llvm_unreachable("Opcode not supported");
225   }
226 }
227 
228 
229 void IRTranslator::finalize() {
230   // Release the memory used by the different maps we
231   // needed during the translation.
232   ValToVReg.clear();
233   Constants.clear();
234 }
235 
236 bool IRTranslator::runOnMachineFunction(MachineFunction &MF) {
237   const Function &F = *MF.getFunction();
238   if (F.empty())
239     return false;
240   CLI = MF.getSubtarget().getCallLowering();
241   MIRBuilder.setMF(MF);
242   MRI = &MF.getRegInfo();
243   DL = &F.getParent()->getDataLayout();
244 
245   // Setup the arguments.
246   MachineBasicBlock &MBB = getOrCreateBB(F.front());
247   MIRBuilder.setMBB(MBB);
248   SmallVector<unsigned, 8> VRegArgs;
249   for (const Argument &Arg: F.args())
250     VRegArgs.push_back(getOrCreateVReg(Arg));
251   bool Succeeded =
252       CLI->lowerFormalArguments(MIRBuilder, F.getArgumentList(), VRegArgs);
253   if (!Succeeded)
254     report_fatal_error("Unable to lower arguments");
255 
256   for (const BasicBlock &BB: F) {
257     MachineBasicBlock &MBB = getOrCreateBB(BB);
258     // Set the insertion point of all the following translations to
259     // the end of this basic block.
260     MIRBuilder.setMBB(MBB);
261     for (const Instruction &Inst: BB) {
262       bool Succeeded = translate(Inst);
263       if (!Succeeded) {
264         DEBUG(dbgs() << "Cannot translate: " << Inst << '\n');
265         report_fatal_error("Unable to translate instruction");
266       }
267     }
268   }
269 
270   // Now that the MachineFrameInfo has been configured, no further changes to
271   // the reserved registers are possible.
272   MRI->freezeReservedRegs(MF);
273 
274   return false;
275 }
276