LLVM 22.0.0git
IRTranslator.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements the IRTranslator class.
10//===----------------------------------------------------------------------===//
11
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/ScopeExit.h"
20#include "llvm/Analysis/Loads.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/CFG.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/Function.h"
59#include "llvm/IR/InlineAsm.h"
60#include "llvm/IR/InstrTypes.h"
63#include "llvm/IR/Intrinsics.h"
64#include "llvm/IR/IntrinsicsAMDGPU.h"
65#include "llvm/IR/LLVMContext.h"
66#include "llvm/IR/Metadata.h"
68#include "llvm/IR/Statepoint.h"
69#include "llvm/IR/Type.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
73#include "llvm/MC/MCContext.h"
74#include "llvm/Pass.h"
77#include "llvm/Support/Debug.h"
84#include <algorithm>
85#include <cassert>
86#include <cstdint>
87#include <iterator>
88#include <optional>
89#include <string>
90#include <utility>
91#include <vector>
92
93#define DEBUG_TYPE "irtranslator"
94
95using namespace llvm;
96
97static cl::opt<bool>
98 EnableCSEInIRTranslator("enable-cse-in-irtranslator",
99 cl::desc("Should enable CSE in irtranslator"),
100 cl::Optional, cl::init(false));
101char IRTranslator::ID = 0;
102
103INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
104 false, false)
110INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
112
117 MF.getProperties().setFailedISel();
118
119 // Print the function name explicitly if we don't have a debug location (which
120 // makes the diagnostic less useful) or if we're going to emit a raw error.
121 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
122 R << (" (in function: " + MF.getName() + ")").str();
123
124 if (TPC.isGlobalISelAbortEnabled())
125 report_fatal_error(Twine(R.getMsg()));
126 else
127 ORE.emit(R);
128}
129
131 : MachineFunctionPass(ID), OptLevel(optlevel) {}
132
133#ifndef NDEBUG
134namespace {
135/// Verify that every instruction created has the same DILocation as the
136/// instruction being translated.
137class DILocationVerifier : public GISelChangeObserver {
138 const Instruction *CurrInst = nullptr;
139
140public:
141 DILocationVerifier() = default;
142 ~DILocationVerifier() override = default;
143
144 const Instruction *getCurrentInst() const { return CurrInst; }
145 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
146
147 void erasingInstr(MachineInstr &MI) override {}
148 void changingInstr(MachineInstr &MI) override {}
149 void changedInstr(MachineInstr &MI) override {}
150
151 void createdInstr(MachineInstr &MI) override {
152 assert(getCurrentInst() && "Inserted instruction without a current MI");
153
154 // Only print the check message if we're actually checking it.
155#ifndef NDEBUG
156 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
157 << " was copied to " << MI);
158#endif
159 // We allow insts in the entry block to have no debug loc because
160 // they could have originated from constants, and we don't want a jumpy
161 // debug experience.
162 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
163 (MI.getParent()->isEntryBlock() && !MI.getDebugLoc()) ||
164 (MI.isDebugInstr())) &&
165 "Line info was not transferred to all instructions");
166 }
167};
168} // namespace
169#endif // ifndef NDEBUG
170
171
186
187IRTranslator::ValueToVRegInfo::VRegListT &
188IRTranslator::allocateVRegs(const Value &Val) {
189 auto VRegsIt = VMap.findVRegs(Val);
190 if (VRegsIt != VMap.vregs_end())
191 return *VRegsIt->second;
192 auto *Regs = VMap.getVRegs(Val);
193 auto *Offsets = VMap.getOffsets(Val);
194 SmallVector<LLT, 4> SplitTys;
195 computeValueLLTs(*DL, *Val.getType(), SplitTys,
196 Offsets->empty() ? Offsets : nullptr);
197 for (unsigned i = 0; i < SplitTys.size(); ++i)
198 Regs->push_back(0);
199 return *Regs;
200}
201
202ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
203 auto VRegsIt = VMap.findVRegs(Val);
204 if (VRegsIt != VMap.vregs_end())
205 return *VRegsIt->second;
206
207 if (Val.getType()->isVoidTy())
208 return *VMap.getVRegs(Val);
209
210 // Create entry for this type.
211 auto *VRegs = VMap.getVRegs(Val);
212 auto *Offsets = VMap.getOffsets(Val);
213
214 if (!Val.getType()->isTokenTy())
215 assert(Val.getType()->isSized() &&
216 "Don't know how to create an empty vreg");
217
218 SmallVector<LLT, 4> SplitTys;
219 computeValueLLTs(*DL, *Val.getType(), SplitTys,
220 Offsets->empty() ? Offsets : nullptr);
221
222 if (!isa<Constant>(Val)) {
223 for (auto Ty : SplitTys)
224 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
225 return *VRegs;
226 }
227
228 if (Val.getType()->isAggregateType()) {
229 // UndefValue, ConstantAggregateZero
230 auto &C = cast<Constant>(Val);
231 unsigned Idx = 0;
232 while (auto Elt = C.getAggregateElement(Idx++)) {
233 auto EltRegs = getOrCreateVRegs(*Elt);
234 llvm::append_range(*VRegs, EltRegs);
235 }
236 } else {
237 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
238 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
239 bool Success = translate(cast<Constant>(Val), VRegs->front());
240 if (!Success) {
241 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
242 MF->getFunction().getSubprogram(),
243 &MF->getFunction().getEntryBlock());
244 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
245 reportTranslationError(*MF, *TPC, *ORE, R);
246 return *VRegs;
247 }
248 }
249
250 return *VRegs;
251}
252
253int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
254 auto [MapEntry, Inserted] = FrameIndices.try_emplace(&AI);
255 if (!Inserted)
256 return MapEntry->second;
257
258 uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
259 uint64_t Size =
260 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
261
262 // Always allocate at least one byte.
263 Size = std::max<uint64_t>(Size, 1u);
264
265 int &FI = MapEntry->second;
266 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
267 return FI;
268}
269
270Align IRTranslator::getMemOpAlign(const Instruction &I) {
271 if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
272 return SI->getAlign();
273 if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
274 return LI->getAlign();
275 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
276 return AI->getAlign();
277 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
278 return AI->getAlign();
279
280 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
281 R << "unable to translate memop: " << ore::NV("Opcode", &I);
282 reportTranslationError(*MF, *TPC, *ORE, R);
283 return Align(1);
284}
285
286MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
287 MachineBasicBlock *MBB = FuncInfo.getMBB(&BB);
288 assert(MBB && "BasicBlock was not encountered before");
289 return *MBB;
290}
291
292void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
293 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
294 MachinePreds[Edge].push_back(NewPred);
295}
296
297static bool containsBF16Type(const User &U) {
298 // BF16 cannot currently be represented by LLT, to avoid miscompiles we
299 // prevent any instructions using them. FIXME: This can be removed once LLT
300 // supports bfloat.
301 return U.getType()->getScalarType()->isBFloatTy() ||
302 any_of(U.operands(), [](Value *V) {
303 return V->getType()->getScalarType()->isBFloatTy();
304 });
305}
306
307bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
308 MachineIRBuilder &MIRBuilder) {
309 if (containsBF16Type(U))
310 return false;
311
312 // Get or create a virtual register for each value.
313 // Unless the value is a Constant => loadimm cst?
314 // or inline constant each time?
315 // Creation of a virtual register needs to have a size.
316 Register Op0 = getOrCreateVReg(*U.getOperand(0));
317 Register Op1 = getOrCreateVReg(*U.getOperand(1));
318 Register Res = getOrCreateVReg(U);
319 uint32_t Flags = 0;
320 if (isa<Instruction>(U)) {
321 const Instruction &I = cast<Instruction>(U);
323 }
324
325 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
326 return true;
327}
328
329bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U,
330 MachineIRBuilder &MIRBuilder) {
331 if (containsBF16Type(U))
332 return false;
333
334 Register Op0 = getOrCreateVReg(*U.getOperand(0));
335 Register Res = getOrCreateVReg(U);
336 uint32_t Flags = 0;
337 if (isa<Instruction>(U)) {
338 const Instruction &I = cast<Instruction>(U);
340 }
341 MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
342 return true;
343}
344
345bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
346 return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
347}
348
349bool IRTranslator::translateCompare(const User &U,
350 MachineIRBuilder &MIRBuilder) {
351 if (containsBF16Type(U))
352 return false;
353
354 auto *CI = cast<CmpInst>(&U);
355 Register Op0 = getOrCreateVReg(*U.getOperand(0));
356 Register Op1 = getOrCreateVReg(*U.getOperand(1));
357 Register Res = getOrCreateVReg(U);
358 CmpInst::Predicate Pred = CI->getPredicate();
360 if (CmpInst::isIntPredicate(Pred))
361 MIRBuilder.buildICmp(Pred, Res, Op0, Op1, Flags);
362 else if (Pred == CmpInst::FCMP_FALSE)
363 MIRBuilder.buildCopy(
364 Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
365 else if (Pred == CmpInst::FCMP_TRUE)
366 MIRBuilder.buildCopy(
367 Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
368 else
369 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags);
370
371 return true;
372}
373
374bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
375 const ReturnInst &RI = cast<ReturnInst>(U);
376 const Value *Ret = RI.getReturnValue();
377 if (Ret && DL->getTypeStoreSize(Ret->getType()).isZero())
378 Ret = nullptr;
379
380 ArrayRef<Register> VRegs;
381 if (Ret)
382 VRegs = getOrCreateVRegs(*Ret);
383
384 Register SwiftErrorVReg = 0;
385 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
386 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
387 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
388 }
389
390 // The target may mess up with the insertion point, but
391 // this is not important as a return is the last instruction
392 // of the block anyway.
393 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
394}
395
396void IRTranslator::emitBranchForMergedCondition(
398 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
399 BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
400 // If the leaf of the tree is a comparison, merge the condition into
401 // the caseblock.
402 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
403 CmpInst::Predicate Condition;
404 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
405 Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
406 } else {
407 const FCmpInst *FC = cast<FCmpInst>(Cond);
408 Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
409 }
410
411 SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
412 BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
413 CurBuilder->getDebugLoc(), TProb, FProb);
414 SL->SwitchCases.push_back(CB);
415 return;
416 }
417
418 // Create a CaseBlock record representing this branch.
420 SwitchCG::CaseBlock CB(
421 Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
422 nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
423 SL->SwitchCases.push_back(CB);
424}
425
426static bool isValInBlock(const Value *V, const BasicBlock *BB) {
427 if (const Instruction *I = dyn_cast<Instruction>(V))
428 return I->getParent() == BB;
429 return true;
430}
431
432void IRTranslator::findMergedConditions(
434 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
436 BranchProbability FProb, bool InvertCond) {
437 using namespace PatternMatch;
438 assert((Opc == Instruction::And || Opc == Instruction::Or) &&
439 "Expected Opc to be AND/OR");
440 // Skip over not part of the tree and remember to invert op and operands at
441 // next level.
442 Value *NotCond;
443 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
444 isValInBlock(NotCond, CurBB->getBasicBlock())) {
445 findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
446 !InvertCond);
447 return;
448 }
449
451 const Value *BOpOp0, *BOpOp1;
452 // Compute the effective opcode for Cond, taking into account whether it needs
453 // to be inverted, e.g.
454 // and (not (or A, B)), C
455 // gets lowered as
456 // and (and (not A, not B), C)
458 if (BOp) {
459 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
460 ? Instruction::And
461 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
462 ? Instruction::Or
464 if (InvertCond) {
465 if (BOpc == Instruction::And)
466 BOpc = Instruction::Or;
467 else if (BOpc == Instruction::Or)
468 BOpc = Instruction::And;
469 }
470 }
471
472 // If this node is not part of the or/and tree, emit it as a branch.
473 // Note that all nodes in the tree should have same opcode.
474 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
475 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
476 !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
477 !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
478 emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
479 InvertCond);
480 return;
481 }
482
483 // Create TmpBB after CurBB.
484 MachineFunction::iterator BBI(CurBB);
485 MachineBasicBlock *TmpBB =
486 MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
487 CurBB->getParent()->insert(++BBI, TmpBB);
488
489 if (Opc == Instruction::Or) {
490 // Codegen X | Y as:
491 // BB1:
492 // jmp_if_X TBB
493 // jmp TmpBB
494 // TmpBB:
495 // jmp_if_Y TBB
496 // jmp FBB
497 //
498
499 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
500 // The requirement is that
501 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
502 // = TrueProb for original BB.
503 // Assuming the original probabilities are A and B, one choice is to set
504 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
505 // A/(1+B) and 2B/(1+B). This choice assumes that
506 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
507 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
508 // TmpBB, but the math is more complicated.
509
510 auto NewTrueProb = TProb / 2;
511 auto NewFalseProb = TProb / 2 + FProb;
512 // Emit the LHS condition.
513 findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
514 NewFalseProb, InvertCond);
515
516 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
517 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
519 // Emit the RHS condition into TmpBB.
520 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
521 Probs[1], InvertCond);
522 } else {
523 assert(Opc == Instruction::And && "Unknown merge op!");
524 // Codegen X & Y as:
525 // BB1:
526 // jmp_if_X TmpBB
527 // jmp FBB
528 // TmpBB:
529 // jmp_if_Y TBB
530 // jmp FBB
531 //
532 // This requires creation of TmpBB after CurBB.
533
534 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
535 // The requirement is that
536 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
537 // = FalseProb for original BB.
538 // Assuming the original probabilities are A and B, one choice is to set
539 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
540 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
541 // TrueProb for BB1 * FalseProb for TmpBB.
542
543 auto NewTrueProb = TProb + FProb / 2;
544 auto NewFalseProb = FProb / 2;
545 // Emit the LHS condition.
546 findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
547 NewFalseProb, InvertCond);
548
549 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
550 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
552 // Emit the RHS condition into TmpBB.
553 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
554 Probs[1], InvertCond);
555 }
556}
557
558bool IRTranslator::shouldEmitAsBranches(
559 const std::vector<SwitchCG::CaseBlock> &Cases) {
560 // For multiple cases, it's better to emit as branches.
561 if (Cases.size() != 2)
562 return true;
563
564 // If this is two comparisons of the same values or'd or and'd together, they
565 // will get folded into a single comparison, so don't emit two blocks.
566 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
567 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
568 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
569 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
570 return false;
571 }
572
573 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
574 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
575 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
576 Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
577 isa<Constant>(Cases[0].CmpRHS) &&
578 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
579 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
580 Cases[0].TrueBB == Cases[1].ThisBB)
581 return false;
582 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
583 Cases[0].FalseBB == Cases[1].ThisBB)
584 return false;
585 }
586
587 return true;
588}
589
590bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
591 const BranchInst &BrInst = cast<BranchInst>(U);
592 auto &CurMBB = MIRBuilder.getMBB();
593 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
594
595 if (BrInst.isUnconditional()) {
596 // If the unconditional target is the layout successor, fallthrough.
597 if (OptLevel == CodeGenOptLevel::None ||
598 !CurMBB.isLayoutSuccessor(Succ0MBB))
599 MIRBuilder.buildBr(*Succ0MBB);
600
601 // Link successors.
602 for (const BasicBlock *Succ : successors(&BrInst))
603 CurMBB.addSuccessor(&getMBB(*Succ));
604 return true;
605 }
606
607 // If this condition is one of the special cases we handle, do special stuff
608 // now.
609 const Value *CondVal = BrInst.getCondition();
610 MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
611
612 // If this is a series of conditions that are or'd or and'd together, emit
613 // this as a sequence of branches instead of setcc's with and/or operations.
614 // As long as jumps are not expensive (exceptions for multi-use logic ops,
615 // unpredictable branches, and vector extracts because those jumps are likely
616 // expensive for any target), this should improve performance.
617 // For example, instead of something like:
618 // cmp A, B
619 // C = seteq
620 // cmp D, E
621 // F = setle
622 // or C, F
623 // jnz foo
624 // Emit:
625 // cmp A, B
626 // je foo
627 // cmp D, E
628 // jle foo
629 using namespace PatternMatch;
630 const Instruction *CondI = dyn_cast<Instruction>(CondVal);
631 if (!TLI->isJumpExpensive() && CondI && CondI->hasOneUse() &&
632 !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
634 Value *Vec;
635 const Value *BOp0, *BOp1;
636 if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
637 Opcode = Instruction::And;
638 else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
639 Opcode = Instruction::Or;
640
641 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
642 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
643 findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
644 getEdgeProbability(&CurMBB, Succ0MBB),
645 getEdgeProbability(&CurMBB, Succ1MBB),
646 /*InvertCond=*/false);
647 assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
648
649 // Allow some cases to be rejected.
650 if (shouldEmitAsBranches(SL->SwitchCases)) {
651 // Emit the branch for this block.
652 emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
653 SL->SwitchCases.erase(SL->SwitchCases.begin());
654 return true;
655 }
656
657 // Okay, we decided not to do this, remove any inserted MBB's and clear
658 // SwitchCases.
659 for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
660 MF->erase(SL->SwitchCases[I].ThisBB);
661
662 SL->SwitchCases.clear();
663 }
664 }
665
666 // Create a CaseBlock record representing this branch.
667 SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
668 ConstantInt::getTrue(MF->getFunction().getContext()),
669 nullptr, Succ0MBB, Succ1MBB, &CurMBB,
670 CurBuilder->getDebugLoc());
671
672 // Use emitSwitchCase to actually insert the fast branch sequence for this
673 // cond branch.
674 emitSwitchCase(CB, &CurMBB, *CurBuilder);
675 return true;
676}
677
678void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
680 BranchProbability Prob) {
681 if (!FuncInfo.BPI) {
682 Src->addSuccessorWithoutProb(Dst);
683 return;
684 }
685 if (Prob.isUnknown())
686 Prob = getEdgeProbability(Src, Dst);
687 Src->addSuccessor(Dst, Prob);
688}
689
691IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
692 const MachineBasicBlock *Dst) const {
693 const BasicBlock *SrcBB = Src->getBasicBlock();
694 const BasicBlock *DstBB = Dst->getBasicBlock();
695 if (!FuncInfo.BPI) {
696 // If BPI is not available, set the default probability as 1 / N, where N is
697 // the number of successors.
698 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
699 return BranchProbability(1, SuccSize);
700 }
701 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
702}
703
704bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
705 using namespace SwitchCG;
706 // Extract cases from the switch.
707 const SwitchInst &SI = cast<SwitchInst>(U);
708 BranchProbabilityInfo *BPI = FuncInfo.BPI;
709 CaseClusterVector Clusters;
710 Clusters.reserve(SI.getNumCases());
711 for (const auto &I : SI.cases()) {
712 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
713 assert(Succ && "Could not find successor mbb in mapping");
714 const ConstantInt *CaseVal = I.getCaseValue();
715 BranchProbability Prob =
716 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
717 : BranchProbability(1, SI.getNumCases() + 1);
718 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
719 }
720
721 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
722
723 // Cluster adjacent cases with the same destination. We do this at all
724 // optimization levels because it's cheap to do and will make codegen faster
725 // if there are many clusters.
726 sortAndRangeify(Clusters);
727
728 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
729
730 // If there is only the default destination, jump there directly.
731 if (Clusters.empty()) {
732 SwitchMBB->addSuccessor(DefaultMBB);
733 if (DefaultMBB != SwitchMBB->getNextNode())
734 MIB.buildBr(*DefaultMBB);
735 return true;
736 }
737
738 SL->findJumpTables(Clusters, &SI, std::nullopt, DefaultMBB, nullptr, nullptr);
739 SL->findBitTestClusters(Clusters, &SI);
740
741 LLVM_DEBUG({
742 dbgs() << "Case clusters: ";
743 for (const CaseCluster &C : Clusters) {
744 if (C.Kind == CC_JumpTable)
745 dbgs() << "JT:";
746 if (C.Kind == CC_BitTests)
747 dbgs() << "BT:";
748
749 C.Low->getValue().print(dbgs(), true);
750 if (C.Low != C.High) {
751 dbgs() << '-';
752 C.High->getValue().print(dbgs(), true);
753 }
754 dbgs() << ' ';
755 }
756 dbgs() << '\n';
757 });
758
759 assert(!Clusters.empty());
760 SwitchWorkList WorkList;
761 CaseClusterIt First = Clusters.begin();
762 CaseClusterIt Last = Clusters.end() - 1;
763 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
764 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
765
766 while (!WorkList.empty()) {
767 SwitchWorkListItem W = WorkList.pop_back_val();
768
769 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
770 // For optimized builds, lower large range as a balanced binary tree.
771 if (NumClusters > 3 &&
772 MF->getTarget().getOptLevel() != CodeGenOptLevel::None &&
773 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
774 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB, MIB);
775 continue;
776 }
777
778 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
779 return false;
780 }
781 return true;
782}
783
784void IRTranslator::splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
786 Value *Cond, MachineBasicBlock *SwitchMBB,
787 MachineIRBuilder &MIB) {
788 using namespace SwitchCG;
789 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
790 "Clusters not sorted?");
791 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
792
793 auto [LastLeft, FirstRight, LeftProb, RightProb] =
794 SL->computeSplitWorkItemInfo(W);
795
796 // Use the first element on the right as pivot since we will make less-than
797 // comparisons against it.
798 CaseClusterIt PivotCluster = FirstRight;
799 assert(PivotCluster > W.FirstCluster);
800 assert(PivotCluster <= W.LastCluster);
801
802 CaseClusterIt FirstLeft = W.FirstCluster;
803 CaseClusterIt LastRight = W.LastCluster;
804
805 const ConstantInt *Pivot = PivotCluster->Low;
806
807 // New blocks will be inserted immediately after the current one.
809 ++BBI;
810
811 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
812 // we can branch to its destination directly if it's squeezed exactly in
813 // between the known lower bound and Pivot - 1.
814 MachineBasicBlock *LeftMBB;
815 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
816 FirstLeft->Low == W.GE &&
817 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
818 LeftMBB = FirstLeft->MBB;
819 } else {
820 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
821 FuncInfo.MF->insert(BBI, LeftMBB);
822 WorkList.push_back(
823 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
824 }
825
826 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
827 // single cluster, RHS.Low == Pivot, and we can branch to its destination
828 // directly if RHS.High equals the current upper bound.
829 MachineBasicBlock *RightMBB;
830 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && W.LT &&
831 (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
832 RightMBB = FirstRight->MBB;
833 } else {
834 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
835 FuncInfo.MF->insert(BBI, RightMBB);
836 WorkList.push_back(
837 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
838 }
839
840 // Create the CaseBlock record that will be used to lower the branch.
841 CaseBlock CB(ICmpInst::Predicate::ICMP_SLT, false, Cond, Pivot, nullptr,
842 LeftMBB, RightMBB, W.MBB, MIB.getDebugLoc(), LeftProb,
843 RightProb);
844
845 if (W.MBB == SwitchMBB)
846 emitSwitchCase(CB, SwitchMBB, MIB);
847 else
848 SL->SwitchCases.push_back(CB);
849}
850
851void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
853 // Emit the code for the jump table
854 assert(JT.Reg && "Should lower JT Header first!");
855 MachineIRBuilder MIB(*MBB->getParent());
856 MIB.setMBB(*MBB);
857 MIB.setDebugLoc(CurBuilder->getDebugLoc());
858
859 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
860 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
861
862 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
863 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
864}
865
866bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
868 MachineBasicBlock *HeaderBB) {
869 MachineIRBuilder MIB(*HeaderBB->getParent());
870 MIB.setMBB(*HeaderBB);
871 MIB.setDebugLoc(CurBuilder->getDebugLoc());
872
873 const Value &SValue = *JTH.SValue;
874 // Subtract the lowest switch case value from the value being switched on.
875 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
876 Register SwitchOpReg = getOrCreateVReg(SValue);
877 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
878 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
879
880 // This value may be smaller or larger than the target's pointer type, and
881 // therefore require extension or truncating.
882 auto *PtrIRTy = PointerType::getUnqual(SValue.getContext());
883 const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
884 Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
885
886 JT.Reg = Sub.getReg(0);
887
888 if (JTH.FallthroughUnreachable) {
889 if (JT.MBB != HeaderBB->getNextNode())
890 MIB.buildBr(*JT.MBB);
891 return true;
892 }
893
894 // Emit the range check for the jump table, and branch to the default block
895 // for the switch statement if the value being switched on exceeds the
896 // largest case in the switch.
897 auto Cst = getOrCreateVReg(
898 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
899 Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
900 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
901
902 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
903
904 // Avoid emitting unnecessary branches to the next block.
905 if (JT.MBB != HeaderBB->getNextNode())
906 BrCond = MIB.buildBr(*JT.MBB);
907 return true;
908}
909
910void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
911 MachineBasicBlock *SwitchBB,
912 MachineIRBuilder &MIB) {
913 Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
915 DebugLoc OldDbgLoc = MIB.getDebugLoc();
916 MIB.setDebugLoc(CB.DbgLoc);
917 MIB.setMBB(*CB.ThisBB);
918
919 if (CB.PredInfo.NoCmp) {
920 // Branch or fall through to TrueBB.
921 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
922 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
923 CB.ThisBB);
925 if (CB.TrueBB != CB.ThisBB->getNextNode())
926 MIB.buildBr(*CB.TrueBB);
927 MIB.setDebugLoc(OldDbgLoc);
928 return;
929 }
930
931 const LLT i1Ty = LLT::scalar(1);
932 // Build the compare.
933 if (!CB.CmpMHS) {
934 const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
935 // For conditional branch lowering, we might try to do something silly like
936 // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
937 // just re-use the existing condition vreg.
938 if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI && CI->isOne() &&
940 Cond = CondLHS;
941 } else {
942 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
944 Cond =
945 MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
946 else
947 Cond =
948 MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
949 }
950 } else {
952 "Can only handle SLE ranges");
953
954 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
955 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
956
957 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
958 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
959 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
960 Cond =
961 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
962 } else {
963 const LLT CmpTy = MRI->getType(CmpOpReg);
964 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
965 auto Diff = MIB.buildConstant(CmpTy, High - Low);
966 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
967 }
968 }
969
970 // Update successor info
971 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
972
973 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
974 CB.ThisBB);
975
976 // TrueBB and FalseBB are always different unless the incoming IR is
977 // degenerate. This only happens when running llc on weird IR.
978 if (CB.TrueBB != CB.FalseBB)
979 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
981
982 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
983 CB.ThisBB);
984
985 MIB.buildBrCond(Cond, *CB.TrueBB);
986 MIB.buildBr(*CB.FalseBB);
987 MIB.setDebugLoc(OldDbgLoc);
988}
989
990bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
991 MachineBasicBlock *SwitchMBB,
992 MachineBasicBlock *CurMBB,
993 MachineBasicBlock *DefaultMBB,
994 MachineIRBuilder &MIB,
996 BranchProbability UnhandledProbs,
998 MachineBasicBlock *Fallthrough,
999 bool FallthroughUnreachable) {
1000 using namespace SwitchCG;
1001 MachineFunction *CurMF = SwitchMBB->getParent();
1002 // FIXME: Optimize away range check based on pivot comparisons.
1003 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
1004 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
1005 BranchProbability DefaultProb = W.DefaultProb;
1006
1007 // The jump block hasn't been inserted yet; insert it here.
1008 MachineBasicBlock *JumpMBB = JT->MBB;
1009 CurMF->insert(BBI, JumpMBB);
1010
1011 // Since the jump table block is separate from the switch block, we need
1012 // to keep track of it as a machine predecessor to the default block,
1013 // otherwise we lose the phi edges.
1014 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1015 CurMBB);
1016 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1017 JumpMBB);
1018
1019 auto JumpProb = I->Prob;
1020 auto FallthroughProb = UnhandledProbs;
1021
1022 // If the default statement is a target of the jump table, we evenly
1023 // distribute the default probability to successors of CurMBB. Also
1024 // update the probability on the edge from JumpMBB to Fallthrough.
1025 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
1026 SE = JumpMBB->succ_end();
1027 SI != SE; ++SI) {
1028 if (*SI == DefaultMBB) {
1029 JumpProb += DefaultProb / 2;
1030 FallthroughProb -= DefaultProb / 2;
1031 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
1032 JumpMBB->normalizeSuccProbs();
1033 } else {
1034 // Also record edges from the jump table block to it's successors.
1035 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
1036 JumpMBB);
1037 }
1038 }
1039
1040 if (FallthroughUnreachable)
1041 JTH->FallthroughUnreachable = true;
1042
1043 if (!JTH->FallthroughUnreachable)
1044 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
1045 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
1046 CurMBB->normalizeSuccProbs();
1047
1048 // The jump table header will be inserted in our current block, do the
1049 // range check, and fall through to our fallthrough block.
1050 JTH->HeaderBB = CurMBB;
1051 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
1052
1053 // If we're in the right place, emit the jump table header right now.
1054 if (CurMBB == SwitchMBB) {
1055 if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
1056 return false;
1057 JTH->Emitted = true;
1058 }
1059 return true;
1060}
1061bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
1062 Value *Cond,
1063 MachineBasicBlock *Fallthrough,
1064 bool FallthroughUnreachable,
1065 BranchProbability UnhandledProbs,
1066 MachineBasicBlock *CurMBB,
1067 MachineIRBuilder &MIB,
1068 MachineBasicBlock *SwitchMBB) {
1069 using namespace SwitchCG;
1070 const Value *RHS, *LHS, *MHS;
1071 CmpInst::Predicate Pred;
1072 if (I->Low == I->High) {
1073 // Check Cond == I->Low.
1074 Pred = CmpInst::ICMP_EQ;
1075 LHS = Cond;
1076 RHS = I->Low;
1077 MHS = nullptr;
1078 } else {
1079 // Check I->Low <= Cond <= I->High.
1080 Pred = CmpInst::ICMP_SLE;
1081 LHS = I->Low;
1082 MHS = Cond;
1083 RHS = I->High;
1084 }
1085
1086 // If Fallthrough is unreachable, fold away the comparison.
1087 // The false probability is the sum of all unhandled cases.
1088 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
1089 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
1090
1091 emitSwitchCase(CB, SwitchMBB, MIB);
1092 return true;
1093}
1094
1095void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B,
1096 MachineBasicBlock *SwitchBB) {
1097 MachineIRBuilder &MIB = *CurBuilder;
1098 MIB.setMBB(*SwitchBB);
1099
1100 // Subtract the minimum value.
1101 Register SwitchOpReg = getOrCreateVReg(*B.SValue);
1102
1103 LLT SwitchOpTy = MRI->getType(SwitchOpReg);
1104 Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
1105 auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
1106
1107 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1108 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1109
1110 LLT MaskTy = SwitchOpTy;
1111 if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
1113 MaskTy = LLT::scalar(PtrTy.getSizeInBits());
1114 else {
1115 // Ensure that the type will fit the mask value.
1116 for (const SwitchCG::BitTestCase &Case : B.Cases) {
1117 if (!isUIntN(SwitchOpTy.getSizeInBits(), Case.Mask)) {
1118 // Switch table case range are encoded into series of masks.
1119 // Just use pointer type, it's guaranteed to fit.
1120 MaskTy = LLT::scalar(PtrTy.getSizeInBits());
1121 break;
1122 }
1123 }
1124 }
1125 Register SubReg = RangeSub.getReg(0);
1126 if (SwitchOpTy != MaskTy)
1127 SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
1128
1129 B.RegVT = getMVTForLLT(MaskTy);
1130 B.Reg = SubReg;
1131
1132 MachineBasicBlock *MBB = B.Cases[0].ThisBB;
1133
1134 if (!B.FallthroughUnreachable)
1135 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
1136 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
1137
1138 SwitchBB->normalizeSuccProbs();
1139
1140 if (!B.FallthroughUnreachable) {
1141 // Conditional branch to the default block.
1142 auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
1143 auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1),
1144 RangeSub, RangeCst);
1145 MIB.buildBrCond(RangeCmp, *B.Default);
1146 }
1147
1148 // Avoid emitting unnecessary branches to the next block.
1149 if (MBB != SwitchBB->getNextNode())
1150 MIB.buildBr(*MBB);
1151}
1152
1153void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB,
1154 MachineBasicBlock *NextMBB,
1155 BranchProbability BranchProbToNext,
1157 MachineBasicBlock *SwitchBB) {
1158 MachineIRBuilder &MIB = *CurBuilder;
1159 MIB.setMBB(*SwitchBB);
1160
1161 LLT SwitchTy = getLLTForMVT(BB.RegVT);
1162 Register Cmp;
1163 unsigned PopCount = llvm::popcount(B.Mask);
1164 if (PopCount == 1) {
1165 // Testing for a single bit; just compare the shift count with what it
1166 // would need to be to shift a 1 bit in that position.
1167 auto MaskTrailingZeros =
1168 MIB.buildConstant(SwitchTy, llvm::countr_zero(B.Mask));
1169 Cmp =
1170 MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros)
1171 .getReg(0);
1172 } else if (PopCount == BB.Range) {
1173 // There is only one zero bit in the range, test for it directly.
1174 auto MaskTrailingOnes =
1175 MIB.buildConstant(SwitchTy, llvm::countr_one(B.Mask));
1176 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes)
1177 .getReg(0);
1178 } else {
1179 // Make desired shift.
1180 auto CstOne = MIB.buildConstant(SwitchTy, 1);
1181 auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
1182
1183 // Emit bit tests and jumps.
1184 auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
1185 auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
1186 auto CstZero = MIB.buildConstant(SwitchTy, 0);
1187 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero)
1188 .getReg(0);
1189 }
1190
1191 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
1192 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
1193 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
1194 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
1195 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
1196 // one as they are relative probabilities (and thus work more like weights),
1197 // and hence we need to normalize them to let the sum of them become one.
1198 SwitchBB->normalizeSuccProbs();
1199
1200 // Record the fact that the IR edge from the header to the bit test target
1201 // will go through our new block. Neeeded for PHIs to have nodes added.
1202 addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
1203 SwitchBB);
1204
1205 MIB.buildBrCond(Cmp, *B.TargetBB);
1206
1207 // Avoid emitting unnecessary branches to the next block.
1208 if (NextMBB != SwitchBB->getNextNode())
1209 MIB.buildBr(*NextMBB);
1210}
1211
1212bool IRTranslator::lowerBitTestWorkItem(
1214 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1216 BranchProbability DefaultProb, BranchProbability UnhandledProbs,
1218 bool FallthroughUnreachable) {
1219 using namespace SwitchCG;
1220 MachineFunction *CurMF = SwitchMBB->getParent();
1221 // FIXME: Optimize away range check based on pivot comparisons.
1222 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
1223 // The bit test blocks haven't been inserted yet; insert them here.
1224 for (BitTestCase &BTC : BTB->Cases)
1225 CurMF->insert(BBI, BTC.ThisBB);
1226
1227 // Fill in fields of the BitTestBlock.
1228 BTB->Parent = CurMBB;
1229 BTB->Default = Fallthrough;
1230
1231 BTB->DefaultProb = UnhandledProbs;
1232 // If the cases in bit test don't form a contiguous range, we evenly
1233 // distribute the probability on the edge to Fallthrough to two
1234 // successors of CurMBB.
1235 if (!BTB->ContiguousRange) {
1236 BTB->Prob += DefaultProb / 2;
1237 BTB->DefaultProb -= DefaultProb / 2;
1238 }
1239
1240 if (FallthroughUnreachable)
1241 BTB->FallthroughUnreachable = true;
1242
1243 // If we're in the right place, emit the bit test header right now.
1244 if (CurMBB == SwitchMBB) {
1245 emitBitTestHeader(*BTB, SwitchMBB);
1246 BTB->Emitted = true;
1247 }
1248 return true;
1249}
1250
1251bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
1252 Value *Cond,
1253 MachineBasicBlock *SwitchMBB,
1254 MachineBasicBlock *DefaultMBB,
1255 MachineIRBuilder &MIB) {
1256 using namespace SwitchCG;
1257 MachineFunction *CurMF = FuncInfo.MF;
1258 MachineBasicBlock *NextMBB = nullptr;
1260 if (++BBI != FuncInfo.MF->end())
1261 NextMBB = &*BBI;
1262
1263 if (EnableOpts) {
1264 // Here, we order cases by probability so the most likely case will be
1265 // checked first. However, two clusters can have the same probability in
1266 // which case their relative ordering is non-deterministic. So we use Low
1267 // as a tie-breaker as clusters are guaranteed to never overlap.
1268 llvm::sort(W.FirstCluster, W.LastCluster + 1,
1269 [](const CaseCluster &a, const CaseCluster &b) {
1270 return a.Prob != b.Prob
1271 ? a.Prob > b.Prob
1272 : a.Low->getValue().slt(b.Low->getValue());
1273 });
1274
1275 // Rearrange the case blocks so that the last one falls through if possible
1276 // without changing the order of probabilities.
1277 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
1278 --I;
1279 if (I->Prob > W.LastCluster->Prob)
1280 break;
1281 if (I->Kind == CC_Range && I->MBB == NextMBB) {
1282 std::swap(*I, *W.LastCluster);
1283 break;
1284 }
1285 }
1286 }
1287
1288 // Compute total probability.
1289 BranchProbability DefaultProb = W.DefaultProb;
1290 BranchProbability UnhandledProbs = DefaultProb;
1291 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
1292 UnhandledProbs += I->Prob;
1293
1294 MachineBasicBlock *CurMBB = W.MBB;
1295 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
1296 bool FallthroughUnreachable = false;
1297 MachineBasicBlock *Fallthrough;
1298 if (I == W.LastCluster) {
1299 // For the last cluster, fall through to the default destination.
1300 Fallthrough = DefaultMBB;
1301 FallthroughUnreachable = isa<UnreachableInst>(
1302 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
1303 } else {
1304 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
1305 CurMF->insert(BBI, Fallthrough);
1306 }
1307 UnhandledProbs -= I->Prob;
1308
1309 switch (I->Kind) {
1310 case CC_BitTests: {
1311 if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1312 DefaultProb, UnhandledProbs, I, Fallthrough,
1313 FallthroughUnreachable)) {
1314 LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
1315 return false;
1316 }
1317 break;
1318 }
1319
1320 case CC_JumpTable: {
1321 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1322 UnhandledProbs, I, Fallthrough,
1323 FallthroughUnreachable)) {
1324 LLVM_DEBUG(dbgs() << "Failed to lower jump table");
1325 return false;
1326 }
1327 break;
1328 }
1329 case CC_Range: {
1330 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
1331 FallthroughUnreachable, UnhandledProbs,
1332 CurMBB, MIB, SwitchMBB)) {
1333 LLVM_DEBUG(dbgs() << "Failed to lower switch range");
1334 return false;
1335 }
1336 break;
1337 }
1338 }
1339 CurMBB = Fallthrough;
1340 }
1341
1342 return true;
1343}
1344
1345bool IRTranslator::translateIndirectBr(const User &U,
1346 MachineIRBuilder &MIRBuilder) {
1347 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
1348
1349 const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
1350 MIRBuilder.buildBrIndirect(Tgt);
1351
1352 // Link successors.
1353 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
1354 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
1355 for (const BasicBlock *Succ : successors(&BrInst)) {
1356 // It's legal for indirectbr instructions to have duplicate blocks in the
1357 // destination list. We don't allow this in MIR. Skip anything that's
1358 // already a successor.
1359 if (!AddedSuccessors.insert(Succ).second)
1360 continue;
1361 CurBB.addSuccessor(&getMBB(*Succ));
1362 }
1363
1364 return true;
1365}
1366
1367static bool isSwiftError(const Value *V) {
1368 if (auto Arg = dyn_cast<Argument>(V))
1369 return Arg->hasSwiftErrorAttr();
1370 if (auto AI = dyn_cast<AllocaInst>(V))
1371 return AI->isSwiftError();
1372 return false;
1373}
1374
1375bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
1376 const LoadInst &LI = cast<LoadInst>(U);
1377 TypeSize StoreSize = DL->getTypeStoreSize(LI.getType());
1378 if (StoreSize.isZero())
1379 return true;
1380
1381 ArrayRef<Register> Regs = getOrCreateVRegs(LI);
1382 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
1383 Register Base = getOrCreateVReg(*LI.getPointerOperand());
1384 AAMDNodes AAInfo = LI.getAAMetadata();
1385
1386 const Value *Ptr = LI.getPointerOperand();
1387 Type *OffsetIRTy = DL->getIndexType(Ptr->getType());
1388 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1389
1390 if (CLI->supportSwiftError() && isSwiftError(Ptr)) {
1391 assert(Regs.size() == 1 && "swifterror should be single pointer");
1392 Register VReg =
1393 SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), Ptr);
1394 MIRBuilder.buildCopy(Regs[0], VReg);
1395 return true;
1396 }
1397
1399 TLI->getLoadMemOperandFlags(LI, *DL, AC, LibInfo);
1400 if (AA && !(Flags & MachineMemOperand::MOInvariant)) {
1401 if (AA->pointsToConstantMemory(
1402 MemoryLocation(Ptr, LocationSize::precise(StoreSize), AAInfo))) {
1404 }
1405 }
1406
1407 const MDNode *Ranges =
1408 Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
1409 for (unsigned i = 0; i < Regs.size(); ++i) {
1410 Register Addr;
1411 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i] / 8);
1412
1413 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
1414 Align BaseAlign = getMemOpAlign(LI);
1415 auto MMO = MF->getMachineMemOperand(
1416 Ptr, Flags, MRI->getType(Regs[i]),
1417 commonAlignment(BaseAlign, Offsets[i] / 8), AAInfo, Ranges,
1418 LI.getSyncScopeID(), LI.getOrdering());
1419 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
1420 }
1421
1422 return true;
1423}
1424
1425bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
1426 const StoreInst &SI = cast<StoreInst>(U);
1427 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()).isZero())
1428 return true;
1429
1430 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
1431 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
1432 Register Base = getOrCreateVReg(*SI.getPointerOperand());
1433
1434 Type *OffsetIRTy = DL->getIndexType(SI.getPointerOperandType());
1435 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1436
1437 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
1438 assert(Vals.size() == 1 && "swifterror should be single pointer");
1439
1440 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
1441 SI.getPointerOperand());
1442 MIRBuilder.buildCopy(VReg, Vals[0]);
1443 return true;
1444 }
1445
1446 MachineMemOperand::Flags Flags = TLI->getStoreMemOperandFlags(SI, *DL);
1447
1448 for (unsigned i = 0; i < Vals.size(); ++i) {
1449 Register Addr;
1450 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i] / 8);
1451
1452 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
1453 Align BaseAlign = getMemOpAlign(SI);
1454 auto MMO = MF->getMachineMemOperand(
1455 Ptr, Flags, MRI->getType(Vals[i]),
1456 commonAlignment(BaseAlign, Offsets[i] / 8), SI.getAAMetadata(), nullptr,
1457 SI.getSyncScopeID(), SI.getOrdering());
1458 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
1459 }
1460 return true;
1461}
1462
1464 const Value *Src = U.getOperand(0);
1465 Type *Int32Ty = Type::getInt32Ty(U.getContext());
1466
1467 // getIndexedOffsetInType is designed for GEPs, so the first index is the
1468 // usual array element rather than looking into the actual aggregate.
1470 Indices.push_back(ConstantInt::get(Int32Ty, 0));
1471
1472 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
1473 for (auto Idx : EVI->indices())
1474 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1475 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
1476 for (auto Idx : IVI->indices())
1477 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1478 } else {
1479 llvm::append_range(Indices, drop_begin(U.operands()));
1480 }
1481
1482 return 8 * static_cast<uint64_t>(
1483 DL.getIndexedOffsetInType(Src->getType(), Indices));
1484}
1485
1486bool IRTranslator::translateExtractValue(const User &U,
1487 MachineIRBuilder &MIRBuilder) {
1488 const Value *Src = U.getOperand(0);
1489 uint64_t Offset = getOffsetFromIndices(U, *DL);
1490 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1491 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
1492 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
1493 auto &DstRegs = allocateVRegs(U);
1494
1495 for (unsigned i = 0; i < DstRegs.size(); ++i)
1496 DstRegs[i] = SrcRegs[Idx++];
1497
1498 return true;
1499}
1500
1501bool IRTranslator::translateInsertValue(const User &U,
1502 MachineIRBuilder &MIRBuilder) {
1503 const Value *Src = U.getOperand(0);
1504 uint64_t Offset = getOffsetFromIndices(U, *DL);
1505 auto &DstRegs = allocateVRegs(U);
1506 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
1507 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1508 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
1509 auto *InsertedIt = InsertedRegs.begin();
1510
1511 for (unsigned i = 0; i < DstRegs.size(); ++i) {
1512 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
1513 DstRegs[i] = *InsertedIt++;
1514 else
1515 DstRegs[i] = SrcRegs[i];
1516 }
1517
1518 return true;
1519}
1520
1521bool IRTranslator::translateSelect(const User &U,
1522 MachineIRBuilder &MIRBuilder) {
1523 Register Tst = getOrCreateVReg(*U.getOperand(0));
1524 ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1525 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1526 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1527
1528 uint32_t Flags = 0;
1529 if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
1531
1532 for (unsigned i = 0; i < ResRegs.size(); ++i) {
1533 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
1534 }
1535
1536 return true;
1537}
1538
1539bool IRTranslator::translateCopy(const User &U, const Value &V,
1540 MachineIRBuilder &MIRBuilder) {
1541 Register Src = getOrCreateVReg(V);
1542 auto &Regs = *VMap.getVRegs(U);
1543 if (Regs.empty()) {
1544 Regs.push_back(Src);
1545 VMap.getOffsets(U)->push_back(0);
1546 } else {
1547 // If we already assigned a vreg for this instruction, we can't change that.
1548 // Emit a copy to satisfy the users we already emitted.
1549 MIRBuilder.buildCopy(Regs[0], Src);
1550 }
1551 return true;
1552}
1553
1554bool IRTranslator::translateBitCast(const User &U,
1555 MachineIRBuilder &MIRBuilder) {
1556 // If we're bitcasting to the source type, we can reuse the source vreg.
1557 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1558 getLLTForType(*U.getType(), *DL)) {
1559 // If the source is a ConstantInt then it was probably created by
1560 // ConstantHoisting and we should leave it alone.
1561 if (isa<ConstantInt>(U.getOperand(0)))
1562 return translateCast(TargetOpcode::G_CONSTANT_FOLD_BARRIER, U,
1563 MIRBuilder);
1564 return translateCopy(U, *U.getOperand(0), MIRBuilder);
1565 }
1566
1567 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1568}
1569
1570bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1571 MachineIRBuilder &MIRBuilder) {
1572 if (containsBF16Type(U))
1573 return false;
1574
1575 uint32_t Flags = 0;
1576 if (const Instruction *I = dyn_cast<Instruction>(&U))
1578
1579 Register Op = getOrCreateVReg(*U.getOperand(0));
1580 Register Res = getOrCreateVReg(U);
1581 MIRBuilder.buildInstr(Opcode, {Res}, {Op}, Flags);
1582 return true;
1583}
1584
1585bool IRTranslator::translateGetElementPtr(const User &U,
1586 MachineIRBuilder &MIRBuilder) {
1587 Value &Op0 = *U.getOperand(0);
1588 Register BaseReg = getOrCreateVReg(Op0);
1589 Type *PtrIRTy = Op0.getType();
1590 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1591 Type *OffsetIRTy = DL->getIndexType(PtrIRTy);
1592 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1593
1594 uint32_t PtrAddFlags = 0;
1595 // Each PtrAdd generated to implement the GEP inherits its nuw, nusw, inbounds
1596 // flags.
1597 if (const Instruction *I = dyn_cast<Instruction>(&U))
1599
1600 auto PtrAddFlagsWithConst = [&](int64_t Offset) {
1601 // For nusw/inbounds GEP with an offset that is nonnegative when interpreted
1602 // as signed, assume there is no unsigned overflow.
1603 if (Offset >= 0 && (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap))
1604 return PtrAddFlags | MachineInstr::MIFlag::NoUWrap;
1605 return PtrAddFlags;
1606 };
1607
1608 // Normalize Vector GEP - all scalar operands should be converted to the
1609 // splat vector.
1610 unsigned VectorWidth = 0;
1611
1612 // True if we should use a splat vector; using VectorWidth alone is not
1613 // sufficient.
1614 bool WantSplatVector = false;
1615 if (auto *VT = dyn_cast<VectorType>(U.getType())) {
1616 VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
1617 // We don't produce 1 x N vectors; those are treated as scalars.
1618 WantSplatVector = VectorWidth > 1;
1619 }
1620
1621 // We might need to splat the base pointer into a vector if the offsets
1622 // are vectors.
1623 if (WantSplatVector && !PtrTy.isVector()) {
1624 BaseReg = MIRBuilder
1625 .buildSplatBuildVector(LLT::fixed_vector(VectorWidth, PtrTy),
1626 BaseReg)
1627 .getReg(0);
1628 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
1629 PtrTy = getLLTForType(*PtrIRTy, *DL);
1630 OffsetIRTy = DL->getIndexType(PtrIRTy);
1631 OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1632 }
1633
1634 int64_t Offset = 0;
1635 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1636 GTI != E; ++GTI) {
1637 const Value *Idx = GTI.getOperand();
1638 if (StructType *StTy = GTI.getStructTypeOrNull()) {
1639 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1640 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1641 continue;
1642 } else {
1643 uint64_t ElementSize = GTI.getSequentialElementStride(*DL);
1644
1645 // If this is a scalar constant or a splat vector of constants,
1646 // handle it quickly.
1647 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1648 if (std::optional<int64_t> Val = CI->getValue().trySExtValue()) {
1649 Offset += ElementSize * *Val;
1650 continue;
1651 }
1652 }
1653
1654 if (Offset != 0) {
1655 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1656 BaseReg = MIRBuilder
1657 .buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0),
1658 PtrAddFlagsWithConst(Offset))
1659 .getReg(0);
1660 Offset = 0;
1661 }
1662
1663 Register IdxReg = getOrCreateVReg(*Idx);
1664 LLT IdxTy = MRI->getType(IdxReg);
1665 if (IdxTy != OffsetTy) {
1666 if (!IdxTy.isVector() && WantSplatVector) {
1667 IdxReg = MIRBuilder
1669 IdxReg)
1670 .getReg(0);
1671 }
1672
1673 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1674 }
1675
1676 // N = N + Idx * ElementSize;
1677 // Avoid doing it for ElementSize of 1.
1678 Register GepOffsetReg;
1679 if (ElementSize != 1) {
1680 auto ElementSizeMIB = MIRBuilder.buildConstant(
1681 getLLTForType(*OffsetIRTy, *DL), ElementSize);
1682
1683 // The multiplication is NUW if the GEP is NUW and NSW if the GEP is
1684 // NUSW.
1685 uint32_t ScaleFlags = PtrAddFlags & MachineInstr::MIFlag::NoUWrap;
1686 if (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap)
1687 ScaleFlags |= MachineInstr::MIFlag::NoSWrap;
1688
1689 GepOffsetReg =
1690 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB, ScaleFlags)
1691 .getReg(0);
1692 } else {
1693 GepOffsetReg = IdxReg;
1694 }
1695
1696 BaseReg =
1697 MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg, PtrAddFlags)
1698 .getReg(0);
1699 }
1700 }
1701
1702 if (Offset != 0) {
1703 auto OffsetMIB =
1704 MIRBuilder.buildConstant(OffsetTy, Offset);
1705
1706 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0),
1707 PtrAddFlagsWithConst(Offset));
1708 return true;
1709 }
1710
1711 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1712 return true;
1713}
1714
1715bool IRTranslator::translateMemFunc(const CallInst &CI,
1716 MachineIRBuilder &MIRBuilder,
1717 unsigned Opcode) {
1718 const Value *SrcPtr = CI.getArgOperand(1);
1719 // If the source is undef, then just emit a nop.
1720 if (isa<UndefValue>(SrcPtr))
1721 return true;
1722
1724
1725 unsigned MinPtrSize = UINT_MAX;
1726 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
1727 Register SrcReg = getOrCreateVReg(**AI);
1728 LLT SrcTy = MRI->getType(SrcReg);
1729 if (SrcTy.isPointer())
1730 MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
1731 SrcRegs.push_back(SrcReg);
1732 }
1733
1734 LLT SizeTy = LLT::scalar(MinPtrSize);
1735
1736 // The size operand should be the minimum of the pointer sizes.
1737 Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
1738 if (MRI->getType(SizeOpReg) != SizeTy)
1739 SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
1740
1741 auto ICall = MIRBuilder.buildInstr(Opcode);
1742 for (Register SrcReg : SrcRegs)
1743 ICall.addUse(SrcReg);
1744
1745 Align DstAlign;
1746 Align SrcAlign;
1747 unsigned IsVol =
1748 cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1))->getZExtValue();
1749
1750 ConstantInt *CopySize = nullptr;
1751
1752 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1753 DstAlign = MCI->getDestAlign().valueOrOne();
1754 SrcAlign = MCI->getSourceAlign().valueOrOne();
1755 CopySize = dyn_cast<ConstantInt>(MCI->getArgOperand(2));
1756 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1757 DstAlign = MMI->getDestAlign().valueOrOne();
1758 SrcAlign = MMI->getSourceAlign().valueOrOne();
1759 CopySize = dyn_cast<ConstantInt>(MMI->getArgOperand(2));
1760 } else {
1761 auto *MSI = cast<MemSetInst>(&CI);
1762 DstAlign = MSI->getDestAlign().valueOrOne();
1763 }
1764
1765 if (Opcode != TargetOpcode::G_MEMCPY_INLINE) {
1766 // We need to propagate the tail call flag from the IR inst as an argument.
1767 // Otherwise, we have to pessimize and assume later that we cannot tail call
1768 // any memory intrinsics.
1769 ICall.addImm(CI.isTailCall() ? 1 : 0);
1770 }
1771
1772 // Create mem operands to store the alignment and volatile info.
1775 if (IsVol) {
1776 LoadFlags |= MachineMemOperand::MOVolatile;
1777 StoreFlags |= MachineMemOperand::MOVolatile;
1778 }
1779
1780 AAMDNodes AAInfo = CI.getAAMetadata();
1781 if (AA && CopySize &&
1782 AA->pointsToConstantMemory(MemoryLocation(
1783 SrcPtr, LocationSize::precise(CopySize->getZExtValue()), AAInfo))) {
1784 LoadFlags |= MachineMemOperand::MOInvariant;
1785
1786 // FIXME: pointsToConstantMemory probably does not imply dereferenceable,
1787 // but the previous usage implied it did. Probably should check
1788 // isDereferenceableAndAlignedPointer.
1790 }
1791
1792 ICall.addMemOperand(
1793 MF->getMachineMemOperand(MachinePointerInfo(CI.getArgOperand(0)),
1794 StoreFlags, 1, DstAlign, AAInfo));
1795 if (Opcode != TargetOpcode::G_MEMSET)
1796 ICall.addMemOperand(MF->getMachineMemOperand(
1797 MachinePointerInfo(SrcPtr), LoadFlags, 1, SrcAlign, AAInfo));
1798
1799 return true;
1800}
1801
1802bool IRTranslator::translateTrap(const CallInst &CI,
1803 MachineIRBuilder &MIRBuilder,
1804 unsigned Opcode) {
1805 StringRef TrapFuncName =
1806 CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
1807 if (TrapFuncName.empty()) {
1808 if (Opcode == TargetOpcode::G_UBSANTRAP) {
1809 uint64_t Code = cast<ConstantInt>(CI.getOperand(0))->getZExtValue();
1810 MIRBuilder.buildInstr(Opcode, {}, ArrayRef<llvm::SrcOp>{Code});
1811 } else {
1812 MIRBuilder.buildInstr(Opcode);
1813 }
1814 return true;
1815 }
1816
1817 CallLowering::CallLoweringInfo Info;
1818 if (Opcode == TargetOpcode::G_UBSANTRAP)
1819 Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
1820 CI.getArgOperand(0)->getType(), 0});
1821
1822 Info.Callee = MachineOperand::CreateES(TrapFuncName.data());
1823 Info.CB = &CI;
1824 Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
1825 return CLI->lowerCall(MIRBuilder, Info);
1826}
1827
1828bool IRTranslator::translateVectorInterleave2Intrinsic(
1829 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
1830 assert(CI.getIntrinsicID() == Intrinsic::vector_interleave2 &&
1831 "This function can only be called on the interleave2 intrinsic!");
1832 // Canonicalize interleave2 to G_SHUFFLE_VECTOR (similar to SelectionDAG).
1833 Register Op0 = getOrCreateVReg(*CI.getOperand(0));
1834 Register Op1 = getOrCreateVReg(*CI.getOperand(1));
1835 Register Res = getOrCreateVReg(CI);
1836
1837 LLT OpTy = MRI->getType(Op0);
1838 MIRBuilder.buildShuffleVector(Res, Op0, Op1,
1840
1841 return true;
1842}
1843
1844bool IRTranslator::translateVectorDeinterleave2Intrinsic(
1845 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
1846 assert(CI.getIntrinsicID() == Intrinsic::vector_deinterleave2 &&
1847 "This function can only be called on the deinterleave2 intrinsic!");
1848 // Canonicalize deinterleave2 to shuffles that extract sub-vectors (similar to
1849 // SelectionDAG).
1850 Register Op = getOrCreateVReg(*CI.getOperand(0));
1851 auto Undef = MIRBuilder.buildUndef(MRI->getType(Op));
1852 ArrayRef<Register> Res = getOrCreateVRegs(CI);
1853
1854 LLT ResTy = MRI->getType(Res[0]);
1855 MIRBuilder.buildShuffleVector(Res[0], Op, Undef,
1856 createStrideMask(0, 2, ResTy.getNumElements()));
1857 MIRBuilder.buildShuffleVector(Res[1], Op, Undef,
1858 createStrideMask(1, 2, ResTy.getNumElements()));
1859
1860 return true;
1861}
1862
1863void IRTranslator::getStackGuard(Register DstReg,
1864 MachineIRBuilder &MIRBuilder) {
1865 Value *Global = TLI->getSDagStackGuard(*MF->getFunction().getParent());
1866 if (!Global) {
1867 LLVMContext &Ctx = MIRBuilder.getContext();
1868 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
1869 MIRBuilder.buildUndef(DstReg);
1870 return;
1871 }
1872
1873 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1874 MRI->setRegClass(DstReg, TRI->getPointerRegClass());
1875 auto MIB =
1876 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1877
1878 unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
1879 LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
1880
1881 MachinePointerInfo MPInfo(Global);
1884 MachineMemOperand *MemRef = MF->getMachineMemOperand(
1885 MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
1886 MIB.setMemRefs({MemRef});
1887}
1888
1889bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1890 MachineIRBuilder &MIRBuilder) {
1891 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1892 MIRBuilder.buildInstr(
1893 Op, {ResRegs[0], ResRegs[1]},
1894 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1895
1896 return true;
1897}
1898
1899bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
1900 MachineIRBuilder &MIRBuilder) {
1901 Register Dst = getOrCreateVReg(CI);
1902 Register Src0 = getOrCreateVReg(*CI.getOperand(0));
1903 Register Src1 = getOrCreateVReg(*CI.getOperand(1));
1904 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
1905 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
1906 return true;
1907}
1908
1909unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1910 switch (ID) {
1911 default:
1912 break;
1913 case Intrinsic::acos:
1914 return TargetOpcode::G_FACOS;
1915 case Intrinsic::asin:
1916 return TargetOpcode::G_FASIN;
1917 case Intrinsic::atan:
1918 return TargetOpcode::G_FATAN;
1919 case Intrinsic::atan2:
1920 return TargetOpcode::G_FATAN2;
1921 case Intrinsic::bswap:
1922 return TargetOpcode::G_BSWAP;
1923 case Intrinsic::bitreverse:
1924 return TargetOpcode::G_BITREVERSE;
1925 case Intrinsic::fshl:
1926 return TargetOpcode::G_FSHL;
1927 case Intrinsic::fshr:
1928 return TargetOpcode::G_FSHR;
1929 case Intrinsic::ceil:
1930 return TargetOpcode::G_FCEIL;
1931 case Intrinsic::cos:
1932 return TargetOpcode::G_FCOS;
1933 case Intrinsic::cosh:
1934 return TargetOpcode::G_FCOSH;
1935 case Intrinsic::ctpop:
1936 return TargetOpcode::G_CTPOP;
1937 case Intrinsic::exp:
1938 return TargetOpcode::G_FEXP;
1939 case Intrinsic::exp2:
1940 return TargetOpcode::G_FEXP2;
1941 case Intrinsic::exp10:
1942 return TargetOpcode::G_FEXP10;
1943 case Intrinsic::fabs:
1944 return TargetOpcode::G_FABS;
1945 case Intrinsic::copysign:
1946 return TargetOpcode::G_FCOPYSIGN;
1947 case Intrinsic::minnum:
1948 return TargetOpcode::G_FMINNUM;
1949 case Intrinsic::maxnum:
1950 return TargetOpcode::G_FMAXNUM;
1951 case Intrinsic::minimum:
1952 return TargetOpcode::G_FMINIMUM;
1953 case Intrinsic::maximum:
1954 return TargetOpcode::G_FMAXIMUM;
1955 case Intrinsic::minimumnum:
1956 return TargetOpcode::G_FMINIMUMNUM;
1957 case Intrinsic::maximumnum:
1958 return TargetOpcode::G_FMAXIMUMNUM;
1959 case Intrinsic::canonicalize:
1960 return TargetOpcode::G_FCANONICALIZE;
1961 case Intrinsic::floor:
1962 return TargetOpcode::G_FFLOOR;
1963 case Intrinsic::fma:
1964 return TargetOpcode::G_FMA;
1965 case Intrinsic::log:
1966 return TargetOpcode::G_FLOG;
1967 case Intrinsic::log2:
1968 return TargetOpcode::G_FLOG2;
1969 case Intrinsic::log10:
1970 return TargetOpcode::G_FLOG10;
1971 case Intrinsic::ldexp:
1972 return TargetOpcode::G_FLDEXP;
1973 case Intrinsic::nearbyint:
1974 return TargetOpcode::G_FNEARBYINT;
1975 case Intrinsic::pow:
1976 return TargetOpcode::G_FPOW;
1977 case Intrinsic::powi:
1978 return TargetOpcode::G_FPOWI;
1979 case Intrinsic::rint:
1980 return TargetOpcode::G_FRINT;
1981 case Intrinsic::round:
1982 return TargetOpcode::G_INTRINSIC_ROUND;
1983 case Intrinsic::roundeven:
1984 return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
1985 case Intrinsic::sin:
1986 return TargetOpcode::G_FSIN;
1987 case Intrinsic::sinh:
1988 return TargetOpcode::G_FSINH;
1989 case Intrinsic::sqrt:
1990 return TargetOpcode::G_FSQRT;
1991 case Intrinsic::tan:
1992 return TargetOpcode::G_FTAN;
1993 case Intrinsic::tanh:
1994 return TargetOpcode::G_FTANH;
1995 case Intrinsic::trunc:
1996 return TargetOpcode::G_INTRINSIC_TRUNC;
1997 case Intrinsic::readcyclecounter:
1998 return TargetOpcode::G_READCYCLECOUNTER;
1999 case Intrinsic::readsteadycounter:
2000 return TargetOpcode::G_READSTEADYCOUNTER;
2001 case Intrinsic::ptrmask:
2002 return TargetOpcode::G_PTRMASK;
2003 case Intrinsic::lrint:
2004 return TargetOpcode::G_INTRINSIC_LRINT;
2005 case Intrinsic::llrint:
2006 return TargetOpcode::G_INTRINSIC_LLRINT;
2007 // FADD/FMUL require checking the FMF, so are handled elsewhere.
2008 case Intrinsic::vector_reduce_fmin:
2009 return TargetOpcode::G_VECREDUCE_FMIN;
2010 case Intrinsic::vector_reduce_fmax:
2011 return TargetOpcode::G_VECREDUCE_FMAX;
2012 case Intrinsic::vector_reduce_fminimum:
2013 return TargetOpcode::G_VECREDUCE_FMINIMUM;
2014 case Intrinsic::vector_reduce_fmaximum:
2015 return TargetOpcode::G_VECREDUCE_FMAXIMUM;
2016 case Intrinsic::vector_reduce_add:
2017 return TargetOpcode::G_VECREDUCE_ADD;
2018 case Intrinsic::vector_reduce_mul:
2019 return TargetOpcode::G_VECREDUCE_MUL;
2020 case Intrinsic::vector_reduce_and:
2021 return TargetOpcode::G_VECREDUCE_AND;
2022 case Intrinsic::vector_reduce_or:
2023 return TargetOpcode::G_VECREDUCE_OR;
2024 case Intrinsic::vector_reduce_xor:
2025 return TargetOpcode::G_VECREDUCE_XOR;
2026 case Intrinsic::vector_reduce_smax:
2027 return TargetOpcode::G_VECREDUCE_SMAX;
2028 case Intrinsic::vector_reduce_smin:
2029 return TargetOpcode::G_VECREDUCE_SMIN;
2030 case Intrinsic::vector_reduce_umax:
2031 return TargetOpcode::G_VECREDUCE_UMAX;
2032 case Intrinsic::vector_reduce_umin:
2033 return TargetOpcode::G_VECREDUCE_UMIN;
2034 case Intrinsic::experimental_vector_compress:
2035 return TargetOpcode::G_VECTOR_COMPRESS;
2036 case Intrinsic::lround:
2037 return TargetOpcode::G_LROUND;
2038 case Intrinsic::llround:
2039 return TargetOpcode::G_LLROUND;
2040 case Intrinsic::get_fpenv:
2041 return TargetOpcode::G_GET_FPENV;
2042 case Intrinsic::get_fpmode:
2043 return TargetOpcode::G_GET_FPMODE;
2044 }
2046}
2047
2048bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
2050 MachineIRBuilder &MIRBuilder) {
2051
2052 unsigned Op = getSimpleIntrinsicOpcode(ID);
2053
2054 // Is this a simple intrinsic?
2056 return false;
2057
2058 // Yes. Let's translate it.
2060 for (const auto &Arg : CI.args())
2061 VRegs.push_back(getOrCreateVReg(*Arg));
2062
2063 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
2065 return true;
2066}
2067
2068// TODO: Include ConstainedOps.def when all strict instructions are defined.
2070 switch (ID) {
2071 case Intrinsic::experimental_constrained_fadd:
2072 return TargetOpcode::G_STRICT_FADD;
2073 case Intrinsic::experimental_constrained_fsub:
2074 return TargetOpcode::G_STRICT_FSUB;
2075 case Intrinsic::experimental_constrained_fmul:
2076 return TargetOpcode::G_STRICT_FMUL;
2077 case Intrinsic::experimental_constrained_fdiv:
2078 return TargetOpcode::G_STRICT_FDIV;
2079 case Intrinsic::experimental_constrained_frem:
2080 return TargetOpcode::G_STRICT_FREM;
2081 case Intrinsic::experimental_constrained_fma:
2082 return TargetOpcode::G_STRICT_FMA;
2083 case Intrinsic::experimental_constrained_sqrt:
2084 return TargetOpcode::G_STRICT_FSQRT;
2085 case Intrinsic::experimental_constrained_ldexp:
2086 return TargetOpcode::G_STRICT_FLDEXP;
2087 default:
2088 return 0;
2089 }
2090}
2091
2092bool IRTranslator::translateConstrainedFPIntrinsic(
2093 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
2095
2096 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
2097 if (!Opcode)
2098 return false;
2099
2103
2105 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
2106 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(I)));
2107
2108 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
2109 return true;
2110}
2111
2112std::optional<MCRegister> IRTranslator::getArgPhysReg(Argument &Arg) {
2113 auto VRegs = getOrCreateVRegs(Arg);
2114 if (VRegs.size() != 1)
2115 return std::nullopt;
2116
2117 // Arguments are lowered as a copy of a livein physical register.
2118 auto *VRegDef = MF->getRegInfo().getVRegDef(VRegs[0]);
2119 if (!VRegDef || !VRegDef->isCopy())
2120 return std::nullopt;
2121 return VRegDef->getOperand(1).getReg().asMCReg();
2122}
2123
2124bool IRTranslator::translateIfEntryValueArgument(bool isDeclare, Value *Val,
2125 const DILocalVariable *Var,
2126 const DIExpression *Expr,
2127 const DebugLoc &DL,
2128 MachineIRBuilder &MIRBuilder) {
2129 auto *Arg = dyn_cast<Argument>(Val);
2130 if (!Arg)
2131 return false;
2132
2133 if (!Expr->isEntryValue())
2134 return false;
2135
2136 std::optional<MCRegister> PhysReg = getArgPhysReg(*Arg);
2137 if (!PhysReg) {
2138 LLVM_DEBUG(dbgs() << "Dropping dbg." << (isDeclare ? "declare" : "value")
2139 << ": expression is entry_value but "
2140 << "couldn't find a physical register\n");
2141 LLVM_DEBUG(dbgs() << *Var << "\n");
2142 return true;
2143 }
2144
2145 if (isDeclare) {
2146 // Append an op deref to account for the fact that this is a dbg_declare.
2147 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
2148 MF->setVariableDbgInfo(Var, Expr, *PhysReg, DL);
2149 } else {
2150 MIRBuilder.buildDirectDbgValue(*PhysReg, Var, Expr);
2151 }
2152
2153 return true;
2154}
2155
2157 switch (ID) {
2158 default:
2159 llvm_unreachable("Unexpected intrinsic");
2160 case Intrinsic::experimental_convergence_anchor:
2161 return TargetOpcode::CONVERGENCECTRL_ANCHOR;
2162 case Intrinsic::experimental_convergence_entry:
2163 return TargetOpcode::CONVERGENCECTRL_ENTRY;
2164 case Intrinsic::experimental_convergence_loop:
2165 return TargetOpcode::CONVERGENCECTRL_LOOP;
2166 }
2167}
2168
2169bool IRTranslator::translateConvergenceControlIntrinsic(
2170 const CallInst &CI, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder) {
2171 MachineInstrBuilder MIB = MIRBuilder.buildInstr(getConvOpcode(ID));
2172 Register OutputReg = getOrCreateConvergenceTokenVReg(CI);
2173 MIB.addDef(OutputReg);
2174
2175 if (ID == Intrinsic::experimental_convergence_loop) {
2177 assert(Bundle && "Expected a convergence control token.");
2178 Register InputReg =
2179 getOrCreateConvergenceTokenVReg(*Bundle->Inputs[0].get());
2180 MIB.addUse(InputReg);
2181 }
2182
2183 return true;
2184}
2185
2186bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
2187 MachineIRBuilder &MIRBuilder) {
2188 if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
2189 if (ORE->enabled()) {
2190 if (MemoryOpRemark::canHandle(MI, *LibInfo)) {
2191 MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
2192 R.visit(MI);
2193 }
2194 }
2195 }
2196
2197 // If this is a simple intrinsic (that is, we just need to add a def of
2198 // a vreg, and uses for each arg operand, then translate it.
2199 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
2200 return true;
2201
2202 switch (ID) {
2203 default:
2204 break;
2205 case Intrinsic::lifetime_start:
2206 case Intrinsic::lifetime_end: {
2207 // No stack colouring in O0, discard region information.
2208 if (MF->getTarget().getOptLevel() == CodeGenOptLevel::None ||
2209 MF->getFunction().hasOptNone())
2210 return true;
2211
2212 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
2213 : TargetOpcode::LIFETIME_END;
2214
2215 const AllocaInst *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0));
2216 if (!AI || !AI->isStaticAlloca())
2217 return true;
2218
2219 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
2220 return true;
2221 }
2222 case Intrinsic::fake_use: {
2224 for (const auto &Arg : CI.args())
2225 llvm::append_range(VRegs, getOrCreateVRegs(*Arg));
2226 MIRBuilder.buildInstr(TargetOpcode::FAKE_USE, {}, VRegs);
2227 MF->setHasFakeUses(true);
2228 return true;
2229 }
2230 case Intrinsic::dbg_declare: {
2231 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
2232 assert(DI.getVariable() && "Missing variable");
2233 translateDbgDeclareRecord(DI.getAddress(), DI.hasArgList(), DI.getVariable(),
2234 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
2235 return true;
2236 }
2237 case Intrinsic::dbg_label: {
2238 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
2239 assert(DI.getLabel() && "Missing label");
2240
2242 MIRBuilder.getDebugLoc()) &&
2243 "Expected inlined-at fields to agree");
2244
2245 MIRBuilder.buildDbgLabel(DI.getLabel());
2246 return true;
2247 }
2248 case Intrinsic::vaend:
2249 // No target I know of cares about va_end. Certainly no in-tree target
2250 // does. Simplest intrinsic ever!
2251 return true;
2252 case Intrinsic::vastart: {
2253 Value *Ptr = CI.getArgOperand(0);
2254 unsigned ListSize = TLI->getVaListSizeInBits(*DL) / 8;
2255 Align Alignment = getKnownAlignment(Ptr, *DL);
2256
2257 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
2258 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
2260 ListSize, Alignment));
2261 return true;
2262 }
2263 case Intrinsic::dbg_assign:
2264 // A dbg.assign is a dbg.value with more information about stack locations,
2265 // typically produced during optimisation of variables with leaked
2266 // addresses. We can treat it like a normal dbg_value intrinsic here; to
2267 // benefit from the full analysis of stack/SSA locations, GlobalISel would
2268 // need to register for and use the AssignmentTrackingAnalysis pass.
2269 [[fallthrough]];
2270 case Intrinsic::dbg_value: {
2271 // This form of DBG_VALUE is target-independent.
2272 const DbgValueInst &DI = cast<DbgValueInst>(CI);
2273 translateDbgValueRecord(DI.getValue(), DI.hasArgList(), DI.getVariable(),
2274 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
2275 return true;
2276 }
2277 case Intrinsic::uadd_with_overflow:
2278 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
2279 case Intrinsic::sadd_with_overflow:
2280 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
2281 case Intrinsic::usub_with_overflow:
2282 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
2283 case Intrinsic::ssub_with_overflow:
2284 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
2285 case Intrinsic::umul_with_overflow:
2286 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
2287 case Intrinsic::smul_with_overflow:
2288 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
2289 case Intrinsic::uadd_sat:
2290 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
2291 case Intrinsic::sadd_sat:
2292 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
2293 case Intrinsic::usub_sat:
2294 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
2295 case Intrinsic::ssub_sat:
2296 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
2297 case Intrinsic::ushl_sat:
2298 return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
2299 case Intrinsic::sshl_sat:
2300 return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
2301 case Intrinsic::umin:
2302 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
2303 case Intrinsic::umax:
2304 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
2305 case Intrinsic::smin:
2306 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
2307 case Intrinsic::smax:
2308 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
2309 case Intrinsic::abs:
2310 // TODO: Preserve "int min is poison" arg in GMIR?
2311 return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
2312 case Intrinsic::smul_fix:
2313 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
2314 case Intrinsic::umul_fix:
2315 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
2316 case Intrinsic::smul_fix_sat:
2317 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
2318 case Intrinsic::umul_fix_sat:
2319 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
2320 case Intrinsic::sdiv_fix:
2321 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
2322 case Intrinsic::udiv_fix:
2323 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
2324 case Intrinsic::sdiv_fix_sat:
2325 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
2326 case Intrinsic::udiv_fix_sat:
2327 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
2328 case Intrinsic::fmuladd: {
2329 const TargetMachine &TM = MF->getTarget();
2330 Register Dst = getOrCreateVReg(CI);
2331 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
2332 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
2333 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
2334 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
2335 TLI->isFMAFasterThanFMulAndFAdd(*MF,
2336 TLI->getValueType(*DL, CI.getType()))) {
2337 // TODO: Revisit this to see if we should move this part of the
2338 // lowering to the combiner.
2339 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
2341 } else {
2342 LLT Ty = getLLTForType(*CI.getType(), *DL);
2343 auto FMul = MIRBuilder.buildFMul(
2344 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
2345 MIRBuilder.buildFAdd(Dst, FMul, Op2,
2347 }
2348 return true;
2349 }
2350 case Intrinsic::convert_from_fp16:
2351 // FIXME: This intrinsic should probably be removed from the IR.
2352 MIRBuilder.buildFPExt(getOrCreateVReg(CI),
2353 getOrCreateVReg(*CI.getArgOperand(0)),
2355 return true;
2356 case Intrinsic::convert_to_fp16:
2357 // FIXME: This intrinsic should probably be removed from the IR.
2358 MIRBuilder.buildFPTrunc(getOrCreateVReg(CI),
2359 getOrCreateVReg(*CI.getArgOperand(0)),
2361 return true;
2362 case Intrinsic::frexp: {
2363 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
2364 MIRBuilder.buildFFrexp(VRegs[0], VRegs[1],
2365 getOrCreateVReg(*CI.getArgOperand(0)),
2367 return true;
2368 }
2369 case Intrinsic::modf: {
2370 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
2371 MIRBuilder.buildModf(VRegs[0], VRegs[1],
2372 getOrCreateVReg(*CI.getArgOperand(0)),
2374 return true;
2375 }
2376 case Intrinsic::sincos: {
2377 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
2378 MIRBuilder.buildFSincos(VRegs[0], VRegs[1],
2379 getOrCreateVReg(*CI.getArgOperand(0)),
2381 return true;
2382 }
2383 case Intrinsic::fptosi_sat:
2384 MIRBuilder.buildFPTOSI_SAT(getOrCreateVReg(CI),
2385 getOrCreateVReg(*CI.getArgOperand(0)));
2386 return true;
2387 case Intrinsic::fptoui_sat:
2388 MIRBuilder.buildFPTOUI_SAT(getOrCreateVReg(CI),
2389 getOrCreateVReg(*CI.getArgOperand(0)));
2390 return true;
2391 case Intrinsic::memcpy_inline:
2392 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
2393 case Intrinsic::memcpy:
2394 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
2395 case Intrinsic::memmove:
2396 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
2397 case Intrinsic::memset:
2398 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
2399 case Intrinsic::eh_typeid_for: {
2400 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
2401 Register Reg = getOrCreateVReg(CI);
2402 unsigned TypeID = MF->getTypeIDFor(GV);
2403 MIRBuilder.buildConstant(Reg, TypeID);
2404 return true;
2405 }
2406 case Intrinsic::objectsize:
2407 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2408
2409 case Intrinsic::is_constant:
2410 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2411
2412 case Intrinsic::stackguard:
2413 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
2414 return true;
2415 case Intrinsic::stackprotector: {
2416 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
2417 Register GuardVal;
2418 if (TLI->useLoadStackGuardNode(*CI.getModule())) {
2419 GuardVal = MRI->createGenericVirtualRegister(PtrTy);
2420 getStackGuard(GuardVal, MIRBuilder);
2421 } else
2422 GuardVal = getOrCreateVReg(*CI.getArgOperand(0)); // The guard's value.
2423
2424 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
2425 int FI = getOrCreateFrameIndex(*Slot);
2426 MF->getFrameInfo().setStackProtectorIndex(FI);
2427
2428 MIRBuilder.buildStore(
2429 GuardVal, getOrCreateVReg(*Slot),
2430 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
2433 PtrTy, Align(8)));
2434 return true;
2435 }
2436 case Intrinsic::stacksave: {
2437 MIRBuilder.buildInstr(TargetOpcode::G_STACKSAVE, {getOrCreateVReg(CI)}, {});
2438 return true;
2439 }
2440 case Intrinsic::stackrestore: {
2441 MIRBuilder.buildInstr(TargetOpcode::G_STACKRESTORE, {},
2442 {getOrCreateVReg(*CI.getArgOperand(0))});
2443 return true;
2444 }
2445 case Intrinsic::cttz:
2446 case Intrinsic::ctlz: {
2447 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
2448 bool isTrailing = ID == Intrinsic::cttz;
2449 unsigned Opcode = isTrailing
2450 ? Cst->isZero() ? TargetOpcode::G_CTTZ
2451 : TargetOpcode::G_CTTZ_ZERO_UNDEF
2452 : Cst->isZero() ? TargetOpcode::G_CTLZ
2453 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
2454 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
2455 {getOrCreateVReg(*CI.getArgOperand(0))});
2456 return true;
2457 }
2458 case Intrinsic::invariant_start: {
2459 MIRBuilder.buildUndef(getOrCreateVReg(CI));
2460 return true;
2461 }
2462 case Intrinsic::invariant_end:
2463 return true;
2464 case Intrinsic::expect:
2465 case Intrinsic::expect_with_probability:
2466 case Intrinsic::annotation:
2467 case Intrinsic::ptr_annotation:
2468 case Intrinsic::launder_invariant_group:
2469 case Intrinsic::strip_invariant_group: {
2470 // Drop the intrinsic, but forward the value.
2471 MIRBuilder.buildCopy(getOrCreateVReg(CI),
2472 getOrCreateVReg(*CI.getArgOperand(0)));
2473 return true;
2474 }
2475 case Intrinsic::assume:
2476 case Intrinsic::experimental_noalias_scope_decl:
2477 case Intrinsic::var_annotation:
2478 case Intrinsic::sideeffect:
2479 // Discard annotate attributes, assumptions, and artificial side-effects.
2480 return true;
2481 case Intrinsic::read_volatile_register:
2482 case Intrinsic::read_register: {
2483 Value *Arg = CI.getArgOperand(0);
2484 MIRBuilder
2485 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
2486 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
2487 return true;
2488 }
2489 case Intrinsic::write_register: {
2490 Value *Arg = CI.getArgOperand(0);
2491 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
2492 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
2493 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
2494 return true;
2495 }
2496 case Intrinsic::localescape: {
2497 MachineBasicBlock &EntryMBB = MF->front();
2498 StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
2499
2500 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
2501 // is the same on all targets.
2502 for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) {
2503 Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
2504 if (isa<ConstantPointerNull>(Arg))
2505 continue; // Skip null pointers. They represent a hole in index space.
2506
2507 int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
2508 MCSymbol *FrameAllocSym =
2509 MF->getContext().getOrCreateFrameAllocSymbol(EscapedName, Idx);
2510
2511 // This should be inserted at the start of the entry block.
2512 auto LocalEscape =
2513 MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
2514 .addSym(FrameAllocSym)
2515 .addFrameIndex(FI);
2516
2517 EntryMBB.insert(EntryMBB.begin(), LocalEscape);
2518 }
2519
2520 return true;
2521 }
2522 case Intrinsic::vector_reduce_fadd:
2523 case Intrinsic::vector_reduce_fmul: {
2524 // Need to check for the reassoc flag to decide whether we want a
2525 // sequential reduction opcode or not.
2526 Register Dst = getOrCreateVReg(CI);
2527 Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
2528 Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
2529 unsigned Opc = 0;
2530 if (!CI.hasAllowReassoc()) {
2531 // The sequential ordering case.
2532 Opc = ID == Intrinsic::vector_reduce_fadd
2533 ? TargetOpcode::G_VECREDUCE_SEQ_FADD
2534 : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
2535 if (!MRI->getType(VecSrc).isVector())
2536 Opc = ID == Intrinsic::vector_reduce_fadd ? TargetOpcode::G_FADD
2537 : TargetOpcode::G_FMUL;
2538 MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
2540 return true;
2541 }
2542 // We split the operation into a separate G_FADD/G_FMUL + the reduce,
2543 // since the associativity doesn't matter.
2544 unsigned ScalarOpc;
2545 if (ID == Intrinsic::vector_reduce_fadd) {
2546 Opc = TargetOpcode::G_VECREDUCE_FADD;
2547 ScalarOpc = TargetOpcode::G_FADD;
2548 } else {
2549 Opc = TargetOpcode::G_VECREDUCE_FMUL;
2550 ScalarOpc = TargetOpcode::G_FMUL;
2551 }
2552 LLT DstTy = MRI->getType(Dst);
2553 auto Rdx = MIRBuilder.buildInstr(
2554 Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
2555 MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
2557
2558 return true;
2559 }
2560 case Intrinsic::trap:
2561 return translateTrap(CI, MIRBuilder, TargetOpcode::G_TRAP);
2562 case Intrinsic::debugtrap:
2563 return translateTrap(CI, MIRBuilder, TargetOpcode::G_DEBUGTRAP);
2564 case Intrinsic::ubsantrap:
2565 return translateTrap(CI, MIRBuilder, TargetOpcode::G_UBSANTRAP);
2566 case Intrinsic::allow_runtime_check:
2567 case Intrinsic::allow_ubsan_check:
2568 MIRBuilder.buildCopy(getOrCreateVReg(CI),
2569 getOrCreateVReg(*ConstantInt::getTrue(CI.getType())));
2570 return true;
2571 case Intrinsic::amdgcn_cs_chain:
2572 case Intrinsic::amdgcn_call_whole_wave:
2573 return translateCallBase(CI, MIRBuilder);
2574 case Intrinsic::fptrunc_round: {
2576
2577 // Convert the metadata argument to a constant integer
2578 Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(1))->getMetadata();
2579 std::optional<RoundingMode> RoundMode =
2580 convertStrToRoundingMode(cast<MDString>(MD)->getString());
2581
2582 // Add the Rounding mode as an integer
2583 MIRBuilder
2584 .buildInstr(TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND,
2585 {getOrCreateVReg(CI)},
2586 {getOrCreateVReg(*CI.getArgOperand(0))}, Flags)
2587 .addImm((int)*RoundMode);
2588
2589 return true;
2590 }
2591 case Intrinsic::is_fpclass: {
2592 Value *FpValue = CI.getOperand(0);
2593 ConstantInt *TestMaskValue = cast<ConstantInt>(CI.getOperand(1));
2594
2595 MIRBuilder
2596 .buildInstr(TargetOpcode::G_IS_FPCLASS, {getOrCreateVReg(CI)},
2597 {getOrCreateVReg(*FpValue)})
2598 .addImm(TestMaskValue->getZExtValue());
2599
2600 return true;
2601 }
2602 case Intrinsic::set_fpenv: {
2603 Value *FPEnv = CI.getOperand(0);
2604 MIRBuilder.buildSetFPEnv(getOrCreateVReg(*FPEnv));
2605 return true;
2606 }
2607 case Intrinsic::reset_fpenv:
2608 MIRBuilder.buildResetFPEnv();
2609 return true;
2610 case Intrinsic::set_fpmode: {
2611 Value *FPState = CI.getOperand(0);
2612 MIRBuilder.buildSetFPMode(getOrCreateVReg(*FPState));
2613 return true;
2614 }
2615 case Intrinsic::reset_fpmode:
2616 MIRBuilder.buildResetFPMode();
2617 return true;
2618 case Intrinsic::get_rounding:
2619 MIRBuilder.buildGetRounding(getOrCreateVReg(CI));
2620 return true;
2621 case Intrinsic::set_rounding:
2622 MIRBuilder.buildSetRounding(getOrCreateVReg(*CI.getOperand(0)));
2623 return true;
2624 case Intrinsic::vscale: {
2625 MIRBuilder.buildVScale(getOrCreateVReg(CI), 1);
2626 return true;
2627 }
2628 case Intrinsic::scmp:
2629 MIRBuilder.buildSCmp(getOrCreateVReg(CI),
2630 getOrCreateVReg(*CI.getOperand(0)),
2631 getOrCreateVReg(*CI.getOperand(1)));
2632 return true;
2633 case Intrinsic::ucmp:
2634 MIRBuilder.buildUCmp(getOrCreateVReg(CI),
2635 getOrCreateVReg(*CI.getOperand(0)),
2636 getOrCreateVReg(*CI.getOperand(1)));
2637 return true;
2638 case Intrinsic::vector_extract:
2639 return translateExtractVector(CI, MIRBuilder);
2640 case Intrinsic::vector_insert:
2641 return translateInsertVector(CI, MIRBuilder);
2642 case Intrinsic::stepvector: {
2643 MIRBuilder.buildStepVector(getOrCreateVReg(CI), 1);
2644 return true;
2645 }
2646 case Intrinsic::prefetch: {
2647 Value *Addr = CI.getOperand(0);
2648 unsigned RW = cast<ConstantInt>(CI.getOperand(1))->getZExtValue();
2649 unsigned Locality = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
2650 unsigned CacheType = cast<ConstantInt>(CI.getOperand(3))->getZExtValue();
2651
2653 auto &MMO = *MF->getMachineMemOperand(MachinePointerInfo(Addr), Flags,
2654 LLT(), Align());
2655
2656 MIRBuilder.buildPrefetch(getOrCreateVReg(*Addr), RW, Locality, CacheType,
2657 MMO);
2658
2659 return true;
2660 }
2661
2662 case Intrinsic::vector_interleave2:
2663 case Intrinsic::vector_deinterleave2: {
2664 // Both intrinsics have at least one operand.
2665 Value *Op0 = CI.getOperand(0);
2666 LLT ResTy = getLLTForType(*Op0->getType(), MIRBuilder.getDataLayout());
2667 if (!ResTy.isFixedVector())
2668 return false;
2669
2670 if (CI.getIntrinsicID() == Intrinsic::vector_interleave2)
2671 return translateVectorInterleave2Intrinsic(CI, MIRBuilder);
2672
2673 return translateVectorDeinterleave2Intrinsic(CI, MIRBuilder);
2674 }
2675
2676#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
2677 case Intrinsic::INTRINSIC:
2678#include "llvm/IR/ConstrainedOps.def"
2679 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
2680 MIRBuilder);
2681 case Intrinsic::experimental_convergence_anchor:
2682 case Intrinsic::experimental_convergence_entry:
2683 case Intrinsic::experimental_convergence_loop:
2684 return translateConvergenceControlIntrinsic(CI, ID, MIRBuilder);
2685 }
2686 return false;
2687}
2688
2689bool IRTranslator::translateInlineAsm(const CallBase &CB,
2690 MachineIRBuilder &MIRBuilder) {
2691 if (containsBF16Type(CB))
2692 return false;
2693
2694 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
2695
2696 if (!ALI) {
2697 LLVM_DEBUG(
2698 dbgs() << "Inline asm lowering is not supported for this target yet\n");
2699 return false;
2700 }
2701
2702 return ALI->lowerInlineAsm(
2703 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
2704}
2705
2706bool IRTranslator::translateCallBase(const CallBase &CB,
2707 MachineIRBuilder &MIRBuilder) {
2708 ArrayRef<Register> Res = getOrCreateVRegs(CB);
2709
2711 Register SwiftInVReg = 0;
2712 Register SwiftErrorVReg = 0;
2713 for (const auto &Arg : CB.args()) {
2714 if (CLI->supportSwiftError() && isSwiftError(Arg)) {
2715 assert(SwiftInVReg == 0 && "Expected only one swift error argument");
2716 LLT Ty = getLLTForType(*Arg->getType(), *DL);
2717 SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
2718 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
2719 &CB, &MIRBuilder.getMBB(), Arg));
2720 Args.emplace_back(ArrayRef(SwiftInVReg));
2721 SwiftErrorVReg =
2722 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
2723 continue;
2724 }
2725 Args.push_back(getOrCreateVRegs(*Arg));
2726 }
2727
2728 if (auto *CI = dyn_cast<CallInst>(&CB)) {
2729 if (ORE->enabled()) {
2730 if (MemoryOpRemark::canHandle(CI, *LibInfo)) {
2731 MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
2732 R.visit(CI);
2733 }
2734 }
2735 }
2736
2737 std::optional<CallLowering::PtrAuthInfo> PAI;
2738 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_ptrauth)) {
2739 // Functions should never be ptrauth-called directly.
2740 assert(!CB.getCalledFunction() && "invalid direct ptrauth call");
2741
2742 const Value *Key = Bundle->Inputs[0];
2743 const Value *Discriminator = Bundle->Inputs[1];
2744
2745 // Look through ptrauth constants to try to eliminate the matching bundle
2746 // and turn this into a direct call with no ptrauth.
2747 // CallLowering will use the raw pointer if it doesn't find the PAI.
2748 const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CB.getCalledOperand());
2749 if (!CalleeCPA || !isa<Function>(CalleeCPA->getPointer()) ||
2750 !CalleeCPA->isKnownCompatibleWith(Key, Discriminator, *DL)) {
2751 // If we can't make it direct, package the bundle into PAI.
2752 Register DiscReg = getOrCreateVReg(*Discriminator);
2753 PAI = CallLowering::PtrAuthInfo{cast<ConstantInt>(Key)->getZExtValue(),
2754 DiscReg};
2755 }
2756 }
2757
2758 Register ConvergenceCtrlToken = 0;
2759 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
2760 const auto &Token = *Bundle->Inputs[0].get();
2761 ConvergenceCtrlToken = getOrCreateConvergenceTokenVReg(Token);
2762 }
2763
2764 // We don't set HasCalls on MFI here yet because call lowering may decide to
2765 // optimize into tail calls. Instead, we defer that to selection where a final
2766 // scan is done to check if any instructions are calls.
2767 bool Success = CLI->lowerCall(
2768 MIRBuilder, CB, Res, Args, SwiftErrorVReg, PAI, ConvergenceCtrlToken,
2769 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
2770
2771 // Check if we just inserted a tail call.
2772 if (Success) {
2773 assert(!HasTailCall && "Can't tail call return twice from block?");
2774 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2775 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
2776 }
2777
2778 return Success;
2779}
2780
2781bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
2782 if (!MF->getTarget().getTargetTriple().isSPIRV() && containsBF16Type(U))
2783 return false;
2784
2785 const CallInst &CI = cast<CallInst>(U);
2786 const Function *F = CI.getCalledFunction();
2787
2788 // FIXME: support Windows dllimport function calls and calls through
2789 // weak symbols.
2790 if (F && (F->hasDLLImportStorageClass() ||
2791 (MF->getTarget().getTargetTriple().isOSWindows() &&
2792 F->hasExternalWeakLinkage())))
2793 return false;
2794
2795 // FIXME: support control flow guard targets.
2797 return false;
2798
2799 // FIXME: support statepoints and related.
2801 return false;
2802
2803 if (CI.isInlineAsm())
2804 return translateInlineAsm(CI, MIRBuilder);
2805
2806 Intrinsic::ID ID = F ? F->getIntrinsicID() : Intrinsic::not_intrinsic;
2807 if (!F || ID == Intrinsic::not_intrinsic) {
2808 if (translateCallBase(CI, MIRBuilder)) {
2809 diagnoseDontCall(CI);
2810 return true;
2811 }
2812 return false;
2813 }
2814
2815 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
2816
2817 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
2818 return true;
2819
2820 ArrayRef<Register> ResultRegs;
2821 if (!CI.getType()->isVoidTy())
2822 ResultRegs = getOrCreateVRegs(CI);
2823
2824 // Ignore the callsite attributes. Backend code is most likely not expecting
2825 // an intrinsic to sometimes have side effects and sometimes not.
2826 MachineInstrBuilder MIB = MIRBuilder.buildIntrinsic(ID, ResultRegs);
2827 if (isa<FPMathOperator>(CI))
2828 MIB->copyIRFlags(CI);
2829
2830 for (const auto &Arg : enumerate(CI.args())) {
2831 // If this is required to be an immediate, don't materialize it in a
2832 // register.
2833 if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
2834 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
2835 // imm arguments are more convenient than cimm (and realistically
2836 // probably sufficient), so use them.
2837 assert(CI->getBitWidth() <= 64 &&
2838 "large intrinsic immediates not handled");
2839 MIB.addImm(CI->getSExtValue());
2840 } else {
2841 MIB.addFPImm(cast<ConstantFP>(Arg.value()));
2842 }
2843 } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
2844 auto *MD = MDVal->getMetadata();
2845 auto *MDN = dyn_cast<MDNode>(MD);
2846 if (!MDN) {
2847 if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
2848 MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
2849 else // This was probably an MDString.
2850 return false;
2851 }
2852 MIB.addMetadata(MDN);
2853 } else {
2854 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
2855 if (VRegs.size() > 1)
2856 return false;
2857 MIB.addUse(VRegs[0]);
2858 }
2859 }
2860
2861 // Add a MachineMemOperand if it is a target mem intrinsic.
2862 TargetLowering::IntrinsicInfo Info;
2863 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
2864 if (TLI->getTgtMemIntrinsic(Info, CI, *MF, ID)) {
2865 Align Alignment = Info.align.value_or(
2866 DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext())));
2867 LLT MemTy = Info.memVT.isSimple()
2868 ? getLLTForMVT(Info.memVT.getSimpleVT())
2869 : LLT::scalar(Info.memVT.getStoreSizeInBits());
2870
2871 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
2872 // didn't yield anything useful.
2873 MachinePointerInfo MPI;
2874 if (Info.ptrVal)
2875 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
2876 else if (Info.fallbackAddressSpace)
2877 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
2878 MIB.addMemOperand(MF->getMachineMemOperand(
2879 MPI, Info.flags, MemTy, Alignment, CI.getAAMetadata(),
2880 /*Ranges=*/nullptr, Info.ssid, Info.order, Info.failureOrder));
2881 }
2882
2883 if (CI.isConvergent()) {
2884 if (auto Bundle = CI.getOperandBundle(LLVMContext::OB_convergencectrl)) {
2885 auto *Token = Bundle->Inputs[0].get();
2886 Register TokenReg = getOrCreateVReg(*Token);
2887 MIB.addUse(TokenReg, RegState::Implicit);
2888 }
2889 }
2890
2891 return true;
2892}
2893
2894bool IRTranslator::findUnwindDestinations(
2895 const BasicBlock *EHPadBB,
2896 BranchProbability Prob,
2897 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2898 &UnwindDests) {
2900 EHPadBB->getParent()->getFunction().getPersonalityFn());
2901 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2902 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2903 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2904 bool IsSEH = isAsynchronousEHPersonality(Personality);
2905
2906 if (IsWasmCXX) {
2907 // Ignore this for now.
2908 return false;
2909 }
2910
2911 while (EHPadBB) {
2913 BasicBlock *NewEHPadBB = nullptr;
2914 if (isa<LandingPadInst>(Pad)) {
2915 // Stop on landingpads. They are not funclets.
2916 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2917 break;
2918 }
2919 if (isa<CleanupPadInst>(Pad)) {
2920 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2921 // personalities.
2922 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2923 UnwindDests.back().first->setIsEHScopeEntry();
2924 UnwindDests.back().first->setIsEHFuncletEntry();
2925 break;
2926 }
2927 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2928 // Add the catchpad handlers to the possible destinations.
2929 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2930 UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
2931 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2932 if (IsMSVCCXX || IsCoreCLR)
2933 UnwindDests.back().first->setIsEHFuncletEntry();
2934 if (!IsSEH)
2935 UnwindDests.back().first->setIsEHScopeEntry();
2936 }
2937 NewEHPadBB = CatchSwitch->getUnwindDest();
2938 } else {
2939 continue;
2940 }
2941
2942 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2943 if (BPI && NewEHPadBB)
2944 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2945 EHPadBB = NewEHPadBB;
2946 }
2947 return true;
2948}
2949
2950bool IRTranslator::translateInvoke(const User &U,
2951 MachineIRBuilder &MIRBuilder) {
2952 const InvokeInst &I = cast<InvokeInst>(U);
2953 MCContext &Context = MF->getContext();
2954
2955 const BasicBlock *ReturnBB = I.getSuccessor(0);
2956 const BasicBlock *EHPadBB = I.getSuccessor(1);
2957
2958 const Function *Fn = I.getCalledFunction();
2959
2960 // FIXME: support invoking patchpoint and statepoint intrinsics.
2961 if (Fn && Fn->isIntrinsic())
2962 return false;
2963
2964 // FIXME: support whatever these are.
2965 if (I.hasDeoptState())
2966 return false;
2967
2968 // FIXME: support control flow guard targets.
2969 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2970 return false;
2971
2972 // FIXME: support Windows exception handling.
2973 if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHIIt()))
2974 return false;
2975
2976 // FIXME: support Windows dllimport function calls and calls through
2977 // weak symbols.
2978 if (Fn && (Fn->hasDLLImportStorageClass() ||
2979 (MF->getTarget().getTargetTriple().isOSWindows() &&
2980 Fn->hasExternalWeakLinkage())))
2981 return false;
2982
2983 bool LowerInlineAsm = I.isInlineAsm();
2984 bool NeedEHLabel = true;
2985
2986 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
2987 // the region covered by the try.
2988 MCSymbol *BeginSymbol = nullptr;
2989 if (NeedEHLabel) {
2990 MIRBuilder.buildInstr(TargetOpcode::G_INVOKE_REGION_START);
2991 BeginSymbol = Context.createTempSymbol();
2992 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
2993 }
2994
2995 if (LowerInlineAsm) {
2996 if (!translateInlineAsm(I, MIRBuilder))
2997 return false;
2998 } else if (!translateCallBase(I, MIRBuilder))
2999 return false;
3000
3001 MCSymbol *EndSymbol = nullptr;
3002 if (NeedEHLabel) {
3003 EndSymbol = Context.createTempSymbol();
3004 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
3005 }
3006
3008 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3009 MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
3010 BranchProbability EHPadBBProb =
3011 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3013
3014 if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
3015 return false;
3016
3017 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
3018 &ReturnMBB = getMBB(*ReturnBB);
3019 // Update successor info.
3020 addSuccessorWithProb(InvokeMBB, &ReturnMBB);
3021 for (auto &UnwindDest : UnwindDests) {
3022 UnwindDest.first->setIsEHPad();
3023 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3024 }
3025 InvokeMBB->normalizeSuccProbs();
3026
3027 if (NeedEHLabel) {
3028 assert(BeginSymbol && "Expected a begin symbol!");
3029 assert(EndSymbol && "Expected an end symbol!");
3030 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
3031 }
3032
3033 MIRBuilder.buildBr(ReturnMBB);
3034 return true;
3035}
3036
3037bool IRTranslator::translateCallBr(const User &U,
3038 MachineIRBuilder &MIRBuilder) {
3039 // FIXME: Implement this.
3040 return false;
3041}
3042
3043bool IRTranslator::translateLandingPad(const User &U,
3044 MachineIRBuilder &MIRBuilder) {
3045 const LandingPadInst &LP = cast<LandingPadInst>(U);
3046
3047 MachineBasicBlock &MBB = MIRBuilder.getMBB();
3048
3049 MBB.setIsEHPad();
3050
3051 // If there aren't registers to copy the values into (e.g., during SjLj
3052 // exceptions), then don't bother.
3053 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
3054 if (TLI->getExceptionPointerRegister(PersonalityFn) == 0 &&
3055 TLI->getExceptionSelectorRegister(PersonalityFn) == 0)
3056 return true;
3057
3058 // If landingpad's return type is token type, we don't create DAG nodes
3059 // for its exception pointer and selector value. The extraction of exception
3060 // pointer or selector value from token type landingpads is not currently
3061 // supported.
3062 if (LP.getType()->isTokenTy())
3063 return true;
3064
3065 // Add a label to mark the beginning of the landing pad. Deletion of the
3066 // landing pad can thus be detected via the MachineModuleInfo.
3067 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
3068 .addSym(MF->addLandingPad(&MBB));
3069
3070 // If the unwinder does not preserve all registers, ensure that the
3071 // function marks the clobbered registers as used.
3072 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
3073 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
3074 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
3075
3076 LLT Ty = getLLTForType(*LP.getType(), *DL);
3077 Register Undef = MRI->createGenericVirtualRegister(Ty);
3078 MIRBuilder.buildUndef(Undef);
3079
3081 for (Type *Ty : cast<StructType>(LP.getType())->elements())
3082 Tys.push_back(getLLTForType(*Ty, *DL));
3083 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
3084
3085 // Mark exception register as live in.
3086 Register ExceptionReg = TLI->getExceptionPointerRegister(PersonalityFn);
3087 if (!ExceptionReg)
3088 return false;
3089
3090 MBB.addLiveIn(ExceptionReg);
3091 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
3092 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
3093
3094 Register SelectorReg = TLI->getExceptionSelectorRegister(PersonalityFn);
3095 if (!SelectorReg)
3096 return false;
3097
3098 MBB.addLiveIn(SelectorReg);
3099 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
3100 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
3101 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
3102
3103 return true;
3104}
3105
3106bool IRTranslator::translateAlloca(const User &U,
3107 MachineIRBuilder &MIRBuilder) {
3108 auto &AI = cast<AllocaInst>(U);
3109
3110 if (AI.isSwiftError())
3111 return true;
3112
3113 if (AI.isStaticAlloca()) {
3114 Register Res = getOrCreateVReg(AI);
3115 int FI = getOrCreateFrameIndex(AI);
3116 MIRBuilder.buildFrameIndex(Res, FI);
3117 return true;
3118 }
3119
3120 // FIXME: support stack probing for Windows.
3121 if (MF->getTarget().getTargetTriple().isOSWindows())
3122 return false;
3123
3124 // Now we're in the harder dynamic case.
3125 Register NumElts = getOrCreateVReg(*AI.getArraySize());
3126 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
3127 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
3128 if (MRI->getType(NumElts) != IntPtrTy) {
3129 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
3130 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
3131 NumElts = ExtElts;
3132 }
3133
3134 Type *Ty = AI.getAllocatedType();
3135
3136 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
3137 Register TySize =
3138 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
3139 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
3140
3141 // Round the size of the allocation up to the stack alignment size
3142 // by add SA-1 to the size. This doesn't overflow because we're computing
3143 // an address inside an alloca.
3144 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
3145 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
3146 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
3148 auto AlignCst =
3149 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
3150 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
3151
3152 Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty));
3153 if (Alignment <= StackAlign)
3154 Alignment = Align(1);
3155 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
3156
3157 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
3158 assert(MF->getFrameInfo().hasVarSizedObjects());
3159 return true;
3160}
3161
3162bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
3163 // FIXME: We may need more info about the type. Because of how LLT works,
3164 // we're completely discarding the i64/double distinction here (amongst
3165 // others). Fortunately the ABIs I know of where that matters don't use va_arg
3166 // anyway but that's not guaranteed.
3167 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
3168 {getOrCreateVReg(*U.getOperand(0)),
3169 DL->getABITypeAlign(U.getType()).value()});
3170 return true;
3171}
3172
3173bool IRTranslator::translateUnreachable(const User &U,
3174 MachineIRBuilder &MIRBuilder) {
3175 auto &UI = cast<UnreachableInst>(U);
3176 if (!UI.shouldLowerToTrap(MF->getTarget().Options.TrapUnreachable,
3177 MF->getTarget().Options.NoTrapAfterNoreturn))
3178 return true;
3179
3180 MIRBuilder.buildTrap();
3181 return true;
3182}
3183
3184bool IRTranslator::translateInsertElement(const User &U,
3185 MachineIRBuilder &MIRBuilder) {
3186 // If it is a <1 x Ty> vector, use the scalar as it is
3187 // not a legal vector type in LLT.
3188 if (auto *FVT = dyn_cast<FixedVectorType>(U.getType());
3189 FVT && FVT->getNumElements() == 1)
3190 return translateCopy(U, *U.getOperand(1), MIRBuilder);
3191
3192 Register Res = getOrCreateVReg(U);
3193 Register Val = getOrCreateVReg(*U.getOperand(0));
3194 Register Elt = getOrCreateVReg(*U.getOperand(1));
3195 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
3196 Register Idx;
3197 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(2))) {
3198 if (CI->getBitWidth() != PreferredVecIdxWidth) {
3199 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3200 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
3201 Idx = getOrCreateVReg(*NewIdxCI);
3202 }
3203 }
3204 if (!Idx)
3205 Idx = getOrCreateVReg(*U.getOperand(2));
3206 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
3207 const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3208 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
3209 }
3210 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
3211 return true;
3212}
3213
3214bool IRTranslator::translateInsertVector(const User &U,
3215 MachineIRBuilder &MIRBuilder) {
3216 Register Dst = getOrCreateVReg(U);
3217 Register Vec = getOrCreateVReg(*U.getOperand(0));
3218 Register Elt = getOrCreateVReg(*U.getOperand(1));
3219
3220 ConstantInt *CI = cast<ConstantInt>(U.getOperand(2));
3221 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
3222
3223 // Resize Index to preferred index width.
3224 if (CI->getBitWidth() != PreferredVecIdxWidth) {
3225 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3226 CI = ConstantInt::get(CI->getContext(), NewIdx);
3227 }
3228
3229 // If it is a <1 x Ty> vector, we have to use other means.
3230 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getOperand(1)->getType());
3231 ResultType && ResultType->getNumElements() == 1) {
3232 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
3233 InputType && InputType->getNumElements() == 1) {
3234 // We are inserting an illegal fixed vector into an illegal
3235 // fixed vector, use the scalar as it is not a legal vector type
3236 // in LLT.
3237 return translateCopy(U, *U.getOperand(0), MIRBuilder);
3238 }
3239 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
3240 // We are inserting an illegal fixed vector into a legal fixed
3241 // vector, use the scalar as it is not a legal vector type in
3242 // LLT.
3243 Register Idx = getOrCreateVReg(*CI);
3244 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, Idx);
3245 return true;
3246 }
3247 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
3248 // We are inserting an illegal fixed vector into a scalable
3249 // vector, use a scalar element insert.
3250 LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3251 Register Idx = getOrCreateVReg(*CI);
3252 auto ScaledIndex = MIRBuilder.buildMul(
3253 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
3254 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, ScaledIndex);
3255 return true;
3256 }
3257 }
3258
3259 MIRBuilder.buildInsertSubvector(
3260 getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
3261 getOrCreateVReg(*U.getOperand(1)), CI->getZExtValue());
3262 return true;
3263}
3264
3265bool IRTranslator::translateExtractElement(const User &U,
3266 MachineIRBuilder &MIRBuilder) {
3267 // If it is a <1 x Ty> vector, use the scalar as it is
3268 // not a legal vector type in LLT.
3269 if (const FixedVectorType *FVT =
3270 dyn_cast<FixedVectorType>(U.getOperand(0)->getType()))
3271 if (FVT->getNumElements() == 1)
3272 return translateCopy(U, *U.getOperand(0), MIRBuilder);
3273
3274 Register Res = getOrCreateVReg(U);
3275 Register Val = getOrCreateVReg(*U.getOperand(0));
3276 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
3277 Register Idx;
3278 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
3279 if (CI->getBitWidth() != PreferredVecIdxWidth) {
3280 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3281 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
3282 Idx = getOrCreateVReg(*NewIdxCI);
3283 }
3284 }
3285 if (!Idx)
3286 Idx = getOrCreateVReg(*U.getOperand(1));
3287 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
3288 const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3289 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
3290 }
3291 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
3292 return true;
3293}
3294
3295bool IRTranslator::translateExtractVector(const User &U,
3296 MachineIRBuilder &MIRBuilder) {
3297 Register Res = getOrCreateVReg(U);
3298 Register Vec = getOrCreateVReg(*U.getOperand(0));
3299 ConstantInt *CI = cast<ConstantInt>(U.getOperand(1));
3300 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
3301
3302 // Resize Index to preferred index width.
3303 if (CI->getBitWidth() != PreferredVecIdxWidth) {
3304 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3305 CI = ConstantInt::get(CI->getContext(), NewIdx);
3306 }
3307
3308 // If it is a <1 x Ty> vector, we have to use other means.
3309 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getType());
3310 ResultType && ResultType->getNumElements() == 1) {
3311 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
3312 InputType && InputType->getNumElements() == 1) {
3313 // We are extracting an illegal fixed vector from an illegal fixed vector,
3314 // use the scalar as it is not a legal vector type in LLT.
3315 return translateCopy(U, *U.getOperand(0), MIRBuilder);
3316 }
3317 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
3318 // We are extracting an illegal fixed vector from a legal fixed
3319 // vector, use the scalar as it is not a legal vector type in
3320 // LLT.
3321 Register Idx = getOrCreateVReg(*CI);
3322 MIRBuilder.buildExtractVectorElement(Res, Vec, Idx);
3323 return true;
3324 }
3325 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
3326 // We are extracting an illegal fixed vector from a scalable
3327 // vector, use a scalar element extract.
3328 LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3329 Register Idx = getOrCreateVReg(*CI);
3330 auto ScaledIndex = MIRBuilder.buildMul(
3331 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
3332 MIRBuilder.buildExtractVectorElement(Res, Vec, ScaledIndex);
3333 return true;
3334 }
3335 }
3336
3337 MIRBuilder.buildExtractSubvector(getOrCreateVReg(U),
3338 getOrCreateVReg(*U.getOperand(0)),
3339 CI->getZExtValue());
3340 return true;
3341}
3342
3343bool IRTranslator::translateShuffleVector(const User &U,
3344 MachineIRBuilder &MIRBuilder) {
3345 // A ShuffleVector that operates on scalable vectors is a splat vector where
3346 // the value of the splat vector is the 0th element of the first operand,
3347 // since the index mask operand is the zeroinitializer (undef and
3348 // poison are treated as zeroinitializer here).
3349 if (U.getOperand(0)->getType()->isScalableTy()) {
3350 Register Val = getOrCreateVReg(*U.getOperand(0));
3351 auto SplatVal = MIRBuilder.buildExtractVectorElementConstant(
3352 MRI->getType(Val).getElementType(), Val, 0);
3353 MIRBuilder.buildSplatVector(getOrCreateVReg(U), SplatVal);
3354 return true;
3355 }
3356
3357 ArrayRef<int> Mask;
3358 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
3359 Mask = SVI->getShuffleMask();
3360 else
3361 Mask = cast<ConstantExpr>(U).getShuffleMask();
3362
3363 // As GISel does not represent <1 x > vectors as a separate type from scalars,
3364 // we transform shuffle_vector with a scalar output to an
3365 // ExtractVectorElement. If the input type is also scalar it becomes a Copy.
3366 unsigned DstElts = cast<FixedVectorType>(U.getType())->getNumElements();
3367 unsigned SrcElts =
3368 cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements();
3369 if (DstElts == 1) {
3370 unsigned M = Mask[0];
3371 if (SrcElts == 1) {
3372 if (M == 0 || M == 1)
3373 return translateCopy(U, *U.getOperand(M), MIRBuilder);
3374 MIRBuilder.buildUndef(getOrCreateVReg(U));
3375 } else {
3376 Register Dst = getOrCreateVReg(U);
3377 if (M < SrcElts) {
3379 Dst, getOrCreateVReg(*U.getOperand(0)), M);
3380 } else if (M < SrcElts * 2) {
3382 Dst, getOrCreateVReg(*U.getOperand(1)), M - SrcElts);
3383 } else {
3384 MIRBuilder.buildUndef(Dst);
3385 }
3386 }
3387 return true;
3388 }
3389
3390 // A single element src is transformed to a build_vector.
3391 if (SrcElts == 1) {
3394 for (int M : Mask) {
3395 LLT SrcTy = getLLTForType(*U.getOperand(0)->getType(), *DL);
3396 if (M == 0 || M == 1) {
3397 Ops.push_back(getOrCreateVReg(*U.getOperand(M)));
3398 } else {
3399 if (!Undef.isValid()) {
3400 Undef = MRI->createGenericVirtualRegister(SrcTy);
3401 MIRBuilder.buildUndef(Undef);
3402 }
3403 Ops.push_back(Undef);
3404 }
3405 }
3406 MIRBuilder.buildBuildVector(getOrCreateVReg(U), Ops);
3407 return true;
3408 }
3409
3410 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
3411 MIRBuilder
3412 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
3413 {getOrCreateVReg(*U.getOperand(0)),
3414 getOrCreateVReg(*U.getOperand(1))})
3415 .addShuffleMask(MaskAlloc);
3416 return true;
3417}
3418
3419bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
3420 const PHINode &PI = cast<PHINode>(U);
3421
3422 SmallVector<MachineInstr *, 4> Insts;
3423 for (auto Reg : getOrCreateVRegs(PI)) {
3424 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
3425 Insts.push_back(MIB.getInstr());
3426 }
3427
3428 PendingPHIs.emplace_back(&PI, std::move(Insts));
3429 return true;
3430}
3431
3432bool IRTranslator::translateAtomicCmpXchg(const User &U,
3433 MachineIRBuilder &MIRBuilder) {
3434 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
3435
3436 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
3437
3438 auto Res = getOrCreateVRegs(I);
3439 Register OldValRes = Res[0];
3440 Register SuccessRes = Res[1];
3441 Register Addr = getOrCreateVReg(*I.getPointerOperand());
3442 Register Cmp = getOrCreateVReg(*I.getCompareOperand());
3443 Register NewVal = getOrCreateVReg(*I.getNewValOperand());
3444
3446 OldValRes, SuccessRes, Addr, Cmp, NewVal,
3447 *MF->getMachineMemOperand(
3448 MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
3449 getMemOpAlign(I), I.getAAMetadata(), nullptr, I.getSyncScopeID(),
3450 I.getSuccessOrdering(), I.getFailureOrdering()));
3451 return true;
3452}
3453
3454bool IRTranslator::translateAtomicRMW(const User &U,
3455 MachineIRBuilder &MIRBuilder) {
3456 if (containsBF16Type(U))
3457 return false;
3458
3459 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
3460 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
3461
3462 Register Res = getOrCreateVReg(I);
3463 Register Addr = getOrCreateVReg(*I.getPointerOperand());
3464 Register Val = getOrCreateVReg(*I.getValOperand());
3465
3466 unsigned Opcode = 0;
3467 switch (I.getOperation()) {
3468 default:
3469 return false;
3471 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
3472 break;
3473 case AtomicRMWInst::Add:
3474 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
3475 break;
3476 case AtomicRMWInst::Sub:
3477 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
3478 break;
3479 case AtomicRMWInst::And:
3480 Opcode = TargetOpcode::G_ATOMICRMW_AND;
3481 break;
3483 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
3484 break;
3485 case AtomicRMWInst::Or:
3486 Opcode = TargetOpcode::G_ATOMICRMW_OR;
3487 break;
3488 case AtomicRMWInst::Xor:
3489 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
3490 break;
3491 case AtomicRMWInst::Max:
3492 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
3493 break;
3494 case AtomicRMWInst::Min:
3495 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
3496 break;
3498 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
3499 break;
3501 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
3502 break;
3504 Opcode = TargetOpcode::G_ATOMICRMW_FADD;
3505 break;
3507 Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
3508 break;
3510 Opcode = TargetOpcode::G_ATOMICRMW_FMAX;
3511 break;
3513 Opcode = TargetOpcode::G_ATOMICRMW_FMIN;
3514 break;
3516 Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUM;
3517 break;
3519 Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUM;
3520 break;
3522 Opcode = TargetOpcode::G_ATOMICRMW_UINC_WRAP;
3523 break;
3525 Opcode = TargetOpcode::G_ATOMICRMW_UDEC_WRAP;
3526 break;
3528 Opcode = TargetOpcode::G_ATOMICRMW_USUB_COND;
3529 break;
3531 Opcode = TargetOpcode::G_ATOMICRMW_USUB_SAT;
3532 break;
3533 }
3534
3535 MIRBuilder.buildAtomicRMW(
3536 Opcode, Res, Addr, Val,
3537 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3538 Flags, MRI->getType(Val), getMemOpAlign(I),
3539 I.getAAMetadata(), nullptr, I.getSyncScopeID(),
3540 I.getOrdering()));
3541 return true;
3542}
3543
3544bool IRTranslator::translateFence(const User &U,
3545 MachineIRBuilder &MIRBuilder) {
3546 const FenceInst &Fence = cast<FenceInst>(U);
3547 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
3548 Fence.getSyncScopeID());
3549 return true;
3550}
3551
3552bool IRTranslator::translateFreeze(const User &U,
3553 MachineIRBuilder &MIRBuilder) {
3554 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
3555 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
3556
3557 assert(DstRegs.size() == SrcRegs.size() &&
3558 "Freeze with different source and destination type?");
3559
3560 for (unsigned I = 0; I < DstRegs.size(); ++I) {
3561 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
3562 }
3563
3564 return true;
3565}
3566
3567void IRTranslator::finishPendingPhis() {
3568#ifndef NDEBUG
3569 DILocationVerifier Verifier;
3570 GISelObserverWrapper WrapperObserver(&Verifier);
3571 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
3572#endif // ifndef NDEBUG
3573 for (auto &Phi : PendingPHIs) {
3574 const PHINode *PI = Phi.first;
3575 if (PI->getType()->isEmptyTy())
3576 continue;
3577 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
3578 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
3579 EntryBuilder->setDebugLoc(PI->getDebugLoc());
3580#ifndef NDEBUG
3581 Verifier.setCurrentInst(PI);
3582#endif // ifndef NDEBUG
3583
3584 SmallPtrSet<const MachineBasicBlock *, 16> SeenPreds;
3585 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
3586 auto IRPred = PI->getIncomingBlock(i);
3587 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
3588 for (auto *Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
3589 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
3590 continue;
3591 SeenPreds.insert(Pred);
3592 for (unsigned j = 0; j < ValRegs.size(); ++j) {
3593 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
3594 MIB.addUse(ValRegs[j]);
3595 MIB.addMBB(Pred);
3596 }
3597 }
3598 }
3599 }
3600}
3601
3602void IRTranslator::translateDbgValueRecord(Value *V, bool HasArgList,
3603 const DILocalVariable *Variable,
3604 const DIExpression *Expression,
3605 const DebugLoc &DL,
3606 MachineIRBuilder &MIRBuilder) {
3607 assert(Variable->isValidLocationForIntrinsic(DL) &&
3608 "Expected inlined-at fields to agree");
3609 // Act as if we're handling a debug intrinsic.
3610 MIRBuilder.setDebugLoc(DL);
3611
3612 if (!V || HasArgList) {
3613 // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
3614 // terminate any prior location.
3615 MIRBuilder.buildIndirectDbgValue(0, Variable, Expression);
3616 return;
3617 }
3618
3619 if (const auto *CI = dyn_cast<Constant>(V)) {
3620 MIRBuilder.buildConstDbgValue(*CI, Variable, Expression);
3621 return;
3622 }
3623
3624 if (auto *AI = dyn_cast<AllocaInst>(V);
3625 AI && AI->isStaticAlloca() && Expression->startsWithDeref()) {
3626 // If the value is an alloca and the expression starts with a
3627 // dereference, track a stack slot instead of a register, as registers
3628 // may be clobbered.
3629 auto ExprOperands = Expression->getElements();
3630 auto *ExprDerefRemoved =
3631 DIExpression::get(AI->getContext(), ExprOperands.drop_front());
3632 MIRBuilder.buildFIDbgValue(getOrCreateFrameIndex(*AI), Variable,
3633 ExprDerefRemoved);
3634 return;
3635 }
3636 if (translateIfEntryValueArgument(false, V, Variable, Expression, DL,
3637 MIRBuilder))
3638 return;
3639 for (Register Reg : getOrCreateVRegs(*V)) {
3640 // FIXME: This does not handle register-indirect values at offset 0. The
3641 // direct/indirect thing shouldn't really be handled by something as
3642 // implicit as reg+noreg vs reg+imm in the first place, but it seems
3643 // pretty baked in right now.
3644 MIRBuilder.buildDirectDbgValue(Reg, Variable, Expression);
3645 }
3646}
3647
3648void IRTranslator::translateDbgDeclareRecord(Value *Address, bool HasArgList,
3649 const DILocalVariable *Variable,
3650 const DIExpression *Expression,
3651 const DebugLoc &DL,
3652 MachineIRBuilder &MIRBuilder) {
3653 if (!Address || isa<UndefValue>(Address)) {
3654 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *Variable << "\n");
3655 return;
3656 }
3657
3658 assert(Variable->isValidLocationForIntrinsic(DL) &&
3659 "Expected inlined-at fields to agree");
3660 auto AI = dyn_cast<AllocaInst>(Address);
3661 if (AI && AI->isStaticAlloca()) {
3662 // Static allocas are tracked at the MF level, no need for DBG_VALUE
3663 // instructions (in fact, they get ignored if they *do* exist).
3664 MF->setVariableDbgInfo(Variable, Expression,
3665 getOrCreateFrameIndex(*AI), DL);
3666 return;
3667 }
3668
3669 if (translateIfEntryValueArgument(true, Address, Variable,
3670 Expression, DL,
3671 MIRBuilder))
3672 return;
3673
3674 // A dbg.declare describes the address of a source variable, so lower it
3675 // into an indirect DBG_VALUE.
3676 MIRBuilder.setDebugLoc(DL);
3677 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), Variable,
3678 Expression);
3679}
3680
3681void IRTranslator::translateDbgInfo(const Instruction &Inst,
3682 MachineIRBuilder &MIRBuilder) {
3683 for (DbgRecord &DR : Inst.getDbgRecordRange()) {
3684 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3685 MIRBuilder.setDebugLoc(DLR->getDebugLoc());
3686 assert(DLR->getLabel() && "Missing label");
3687 assert(DLR->getLabel()->isValidLocationForIntrinsic(
3688 MIRBuilder.getDebugLoc()) &&
3689 "Expected inlined-at fields to agree");
3690 MIRBuilder.buildDbgLabel(DLR->getLabel());
3691 continue;
3692 }
3693 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3694 const DILocalVariable *Variable = DVR.getVariable();
3695 const DIExpression *Expression = DVR.getExpression();
3696 Value *V = DVR.getVariableLocationOp(0);
3697 if (DVR.isDbgDeclare())
3698 translateDbgDeclareRecord(V, DVR.hasArgList(), Variable, Expression,
3699 DVR.getDebugLoc(), MIRBuilder);
3700 else
3701 translateDbgValueRecord(V, DVR.hasArgList(), Variable, Expression,
3702 DVR.getDebugLoc(), MIRBuilder);
3703 }
3704}
3705
3706bool IRTranslator::translate(const Instruction &Inst) {
3707 CurBuilder->setDebugLoc(Inst.getDebugLoc());
3708 CurBuilder->setPCSections(Inst.getMetadata(LLVMContext::MD_pcsections));
3709 CurBuilder->setMMRAMetadata(Inst.getMetadata(LLVMContext::MD_mmra));
3710
3711 if (TLI->fallBackToDAGISel(Inst))
3712 return false;
3713
3714 switch (Inst.getOpcode()) {
3715#define HANDLE_INST(NUM, OPCODE, CLASS) \
3716 case Instruction::OPCODE: \
3717 return translate##OPCODE(Inst, *CurBuilder.get());
3718#include "llvm/IR/Instruction.def"
3719 default:
3720 return false;
3721 }
3722}
3723
3724bool IRTranslator::translate(const Constant &C, Register Reg) {
3725 // We only emit constants into the entry block from here. To prevent jumpy
3726 // debug behaviour remove debug line.
3727 if (auto CurrInstDL = CurBuilder->getDL())
3728 EntryBuilder->setDebugLoc(DebugLoc());
3729
3730 if (auto CI = dyn_cast<ConstantInt>(&C)) {
3731 // buildConstant expects a to-be-splatted scalar ConstantInt.
3732 if (isa<VectorType>(CI->getType()))
3733 CI = ConstantInt::get(CI->getContext(), CI->getValue());
3734 EntryBuilder->buildConstant(Reg, *CI);
3735 } else if (auto CF = dyn_cast<ConstantFP>(&C)) {
3736 // buildFConstant expects a to-be-splatted scalar ConstantFP.
3737 if (isa<VectorType>(CF->getType()))
3738 CF = ConstantFP::get(CF->getContext(), CF->getValue());
3739 EntryBuilder->buildFConstant(Reg, *CF);
3740 } else if (isa<UndefValue>(C))
3741 EntryBuilder->buildUndef(Reg);
3742 else if (isa<ConstantPointerNull>(C))
3743 EntryBuilder->buildConstant(Reg, 0);
3744 else if (auto GV = dyn_cast<GlobalValue>(&C))
3745 EntryBuilder->buildGlobalValue(Reg, GV);
3746 else if (auto CPA = dyn_cast<ConstantPtrAuth>(&C)) {
3747 Register Addr = getOrCreateVReg(*CPA->getPointer());
3748 Register AddrDisc = getOrCreateVReg(*CPA->getAddrDiscriminator());
3749 EntryBuilder->buildConstantPtrAuth(Reg, CPA, Addr, AddrDisc);
3750 } else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
3751 Constant &Elt = *CAZ->getElementValue(0u);
3752 if (isa<ScalableVectorType>(CAZ->getType())) {
3753 EntryBuilder->buildSplatVector(Reg, getOrCreateVReg(Elt));
3754 return true;
3755 }
3756 // Return the scalar if it is a <1 x Ty> vector.
3757 unsigned NumElts = CAZ->getElementCount().getFixedValue();
3758 if (NumElts == 1)
3759 return translateCopy(C, Elt, *EntryBuilder);
3760 // All elements are zero so we can just use the first one.
3761 EntryBuilder->buildSplatBuildVector(Reg, getOrCreateVReg(Elt));
3762 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
3763 // Return the scalar if it is a <1 x Ty> vector.
3764 if (CV->getNumElements() == 1)
3765 return translateCopy(C, *CV->getElementAsConstant(0), *EntryBuilder);
3767 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
3768 Constant &Elt = *CV->getElementAsConstant(i);
3769 Ops.push_back(getOrCreateVReg(Elt));
3770 }
3771 EntryBuilder->buildBuildVector(Reg, Ops);
3772 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
3773 switch(CE->getOpcode()) {
3774#define HANDLE_INST(NUM, OPCODE, CLASS) \
3775 case Instruction::OPCODE: \
3776 return translate##OPCODE(*CE, *EntryBuilder.get());
3777#include "llvm/IR/Instruction.def"
3778 default:
3779 return false;
3780 }
3781 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
3782 if (CV->getNumOperands() == 1)
3783 return translateCopy(C, *CV->getOperand(0), *EntryBuilder);
3785 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
3786 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
3787 }
3788 EntryBuilder->buildBuildVector(Reg, Ops);
3789 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
3790 EntryBuilder->buildBlockAddress(Reg, BA);
3791 } else
3792 return false;
3793
3794 return true;
3795}
3796
3797bool IRTranslator::finalizeBasicBlock(const BasicBlock &BB,
3799 for (auto &BTB : SL->BitTestCases) {
3800 // Emit header first, if it wasn't already emitted.
3801 if (!BTB.Emitted)
3802 emitBitTestHeader(BTB, BTB.Parent);
3803
3804 BranchProbability UnhandledProb = BTB.Prob;
3805 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
3806 UnhandledProb -= BTB.Cases[j].ExtraProb;
3807 // Set the current basic block to the mbb we wish to insert the code into
3808 MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
3809 // If all cases cover a contiguous range, it is not necessary to jump to
3810 // the default block after the last bit test fails. This is because the
3811 // range check during bit test header creation has guaranteed that every
3812 // case here doesn't go outside the range. In this case, there is no need
3813 // to perform the last bit test, as it will always be true. Instead, make
3814 // the second-to-last bit-test fall through to the target of the last bit
3815 // test, and delete the last bit test.
3816
3817 MachineBasicBlock *NextMBB;
3818 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3819 // Second-to-last bit-test with contiguous range: fall through to the
3820 // target of the final bit test.
3821 NextMBB = BTB.Cases[j + 1].TargetBB;
3822 } else if (j + 1 == ej) {
3823 // For the last bit test, fall through to Default.
3824 NextMBB = BTB.Default;
3825 } else {
3826 // Otherwise, fall through to the next bit test.
3827 NextMBB = BTB.Cases[j + 1].ThisBB;
3828 }
3829
3830 emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
3831
3832 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3833 // We need to record the replacement phi edge here that normally
3834 // happens in emitBitTestCase before we delete the case, otherwise the
3835 // phi edge will be lost.
3836 addMachineCFGPred({BTB.Parent->getBasicBlock(),
3837 BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
3838 MBB);
3839 // Since we're not going to use the final bit test, remove it.
3840 BTB.Cases.pop_back();
3841 break;
3842 }
3843 }
3844 // This is "default" BB. We have two jumps to it. From "header" BB and from
3845 // last "case" BB, unless the latter was skipped.
3846 CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
3847 BTB.Default->getBasicBlock()};
3848 addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
3849 if (!BTB.ContiguousRange) {
3850 addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
3851 }
3852 }
3853 SL->BitTestCases.clear();
3854
3855 for (auto &JTCase : SL->JTCases) {
3856 // Emit header first, if it wasn't already emitted.
3857 if (!JTCase.first.Emitted)
3858 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
3859
3860 emitJumpTable(JTCase.second, JTCase.second.MBB);
3861 }
3862 SL->JTCases.clear();
3863
3864 for (auto &SwCase : SL->SwitchCases)
3865 emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
3866 SL->SwitchCases.clear();
3867
3868 // Check if we need to generate stack-protector guard checks.
3869 StackProtector &SP = getAnalysis<StackProtector>();
3870 if (SP.shouldEmitSDCheck(BB)) {
3871 bool FunctionBasedInstrumentation =
3872 TLI->getSSPStackGuardCheck(*MF->getFunction().getParent());
3873 SPDescriptor.initialize(&BB, &MBB, FunctionBasedInstrumentation);
3874 }
3875 // Handle stack protector.
3876 if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
3877 LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n");
3878 return false;
3879 } else if (SPDescriptor.shouldEmitStackProtector()) {
3880 MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB();
3881 MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB();
3882
3883 // Find the split point to split the parent mbb. At the same time copy all
3884 // physical registers used in the tail of parent mbb into virtual registers
3885 // before the split point and back into physical registers after the split
3886 // point. This prevents us needing to deal with Live-ins and many other
3887 // register allocation issues caused by us splitting the parent mbb. The
3888 // register allocator will clean up said virtual copies later on.
3890 ParentMBB, *MF->getSubtarget().getInstrInfo());
3891
3892 // Splice the terminator of ParentMBB into SuccessMBB.
3893 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
3894 ParentMBB->end());
3895
3896 // Add compare/jump on neq/jump to the parent BB.
3897 if (!emitSPDescriptorParent(SPDescriptor, ParentMBB))
3898 return false;
3899
3900 // CodeGen Failure MBB if we have not codegened it yet.
3901 MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB();
3902 if (FailureMBB->empty()) {
3903 if (!emitSPDescriptorFailure(SPDescriptor, FailureMBB))
3904 return false;
3905 }
3906
3907 // Clear the Per-BB State.
3908 SPDescriptor.resetPerBBState();
3909 }
3910 return true;
3911}
3912
3913bool IRTranslator::emitSPDescriptorParent(StackProtectorDescriptor &SPD,
3914 MachineBasicBlock *ParentBB) {
3915 CurBuilder->setInsertPt(*ParentBB, ParentBB->end());
3916 // First create the loads to the guard/stack slot for the comparison.
3917 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
3918 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
3919 LLT PtrMemTy = getLLTForMVT(TLI->getPointerMemTy(*DL));
3920
3921 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3922 int FI = MFI.getStackProtectorIndex();
3923
3924 Register Guard;
3925 Register StackSlotPtr = CurBuilder->buildFrameIndex(PtrTy, FI).getReg(0);
3926 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3927 Align Align = DL->getPrefTypeAlign(PointerType::getUnqual(M.getContext()));
3928
3929 // Generate code to load the content of the guard slot.
3930 Register GuardVal =
3931 CurBuilder
3932 ->buildLoad(PtrMemTy, StackSlotPtr,
3933 MachinePointerInfo::getFixedStack(*MF, FI), Align,
3935 .getReg(0);
3936
3937 if (TLI->useStackGuardXorFP()) {
3938 LLVM_DEBUG(dbgs() << "Stack protector xor'ing with FP not yet implemented");
3939 return false;
3940 }
3941
3942 // Retrieve guard check function, nullptr if instrumentation is inlined.
3943 if (const Function *GuardCheckFn = TLI->getSSPStackGuardCheck(M)) {
3944 // This path is currently untestable on GlobalISel, since the only platform
3945 // that needs this seems to be Windows, and we fall back on that currently.
3946 // The code still lives here in case that changes.
3947 // Silence warning about unused variable until the code below that uses
3948 // 'GuardCheckFn' is enabled.
3949 (void)GuardCheckFn;
3950 return false;
3951#if 0
3952 // The target provides a guard check function to validate the guard value.
3953 // Generate a call to that function with the content of the guard slot as
3954 // argument.
3955 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3956 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3957 ISD::ArgFlagsTy Flags;
3958 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
3959 Flags.setInReg();
3960 CallLowering::ArgInfo GuardArgInfo(
3961 {GuardVal, FnTy->getParamType(0), {Flags}});
3962
3963 CallLowering::CallLoweringInfo Info;
3964 Info.OrigArgs.push_back(GuardArgInfo);
3965 Info.CallConv = GuardCheckFn->getCallingConv();
3966 Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0);
3967 Info.OrigRet = {Register(), FnTy->getReturnType()};
3968 if (!CLI->lowerCall(MIRBuilder, Info)) {
3969 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n");
3970 return false;
3971 }
3972 return true;
3973#endif
3974 }
3975
3976 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3977 // Otherwise, emit a volatile load to retrieve the stack guard value.
3978 if (TLI->useLoadStackGuardNode(*ParentBB->getBasicBlock()->getModule())) {
3979 Guard =
3980 MRI->createGenericVirtualRegister(LLT::scalar(PtrTy.getSizeInBits()));
3981 getStackGuard(Guard, *CurBuilder);
3982 } else {
3983 // TODO: test using android subtarget when we support @llvm.thread.pointer.
3984 const Value *IRGuard = TLI->getSDagStackGuard(M);
3985 Register GuardPtr = getOrCreateVReg(*IRGuard);
3986
3987 Guard = CurBuilder
3988 ->buildLoad(PtrMemTy, GuardPtr,
3989 MachinePointerInfo::getFixedStack(*MF, FI), Align,
3992 .getReg(0);
3993 }
3994
3995 // Perform the comparison.
3996 auto Cmp =
3997 CurBuilder->buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Guard, GuardVal);
3998 // If the guard/stackslot do not equal, branch to failure MBB.
3999 CurBuilder->buildBrCond(Cmp, *SPD.getFailureMBB());
4000 // Otherwise branch to success MBB.
4001 CurBuilder->buildBr(*SPD.getSuccessMBB());
4002 return true;
4003}
4004
4005bool IRTranslator::emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
4006 MachineBasicBlock *FailureBB) {
4007 CurBuilder->setInsertPt(*FailureBB, FailureBB->end());
4008
4009 const RTLIB::Libcall Libcall = RTLIB::STACKPROTECTOR_CHECK_FAIL;
4010 const char *Name = TLI->getLibcallName(Libcall);
4011
4012 CallLowering::CallLoweringInfo Info;
4013 Info.CallConv = TLI->getLibcallCallingConv(Libcall);
4014 Info.Callee = MachineOperand::CreateES(Name);
4015 Info.OrigRet = {Register(), Type::getVoidTy(MF->getFunction().getContext()),
4016 0};
4017 if (!CLI->lowerCall(*CurBuilder, Info)) {
4018 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n");
4019 return false;
4020 }
4021
4022 // Emit a trap instruction if we are required to do so.
4023 const TargetOptions &TargetOpts = TLI->getTargetMachine().Options;
4024 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
4025 CurBuilder->buildInstr(TargetOpcode::G_TRAP);
4026
4027 return true;
4028}
4029
4030void IRTranslator::finalizeFunction() {
4031 // Release the memory used by the different maps we
4032 // needed during the translation.
4033 PendingPHIs.clear();
4034 VMap.reset();
4035 FrameIndices.clear();
4036 MachinePreds.clear();
4037 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
4038 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
4039 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
4040 EntryBuilder.reset();
4041 CurBuilder.reset();
4042 FuncInfo.clear();
4043 SPDescriptor.resetPerFunctionState();
4044}
4045
4046/// Returns true if a BasicBlock \p BB within a variadic function contains a
4047/// variadic musttail call.
4048static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
4049 if (!IsVarArg)
4050 return false;
4051
4052 // Walk the block backwards, because tail calls usually only appear at the end
4053 // of a block.
4054 return llvm::any_of(llvm::reverse(BB), [](const Instruction &I) {
4055 const auto *CI = dyn_cast<CallInst>(&I);
4056 return CI && CI->isMustTailCall();
4057 });
4058}
4059
4061 MF = &CurMF;
4062 const Function &F = MF->getFunction();
4065 // Set the CSEConfig and run the analysis.
4066 GISelCSEInfo *CSEInfo = nullptr;
4068 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
4070 : TPC->isGISelCSEEnabled();
4071 TLI = MF->getSubtarget().getTargetLowering();
4072
4073 if (EnableCSE) {
4074 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
4075 CSEInfo = &Wrapper.get(TPC->getCSEConfig());
4076 EntryBuilder->setCSEInfo(CSEInfo);
4077 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
4078 CurBuilder->setCSEInfo(CSEInfo);
4079 } else {
4080 EntryBuilder = std::make_unique<MachineIRBuilder>();
4081 CurBuilder = std::make_unique<MachineIRBuilder>();
4082 }
4083 CLI = MF->getSubtarget().getCallLowering();
4084 CurBuilder->setMF(*MF);
4085 EntryBuilder->setMF(*MF);
4086 MRI = &MF->getRegInfo();
4087 DL = &F.getDataLayout();
4088 ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
4089 const TargetMachine &TM = MF->getTarget();
4090 TM.resetTargetOptions(F);
4091 EnableOpts = OptLevel != CodeGenOptLevel::None && !skipFunction(F);
4092 FuncInfo.MF = MF;
4093 if (EnableOpts) {
4094 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4095 FuncInfo.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
4096 } else {
4097 AA = nullptr;
4098 FuncInfo.BPI = nullptr;
4099 }
4100
4101 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
4102 MF->getFunction());
4103 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
4104 FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
4105
4106 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
4107 SL->init(*TLI, TM, *DL);
4108
4109 assert(PendingPHIs.empty() && "stale PHIs");
4110
4111 // Targets which want to use big endian can enable it using
4112 // enableBigEndian()
4113 if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
4114 // Currently we don't properly handle big endian code.
4115 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4116 F.getSubprogram(), &F.getEntryBlock());
4117 R << "unable to translate in big endian mode";
4118 reportTranslationError(*MF, *TPC, *ORE, R);
4119 return false;
4120 }
4121
4122 // Release the per-function state when we return, whether we succeeded or not.
4123 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
4124
4125 // Setup a separate basic-block for the arguments and constants
4126 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
4127 MF->push_back(EntryBB);
4128 EntryBuilder->setMBB(*EntryBB);
4129
4130 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHIIt()->getDebugLoc();
4131 SwiftError.setFunction(CurMF);
4132 SwiftError.createEntriesInEntryBlock(DbgLoc);
4133
4134 bool IsVarArg = F.isVarArg();
4135 bool HasMustTailInVarArgFn = false;
4136
4137 // Create all blocks, in IR order, to preserve the layout.
4138 FuncInfo.MBBMap.resize(F.getMaxBlockNumber());
4139 for (const BasicBlock &BB: F) {
4140 auto *&MBB = FuncInfo.MBBMap[BB.getNumber()];
4141
4142 MBB = MF->CreateMachineBasicBlock(&BB);
4143 MF->push_back(MBB);
4144
4145 if (BB.hasAddressTaken())
4146 MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
4147
4148 if (!HasMustTailInVarArgFn)
4149 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
4150 }
4151
4152 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
4153
4154 // Make our arguments/constants entry block fallthrough to the IR entry block.
4155 EntryBB->addSuccessor(&getMBB(F.front()));
4156
4157 if (CLI->fallBackToDAGISel(*MF)) {
4158 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4159 F.getSubprogram(), &F.getEntryBlock());
4160 R << "unable to lower function: "
4161 << ore::NV("Prototype", F.getFunctionType());
4162 reportTranslationError(*MF, *TPC, *ORE, R);
4163 return false;
4164 }
4165
4166 // Lower the actual args into this basic block.
4167 SmallVector<ArrayRef<Register>, 8> VRegArgs;
4168 for (const Argument &Arg: F.args()) {
4169 if (DL->getTypeStoreSize(Arg.getType()).isZero())
4170 continue; // Don't handle zero sized types.
4171 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
4172 VRegArgs.push_back(VRegs);
4173
4174 if (Arg.hasSwiftErrorAttr()) {
4175 assert(VRegs.size() == 1 && "Too many vregs for Swift error");
4176 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
4177 }
4178 }
4179
4180 if (!CLI->lowerFormalArguments(*EntryBuilder, F, VRegArgs, FuncInfo)) {
4181 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4182 F.getSubprogram(), &F.getEntryBlock());
4183 R << "unable to lower arguments: "
4184 << ore::NV("Prototype", F.getFunctionType());
4185 reportTranslationError(*MF, *TPC, *ORE, R);
4186 return false;
4187 }
4188
4189 // Need to visit defs before uses when translating instructions.
4190 GISelObserverWrapper WrapperObserver;
4191 if (EnableCSE && CSEInfo)
4192 WrapperObserver.addObserver(CSEInfo);
4193 {
4195#ifndef NDEBUG
4196 DILocationVerifier Verifier;
4197 WrapperObserver.addObserver(&Verifier);
4198#endif // ifndef NDEBUG
4199 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
4200 for (const BasicBlock *BB : RPOT) {
4201 MachineBasicBlock &MBB = getMBB(*BB);
4202 // Set the insertion point of all the following translations to
4203 // the end of this basic block.
4204 CurBuilder->setMBB(MBB);
4205 HasTailCall = false;
4206 for (const Instruction &Inst : *BB) {
4207 // If we translated a tail call in the last step, then we know
4208 // everything after the call is either a return, or something that is
4209 // handled by the call itself. (E.g. a lifetime marker or assume
4210 // intrinsic.) In this case, we should stop translating the block and
4211 // move on.
4212 if (HasTailCall)
4213 break;
4214#ifndef NDEBUG
4215 Verifier.setCurrentInst(&Inst);
4216#endif // ifndef NDEBUG
4217
4218 // Translate any debug-info attached to the instruction.
4219 translateDbgInfo(Inst, *CurBuilder);
4220
4221 if (translate(Inst))
4222 continue;
4223
4224 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4225 Inst.getDebugLoc(), BB);
4226 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
4227
4228 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
4229 std::string InstStrStorage;
4230 raw_string_ostream InstStr(InstStrStorage);
4231 InstStr << Inst;
4232
4233 R << ": '" << InstStrStorage << "'";
4234 }
4235
4236 reportTranslationError(*MF, *TPC, *ORE, R);
4237 return false;
4238 }
4239
4240 if (!finalizeBasicBlock(*BB, MBB)) {
4241 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4242 BB->getTerminator()->getDebugLoc(), BB);
4243 R << "unable to translate basic block";
4244 reportTranslationError(*MF, *TPC, *ORE, R);
4245 return false;
4246 }
4247 }
4248#ifndef NDEBUG
4249 WrapperObserver.removeObserver(&Verifier);
4250#endif
4251 }
4252
4253 finishPendingPhis();
4254
4255 SwiftError.propagateVRegs();
4256
4257 // Merge the argument lowering and constants block with its single
4258 // successor, the LLVM-IR entry block. We want the basic block to
4259 // be maximal.
4260 assert(EntryBB->succ_size() == 1 &&
4261 "Custom BB used for lowering should have only one successor");
4262 // Get the successor of the current entry block.
4263 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
4264 assert(NewEntryBB.pred_size() == 1 &&
4265 "LLVM-IR entry block has a predecessor!?");
4266 // Move all the instruction from the current entry block to the
4267 // new entry block.
4268 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
4269 EntryBB->end());
4270
4271 // Update the live-in information for the new entry block.
4272 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
4273 NewEntryBB.addLiveIn(LiveIn);
4274 NewEntryBB.sortUniqueLiveIns();
4275
4276 // Get rid of the now empty basic block.
4277 EntryBB->removeSuccessor(&NewEntryBB);
4278 MF->remove(EntryBB);
4279 MF->deleteMachineBasicBlock(EntryBB);
4280
4281 assert(&MF->front() == &NewEntryBB &&
4282 "New entry wasn't next in the list of basic block!");
4283
4284 // Initialize stack protector information.
4286 SP.copyToMachineFrameInfo(MF->getFrameInfo());
4287
4288 return false;
4289}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
Provides analysis for continuously CSEing during GISel passes.
This file implements a version of MachineIRBuilder which CSEs insts within a MachineBasicBlock.
This file describes how to lower LLVM calls to machine code calls.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This contains common code to allow clients to notify changes to machine instr.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR static false void reportTranslationError(MachineFunction &MF, const TargetPassConfig &TPC, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R)
static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB)
Returns true if a BasicBlock BB within a variadic function contains a variadic musttail call.
static bool containsBF16Type(const User &U)
static unsigned getConvOpcode(Intrinsic::ID ID)
static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL)
static unsigned getConstrainedOpcode(Intrinsic::ID ID)
IRTranslator LLVM IR MI
static cl::opt< bool > EnableCSEInIRTranslator("enable-cse-in-irtranslator", cl::desc("Should enable CSE in irtranslator"), cl::Optional, cl::init(false))
static bool isValInBlock(const Value *V, const BasicBlock *BB)
static bool isSwiftError(const Value *V)
This file declares the IRTranslator pass.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This file describes how to lower LLVM inline asm to machine code INLINEASM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Implement a low-level type suitable for MachineInstr level instruction selection.
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Machine Check Debug Module
This file declares the MachineIRBuilder class.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
uint64_t High
OptimizedStructLayoutField Field
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1033
an instruction to allocate memory on the stack
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
const Value * getArraySize() const
Get the number of elements allocated.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
iterator end() const
Definition ArrayRef.h:136
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:142
An immutable pass that tracks lazily created AssumptionCache objects.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:690
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Legacy analysis pass which computes BlockFrequencyInfo.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
Legacy analysis pass which computes BranchProbabilityInfo.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static BranchProbability getZero()
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
bool isFPPredicate() const
Definition InstrTypes.h:782
bool isIntPredicate() const
Definition InstrTypes.h:783
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:214
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:154
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
ArrayRef< uint64_t > getElements() const
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this label.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Value * getAddress() const
DILabel * getLabel() const
DebugLoc getDebugLoc() const
Value * getValue(unsigned OpIdx=0) const
DILocalVariable * getVariable() const
DIExpression * getExpression() const
DIExpression * getExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DILocalVariable * getVariable() const
A debug info location.
Definition DebugLoc.h:124
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:803
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:188
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:703
Constant * getPersonalityFn() const
Get the personality function associated with this function.
const Function & getFunction() const
Definition Function.h:164
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:249
The actual analysis pass wrapper.
Definition CSEInfo.h:229
Simple wrapper that does the following.
Definition CSEInfo.h:211
The CSE Analysis object.
Definition CSEInfo.h:71
Abstract class that contains various methods for clients to notify about changes.
Simple wrapper observer that takes several observers, and calls each one for each event.
void removeObserver(GISelChangeObserver *O)
void addObserver(GISelChangeObserver *O)
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
bool isTailCall(const MachineInstr &MI) const override
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
IRTranslator(CodeGenOptLevel OptLevel=CodeGenOptLevel::None)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool lowerInlineAsm(MachineIRBuilder &MIRBuilder, const CallBase &CB, std::function< ArrayRef< Register >(const Value &Val)> GetOrCreateVRegs) const
Lower the given inline asm call instruction GetOrCreateVRegs is a callback to materialize a register ...
This instruction inserts a struct field of array element value into an aggregate value.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Value * getPointerOperand()
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
static LocationSize precise(uint64_t Value)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void push_back(MachineInstr *MI)
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
int getStackProtectorIndex() const
Return the index for the stack protector object.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
Helper class to build MachineInstr.
MachineInstrBuilder buildFPTOUI_SAT(const DstOp &Dst, const SrcOp &Src0)
Build and insert Res = G_FPTOUI_SAT Src0.
MachineInstrBuilder buildFMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildFreeze(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_FREEZE Src.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
MachineInstrBuilder buildModf(const DstOp &Fract, const DstOp &Int, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Fract, Int = G_FMODF Src.
LLVMContext & getContext() const
MachineInstrBuilder buildAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ADD Op0, Op1.
MachineInstrBuilder buildUndef(const DstOp &Res)
Build and insert Res = IMPLICIT_DEF.
MachineInstrBuilder buildResetFPMode()
Build and insert G_RESET_FPMODE.
MachineInstrBuilder buildFPExt(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FPEXT Op.
MachineInstrBuilder buildFPTOSI_SAT(const DstOp &Dst, const SrcOp &Src0)
Build and insert Res = G_FPTOSI_SAT Src0.
MachineInstrBuilder buildUCmp(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert a Res = G_UCMP Op0, Op1.
MachineInstrBuilder buildJumpTable(const LLT PtrTy, unsigned JTI)
Build and insert Res = G_JUMP_TABLE JTI.
MachineInstrBuilder buildGetRounding(const DstOp &Dst)
Build and insert Dst = G_GET_ROUNDING.
MachineInstrBuilder buildSCmp(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert a Res = G_SCMP Op0, Op1.
MachineInstrBuilder buildFence(unsigned Ordering, unsigned Scope)
Build and insert G_FENCE Ordering, Scope.
MachineInstrBuilder buildSelect(const DstOp &Res, const SrcOp &Tst, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_SELECT Tst, Op0, Op1.
MachineInstrBuilder buildFMA(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, const SrcOp &Src2, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FMA Op0, Op1, Op2.
MachineInstrBuilder buildMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_MUL Op0, Op1.
MachineInstrBuilder buildInsertSubvector(const DstOp &Res, const SrcOp &Src0, const SrcOp &Src1, unsigned Index)
Build and insert Res = G_INSERT_SUBVECTOR Src0, Src1, Idx.
MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1)
Build and insert Res = G_AND Op0, Op1.
MachineInstrBuilder buildCast(const DstOp &Dst, const SrcOp &Src)
Build and insert an appropriate cast between two registers of equal size.
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
MachineInstrBuilder buildSExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_SEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
MachineInstrBuilder buildAtomicRMW(unsigned Opcode, const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO)
Build and insert OldValRes<def> = G_ATOMICRMW_<Opcode> Addr, Val, MMO.
MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_SUB Op0, Op1.
MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, ArrayRef< Register > Res, bool HasSideEffects, bool isConvergent)
Build and insert a G_INTRINSIC instruction.
MachineInstrBuilder buildVScale(const DstOp &Res, unsigned MinElts)
Build and insert Res = G_VSCALE MinElts.
MachineInstrBuilder buildSplatBuildVector(const DstOp &Res, const SrcOp &Src)
Build and insert Res = G_BUILD_VECTOR with Src replicated to fill the number of elements.
MachineInstrBuilder buildSetFPMode(const SrcOp &Src)
Build and insert G_SET_FPMODE Src.
MachineInstrBuilder buildIndirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in me...
MachineInstrBuilder buildBuildVector(const DstOp &Res, ArrayRef< Register > Ops)
Build and insert Res = G_BUILD_VECTOR Op0, ...
MachineInstrBuilder buildConstDbgValue(const Constant &C, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instructions specifying that Variable is given by C (suitably modified b...
MachineInstrBuilder buildBrCond(const SrcOp &Tst, MachineBasicBlock &Dest)
Build and insert G_BRCOND Tst, Dest.
std::optional< MachineInstrBuilder > materializeObjectPtrOffset(Register &Res, Register Op0, const LLT ValueTy, uint64_t Value)
Materialize and insert an instruction with appropriate flags for addressing some offset of an object,...
MachineInstrBuilder buildSetRounding(const SrcOp &Src)
Build and insert G_SET_ROUNDING.
MachineInstrBuilder buildExtractVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
MachineInstrBuilder buildZExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ZEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
MachineInstrBuilder buildExtractVectorElementConstant(const DstOp &Res, const SrcOp &Val, const int Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineInstrBuilder buildDirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in Re...
MachineInstrBuilder buildDbgLabel(const MDNode *Label)
Build and insert a DBG_LABEL instructions specifying that Label is given.
MachineInstrBuilder buildBrJT(Register TablePtr, unsigned JTI, Register IndexReg)
Build and insert G_BRJT TablePtr, JTI, IndexReg.
MachineInstrBuilder buildDynStackAlloc(const DstOp &Res, const SrcOp &Size, Align Alignment)
Build and insert Res = G_DYN_STACKALLOC Size, Align.
MachineInstrBuilder buildFIDbgValue(int FI, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in th...
MachineInstrBuilder buildResetFPEnv()
Build and insert G_RESET_FPENV.
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
MachineInstrBuilder buildInsertVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Elt, const SrcOp &Idx)
Build and insert Res = G_INSERT_VECTOR_ELT Val, Elt, Idx.
MachineInstrBuilder buildAtomicCmpXchgWithSuccess(const DstOp &OldValRes, const DstOp &SuccessRes, const SrcOp &Addr, const SrcOp &CmpVal, const SrcOp &NewVal, MachineMemOperand &MMO)
Build and insert OldValRes<def>, SuccessRes<def> = / G_ATOMIC_CMPXCHG_WITH_SUCCESS Addr,...
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
const DebugLoc & getDebugLoc()
Get the current instruction's debug location.
MachineInstrBuilder buildTrap(bool Debug=false)
Build and insert G_TRAP or G_DEBUGTRAP.
MachineInstrBuilder buildFFrexp(const DstOp &Fract, const DstOp &Exp, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Fract, Exp = G_FFREXP Src.
MachineInstrBuilder buildFPTrunc(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FPTRUNC Op.
MachineInstrBuilder buildFSincos(const DstOp &Sin, const DstOp &Cos, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Sin, Cos = G_FSINCOS Src.
MachineInstrBuilder buildShuffleVector(const DstOp &Res, const SrcOp &Src1, const SrcOp &Src2, ArrayRef< int > Mask)
Build and insert Res = G_SHUFFLE_VECTOR Src1, Src2, Mask.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
MachineInstrBuilder buildPrefetch(const SrcOp &Addr, unsigned RW, unsigned Locality, unsigned CacheType, MachineMemOperand &MMO)
Build and insert G_PREFETCH Addr, RW, Locality, CacheType.
MachineInstrBuilder buildExtractSubvector(const DstOp &Res, const SrcOp &Src, unsigned Index)
Build and insert Res = G_EXTRACT_SUBVECTOR Src, Idx0.
const DataLayout & getDataLayout() const
MachineInstrBuilder buildBrIndirect(Register Tgt)
Build and insert G_BRINDIRECT Tgt.
MachineInstrBuilder buildSplatVector(const DstOp &Res, const SrcOp &Val)
Build and insert Res = G_SPLAT_VECTOR Val.
MachineInstrBuilder buildStepVector(const DstOp &Res, unsigned Step)
Build and insert Res = G_STEP_VECTOR Step.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
MachineInstrBuilder buildFCmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_FCMP PredOp0, Op1.
MachineInstrBuilder buildFAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FADD Op0, Op1.
MachineInstrBuilder buildSetFPEnv(const SrcOp &Src)
Build and insert G_SET_FPENV Src.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addFPImm(const ConstantFP *Val) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
LLVM_ABI void copyIRFlags(const Instruction &I)
Copy all flags to MachineInst MIFlags.
static LLVM_ABI uint32_t copyFlagsFromInstruction(const Instruction &I)
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
The optimization diagnostic interface.
Diagnostic information for missed-optimization remarks.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Class to install both of the above.
Wrapper class representing virtual and physical registers.
Definition Register.h:19
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
Primary interface to the complete machine description for the target machine.
unsigned NoTrapAfterNoreturn
Do not emit a trap instruction for 'unreachable' IR instructions behind noreturn calls,...
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
Target-Independent Code Generator Pass Configuration Options.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:181
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:297
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:281
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:701
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1099
constexpr bool isZero() const
Definition TypeSize.h:154
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ Libcall
The operation should be implemented as a call to some kind of runtime support library.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Undef
Value of the register doesn't matter.
Offsets
Offsets in bytes from the start of the input buffer.
void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
std::vector< CaseCluster > CaseClusterVector
@ CC_Range
A cluster of adjacent case labels with the same destination, or just one case.
@ CC_JumpTable
A cluster of cases suitable for jump table lowering.
@ CC_BitTests
A cluster of cases suitable for bit test lowering.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
CaseClusterVector::iterator CaseClusterIt
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:48
initializer< Ty > init(const Ty &Val)
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2472
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:293
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
LLVM_ABI void diagnoseDontCall(const CallInst &CI)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
gep_type_iterator gep_type_end(const User *GEP)
MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:154
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:202
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:252
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:147
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
void computeValueLLTs(const DataLayout &DL, Type &Ty, SmallVectorImpl< LLT > &ValueTys, SmallVectorImpl< uint64_t > *Offsets=nullptr, uint64_t StartingOffset=0)
computeValueLLTs - Given an LLVM IR type, compute a sequence of LLTs that represent all the individua...
Definition Analysis.cpp:149
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
generic_gep_type_iterator<> gep_type_iterator
auto succ_size(const MachineBasicBlock *BB)
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Global
Append to llvm.global_dtors.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1184
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1994
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:24
gep_type_iterator gep_type_begin(const User *GEP)
GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:185
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:869
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Pair of physical register and lane mask.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
static bool canHandle(const Instruction *I, const TargetLibraryInfo &TLI)
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...