blob: 1e8f6c222d71f6fc723de4c8e406900df49030e0 [file] [log] [blame]
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001//===-- 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
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +000015#include "llvm/ADT/ScopeExit.h"
Tim Northoverb6636fd2017-01-17 22:13:50 +000016#include "llvm/ADT/SmallSet.h"
Quentin Colombetfd9d0a02016-02-11 19:59:41 +000017#include "llvm/ADT/SmallVector.h"
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000018#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Quentin Colombetba2a0162016-02-16 19:26:02 +000019#include "llvm/CodeGen/GlobalISel/CallLowering.h"
Tim Northovera9105be2016-11-09 22:39:54 +000020#include "llvm/CodeGen/Analysis.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000021#include "llvm/CodeGen/MachineFunction.h"
Tim Northoverbd505462016-07-22 16:59:52 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Tim Northovera9105be2016-11-09 22:39:54 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000025#include "llvm/CodeGen/TargetPassConfig.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000026#include "llvm/IR/Constant.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000027#include "llvm/IR/DebugInfo.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000028#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000030#include "llvm/IR/IntrinsicInst.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000031#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
Tim Northoverc3e3f592017-02-03 18:22:45 +000033#include "llvm/Target/TargetFrameLowering.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000034#include "llvm/Target/TargetIntrinsicInfo.h"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +000035#include "llvm/Target/TargetLowering.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000036
37#define DEBUG_TYPE "irtranslator"
38
Quentin Colombet105cf2b2016-01-20 20:58:56 +000039using namespace llvm;
40
41char IRTranslator::ID = 0;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000042INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
43 false, false)
44INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
45INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000046 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000047
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000048static void reportTranslationError(MachineFunction &MF,
49 const TargetPassConfig &TPC,
50 OptimizationRemarkEmitter &ORE,
51 OptimizationRemarkMissed &R) {
52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
53
54 // Print the function name explicitly if we don't have a debug location (which
55 // makes the diagnostic less useful) or if we're going to emit a raw error.
56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
57 R << (" (in function: " + MF.getName() + ")").str();
58
59 if (TPC.isGlobalISelAbortEnabled())
60 report_fatal_error(R.getMsg());
61 else
62 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +000063}
64
Quentin Colombeta7fae162016-02-11 17:53:23 +000065IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
Quentin Colombet39293d32016-03-08 01:38:55 +000066 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +000067}
68
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000069void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetPassConfig>();
71 MachineFunctionPass::getAnalysisUsage(AU);
72}
73
74
Quentin Colombete225e252016-03-11 17:27:54 +000075unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
76 unsigned &ValReg = ValToVReg[&Val];
Tim Northover5ed648e2016-08-09 21:28:04 +000077
Tim Northover9e35f1e2017-01-25 20:58:22 +000078 if (ValReg)
79 return ValReg;
80
81 // Fill ValRegsSequence with the sequence of registers
82 // we need to concat together to produce the value.
83 assert(Val.getType()->isSized() &&
84 "Don't know how to create an empty vreg");
Daniel Sanders52b4ce72017-03-07 23:20:35 +000085 unsigned VReg =
86 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
Tim Northover9e35f1e2017-01-25 20:58:22 +000087 ValReg = VReg;
88
89 if (auto CV = dyn_cast<Constant>(&Val)) {
90 bool Success = translate(*CV, VReg);
91 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000092 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +000093 MF->getFunction()->getSubprogram(),
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000094 &MF->getFunction()->getEntryBlock());
95 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
96 reportTranslationError(*MF, *TPC, *ORE, R);
97 return VReg;
Tim Northover5ed648e2016-08-09 21:28:04 +000098 }
Quentin Colombet17c494b2016-02-11 17:51:31 +000099 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000100
Tim Northover9e35f1e2017-01-25 20:58:22 +0000101 return VReg;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000102}
103
Tim Northovercdf23f12016-10-31 18:30:59 +0000104int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
105 if (FrameIndices.find(&AI) != FrameIndices.end())
106 return FrameIndices[&AI];
107
Tim Northovercdf23f12016-10-31 18:30:59 +0000108 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
109 unsigned Size =
110 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
111
112 // Always allocate at least one byte.
113 Size = std::max(Size, 1u);
114
115 unsigned Alignment = AI.getAlignment();
116 if (!Alignment)
117 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
118
119 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000120 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000121 return FI;
122}
123
Tim Northoverad2b7172016-07-26 20:23:26 +0000124unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
125 unsigned Alignment = 0;
126 Type *ValTy = nullptr;
127 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
128 Alignment = SI->getAlignment();
129 ValTy = SI->getValueOperand()->getType();
130 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
131 Alignment = LI->getAlignment();
132 ValTy = LI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000133 } else {
134 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
135 R << "unable to translate memop: " << ore::NV("Opcode", &I);
136 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000137 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000138 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000139
140 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
141}
142
Quentin Colombet53237a92016-03-11 17:27:43 +0000143MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
144 MachineBasicBlock *&MBB = BBToMBB[&BB];
Quentin Colombet17c494b2016-02-11 17:51:31 +0000145 if (!MBB) {
Kristof Beylsa983e7c2017-01-05 13:27:52 +0000146 MBB = MF->CreateMachineBasicBlock(&BB);
Tim Northover50db7f412016-12-07 21:17:47 +0000147 MF->push_back(MBB);
Kristof Beylsa983e7c2017-01-05 13:27:52 +0000148
149 if (BB.hasAddressTaken())
150 MBB->setHasAddressTaken();
Quentin Colombet17c494b2016-02-11 17:51:31 +0000151 }
152 return *MBB;
153}
154
Tim Northoverb6636fd2017-01-17 22:13:50 +0000155void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
156 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
157 MachinePreds[Edge].push_back(NewPred);
158}
159
Tim Northoverc53606e2016-12-07 21:29:15 +0000160bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
161 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000162 // FIXME: handle signed/unsigned wrapping flags.
163
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000164 // Get or create a virtual register for each value.
165 // Unless the value is a Constant => loadimm cst?
166 // or inline constant each time?
167 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000168 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
169 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
170 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000171 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000172 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000173}
174
Volkan Keles20d3c422017-03-07 18:03:28 +0000175bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
176 // -0.0 - X --> G_FNEG
177 if (isa<Constant>(U.getOperand(0)) &&
178 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
179 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
180 .addDef(getOrCreateVReg(U))
181 .addUse(getOrCreateVReg(*U.getOperand(1)));
182 return true;
183 }
184 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
185}
186
Tim Northoverc53606e2016-12-07 21:29:15 +0000187bool IRTranslator::translateCompare(const User &U,
188 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000189 const CmpInst *CI = dyn_cast<CmpInst>(&U);
190 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
191 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
192 unsigned Res = getOrCreateVReg(U);
193 CmpInst::Predicate Pred =
194 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
195 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000196 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000197 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000198 else if (Pred == CmpInst::FCMP_FALSE)
199 MIRBuilder.buildConstant(Res, 0);
200 else if (Pred == CmpInst::FCMP_TRUE)
201 MIRBuilder.buildConstant(Res, 1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000202 else
Tim Northover0f140c72016-09-09 11:46:34 +0000203 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000204
Tim Northoverde3aea0412016-08-17 20:25:25 +0000205 return true;
206}
207
Tim Northoverc53606e2016-12-07 21:29:15 +0000208bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000209 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000210 const Value *Ret = RI.getReturnValue();
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000211 // The target may mess up with the insertion point, but
212 // this is not important as a return is the last instruction
213 // of the block anyway.
Tom Stellardb72a65f2016-04-14 17:23:33 +0000214 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000215}
216
Tim Northoverc53606e2016-12-07 21:29:15 +0000217bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000218 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000219 unsigned Succ = 0;
220 if (!BrInst.isUnconditional()) {
221 // We want a G_BRCOND to the true BB followed by an unconditional branch.
222 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
223 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
224 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000225 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000226 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000227
228 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
229 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
230 MIRBuilder.buildBr(TgtBB);
231
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000232 // Link successors.
233 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
234 for (const BasicBlock *Succ : BrInst.successors())
235 CurBB.addSuccessor(&getOrCreateBB(*Succ));
236 return true;
237}
238
Kristof Beylseced0712017-01-05 11:28:51 +0000239bool IRTranslator::translateSwitch(const User &U,
240 MachineIRBuilder &MIRBuilder) {
241 // For now, just translate as a chain of conditional branches.
242 // FIXME: could we share most of the logic/code in
243 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
244 // At first sight, it seems most of the logic in there is independent of
245 // SelectionDAG-specifics and a lot of work went in to optimize switch
246 // lowering in there.
247
248 const SwitchInst &SwInst = cast<SwitchInst>(U);
249 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000250 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000251
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000252 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000253 for (auto &CaseIt : SwInst.cases()) {
254 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
255 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
256 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000257 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
258 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
259 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000260
Tim Northoverb6636fd2017-01-17 22:13:50 +0000261 MIRBuilder.buildBrCond(Tst, TrueMBB);
262 CurMBB.addSuccessor(&TrueMBB);
263 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000264
Tim Northoverb6636fd2017-01-17 22:13:50 +0000265 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000266 MF->CreateMachineBasicBlock(SwInst.getParent());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000267 MF->push_back(FalseMBB);
268 MIRBuilder.buildBr(*FalseMBB);
269 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000270
Tim Northoverb6636fd2017-01-17 22:13:50 +0000271 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000272 }
273 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000274 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
275 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
276 MIRBuilder.buildBr(DefaultMBB);
277 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
278 CurMBB.addSuccessor(&DefaultMBB);
279 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000280
281 return true;
282}
283
Kristof Beyls65a12c02017-01-30 09:13:18 +0000284bool IRTranslator::translateIndirectBr(const User &U,
285 MachineIRBuilder &MIRBuilder) {
286 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
287
288 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
289 MIRBuilder.buildBrIndirect(Tgt);
290
291 // Link successors.
292 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
293 for (const BasicBlock *Succ : BrInst.successors())
294 CurBB.addSuccessor(&getOrCreateBB(*Succ));
295
296 return true;
297}
298
Tim Northoverc53606e2016-12-07 21:29:15 +0000299bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000300 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000301
Tim Northover7152dca2016-10-19 15:55:06 +0000302 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
303 : MachineMemOperand::MONone;
304 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000305
Tim Northoverad2b7172016-07-26 20:23:26 +0000306 unsigned Res = getOrCreateVReg(LI);
307 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000308
Tim Northoverad2b7172016-07-26 20:23:26 +0000309 MIRBuilder.buildLoad(
Tim Northover0f140c72016-09-09 11:46:34 +0000310 Res, Addr,
Tim Northover50db7f412016-12-07 21:17:47 +0000311 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
312 Flags, DL->getTypeStoreSize(LI.getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000313 getMemOpAlignment(LI), AAMDNodes(), nullptr,
314 LI.getSynchScope(), LI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000315 return true;
316}
317
Tim Northoverc53606e2016-12-07 21:29:15 +0000318bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000319 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000320 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
321 : MachineMemOperand::MONone;
322 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000323
Tim Northoverad2b7172016-07-26 20:23:26 +0000324 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
325 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000326
327 MIRBuilder.buildStore(
Tim Northover50db7f412016-12-07 21:17:47 +0000328 Val, Addr,
329 *MF->getMachineMemOperand(
330 MachinePointerInfo(SI.getPointerOperand()), Flags,
331 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000332 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
333 SI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000334 return true;
335}
336
Tim Northoverc53606e2016-12-07 21:29:15 +0000337bool IRTranslator::translateExtractValue(const User &U,
338 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000339 const Value *Src = U.getOperand(0);
340 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northover6f80b082016-08-19 17:47:05 +0000341 SmallVector<Value *, 1> Indices;
342
343 // getIndexedOffsetInType is designed for GEPs, so the first index is the
344 // usual array element rather than looking into the actual aggregate.
345 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000346
347 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
348 for (auto Idx : EVI->indices())
349 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
350 } else {
351 for (unsigned i = 1; i < U.getNumOperands(); ++i)
352 Indices.push_back(U.getOperand(i));
353 }
Tim Northover6f80b082016-08-19 17:47:05 +0000354
355 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
356
Tim Northoverb6046222016-08-19 20:09:03 +0000357 unsigned Res = getOrCreateVReg(U);
Tim Northoverc2c545b2017-03-06 23:50:28 +0000358 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
Tim Northover6f80b082016-08-19 17:47:05 +0000359
360 return true;
361}
362
Tim Northoverc53606e2016-12-07 21:29:15 +0000363bool IRTranslator::translateInsertValue(const User &U,
364 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000365 const Value *Src = U.getOperand(0);
366 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000367 SmallVector<Value *, 1> Indices;
368
369 // getIndexedOffsetInType is designed for GEPs, so the first index is the
370 // usual array element rather than looking into the actual aggregate.
371 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000372
373 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
374 for (auto Idx : IVI->indices())
375 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
376 } else {
377 for (unsigned i = 2; i < U.getNumOperands(); ++i)
378 Indices.push_back(U.getOperand(i));
379 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000380
381 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
382
Tim Northoverb6046222016-08-19 20:09:03 +0000383 unsigned Res = getOrCreateVReg(U);
384 const Value &Inserted = *U.getOperand(1);
Tim Northover0f140c72016-09-09 11:46:34 +0000385 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
386 Offset);
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000387
388 return true;
389}
390
Tim Northoverc53606e2016-12-07 21:29:15 +0000391bool IRTranslator::translateSelect(const User &U,
392 MachineIRBuilder &MIRBuilder) {
Tim Northover0f140c72016-09-09 11:46:34 +0000393 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
394 getOrCreateVReg(*U.getOperand(1)),
395 getOrCreateVReg(*U.getOperand(2)));
Tim Northover5a28c362016-08-19 20:09:07 +0000396 return true;
397}
398
Tim Northoverc53606e2016-12-07 21:29:15 +0000399bool IRTranslator::translateBitCast(const User &U,
400 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000401 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000402 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
403 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000404 // Get the source vreg now, to avoid invalidating ValToVReg.
405 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Tim Northover357f1be2016-08-10 23:02:41 +0000406 unsigned &Reg = ValToVReg[&U];
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000407 // If we already assigned a vreg for this bitcast, we can't change that.
408 // Emit a copy to satisfy the users we already emitted.
Tim Northover7552ef52016-08-10 16:51:14 +0000409 if (Reg)
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000410 MIRBuilder.buildCopy(Reg, SrcReg);
Tim Northover7552ef52016-08-10 16:51:14 +0000411 else
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000412 Reg = SrcReg;
Tim Northover7c9eba92016-07-25 21:01:29 +0000413 return true;
414 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000415 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000416}
417
Tim Northoverc53606e2016-12-07 21:29:15 +0000418bool IRTranslator::translateCast(unsigned Opcode, const User &U,
419 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000420 unsigned Op = getOrCreateVReg(*U.getOperand(0));
421 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000422 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000423 return true;
424}
425
Tim Northoverc53606e2016-12-07 21:29:15 +0000426bool IRTranslator::translateGetElementPtr(const User &U,
427 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000428 // FIXME: support vector GEPs.
429 if (U.getType()->isVectorTy())
430 return false;
431
432 Value &Op0 = *U.getOperand(0);
433 unsigned BaseReg = getOrCreateVReg(Op0);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000434 LLT PtrTy = getLLTForType(*Op0.getType(), *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000435 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
436 LLT OffsetTy = LLT::scalar(PtrSize);
437
438 int64_t Offset = 0;
439 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
440 GTI != E; ++GTI) {
441 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000442 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000443 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
444 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
445 continue;
446 } else {
447 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
448
449 // If this is a scalar constant or a splat vector of constants,
450 // handle it quickly.
451 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
452 Offset += ElementSize * CI->getSExtValue();
453 continue;
454 }
455
456 if (Offset != 0) {
457 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
458 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
459 MIRBuilder.buildConstant(OffsetReg, Offset);
460 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
461
462 BaseReg = NewBaseReg;
463 Offset = 0;
464 }
465
466 // N = N + Idx * ElementSize;
467 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
468 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
469
470 unsigned IdxReg = getOrCreateVReg(*Idx);
471 if (MRI->getType(IdxReg) != OffsetTy) {
472 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
473 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
474 IdxReg = NewIdxReg;
475 }
476
477 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
478 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
479
480 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
481 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
482 BaseReg = NewBaseReg;
483 }
484 }
485
486 if (Offset != 0) {
487 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
488 MIRBuilder.buildConstant(OffsetReg, Offset);
489 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
490 return true;
491 }
492
493 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
494 return true;
495}
496
Tim Northover79f43f12017-01-30 19:33:07 +0000497bool IRTranslator::translateMemfunc(const CallInst &CI,
498 MachineIRBuilder &MIRBuilder,
499 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000500 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000501 Type *DstTy = CI.getArgOperand(0)->getType();
502 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000503 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
504 return false;
505
506 SmallVector<CallLowering::ArgInfo, 8> Args;
507 for (int i = 0; i < 3; ++i) {
508 const auto &Arg = CI.getArgOperand(i);
509 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
510 }
511
Tim Northover79f43f12017-01-30 19:33:07 +0000512 const char *Callee;
513 switch (ID) {
514 case Intrinsic::memmove:
515 case Intrinsic::memcpy: {
516 Type *SrcTy = CI.getArgOperand(1)->getType();
517 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
518 return false;
519 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
520 break;
521 }
522 case Intrinsic::memset:
523 Callee = "memset";
524 break;
525 default:
526 return false;
527 }
Tim Northover3f186032016-10-18 20:03:45 +0000528
Tim Northover79f43f12017-01-30 19:33:07 +0000529 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000530 CallLowering::ArgInfo(0, CI.getType()), Args);
531}
Tim Northovera7653b32016-09-12 11:20:22 +0000532
Tim Northoverc53606e2016-12-07 21:29:15 +0000533void IRTranslator::getStackGuard(unsigned DstReg,
534 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000535 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
536 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000537 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
538 MIB.addDef(DstReg);
539
Tim Northover50db7f412016-12-07 21:17:47 +0000540 auto &TLI = *MF->getSubtarget().getTargetLowering();
541 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000542 if (!Global)
543 return;
544
545 MachinePointerInfo MPInfo(Global);
Tim Northover50db7f412016-12-07 21:17:47 +0000546 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
Tim Northovercdf23f12016-10-31 18:30:59 +0000547 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
548 MachineMemOperand::MODereferenceable;
549 *MemRefs =
Tim Northover50db7f412016-12-07 21:17:47 +0000550 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
551 DL->getPointerABIAlignment());
Tim Northovercdf23f12016-10-31 18:30:59 +0000552 MIB.setMemRefs(MemRefs, MemRefs + 1);
553}
554
Tim Northover1e656ec2016-12-08 22:44:00 +0000555bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
556 MachineIRBuilder &MIRBuilder) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000557 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
Tim Northover1e656ec2016-12-08 22:44:00 +0000558 LLT s1 = LLT::scalar(1);
559 unsigned Width = Ty.getSizeInBits();
560 unsigned Res = MRI->createGenericVirtualRegister(Ty);
561 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
562 auto MIB = MIRBuilder.buildInstr(Op)
563 .addDef(Res)
564 .addDef(Overflow)
565 .addUse(getOrCreateVReg(*CI.getOperand(0)))
566 .addUse(getOrCreateVReg(*CI.getOperand(1)));
567
568 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
569 unsigned Zero = MRI->createGenericVirtualRegister(s1);
570 EntryBuilder.buildConstant(Zero, 0);
571 MIB.addUse(Zero);
572 }
573
574 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
575 return true;
576}
577
Tim Northoverc53606e2016-12-07 21:29:15 +0000578bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
579 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000580 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000581 default:
582 break;
Tim Northover0e011702017-02-10 19:10:38 +0000583 case Intrinsic::lifetime_start:
584 case Intrinsic::lifetime_end:
585 // Stack coloring is not enabled in O0 (which we care about now) so we can
586 // drop these. Make sure someone notices when we start compiling at higher
587 // opts though.
588 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
589 return false;
590 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000591 case Intrinsic::dbg_declare: {
592 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
593 assert(DI.getVariable() && "Missing variable");
594
595 const Value *Address = DI.getAddress();
596 if (!Address || isa<UndefValue>(Address)) {
597 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
598 return true;
599 }
600
Tim Northover09aac4a2017-01-26 23:39:14 +0000601 assert(DI.getVariable()->isValidLocationForIntrinsic(
602 MIRBuilder.getDebugLoc()) &&
603 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000604 auto AI = dyn_cast<AllocaInst>(Address);
605 if (AI && AI->isStaticAlloca()) {
606 // Static allocas are tracked at the MF level, no need for DBG_VALUE
607 // instructions (in fact, they get ignored if they *do* exist).
608 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
609 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000610 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000611 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
612 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000613 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000614 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000615 case Intrinsic::vaend:
616 // No target I know of cares about va_end. Certainly no in-tree target
617 // does. Simplest intrinsic ever!
618 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000619 case Intrinsic::vastart: {
620 auto &TLI = *MF->getSubtarget().getTargetLowering();
621 Value *Ptr = CI.getArgOperand(0);
622 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
623
624 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
625 .addUse(getOrCreateVReg(*Ptr))
626 .addMemOperand(MF->getMachineMemOperand(
627 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
628 return true;
629 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000630 case Intrinsic::dbg_value: {
631 // This form of DBG_VALUE is target-independent.
632 const DbgValueInst &DI = cast<DbgValueInst>(CI);
633 const Value *V = DI.getValue();
634 assert(DI.getVariable()->isValidLocationForIntrinsic(
635 MIRBuilder.getDebugLoc()) &&
636 "Expected inlined-at fields to agree");
637 if (!V) {
638 // Currently the optimizer can produce this; insert an undef to
639 // help debugging. Probably the optimizer should not do this.
640 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
641 DI.getExpression());
642 } else if (const auto *CI = dyn_cast<Constant>(V)) {
643 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
644 DI.getExpression());
645 } else {
646 unsigned Reg = getOrCreateVReg(*V);
647 // FIXME: This does not handle register-indirect values at offset 0. The
648 // direct/indirect thing shouldn't really be handled by something as
649 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
650 // pretty baked in right now.
651 if (DI.getOffset() != 0)
652 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
653 DI.getExpression());
654 else
655 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
656 DI.getExpression());
657 }
658 return true;
659 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000660 case Intrinsic::uadd_with_overflow:
661 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
662 case Intrinsic::sadd_with_overflow:
663 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
664 case Intrinsic::usub_with_overflow:
665 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
666 case Intrinsic::ssub_with_overflow:
667 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
668 case Intrinsic::umul_with_overflow:
669 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
670 case Intrinsic::smul_with_overflow:
671 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000672 case Intrinsic::pow:
673 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
674 .addDef(getOrCreateVReg(CI))
675 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
676 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
677 return true;
Tim Northover3f186032016-10-18 20:03:45 +0000678 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000679 case Intrinsic::memmove:
680 case Intrinsic::memset:
681 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000682 case Intrinsic::eh_typeid_for: {
683 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
684 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000685 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000686 MIRBuilder.buildConstant(Reg, TypeID);
687 return true;
688 }
Tim Northover6e904302016-10-18 20:03:51 +0000689 case Intrinsic::objectsize: {
690 // If we don't know by now, we're never going to know.
691 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
692
693 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
694 return true;
695 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000696 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000697 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000698 return true;
699 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000700 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000701 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000702 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000703
704 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
705 MIRBuilder.buildStore(
706 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000707 *MF->getMachineMemOperand(
708 MachinePointerInfo::getFixedStack(*MF,
709 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000710 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
711 PtrTy.getSizeInBits() / 8, 8));
712 return true;
713 }
Tim Northover91c81732016-08-19 17:17:06 +0000714 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000715 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000716}
717
Tim Northoveraa995c92017-03-09 23:36:26 +0000718bool IRTranslator::translateInlineAsm(const CallInst &CI,
719 MachineIRBuilder &MIRBuilder) {
720 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
721 if (!IA.getConstraintString().empty())
722 return false;
723
724 unsigned ExtraInfo = 0;
725 if (IA.hasSideEffects())
726 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
727 if (IA.getDialect() == InlineAsm::AD_Intel)
728 ExtraInfo |= InlineAsm::Extra_AsmDialect;
729
730 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
731 .addExternalSymbol(IA.getAsmString().c_str())
732 .addImm(ExtraInfo);
733
734 return true;
735}
736
Tim Northoverc53606e2016-12-07 21:29:15 +0000737bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000738 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000739 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +0000740 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +0000741
Tim Northover3babfef2017-01-19 23:59:35 +0000742 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +0000743 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +0000744
Tim Northover406024a2016-08-10 21:44:01 +0000745 if (!F || !F->isIntrinsic()) {
Tim Northover406024a2016-08-10 21:44:01 +0000746 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
747 SmallVector<unsigned, 8> Args;
748 for (auto &Arg: CI.arg_operands())
749 Args.push_back(getOrCreateVReg(*Arg));
750
Tim Northoverd1e951e2017-03-09 22:00:39 +0000751 MF->getFrameInfo().setHasCalls(true);
Tim Northoverfe5f89b2016-08-29 19:07:08 +0000752 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
753 return getOrCreateVReg(*CI.getCalledValue());
754 });
Tim Northover406024a2016-08-10 21:44:01 +0000755 }
756
757 Intrinsic::ID ID = F->getIntrinsicID();
758 if (TII && ID == Intrinsic::not_intrinsic)
759 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
760
761 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +0000762
Tim Northoverc53606e2016-12-07 21:29:15 +0000763 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +0000764 return true;
765
Tim Northover5fb414d2016-07-29 22:32:36 +0000766 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
767 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +0000768 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +0000769
770 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +0000771 // Some intrinsics take metadata parameters. Reject them.
772 if (isa<MetadataAsValue>(Arg))
773 return false;
Tim Northover5fb414d2016-07-29 22:32:36 +0000774 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
775 MIB.addImm(CI->getSExtValue());
776 else
777 MIB.addUse(getOrCreateVReg(*Arg));
778 }
779 return true;
780}
781
Tim Northoverc53606e2016-12-07 21:29:15 +0000782bool IRTranslator::translateInvoke(const User &U,
783 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000784 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000785 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +0000786
787 const BasicBlock *ReturnBB = I.getSuccessor(0);
788 const BasicBlock *EHPadBB = I.getSuccessor(1);
789
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000790 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +0000791 const Function *Fn = dyn_cast<Function>(Callee);
792 if (isa<InlineAsm>(Callee))
793 return false;
794
795 // FIXME: support invoking patchpoint and statepoint intrinsics.
796 if (Fn && Fn->isIntrinsic())
797 return false;
798
799 // FIXME: support whatever these are.
800 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
801 return false;
802
803 // FIXME: support Windows exception handling.
804 if (!isa<LandingPadInst>(EHPadBB->front()))
805 return false;
806
807
Matthias Braund0ee66c2016-12-01 19:32:15 +0000808 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +0000809 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000810 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000811 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
812
813 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
Tim Northover293f7432017-01-31 18:36:11 +0000814 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +0000815 for (auto &Arg: I.arg_operands())
Tim Northover293f7432017-01-31 18:36:11 +0000816 Args.push_back(getOrCreateVReg(*Arg));
Tim Northovera9105be2016-11-09 22:39:54 +0000817
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000818 if (!CLI->lowerCall(MIRBuilder, I, Res, Args,
819 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
820 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000821
Matthias Braund0ee66c2016-12-01 19:32:15 +0000822 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000823 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
824
825 // FIXME: track probabilities.
826 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
827 &ReturnMBB = getOrCreateBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +0000828 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +0000829 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
830 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +0000831 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000832
833 return true;
834}
835
Tim Northoverc53606e2016-12-07 21:29:15 +0000836bool IRTranslator::translateLandingPad(const User &U,
837 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000838 const LandingPadInst &LP = cast<LandingPadInst>(U);
839
840 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +0000841 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000842
843 MBB.setIsEHPad();
844
845 // If there aren't registers to copy the values into (e.g., during SjLj
846 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +0000847 auto &TLI = *MF->getSubtarget().getTargetLowering();
848 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +0000849 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
850 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
851 return true;
852
853 // If landingpad's return type is token type, we don't create DAG nodes
854 // for its exception pointer and selector value. The extraction of exception
855 // pointer or selector value from token type landingpads is not currently
856 // supported.
857 if (LP.getType()->isTokenTy())
858 return true;
859
860 // Add a label to mark the beginning of the landing pad. Deletion of the
861 // landing pad can thus be detected via the MachineModuleInfo.
862 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +0000863 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +0000864
Daniel Sanders1351db42017-03-07 23:32:10 +0000865 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +0000866 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
867 MIRBuilder.buildUndef(Undef);
868
Justin Bognera0295312017-01-25 00:16:53 +0000869 SmallVector<LLT, 2> Tys;
870 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000871 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +0000872 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
873
Tim Northovera9105be2016-11-09 22:39:54 +0000874 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +0000875 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
876 if (!ExceptionReg)
877 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000878
Tim Northover542d1c12017-03-07 23:04:06 +0000879 MBB.addLiveIn(ExceptionReg);
880 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
881 Tmp = MRI->createGenericVirtualRegister(Ty);
882 MIRBuilder.buildCopy(VReg, ExceptionReg);
883 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
Tim Northoverc9449702017-01-30 20:52:42 +0000884
Tim Northover542d1c12017-03-07 23:04:06 +0000885 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
886 if (!SelectorReg)
887 return false;
Tim Northoverc9449702017-01-30 20:52:42 +0000888
Tim Northover542d1c12017-03-07 23:04:06 +0000889 MBB.addLiveIn(SelectorReg);
Tim Northovera9105be2016-11-09 22:39:54 +0000890
Tim Northover542d1c12017-03-07 23:04:06 +0000891 // N.b. the exception selector register always has pointer type and may not
892 // match the actual IR-level type in the landingpad so an extra cast is
893 // needed.
894 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
895 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
896
897 VReg = MRI->createGenericVirtualRegister(Tys[1]);
898 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
899 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
900 Tys[0].getSizeInBits());
Tim Northovera9105be2016-11-09 22:39:54 +0000901 return true;
902}
903
Tim Northoverc3e3f592017-02-03 18:22:45 +0000904bool IRTranslator::translateAlloca(const User &U,
905 MachineIRBuilder &MIRBuilder) {
906 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000907
Tim Northoverc3e3f592017-02-03 18:22:45 +0000908 if (AI.isStaticAlloca()) {
909 unsigned Res = getOrCreateVReg(AI);
910 int FI = getOrCreateFrameIndex(AI);
911 MIRBuilder.buildFrameIndex(Res, FI);
912 return true;
913 }
914
915 // Now we're in the harder dynamic case.
916 Type *Ty = AI.getAllocatedType();
917 unsigned Align =
918 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
919
920 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
921
922 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
923 if (MRI->getType(NumElts) != IntPtrTy) {
924 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
925 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
926 NumElts = ExtElts;
927 }
928
929 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
930 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
Tim Northoverc2f89562017-02-14 20:56:18 +0000931 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
Tim Northoverc3e3f592017-02-03 18:22:45 +0000932 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
933
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000934 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000935 auto &TLI = *MF->getSubtarget().getTargetLowering();
936 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
937
938 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
939 MIRBuilder.buildCopy(SPTmp, SPReg);
940
Tim Northoverc2f89562017-02-14 20:56:18 +0000941 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
942 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000943
944 // Handle alignment. We have to realign if the allocation granule was smaller
945 // than stack alignment, or the specific alloca requires more than stack
946 // alignment.
947 unsigned StackAlign =
948 MF->getSubtarget().getFrameLowering()->getStackAlignment();
949 Align = std::max(Align, StackAlign);
950 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
951 // Round the size of the allocation up to the stack alignment size
952 // by add SA-1 to the size. This doesn't overflow because we're computing
953 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +0000954 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
955 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
956 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +0000957 }
958
Tim Northoverc2f89562017-02-14 20:56:18 +0000959 MIRBuilder.buildCopy(SPReg, AllocTmp);
960 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000961
962 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
963 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +0000964 return true;
965}
966
Tim Northover4a652222017-02-15 23:22:33 +0000967bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
968 // FIXME: We may need more info about the type. Because of how LLT works,
969 // we're completely discarding the i64/double distinction here (amongst
970 // others). Fortunately the ABIs I know of where that matters don't use va_arg
971 // anyway but that's not guaranteed.
972 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
973 .addDef(getOrCreateVReg(U))
974 .addUse(getOrCreateVReg(*U.getOperand(0)))
975 .addImm(DL->getABITypeAlignment(U.getType()));
976 return true;
977}
978
Tim Northoverc53606e2016-12-07 21:29:15 +0000979bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000980 const PHINode &PI = cast<PHINode>(U);
Tim Northover25d12862016-09-09 11:47:31 +0000981 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
Tim Northover97d0cb32016-08-05 17:16:40 +0000982 MIB.addDef(getOrCreateVReg(PI));
983
984 PendingPHIs.emplace_back(&PI, MIB.getInstr());
985 return true;
986}
987
988void IRTranslator::finishPendingPhis() {
989 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
990 const PHINode *PI = Phi.first;
Tim Northoverc53606e2016-12-07 21:29:15 +0000991 MachineInstrBuilder MIB(*MF, Phi.second);
Tim Northover97d0cb32016-08-05 17:16:40 +0000992
993 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
994 // won't create extra control flow here, otherwise we need to find the
995 // dominating predecessor here (or perhaps force the weirder IRTranslators
996 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +0000997 SmallSet<const BasicBlock *, 4> HandledPreds;
998
Tim Northover97d0cb32016-08-05 17:16:40 +0000999 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001000 auto IRPred = PI->getIncomingBlock(i);
1001 if (HandledPreds.count(IRPred))
1002 continue;
1003
1004 HandledPreds.insert(IRPred);
1005 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
1006 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1007 assert(Pred->isSuccessor(MIB->getParent()) &&
1008 "incorrect CFG at MachineBasicBlock level");
1009 MIB.addUse(ValReg);
1010 MIB.addMBB(Pred);
1011 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001012 }
1013 }
1014}
1015
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001016bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001017 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001018 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001019#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001020 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001021#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001022 default:
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001023 if (!TPC->isGlobalISelAbortEnabled())
1024 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001025 llvm_unreachable("unknown opcode");
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001026 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001027}
1028
Tim Northover5ed648e2016-08-09 21:28:04 +00001029bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001030 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001031 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001032 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001033 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001034 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001035 EntryBuilder.buildUndef(Reg);
Tim Northover8e0c53a2016-08-11 21:40:55 +00001036 else if (isa<ConstantPointerNull>(C))
Tim Northover9267ac52016-12-05 21:47:07 +00001037 EntryBuilder.buildConstant(Reg, 0);
Tim Northover032548f2016-09-12 12:10:41 +00001038 else if (auto GV = dyn_cast<GlobalValue>(&C))
1039 EntryBuilder.buildGlobalValue(Reg, GV);
Tim Northover357f1be2016-08-10 23:02:41 +00001040 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1041 switch(CE->getOpcode()) {
1042#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001043 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001044#include "llvm/IR/Instruction.def"
1045 default:
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001046 if (!TPC->isGlobalISelAbortEnabled())
1047 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001048 llvm_unreachable("unknown opcode");
1049 }
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001050 } else if (!TPC->isGlobalISelAbortEnabled())
1051 return false;
1052 else
Tim Northoverd403a3d2016-08-09 23:01:30 +00001053 llvm_unreachable("unhandled constant kind");
Tim Northover5ed648e2016-08-09 21:28:04 +00001054
Tim Northoverd403a3d2016-08-09 23:01:30 +00001055 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001056}
1057
Tim Northover0d510442016-08-11 16:21:29 +00001058void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001059 // Release the memory used by the different maps we
1060 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001061 PendingPHIs.clear();
Quentin Colombetccd77252016-02-11 21:48:32 +00001062 ValToVReg.clear();
Tim Northovercdf23f12016-10-31 18:30:59 +00001063 FrameIndices.clear();
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001064 Constants.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001065 MachinePreds.clear();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001066}
1067
Tim Northover50db7f412016-12-07 21:17:47 +00001068bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1069 MF = &CurMF;
1070 const Function &F = *MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001071 if (F.empty())
1072 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001073 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001074 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001075 EntryBuilder.setMF(*MF);
1076 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001077 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001078 TPC = &getAnalysis<TargetPassConfig>();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001079 ORE = make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001080
Tim Northover14e7f732016-08-05 17:50:36 +00001081 assert(PendingPHIs.empty() && "stale PHIs");
1082
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001083 // Release the per-function state when we return, whether we succeeded or not.
1084 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1085
Tim Northover05cc4852016-12-07 21:05:38 +00001086 // Setup a separate basic-block for the arguments and constants, falling
1087 // through to the IR-level Function's entry block.
Tim Northover50db7f412016-12-07 21:17:47 +00001088 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1089 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001090 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1091 EntryBuilder.setMBB(*EntryBB);
1092
1093 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001094 SmallVector<unsigned, 8> VRegArgs;
1095 for (const Argument &Arg: F.args())
Quentin Colombete225e252016-03-11 17:27:54 +00001096 VRegArgs.push_back(getOrCreateVReg(Arg));
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001097 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001098 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1099 MF->getFunction()->getSubprogram(),
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001100 &MF->getFunction()->getEntryBlock());
1101 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1102 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001103 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001104 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001105
Tim Northover05cc4852016-12-07 21:05:38 +00001106 // And translate the function!
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001107 for (const BasicBlock &BB: F) {
Quentin Colombet53237a92016-03-11 17:27:43 +00001108 MachineBasicBlock &MBB = getOrCreateBB(BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001109 // Set the insertion point of all the following translations to
1110 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001111 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001112
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001113 for (const Instruction &Inst: BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001114 if (translate(Inst))
1115 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001116
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001117 std::string InstStrStorage;
1118 raw_string_ostream InstStr(InstStrStorage);
1119 InstStr << Inst;
1120
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001121 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1122 Inst.getDebugLoc(), &BB);
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001123 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1124 << ": '" << InstStr.str() << "'";
1125 reportTranslationError(*MF, *TPC, *ORE, R);
1126 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001127 }
1128 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001129
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001130 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001131
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001132 // Now that the MachineFrameInfo has been configured, no further changes to
1133 // the reserved registers are possible.
1134 MRI->freezeReservedRegs(*MF);
Quentin Colombet327f9422016-12-15 23:32:25 +00001135
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001136 // Merge the argument lowering and constants block with its single
1137 // successor, the LLVM-IR entry block. We want the basic block to
1138 // be maximal.
1139 assert(EntryBB->succ_size() == 1 &&
1140 "Custom BB used for lowering should have only one successor");
1141 // Get the successor of the current entry block.
1142 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1143 assert(NewEntryBB.pred_size() == 1 &&
1144 "LLVM-IR entry block has a predecessor!?");
1145 // Move all the instruction from the current entry block to the
1146 // new entry block.
1147 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1148 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001149
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001150 // Update the live-in information for the new entry block.
1151 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1152 NewEntryBB.addLiveIn(LiveIn);
1153 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001154
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001155 // Get rid of the now empty basic block.
1156 EntryBB->removeSuccessor(&NewEntryBB);
1157 MF->remove(EntryBB);
1158 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001159
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001160 assert(&MF->front() == &NewEntryBB &&
1161 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001162
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001163 return false;
1164}