blob: 974629bc4f4670a15458a9f30718282e8ffcc8e5 [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the IRTranslator class.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000014#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +000016#include "llvm/ADT/ScopeExit.h"
Tim Northoverb6636fd2017-01-17 22:13:50 +000017#include "llvm/ADT/SmallSet.h"
Quentin Colombetfd9d0a02016-02-11 19:59:41 +000018#include "llvm/ADT/SmallVector.h"
Adam Nemet0965da22017-10-09 23:19:02 +000019#include "llvm/Analysis/OptimizationRemarkEmitter.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"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000022#include "llvm/CodeGen/LowLevelType.h"
23#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northoverbd505462016-07-22 16:59:52 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineMemOperand.h"
28#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Braun90ad6832018-07-13 00:08:38 +000030#include "llvm/CodeGen/StackProtector.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetFrameLowering.h"
32#include "llvm/CodeGen/TargetLowering.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000033#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000036#include "llvm/IR/BasicBlock.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000037#include "llvm/IR/CFG.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000038#include "llvm/IR/Constant.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000039#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000041#include "llvm/IR/DebugInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000042#include "llvm/IR/DerivedTypes.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000043#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000044#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000045#include "llvm/IR/InlineAsm.h"
46#include "llvm/IR/InstrTypes.h"
47#include "llvm/IR/Instructions.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000048#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000049#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000052#include "llvm/IR/Type.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000053#include "llvm/IR/User.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000054#include "llvm/IR/Value.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000055#include "llvm/MC/MCContext.h"
56#include "llvm/Pass.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/CodeGen.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/LowLevelTypeImpl.h"
62#include "llvm/Support/MathExtras.h"
63#include "llvm/Support/raw_ostream.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000064#include "llvm/Target/TargetIntrinsicInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000065#include "llvm/Target/TargetMachine.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000066#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <iterator>
70#include <string>
71#include <utility>
72#include <vector>
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000073
74#define DEBUG_TYPE "irtranslator"
75
Quentin Colombet105cf2b2016-01-20 20:58:56 +000076using namespace llvm;
77
78char IRTranslator::ID = 0;
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000079
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000080INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
81 false, false)
82INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
83INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000084 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000085
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000086static void reportTranslationError(MachineFunction &MF,
87 const TargetPassConfig &TPC,
88 OptimizationRemarkEmitter &ORE,
89 OptimizationRemarkMissed &R) {
90 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
91
92 // Print the function name explicitly if we don't have a debug location (which
93 // makes the diagnostic less useful) or if we're going to emit a raw error.
94 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
95 R << (" (in function: " + MF.getName() + ")").str();
96
97 if (TPC.isGlobalISelAbortEnabled())
98 report_fatal_error(R.getMsg());
99 else
100 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +0000101}
102
Eugene Zelenko76bf48d2017-06-26 22:44:03 +0000103IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
Quentin Colombet39293d32016-03-08 01:38:55 +0000104 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +0000105}
106
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000107void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun90ad6832018-07-13 00:08:38 +0000108 AU.addRequired<StackProtector>();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000109 AU.addRequired<TargetPassConfig>();
Matthias Braun90ad6832018-07-13 00:08:38 +0000110 getSelectionDAGFallbackAnalysisUsage(AU);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000111 MachineFunctionPass::getAnalysisUsage(AU);
112}
113
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000114static void computeValueLLTs(const DataLayout &DL, Type &Ty,
115 SmallVectorImpl<LLT> &ValueTys,
116 SmallVectorImpl<uint64_t> *Offsets = nullptr,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (StructType *STy = dyn_cast<StructType>(&Ty)) {
120 const StructLayout *SL = DL.getStructLayout(STy);
121 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
122 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
123 StartingOffset + SL->getElementOffset(I));
124 return;
125 }
126 // Given an array type, recursively traverse the elements.
127 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
128 Type *EltTy = ATy->getElementType();
129 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
130 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
131 computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
132 StartingOffset + i * EltSize);
133 return;
134 }
135 // Interpret void as zero return values.
136 if (Ty.isVoidTy())
137 return;
138 // Base case: we can get an LLT for this LLVM IR type.
139 ValueTys.push_back(getLLTForType(Ty, DL));
140 if (Offsets != nullptr)
141 Offsets->push_back(StartingOffset * 8);
142}
Tim Northover5ed648e2016-08-09 21:28:04 +0000143
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000144IRTranslator::ValueToVRegInfo::VRegListT &
145IRTranslator::allocateVRegs(const Value &Val) {
146 assert(!VMap.contains(Val) && "Value already allocated in VMap");
147 auto *Regs = VMap.getVRegs(Val);
148 auto *Offsets = VMap.getOffsets(Val);
149 SmallVector<LLT, 4> SplitTys;
150 computeValueLLTs(*DL, *Val.getType(), SplitTys,
151 Offsets->empty() ? Offsets : nullptr);
152 for (unsigned i = 0; i < SplitTys.size(); ++i)
153 Regs->push_back(0);
154 return *Regs;
155}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000156
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000157ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
158 auto VRegsIt = VMap.findVRegs(Val);
159 if (VRegsIt != VMap.vregs_end())
160 return *VRegsIt->second;
161
162 if (Val.getType()->isVoidTy())
163 return *VMap.getVRegs(Val);
164
165 // Create entry for this type.
166 auto *VRegs = VMap.getVRegs(Val);
167 auto *Offsets = VMap.getOffsets(Val);
168
Tim Northover9e35f1e2017-01-25 20:58:22 +0000169 assert(Val.getType()->isSized() &&
170 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000171
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000172 SmallVector<LLT, 4> SplitTys;
173 computeValueLLTs(*DL, *Val.getType(), SplitTys,
174 Offsets->empty() ? Offsets : nullptr);
175
176 if (!isa<Constant>(Val)) {
177 for (auto Ty : SplitTys)
178 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
179 return *VRegs;
180 }
181
182 if (Val.getType()->isAggregateType()) {
183 // UndefValue, ConstantAggregateZero
184 auto &C = cast<Constant>(Val);
185 unsigned Idx = 0;
186 while (auto Elt = C.getAggregateElement(Idx++)) {
187 auto EltRegs = getOrCreateVRegs(*Elt);
188 std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
189 }
190 } else {
191 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
192 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
193 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000194 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000195 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000196 MF->getFunction().getSubprogram(),
197 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000198 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
199 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000200 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000201 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000202 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000203
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000204 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000205}
206
Tim Northovercdf23f12016-10-31 18:30:59 +0000207int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
208 if (FrameIndices.find(&AI) != FrameIndices.end())
209 return FrameIndices[&AI];
210
Tim Northovercdf23f12016-10-31 18:30:59 +0000211 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
212 unsigned Size =
213 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
214
215 // Always allocate at least one byte.
216 Size = std::max(Size, 1u);
217
218 unsigned Alignment = AI.getAlignment();
219 if (!Alignment)
220 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
221
222 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000223 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000224 return FI;
225}
226
Tim Northoverad2b7172016-07-26 20:23:26 +0000227unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
228 unsigned Alignment = 0;
229 Type *ValTy = nullptr;
230 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
231 Alignment = SI->getAlignment();
232 ValTy = SI->getValueOperand()->getType();
233 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
234 Alignment = LI->getAlignment();
235 ValTy = LI->getType();
Daniel Sanders94813992018-07-09 19:33:40 +0000236 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
237 // TODO(PR27168): This instruction has no alignment attribute, but unlike
238 // the default alignment for load/store, the default here is to assume
239 // it has NATURAL alignment, not DataLayout-specified alignment.
240 const DataLayout &DL = AI->getModule()->getDataLayout();
241 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
242 ValTy = AI->getCompareOperand()->getType();
243 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
244 // TODO(PR27168): This instruction has no alignment attribute, but unlike
245 // the default alignment for load/store, the default here is to assume
246 // it has NATURAL alignment, not DataLayout-specified alignment.
247 const DataLayout &DL = AI->getModule()->getDataLayout();
248 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
249 ValTy = AI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000250 } else {
251 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
252 R << "unable to translate memop: " << ore::NV("Opcode", &I);
253 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000254 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000255 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000256
257 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
258}
259
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000260MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000261 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000262 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000263 return *MBB;
264}
265
Tim Northoverb6636fd2017-01-17 22:13:50 +0000266void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
267 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
268 MachinePreds[Edge].push_back(NewPred);
269}
270
Tim Northoverc53606e2016-12-07 21:29:15 +0000271bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
272 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000273 // FIXME: handle signed/unsigned wrapping flags.
274
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000275 // Get or create a virtual register for each value.
276 // Unless the value is a Constant => loadimm cst?
277 // or inline constant each time?
278 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000279 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
280 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
281 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000282 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000283 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000284}
285
Volkan Keles20d3c422017-03-07 18:03:28 +0000286bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
287 // -0.0 - X --> G_FNEG
288 if (isa<Constant>(U.getOperand(0)) &&
289 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
290 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
291 .addDef(getOrCreateVReg(U))
292 .addUse(getOrCreateVReg(*U.getOperand(1)));
293 return true;
294 }
295 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
296}
297
Tim Northoverc53606e2016-12-07 21:29:15 +0000298bool IRTranslator::translateCompare(const User &U,
299 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000300 const CmpInst *CI = dyn_cast<CmpInst>(&U);
301 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
302 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
303 unsigned Res = getOrCreateVReg(U);
304 CmpInst::Predicate Pred =
305 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
306 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000307 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000308 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000309 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000310 MIRBuilder.buildCopy(
311 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
312 else if (Pred == CmpInst::FCMP_TRUE)
313 MIRBuilder.buildCopy(
314 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000315 else
Tim Northover0f140c72016-09-09 11:46:34 +0000316 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000317
Tim Northoverde3aea0412016-08-17 20:25:25 +0000318 return true;
319}
320
Tim Northoverc53606e2016-12-07 21:29:15 +0000321bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000322 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000323 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000324 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
325 Ret = nullptr;
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000326
327 ArrayRef<unsigned> VRegs;
328 if (Ret)
329 VRegs = getOrCreateVRegs(*Ret);
330
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000331 // The target may mess up with the insertion point, but
332 // this is not important as a return is the last instruction
333 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000334
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000335 return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000336}
337
Tim Northoverc53606e2016-12-07 21:29:15 +0000338bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000339 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000340 unsigned Succ = 0;
341 if (!BrInst.isUnconditional()) {
342 // We want a G_BRCOND to the true BB followed by an unconditional branch.
343 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
344 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000345 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000346 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000347 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000348
349 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000350 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000351 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
352
353 // If the unconditional target is the layout successor, fallthrough.
354 if (!CurBB.isLayoutSuccessor(&TgtBB))
355 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000356
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000357 // Link successors.
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000358 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000359 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000360 return true;
361}
362
Kristof Beylseced0712017-01-05 11:28:51 +0000363bool IRTranslator::translateSwitch(const User &U,
364 MachineIRBuilder &MIRBuilder) {
365 // For now, just translate as a chain of conditional branches.
366 // FIXME: could we share most of the logic/code in
367 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
368 // At first sight, it seems most of the logic in there is independent of
369 // SelectionDAG-specifics and a lot of work went in to optimize switch
370 // lowering in there.
371
372 const SwitchInst &SwInst = cast<SwitchInst>(U);
373 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000374 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000375
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000376 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000377 for (auto &CaseIt : SwInst.cases()) {
378 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
379 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
380 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000381 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
382 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000383 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000384
Tim Northoverb6636fd2017-01-17 22:13:50 +0000385 MIRBuilder.buildBrCond(Tst, TrueMBB);
386 CurMBB.addSuccessor(&TrueMBB);
387 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000388
Tim Northoverb6636fd2017-01-17 22:13:50 +0000389 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000390 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000391 // Insert the comparison blocks one after the other.
392 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000393 MIRBuilder.buildBr(*FalseMBB);
394 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000395
Tim Northoverb6636fd2017-01-17 22:13:50 +0000396 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000397 }
398 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000399 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000400 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000401 MIRBuilder.buildBr(DefaultMBB);
402 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
403 CurMBB.addSuccessor(&DefaultMBB);
404 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000405
406 return true;
407}
408
Kristof Beyls65a12c02017-01-30 09:13:18 +0000409bool IRTranslator::translateIndirectBr(const User &U,
410 MachineIRBuilder &MIRBuilder) {
411 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
412
413 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
414 MIRBuilder.buildBrIndirect(Tgt);
415
416 // Link successors.
417 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000418 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000419 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000420
421 return true;
422}
423
Tim Northoverc53606e2016-12-07 21:29:15 +0000424bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000425 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000426
Tim Northover7152dca2016-10-19 15:55:06 +0000427 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
428 : MachineMemOperand::MONone;
429 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000430
Amara Emersond78d65c2017-11-30 20:06:02 +0000431 if (DL->getTypeStoreSize(LI.getType()) == 0)
432 return true;
433
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000434 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
435 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
436 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000437
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000438 for (unsigned i = 0; i < Regs.size(); ++i) {
439 unsigned Addr = 0;
440 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
441
442 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
443 unsigned BaseAlign = getMemOpAlignment(LI);
444 auto MMO = MF->getMachineMemOperand(
445 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
446 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
447 LI.getSyncScopeID(), LI.getOrdering());
448 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
449 }
450
Tim Northoverad2b7172016-07-26 20:23:26 +0000451 return true;
452}
453
Tim Northoverc53606e2016-12-07 21:29:15 +0000454bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000455 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000456 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
457 : MachineMemOperand::MONone;
458 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000459
Amara Emersond78d65c2017-11-30 20:06:02 +0000460 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
461 return true;
462
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000463 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
464 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
465 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000466
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000467 for (unsigned i = 0; i < Vals.size(); ++i) {
468 unsigned Addr = 0;
469 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
470
471 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
472 unsigned BaseAlign = getMemOpAlignment(SI);
473 auto MMO = MF->getMachineMemOperand(
474 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
475 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
476 SI.getSyncScopeID(), SI.getOrdering());
477 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
478 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000479 return true;
480}
481
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000482static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000483 const Value *Src = U.getOperand(0);
484 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000485
Tim Northover6f80b082016-08-19 17:47:05 +0000486 // getIndexedOffsetInType is designed for GEPs, so the first index is the
487 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000488 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000489 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000490
491 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
492 for (auto Idx : EVI->indices())
493 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000494 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
495 for (auto Idx : IVI->indices())
496 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000497 } else {
498 for (unsigned i = 1; i < U.getNumOperands(); ++i)
499 Indices.push_back(U.getOperand(i));
500 }
Tim Northover6f80b082016-08-19 17:47:05 +0000501
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000502 return 8 * static_cast<uint64_t>(
503 DL.getIndexedOffsetInType(Src->getType(), Indices));
504}
Tim Northover6f80b082016-08-19 17:47:05 +0000505
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000506bool IRTranslator::translateExtractValue(const User &U,
507 MachineIRBuilder &MIRBuilder) {
508 const Value *Src = U.getOperand(0);
509 uint64_t Offset = getOffsetFromIndices(U, *DL);
510 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
511 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
512 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
513 Offsets.begin();
514 auto &DstRegs = allocateVRegs(U);
515
516 for (unsigned i = 0; i < DstRegs.size(); ++i)
517 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000518
519 return true;
520}
521
Tim Northoverc53606e2016-12-07 21:29:15 +0000522bool IRTranslator::translateInsertValue(const User &U,
523 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000524 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000525 uint64_t Offset = getOffsetFromIndices(U, *DL);
526 auto &DstRegs = allocateVRegs(U);
527 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
528 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
529 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
530 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000531
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000532 for (unsigned i = 0; i < DstRegs.size(); ++i) {
533 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
534 DstRegs[i] = *InsertedIt++;
535 else
536 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000537 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000538
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000539 return true;
540}
541
Tim Northoverc53606e2016-12-07 21:29:15 +0000542bool IRTranslator::translateSelect(const User &U,
543 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000544 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000545 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
546 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
547 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
548
549 for (unsigned i = 0; i < ResRegs.size(); ++i)
550 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
551
Tim Northover5a28c362016-08-19 20:09:07 +0000552 return true;
553}
554
Tim Northoverc53606e2016-12-07 21:29:15 +0000555bool IRTranslator::translateBitCast(const User &U,
556 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000557 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000558 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
559 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000560 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000561 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000562 // If we already assigned a vreg for this bitcast, we can't change that.
563 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000564 if (!Regs.empty())
565 MIRBuilder.buildCopy(Regs[0], SrcReg);
566 else {
567 Regs.push_back(SrcReg);
568 VMap.getOffsets(U)->push_back(0);
569 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000570 return true;
571 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000572 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000573}
574
Tim Northoverc53606e2016-12-07 21:29:15 +0000575bool IRTranslator::translateCast(unsigned Opcode, const User &U,
576 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000577 unsigned Op = getOrCreateVReg(*U.getOperand(0));
578 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000579 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000580 return true;
581}
582
Tim Northoverc53606e2016-12-07 21:29:15 +0000583bool IRTranslator::translateGetElementPtr(const User &U,
584 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000585 // FIXME: support vector GEPs.
586 if (U.getType()->isVectorTy())
587 return false;
588
589 Value &Op0 = *U.getOperand(0);
590 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000591 Type *PtrIRTy = Op0.getType();
592 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
593 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
594 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000595
596 int64_t Offset = 0;
597 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
598 GTI != E; ++GTI) {
599 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000600 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000601 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
602 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
603 continue;
604 } else {
605 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
606
607 // If this is a scalar constant or a splat vector of constants,
608 // handle it quickly.
609 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
610 Offset += ElementSize * CI->getSExtValue();
611 continue;
612 }
613
614 if (Offset != 0) {
615 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000616 unsigned OffsetReg =
617 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000618 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
619
620 BaseReg = NewBaseReg;
621 Offset = 0;
622 }
623
Tim Northovera7653b32016-09-12 11:20:22 +0000624 unsigned IdxReg = getOrCreateVReg(*Idx);
625 if (MRI->getType(IdxReg) != OffsetTy) {
626 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
627 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
628 IdxReg = NewIdxReg;
629 }
630
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000631 // N = N + Idx * ElementSize;
632 // Avoid doing it for ElementSize of 1.
633 unsigned GepOffsetReg;
634 if (ElementSize != 1) {
635 unsigned ElementSizeReg =
636 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
637
638 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
639 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
640 } else
641 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000642
643 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000644 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000645 BaseReg = NewBaseReg;
646 }
647 }
648
649 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000650 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000651 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
652 return true;
653 }
654
655 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
656 return true;
657}
658
Tim Northover79f43f12017-01-30 19:33:07 +0000659bool IRTranslator::translateMemfunc(const CallInst &CI,
660 MachineIRBuilder &MIRBuilder,
661 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000662 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000663 Type *DstTy = CI.getArgOperand(0)->getType();
664 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000665 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
666 return false;
667
668 SmallVector<CallLowering::ArgInfo, 8> Args;
669 for (int i = 0; i < 3; ++i) {
670 const auto &Arg = CI.getArgOperand(i);
671 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
672 }
673
Tim Northover79f43f12017-01-30 19:33:07 +0000674 const char *Callee;
675 switch (ID) {
676 case Intrinsic::memmove:
677 case Intrinsic::memcpy: {
678 Type *SrcTy = CI.getArgOperand(1)->getType();
679 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
680 return false;
681 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
682 break;
683 }
684 case Intrinsic::memset:
685 Callee = "memset";
686 break;
687 default:
688 return false;
689 }
Tim Northover3f186032016-10-18 20:03:45 +0000690
Diana Picusd79253a2017-03-20 14:40:18 +0000691 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
692 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000693 CallLowering::ArgInfo(0, CI.getType()), Args);
694}
Tim Northovera7653b32016-09-12 11:20:22 +0000695
Tim Northoverc53606e2016-12-07 21:29:15 +0000696void IRTranslator::getStackGuard(unsigned DstReg,
697 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000698 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
699 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000700 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
701 MIB.addDef(DstReg);
702
Tim Northover50db7f412016-12-07 21:17:47 +0000703 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000704 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000705 if (!Global)
706 return;
707
708 MachinePointerInfo MPInfo(Global);
Tim Northovercdf23f12016-10-31 18:30:59 +0000709 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
710 MachineMemOperand::MODereferenceable;
Chandler Carruthc73c0302018-08-16 21:30:05 +0000711 MachineMemOperand *MemRef =
Tim Northover50db7f412016-12-07 21:17:47 +0000712 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000713 DL->getPointerABIAlignment(0));
Chandler Carruthc73c0302018-08-16 21:30:05 +0000714 MIB.setMemRefs({MemRef});
Tim Northovercdf23f12016-10-31 18:30:59 +0000715}
716
Tim Northover1e656ec2016-12-08 22:44:00 +0000717bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
718 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000719 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000720 MIRBuilder.buildInstr(Op)
721 .addDef(ResRegs[0])
722 .addDef(ResRegs[1])
723 .addUse(getOrCreateVReg(*CI.getOperand(0)))
724 .addUse(getOrCreateVReg(*CI.getOperand(1)));
Tim Northover1e656ec2016-12-08 22:44:00 +0000725
Tim Northover1e656ec2016-12-08 22:44:00 +0000726 return true;
727}
728
Tim Northoverc53606e2016-12-07 21:29:15 +0000729bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
730 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000731 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000732 default:
733 break;
Tim Northover0e011702017-02-10 19:10:38 +0000734 case Intrinsic::lifetime_start:
735 case Intrinsic::lifetime_end:
736 // Stack coloring is not enabled in O0 (which we care about now) so we can
737 // drop these. Make sure someone notices when we start compiling at higher
738 // opts though.
739 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
740 return false;
741 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000742 case Intrinsic::dbg_declare: {
743 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
744 assert(DI.getVariable() && "Missing variable");
745
746 const Value *Address = DI.getAddress();
747 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000748 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000749 return true;
750 }
751
Tim Northover09aac4a2017-01-26 23:39:14 +0000752 assert(DI.getVariable()->isValidLocationForIntrinsic(
753 MIRBuilder.getDebugLoc()) &&
754 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000755 auto AI = dyn_cast<AllocaInst>(Address);
756 if (AI && AI->isStaticAlloca()) {
757 // Static allocas are tracked at the MF level, no need for DBG_VALUE
758 // instructions (in fact, they get ignored if they *do* exist).
759 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
760 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000761 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000762 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
763 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000764 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000765 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000766 case Intrinsic::dbg_label: {
767 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
768 assert(DI.getLabel() && "Missing label");
769
770 assert(DI.getLabel()->isValidLocationForIntrinsic(
771 MIRBuilder.getDebugLoc()) &&
772 "Expected inlined-at fields to agree");
773
774 MIRBuilder.buildDbgLabel(DI.getLabel());
775 return true;
776 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000777 case Intrinsic::vaend:
778 // No target I know of cares about va_end. Certainly no in-tree target
779 // does. Simplest intrinsic ever!
780 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000781 case Intrinsic::vastart: {
782 auto &TLI = *MF->getSubtarget().getTargetLowering();
783 Value *Ptr = CI.getArgOperand(0);
784 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
785
786 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
787 .addUse(getOrCreateVReg(*Ptr))
788 .addMemOperand(MF->getMachineMemOperand(
789 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
790 return true;
791 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000792 case Intrinsic::dbg_value: {
793 // This form of DBG_VALUE is target-independent.
794 const DbgValueInst &DI = cast<DbgValueInst>(CI);
795 const Value *V = DI.getValue();
796 assert(DI.getVariable()->isValidLocationForIntrinsic(
797 MIRBuilder.getDebugLoc()) &&
798 "Expected inlined-at fields to agree");
799 if (!V) {
800 // Currently the optimizer can produce this; insert an undef to
801 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000802 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000803 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000804 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000805 } else {
806 unsigned Reg = getOrCreateVReg(*V);
807 // FIXME: This does not handle register-indirect values at offset 0. The
808 // direct/indirect thing shouldn't really be handled by something as
809 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
810 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000811 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000812 }
813 return true;
814 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000815 case Intrinsic::uadd_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000816 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000817 case Intrinsic::sadd_with_overflow:
818 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
819 case Intrinsic::usub_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000820 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000821 case Intrinsic::ssub_with_overflow:
822 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
823 case Intrinsic::umul_with_overflow:
824 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
825 case Intrinsic::smul_with_overflow:
826 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000827 case Intrinsic::pow:
828 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
829 .addDef(getOrCreateVReg(CI))
830 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
831 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
832 return true;
Aditya Nandakumarcca75d22017-06-27 22:19:32 +0000833 case Intrinsic::exp:
834 MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
835 .addDef(getOrCreateVReg(CI))
836 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
837 return true;
838 case Intrinsic::exp2:
839 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
840 .addDef(getOrCreateVReg(CI))
841 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
842 return true;
Aditya Nandakumar20f62072017-06-29 23:43:44 +0000843 case Intrinsic::log:
844 MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
845 .addDef(getOrCreateVReg(CI))
846 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
847 return true;
848 case Intrinsic::log2:
849 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
850 .addDef(getOrCreateVReg(CI))
851 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
852 return true;
Volkan Keles2bc42e92018-03-05 22:31:55 +0000853 case Intrinsic::fabs:
854 MIRBuilder.buildInstr(TargetOpcode::G_FABS)
855 .addDef(getOrCreateVReg(CI))
856 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
857 return true;
Aditya Nandakumar2a082852018-08-20 18:43:19 +0000858 case Intrinsic::trunc:
859 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_TRUNC)
860 .addDef(getOrCreateVReg(CI))
861 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
862 return true;
863 case Intrinsic::round:
864 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_ROUND)
865 .addDef(getOrCreateVReg(CI))
866 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
867 return true;
Aditya Nandakumarc6a41912017-06-20 19:25:23 +0000868 case Intrinsic::fma:
869 MIRBuilder.buildInstr(TargetOpcode::G_FMA)
870 .addDef(getOrCreateVReg(CI))
871 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
872 .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
873 .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
874 return true;
Volkan Keles92837632018-02-13 00:47:46 +0000875 case Intrinsic::fmuladd: {
876 const TargetMachine &TM = MF->getTarget();
877 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
878 unsigned Dst = getOrCreateVReg(CI);
879 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
880 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
881 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
882 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
883 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
884 // TODO: Revisit this to see if we should move this part of the
885 // lowering to the combiner.
886 MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
887 } else {
888 LLT Ty = getLLTForType(*CI.getType(), *DL);
889 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
890 MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
891 }
892 return true;
893 }
Tim Northover3f186032016-10-18 20:03:45 +0000894 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000895 case Intrinsic::memmove:
896 case Intrinsic::memset:
897 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000898 case Intrinsic::eh_typeid_for: {
899 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
900 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000901 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000902 MIRBuilder.buildConstant(Reg, TypeID);
903 return true;
904 }
Tim Northover6e904302016-10-18 20:03:51 +0000905 case Intrinsic::objectsize: {
906 // If we don't know by now, we're never going to know.
907 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
908
909 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
910 return true;
911 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000912 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000913 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000914 return true;
915 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000916 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000917 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000918 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000919
920 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
921 MIRBuilder.buildStore(
922 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000923 *MF->getMachineMemOperand(
924 MachinePointerInfo::getFixedStack(*MF,
925 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000926 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
927 PtrTy.getSizeInBits() / 8, 8));
928 return true;
929 }
Aditya Nandakumare07b3b72018-08-04 01:22:12 +0000930 case Intrinsic::cttz:
931 case Intrinsic::ctlz: {
932 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
933 bool isTrailing = ID == Intrinsic::cttz;
934 unsigned Opcode = isTrailing
935 ? Cst->isZero() ? TargetOpcode::G_CTTZ
936 : TargetOpcode::G_CTTZ_ZERO_UNDEF
937 : Cst->isZero() ? TargetOpcode::G_CTLZ
938 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
939 MIRBuilder.buildInstr(Opcode)
940 .addDef(getOrCreateVReg(CI))
941 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
942 return true;
943 }
944 case Intrinsic::ctpop: {
945 MIRBuilder.buildInstr(TargetOpcode::G_CTPOP)
946 .addDef(getOrCreateVReg(CI))
947 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
948 return true;
949 }
Tim Northover91c81732016-08-19 17:17:06 +0000950 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000951 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000952}
953
Tim Northoveraa995c92017-03-09 23:36:26 +0000954bool IRTranslator::translateInlineAsm(const CallInst &CI,
955 MachineIRBuilder &MIRBuilder) {
956 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
957 if (!IA.getConstraintString().empty())
958 return false;
959
960 unsigned ExtraInfo = 0;
961 if (IA.hasSideEffects())
962 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
963 if (IA.getDialect() == InlineAsm::AD_Intel)
964 ExtraInfo |= InlineAsm::Extra_AsmDialect;
965
966 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
967 .addExternalSymbol(IA.getAsmString().c_str())
968 .addImm(ExtraInfo);
969
970 return true;
971}
972
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000973unsigned IRTranslator::packRegs(const Value &V,
974 MachineIRBuilder &MIRBuilder) {
975 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
976 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
977 LLT BigTy = getLLTForType(*V.getType(), *DL);
978
979 if (Regs.size() == 1)
980 return Regs[0];
981
982 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
983 MIRBuilder.buildUndef(Dst);
984 for (unsigned i = 0; i < Regs.size(); ++i) {
985 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
986 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
987 Dst = NewDst;
988 }
989 return Dst;
990}
991
992void IRTranslator::unpackRegs(const Value &V, unsigned Src,
993 MachineIRBuilder &MIRBuilder) {
994 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
995 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
996
997 for (unsigned i = 0; i < Regs.size(); ++i)
998 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
999}
1000
Tim Northoverc53606e2016-12-07 21:29:15 +00001001bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001002 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001003 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +00001004 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +00001005
Martin Storsjocc981d22018-01-30 19:50:58 +00001006 // FIXME: support Windows dllimport function calls.
1007 if (F && F->hasDLLImportStorageClass())
1008 return false;
1009
Tim Northover3babfef2017-01-19 23:59:35 +00001010 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +00001011 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +00001012
Amara Emerson913918c2018-01-02 18:56:39 +00001013 Intrinsic::ID ID = Intrinsic::not_intrinsic;
1014 if (F && F->isIntrinsic()) {
1015 ID = F->getIntrinsicID();
1016 if (TII && ID == Intrinsic::not_intrinsic)
1017 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1018 }
1019
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001020 bool IsSplitType = valueIsSplit(CI);
Amara Emerson913918c2018-01-02 18:56:39 +00001021 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001022 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1023 getLLTForType(*CI.getType(), *DL))
1024 : getOrCreateVReg(CI);
1025
Tim Northover406024a2016-08-10 21:44:01 +00001026 SmallVector<unsigned, 8> Args;
1027 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001028 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +00001029
Tim Northoverd1e951e2017-03-09 22:00:39 +00001030 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001031 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +00001032 return getOrCreateVReg(*CI.getCalledValue());
1033 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001034
1035 if (IsSplitType)
1036 unpackRegs(CI, Res, MIRBuilder);
1037 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001038 }
1039
Tim Northover406024a2016-08-10 21:44:01 +00001040 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001041
Tim Northoverc53606e2016-12-07 21:29:15 +00001042 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001043 return true;
1044
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001045 unsigned Res = 0;
1046 if (!CI.getType()->isVoidTy()) {
1047 if (IsSplitType)
1048 Res =
1049 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
1050 else
1051 Res = getOrCreateVReg(CI);
1052 }
Tim Northover5fb414d2016-07-29 22:32:36 +00001053 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +00001054 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +00001055
1056 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001057 // Some intrinsics take metadata parameters. Reject them.
1058 if (isa<MetadataAsValue>(Arg))
1059 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001060 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001061 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001062
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001063 if (IsSplitType)
1064 unpackRegs(CI, Res, MIRBuilder);
1065
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001066 // Add a MachineMemOperand if it is a target mem intrinsic.
1067 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1068 TargetLowering::IntrinsicInfo Info;
1069 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001070 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001071 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001072 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault11171332017-12-14 21:39:51 +00001073 Info.flags, Size, Info.align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001074 }
1075
Tim Northover5fb414d2016-07-29 22:32:36 +00001076 return true;
1077}
1078
Tim Northoverc53606e2016-12-07 21:29:15 +00001079bool IRTranslator::translateInvoke(const User &U,
1080 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001081 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001082 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001083
1084 const BasicBlock *ReturnBB = I.getSuccessor(0);
1085 const BasicBlock *EHPadBB = I.getSuccessor(1);
1086
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001087 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001088 const Function *Fn = dyn_cast<Function>(Callee);
1089 if (isa<InlineAsm>(Callee))
1090 return false;
1091
1092 // FIXME: support invoking patchpoint and statepoint intrinsics.
1093 if (Fn && Fn->isIntrinsic())
1094 return false;
1095
1096 // FIXME: support whatever these are.
1097 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1098 return false;
1099
1100 // FIXME: support Windows exception handling.
1101 if (!isa<LandingPadInst>(EHPadBB->front()))
1102 return false;
1103
Matthias Braund0ee66c2016-12-01 19:32:15 +00001104 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001105 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001106 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001107 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1108
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001109 unsigned Res =
1110 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001111 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001112 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001113 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001114
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001115 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001116 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1117 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001118
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001119 unpackRegs(I, Res, MIRBuilder);
1120
Matthias Braund0ee66c2016-12-01 19:32:15 +00001121 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001122 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1123
1124 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001125 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1126 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001127 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001128 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1129 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001130 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001131
1132 return true;
1133}
1134
Tim Northoverc53606e2016-12-07 21:29:15 +00001135bool IRTranslator::translateLandingPad(const User &U,
1136 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001137 const LandingPadInst &LP = cast<LandingPadInst>(U);
1138
1139 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +00001140 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001141
1142 MBB.setIsEHPad();
1143
1144 // If there aren't registers to copy the values into (e.g., during SjLj
1145 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001146 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001147 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001148 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1149 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1150 return true;
1151
1152 // If landingpad's return type is token type, we don't create DAG nodes
1153 // for its exception pointer and selector value. The extraction of exception
1154 // pointer or selector value from token type landingpads is not currently
1155 // supported.
1156 if (LP.getType()->isTokenTy())
1157 return true;
1158
1159 // Add a label to mark the beginning of the landing pad. Deletion of the
1160 // landing pad can thus be detected via the MachineModuleInfo.
1161 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001162 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001163
Daniel Sanders1351db42017-03-07 23:32:10 +00001164 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001165 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1166 MIRBuilder.buildUndef(Undef);
1167
Justin Bognera0295312017-01-25 00:16:53 +00001168 SmallVector<LLT, 2> Tys;
1169 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001170 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001171 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1172
Tim Northovera9105be2016-11-09 22:39:54 +00001173 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001174 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1175 if (!ExceptionReg)
1176 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001177
Tim Northover542d1c12017-03-07 23:04:06 +00001178 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001179 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1180 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001181
Tim Northover542d1c12017-03-07 23:04:06 +00001182 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1183 if (!SelectorReg)
1184 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001185
Tim Northover542d1c12017-03-07 23:04:06 +00001186 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001187 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1188 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001189 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001190
Tim Northovera9105be2016-11-09 22:39:54 +00001191 return true;
1192}
1193
Tim Northoverc3e3f592017-02-03 18:22:45 +00001194bool IRTranslator::translateAlloca(const User &U,
1195 MachineIRBuilder &MIRBuilder) {
1196 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001197
Amara Emersonfdd089a2018-07-26 01:25:58 +00001198 if (AI.isSwiftError())
1199 return false;
1200
Tim Northoverc3e3f592017-02-03 18:22:45 +00001201 if (AI.isStaticAlloca()) {
1202 unsigned Res = getOrCreateVReg(AI);
1203 int FI = getOrCreateFrameIndex(AI);
1204 MIRBuilder.buildFrameIndex(Res, FI);
1205 return true;
1206 }
1207
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001208 // FIXME: support stack probing for Windows.
1209 if (MF->getTarget().getTargetTriple().isOSWindows())
1210 return false;
1211
Tim Northoverc3e3f592017-02-03 18:22:45 +00001212 // Now we're in the harder dynamic case.
1213 Type *Ty = AI.getAllocatedType();
1214 unsigned Align =
1215 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1216
1217 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1218
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001219 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1220 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001221 if (MRI->getType(NumElts) != IntPtrTy) {
1222 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1223 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1224 NumElts = ExtElts;
1225 }
1226
1227 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001228 unsigned TySize =
1229 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001230 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1231
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001232 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001233 auto &TLI = *MF->getSubtarget().getTargetLowering();
1234 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1235
1236 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1237 MIRBuilder.buildCopy(SPTmp, SPReg);
1238
Tim Northoverc2f89562017-02-14 20:56:18 +00001239 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1240 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001241
1242 // Handle alignment. We have to realign if the allocation granule was smaller
1243 // than stack alignment, or the specific alloca requires more than stack
1244 // alignment.
1245 unsigned StackAlign =
1246 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1247 Align = std::max(Align, StackAlign);
1248 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1249 // Round the size of the allocation up to the stack alignment size
1250 // by add SA-1 to the size. This doesn't overflow because we're computing
1251 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001252 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1253 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1254 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001255 }
1256
Tim Northoverc2f89562017-02-14 20:56:18 +00001257 MIRBuilder.buildCopy(SPReg, AllocTmp);
1258 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001259
1260 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1261 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001262 return true;
1263}
1264
Tim Northover4a652222017-02-15 23:22:33 +00001265bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1266 // FIXME: We may need more info about the type. Because of how LLT works,
1267 // we're completely discarding the i64/double distinction here (amongst
1268 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1269 // anyway but that's not guaranteed.
1270 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1271 .addDef(getOrCreateVReg(U))
1272 .addUse(getOrCreateVReg(*U.getOperand(0)))
1273 .addImm(DL->getABITypeAlignment(U.getType()));
1274 return true;
1275}
1276
Volkan Keles04cb08c2017-03-10 19:08:28 +00001277bool IRTranslator::translateInsertElement(const User &U,
1278 MachineIRBuilder &MIRBuilder) {
1279 // If it is a <1 x Ty> vector, use the scalar as it is
1280 // not a legal vector type in LLT.
1281 if (U.getType()->getVectorNumElements() == 1) {
1282 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001283 auto &Regs = *VMap.getVRegs(U);
1284 if (Regs.empty()) {
1285 Regs.push_back(Elt);
1286 VMap.getOffsets(U)->push_back(0);
1287 } else {
1288 MIRBuilder.buildCopy(Regs[0], Elt);
1289 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001290 return true;
1291 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001292
Kristof Beyls7a713502017-04-19 06:38:37 +00001293 unsigned Res = getOrCreateVReg(U);
1294 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1295 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1296 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1297 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001298 return true;
1299}
1300
1301bool IRTranslator::translateExtractElement(const User &U,
1302 MachineIRBuilder &MIRBuilder) {
1303 // If it is a <1 x Ty> vector, use the scalar as it is
1304 // not a legal vector type in LLT.
1305 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1306 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001307 auto &Regs = *VMap.getVRegs(U);
1308 if (Regs.empty()) {
1309 Regs.push_back(Elt);
1310 VMap.getOffsets(U)->push_back(0);
1311 } else {
1312 MIRBuilder.buildCopy(Regs[0], Elt);
1313 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001314 return true;
1315 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001316 unsigned Res = getOrCreateVReg(U);
1317 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1318 unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1319 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001320 return true;
1321}
1322
Volkan Keles75bdc762017-03-21 08:44:13 +00001323bool IRTranslator::translateShuffleVector(const User &U,
1324 MachineIRBuilder &MIRBuilder) {
1325 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1326 .addDef(getOrCreateVReg(U))
1327 .addUse(getOrCreateVReg(*U.getOperand(0)))
1328 .addUse(getOrCreateVReg(*U.getOperand(1)))
1329 .addUse(getOrCreateVReg(*U.getOperand(2)));
1330 return true;
1331}
1332
Tim Northoverc53606e2016-12-07 21:29:15 +00001333bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001334 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001335
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001336 SmallVector<MachineInstr *, 4> Insts;
1337 for (auto Reg : getOrCreateVRegs(PI)) {
1338 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1339 Insts.push_back(MIB.getInstr());
1340 }
1341
1342 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001343 return true;
1344}
1345
Daniel Sanders94813992018-07-09 19:33:40 +00001346bool IRTranslator::translateAtomicCmpXchg(const User &U,
1347 MachineIRBuilder &MIRBuilder) {
1348 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1349
1350 if (I.isWeak())
1351 return false;
1352
1353 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1354 : MachineMemOperand::MONone;
1355 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1356
1357 Type *ResType = I.getType();
1358 Type *ValType = ResType->Type::getStructElementType(0);
1359
1360 auto Res = getOrCreateVRegs(I);
1361 unsigned OldValRes = Res[0];
1362 unsigned SuccessRes = Res[1];
1363 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1364 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1365 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1366
1367 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1368 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1369 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1370 Flags, DL->getTypeStoreSize(ValType),
1371 getMemOpAlignment(I), AAMDNodes(), nullptr,
1372 I.getSyncScopeID(), I.getSuccessOrdering(),
1373 I.getFailureOrdering()));
1374 return true;
1375}
1376
1377bool IRTranslator::translateAtomicRMW(const User &U,
1378 MachineIRBuilder &MIRBuilder) {
1379 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1380
1381 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1382 : MachineMemOperand::MONone;
1383 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1384
1385 Type *ResType = I.getType();
1386
1387 unsigned Res = getOrCreateVReg(I);
1388 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1389 unsigned Val = getOrCreateVReg(*I.getValOperand());
1390
1391 unsigned Opcode = 0;
1392 switch (I.getOperation()) {
1393 default:
1394 llvm_unreachable("Unknown atomicrmw op");
1395 return false;
1396 case AtomicRMWInst::Xchg:
1397 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1398 break;
1399 case AtomicRMWInst::Add:
1400 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1401 break;
1402 case AtomicRMWInst::Sub:
1403 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1404 break;
1405 case AtomicRMWInst::And:
1406 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1407 break;
1408 case AtomicRMWInst::Nand:
1409 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1410 break;
1411 case AtomicRMWInst::Or:
1412 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1413 break;
1414 case AtomicRMWInst::Xor:
1415 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1416 break;
1417 case AtomicRMWInst::Max:
1418 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1419 break;
1420 case AtomicRMWInst::Min:
1421 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1422 break;
1423 case AtomicRMWInst::UMax:
1424 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1425 break;
1426 case AtomicRMWInst::UMin:
1427 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1428 break;
1429 }
1430
1431 MIRBuilder.buildAtomicRMW(
1432 Opcode, Res, Addr, Val,
1433 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1434 Flags, DL->getTypeStoreSize(ResType),
1435 getMemOpAlignment(I), AAMDNodes(), nullptr,
1436 I.getSyncScopeID(), I.getOrdering()));
1437 return true;
1438}
1439
Tim Northover97d0cb32016-08-05 17:16:40 +00001440void IRTranslator::finishPendingPhis() {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001441 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001442 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001443 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Tim Northover97d0cb32016-08-05 17:16:40 +00001444
1445 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1446 // won't create extra control flow here, otherwise we need to find the
1447 // dominating predecessor here (or perhaps force the weirder IRTranslators
1448 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001449 SmallSet<const BasicBlock *, 4> HandledPreds;
1450
Tim Northover97d0cb32016-08-05 17:16:40 +00001451 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001452 auto IRPred = PI->getIncomingBlock(i);
1453 if (HandledPreds.count(IRPred))
1454 continue;
1455
1456 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001457 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001458 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001459 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001460 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001461 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1462 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1463 MIB.addUse(ValRegs[j]);
1464 MIB.addMBB(Pred);
1465 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001466 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001467 }
1468 }
1469}
1470
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001471bool IRTranslator::valueIsSplit(const Value &V,
1472 SmallVectorImpl<uint64_t> *Offsets) {
1473 SmallVector<LLT, 4> SplitTys;
Amara Emerson30e61402018-08-14 12:04:25 +00001474 if (Offsets && !Offsets->empty())
1475 Offsets->clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001476 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1477 return SplitTys.size() > 1;
1478}
1479
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001480bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001481 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001482 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001483#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001484 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001485#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001486 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001487 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001488 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001489}
1490
Tim Northover5ed648e2016-08-09 21:28:04 +00001491bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001492 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001493 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001494 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001495 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001496 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001497 EntryBuilder.buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001498 else if (isa<ConstantPointerNull>(C)) {
1499 // As we are trying to build a constant val of 0 into a pointer,
1500 // insert a cast to make them correct with respect to types.
1501 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1502 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1503 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1504 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1505 EntryBuilder.buildCast(Reg, ZeroReg);
1506 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Tim Northover032548f2016-09-12 12:10:41 +00001507 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001508 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1509 if (!CAZ->getType()->isVectorTy())
1510 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001511 // Return the scalar if it is a <1 x Ty> vector.
1512 if (CAZ->getNumElements() == 1)
1513 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001514 std::vector<unsigned> Ops;
1515 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1516 Constant &Elt = *CAZ->getElementValue(i);
1517 Ops.push_back(getOrCreateVReg(Elt));
1518 }
1519 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001520 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001521 // Return the scalar if it is a <1 x Ty> vector.
1522 if (CV->getNumElements() == 1)
1523 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001524 std::vector<unsigned> Ops;
1525 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1526 Constant &Elt = *CV->getElementAsConstant(i);
1527 Ops.push_back(getOrCreateVReg(Elt));
1528 }
1529 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001530 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001531 switch(CE->getOpcode()) {
1532#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001533 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001534#include "llvm/IR/Instruction.def"
1535 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001536 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001537 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001538 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1539 if (CV->getNumOperands() == 1)
1540 return translate(*CV->getOperand(0), Reg);
1541 SmallVector<unsigned, 4> Ops;
1542 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1543 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1544 }
1545 EntryBuilder.buildMerge(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001546 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1547 EntryBuilder.buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001548 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001549 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001550
Tim Northoverd403a3d2016-08-09 23:01:30 +00001551 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001552}
1553
Tim Northover0d510442016-08-11 16:21:29 +00001554void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001555 // Release the memory used by the different maps we
1556 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001557 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001558 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001559 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001560 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001561 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1562 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1563 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1564 EntryBuilder = MachineIRBuilder();
1565 CurBuilder = MachineIRBuilder();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001566}
1567
Tim Northover50db7f412016-12-07 21:17:47 +00001568bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1569 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001570 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001571 if (F.empty())
1572 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001573 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001574 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001575 EntryBuilder.setMF(*MF);
1576 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001577 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001578 TPC = &getAnalysis<TargetPassConfig>();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001579 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001580
Tim Northover14e7f732016-08-05 17:50:36 +00001581 assert(PendingPHIs.empty() && "stale PHIs");
1582
Amara Emersondf9b5292017-12-11 16:58:29 +00001583 if (!DL->isLittleEndian()) {
1584 // Currently we don't properly handle big endian code.
1585 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001586 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001587 R << "unable to translate in big endian mode";
1588 reportTranslationError(*MF, *TPC, *ORE, R);
1589 }
1590
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001591 // Release the per-function state when we return, whether we succeeded or not.
1592 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1593
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001594 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001595 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1596 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001597 EntryBuilder.setMBB(*EntryBB);
1598
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001599 // Create all blocks, in IR order, to preserve the layout.
1600 for (const BasicBlock &BB: F) {
1601 auto *&MBB = BBToMBB[&BB];
1602
1603 MBB = MF->CreateMachineBasicBlock(&BB);
1604 MF->push_back(MBB);
1605
1606 if (BB.hasAddressTaken())
1607 MBB->setHasAddressTaken();
1608 }
1609
1610 // Make our arguments/constants entry block fallthrough to the IR entry block.
1611 EntryBB->addSuccessor(&getMBB(F.front()));
1612
Tim Northover05cc4852016-12-07 21:05:38 +00001613 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001614 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001615 for (const Argument &Arg: F.args()) {
1616 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1617 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001618 VRegArgs.push_back(
1619 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001620 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001621
Amara Emersonfdd089a2018-07-26 01:25:58 +00001622 // We don't currently support translating swifterror or swiftself functions.
1623 for (auto &Arg : F.args()) {
1624 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1625 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1626 F.getSubprogram(), &F.getEntryBlock());
1627 R << "unable to lower arguments due to swifterror/swiftself: "
1628 << ore::NV("Prototype", F.getType());
1629 reportTranslationError(*MF, *TPC, *ORE, R);
1630 return false;
1631 }
1632 }
1633
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001634 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001635 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001636 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001637 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1638 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001639 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001640 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001641
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001642 auto ArgIt = F.arg_begin();
1643 for (auto &VArg : VRegArgs) {
1644 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1645 // creating redundant copies.
1646 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1647 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1648 assert(VRegs.empty() && "VRegs already populated?");
1649 VRegs.push_back(VArg);
1650 } else {
1651 unpackRegs(*ArgIt, VArg, EntryBuilder);
1652 }
1653 ArgIt++;
1654 }
1655
Amara Emerson6cdfe292018-08-01 02:17:42 +00001656 // Need to visit defs before uses when translating instructions.
1657 ReversePostOrderTraversal<const Function *> RPOT(&F);
1658 for (const BasicBlock *BB : RPOT) {
1659 MachineBasicBlock &MBB = getMBB(*BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001660 // Set the insertion point of all the following translations to
1661 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001662 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001663
Amara Emerson6cdfe292018-08-01 02:17:42 +00001664 for (const Instruction &Inst : *BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001665 if (translate(Inst))
1666 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001667
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001668 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Amara Emerson6cdfe292018-08-01 02:17:42 +00001669 Inst.getDebugLoc(), BB);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001670 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1671
1672 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1673 std::string InstStrStorage;
1674 raw_string_ostream InstStr(InstStrStorage);
1675 InstStr << Inst;
1676
1677 R << ": '" << InstStr.str() << "'";
1678 }
1679
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001680 reportTranslationError(*MF, *TPC, *ORE, R);
1681 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001682 }
1683 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001684
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001685 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001686
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001687 // Merge the argument lowering and constants block with its single
1688 // successor, the LLVM-IR entry block. We want the basic block to
1689 // be maximal.
1690 assert(EntryBB->succ_size() == 1 &&
1691 "Custom BB used for lowering should have only one successor");
1692 // Get the successor of the current entry block.
1693 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1694 assert(NewEntryBB.pred_size() == 1 &&
1695 "LLVM-IR entry block has a predecessor!?");
1696 // Move all the instruction from the current entry block to the
1697 // new entry block.
1698 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1699 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001700
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001701 // Update the live-in information for the new entry block.
1702 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1703 NewEntryBB.addLiveIn(LiveIn);
1704 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001705
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001706 // Get rid of the now empty basic block.
1707 EntryBB->removeSuccessor(&NewEntryBB);
1708 MF->remove(EntryBB);
1709 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001710
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001711 assert(&MF->front() == &NewEntryBB &&
1712 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001713
Matthias Braun90ad6832018-07-13 00:08:38 +00001714 // Initialize stack protector information.
1715 StackProtector &SP = getAnalysis<StackProtector>();
1716 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1717
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001718 return false;
1719}