blob: 01823527f1ff1c8061689c954e681b29ce871df5 [file] [log] [blame]
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001//===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
Quentin Colombet105cf2b2016-01-20 20:58:56 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Quentin Colombet105cf2b2016-01-20 20:58:56 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements the IRTranslator class.
10//===----------------------------------------------------------------------===//
11
12#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000013#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000014#include "llvm/ADT/STLExtras.h"
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"
Adam Nemet0965da22017-10-09 23:19:02 +000018#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Jessica Paquette2e35dc52019-01-28 19:22:29 +000019#include "llvm/Analysis/ValueTracking.h"
Tim Northovera9105be2016-11-09 22:39:54 +000020#include "llvm/CodeGen/Analysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/CodeGen/GlobalISel/CallLowering.h"
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000022#include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000023#include "llvm/CodeGen/LowLevelType.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northoverbd505462016-07-22 16:59:52 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000027#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineMemOperand.h"
29#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Braun90ad6832018-07-13 00:08:38 +000031#include "llvm/CodeGen/StackProtector.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetFrameLowering.h"
33#include "llvm/CodeGen/TargetLowering.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000034#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetRegisterInfo.h"
36#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000037#include "llvm/IR/BasicBlock.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000038#include "llvm/IR/CFG.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000039#include "llvm/IR/Constant.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000042#include "llvm/IR/DebugInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000043#include "llvm/IR/DerivedTypes.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000044#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000045#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000046#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instructions.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000049#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000050#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/Metadata.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000053#include "llvm/IR/Type.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000054#include "llvm/IR/User.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000055#include "llvm/IR/Value.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000056#include "llvm/MC/MCContext.h"
57#include "llvm/Pass.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/CodeGen.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/LowLevelTypeImpl.h"
63#include "llvm/Support/MathExtras.h"
64#include "llvm/Support/raw_ostream.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000065#include "llvm/Target/TargetIntrinsicInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000066#include "llvm/Target/TargetMachine.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000067#include <algorithm>
68#include <cassert>
69#include <cstdint>
70#include <iterator>
71#include <string>
72#include <utility>
73#include <vector>
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000074
75#define DEBUG_TYPE "irtranslator"
76
Quentin Colombet105cf2b2016-01-20 20:58:56 +000077using namespace llvm;
78
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000079static cl::opt<bool>
80 EnableCSEInIRTranslator("enable-cse-in-irtranslator",
81 cl::desc("Should enable CSE in irtranslator"),
82 cl::Optional, cl::init(false));
Quentin Colombet105cf2b2016-01-20 20:58:56 +000083char IRTranslator::ID = 0;
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000084
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000085INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
86 false, false)
87INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000088INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000089INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000090 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000091
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000092static void reportTranslationError(MachineFunction &MF,
93 const TargetPassConfig &TPC,
94 OptimizationRemarkEmitter &ORE,
95 OptimizationRemarkMissed &R) {
96 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
97
98 // Print the function name explicitly if we don't have a debug location (which
99 // makes the diagnostic less useful) or if we're going to emit a raw error.
100 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
101 R << (" (in function: " + MF.getName() + ")").str();
102
103 if (TPC.isGlobalISelAbortEnabled())
104 report_fatal_error(R.getMsg());
105 else
106 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +0000107}
108
Eugene Zelenko76bf48d2017-06-26 22:44:03 +0000109IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
Quentin Colombet39293d32016-03-08 01:38:55 +0000110 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +0000111}
112
Daniel Sanders3b390402018-10-31 17:31:23 +0000113#ifndef NDEBUG
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000114namespace {
Daniel Sanders3b390402018-10-31 17:31:23 +0000115/// Verify that every instruction created has the same DILocation as the
116/// instruction being translated.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000117class DILocationVerifier : public GISelChangeObserver {
Daniel Sanders3b390402018-10-31 17:31:23 +0000118 const Instruction *CurrInst = nullptr;
119
120public:
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000121 DILocationVerifier() = default;
122 ~DILocationVerifier() = default;
Daniel Sanders3b390402018-10-31 17:31:23 +0000123
124 const Instruction *getCurrentInst() const { return CurrInst; }
125 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
126
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000127 void erasingInstr(MachineInstr &MI) override {}
128 void changingInstr(MachineInstr &MI) override {}
129 void changedInstr(MachineInstr &MI) override {}
130
131 void createdInstr(MachineInstr &MI) override {
Daniel Sanders3b390402018-10-31 17:31:23 +0000132 assert(getCurrentInst() && "Inserted instruction without a current MI");
133
134 // Only print the check message if we're actually checking it.
135#ifndef NDEBUG
136 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
137 << " was copied to " << MI);
138#endif
139 assert(CurrInst->getDebugLoc() == MI.getDebugLoc() &&
140 "Line info was not transferred to all instructions");
141 }
Daniel Sanders3b390402018-10-31 17:31:23 +0000142};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000143} // namespace
Daniel Sanders3b390402018-10-31 17:31:23 +0000144#endif // ifndef NDEBUG
145
146
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000147void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun90ad6832018-07-13 00:08:38 +0000148 AU.addRequired<StackProtector>();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000149 AU.addRequired<TargetPassConfig>();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000150 AU.addRequired<GISelCSEAnalysisWrapperPass>();
Matthias Braun90ad6832018-07-13 00:08:38 +0000151 getSelectionDAGFallbackAnalysisUsage(AU);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000152 MachineFunctionPass::getAnalysisUsage(AU);
153}
154
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000155IRTranslator::ValueToVRegInfo::VRegListT &
156IRTranslator::allocateVRegs(const Value &Val) {
157 assert(!VMap.contains(Val) && "Value already allocated in VMap");
158 auto *Regs = VMap.getVRegs(Val);
159 auto *Offsets = VMap.getOffsets(Val);
160 SmallVector<LLT, 4> SplitTys;
161 computeValueLLTs(*DL, *Val.getType(), SplitTys,
162 Offsets->empty() ? Offsets : nullptr);
163 for (unsigned i = 0; i < SplitTys.size(); ++i)
164 Regs->push_back(0);
165 return *Regs;
166}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000167
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000168ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
169 auto VRegsIt = VMap.findVRegs(Val);
170 if (VRegsIt != VMap.vregs_end())
171 return *VRegsIt->second;
172
173 if (Val.getType()->isVoidTy())
174 return *VMap.getVRegs(Val);
175
176 // Create entry for this type.
177 auto *VRegs = VMap.getVRegs(Val);
178 auto *Offsets = VMap.getOffsets(Val);
179
Tim Northover9e35f1e2017-01-25 20:58:22 +0000180 assert(Val.getType()->isSized() &&
181 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000182
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000183 SmallVector<LLT, 4> SplitTys;
184 computeValueLLTs(*DL, *Val.getType(), SplitTys,
185 Offsets->empty() ? Offsets : nullptr);
186
187 if (!isa<Constant>(Val)) {
188 for (auto Ty : SplitTys)
189 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
190 return *VRegs;
191 }
192
193 if (Val.getType()->isAggregateType()) {
194 // UndefValue, ConstantAggregateZero
195 auto &C = cast<Constant>(Val);
196 unsigned Idx = 0;
197 while (auto Elt = C.getAggregateElement(Idx++)) {
198 auto EltRegs = getOrCreateVRegs(*Elt);
Fangrui Song75709322018-11-17 01:44:25 +0000199 llvm::copy(EltRegs, std::back_inserter(*VRegs));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000200 }
201 } else {
202 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
203 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
204 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000205 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000206 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000207 MF->getFunction().getSubprogram(),
208 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000209 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
210 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000211 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000212 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000213 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000214
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000215 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000216}
217
Tim Northovercdf23f12016-10-31 18:30:59 +0000218int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
219 if (FrameIndices.find(&AI) != FrameIndices.end())
220 return FrameIndices[&AI];
221
Tim Northovercdf23f12016-10-31 18:30:59 +0000222 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
223 unsigned Size =
224 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
225
226 // Always allocate at least one byte.
227 Size = std::max(Size, 1u);
228
229 unsigned Alignment = AI.getAlignment();
230 if (!Alignment)
231 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
232
233 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000234 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000235 return FI;
236}
237
Tim Northoverad2b7172016-07-26 20:23:26 +0000238unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
239 unsigned Alignment = 0;
240 Type *ValTy = nullptr;
241 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
242 Alignment = SI->getAlignment();
243 ValTy = SI->getValueOperand()->getType();
244 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
245 Alignment = LI->getAlignment();
246 ValTy = LI->getType();
Daniel Sanders94813992018-07-09 19:33:40 +0000247 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
248 // TODO(PR27168): This instruction has no alignment attribute, but unlike
249 // the default alignment for load/store, the default here is to assume
250 // it has NATURAL alignment, not DataLayout-specified alignment.
251 const DataLayout &DL = AI->getModule()->getDataLayout();
252 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
253 ValTy = AI->getCompareOperand()->getType();
254 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
255 // TODO(PR27168): This instruction has no alignment attribute, but unlike
256 // the default alignment for load/store, the default here is to assume
257 // it has NATURAL alignment, not DataLayout-specified alignment.
258 const DataLayout &DL = AI->getModule()->getDataLayout();
259 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
260 ValTy = AI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000261 } else {
262 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
263 R << "unable to translate memop: " << ore::NV("Opcode", &I);
264 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000265 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000266 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000267
268 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
269}
270
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000271MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000272 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000273 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000274 return *MBB;
275}
276
Tim Northoverb6636fd2017-01-17 22:13:50 +0000277void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
278 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
279 MachinePreds[Edge].push_back(NewPred);
280}
281
Tim Northoverc53606e2016-12-07 21:29:15 +0000282bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
283 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000284 // FIXME: handle signed/unsigned wrapping flags.
285
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000286 // Get or create a virtual register for each value.
287 // Unless the value is a Constant => loadimm cst?
288 // or inline constant each time?
289 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000290 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
291 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
292 unsigned Res = getOrCreateVReg(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000293 uint16_t Flags = 0;
Michael Berg894c39f2018-09-19 18:52:08 +0000294 if (isa<Instruction>(U)) {
Michael Berg894c39f2018-09-19 18:52:08 +0000295 const Instruction &I = cast<Instruction>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000296 Flags = MachineInstr::copyFlagsFromInstruction(I);
Michael Berg894c39f2018-09-19 18:52:08 +0000297 }
Michael Bergf0d81a32019-02-06 19:57:06 +0000298
299 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000300 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000301}
302
Volkan Keles20d3c422017-03-07 18:03:28 +0000303bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
304 // -0.0 - X --> G_FNEG
305 if (isa<Constant>(U.getOperand(0)) &&
306 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
307 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
308 .addDef(getOrCreateVReg(U))
309 .addUse(getOrCreateVReg(*U.getOperand(1)));
310 return true;
311 }
312 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
313}
314
Cameron McInallycbde0d92018-11-13 18:15:47 +0000315bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
316 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
317 .addDef(getOrCreateVReg(U))
Amara Emerson203760a2019-01-26 23:47:09 +0000318 .addUse(getOrCreateVReg(*U.getOperand(0)));
Cameron McInallycbde0d92018-11-13 18:15:47 +0000319 return true;
320}
321
Tim Northoverc53606e2016-12-07 21:29:15 +0000322bool IRTranslator::translateCompare(const User &U,
323 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000324 const CmpInst *CI = dyn_cast<CmpInst>(&U);
325 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
326 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
327 unsigned Res = getOrCreateVReg(U);
328 CmpInst::Predicate Pred =
329 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
330 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000331 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000332 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000333 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000334 MIRBuilder.buildCopy(
335 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
336 else if (Pred == CmpInst::FCMP_TRUE)
337 MIRBuilder.buildCopy(
338 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Michael Bergc6a52452018-12-18 17:54:52 +0000339 else {
Michael Bergf0d81a32019-02-06 19:57:06 +0000340 MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
341 MachineInstr::copyFlagsFromInstruction(*CI));
Michael Bergc6a52452018-12-18 17:54:52 +0000342 }
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000343
Tim Northoverde3aea0412016-08-17 20:25:25 +0000344 return true;
345}
346
Tim Northoverc53606e2016-12-07 21:29:15 +0000347bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000348 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000349 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000350 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
351 Ret = nullptr;
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000352
353 ArrayRef<unsigned> VRegs;
354 if (Ret)
355 VRegs = getOrCreateVRegs(*Ret);
356
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000357 // The target may mess up with the insertion point, but
358 // this is not important as a return is the last instruction
359 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000360
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000361 return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000362}
363
Tim Northoverc53606e2016-12-07 21:29:15 +0000364bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000365 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000366 unsigned Succ = 0;
367 if (!BrInst.isUnconditional()) {
368 // We want a G_BRCOND to the true BB followed by an unconditional branch.
369 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
370 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000371 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000372 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000373 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000374
375 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000376 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000377 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
378
379 // If the unconditional target is the layout successor, fallthrough.
380 if (!CurBB.isLayoutSuccessor(&TgtBB))
381 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000382
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000383 // Link successors.
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000384 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000385 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000386 return true;
387}
388
Kristof Beylseced0712017-01-05 11:28:51 +0000389bool IRTranslator::translateSwitch(const User &U,
390 MachineIRBuilder &MIRBuilder) {
391 // For now, just translate as a chain of conditional branches.
392 // FIXME: could we share most of the logic/code in
393 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
394 // At first sight, it seems most of the logic in there is independent of
395 // SelectionDAG-specifics and a lot of work went in to optimize switch
396 // lowering in there.
397
398 const SwitchInst &SwInst = cast<SwitchInst>(U);
399 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000400 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000401
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000402 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000403 for (auto &CaseIt : SwInst.cases()) {
404 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
405 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
406 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000407 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
408 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000409 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000410
Tim Northoverb6636fd2017-01-17 22:13:50 +0000411 MIRBuilder.buildBrCond(Tst, TrueMBB);
412 CurMBB.addSuccessor(&TrueMBB);
413 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000414
Tim Northoverb6636fd2017-01-17 22:13:50 +0000415 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000416 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000417 // Insert the comparison blocks one after the other.
418 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000419 MIRBuilder.buildBr(*FalseMBB);
420 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000421
Tim Northoverb6636fd2017-01-17 22:13:50 +0000422 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000423 }
424 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000425 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000426 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000427 MIRBuilder.buildBr(DefaultMBB);
428 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
429 CurMBB.addSuccessor(&DefaultMBB);
430 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000431
432 return true;
433}
434
Kristof Beyls65a12c02017-01-30 09:13:18 +0000435bool IRTranslator::translateIndirectBr(const User &U,
436 MachineIRBuilder &MIRBuilder) {
437 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
438
439 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
440 MIRBuilder.buildBrIndirect(Tgt);
441
442 // Link successors.
443 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000444 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000445 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000446
447 return true;
448}
449
Tim Northoverc53606e2016-12-07 21:29:15 +0000450bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000451 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000452
Tim Northover7152dca2016-10-19 15:55:06 +0000453 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
454 : MachineMemOperand::MONone;
455 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000456
Amara Emersond78d65c2017-11-30 20:06:02 +0000457 if (DL->getTypeStoreSize(LI.getType()) == 0)
458 return true;
459
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000460 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
461 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
462 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000463
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000464 for (unsigned i = 0; i < Regs.size(); ++i) {
465 unsigned Addr = 0;
466 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
467
468 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
469 unsigned BaseAlign = getMemOpAlignment(LI);
470 auto MMO = MF->getMachineMemOperand(
471 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
472 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
473 LI.getSyncScopeID(), LI.getOrdering());
474 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
475 }
476
Tim Northoverad2b7172016-07-26 20:23:26 +0000477 return true;
478}
479
Tim Northoverc53606e2016-12-07 21:29:15 +0000480bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000481 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000482 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
483 : MachineMemOperand::MONone;
484 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000485
Amara Emersond78d65c2017-11-30 20:06:02 +0000486 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
487 return true;
488
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000489 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
490 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
491 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000492
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000493 for (unsigned i = 0; i < Vals.size(); ++i) {
494 unsigned Addr = 0;
495 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
496
497 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
498 unsigned BaseAlign = getMemOpAlignment(SI);
499 auto MMO = MF->getMachineMemOperand(
500 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
501 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
502 SI.getSyncScopeID(), SI.getOrdering());
503 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
504 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000505 return true;
506}
507
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000508static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000509 const Value *Src = U.getOperand(0);
510 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000511
Tim Northover6f80b082016-08-19 17:47:05 +0000512 // getIndexedOffsetInType is designed for GEPs, so the first index is the
513 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000514 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000515 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000516
517 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
518 for (auto Idx : EVI->indices())
519 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000520 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
521 for (auto Idx : IVI->indices())
522 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000523 } else {
524 for (unsigned i = 1; i < U.getNumOperands(); ++i)
525 Indices.push_back(U.getOperand(i));
526 }
Tim Northover6f80b082016-08-19 17:47:05 +0000527
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000528 return 8 * static_cast<uint64_t>(
529 DL.getIndexedOffsetInType(Src->getType(), Indices));
530}
Tim Northover6f80b082016-08-19 17:47:05 +0000531
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000532bool IRTranslator::translateExtractValue(const User &U,
533 MachineIRBuilder &MIRBuilder) {
534 const Value *Src = U.getOperand(0);
535 uint64_t Offset = getOffsetFromIndices(U, *DL);
536 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
537 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
Fangrui Songcecc4352019-04-12 02:02:06 +0000538 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000539 auto &DstRegs = allocateVRegs(U);
540
541 for (unsigned i = 0; i < DstRegs.size(); ++i)
542 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000543
544 return true;
545}
546
Tim Northoverc53606e2016-12-07 21:29:15 +0000547bool IRTranslator::translateInsertValue(const User &U,
548 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000549 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000550 uint64_t Offset = getOffsetFromIndices(U, *DL);
551 auto &DstRegs = allocateVRegs(U);
552 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
553 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
554 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
555 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000556
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000557 for (unsigned i = 0; i < DstRegs.size(); ++i) {
558 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
559 DstRegs[i] = *InsertedIt++;
560 else
561 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000562 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000563
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000564 return true;
565}
566
Tim Northoverc53606e2016-12-07 21:29:15 +0000567bool IRTranslator::translateSelect(const User &U,
568 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000569 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000570 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
571 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
572 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
573
Michael Bergc6a52452018-12-18 17:54:52 +0000574 const SelectInst &SI = cast<SelectInst>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000575 uint16_t Flags = 0;
576 if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
577 Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
578
Michael Bergc6a52452018-12-18 17:54:52 +0000579 for (unsigned i = 0; i < ResRegs.size(); ++i) {
Michael Bergf0d81a32019-02-06 19:57:06 +0000580 MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
581 {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
Michael Bergc6a52452018-12-18 17:54:52 +0000582 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000583
Tim Northover5a28c362016-08-19 20:09:07 +0000584 return true;
585}
586
Tim Northoverc53606e2016-12-07 21:29:15 +0000587bool IRTranslator::translateBitCast(const User &U,
588 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000589 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000590 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
591 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000592 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000593 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000594 // If we already assigned a vreg for this bitcast, we can't change that.
595 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000596 if (!Regs.empty())
597 MIRBuilder.buildCopy(Regs[0], SrcReg);
598 else {
599 Regs.push_back(SrcReg);
600 VMap.getOffsets(U)->push_back(0);
601 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000602 return true;
603 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000604 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000605}
606
Tim Northoverc53606e2016-12-07 21:29:15 +0000607bool IRTranslator::translateCast(unsigned Opcode, const User &U,
608 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000609 unsigned Op = getOrCreateVReg(*U.getOperand(0));
610 unsigned Res = getOrCreateVReg(U);
Aditya Nandakumar92663372019-04-18 02:19:29 +0000611 MIRBuilder.buildInstr(Opcode, {Res}, {Op});
Tim Northover7c9eba92016-07-25 21:01:29 +0000612 return true;
613}
614
Tim Northoverc53606e2016-12-07 21:29:15 +0000615bool IRTranslator::translateGetElementPtr(const User &U,
616 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000617 // FIXME: support vector GEPs.
618 if (U.getType()->isVectorTy())
619 return false;
620
621 Value &Op0 = *U.getOperand(0);
622 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000623 Type *PtrIRTy = Op0.getType();
624 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
625 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
626 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000627
628 int64_t Offset = 0;
629 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
630 GTI != E; ++GTI) {
631 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000632 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000633 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
634 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
635 continue;
636 } else {
637 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
638
639 // If this is a scalar constant or a splat vector of constants,
640 // handle it quickly.
641 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
642 Offset += ElementSize * CI->getSExtValue();
643 continue;
644 }
645
646 if (Offset != 0) {
647 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Amara Emerson946b1242019-04-15 05:04:20 +0000648 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
649 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
650 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetMIB.getReg(0));
Tim Northovera7653b32016-09-12 11:20:22 +0000651
652 BaseReg = NewBaseReg;
653 Offset = 0;
654 }
655
Tim Northovera7653b32016-09-12 11:20:22 +0000656 unsigned IdxReg = getOrCreateVReg(*Idx);
657 if (MRI->getType(IdxReg) != OffsetTy) {
658 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
659 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
660 IdxReg = NewIdxReg;
661 }
662
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000663 // N = N + Idx * ElementSize;
664 // Avoid doing it for ElementSize of 1.
665 unsigned GepOffsetReg;
666 if (ElementSize != 1) {
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000667 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
Amara Emerson946b1242019-04-15 05:04:20 +0000668 auto ElementSizeMIB = MIRBuilder.buildConstant(
669 getLLTForType(*OffsetIRTy, *DL), ElementSize);
670 MIRBuilder.buildMul(GepOffsetReg, ElementSizeMIB.getReg(0), IdxReg);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000671 } else
672 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000673
674 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000675 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000676 BaseReg = NewBaseReg;
677 }
678 }
679
680 if (Offset != 0) {
Amara Emerson946b1242019-04-15 05:04:20 +0000681 auto OffsetMIB =
682 MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
683 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
Tim Northovera7653b32016-09-12 11:20:22 +0000684 return true;
685 }
686
687 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
688 return true;
689}
690
Tim Northover79f43f12017-01-30 19:33:07 +0000691bool IRTranslator::translateMemfunc(const CallInst &CI,
692 MachineIRBuilder &MIRBuilder,
693 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000694 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000695 Type *DstTy = CI.getArgOperand(0)->getType();
696 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000697 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
698 return false;
699
700 SmallVector<CallLowering::ArgInfo, 8> Args;
701 for (int i = 0; i < 3; ++i) {
702 const auto &Arg = CI.getArgOperand(i);
703 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
704 }
705
Tim Northover79f43f12017-01-30 19:33:07 +0000706 const char *Callee;
707 switch (ID) {
708 case Intrinsic::memmove:
709 case Intrinsic::memcpy: {
710 Type *SrcTy = CI.getArgOperand(1)->getType();
711 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
712 return false;
713 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
714 break;
715 }
716 case Intrinsic::memset:
717 Callee = "memset";
718 break;
719 default:
720 return false;
721 }
Tim Northover3f186032016-10-18 20:03:45 +0000722
Diana Picusd79253a2017-03-20 14:40:18 +0000723 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
724 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000725 CallLowering::ArgInfo(0, CI.getType()), Args);
726}
Tim Northovera7653b32016-09-12 11:20:22 +0000727
Tim Northoverc53606e2016-12-07 21:29:15 +0000728void IRTranslator::getStackGuard(unsigned DstReg,
729 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000730 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
731 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000732 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
733 MIB.addDef(DstReg);
734
Tim Northover50db7f412016-12-07 21:17:47 +0000735 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000736 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000737 if (!Global)
738 return;
739
740 MachinePointerInfo MPInfo(Global);
Tim Northovercdf23f12016-10-31 18:30:59 +0000741 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
742 MachineMemOperand::MODereferenceable;
Chandler Carruthc73c0302018-08-16 21:30:05 +0000743 MachineMemOperand *MemRef =
Tim Northover50db7f412016-12-07 21:17:47 +0000744 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000745 DL->getPointerABIAlignment(0));
Chandler Carruthc73c0302018-08-16 21:30:05 +0000746 MIB.setMemRefs({MemRef});
Tim Northovercdf23f12016-10-31 18:30:59 +0000747}
748
Tim Northover1e656ec2016-12-08 22:44:00 +0000749bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
750 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000751 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000752 MIRBuilder.buildInstr(Op)
753 .addDef(ResRegs[0])
754 .addDef(ResRegs[1])
755 .addUse(getOrCreateVReg(*CI.getOperand(0)))
756 .addUse(getOrCreateVReg(*CI.getOperand(1)));
Tim Northover1e656ec2016-12-08 22:44:00 +0000757
Tim Northover1e656ec2016-12-08 22:44:00 +0000758 return true;
759}
760
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000761unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000762 switch (ID) {
763 default:
764 break;
Jessica Paquette0e71e732019-02-12 17:28:17 +0000765 case Intrinsic::bswap:
766 return TargetOpcode::G_BSWAP;
Jessica Paquettee288c522019-02-06 17:25:54 +0000767 case Intrinsic::ceil:
768 return TargetOpcode::G_FCEIL;
769 case Intrinsic::cos:
770 return TargetOpcode::G_FCOS;
771 case Intrinsic::ctpop:
772 return TargetOpcode::G_CTPOP;
773 case Intrinsic::exp:
774 return TargetOpcode::G_FEXP;
775 case Intrinsic::exp2:
776 return TargetOpcode::G_FEXP2;
777 case Intrinsic::fabs:
778 return TargetOpcode::G_FABS;
Matt Arsenault9dba67f2019-02-11 17:05:20 +0000779 case Intrinsic::canonicalize:
780 return TargetOpcode::G_FCANONICALIZE;
Jessica Paquettef472f312019-02-11 17:16:32 +0000781 case Intrinsic::floor:
782 return TargetOpcode::G_FFLOOR;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000783 case Intrinsic::fma:
784 return TargetOpcode::G_FMA;
Jessica Paquettee288c522019-02-06 17:25:54 +0000785 case Intrinsic::log:
786 return TargetOpcode::G_FLOG;
787 case Intrinsic::log2:
788 return TargetOpcode::G_FLOG2;
789 case Intrinsic::log10:
790 return TargetOpcode::G_FLOG10;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000791 case Intrinsic::pow:
792 return TargetOpcode::G_FPOW;
Jessica Paquettead69af32019-04-19 21:46:12 +0000793 case Intrinsic::rint:
794 return TargetOpcode::G_FRINT;
Jessica Paquettee288c522019-02-06 17:25:54 +0000795 case Intrinsic::round:
796 return TargetOpcode::G_INTRINSIC_ROUND;
797 case Intrinsic::sin:
798 return TargetOpcode::G_FSIN;
799 case Intrinsic::sqrt:
800 return TargetOpcode::G_FSQRT;
801 case Intrinsic::trunc:
802 return TargetOpcode::G_INTRINSIC_TRUNC;
803 }
804 return Intrinsic::not_intrinsic;
805}
806
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000807bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
808 Intrinsic::ID ID,
809 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000810
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000811 unsigned Op = getSimpleIntrinsicOpcode(ID);
Jessica Paquettee288c522019-02-06 17:25:54 +0000812
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000813 // Is this a simple intrinsic?
Jessica Paquettee288c522019-02-06 17:25:54 +0000814 if (Op == Intrinsic::not_intrinsic)
815 return false;
816
817 // Yes. Let's translate it.
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000818 SmallVector<llvm::SrcOp, 4> VRegs;
819 for (auto &Arg : CI.arg_operands())
820 VRegs.push_back(getOrCreateVReg(*Arg));
821
822 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
Michael Bergf0d81a32019-02-06 19:57:06 +0000823 MachineInstr::copyFlagsFromInstruction(CI));
Jessica Paquettee288c522019-02-06 17:25:54 +0000824 return true;
825}
826
Tim Northoverc53606e2016-12-07 21:29:15 +0000827bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
828 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000829
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000830 // If this is a simple intrinsic (that is, we just need to add a def of
831 // a vreg, and uses for each arg operand, then translate it.
832 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
Jessica Paquettee288c522019-02-06 17:25:54 +0000833 return true;
834
Tim Northover91c81732016-08-19 17:17:06 +0000835 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000836 default:
837 break;
Tim Northover0e011702017-02-10 19:10:38 +0000838 case Intrinsic::lifetime_start:
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000839 case Intrinsic::lifetime_end: {
840 // No stack colouring in O0, discard region information.
841 if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
842 return true;
843
844 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
845 : TargetOpcode::LIFETIME_END;
846
847 // Get the underlying objects for the location passed on the lifetime
848 // marker.
849 SmallVector<Value *, 4> Allocas;
850 GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
851
852 // Iterate over each underlying object, creating lifetime markers for each
853 // static alloca. Quit if we find a non-static alloca.
854 for (Value *V : Allocas) {
855 AllocaInst *AI = dyn_cast<AllocaInst>(V);
856 if (!AI)
857 continue;
858
859 if (!AI->isStaticAlloca())
860 return true;
861
862 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
863 }
Tim Northover0e011702017-02-10 19:10:38 +0000864 return true;
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000865 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000866 case Intrinsic::dbg_declare: {
867 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
868 assert(DI.getVariable() && "Missing variable");
869
870 const Value *Address = DI.getAddress();
871 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000872 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000873 return true;
874 }
875
Tim Northover09aac4a2017-01-26 23:39:14 +0000876 assert(DI.getVariable()->isValidLocationForIntrinsic(
877 MIRBuilder.getDebugLoc()) &&
878 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000879 auto AI = dyn_cast<AllocaInst>(Address);
880 if (AI && AI->isStaticAlloca()) {
881 // Static allocas are tracked at the MF level, no need for DBG_VALUE
882 // instructions (in fact, they get ignored if they *do* exist).
883 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
884 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Josh Stonef446fac2018-09-11 17:52:01 +0000885 } else {
886 // A dbg.declare describes the address of a source variable, so lower it
887 // into an indirect DBG_VALUE.
888 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
889 DI.getVariable(), DI.getExpression());
890 }
Tim Northoverb58346f2016-12-08 22:44:13 +0000891 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000892 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000893 case Intrinsic::dbg_label: {
894 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
895 assert(DI.getLabel() && "Missing label");
896
897 assert(DI.getLabel()->isValidLocationForIntrinsic(
898 MIRBuilder.getDebugLoc()) &&
899 "Expected inlined-at fields to agree");
900
901 MIRBuilder.buildDbgLabel(DI.getLabel());
902 return true;
903 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000904 case Intrinsic::vaend:
905 // No target I know of cares about va_end. Certainly no in-tree target
906 // does. Simplest intrinsic ever!
907 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000908 case Intrinsic::vastart: {
909 auto &TLI = *MF->getSubtarget().getTargetLowering();
910 Value *Ptr = CI.getArgOperand(0);
911 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
912
Matt Arsenault2a645982019-01-31 01:38:47 +0000913 // FIXME: Get alignment
Tim Northoverf19d4672017-02-08 17:57:20 +0000914 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
915 .addUse(getOrCreateVReg(*Ptr))
916 .addMemOperand(MF->getMachineMemOperand(
Matt Arsenault2a645982019-01-31 01:38:47 +0000917 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
Tim Northoverf19d4672017-02-08 17:57:20 +0000918 return true;
919 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000920 case Intrinsic::dbg_value: {
921 // This form of DBG_VALUE is target-independent.
922 const DbgValueInst &DI = cast<DbgValueInst>(CI);
923 const Value *V = DI.getValue();
924 assert(DI.getVariable()->isValidLocationForIntrinsic(
925 MIRBuilder.getDebugLoc()) &&
926 "Expected inlined-at fields to agree");
927 if (!V) {
928 // Currently the optimizer can produce this; insert an undef to
929 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000930 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000931 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000932 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000933 } else {
934 unsigned Reg = getOrCreateVReg(*V);
935 // FIXME: This does not handle register-indirect values at offset 0. The
936 // direct/indirect thing shouldn't really be handled by something as
937 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
938 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000939 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000940 }
941 return true;
942 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000943 case Intrinsic::uadd_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000944 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000945 case Intrinsic::sadd_with_overflow:
946 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
947 case Intrinsic::usub_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000948 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000949 case Intrinsic::ssub_with_overflow:
950 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
951 case Intrinsic::umul_with_overflow:
952 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
953 case Intrinsic::smul_with_overflow:
954 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Volkan Keles92837632018-02-13 00:47:46 +0000955 case Intrinsic::fmuladd: {
956 const TargetMachine &TM = MF->getTarget();
957 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
958 unsigned Dst = getOrCreateVReg(CI);
959 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
960 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
961 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
962 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
963 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
964 // TODO: Revisit this to see if we should move this part of the
965 // lowering to the combiner.
Michael Bergf0d81a32019-02-06 19:57:06 +0000966 MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
967 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +0000968 } else {
969 LLT Ty = getLLTForType(*CI.getType(), *DL);
Michael Bergf0d81a32019-02-06 19:57:06 +0000970 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
971 MachineInstr::copyFlagsFromInstruction(CI));
972 MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
973 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +0000974 }
975 return true;
976 }
Tim Northover3f186032016-10-18 20:03:45 +0000977 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000978 case Intrinsic::memmove:
979 case Intrinsic::memset:
980 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000981 case Intrinsic::eh_typeid_for: {
982 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
983 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000984 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000985 MIRBuilder.buildConstant(Reg, TypeID);
986 return true;
987 }
Tim Northover6e904302016-10-18 20:03:51 +0000988 case Intrinsic::objectsize: {
989 // If we don't know by now, we're never going to know.
990 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
991
992 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
993 return true;
994 }
James Y Knight72f76bf2018-11-07 15:24:12 +0000995 case Intrinsic::is_constant:
996 // If this wasn't constant-folded away by now, then it's not a
997 // constant.
998 MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
999 return true;
Tim Northovercdf23f12016-10-31 18:30:59 +00001000 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +00001001 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001002 return true;
1003 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001004 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +00001005 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +00001006 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001007
1008 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001009 int FI = getOrCreateFrameIndex(*Slot);
1010 MF->getFrameInfo().setStackProtectorIndex(FI);
1011
Tim Northovercdf23f12016-10-31 18:30:59 +00001012 MIRBuilder.buildStore(
1013 GuardVal, getOrCreateVReg(*Slot),
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001014 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1015 MachineMemOperand::MOStore |
1016 MachineMemOperand::MOVolatile,
1017 PtrTy.getSizeInBits() / 8, 8));
Tim Northovercdf23f12016-10-31 18:30:59 +00001018 return true;
1019 }
Jessica Paquetteed233522019-04-02 22:46:31 +00001020 case Intrinsic::stacksave: {
1021 // Save the stack pointer to the location provided by the intrinsic.
1022 unsigned Reg = getOrCreateVReg(CI);
1023 unsigned StackPtr = MF->getSubtarget()
1024 .getTargetLowering()
1025 ->getStackPointerRegisterToSaveRestore();
1026
1027 // If the target doesn't specify a stack pointer, then fall back.
1028 if (!StackPtr)
1029 return false;
1030
1031 MIRBuilder.buildCopy(Reg, StackPtr);
1032 return true;
1033 }
1034 case Intrinsic::stackrestore: {
1035 // Restore the stack pointer from the location provided by the intrinsic.
1036 unsigned Reg = getOrCreateVReg(*CI.getArgOperand(0));
1037 unsigned StackPtr = MF->getSubtarget()
1038 .getTargetLowering()
1039 ->getStackPointerRegisterToSaveRestore();
1040
1041 // If the target doesn't specify a stack pointer, then fall back.
1042 if (!StackPtr)
1043 return false;
1044
1045 MIRBuilder.buildCopy(StackPtr, Reg);
1046 return true;
1047 }
Aditya Nandakumare07b3b72018-08-04 01:22:12 +00001048 case Intrinsic::cttz:
1049 case Intrinsic::ctlz: {
1050 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1051 bool isTrailing = ID == Intrinsic::cttz;
1052 unsigned Opcode = isTrailing
1053 ? Cst->isZero() ? TargetOpcode::G_CTTZ
1054 : TargetOpcode::G_CTTZ_ZERO_UNDEF
1055 : Cst->isZero() ? TargetOpcode::G_CTLZ
1056 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1057 MIRBuilder.buildInstr(Opcode)
1058 .addDef(getOrCreateVReg(CI))
1059 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1060 return true;
1061 }
Jessica Paquetteb328d952018-10-05 21:02:46 +00001062 case Intrinsic::invariant_start: {
1063 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1064 unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1065 MIRBuilder.buildUndef(Undef);
1066 return true;
1067 }
1068 case Intrinsic::invariant_end:
1069 return true;
Tim Northover91c81732016-08-19 17:17:06 +00001070 }
Tim Northover1e656ec2016-12-08 22:44:00 +00001071 return false;
Tim Northover91c81732016-08-19 17:17:06 +00001072}
1073
Tim Northoveraa995c92017-03-09 23:36:26 +00001074bool IRTranslator::translateInlineAsm(const CallInst &CI,
1075 MachineIRBuilder &MIRBuilder) {
1076 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1077 if (!IA.getConstraintString().empty())
1078 return false;
1079
1080 unsigned ExtraInfo = 0;
1081 if (IA.hasSideEffects())
1082 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1083 if (IA.getDialect() == InlineAsm::AD_Intel)
1084 ExtraInfo |= InlineAsm::Extra_AsmDialect;
1085
1086 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1087 .addExternalSymbol(IA.getAsmString().c_str())
1088 .addImm(ExtraInfo);
1089
1090 return true;
1091}
1092
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001093unsigned IRTranslator::packRegs(const Value &V,
1094 MachineIRBuilder &MIRBuilder) {
1095 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1096 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1097 LLT BigTy = getLLTForType(*V.getType(), *DL);
1098
1099 if (Regs.size() == 1)
1100 return Regs[0];
1101
1102 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1103 MIRBuilder.buildUndef(Dst);
1104 for (unsigned i = 0; i < Regs.size(); ++i) {
1105 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1106 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1107 Dst = NewDst;
1108 }
1109 return Dst;
1110}
1111
1112void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1113 MachineIRBuilder &MIRBuilder) {
1114 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1115 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1116
1117 for (unsigned i = 0; i < Regs.size(); ++i)
1118 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1119}
1120
Tim Northoverc53606e2016-12-07 21:29:15 +00001121bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001122 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001123 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +00001124 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +00001125
Martin Storsjocc981d22018-01-30 19:50:58 +00001126 // FIXME: support Windows dllimport function calls.
1127 if (F && F->hasDLLImportStorageClass())
1128 return false;
1129
Tim Northover3babfef2017-01-19 23:59:35 +00001130 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +00001131 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +00001132
Amara Emerson913918c2018-01-02 18:56:39 +00001133 Intrinsic::ID ID = Intrinsic::not_intrinsic;
1134 if (F && F->isIntrinsic()) {
1135 ID = F->getIntrinsicID();
1136 if (TII && ID == Intrinsic::not_intrinsic)
1137 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1138 }
1139
1140 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Matt Arsenault13371692019-03-14 14:18:56 +00001141 bool IsSplitType = valueIsSplit(CI);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001142 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1143 getLLTForType(*CI.getType(), *DL))
1144 : getOrCreateVReg(CI);
1145
Tim Northover406024a2016-08-10 21:44:01 +00001146 SmallVector<unsigned, 8> Args;
1147 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001148 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +00001149
Tim Northoverd1e951e2017-03-09 22:00:39 +00001150 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001151 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +00001152 return getOrCreateVReg(*CI.getCalledValue());
1153 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001154
1155 if (IsSplitType)
1156 unpackRegs(CI, Res, MIRBuilder);
1157 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001158 }
1159
Tim Northover406024a2016-08-10 21:44:01 +00001160 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001161
Tim Northoverc53606e2016-12-07 21:29:15 +00001162 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001163 return true;
1164
Matt Arsenault13371692019-03-14 14:18:56 +00001165 ArrayRef<unsigned> ResultRegs;
1166 if (!CI.getType()->isVoidTy())
1167 ResultRegs = getOrCreateVRegs(CI);
1168
Tim Northover5fb414d2016-07-29 22:32:36 +00001169 MachineInstrBuilder MIB =
Matt Arsenault13371692019-03-14 14:18:56 +00001170 MIRBuilder.buildIntrinsic(ID, ResultRegs, !CI.doesNotAccessMemory());
Michael Bergd573aa02019-04-18 18:48:57 +00001171 if (isa<FPMathOperator>(CI))
1172 MIB->copyIRFlags(CI);
Tim Northover5fb414d2016-07-29 22:32:36 +00001173
1174 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001175 // Some intrinsics take metadata parameters. Reject them.
1176 if (isa<MetadataAsValue>(Arg))
1177 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001178 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001179 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001180
1181 // Add a MachineMemOperand if it is a target mem intrinsic.
1182 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1183 TargetLowering::IntrinsicInfo Info;
1184 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001185 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Matt Arsenault50d65792019-01-31 23:41:23 +00001186 unsigned Align = Info.align;
1187 if (Align == 0)
1188 Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
Matt Arsenault2a645982019-01-31 01:38:47 +00001189
Matt Arsenault50d65792019-01-31 23:41:23 +00001190 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001191 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault50d65792019-01-31 23:41:23 +00001192 Info.flags, Size, Align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001193 }
1194
Tim Northover5fb414d2016-07-29 22:32:36 +00001195 return true;
1196}
1197
Tim Northoverc53606e2016-12-07 21:29:15 +00001198bool IRTranslator::translateInvoke(const User &U,
1199 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001200 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001201 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001202
1203 const BasicBlock *ReturnBB = I.getSuccessor(0);
1204 const BasicBlock *EHPadBB = I.getSuccessor(1);
1205
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001206 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001207 const Function *Fn = dyn_cast<Function>(Callee);
1208 if (isa<InlineAsm>(Callee))
1209 return false;
1210
1211 // FIXME: support invoking patchpoint and statepoint intrinsics.
1212 if (Fn && Fn->isIntrinsic())
1213 return false;
1214
1215 // FIXME: support whatever these are.
1216 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1217 return false;
1218
1219 // FIXME: support Windows exception handling.
1220 if (!isa<LandingPadInst>(EHPadBB->front()))
1221 return false;
1222
Matthias Braund0ee66c2016-12-01 19:32:15 +00001223 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001224 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001225 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001226 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1227
Matt Arsenault0aab9992019-04-10 17:27:55 +00001228 unsigned Res = 0;
1229 if (!I.getType()->isVoidTy())
1230 Res = MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001231 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001232 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001233 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001234
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001235 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001236 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1237 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001238
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001239 unpackRegs(I, Res, MIRBuilder);
1240
Matthias Braund0ee66c2016-12-01 19:32:15 +00001241 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001242 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1243
1244 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001245 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1246 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001247 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001248 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1249 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001250 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001251
1252 return true;
1253}
1254
Craig Topper784929d2019-02-08 20:48:56 +00001255bool IRTranslator::translateCallBr(const User &U,
1256 MachineIRBuilder &MIRBuilder) {
1257 // FIXME: Implement this.
1258 return false;
1259}
1260
Tim Northoverc53606e2016-12-07 21:29:15 +00001261bool IRTranslator::translateLandingPad(const User &U,
1262 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001263 const LandingPadInst &LP = cast<LandingPadInst>(U);
1264
1265 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Tim Northovera9105be2016-11-09 22:39:54 +00001266
1267 MBB.setIsEHPad();
1268
1269 // If there aren't registers to copy the values into (e.g., during SjLj
1270 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001271 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001272 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001273 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1274 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1275 return true;
1276
1277 // If landingpad's return type is token type, we don't create DAG nodes
1278 // for its exception pointer and selector value. The extraction of exception
1279 // pointer or selector value from token type landingpads is not currently
1280 // supported.
1281 if (LP.getType()->isTokenTy())
1282 return true;
1283
1284 // Add a label to mark the beginning of the landing pad. Deletion of the
1285 // landing pad can thus be detected via the MachineModuleInfo.
1286 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001287 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001288
Daniel Sanders1351db42017-03-07 23:32:10 +00001289 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001290 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1291 MIRBuilder.buildUndef(Undef);
1292
Justin Bognera0295312017-01-25 00:16:53 +00001293 SmallVector<LLT, 2> Tys;
1294 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001295 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001296 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1297
Tim Northovera9105be2016-11-09 22:39:54 +00001298 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001299 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1300 if (!ExceptionReg)
1301 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001302
Tim Northover542d1c12017-03-07 23:04:06 +00001303 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001304 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1305 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001306
Tim Northover542d1c12017-03-07 23:04:06 +00001307 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1308 if (!SelectorReg)
1309 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001310
Tim Northover542d1c12017-03-07 23:04:06 +00001311 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001312 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1313 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001314 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001315
Tim Northovera9105be2016-11-09 22:39:54 +00001316 return true;
1317}
1318
Tim Northoverc3e3f592017-02-03 18:22:45 +00001319bool IRTranslator::translateAlloca(const User &U,
1320 MachineIRBuilder &MIRBuilder) {
1321 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001322
Amara Emersonfdd089a2018-07-26 01:25:58 +00001323 if (AI.isSwiftError())
1324 return false;
1325
Tim Northoverc3e3f592017-02-03 18:22:45 +00001326 if (AI.isStaticAlloca()) {
1327 unsigned Res = getOrCreateVReg(AI);
1328 int FI = getOrCreateFrameIndex(AI);
1329 MIRBuilder.buildFrameIndex(Res, FI);
1330 return true;
1331 }
1332
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001333 // FIXME: support stack probing for Windows.
1334 if (MF->getTarget().getTargetTriple().isOSWindows())
1335 return false;
1336
Tim Northoverc3e3f592017-02-03 18:22:45 +00001337 // Now we're in the harder dynamic case.
1338 Type *Ty = AI.getAllocatedType();
1339 unsigned Align =
1340 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1341
1342 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1343
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001344 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1345 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001346 if (MRI->getType(NumElts) != IntPtrTy) {
1347 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1348 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1349 NumElts = ExtElts;
1350 }
1351
1352 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001353 unsigned TySize =
1354 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001355 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1356
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001357 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001358 auto &TLI = *MF->getSubtarget().getTargetLowering();
1359 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1360
1361 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1362 MIRBuilder.buildCopy(SPTmp, SPReg);
1363
Tim Northoverc2f89562017-02-14 20:56:18 +00001364 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1365 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001366
1367 // Handle alignment. We have to realign if the allocation granule was smaller
1368 // than stack alignment, or the specific alloca requires more than stack
1369 // alignment.
1370 unsigned StackAlign =
1371 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1372 Align = std::max(Align, StackAlign);
1373 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1374 // Round the size of the allocation up to the stack alignment size
1375 // by add SA-1 to the size. This doesn't overflow because we're computing
1376 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001377 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1378 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1379 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001380 }
1381
Tim Northoverc2f89562017-02-14 20:56:18 +00001382 MIRBuilder.buildCopy(SPReg, AllocTmp);
1383 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001384
1385 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1386 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001387 return true;
1388}
1389
Tim Northover4a652222017-02-15 23:22:33 +00001390bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1391 // FIXME: We may need more info about the type. Because of how LLT works,
1392 // we're completely discarding the i64/double distinction here (amongst
1393 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1394 // anyway but that's not guaranteed.
1395 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1396 .addDef(getOrCreateVReg(U))
1397 .addUse(getOrCreateVReg(*U.getOperand(0)))
1398 .addImm(DL->getABITypeAlignment(U.getType()));
1399 return true;
1400}
1401
Volkan Keles04cb08c2017-03-10 19:08:28 +00001402bool IRTranslator::translateInsertElement(const User &U,
1403 MachineIRBuilder &MIRBuilder) {
1404 // If it is a <1 x Ty> vector, use the scalar as it is
1405 // not a legal vector type in LLT.
1406 if (U.getType()->getVectorNumElements() == 1) {
1407 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001408 auto &Regs = *VMap.getVRegs(U);
1409 if (Regs.empty()) {
1410 Regs.push_back(Elt);
1411 VMap.getOffsets(U)->push_back(0);
1412 } else {
1413 MIRBuilder.buildCopy(Regs[0], Elt);
1414 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001415 return true;
1416 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001417
Kristof Beyls7a713502017-04-19 06:38:37 +00001418 unsigned Res = getOrCreateVReg(U);
1419 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1420 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1421 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1422 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001423 return true;
1424}
1425
1426bool IRTranslator::translateExtractElement(const User &U,
1427 MachineIRBuilder &MIRBuilder) {
1428 // If it is a <1 x Ty> vector, use the scalar as it is
1429 // not a legal vector type in LLT.
1430 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1431 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001432 auto &Regs = *VMap.getVRegs(U);
1433 if (Regs.empty()) {
1434 Regs.push_back(Elt);
1435 VMap.getOffsets(U)->push_back(0);
1436 } else {
1437 MIRBuilder.buildCopy(Regs[0], Elt);
1438 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001439 return true;
1440 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001441 unsigned Res = getOrCreateVReg(U);
1442 unsigned Val = getOrCreateVReg(*U.getOperand(0));
Amara Emersoncbd86d82018-10-25 14:04:54 +00001443 const auto &TLI = *MF->getSubtarget().getTargetLowering();
1444 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1445 unsigned Idx = 0;
1446 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1447 if (CI->getBitWidth() != PreferredVecIdxWidth) {
1448 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1449 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1450 Idx = getOrCreateVReg(*NewIdxCI);
1451 }
1452 }
1453 if (!Idx)
1454 Idx = getOrCreateVReg(*U.getOperand(1));
1455 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1456 const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1457 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1458 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001459 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001460 return true;
1461}
1462
Volkan Keles75bdc762017-03-21 08:44:13 +00001463bool IRTranslator::translateShuffleVector(const User &U,
1464 MachineIRBuilder &MIRBuilder) {
1465 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1466 .addDef(getOrCreateVReg(U))
1467 .addUse(getOrCreateVReg(*U.getOperand(0)))
1468 .addUse(getOrCreateVReg(*U.getOperand(1)))
1469 .addUse(getOrCreateVReg(*U.getOperand(2)));
1470 return true;
1471}
1472
Tim Northoverc53606e2016-12-07 21:29:15 +00001473bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001474 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001475
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001476 SmallVector<MachineInstr *, 4> Insts;
1477 for (auto Reg : getOrCreateVRegs(PI)) {
Aditya Nandakumarcef44a22018-12-11 00:48:50 +00001478 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001479 Insts.push_back(MIB.getInstr());
1480 }
1481
1482 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001483 return true;
1484}
1485
Daniel Sanders94813992018-07-09 19:33:40 +00001486bool IRTranslator::translateAtomicCmpXchg(const User &U,
1487 MachineIRBuilder &MIRBuilder) {
1488 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1489
1490 if (I.isWeak())
1491 return false;
1492
1493 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1494 : MachineMemOperand::MONone;
1495 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1496
1497 Type *ResType = I.getType();
1498 Type *ValType = ResType->Type::getStructElementType(0);
1499
1500 auto Res = getOrCreateVRegs(I);
1501 unsigned OldValRes = Res[0];
1502 unsigned SuccessRes = Res[1];
1503 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1504 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1505 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1506
1507 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1508 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1509 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1510 Flags, DL->getTypeStoreSize(ValType),
1511 getMemOpAlignment(I), AAMDNodes(), nullptr,
1512 I.getSyncScopeID(), I.getSuccessOrdering(),
1513 I.getFailureOrdering()));
1514 return true;
1515}
1516
1517bool IRTranslator::translateAtomicRMW(const User &U,
1518 MachineIRBuilder &MIRBuilder) {
1519 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1520
1521 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1522 : MachineMemOperand::MONone;
1523 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1524
1525 Type *ResType = I.getType();
1526
1527 unsigned Res = getOrCreateVReg(I);
1528 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1529 unsigned Val = getOrCreateVReg(*I.getValOperand());
1530
1531 unsigned Opcode = 0;
1532 switch (I.getOperation()) {
1533 default:
1534 llvm_unreachable("Unknown atomicrmw op");
1535 return false;
1536 case AtomicRMWInst::Xchg:
1537 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1538 break;
1539 case AtomicRMWInst::Add:
1540 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1541 break;
1542 case AtomicRMWInst::Sub:
1543 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1544 break;
1545 case AtomicRMWInst::And:
1546 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1547 break;
1548 case AtomicRMWInst::Nand:
1549 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1550 break;
1551 case AtomicRMWInst::Or:
1552 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1553 break;
1554 case AtomicRMWInst::Xor:
1555 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1556 break;
1557 case AtomicRMWInst::Max:
1558 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1559 break;
1560 case AtomicRMWInst::Min:
1561 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1562 break;
1563 case AtomicRMWInst::UMax:
1564 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1565 break;
1566 case AtomicRMWInst::UMin:
1567 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1568 break;
1569 }
1570
1571 MIRBuilder.buildAtomicRMW(
1572 Opcode, Res, Addr, Val,
1573 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1574 Flags, DL->getTypeStoreSize(ResType),
1575 getMemOpAlignment(I), AAMDNodes(), nullptr,
1576 I.getSyncScopeID(), I.getOrdering()));
1577 return true;
1578}
1579
Tim Northover97d0cb32016-08-05 17:16:40 +00001580void IRTranslator::finishPendingPhis() {
Daniel Sanders3b390402018-10-31 17:31:23 +00001581#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001582 DILocationVerifier Verifier;
1583 GISelObserverWrapper WrapperObserver(&Verifier);
1584 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001585#endif // ifndef NDEBUG
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001586 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001587 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001588 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001589 EntryBuilder->setDebugLoc(PI->getDebugLoc());
Daniel Sanders3b390402018-10-31 17:31:23 +00001590#ifndef NDEBUG
1591 Verifier.setCurrentInst(PI);
1592#endif // ifndef NDEBUG
Tim Northover97d0cb32016-08-05 17:16:40 +00001593
1594 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1595 // won't create extra control flow here, otherwise we need to find the
1596 // dominating predecessor here (or perhaps force the weirder IRTranslators
1597 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001598 SmallSet<const BasicBlock *, 4> HandledPreds;
1599
Tim Northover97d0cb32016-08-05 17:16:40 +00001600 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001601 auto IRPred = PI->getIncomingBlock(i);
1602 if (HandledPreds.count(IRPred))
1603 continue;
1604
1605 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001606 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001607 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001608 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001609 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001610 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1611 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1612 MIB.addUse(ValRegs[j]);
1613 MIB.addMBB(Pred);
1614 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001615 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001616 }
1617 }
1618}
1619
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001620bool IRTranslator::valueIsSplit(const Value &V,
1621 SmallVectorImpl<uint64_t> *Offsets) {
1622 SmallVector<LLT, 4> SplitTys;
Amara Emerson30e61402018-08-14 12:04:25 +00001623 if (Offsets && !Offsets->empty())
1624 Offsets->clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001625 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1626 return SplitTys.size() > 1;
1627}
1628
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001629bool IRTranslator::translate(const Instruction &Inst) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001630 CurBuilder->setDebugLoc(Inst.getDebugLoc());
1631 EntryBuilder->setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001632 switch(Inst.getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001633#define HANDLE_INST(NUM, OPCODE, CLASS) \
1634 case Instruction::OPCODE: \
1635 return translate##OPCODE(Inst, *CurBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001636#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001637 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001638 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001639 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001640}
1641
Tim Northover5ed648e2016-08-09 21:28:04 +00001642bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001643 if (auto CI = dyn_cast<ConstantInt>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001644 EntryBuilder->buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001645 else if (auto CF = dyn_cast<ConstantFP>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001646 EntryBuilder->buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001647 else if (isa<UndefValue>(C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001648 EntryBuilder->buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001649 else if (isa<ConstantPointerNull>(C)) {
1650 // As we are trying to build a constant val of 0 into a pointer,
1651 // insert a cast to make them correct with respect to types.
1652 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1653 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1654 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1655 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001656 EntryBuilder->buildCast(Reg, ZeroReg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001657 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001658 EntryBuilder->buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001659 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1660 if (!CAZ->getType()->isVectorTy())
1661 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001662 // Return the scalar if it is a <1 x Ty> vector.
1663 if (CAZ->getNumElements() == 1)
1664 return translate(*CAZ->getElementValue(0u), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001665 SmallVector<unsigned, 4> Ops;
Volkan Keles970fee42017-03-10 21:23:13 +00001666 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1667 Constant &Elt = *CAZ->getElementValue(i);
1668 Ops.push_back(getOrCreateVReg(Elt));
1669 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001670 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001671 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001672 // Return the scalar if it is a <1 x Ty> vector.
1673 if (CV->getNumElements() == 1)
1674 return translate(*CV->getElementAsConstant(0), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001675 SmallVector<unsigned, 4> Ops;
Volkan Keles38a91a02017-03-13 21:36:19 +00001676 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1677 Constant &Elt = *CV->getElementAsConstant(i);
1678 Ops.push_back(getOrCreateVReg(Elt));
1679 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001680 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001681 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001682 switch(CE->getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001683#define HANDLE_INST(NUM, OPCODE, CLASS) \
1684 case Instruction::OPCODE: \
1685 return translate##OPCODE(*CE, *EntryBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001686#include "llvm/IR/Instruction.def"
1687 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001688 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001689 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001690 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1691 if (CV->getNumOperands() == 1)
1692 return translate(*CV->getOperand(0), Reg);
1693 SmallVector<unsigned, 4> Ops;
1694 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1695 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1696 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001697 EntryBuilder->buildBuildVector(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001698 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001699 EntryBuilder->buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001700 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001701 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001702
Tim Northoverd403a3d2016-08-09 23:01:30 +00001703 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001704}
1705
Tim Northover0d510442016-08-11 16:21:29 +00001706void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001707 // Release the memory used by the different maps we
1708 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001709 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001710 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001711 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001712 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001713 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1714 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1715 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001716 EntryBuilder.reset();
1717 CurBuilder.reset();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001718}
1719
Tim Northover50db7f412016-12-07 21:17:47 +00001720bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1721 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001722 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001723 if (F.empty())
1724 return false;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001725 GISelCSEAnalysisWrapper &Wrapper =
1726 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1727 // Set the CSEConfig and run the analysis.
1728 GISelCSEInfo *CSEInfo = nullptr;
1729 TPC = &getAnalysis<TargetPassConfig>();
Aditya Nandakumar3ba0d942019-01-24 23:11:25 +00001730 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1731 ? EnableCSEInIRTranslator
1732 : TPC->isGISelCSEEnabled();
1733
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001734 if (EnableCSE) {
1735 EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
Amara Emersond1896802019-04-15 04:53:46 +00001736 CSEInfo = &Wrapper.get(TPC->getCSEConfig());
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001737 EntryBuilder->setCSEInfo(CSEInfo);
1738 CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1739 CurBuilder->setCSEInfo(CSEInfo);
1740 } else {
1741 EntryBuilder = make_unique<MachineIRBuilder>();
1742 CurBuilder = make_unique<MachineIRBuilder>();
1743 }
Tim Northover50db7f412016-12-07 21:17:47 +00001744 CLI = MF->getSubtarget().getCallLowering();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001745 CurBuilder->setMF(*MF);
1746 EntryBuilder->setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001747 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001748 DL = &F.getParent()->getDataLayout();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001749 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001750
Tim Northover14e7f732016-08-05 17:50:36 +00001751 assert(PendingPHIs.empty() && "stale PHIs");
1752
Amara Emersondf9b5292017-12-11 16:58:29 +00001753 if (!DL->isLittleEndian()) {
1754 // Currently we don't properly handle big endian code.
1755 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001756 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001757 R << "unable to translate in big endian mode";
1758 reportTranslationError(*MF, *TPC, *ORE, R);
1759 }
1760
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001761 // Release the per-function state when we return, whether we succeeded or not.
1762 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1763
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001764 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001765 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1766 MF->push_back(EntryBB);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001767 EntryBuilder->setMBB(*EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001768
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001769 // Create all blocks, in IR order, to preserve the layout.
1770 for (const BasicBlock &BB: F) {
1771 auto *&MBB = BBToMBB[&BB];
1772
1773 MBB = MF->CreateMachineBasicBlock(&BB);
1774 MF->push_back(MBB);
1775
1776 if (BB.hasAddressTaken())
1777 MBB->setHasAddressTaken();
1778 }
1779
1780 // Make our arguments/constants entry block fallthrough to the IR entry block.
1781 EntryBB->addSuccessor(&getMBB(F.front()));
1782
Tim Northover05cc4852016-12-07 21:05:38 +00001783 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001784 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001785 for (const Argument &Arg: F.args()) {
1786 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1787 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001788 VRegArgs.push_back(
1789 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001790 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001791
Amara Emersonfdd089a2018-07-26 01:25:58 +00001792 // We don't currently support translating swifterror or swiftself functions.
1793 for (auto &Arg : F.args()) {
1794 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1795 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1796 F.getSubprogram(), &F.getEntryBlock());
1797 R << "unable to lower arguments due to swifterror/swiftself: "
1798 << ore::NV("Prototype", F.getType());
1799 reportTranslationError(*MF, *TPC, *ORE, R);
1800 return false;
1801 }
1802 }
1803
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001804 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001805 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001806 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001807 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1808 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001809 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001810 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001811
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001812 auto ArgIt = F.arg_begin();
1813 for (auto &VArg : VRegArgs) {
1814 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1815 // creating redundant copies.
1816 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1817 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1818 assert(VRegs.empty() && "VRegs already populated?");
1819 VRegs.push_back(VArg);
1820 } else {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001821 unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001822 }
1823 ArgIt++;
1824 }
1825
Amara Emerson6cdfe292018-08-01 02:17:42 +00001826 // Need to visit defs before uses when translating instructions.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001827 GISelObserverWrapper WrapperObserver;
1828 if (EnableCSE && CSEInfo)
1829 WrapperObserver.addObserver(CSEInfo);
Daniel Sanders3b390402018-10-31 17:31:23 +00001830 {
1831 ReversePostOrderTraversal<const Function *> RPOT(&F);
1832#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001833 DILocationVerifier Verifier;
1834 WrapperObserver.addObserver(&Verifier);
Daniel Sanders3b390402018-10-31 17:31:23 +00001835#endif // ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001836 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001837 for (const BasicBlock *BB : RPOT) {
1838 MachineBasicBlock &MBB = getMBB(*BB);
1839 // Set the insertion point of all the following translations to
1840 // the end of this basic block.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001841 CurBuilder->setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001842
Daniel Sanders3b390402018-10-31 17:31:23 +00001843 for (const Instruction &Inst : *BB) {
1844#ifndef NDEBUG
1845 Verifier.setCurrentInst(&Inst);
1846#endif // ifndef NDEBUG
1847 if (translate(Inst))
1848 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001849
Daniel Sanders3b390402018-10-31 17:31:23 +00001850 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1851 Inst.getDebugLoc(), BB);
1852 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001853
Daniel Sanders3b390402018-10-31 17:31:23 +00001854 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1855 std::string InstStrStorage;
1856 raw_string_ostream InstStr(InstStrStorage);
1857 InstStr << Inst;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001858
Daniel Sanders3b390402018-10-31 17:31:23 +00001859 R << ": '" << InstStr.str() << "'";
1860 }
1861
1862 reportTranslationError(*MF, *TPC, *ORE, R);
1863 return false;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001864 }
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001865 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001866#ifndef NDEBUG
1867 WrapperObserver.removeObserver(&Verifier);
1868#endif
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001869 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001870
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001871 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001872
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001873 // Merge the argument lowering and constants block with its single
1874 // successor, the LLVM-IR entry block. We want the basic block to
1875 // be maximal.
1876 assert(EntryBB->succ_size() == 1 &&
1877 "Custom BB used for lowering should have only one successor");
1878 // Get the successor of the current entry block.
1879 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1880 assert(NewEntryBB.pred_size() == 1 &&
1881 "LLVM-IR entry block has a predecessor!?");
1882 // Move all the instruction from the current entry block to the
1883 // new entry block.
1884 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1885 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001886
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001887 // Update the live-in information for the new entry block.
1888 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1889 NewEntryBB.addLiveIn(LiveIn);
1890 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001891
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001892 // Get rid of the now empty basic block.
1893 EntryBB->removeSuccessor(&NewEntryBB);
1894 MF->remove(EntryBB);
1895 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001896
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001897 assert(&MF->front() == &NewEntryBB &&
1898 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001899
Matthias Braun90ad6832018-07-13 00:08:38 +00001900 // Initialize stack protector information.
1901 StackProtector &SP = getAnalysis<StackProtector>();
1902 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1903
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001904 return false;
1905}