blob: 206d40274fdad9eb0cd6d0c6ff95ee8e7d0f179a [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);
Michael Berg894c39f2018-09-19 18:52:08 +0000282 auto FBinOp = MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
283 if (isa<Instruction>(U)) {
284 MachineInstr *FBinOpMI = FBinOp.getInstr();
285 const Instruction &I = cast<Instruction>(U);
286 FBinOpMI->copyIRFlags(I);
287 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000288 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000289}
290
Volkan Keles20d3c422017-03-07 18:03:28 +0000291bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
292 // -0.0 - X --> G_FNEG
293 if (isa<Constant>(U.getOperand(0)) &&
294 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
295 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
296 .addDef(getOrCreateVReg(U))
297 .addUse(getOrCreateVReg(*U.getOperand(1)));
298 return true;
299 }
300 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
301}
302
Tim Northoverc53606e2016-12-07 21:29:15 +0000303bool IRTranslator::translateCompare(const User &U,
304 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000305 const CmpInst *CI = dyn_cast<CmpInst>(&U);
306 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
307 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
308 unsigned Res = getOrCreateVReg(U);
309 CmpInst::Predicate Pred =
310 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
311 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000312 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000313 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000314 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000315 MIRBuilder.buildCopy(
316 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
317 else if (Pred == CmpInst::FCMP_TRUE)
318 MIRBuilder.buildCopy(
319 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000320 else
Tim Northover0f140c72016-09-09 11:46:34 +0000321 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000322
Tim Northoverde3aea0412016-08-17 20:25:25 +0000323 return true;
324}
325
Tim Northoverc53606e2016-12-07 21:29:15 +0000326bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000327 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000328 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000329 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
330 Ret = nullptr;
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000331
332 ArrayRef<unsigned> VRegs;
333 if (Ret)
334 VRegs = getOrCreateVRegs(*Ret);
335
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000336 // The target may mess up with the insertion point, but
337 // this is not important as a return is the last instruction
338 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000339
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000340 return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000341}
342
Tim Northoverc53606e2016-12-07 21:29:15 +0000343bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000344 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000345 unsigned Succ = 0;
346 if (!BrInst.isUnconditional()) {
347 // We want a G_BRCOND to the true BB followed by an unconditional branch.
348 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
349 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000350 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000351 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000352 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000353
354 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000355 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000356 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
357
358 // If the unconditional target is the layout successor, fallthrough.
359 if (!CurBB.isLayoutSuccessor(&TgtBB))
360 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000361
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000362 // Link successors.
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000363 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000364 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000365 return true;
366}
367
Kristof Beylseced0712017-01-05 11:28:51 +0000368bool IRTranslator::translateSwitch(const User &U,
369 MachineIRBuilder &MIRBuilder) {
370 // For now, just translate as a chain of conditional branches.
371 // FIXME: could we share most of the logic/code in
372 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
373 // At first sight, it seems most of the logic in there is independent of
374 // SelectionDAG-specifics and a lot of work went in to optimize switch
375 // lowering in there.
376
377 const SwitchInst &SwInst = cast<SwitchInst>(U);
378 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000379 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000380
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000381 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000382 for (auto &CaseIt : SwInst.cases()) {
383 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
384 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
385 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000386 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
387 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000388 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000389
Tim Northoverb6636fd2017-01-17 22:13:50 +0000390 MIRBuilder.buildBrCond(Tst, TrueMBB);
391 CurMBB.addSuccessor(&TrueMBB);
392 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000393
Tim Northoverb6636fd2017-01-17 22:13:50 +0000394 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000395 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000396 // Insert the comparison blocks one after the other.
397 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000398 MIRBuilder.buildBr(*FalseMBB);
399 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000400
Tim Northoverb6636fd2017-01-17 22:13:50 +0000401 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000402 }
403 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000404 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000405 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000406 MIRBuilder.buildBr(DefaultMBB);
407 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
408 CurMBB.addSuccessor(&DefaultMBB);
409 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000410
411 return true;
412}
413
Kristof Beyls65a12c02017-01-30 09:13:18 +0000414bool IRTranslator::translateIndirectBr(const User &U,
415 MachineIRBuilder &MIRBuilder) {
416 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
417
418 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
419 MIRBuilder.buildBrIndirect(Tgt);
420
421 // Link successors.
422 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000423 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000424 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000425
426 return true;
427}
428
Tim Northoverc53606e2016-12-07 21:29:15 +0000429bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000430 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000431
Tim Northover7152dca2016-10-19 15:55:06 +0000432 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
433 : MachineMemOperand::MONone;
434 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000435
Amara Emersond78d65c2017-11-30 20:06:02 +0000436 if (DL->getTypeStoreSize(LI.getType()) == 0)
437 return true;
438
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000439 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
440 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
441 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000442
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000443 for (unsigned i = 0; i < Regs.size(); ++i) {
444 unsigned Addr = 0;
445 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
446
447 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
448 unsigned BaseAlign = getMemOpAlignment(LI);
449 auto MMO = MF->getMachineMemOperand(
450 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
451 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
452 LI.getSyncScopeID(), LI.getOrdering());
453 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
454 }
455
Tim Northoverad2b7172016-07-26 20:23:26 +0000456 return true;
457}
458
Tim Northoverc53606e2016-12-07 21:29:15 +0000459bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000460 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000461 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
462 : MachineMemOperand::MONone;
463 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000464
Amara Emersond78d65c2017-11-30 20:06:02 +0000465 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
466 return true;
467
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000468 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
469 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
470 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000471
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000472 for (unsigned i = 0; i < Vals.size(); ++i) {
473 unsigned Addr = 0;
474 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
475
476 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
477 unsigned BaseAlign = getMemOpAlignment(SI);
478 auto MMO = MF->getMachineMemOperand(
479 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
480 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
481 SI.getSyncScopeID(), SI.getOrdering());
482 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
483 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000484 return true;
485}
486
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000487static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000488 const Value *Src = U.getOperand(0);
489 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000490
Tim Northover6f80b082016-08-19 17:47:05 +0000491 // getIndexedOffsetInType is designed for GEPs, so the first index is the
492 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000493 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000494 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000495
496 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
497 for (auto Idx : EVI->indices())
498 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000499 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
500 for (auto Idx : IVI->indices())
501 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000502 } else {
503 for (unsigned i = 1; i < U.getNumOperands(); ++i)
504 Indices.push_back(U.getOperand(i));
505 }
Tim Northover6f80b082016-08-19 17:47:05 +0000506
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000507 return 8 * static_cast<uint64_t>(
508 DL.getIndexedOffsetInType(Src->getType(), Indices));
509}
Tim Northover6f80b082016-08-19 17:47:05 +0000510
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000511bool IRTranslator::translateExtractValue(const User &U,
512 MachineIRBuilder &MIRBuilder) {
513 const Value *Src = U.getOperand(0);
514 uint64_t Offset = getOffsetFromIndices(U, *DL);
515 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
516 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
517 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
518 Offsets.begin();
519 auto &DstRegs = allocateVRegs(U);
520
521 for (unsigned i = 0; i < DstRegs.size(); ++i)
522 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000523
524 return true;
525}
526
Tim Northoverc53606e2016-12-07 21:29:15 +0000527bool IRTranslator::translateInsertValue(const User &U,
528 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000529 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000530 uint64_t Offset = getOffsetFromIndices(U, *DL);
531 auto &DstRegs = allocateVRegs(U);
532 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
533 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
534 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
535 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000536
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000537 for (unsigned i = 0; i < DstRegs.size(); ++i) {
538 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
539 DstRegs[i] = *InsertedIt++;
540 else
541 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000542 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000543
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000544 return true;
545}
546
Tim Northoverc53606e2016-12-07 21:29:15 +0000547bool IRTranslator::translateSelect(const User &U,
548 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000549 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000550 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
551 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
552 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
553
554 for (unsigned i = 0; i < ResRegs.size(); ++i)
555 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
556
Tim Northover5a28c362016-08-19 20:09:07 +0000557 return true;
558}
559
Tim Northoverc53606e2016-12-07 21:29:15 +0000560bool IRTranslator::translateBitCast(const User &U,
561 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000562 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000563 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
564 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000565 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000566 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000567 // If we already assigned a vreg for this bitcast, we can't change that.
568 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000569 if (!Regs.empty())
570 MIRBuilder.buildCopy(Regs[0], SrcReg);
571 else {
572 Regs.push_back(SrcReg);
573 VMap.getOffsets(U)->push_back(0);
574 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000575 return true;
576 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000577 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000578}
579
Tim Northoverc53606e2016-12-07 21:29:15 +0000580bool IRTranslator::translateCast(unsigned Opcode, const User &U,
581 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000582 unsigned Op = getOrCreateVReg(*U.getOperand(0));
583 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000584 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000585 return true;
586}
587
Tim Northoverc53606e2016-12-07 21:29:15 +0000588bool IRTranslator::translateGetElementPtr(const User &U,
589 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000590 // FIXME: support vector GEPs.
591 if (U.getType()->isVectorTy())
592 return false;
593
594 Value &Op0 = *U.getOperand(0);
595 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000596 Type *PtrIRTy = Op0.getType();
597 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
598 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
599 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000600
601 int64_t Offset = 0;
602 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
603 GTI != E; ++GTI) {
604 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000605 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000606 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
607 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
608 continue;
609 } else {
610 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
611
612 // If this is a scalar constant or a splat vector of constants,
613 // handle it quickly.
614 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
615 Offset += ElementSize * CI->getSExtValue();
616 continue;
617 }
618
619 if (Offset != 0) {
620 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000621 unsigned OffsetReg =
622 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000623 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
624
625 BaseReg = NewBaseReg;
626 Offset = 0;
627 }
628
Tim Northovera7653b32016-09-12 11:20:22 +0000629 unsigned IdxReg = getOrCreateVReg(*Idx);
630 if (MRI->getType(IdxReg) != OffsetTy) {
631 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
632 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
633 IdxReg = NewIdxReg;
634 }
635
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000636 // N = N + Idx * ElementSize;
637 // Avoid doing it for ElementSize of 1.
638 unsigned GepOffsetReg;
639 if (ElementSize != 1) {
640 unsigned ElementSizeReg =
641 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
642
643 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
644 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
645 } else
646 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000647
648 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000649 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000650 BaseReg = NewBaseReg;
651 }
652 }
653
654 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000655 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000656 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
657 return true;
658 }
659
660 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
661 return true;
662}
663
Tim Northover79f43f12017-01-30 19:33:07 +0000664bool IRTranslator::translateMemfunc(const CallInst &CI,
665 MachineIRBuilder &MIRBuilder,
666 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000667 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000668 Type *DstTy = CI.getArgOperand(0)->getType();
669 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000670 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
671 return false;
672
673 SmallVector<CallLowering::ArgInfo, 8> Args;
674 for (int i = 0; i < 3; ++i) {
675 const auto &Arg = CI.getArgOperand(i);
676 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
677 }
678
Tim Northover79f43f12017-01-30 19:33:07 +0000679 const char *Callee;
680 switch (ID) {
681 case Intrinsic::memmove:
682 case Intrinsic::memcpy: {
683 Type *SrcTy = CI.getArgOperand(1)->getType();
684 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
685 return false;
686 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
687 break;
688 }
689 case Intrinsic::memset:
690 Callee = "memset";
691 break;
692 default:
693 return false;
694 }
Tim Northover3f186032016-10-18 20:03:45 +0000695
Diana Picusd79253a2017-03-20 14:40:18 +0000696 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
697 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000698 CallLowering::ArgInfo(0, CI.getType()), Args);
699}
Tim Northovera7653b32016-09-12 11:20:22 +0000700
Tim Northoverc53606e2016-12-07 21:29:15 +0000701void IRTranslator::getStackGuard(unsigned DstReg,
702 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000703 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
704 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000705 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
706 MIB.addDef(DstReg);
707
Tim Northover50db7f412016-12-07 21:17:47 +0000708 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000709 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000710 if (!Global)
711 return;
712
713 MachinePointerInfo MPInfo(Global);
Tim Northovercdf23f12016-10-31 18:30:59 +0000714 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
715 MachineMemOperand::MODereferenceable;
Chandler Carruthc73c0302018-08-16 21:30:05 +0000716 MachineMemOperand *MemRef =
Tim Northover50db7f412016-12-07 21:17:47 +0000717 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000718 DL->getPointerABIAlignment(0));
Chandler Carruthc73c0302018-08-16 21:30:05 +0000719 MIB.setMemRefs({MemRef});
Tim Northovercdf23f12016-10-31 18:30:59 +0000720}
721
Tim Northover1e656ec2016-12-08 22:44:00 +0000722bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
723 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000724 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000725 MIRBuilder.buildInstr(Op)
726 .addDef(ResRegs[0])
727 .addDef(ResRegs[1])
728 .addUse(getOrCreateVReg(*CI.getOperand(0)))
729 .addUse(getOrCreateVReg(*CI.getOperand(1)));
Tim Northover1e656ec2016-12-08 22:44:00 +0000730
Tim Northover1e656ec2016-12-08 22:44:00 +0000731 return true;
732}
733
Tim Northoverc53606e2016-12-07 21:29:15 +0000734bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
735 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000736 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000737 default:
738 break;
Tim Northover0e011702017-02-10 19:10:38 +0000739 case Intrinsic::lifetime_start:
740 case Intrinsic::lifetime_end:
741 // Stack coloring is not enabled in O0 (which we care about now) so we can
742 // drop these. Make sure someone notices when we start compiling at higher
743 // opts though.
744 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
745 return false;
746 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000747 case Intrinsic::dbg_declare: {
748 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
749 assert(DI.getVariable() && "Missing variable");
750
751 const Value *Address = DI.getAddress();
752 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000753 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000754 return true;
755 }
756
Tim Northover09aac4a2017-01-26 23:39:14 +0000757 assert(DI.getVariable()->isValidLocationForIntrinsic(
758 MIRBuilder.getDebugLoc()) &&
759 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000760 auto AI = dyn_cast<AllocaInst>(Address);
761 if (AI && AI->isStaticAlloca()) {
762 // Static allocas are tracked at the MF level, no need for DBG_VALUE
763 // instructions (in fact, they get ignored if they *do* exist).
764 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
765 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Josh Stonef446fac2018-09-11 17:52:01 +0000766 } else {
767 // A dbg.declare describes the address of a source variable, so lower it
768 // into an indirect DBG_VALUE.
769 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
770 DI.getVariable(), DI.getExpression());
771 }
Tim Northoverb58346f2016-12-08 22:44:13 +0000772 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000773 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000774 case Intrinsic::dbg_label: {
775 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
776 assert(DI.getLabel() && "Missing label");
777
778 assert(DI.getLabel()->isValidLocationForIntrinsic(
779 MIRBuilder.getDebugLoc()) &&
780 "Expected inlined-at fields to agree");
781
782 MIRBuilder.buildDbgLabel(DI.getLabel());
783 return true;
784 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000785 case Intrinsic::vaend:
786 // No target I know of cares about va_end. Certainly no in-tree target
787 // does. Simplest intrinsic ever!
788 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000789 case Intrinsic::vastart: {
790 auto &TLI = *MF->getSubtarget().getTargetLowering();
791 Value *Ptr = CI.getArgOperand(0);
792 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
793
794 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
795 .addUse(getOrCreateVReg(*Ptr))
796 .addMemOperand(MF->getMachineMemOperand(
797 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
798 return true;
799 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000800 case Intrinsic::dbg_value: {
801 // This form of DBG_VALUE is target-independent.
802 const DbgValueInst &DI = cast<DbgValueInst>(CI);
803 const Value *V = DI.getValue();
804 assert(DI.getVariable()->isValidLocationForIntrinsic(
805 MIRBuilder.getDebugLoc()) &&
806 "Expected inlined-at fields to agree");
807 if (!V) {
808 // Currently the optimizer can produce this; insert an undef to
809 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000810 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000811 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000812 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000813 } else {
814 unsigned Reg = getOrCreateVReg(*V);
815 // FIXME: This does not handle register-indirect values at offset 0. The
816 // direct/indirect thing shouldn't really be handled by something as
817 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
818 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000819 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000820 }
821 return true;
822 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000823 case Intrinsic::uadd_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000824 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000825 case Intrinsic::sadd_with_overflow:
826 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
827 case Intrinsic::usub_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000828 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000829 case Intrinsic::ssub_with_overflow:
830 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
831 case Intrinsic::umul_with_overflow:
832 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
833 case Intrinsic::smul_with_overflow:
834 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000835 case Intrinsic::pow:
836 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
837 .addDef(getOrCreateVReg(CI))
838 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
839 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
840 return true;
Aditya Nandakumarcca75d22017-06-27 22:19:32 +0000841 case Intrinsic::exp:
842 MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
843 .addDef(getOrCreateVReg(CI))
844 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
845 return true;
846 case Intrinsic::exp2:
847 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
848 .addDef(getOrCreateVReg(CI))
849 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
850 return true;
Aditya Nandakumar20f62072017-06-29 23:43:44 +0000851 case Intrinsic::log:
852 MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
853 .addDef(getOrCreateVReg(CI))
854 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
855 return true;
856 case Intrinsic::log2:
857 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
858 .addDef(getOrCreateVReg(CI))
859 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
860 return true;
Volkan Keles2bc42e92018-03-05 22:31:55 +0000861 case Intrinsic::fabs:
862 MIRBuilder.buildInstr(TargetOpcode::G_FABS)
863 .addDef(getOrCreateVReg(CI))
864 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
865 return true;
Aditya Nandakumar2a082852018-08-20 18:43:19 +0000866 case Intrinsic::trunc:
867 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_TRUNC)
868 .addDef(getOrCreateVReg(CI))
869 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
870 return true;
871 case Intrinsic::round:
872 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_ROUND)
873 .addDef(getOrCreateVReg(CI))
874 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
875 return true;
Aditya Nandakumarc6a41912017-06-20 19:25:23 +0000876 case Intrinsic::fma:
877 MIRBuilder.buildInstr(TargetOpcode::G_FMA)
878 .addDef(getOrCreateVReg(CI))
879 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
880 .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
881 .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
882 return true;
Volkan Keles92837632018-02-13 00:47:46 +0000883 case Intrinsic::fmuladd: {
884 const TargetMachine &TM = MF->getTarget();
885 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
886 unsigned Dst = getOrCreateVReg(CI);
887 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
888 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
889 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
890 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
891 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
892 // TODO: Revisit this to see if we should move this part of the
893 // lowering to the combiner.
894 MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
895 } else {
896 LLT Ty = getLLTForType(*CI.getType(), *DL);
897 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
898 MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
899 }
900 return true;
901 }
Tim Northover3f186032016-10-18 20:03:45 +0000902 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000903 case Intrinsic::memmove:
904 case Intrinsic::memset:
905 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000906 case Intrinsic::eh_typeid_for: {
907 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
908 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000909 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000910 MIRBuilder.buildConstant(Reg, TypeID);
911 return true;
912 }
Tim Northover6e904302016-10-18 20:03:51 +0000913 case Intrinsic::objectsize: {
914 // If we don't know by now, we're never going to know.
915 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
916
917 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
918 return true;
919 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000920 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000921 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000922 return true;
923 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000924 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000925 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000926 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000927
928 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
929 MIRBuilder.buildStore(
930 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000931 *MF->getMachineMemOperand(
932 MachinePointerInfo::getFixedStack(*MF,
933 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000934 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
935 PtrTy.getSizeInBits() / 8, 8));
936 return true;
937 }
Aditya Nandakumare07b3b72018-08-04 01:22:12 +0000938 case Intrinsic::cttz:
939 case Intrinsic::ctlz: {
940 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
941 bool isTrailing = ID == Intrinsic::cttz;
942 unsigned Opcode = isTrailing
943 ? Cst->isZero() ? TargetOpcode::G_CTTZ
944 : TargetOpcode::G_CTTZ_ZERO_UNDEF
945 : Cst->isZero() ? TargetOpcode::G_CTLZ
946 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
947 MIRBuilder.buildInstr(Opcode)
948 .addDef(getOrCreateVReg(CI))
949 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
950 return true;
951 }
952 case Intrinsic::ctpop: {
953 MIRBuilder.buildInstr(TargetOpcode::G_CTPOP)
954 .addDef(getOrCreateVReg(CI))
955 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
956 return true;
957 }
Tim Northover91c81732016-08-19 17:17:06 +0000958 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000959 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000960}
961
Tim Northoveraa995c92017-03-09 23:36:26 +0000962bool IRTranslator::translateInlineAsm(const CallInst &CI,
963 MachineIRBuilder &MIRBuilder) {
964 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
965 if (!IA.getConstraintString().empty())
966 return false;
967
968 unsigned ExtraInfo = 0;
969 if (IA.hasSideEffects())
970 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
971 if (IA.getDialect() == InlineAsm::AD_Intel)
972 ExtraInfo |= InlineAsm::Extra_AsmDialect;
973
974 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
975 .addExternalSymbol(IA.getAsmString().c_str())
976 .addImm(ExtraInfo);
977
978 return true;
979}
980
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000981unsigned IRTranslator::packRegs(const Value &V,
982 MachineIRBuilder &MIRBuilder) {
983 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
984 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
985 LLT BigTy = getLLTForType(*V.getType(), *DL);
986
987 if (Regs.size() == 1)
988 return Regs[0];
989
990 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
991 MIRBuilder.buildUndef(Dst);
992 for (unsigned i = 0; i < Regs.size(); ++i) {
993 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
994 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
995 Dst = NewDst;
996 }
997 return Dst;
998}
999
1000void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1001 MachineIRBuilder &MIRBuilder) {
1002 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1003 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1004
1005 for (unsigned i = 0; i < Regs.size(); ++i)
1006 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1007}
1008
Tim Northoverc53606e2016-12-07 21:29:15 +00001009bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001010 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001011 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +00001012 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +00001013
Martin Storsjocc981d22018-01-30 19:50:58 +00001014 // FIXME: support Windows dllimport function calls.
1015 if (F && F->hasDLLImportStorageClass())
1016 return false;
1017
Tim Northover3babfef2017-01-19 23:59:35 +00001018 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +00001019 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +00001020
Amara Emerson913918c2018-01-02 18:56:39 +00001021 Intrinsic::ID ID = Intrinsic::not_intrinsic;
1022 if (F && F->isIntrinsic()) {
1023 ID = F->getIntrinsicID();
1024 if (TII && ID == Intrinsic::not_intrinsic)
1025 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1026 }
1027
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001028 bool IsSplitType = valueIsSplit(CI);
Amara Emerson913918c2018-01-02 18:56:39 +00001029 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001030 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1031 getLLTForType(*CI.getType(), *DL))
1032 : getOrCreateVReg(CI);
1033
Tim Northover406024a2016-08-10 21:44:01 +00001034 SmallVector<unsigned, 8> Args;
1035 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001036 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +00001037
Tim Northoverd1e951e2017-03-09 22:00:39 +00001038 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001039 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +00001040 return getOrCreateVReg(*CI.getCalledValue());
1041 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001042
1043 if (IsSplitType)
1044 unpackRegs(CI, Res, MIRBuilder);
1045 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001046 }
1047
Tim Northover406024a2016-08-10 21:44:01 +00001048 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001049
Tim Northoverc53606e2016-12-07 21:29:15 +00001050 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001051 return true;
1052
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001053 unsigned Res = 0;
1054 if (!CI.getType()->isVoidTy()) {
1055 if (IsSplitType)
1056 Res =
1057 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
1058 else
1059 Res = getOrCreateVReg(CI);
1060 }
Tim Northover5fb414d2016-07-29 22:32:36 +00001061 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +00001062 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +00001063
1064 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001065 // Some intrinsics take metadata parameters. Reject them.
1066 if (isa<MetadataAsValue>(Arg))
1067 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001068 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001069 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001070
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001071 if (IsSplitType)
1072 unpackRegs(CI, Res, MIRBuilder);
1073
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001074 // Add a MachineMemOperand if it is a target mem intrinsic.
1075 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1076 TargetLowering::IntrinsicInfo Info;
1077 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001078 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001079 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001080 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault11171332017-12-14 21:39:51 +00001081 Info.flags, Size, Info.align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001082 }
1083
Tim Northover5fb414d2016-07-29 22:32:36 +00001084 return true;
1085}
1086
Tim Northoverc53606e2016-12-07 21:29:15 +00001087bool IRTranslator::translateInvoke(const User &U,
1088 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001089 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001090 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001091
1092 const BasicBlock *ReturnBB = I.getSuccessor(0);
1093 const BasicBlock *EHPadBB = I.getSuccessor(1);
1094
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001095 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001096 const Function *Fn = dyn_cast<Function>(Callee);
1097 if (isa<InlineAsm>(Callee))
1098 return false;
1099
1100 // FIXME: support invoking patchpoint and statepoint intrinsics.
1101 if (Fn && Fn->isIntrinsic())
1102 return false;
1103
1104 // FIXME: support whatever these are.
1105 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1106 return false;
1107
1108 // FIXME: support Windows exception handling.
1109 if (!isa<LandingPadInst>(EHPadBB->front()))
1110 return false;
1111
Matthias Braund0ee66c2016-12-01 19:32:15 +00001112 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001113 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001114 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001115 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1116
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001117 unsigned Res =
1118 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001119 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001120 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001121 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001122
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001123 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001124 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1125 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001126
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001127 unpackRegs(I, Res, MIRBuilder);
1128
Matthias Braund0ee66c2016-12-01 19:32:15 +00001129 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001130 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1131
1132 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001133 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1134 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001135 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001136 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1137 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001138 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001139
1140 return true;
1141}
1142
Tim Northoverc53606e2016-12-07 21:29:15 +00001143bool IRTranslator::translateLandingPad(const User &U,
1144 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001145 const LandingPadInst &LP = cast<LandingPadInst>(U);
1146
1147 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +00001148 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001149
1150 MBB.setIsEHPad();
1151
1152 // If there aren't registers to copy the values into (e.g., during SjLj
1153 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001154 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001155 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001156 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1157 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1158 return true;
1159
1160 // If landingpad's return type is token type, we don't create DAG nodes
1161 // for its exception pointer and selector value. The extraction of exception
1162 // pointer or selector value from token type landingpads is not currently
1163 // supported.
1164 if (LP.getType()->isTokenTy())
1165 return true;
1166
1167 // Add a label to mark the beginning of the landing pad. Deletion of the
1168 // landing pad can thus be detected via the MachineModuleInfo.
1169 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001170 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001171
Daniel Sanders1351db42017-03-07 23:32:10 +00001172 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001173 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1174 MIRBuilder.buildUndef(Undef);
1175
Justin Bognera0295312017-01-25 00:16:53 +00001176 SmallVector<LLT, 2> Tys;
1177 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001178 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001179 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1180
Tim Northovera9105be2016-11-09 22:39:54 +00001181 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001182 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1183 if (!ExceptionReg)
1184 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001185
Tim Northover542d1c12017-03-07 23:04:06 +00001186 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001187 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1188 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001189
Tim Northover542d1c12017-03-07 23:04:06 +00001190 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1191 if (!SelectorReg)
1192 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001193
Tim Northover542d1c12017-03-07 23:04:06 +00001194 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001195 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1196 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001197 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001198
Tim Northovera9105be2016-11-09 22:39:54 +00001199 return true;
1200}
1201
Tim Northoverc3e3f592017-02-03 18:22:45 +00001202bool IRTranslator::translateAlloca(const User &U,
1203 MachineIRBuilder &MIRBuilder) {
1204 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001205
Amara Emersonfdd089a2018-07-26 01:25:58 +00001206 if (AI.isSwiftError())
1207 return false;
1208
Tim Northoverc3e3f592017-02-03 18:22:45 +00001209 if (AI.isStaticAlloca()) {
1210 unsigned Res = getOrCreateVReg(AI);
1211 int FI = getOrCreateFrameIndex(AI);
1212 MIRBuilder.buildFrameIndex(Res, FI);
1213 return true;
1214 }
1215
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001216 // FIXME: support stack probing for Windows.
1217 if (MF->getTarget().getTargetTriple().isOSWindows())
1218 return false;
1219
Tim Northoverc3e3f592017-02-03 18:22:45 +00001220 // Now we're in the harder dynamic case.
1221 Type *Ty = AI.getAllocatedType();
1222 unsigned Align =
1223 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1224
1225 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1226
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001227 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1228 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001229 if (MRI->getType(NumElts) != IntPtrTy) {
1230 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1231 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1232 NumElts = ExtElts;
1233 }
1234
1235 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001236 unsigned TySize =
1237 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001238 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1239
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001240 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001241 auto &TLI = *MF->getSubtarget().getTargetLowering();
1242 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1243
1244 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1245 MIRBuilder.buildCopy(SPTmp, SPReg);
1246
Tim Northoverc2f89562017-02-14 20:56:18 +00001247 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1248 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001249
1250 // Handle alignment. We have to realign if the allocation granule was smaller
1251 // than stack alignment, or the specific alloca requires more than stack
1252 // alignment.
1253 unsigned StackAlign =
1254 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1255 Align = std::max(Align, StackAlign);
1256 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1257 // Round the size of the allocation up to the stack alignment size
1258 // by add SA-1 to the size. This doesn't overflow because we're computing
1259 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001260 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1261 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1262 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001263 }
1264
Tim Northoverc2f89562017-02-14 20:56:18 +00001265 MIRBuilder.buildCopy(SPReg, AllocTmp);
1266 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001267
1268 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1269 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001270 return true;
1271}
1272
Tim Northover4a652222017-02-15 23:22:33 +00001273bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1274 // FIXME: We may need more info about the type. Because of how LLT works,
1275 // we're completely discarding the i64/double distinction here (amongst
1276 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1277 // anyway but that's not guaranteed.
1278 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1279 .addDef(getOrCreateVReg(U))
1280 .addUse(getOrCreateVReg(*U.getOperand(0)))
1281 .addImm(DL->getABITypeAlignment(U.getType()));
1282 return true;
1283}
1284
Volkan Keles04cb08c2017-03-10 19:08:28 +00001285bool IRTranslator::translateInsertElement(const User &U,
1286 MachineIRBuilder &MIRBuilder) {
1287 // If it is a <1 x Ty> vector, use the scalar as it is
1288 // not a legal vector type in LLT.
1289 if (U.getType()->getVectorNumElements() == 1) {
1290 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001291 auto &Regs = *VMap.getVRegs(U);
1292 if (Regs.empty()) {
1293 Regs.push_back(Elt);
1294 VMap.getOffsets(U)->push_back(0);
1295 } else {
1296 MIRBuilder.buildCopy(Regs[0], Elt);
1297 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001298 return true;
1299 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001300
Kristof Beyls7a713502017-04-19 06:38:37 +00001301 unsigned Res = getOrCreateVReg(U);
1302 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1303 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1304 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1305 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001306 return true;
1307}
1308
1309bool IRTranslator::translateExtractElement(const User &U,
1310 MachineIRBuilder &MIRBuilder) {
1311 // If it is a <1 x Ty> vector, use the scalar as it is
1312 // not a legal vector type in LLT.
1313 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1314 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001315 auto &Regs = *VMap.getVRegs(U);
1316 if (Regs.empty()) {
1317 Regs.push_back(Elt);
1318 VMap.getOffsets(U)->push_back(0);
1319 } else {
1320 MIRBuilder.buildCopy(Regs[0], Elt);
1321 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001322 return true;
1323 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001324 unsigned Res = getOrCreateVReg(U);
1325 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1326 unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1327 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001328 return true;
1329}
1330
Volkan Keles75bdc762017-03-21 08:44:13 +00001331bool IRTranslator::translateShuffleVector(const User &U,
1332 MachineIRBuilder &MIRBuilder) {
1333 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1334 .addDef(getOrCreateVReg(U))
1335 .addUse(getOrCreateVReg(*U.getOperand(0)))
1336 .addUse(getOrCreateVReg(*U.getOperand(1)))
1337 .addUse(getOrCreateVReg(*U.getOperand(2)));
1338 return true;
1339}
1340
Tim Northoverc53606e2016-12-07 21:29:15 +00001341bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001342 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001343
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001344 SmallVector<MachineInstr *, 4> Insts;
1345 for (auto Reg : getOrCreateVRegs(PI)) {
1346 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1347 Insts.push_back(MIB.getInstr());
1348 }
1349
1350 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001351 return true;
1352}
1353
Daniel Sanders94813992018-07-09 19:33:40 +00001354bool IRTranslator::translateAtomicCmpXchg(const User &U,
1355 MachineIRBuilder &MIRBuilder) {
1356 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1357
1358 if (I.isWeak())
1359 return false;
1360
1361 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1362 : MachineMemOperand::MONone;
1363 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1364
1365 Type *ResType = I.getType();
1366 Type *ValType = ResType->Type::getStructElementType(0);
1367
1368 auto Res = getOrCreateVRegs(I);
1369 unsigned OldValRes = Res[0];
1370 unsigned SuccessRes = Res[1];
1371 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1372 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1373 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1374
1375 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1376 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1377 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1378 Flags, DL->getTypeStoreSize(ValType),
1379 getMemOpAlignment(I), AAMDNodes(), nullptr,
1380 I.getSyncScopeID(), I.getSuccessOrdering(),
1381 I.getFailureOrdering()));
1382 return true;
1383}
1384
1385bool IRTranslator::translateAtomicRMW(const User &U,
1386 MachineIRBuilder &MIRBuilder) {
1387 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1388
1389 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1390 : MachineMemOperand::MONone;
1391 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1392
1393 Type *ResType = I.getType();
1394
1395 unsigned Res = getOrCreateVReg(I);
1396 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1397 unsigned Val = getOrCreateVReg(*I.getValOperand());
1398
1399 unsigned Opcode = 0;
1400 switch (I.getOperation()) {
1401 default:
1402 llvm_unreachable("Unknown atomicrmw op");
1403 return false;
1404 case AtomicRMWInst::Xchg:
1405 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1406 break;
1407 case AtomicRMWInst::Add:
1408 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1409 break;
1410 case AtomicRMWInst::Sub:
1411 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1412 break;
1413 case AtomicRMWInst::And:
1414 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1415 break;
1416 case AtomicRMWInst::Nand:
1417 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1418 break;
1419 case AtomicRMWInst::Or:
1420 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1421 break;
1422 case AtomicRMWInst::Xor:
1423 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1424 break;
1425 case AtomicRMWInst::Max:
1426 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1427 break;
1428 case AtomicRMWInst::Min:
1429 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1430 break;
1431 case AtomicRMWInst::UMax:
1432 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1433 break;
1434 case AtomicRMWInst::UMin:
1435 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1436 break;
1437 }
1438
1439 MIRBuilder.buildAtomicRMW(
1440 Opcode, Res, Addr, Val,
1441 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1442 Flags, DL->getTypeStoreSize(ResType),
1443 getMemOpAlignment(I), AAMDNodes(), nullptr,
1444 I.getSyncScopeID(), I.getOrdering()));
1445 return true;
1446}
1447
Tim Northover97d0cb32016-08-05 17:16:40 +00001448void IRTranslator::finishPendingPhis() {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001449 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001450 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001451 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Tim Northover97d0cb32016-08-05 17:16:40 +00001452
1453 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1454 // won't create extra control flow here, otherwise we need to find the
1455 // dominating predecessor here (or perhaps force the weirder IRTranslators
1456 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001457 SmallSet<const BasicBlock *, 4> HandledPreds;
1458
Tim Northover97d0cb32016-08-05 17:16:40 +00001459 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001460 auto IRPred = PI->getIncomingBlock(i);
1461 if (HandledPreds.count(IRPred))
1462 continue;
1463
1464 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001465 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001466 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001467 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001468 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001469 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1470 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1471 MIB.addUse(ValRegs[j]);
1472 MIB.addMBB(Pred);
1473 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001474 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001475 }
1476 }
1477}
1478
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001479bool IRTranslator::valueIsSplit(const Value &V,
1480 SmallVectorImpl<uint64_t> *Offsets) {
1481 SmallVector<LLT, 4> SplitTys;
Amara Emerson30e61402018-08-14 12:04:25 +00001482 if (Offsets && !Offsets->empty())
1483 Offsets->clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001484 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1485 return SplitTys.size() > 1;
1486}
1487
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001488bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001489 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001490 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001491#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001492 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001493#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001494 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001495 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001496 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001497}
1498
Tim Northover5ed648e2016-08-09 21:28:04 +00001499bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001500 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001501 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001502 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001503 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001504 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001505 EntryBuilder.buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001506 else if (isa<ConstantPointerNull>(C)) {
1507 // As we are trying to build a constant val of 0 into a pointer,
1508 // insert a cast to make them correct with respect to types.
1509 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1510 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1511 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1512 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1513 EntryBuilder.buildCast(Reg, ZeroReg);
1514 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Tim Northover032548f2016-09-12 12:10:41 +00001515 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001516 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1517 if (!CAZ->getType()->isVectorTy())
1518 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001519 // Return the scalar if it is a <1 x Ty> vector.
1520 if (CAZ->getNumElements() == 1)
1521 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001522 std::vector<unsigned> Ops;
1523 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1524 Constant &Elt = *CAZ->getElementValue(i);
1525 Ops.push_back(getOrCreateVReg(Elt));
1526 }
1527 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001528 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001529 // Return the scalar if it is a <1 x Ty> vector.
1530 if (CV->getNumElements() == 1)
1531 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001532 std::vector<unsigned> Ops;
1533 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1534 Constant &Elt = *CV->getElementAsConstant(i);
1535 Ops.push_back(getOrCreateVReg(Elt));
1536 }
1537 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001538 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001539 switch(CE->getOpcode()) {
1540#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001541 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001542#include "llvm/IR/Instruction.def"
1543 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001544 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001545 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001546 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1547 if (CV->getNumOperands() == 1)
1548 return translate(*CV->getOperand(0), Reg);
1549 SmallVector<unsigned, 4> Ops;
1550 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1551 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1552 }
1553 EntryBuilder.buildMerge(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001554 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1555 EntryBuilder.buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001556 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001557 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001558
Tim Northoverd403a3d2016-08-09 23:01:30 +00001559 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001560}
1561
Tim Northover0d510442016-08-11 16:21:29 +00001562void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001563 // Release the memory used by the different maps we
1564 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001565 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001566 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001567 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001568 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001569 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1570 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1571 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1572 EntryBuilder = MachineIRBuilder();
1573 CurBuilder = MachineIRBuilder();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001574}
1575
Tim Northover50db7f412016-12-07 21:17:47 +00001576bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1577 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001578 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001579 if (F.empty())
1580 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001581 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001582 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001583 EntryBuilder.setMF(*MF);
1584 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001585 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001586 TPC = &getAnalysis<TargetPassConfig>();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001587 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001588
Tim Northover14e7f732016-08-05 17:50:36 +00001589 assert(PendingPHIs.empty() && "stale PHIs");
1590
Amara Emersondf9b5292017-12-11 16:58:29 +00001591 if (!DL->isLittleEndian()) {
1592 // Currently we don't properly handle big endian code.
1593 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001594 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001595 R << "unable to translate in big endian mode";
1596 reportTranslationError(*MF, *TPC, *ORE, R);
1597 }
1598
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001599 // Release the per-function state when we return, whether we succeeded or not.
1600 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1601
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001602 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001603 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1604 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001605 EntryBuilder.setMBB(*EntryBB);
1606
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001607 // Create all blocks, in IR order, to preserve the layout.
1608 for (const BasicBlock &BB: F) {
1609 auto *&MBB = BBToMBB[&BB];
1610
1611 MBB = MF->CreateMachineBasicBlock(&BB);
1612 MF->push_back(MBB);
1613
1614 if (BB.hasAddressTaken())
1615 MBB->setHasAddressTaken();
1616 }
1617
1618 // Make our arguments/constants entry block fallthrough to the IR entry block.
1619 EntryBB->addSuccessor(&getMBB(F.front()));
1620
Tim Northover05cc4852016-12-07 21:05:38 +00001621 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001622 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001623 for (const Argument &Arg: F.args()) {
1624 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1625 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001626 VRegArgs.push_back(
1627 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001628 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001629
Amara Emersonfdd089a2018-07-26 01:25:58 +00001630 // We don't currently support translating swifterror or swiftself functions.
1631 for (auto &Arg : F.args()) {
1632 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1633 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1634 F.getSubprogram(), &F.getEntryBlock());
1635 R << "unable to lower arguments due to swifterror/swiftself: "
1636 << ore::NV("Prototype", F.getType());
1637 reportTranslationError(*MF, *TPC, *ORE, R);
1638 return false;
1639 }
1640 }
1641
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001642 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001643 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001644 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001645 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1646 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001647 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001648 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001649
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001650 auto ArgIt = F.arg_begin();
1651 for (auto &VArg : VRegArgs) {
1652 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1653 // creating redundant copies.
1654 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1655 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1656 assert(VRegs.empty() && "VRegs already populated?");
1657 VRegs.push_back(VArg);
1658 } else {
1659 unpackRegs(*ArgIt, VArg, EntryBuilder);
1660 }
1661 ArgIt++;
1662 }
1663
Amara Emerson6cdfe292018-08-01 02:17:42 +00001664 // Need to visit defs before uses when translating instructions.
1665 ReversePostOrderTraversal<const Function *> RPOT(&F);
1666 for (const BasicBlock *BB : RPOT) {
1667 MachineBasicBlock &MBB = getMBB(*BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001668 // Set the insertion point of all the following translations to
1669 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001670 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001671
Amara Emerson6cdfe292018-08-01 02:17:42 +00001672 for (const Instruction &Inst : *BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001673 if (translate(Inst))
1674 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001675
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001676 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Amara Emerson6cdfe292018-08-01 02:17:42 +00001677 Inst.getDebugLoc(), BB);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001678 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1679
1680 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1681 std::string InstStrStorage;
1682 raw_string_ostream InstStr(InstStrStorage);
1683 InstStr << Inst;
1684
1685 R << ": '" << InstStr.str() << "'";
1686 }
1687
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001688 reportTranslationError(*MF, *TPC, *ORE, R);
1689 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001690 }
1691 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001692
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001693 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001694
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001695 // Merge the argument lowering and constants block with its single
1696 // successor, the LLVM-IR entry block. We want the basic block to
1697 // be maximal.
1698 assert(EntryBB->succ_size() == 1 &&
1699 "Custom BB used for lowering should have only one successor");
1700 // Get the successor of the current entry block.
1701 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1702 assert(NewEntryBB.pred_size() == 1 &&
1703 "LLVM-IR entry block has a predecessor!?");
1704 // Move all the instruction from the current entry block to the
1705 // new entry block.
1706 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1707 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001708
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001709 // Update the live-in information for the new entry block.
1710 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1711 NewEntryBB.addLiveIn(LiveIn);
1712 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001713
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001714 // Get rid of the now empty basic block.
1715 EntryBB->removeSuccessor(&NewEntryBB);
1716 MF->remove(EntryBB);
1717 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001718
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001719 assert(&MF->front() == &NewEntryBB &&
1720 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001721
Matthias Braun90ad6832018-07-13 00:08:38 +00001722 // Initialize stack protector information.
1723 StackProtector &SP = getAnalysis<StackProtector>();
1724 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1725
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001726 return false;
1727}