LLVM 24.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"
55#include "llvm/IR/Analysis.h"
56#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/CFG.h"
58#include "llvm/IR/Constant.h"
59#include "llvm/IR/Constants.h"
60#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/Function.h"
65#include "llvm/IR/InlineAsm.h"
66#include "llvm/IR/InstrTypes.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsAMDGPU.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/Metadata.h"
74#include "llvm/IR/Statepoint.h"
75#include "llvm/IR/Type.h"
76#include "llvm/IR/User.h"
77#include "llvm/IR/Value.h"
79#include "llvm/MC/MCContext.h"
80#include "llvm/Pass.h"
83#include "llvm/Support/Debug.h"
90#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <optional>
95#include <string>
96#include <utility>
97#include <vector>
98
99#define DEBUG_TYPE "irtranslator"
100
101using namespace llvm;
102
103static cl::opt<bool>
104 EnableCSEInIRTranslator("enable-cse-in-irtranslator",
105 cl::desc("Should enable CSE in irtranslator"),
106 cl::Optional, cl::init(false));
107
108namespace llvm {
109
111 /// Interface used to lower the everything related to calls.
112 const CallLowering *CLI = nullptr;
113
114 SSPLayoutInfo *SPInfo = nullptr;
115
116 /// This class contains the mapping between the Values to vreg related data.
117 class ValueToVRegInfo {
118 public:
119 ValueToVRegInfo() = default;
120
121 using VRegListT = SmallVector<Register, 1>;
122 using OffsetListT = SmallVector<uint64_t, 1>;
123
124 using const_vreg_iterator =
126 using const_offset_iterator =
128
129 inline const_vreg_iterator vregs_end() const { return ValToVRegs.end(); }
130
131 VRegListT *getVRegs(const Value &V) {
132 auto It = ValToVRegs.find(&V);
133 if (It != ValToVRegs.end())
134 return It->second;
135
136 return insertVRegs(V);
137 }
138
139 OffsetListT *getOffsets(const Value &V) {
140 auto It = TypeToOffsets.find(V.getType());
141 if (It != TypeToOffsets.end())
142 return It->second;
143
144 return insertOffsets(V);
145 }
146
147 const_vreg_iterator findVRegs(const Value &V) const {
148 return ValToVRegs.find(&V);
149 }
150
151 bool contains(const Value &V) const { return ValToVRegs.contains(&V); }
152
153 void reset() {
154 ValToVRegs.clear();
155 TypeToOffsets.clear();
156 VRegAlloc.DestroyAll();
157 OffsetAlloc.DestroyAll();
158 }
159
160 private:
161 VRegListT *insertVRegs(const Value &V) {
162 assert(!ValToVRegs.contains(&V) && "Value already exists");
163
164 // We placement new using our fast allocator since we never try to free
165 // the vectors until translation is finished.
166 auto *VRegList = new (VRegAlloc.Allocate()) VRegListT();
167 ValToVRegs[&V] = VRegList;
168 return VRegList;
169 }
170
171 OffsetListT *insertOffsets(const Value &V) {
172 assert(!TypeToOffsets.contains(V.getType()) && "Type already exists");
173
174 auto *OffsetList = new (OffsetAlloc.Allocate()) OffsetListT();
175 TypeToOffsets[V.getType()] = OffsetList;
176 return OffsetList;
177 }
180
181 // We store pointers to vectors here since references may be invalidated
182 // while we hold them if we stored the vectors directly.
185 };
186
187 /// Mapping of the values of the current LLVM IR function to the related
188 /// virtual registers and offsets.
189 ValueToVRegInfo VMap;
190
191 // One BasicBlock can be translated to multiple MachineBasicBlocks. For such
192 // BasicBlocks translated to multiple MachineBasicBlocks, MachinePreds retains
193 // a mapping between the edges arriving at the BasicBlock to the corresponding
194 // created MachineBasicBlocks. Some BasicBlocks that get translated to a
195 // single MachineBasicBlock may also end up in this Map.
196 using CFGEdge = std::pair<const BasicBlock *, const BasicBlock *>;
198
199 // List of stubbed PHI instructions, for values and basic blocks to be filled
200 // in once all MachineBasicBlocks have been created.
202 PendingPHIs;
203
204 /// Record of what frame index has been allocated to specified allocas for
205 /// this function.
207
208 SwiftErrorValueTracking SwiftError;
209
210 /// \name Methods for translating form LLVM IR to MachineInstr.
211 /// \see ::translate for general information on the translate methods.
212 /// @{
213
214 /// Translate \p Inst into its corresponding MachineInstr instruction(s).
215 /// Insert the newly translated instruction(s) right where the CurBuilder
216 /// is set.
217 ///
218 /// The general algorithm is:
219 /// 1. Look for a virtual register for each operand or
220 /// create one.
221 /// 2 Update the VMap accordingly.
222 /// 2.alt. For constant arguments, if they are compile time constants,
223 /// produce an immediate in the right operand and do not touch
224 /// ValToReg. Actually we will go with a virtual register for each
225 /// constants because it may be expensive to actually materialize the
226 /// constant. Moreover, if the constant spans on several instructions,
227 /// CSE may not catch them.
228 /// => Update ValToVReg and remember that we saw a constant in Constants.
229 /// We will materialize all the constants in finalize.
230 /// Note: we would need to do something so that we can recognize such operand
231 /// as constants.
232 /// 3. Create the generic instruction.
233 ///
234 /// \return true if the translation succeeded.
235 bool translate(const Instruction &Inst);
236
237 /// Materialize \p C into virtual-register \p Reg. The generic instructions
238 /// performing this materialization will be inserted into the entry block of
239 /// the function.
240 ///
241 /// \return true if the materialization succeeded.
242 bool translate(const Constant &C, Register Reg);
243
244 /// Examine any debug-info attached to the instruction (in the form of
245 /// DbgRecords) and translate it.
246 void translateDbgInfo(const Instruction &Inst, MachineIRBuilder &MIRBuilder);
247
248 /// Translate a debug-info record of a dbg.value into a DBG_* instruction.
249 /// Pass in all the contents of the record, rather than relying on how it's
250 /// stored.
251 void translateDbgValueRecord(Value *V, bool HasArgList,
252 const DILocalVariable *Variable,
254 const DebugLoc &DL,
255 MachineIRBuilder &MIRBuilder);
256
257 /// Translate a debug-info record of a dbg.declare into an indirect DBG_*
258 /// instruction. Pass in all the contents of the record, rather than relying
259 /// on how it's stored.
260 void translateDbgDeclareRecord(Value *Address, bool HasArgList,
261 const DILocalVariable *Variable,
263 const DebugLoc &DL,
264 MachineIRBuilder &MIRBuilder);
265
266 // Translate U as a copy of V.
267 bool translateCopy(const User &U, const Value &V,
268 MachineIRBuilder &MIRBuilder);
269 bool translateCopy(const User &U, Register Src, MachineIRBuilder &MIRBuilder);
270
271 /// Translate an LLVM bitcast into generic IR. Either a COPY or a G_BITCAST is
272 /// emitted.
273 bool translateBitCast(const User &U, MachineIRBuilder &MIRBuilder);
274
275 /// Translate an LLVM load instruction into generic IR.
276 bool translateLoad(const User &U, MachineIRBuilder &MIRBuilder);
277
278 /// Translate an LLVM store instruction into generic IR.
279 bool translateStore(const User &U, MachineIRBuilder &MIRBuilder);
280
281 /// Translate an LLVM string intrinsic (memcpy, memset, ...).
282 bool translateMemFunc(const CallInst &CI, MachineIRBuilder &MIRBuilder,
283 unsigned Opcode);
284
285 /// Translate an LLVM trap intrinsic (trap, debugtrap, ubsantrap).
286 bool translateTrap(const CallInst &U, MachineIRBuilder &MIRBuilder,
287 unsigned Opcode);
288
289 // Translate @llvm.vector.interleave2 and
290 // @llvm.vector.deinterleave2 intrinsics for fixed-width vector
291 // types into vector shuffles.
292 bool translateVectorInterleave2Intrinsic(const CallInst &CI,
293 MachineIRBuilder &MIRBuilder);
294 bool translateVectorDeinterleave2Intrinsic(const CallInst &CI,
295 MachineIRBuilder &MIRBuilder);
296
297 void getStackGuard(Register DstReg, MachineIRBuilder &MIRBuilder);
298
299 bool translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
300 MachineIRBuilder &MIRBuilder);
301 bool translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
302 MachineIRBuilder &MIRBuilder);
303
304 /// Helper function for translateSimpleIntrinsic.
305 /// \return The generic opcode for \p IntrinsicID if \p IntrinsicID is a
306 /// simple intrinsic (ceil, fabs, etc.). Otherwise, returns
307 /// Intrinsic::not_intrinsic.
308 unsigned getSimpleIntrinsicOpcode(Intrinsic::ID ID);
309
310 /// Translates the intrinsics defined in getSimpleIntrinsicOpcode.
311 /// \return true if the translation succeeded.
312 bool translateSimpleIntrinsic(const CallInst &CI, Intrinsic::ID ID,
313 MachineIRBuilder &MIRBuilder);
314
315 bool translateConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI,
316 MachineIRBuilder &MIRBuilder);
317
318 bool translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
319 MachineIRBuilder &MIRBuilder);
320
321 /// Returns the single livein physical register Arg was lowered to, if
322 /// possible.
323 std::optional<MCRegister> getArgPhysReg(Argument &Arg);
324
325 /// If debug-info targets an Argument and its expression is an EntryValue,
326 /// lower it as either an entry in the MF debug table (dbg.declare), or a
327 /// DBG_VALUE targeting the corresponding livein register for that Argument
328 /// (dbg.value).
329 bool translateIfEntryValueArgument(bool isDeclare, Value *Arg,
330 const DILocalVariable *Var,
331 const DIExpression *Expr,
332 const DebugLoc &DL,
333 MachineIRBuilder &MIRBuilder);
334
335 bool translateInlineAsm(const CallBase &CB, MachineIRBuilder &MIRBuilder);
336
337 /// Common code for translating normal calls or invokes.
338 bool translateCallBase(const CallBase &CB, MachineIRBuilder &MIRBuilder);
339
340 /// Translate call instruction.
341 /// \pre \p U is a call instruction.
342 bool translateCall(const User &U, MachineIRBuilder &MIRBuilder);
343
344 bool translateIntrinsic(
345 const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder,
346 ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos = {});
347
348 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
349 /// many places it could ultimately go. In the IR, we have a single unwind
350 /// destination, but in the machine CFG, we enumerate all the possible blocks.
351 /// This function skips over imaginary basic blocks that hold catchswitch
352 /// instructions, and finds all the "real" machine
353 /// basic block destinations. As those destinations may not be successors of
354 /// EHPadBB, here we also calculate the edge probability to those
355 /// destinations. The passed-in Prob is the edge probability to EHPadBB.
356 bool findUnwindDestinations(
357 const BasicBlock *EHPadBB, BranchProbability Prob,
358 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
359 &UnwindDests);
360
361 bool translateInvoke(const User &U, MachineIRBuilder &MIRBuilder);
362
363 bool translateCallBr(const User &U, MachineIRBuilder &MIRBuilder);
364
365 bool translateLandingPad(const User &U, MachineIRBuilder &MIRBuilder);
366
367 /// Translate one of LLVM's cast instructions into MachineInstrs, with the
368 /// given generic Opcode.
369 bool translateCast(unsigned Opcode, const User &U,
370 MachineIRBuilder &MIRBuilder);
371
372 /// Translate a phi instruction.
373 bool translatePHI(const User &U, MachineIRBuilder &MIRBuilder);
374
375 /// Translate a comparison (icmp or fcmp) instruction or constant.
376 bool translateCompare(const User &U, MachineIRBuilder &MIRBuilder);
377
378 /// Translate an integer compare instruction (or constant).
379 bool translateICmp(const User &U, MachineIRBuilder &MIRBuilder) {
380 return translateCompare(U, MIRBuilder);
381 }
382
383 /// Translate a floating-point compare instruction (or constant).
384 bool translateFCmp(const User &U, MachineIRBuilder &MIRBuilder) {
385 return translateCompare(U, MIRBuilder);
386 }
387
388 /// Add remaining operands onto phis we've translated. Executed after all
389 /// MachineBasicBlocks for the function have been created.
390 void finishPendingPhis();
391
392 /// Translate \p Inst into a unary operation \p Opcode.
393 /// \pre \p U is a unary operation.
394 bool translateUnaryOp(unsigned Opcode, const User &U,
395 MachineIRBuilder &MIRBuilder);
396
397 /// Translate \p Inst into a binary operation \p Opcode.
398 /// \pre \p U is a binary operation.
399 bool translateBinaryOp(unsigned Opcode, const User &U,
400 MachineIRBuilder &MIRBuilder);
401
402 /// If the set of cases should be emitted as a series of branches, return
403 /// true. If we should emit this as a bunch of and/or'd together conditions,
404 /// return false.
405 bool shouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
406 /// Helper method for findMergedConditions.
407 /// This function emits a branch and is used at the leaves of an OR or an
408 /// AND operator tree.
409 void emitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
411 MachineBasicBlock *CurBB,
412 MachineBasicBlock *SwitchBB,
413 BranchProbability TProb,
414 BranchProbability FProb, bool InvertCond);
415 /// Used during condbr translation to find trees of conditions that can be
416 /// optimized.
417 void findMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
419 MachineBasicBlock *SwitchBB,
421 BranchProbability FProb, bool InvertCond);
422
423 /// Translate branch (br) instruction.
424 /// \pre \p U is a branch instruction.
425 bool translateUncondBr(const User &U, MachineIRBuilder &MIRBuilder);
426 bool translateCondBr(const User &U, MachineIRBuilder &MIRBuilder);
427
428 // Begin switch lowering functions.
429 bool emitJumpTableHeader(SwitchCG::JumpTable &JT,
431 MachineBasicBlock *HeaderBB);
432 void emitJumpTable(SwitchCG::JumpTable &JT, MachineBasicBlock *MBB);
433
434 void emitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB,
435 MachineIRBuilder &MIB);
436
437 /// Generate for the BitTest header block, which precedes each sequence of
438 /// BitTestCases.
439 void emitBitTestHeader(SwitchCG::BitTestBlock &BTB,
440 MachineBasicBlock *SwitchMBB);
441 /// Generate code to produces one "bit test" for a given BitTestCase \p B.
442 void emitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB,
443 BranchProbability BranchProbToNext, Register Reg,
445
446 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
448 MachineBasicBlock *SwitchMBB, MachineIRBuilder &MIB);
449
450 bool lowerJumpTableWorkItem(
452 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
455 MachineBasicBlock *Fallthrough, bool FallthroughUnreachable);
456
457 bool lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, Value *Cond,
458 MachineBasicBlock *Fallthrough,
459 bool FallthroughUnreachable,
460 BranchProbability UnhandledProbs,
461 MachineBasicBlock *CurMBB,
462 MachineIRBuilder &MIB,
463 MachineBasicBlock *SwitchMBB);
464
465 bool lowerBitTestWorkItem(
467 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
469 BranchProbability DefaultProb, BranchProbability UnhandledProbs,
471 bool FallthroughUnreachable);
472
473 bool lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
474 MachineBasicBlock *SwitchMBB,
475 MachineBasicBlock *DefaultMBB,
476 MachineIRBuilder &MIB);
477
478 bool translateSwitch(const User &U, MachineIRBuilder &MIRBuilder);
479 // End switch lowering section.
480
481 bool translateIndirectBr(const User &U, MachineIRBuilder &MIRBuilder);
482
483 bool translateExtractValue(const User &U, MachineIRBuilder &MIRBuilder);
484
485 bool translateInsertValue(const User &U, MachineIRBuilder &MIRBuilder);
486
487 bool translateSelect(const User &U, MachineIRBuilder &MIRBuilder);
488
489 bool translateGetElementPtr(const User &U, MachineIRBuilder &MIRBuilder);
490
491 bool translateAlloca(const User &U, MachineIRBuilder &MIRBuilder);
492
493 /// Translate return (ret) instruction.
494 /// The target needs to implement CallLowering::lowerReturn for
495 /// this to succeed.
496 /// \pre \p U is a return instruction.
497 bool translateRet(const User &U, MachineIRBuilder &MIRBuilder);
498
499 bool translateFNeg(const User &U, MachineIRBuilder &MIRBuilder);
500
501 bool translateAdd(const User &U, MachineIRBuilder &MIRBuilder) {
502 return translateBinaryOp(TargetOpcode::G_ADD, U, MIRBuilder);
503 }
504 bool translateSub(const User &U, MachineIRBuilder &MIRBuilder) {
505 return translateBinaryOp(TargetOpcode::G_SUB, U, MIRBuilder);
506 }
507 bool translateAnd(const User &U, MachineIRBuilder &MIRBuilder) {
508 return translateBinaryOp(TargetOpcode::G_AND, U, MIRBuilder);
509 }
510 bool translateMul(const User &U, MachineIRBuilder &MIRBuilder) {
511 return translateBinaryOp(TargetOpcode::G_MUL, U, MIRBuilder);
512 }
513 bool translateOr(const User &U, MachineIRBuilder &MIRBuilder) {
514 return translateBinaryOp(TargetOpcode::G_OR, U, MIRBuilder);
515 }
516 bool translateXor(const User &U, MachineIRBuilder &MIRBuilder) {
517 return translateBinaryOp(TargetOpcode::G_XOR, U, MIRBuilder);
518 }
519
520 bool translateUDiv(const User &U, MachineIRBuilder &MIRBuilder) {
521 return translateBinaryOp(TargetOpcode::G_UDIV, U, MIRBuilder);
522 }
523 bool translateSDiv(const User &U, MachineIRBuilder &MIRBuilder) {
524 return translateBinaryOp(TargetOpcode::G_SDIV, U, MIRBuilder);
525 }
526 bool translateURem(const User &U, MachineIRBuilder &MIRBuilder) {
527 return translateBinaryOp(TargetOpcode::G_UREM, U, MIRBuilder);
528 }
529 bool translateSRem(const User &U, MachineIRBuilder &MIRBuilder) {
530 return translateBinaryOp(TargetOpcode::G_SREM, U, MIRBuilder);
531 }
532 bool translateIntToPtr(const User &U, MachineIRBuilder &MIRBuilder) {
533 return translateCast(TargetOpcode::G_INTTOPTR, U, MIRBuilder);
534 }
535 bool translatePtrToInt(const User &U, MachineIRBuilder &MIRBuilder) {
536 return translateCast(TargetOpcode::G_PTRTOINT, U, MIRBuilder);
537 }
538 bool translatePtrToAddr(const User &U, MachineIRBuilder &MIRBuilder) {
539 // FIXME: this is not correct for pointers with addr width != pointer width
540 return translatePtrToInt(U, MIRBuilder);
541 }
542 bool translateTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
543 return translateCast(TargetOpcode::G_TRUNC, U, MIRBuilder);
544 }
545 bool translateFPTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
546 return translateCast(TargetOpcode::G_FPTRUNC, U, MIRBuilder);
547 }
548 bool translateFPExt(const User &U, MachineIRBuilder &MIRBuilder) {
549 return translateCast(TargetOpcode::G_FPEXT, U, MIRBuilder);
550 }
551 bool translateFPToUI(const User &U, MachineIRBuilder &MIRBuilder) {
552 return translateCast(TargetOpcode::G_FPTOUI, U, MIRBuilder);
553 }
554 bool translateFPToSI(const User &U, MachineIRBuilder &MIRBuilder) {
555 return translateCast(TargetOpcode::G_FPTOSI, U, MIRBuilder);
556 }
557 bool translateUIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
558 return translateCast(TargetOpcode::G_UITOFP, U, MIRBuilder);
559 }
560 bool translateSIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
561 return translateCast(TargetOpcode::G_SITOFP, U, MIRBuilder);
562 }
563 bool translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder);
564
565 bool translateSExt(const User &U, MachineIRBuilder &MIRBuilder) {
566 return translateCast(TargetOpcode::G_SEXT, U, MIRBuilder);
567 }
568
569 bool translateZExt(const User &U, MachineIRBuilder &MIRBuilder) {
570 return translateCast(TargetOpcode::G_ZEXT, U, MIRBuilder);
571 }
572
573 bool translateShl(const User &U, MachineIRBuilder &MIRBuilder) {
574 return translateBinaryOp(TargetOpcode::G_SHL, U, MIRBuilder);
575 }
576 bool translateLShr(const User &U, MachineIRBuilder &MIRBuilder) {
577 return translateBinaryOp(TargetOpcode::G_LSHR, U, MIRBuilder);
578 }
579 bool translateAShr(const User &U, MachineIRBuilder &MIRBuilder) {
580 return translateBinaryOp(TargetOpcode::G_ASHR, U, MIRBuilder);
581 }
582
583 bool translateFAdd(const User &U, MachineIRBuilder &MIRBuilder) {
584 return translateBinaryOp(TargetOpcode::G_FADD, U, MIRBuilder);
585 }
586 bool translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
587 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
588 }
589 bool translateFMul(const User &U, MachineIRBuilder &MIRBuilder) {
590 return translateBinaryOp(TargetOpcode::G_FMUL, U, MIRBuilder);
591 }
592 bool translateFDiv(const User &U, MachineIRBuilder &MIRBuilder) {
593 return translateBinaryOp(TargetOpcode::G_FDIV, U, MIRBuilder);
594 }
595 bool translateFRem(const User &U, MachineIRBuilder &MIRBuilder) {
596 return translateBinaryOp(TargetOpcode::G_FREM, U, MIRBuilder);
597 }
598
599 bool translateVAArg(const User &U, MachineIRBuilder &MIRBuilder);
600
601 bool translateInsertElement(const User &U, MachineIRBuilder &MIRBuilder);
602 bool translateInsertVector(const User &U, MachineIRBuilder &MIRBuilder);
603
604 bool translateExtractElement(const User &U, MachineIRBuilder &MIRBuilder);
605 bool translateExtractVector(const User &U, MachineIRBuilder &MIRBuilder);
606
607 bool translateShuffleVector(const User &U, MachineIRBuilder &MIRBuilder);
608
609 bool translateAtomicCmpXchg(const User &U, MachineIRBuilder &MIRBuilder);
610 bool translateAtomicRMW(const User &U, MachineIRBuilder &MIRBuilder);
611 bool translateFence(const User &U, MachineIRBuilder &MIRBuilder);
612 bool translateFreeze(const User &U, MachineIRBuilder &MIRBuilder);
613
614 // Stubs to keep the compiler happy while we implement the rest of the
615 // translation.
616 bool translateResume(const User &U, MachineIRBuilder &MIRBuilder) {
617 return false;
618 }
619 bool translateCleanupRet(const User &U, MachineIRBuilder &MIRBuilder) {
620 return false;
621 }
622 bool translateCatchRet(const User &U, MachineIRBuilder &MIRBuilder) {
623 return false;
624 }
625 bool translateCatchSwitch(const User &U, MachineIRBuilder &MIRBuilder) {
626 return false;
627 }
628 bool translateAddrSpaceCast(const User &U, MachineIRBuilder &MIRBuilder) {
629 return translateCast(TargetOpcode::G_ADDRSPACE_CAST, U, MIRBuilder);
630 }
631 bool translateCleanupPad(const User &U, MachineIRBuilder &MIRBuilder) {
632 return false;
633 }
634 bool translateCatchPad(const User &U, MachineIRBuilder &MIRBuilder) {
635 return false;
636 }
637 bool translateUserOp1(const User &U, MachineIRBuilder &MIRBuilder) {
638 return false;
639 }
640 bool translateUserOp2(const User &U, MachineIRBuilder &MIRBuilder) {
641 return false;
642 }
643
644 bool translateConvergenceControlIntrinsic(const CallInst &CI,
645 Intrinsic::ID ID,
646 MachineIRBuilder &MIRBuilder);
647
648 /// @}
649
650 // Builder for machine instruction a la IRBuilder.
651 // I.e., compared to regular MIBuilder, this one also inserts the instruction
652 // in the current block, it can creates block, etc., basically a kind of
653 // IRBuilder, but for Machine IR.
654 // CSEMIRBuilder CurBuilder;
655 std::unique_ptr<MachineIRBuilder> CurBuilder;
656
657 // Builder set to the entry block (just after ABI lowering instructions). Used
658 // as a convenient location for Constants.
659 // CSEMIRBuilder EntryBuilder;
660 std::unique_ptr<MachineIRBuilder> EntryBuilder;
661
662 // The MachineFunction currently being translated.
663 MachineFunction *MF = nullptr;
664
665 /// MachineRegisterInfo used to create virtual registers.
666 MachineRegisterInfo *MRI = nullptr;
667
668 const DataLayout *DL = nullptr;
669
670 CodeGenOptLevel OptLevel;
671
672 /// Current optimization remark emitter. Used to report failures.
673 std::unique_ptr<OptimizationRemarkEmitter> ORE;
674
675 AAResults *AA = nullptr;
676 AssumptionCache *AC = nullptr;
677 const TargetLibraryInfo *LibInfo = nullptr;
678 const LibcallLoweringInfo *Libcalls = nullptr;
679 const TargetLowering *TLI = nullptr;
680 FunctionLoweringInfo FuncInfo;
681
682 // True when either the Target Machine specifies no optimizations or the
683 // function has the optnone attribute.
684 bool EnableOpts = false;
685
686 /// True when the block contains a tail call. This allows the IRTranslator to
687 /// stop translating such blocks early.
688 bool HasTailCall = false;
689
690 StackProtectorDescriptor SPDescriptor;
691
692 bool mayTranslateUserTypes(const User &U) const;
693
694 /// Switch analysis and optimization.
695 class GISelSwitchLowering : public SwitchCG::SwitchLowering {
696 public:
697 GISelSwitchLowering(IRTranslatorImpl *irt, FunctionLoweringInfo &funcinfo)
698 : SwitchLowering(funcinfo), IRT(irt) {
699 assert(irt && "irt is null!");
700 }
701
702 void addSuccessorWithProb(
705 IRT->addSuccessorWithProb(Src, Dst, Prob);
706 }
707
708 ~GISelSwitchLowering() override = default;
709
710 private:
711 IRTranslatorImpl *IRT;
712 };
713
714 std::unique_ptr<GISelSwitchLowering> SL;
715
716 // * Insert all the code needed to materialize the constants
717 // at the proper place. E.g., Entry block or dominator block
718 // of each constant depending on how fancy we want to be.
719 // * Clear the different maps.
720 void finalizeFunction();
721
722 // Processing steps done per block. E.g. emitting jump tables, stack
723 // protectors etc. Returns true if no errors, false if there was a problem
724 // that caused an abort.
725 bool finalizeBasicBlock(const BasicBlock &BB, MachineBasicBlock &MBB);
726
727 /// Codegen a new tail for a stack protector check ParentMBB which has had its
728 /// tail spliced into a stack protector check success bb.
729 ///
730 /// For a high level explanation of how this fits into the stack protector
731 /// generation see the comment on the declaration of class
732 /// StackProtectorDescriptor.
733 ///
734 /// \return true if there were no problems.
735 bool emitSPDescriptorParent(StackProtectorDescriptor &SPD,
736 MachineBasicBlock *ParentBB);
737
738 /// Codegen the failure basic block for a stack protector check.
739 ///
740 /// A failure stack protector machine basic block consists simply of a call to
741 /// __stack_chk_fail().
742 ///
743 /// For a high level explanation of how this fits into the stack protector
744 /// generation see the comment on the declaration of class
745 /// StackProtectorDescriptor.
746 ///
747 /// \return true if there were no problems.
748 bool emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
749 MachineBasicBlock *FailureBB);
750
751 /// Get the VRegs that represent \p Val.
752 /// Non-aggregate types have just one corresponding VReg and the list can be
753 /// used as a single "unsigned". Aggregates get flattened. If such VRegs do
754 /// not exist, they are created.
755 ArrayRef<Register> getOrCreateVRegs(const Value &Val);
756
757 Register getOrCreateVReg(const Value &Val) {
758 auto Regs = getOrCreateVRegs(Val);
759 if (Regs.empty())
760 return 0;
761 assert(Regs.size() == 1 &&
762 "attempt to get single VReg for aggregate or void");
763 return Regs[0];
764 }
765
766 Register getOrCreateConvergenceTokenVReg(const Value &Token) {
767 assert(Token.getType()->isTokenTy());
768 auto &Regs = *VMap.getVRegs(Token);
769 if (!Regs.empty()) {
770 assert(Regs.size() == 1 &&
771 "Expected a single register for convergence tokens.");
772 return Regs[0];
773 }
774
775 auto Reg = MRI->createGenericVirtualRegister(LLT::token());
776 Regs.push_back(Reg);
777 auto &Offsets = *VMap.getOffsets(Token);
778 if (Offsets.empty())
779 Offsets.push_back(0);
780 return Reg;
781 }
782
783 /// Allocate some vregs and offsets in the VMap. Then populate just the
784 /// offsets while leaving the vregs empty.
785 ValueToVRegInfo::VRegListT &allocateVRegs(const Value &Val);
786
787 /// Get the frame index that represents \p Val.
788 /// If such VReg does not exist, it is created.
789 int getOrCreateFrameIndex(const AllocaInst &AI);
790
791 /// Get the alignment of the given memory operation instruction. This will
792 /// either be the explicitly specified value or the ABI-required alignment for
793 /// the type being accessed (according to the Module's DataLayout).
794 Align getMemOpAlign(const Instruction &I);
795
796 /// Get the MachineBasicBlock that represents \p BB. Specifically, the block
797 /// returned will be the head of the translated block (suitable for branch
798 /// destinations).
799 MachineBasicBlock &getMBB(const BasicBlock &BB);
800
801 /// Record \p NewPred as a Machine predecessor to `Edge.second`, corresponding
802 /// to `Edge.first` at the IR level. This is used when IRTranslation creates
803 /// multiple MachineBasicBlocks for a given IR block and the CFG is no longer
804 /// represented simply by the IR-level CFG.
805 void addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred);
806
807 /// Returns the Machine IR predecessors for the given IR CFG edge. Usually
808 /// this is just the single MachineBasicBlock corresponding to the predecessor
809 /// in the IR. More complex lowering can result in multiple MachineBasicBlocks
810 /// preceding the original though (e.g. switch instructions).
811 SmallVector<MachineBasicBlock *, 1> getMachinePredBBs(CFGEdge Edge) {
812 auto RemappedEdge = MachinePreds.find(Edge);
813 if (RemappedEdge != MachinePreds.end())
814 return RemappedEdge->second;
815 return SmallVector<MachineBasicBlock *, 4>(1, &getMBB(*Edge.first));
816 }
817
818 /// Return branch probability calculated by BranchProbabilityInfo for IR
819 /// blocks.
820 BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
821 const MachineBasicBlock *Dst) const;
822
823 void addSuccessorWithProb(
826
827public:
829 : OptLevel(OptLevel) {}
830
831 // Algo:
832 // CallLowering = MF.subtarget.getCallLowering()
833 // F = MF.getParent()
834 // MIRBuilder.reset(MF)
835 // getMBB(F.getEntryBB())
836 // CallLowering->translateArguments(MIRBuilder, F, ValToVReg)
837 // for each bb in F
838 // getMBB(bb)
839 // for each inst in bb
840 // if (!translate(MIRBuilder, inst, ValToVReg, ConstantToSequence))
841 // reportFatalUsageError("Don't know how to translate input");
842 // finalize()
844 function_ref<GISelCSEInfo *()> GetCSEInfo,
845 bool ShouldSkipOpts,
846 function_ref<AAResults *()> GetAAResults,
848 function_ref<AssumptionCache *()> GetAC,
849 TargetLibraryInfo *LibraryInfo,
850 const LibcallLoweringInfo *LibcallInfo,
851 SSPLayoutInfo *StackProtectorInfo);
852};
853
854} // namespace llvm
855
857
859 "IRTranslator LLVM IR -> MI", false, false)
866 "IRTranslator LLVM IR -> MI", false, false)
867
871 MF.getProperties().setFailedISel();
872 bool IsGlobalISelAbortEnabled =
873 MF.getTarget().Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
874
875 // Print the function name explicitly if we don't have a debug location (which
876 // makes the diagnostic less useful) or if we're going to emit a raw error.
877 if (!R.getLocation().isValid() || IsGlobalISelAbortEnabled)
878 R << (" (in function: " + MF.getName() + ")").str();
879
880 if (IsGlobalISelAbortEnabled)
881 report_fatal_error(Twine(R.getMsg()));
882 else
883 ORE.emit(R);
884}
885
887 : MachineFunctionPass(ID), OptLevel(OptLevel),
888 Impl(std::make_unique<IRTranslatorImpl>(OptLevel)) {}
889
891
892#ifndef NDEBUG
893namespace {
894/// Verify that every instruction created has the same DILocation as the
895/// instruction being translated.
896class DILocationVerifier : public GISelChangeObserver {
897 const Instruction *CurrInst = nullptr;
898
899public:
900 DILocationVerifier() = default;
901 ~DILocationVerifier() override = default;
902
903 const Instruction *getCurrentInst() const { return CurrInst; }
904 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
905
906 void erasingInstr(MachineInstr &MI) override {}
907 void changingInstr(MachineInstr &MI) override {}
908 void changedInstr(MachineInstr &MI) override {}
909
910 void createdInstr(MachineInstr &MI) override {
911 assert(getCurrentInst() && "Inserted instruction without a current MI");
912
913 // Only print the check message if we're actually checking it.
914#ifndef NDEBUG
915 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
916 << " was copied to " << MI);
917#endif
918 // We allow insts in the entry block to have no debug loc because
919 // they could have originated from constants, and we don't want a jumpy
920 // debug experience.
921 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
922 (MI.getParent()->isEntryBlock() && !MI.getDebugLoc()) ||
923 (MI.isDebugInstr())) &&
924 "Line info was not transferred to all instructions");
925 }
926};
927} // namespace
928#endif // ifndef NDEBUG
929
946
947IRTranslatorImpl::ValueToVRegInfo::VRegListT &
948IRTranslatorImpl::allocateVRegs(const Value &Val) {
949 auto VRegsIt = VMap.findVRegs(Val);
950 if (VRegsIt != VMap.vregs_end())
951 return *VRegsIt->second;
952 auto *Regs = VMap.getVRegs(Val);
953 auto *Offsets = VMap.getOffsets(Val);
954 SmallVector<LLT, 4> SplitTys;
955 computeValueLLTs(*DL, *Val.getType(), SplitTys,
956 Offsets->empty() ? Offsets : nullptr);
957 for (unsigned i = 0; i < SplitTys.size(); ++i)
958 Regs->push_back(0);
959 return *Regs;
960}
961
962ArrayRef<Register> IRTranslatorImpl::getOrCreateVRegs(const Value &Val) {
963 auto VRegsIt = VMap.findVRegs(Val);
964 if (VRegsIt != VMap.vregs_end())
965 return *VRegsIt->second;
966
967 if (Val.getType()->isVoidTy())
968 return *VMap.getVRegs(Val);
969
970 // Create entry for this type.
971 auto *VRegs = VMap.getVRegs(Val);
972 auto *Offsets = VMap.getOffsets(Val);
973
974 if (!Val.getType()->isTokenTy())
975 assert(Val.getType()->isSized() &&
976 "Don't know how to create an empty vreg");
977
978 // Fast-path values that lower to a single vreg.
979 if (!Val.getType()->isAggregateType()) {
980 LLT Ty = getLLTForType(*Val.getType(), *DL);
981 if (Offsets->empty())
982 Offsets->push_back(0);
983 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
984 if (isa<Constant>(Val)) {
985 bool Success = translate(cast<Constant>(Val), VRegs->front());
986 if (!Success) {
987 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
989 &MF->getFunction().getEntryBlock());
990 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
991 reportTranslationError(*MF, *ORE, R);
992 }
993 }
994 return *VRegs;
995 }
996
997 SmallVector<LLT, 4> SplitTys;
998 computeValueLLTs(*DL, *Val.getType(), SplitTys,
999 Offsets->empty() ? Offsets : nullptr);
1000
1001 if (!isa<Constant>(Val)) {
1002 for (auto Ty : SplitTys)
1003 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
1004 return *VRegs;
1005 }
1006
1007 // UndefValue, ConstantAggregateZero
1008 auto &C = cast<Constant>(Val);
1009 unsigned Idx = 0;
1010 while (auto Elt = C.getAggregateElement(Idx++)) {
1011 auto EltRegs = getOrCreateVRegs(*Elt);
1012 llvm::append_range(*VRegs, EltRegs);
1013 }
1014
1015 return *VRegs;
1016}
1017
1018int IRTranslatorImpl::getOrCreateFrameIndex(const AllocaInst &AI) {
1019 auto [MapEntry, Inserted] = FrameIndices.try_emplace(&AI);
1020 if (!Inserted)
1021 return MapEntry->second;
1022
1023 TypeSize TySize = AI.getAllocationSize(*DL).value_or(TypeSize::getZero());
1024 uint64_t Size = TySize.getKnownMinValue();
1025
1026 // Always allocate at least one byte.
1027 Size = std::max<uint64_t>(Size, 1u);
1028
1029 int &FI = MapEntry->second;
1030 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
1031
1032 // Scalable vectors and structures that contain scalable vectors may
1033 // need a special StackID to distinguish them from other (fixed size)
1034 // stack objects.
1035 if (TySize.isScalable()) {
1036 auto StackID =
1037 MF->getSubtarget().getFrameLowering()->getStackIDForScalableVectors();
1038 MF->getFrameInfo().setStackID(FI, StackID);
1039 }
1040
1041 return FI;
1042}
1043
1044Align IRTranslatorImpl::getMemOpAlign(const Instruction &I) {
1045 if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
1046 return SI->getAlign();
1047 if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
1048 return LI->getAlign();
1049 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
1050 return AI->getAlign();
1051 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
1052 return AI->getAlign();
1053
1054 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
1055 R << "unable to translate memop: " << ore::NV("Opcode", &I);
1056 reportTranslationError(*MF, *ORE, R);
1057 return Align(1);
1058}
1059
1060MachineBasicBlock &IRTranslatorImpl::getMBB(const BasicBlock &BB) {
1061 MachineBasicBlock *MBB = FuncInfo.getMBB(&BB);
1062 assert(MBB && "BasicBlock was not encountered before");
1063 return *MBB;
1064}
1065
1066void IRTranslatorImpl::addMachineCFGPred(CFGEdge Edge,
1067 MachineBasicBlock *NewPred) {
1068 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
1069 MachinePreds[Edge].push_back(NewPred);
1070}
1071
1072bool IRTranslatorImpl::translateBinaryOp(unsigned Opcode, const User &U,
1073 MachineIRBuilder &MIRBuilder) {
1074 if (!mayTranslateUserTypes(U))
1075 return false;
1076
1077 // Get or create a virtual register for each value.
1078 // Unless the value is a Constant => loadimm cst?
1079 // or inline constant each time?
1080 // Creation of a virtual register needs to have a size.
1081 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1082 Register Op1 = getOrCreateVReg(*U.getOperand(1));
1083 Register Res = getOrCreateVReg(U);
1084 uint32_t Flags = 0;
1085 if (isa<Instruction>(U)) {
1086 const Instruction &I = cast<Instruction>(U);
1088 }
1089
1090 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
1091 return true;
1092}
1093
1094bool IRTranslatorImpl::translateUnaryOp(unsigned Opcode, const User &U,
1095 MachineIRBuilder &MIRBuilder) {
1096 if (!mayTranslateUserTypes(U))
1097 return false;
1098
1099 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1100 Register Res = getOrCreateVReg(U);
1101 uint32_t Flags = 0;
1102 if (isa<Instruction>(U)) {
1103 const Instruction &I = cast<Instruction>(U);
1105 }
1106 MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
1107 return true;
1108}
1109
1110bool IRTranslatorImpl::translateFNeg(const User &U,
1111 MachineIRBuilder &MIRBuilder) {
1112 return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
1113}
1114
1115bool IRTranslatorImpl::translateCompare(const User &U,
1116 MachineIRBuilder &MIRBuilder) {
1117 if (!mayTranslateUserTypes(U))
1118 return false;
1119
1120 auto *CI = cast<CmpInst>(&U);
1121 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1122 Register Op1 = getOrCreateVReg(*U.getOperand(1));
1123 Register Res = getOrCreateVReg(U);
1124 CmpInst::Predicate Pred = CI->getPredicate();
1126 if (CmpInst::isIntPredicate(Pred))
1127 MIRBuilder.buildICmp(Pred, Res, Op0, Op1, Flags);
1128 else if (Pred == CmpInst::FCMP_FALSE)
1129 MIRBuilder.buildCopy(
1130 Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
1131 else if (Pred == CmpInst::FCMP_TRUE)
1132 MIRBuilder.buildCopy(
1133 Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
1134 else
1135 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags);
1136
1137 return true;
1138}
1139
1140bool IRTranslatorImpl::translateRet(const User &U,
1141 MachineIRBuilder &MIRBuilder) {
1142 const ReturnInst &RI = cast<ReturnInst>(U);
1143 const Value *Ret = RI.getReturnValue();
1144 if (Ret && DL->getTypeStoreSize(Ret->getType()).isZero())
1145 Ret = nullptr;
1146
1147 ArrayRef<Register> VRegs;
1148 if (Ret)
1149 VRegs = getOrCreateVRegs(*Ret);
1150
1151 Register SwiftErrorVReg = 0;
1152 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
1153 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
1154 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
1155 }
1156
1157 // The target may mess up with the insertion point, but
1158 // this is not important as a return is the last instruction
1159 // of the block anyway.
1160 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
1161}
1162
1163void IRTranslatorImpl::emitBranchForMergedCondition(
1165 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
1166 BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
1167 // If the leaf of the tree is a comparison, merge the condition into
1168 // the caseblock.
1169 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1170 CmpInst::Predicate Condition;
1171 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1172 Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1173 } else {
1174 const FCmpInst *FC = cast<FCmpInst>(Cond);
1175 Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1176 }
1177
1178 SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
1179 BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
1180 CurBuilder->getDebugLoc(), TProb, FProb);
1181 SL->SwitchCases.push_back(CB);
1182 return;
1183 }
1184
1185 // Create a CaseBlock record representing this branch.
1187 SwitchCG::CaseBlock CB(
1188 Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
1189 nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
1190 SL->SwitchCases.push_back(CB);
1191}
1192
1193static bool isValInBlock(const Value *V, const BasicBlock *BB) {
1194 if (const Instruction *I = dyn_cast<Instruction>(V))
1195 return I->getParent() == BB;
1196 return true;
1197}
1198
1199void IRTranslatorImpl::findMergedConditions(
1201 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
1203 BranchProbability FProb, bool InvertCond) {
1204 using namespace PatternMatch;
1205 assert((Opc == Instruction::And || Opc == Instruction::Or) &&
1206 "Expected Opc to be AND/OR");
1207 // Skip over not part of the tree and remember to invert op and operands at
1208 // next level.
1209 Value *NotCond;
1210 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1211 isValInBlock(NotCond, CurBB->getBasicBlock())) {
1212 findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1213 !InvertCond);
1214 return;
1215 }
1216
1218 const Value *BOpOp0, *BOpOp1;
1219 // Compute the effective opcode for Cond, taking into account whether it needs
1220 // to be inverted, e.g.
1221 // and (not (or A, B)), C
1222 // gets lowered as
1223 // and (and (not A, not B), C)
1225 if (BOp) {
1226 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
1227 ? Instruction::And
1228 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
1229 ? Instruction::Or
1231 if (InvertCond) {
1232 if (BOpc == Instruction::And)
1233 BOpc = Instruction::Or;
1234 else if (BOpc == Instruction::Or)
1235 BOpc = Instruction::And;
1236 }
1237 }
1238
1239 // If this node is not part of the or/and tree, emit it as a branch.
1240 // Note that all nodes in the tree should have same opcode.
1241 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
1242 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
1243 !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
1244 !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
1245 emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
1246 InvertCond);
1247 return;
1248 }
1249
1250 // Create TmpBB after CurBB.
1251 MachineFunction::iterator BBI(CurBB);
1252 MachineBasicBlock *TmpBB =
1253 MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
1254 CurBB->getParent()->insert(++BBI, TmpBB);
1255
1256 if (Opc == Instruction::Or) {
1257 // Codegen X | Y as:
1258 // BB1:
1259 // jmp_if_X TBB
1260 // jmp TmpBB
1261 // TmpBB:
1262 // jmp_if_Y TBB
1263 // jmp FBB
1264 //
1265
1266 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1267 // The requirement is that
1268 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1269 // = TrueProb for original BB.
1270 // Assuming the original probabilities are A and B, one choice is to set
1271 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1272 // A/(1+B) and 2B/(1+B). This choice assumes that
1273 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1274 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1275 // TmpBB, but the math is more complicated.
1276
1277 auto NewTrueProb = TProb / 2;
1278 auto NewFalseProb = TProb / 2 + FProb;
1279 // Emit the LHS condition.
1280 findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
1281 NewFalseProb, InvertCond);
1282
1283 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1284 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1286 // Emit the RHS condition into TmpBB.
1287 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
1288 Probs[1], InvertCond);
1289 } else {
1290 assert(Opc == Instruction::And && "Unknown merge op!");
1291 // Codegen X & Y as:
1292 // BB1:
1293 // jmp_if_X TmpBB
1294 // jmp FBB
1295 // TmpBB:
1296 // jmp_if_Y TBB
1297 // jmp FBB
1298 //
1299 // This requires creation of TmpBB after CurBB.
1300
1301 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1302 // The requirement is that
1303 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1304 // = FalseProb for original BB.
1305 // Assuming the original probabilities are A and B, one choice is to set
1306 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1307 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1308 // TrueProb for BB1 * FalseProb for TmpBB.
1309
1310 auto NewTrueProb = TProb + FProb / 2;
1311 auto NewFalseProb = FProb / 2;
1312 // Emit the LHS condition.
1313 findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
1314 NewFalseProb, InvertCond);
1315
1316 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1317 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1319 // Emit the RHS condition into TmpBB.
1320 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
1321 Probs[1], InvertCond);
1322 }
1323}
1324
1325bool IRTranslatorImpl::shouldEmitAsBranches(
1326 const std::vector<SwitchCG::CaseBlock> &Cases) {
1327 // For multiple cases, it's better to emit as branches.
1328 if (Cases.size() != 2)
1329 return true;
1330
1331 // If this is two comparisons of the same values or'd or and'd together, they
1332 // will get folded into a single comparison, so don't emit two blocks.
1333 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1334 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1335 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1336 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1337 return false;
1338 }
1339
1340 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1341 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1342 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1343 Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
1344 isa<Constant>(Cases[0].CmpRHS) &&
1345 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1346 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
1347 Cases[0].TrueBB == Cases[1].ThisBB)
1348 return false;
1349 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
1350 Cases[0].FalseBB == Cases[1].ThisBB)
1351 return false;
1352 }
1353
1354 return true;
1355}
1356
1357bool IRTranslatorImpl::translateUncondBr(const User &U,
1358 MachineIRBuilder &MIRBuilder) {
1359 const UncondBrInst &BrInst = cast<UncondBrInst>(U);
1360 auto &CurMBB = MIRBuilder.getMBB();
1361 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
1362
1363 // If the unconditional target is the layout successor, fallthrough.
1364 if (OptLevel == CodeGenOptLevel::None || !CurMBB.isLayoutSuccessor(Succ0MBB))
1365 MIRBuilder.buildBr(*Succ0MBB);
1366
1367 // Link successors.
1368 for (const BasicBlock *Succ : successors(&BrInst))
1369 CurMBB.addSuccessor(&getMBB(*Succ));
1370 return true;
1371}
1372
1373bool IRTranslatorImpl::translateCondBr(const User &U,
1374 MachineIRBuilder &MIRBuilder) {
1375 const CondBrInst &BrInst = cast<CondBrInst>(U);
1376 auto &CurMBB = MIRBuilder.getMBB();
1377 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
1378
1379 // If this condition is one of the special cases we handle, do special stuff
1380 // now.
1381 const Value *CondVal = BrInst.getCondition();
1382 MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
1383
1384 // If this is a series of conditions that are or'd or and'd together, emit
1385 // this as a sequence of branches instead of setcc's with and/or operations.
1386 // As long as jumps are not expensive (exceptions for multi-use logic ops,
1387 // unpredictable branches, and vector extracts because those jumps are likely
1388 // expensive for any target), this should improve performance.
1389 // For example, instead of something like:
1390 // cmp A, B
1391 // C = seteq
1392 // cmp D, E
1393 // F = setle
1394 // or C, F
1395 // jnz foo
1396 // Emit:
1397 // cmp A, B
1398 // je foo
1399 // cmp D, E
1400 // jle foo
1401 using namespace PatternMatch;
1402 const Instruction *CondI = dyn_cast<Instruction>(CondVal);
1403 if (!TLI->isJumpExpensive() && CondI && CondI->hasOneUse() &&
1404 !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
1406 Value *Vec;
1407 const Value *BOp0, *BOp1;
1408 if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
1409 Opcode = Instruction::And;
1410 else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
1411 Opcode = Instruction::Or;
1412
1413 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
1414 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
1415 findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
1416 getEdgeProbability(&CurMBB, Succ0MBB),
1417 getEdgeProbability(&CurMBB, Succ1MBB),
1418 /*InvertCond=*/false);
1419 assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
1420
1421 // Allow some cases to be rejected.
1422 if (shouldEmitAsBranches(SL->SwitchCases)) {
1423 // Emit the branch for this block.
1424 emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
1425 SL->SwitchCases.erase(SL->SwitchCases.begin());
1426 return true;
1427 }
1428
1429 // Okay, we decided not to do this, remove any inserted MBB's and clear
1430 // SwitchCases.
1431 for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
1432 MF->erase(SL->SwitchCases[I].ThisBB);
1433
1434 SL->SwitchCases.clear();
1435 }
1436 }
1437
1438 // Create a CaseBlock record representing this branch.
1439 SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
1440 ConstantInt::getTrue(MF->getFunction().getContext()),
1441 nullptr, Succ0MBB, Succ1MBB, &CurMBB,
1442 CurBuilder->getDebugLoc());
1443
1444 // Use emitSwitchCase to actually insert the fast branch sequence for this
1445 // cond branch.
1446 emitSwitchCase(CB, &CurMBB, *CurBuilder);
1447 return true;
1448}
1449
1450void IRTranslatorImpl::addSuccessorWithProb(MachineBasicBlock *Src,
1451 MachineBasicBlock *Dst,
1452 BranchProbability Prob) {
1453 if (!FuncInfo.BPI) {
1454 Src->addSuccessorWithoutProb(Dst);
1455 return;
1456 }
1457 if (Prob.isUnknown())
1458 Prob = getEdgeProbability(Src, Dst);
1459 Src->addSuccessor(Dst, Prob);
1460}
1461
1463IRTranslatorImpl::getEdgeProbability(const MachineBasicBlock *Src,
1464 const MachineBasicBlock *Dst) const {
1465 const BasicBlock *SrcBB = Src->getBasicBlock();
1466 const BasicBlock *DstBB = Dst->getBasicBlock();
1467 if (!FuncInfo.BPI) {
1468 // If BPI is not available, set the default probability as 1 / N, where N is
1469 // the number of successors.
1470 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1471 return BranchProbability(1, SuccSize);
1472 }
1473 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
1474}
1475
1476bool IRTranslatorImpl::translateSwitch(const User &U, MachineIRBuilder &MIB) {
1477 using namespace SwitchCG;
1478 // Extract cases from the switch.
1479 const SwitchInst &SI = cast<SwitchInst>(U);
1480 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1481 CaseClusterVector Clusters;
1482 Clusters.reserve(SI.getNumCases());
1483 for (const auto &I : SI.cases()) {
1484 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
1485 assert(Succ && "Could not find successor mbb in mapping");
1486 const ConstantInt *CaseVal = I.getCaseValue();
1487 BranchProbability Prob =
1488 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
1489 : BranchProbability(1, SI.getNumCases() + 1);
1490 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
1491 }
1492
1493 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
1494
1495 // Cluster adjacent cases with the same destination. We do this at all
1496 // optimization levels because it's cheap to do and will make codegen faster
1497 // if there are many clusters.
1498 sortAndRangeify(Clusters);
1499
1500 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
1501
1502 // If there is only the default destination, jump there directly.
1503 if (Clusters.empty()) {
1504 SwitchMBB->addSuccessor(DefaultMBB);
1505 if (DefaultMBB != SwitchMBB->getNextNode())
1506 MIB.buildBr(*DefaultMBB);
1507 return true;
1508 }
1509
1510 SL->findJumpTables(Clusters, &SI, std::nullopt, DefaultMBB, nullptr, nullptr);
1511 SL->findBitTestClusters(Clusters, &SI);
1512
1513 LLVM_DEBUG({
1514 dbgs() << "Case clusters: ";
1515 for (const CaseCluster &C : Clusters) {
1516 if (C.Kind == CC_JumpTable)
1517 dbgs() << "JT:";
1518 if (C.Kind == CC_BitTests)
1519 dbgs() << "BT:";
1520
1521 C.Low->getValue().print(dbgs(), true);
1522 if (C.Low != C.High) {
1523 dbgs() << '-';
1524 C.High->getValue().print(dbgs(), true);
1525 }
1526 dbgs() << ' ';
1527 }
1528 dbgs() << '\n';
1529 });
1530
1531 assert(!Clusters.empty());
1532 SwitchWorkList WorkList;
1533 CaseClusterIt First = Clusters.begin();
1534 CaseClusterIt Last = Clusters.end() - 1;
1535 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
1536 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
1537
1538 while (!WorkList.empty()) {
1539 SwitchWorkListItem W = WorkList.pop_back_val();
1540
1541 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
1542 // For optimized builds, lower large range as a balanced binary tree.
1543 if (NumClusters > 3 &&
1544 MF->getTarget().getOptLevel() != CodeGenOptLevel::None &&
1545 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
1546 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB, MIB);
1547 continue;
1548 }
1549
1550 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
1551 return false;
1552 }
1553 return true;
1554}
1555
1556void IRTranslatorImpl::splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
1558 Value *Cond, MachineBasicBlock *SwitchMBB,
1559 MachineIRBuilder &MIB) {
1560 using namespace SwitchCG;
1561 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
1562 "Clusters not sorted?");
1563 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
1564
1565 auto [LastLeft, FirstRight, LeftProb, RightProb] =
1566 SL->computeSplitWorkItemInfo(W);
1567
1568 // Use the first element on the right as pivot since we will make less-than
1569 // comparisons against it.
1570 CaseClusterIt PivotCluster = FirstRight;
1571 assert(PivotCluster > W.FirstCluster);
1572 assert(PivotCluster <= W.LastCluster);
1573
1574 CaseClusterIt FirstLeft = W.FirstCluster;
1575 CaseClusterIt LastRight = W.LastCluster;
1576
1577 const ConstantInt *Pivot = PivotCluster->Low;
1578
1579 // New blocks will be inserted immediately after the current one.
1581 ++BBI;
1582
1583 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
1584 // we can branch to its destination directly if it's squeezed exactly in
1585 // between the known lower bound and Pivot - 1.
1586 MachineBasicBlock *LeftMBB;
1587 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
1588 FirstLeft->Low == W.GE &&
1589 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
1590 LeftMBB = FirstLeft->MBB;
1591 } else {
1592 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
1593 FuncInfo.MF->insert(BBI, LeftMBB);
1594 WorkList.push_back(
1595 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
1596 }
1597
1598 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
1599 // single cluster, RHS.Low == Pivot, and we can branch to its destination
1600 // directly if RHS.High equals the current upper bound.
1601 MachineBasicBlock *RightMBB;
1602 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && W.LT &&
1603 (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
1604 RightMBB = FirstRight->MBB;
1605 } else {
1606 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
1607 FuncInfo.MF->insert(BBI, RightMBB);
1608 WorkList.push_back(
1609 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
1610 }
1611
1612 // Create the CaseBlock record that will be used to lower the branch.
1613 CaseBlock CB(ICmpInst::Predicate::ICMP_SLT, false, Cond, Pivot, nullptr,
1614 LeftMBB, RightMBB, W.MBB, MIB.getDebugLoc(), LeftProb,
1615 RightProb);
1616
1617 if (W.MBB == SwitchMBB)
1618 emitSwitchCase(CB, SwitchMBB, MIB);
1619 else
1620 SL->SwitchCases.push_back(CB);
1621}
1622
1623void IRTranslatorImpl::emitJumpTable(SwitchCG::JumpTable &JT,
1625 // Emit the code for the jump table
1626 assert(JT.Reg && "Should lower JT Header first!");
1627 MachineIRBuilder MIB(*MBB->getParent());
1628 MIB.setMBB(*MBB);
1629 MIB.setDebugLoc(CurBuilder->getDebugLoc());
1630
1631 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1632 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1633
1634 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
1635 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
1636}
1637
1638bool IRTranslatorImpl::emitJumpTableHeader(SwitchCG::JumpTable &JT,
1640 MachineBasicBlock *HeaderBB) {
1641 MachineIRBuilder MIB(*HeaderBB->getParent());
1642 MIB.setMBB(*HeaderBB);
1643 MIB.setDebugLoc(CurBuilder->getDebugLoc());
1644
1645 const Value &SValue = *JTH.SValue;
1646 // Subtract the lowest switch case value from the value being switched on.
1647 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
1648 Register SwitchOpReg = getOrCreateVReg(SValue);
1649 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
1650 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
1651
1652 // This value may be smaller or larger than the target's pointer type, and
1653 // therefore require extension or truncating.
1654 auto *PtrIRTy = PointerType::getUnqual(SValue.getContext());
1655 const LLT PtrScalarTy = LLT::integer(DL->getTypeSizeInBits(PtrIRTy));
1656 Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
1657
1658 JT.Reg = Sub.getReg(0);
1659
1660 if (JTH.FallthroughUnreachable) {
1661 if (JT.MBB != HeaderBB->getNextNode())
1662 MIB.buildBr(*JT.MBB);
1663 return true;
1664 }
1665
1666 // Emit the range check for the jump table, and branch to the default block
1667 // for the switch statement if the value being switched on exceeds the
1668 // largest case in the switch.
1669 auto Cst = getOrCreateVReg(
1670 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
1671 Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
1672 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::integer(1), Sub, Cst);
1673
1674 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
1675
1676 // Avoid emitting unnecessary branches to the next block.
1677 if (JT.MBB != HeaderBB->getNextNode())
1678 BrCond = MIB.buildBr(*JT.MBB);
1679 return true;
1680}
1681
1682void IRTranslatorImpl::emitSwitchCase(SwitchCG::CaseBlock &CB,
1683 MachineBasicBlock *SwitchBB,
1684 MachineIRBuilder &MIB) {
1685 Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
1686 Register Cond;
1687 DebugLoc OldDbgLoc = MIB.getDebugLoc();
1688 MIB.setDebugLoc(CB.DbgLoc);
1689 MIB.setMBB(*CB.ThisBB);
1690
1691 if (CB.PredInfo.NoCmp) {
1692 // Branch or fall through to TrueBB.
1693 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
1694 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
1695 CB.ThisBB);
1697 if (CB.TrueBB != CB.ThisBB->getNextNode())
1698 MIB.buildBr(*CB.TrueBB);
1699 MIB.setDebugLoc(OldDbgLoc);
1700 return;
1701 }
1702
1703 const LLT i1Ty = LLT::integer(1);
1704 // Build the compare.
1705 if (!CB.CmpMHS) {
1706 const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
1707 // For conditional branch lowering, we might try to do something silly like
1708 // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
1709 // just re-use the existing condition vreg.
1710 if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI && CI->isOne() &&
1712 Cond = CondLHS;
1713 } else {
1714 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
1716 Cond =
1717 MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
1718 else
1719 Cond =
1720 MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
1721 }
1722 } else {
1724 "Can only handle SLE ranges");
1725
1726 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1727 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1728
1729 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
1730 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1731 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
1732 Cond =
1733 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
1734 } else {
1735 const LLT CmpTy = MRI->getType(CmpOpReg);
1736 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
1737 auto Diff = MIB.buildConstant(CmpTy, High - Low);
1738 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
1739 }
1740 }
1741
1742 // Update successor info
1743 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
1744
1745 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
1746 CB.ThisBB);
1747
1748 // TrueBB and FalseBB are always different unless the incoming IR is
1749 // degenerate. This only happens when running llc on weird IR.
1750 if (CB.TrueBB != CB.FalseBB)
1751 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
1753
1754 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
1755 CB.ThisBB);
1756
1757 MIB.buildBrCond(Cond, *CB.TrueBB);
1758 MIB.buildBr(*CB.FalseBB);
1759 MIB.setDebugLoc(OldDbgLoc);
1760}
1761
1762bool IRTranslatorImpl::lowerJumpTableWorkItem(
1764 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1767 MachineBasicBlock *Fallthrough, bool FallthroughUnreachable) {
1768 using namespace SwitchCG;
1769 MachineFunction *CurMF = SwitchMBB->getParent();
1770 // FIXME: Optimize away range check based on pivot comparisons.
1771 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
1772 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
1773 BranchProbability DefaultProb = W.DefaultProb;
1774
1775 // The jump block hasn't been inserted yet; insert it here.
1776 MachineBasicBlock *JumpMBB = JT->MBB;
1777 CurMF->insert(BBI, JumpMBB);
1778
1779 // Since the jump table block is separate from the switch block, we need
1780 // to keep track of it as a machine predecessor to the default block,
1781 // otherwise we lose the phi edges.
1782 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1783 CurMBB);
1784 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1785 JumpMBB);
1786
1787 auto JumpProb = I->Prob;
1788 auto FallthroughProb = UnhandledProbs;
1789
1790 // If the default statement is a target of the jump table, we evenly
1791 // distribute the default probability to successors of CurMBB. Also
1792 // update the probability on the edge from JumpMBB to Fallthrough.
1793 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
1794 SE = JumpMBB->succ_end();
1795 SI != SE; ++SI) {
1796 if (*SI == DefaultMBB) {
1797 JumpProb += DefaultProb / 2;
1798 FallthroughProb -= DefaultProb / 2;
1799 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
1800 JumpMBB->normalizeSuccProbs();
1801 } else {
1802 // Also record edges from the jump table block to it's successors.
1803 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
1804 JumpMBB);
1805 }
1806 }
1807
1808 if (FallthroughUnreachable)
1809 JTH->FallthroughUnreachable = true;
1810
1811 if (!JTH->FallthroughUnreachable)
1812 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
1813 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
1814 CurMBB->normalizeSuccProbs();
1815
1816 // The jump table header will be inserted in our current block, do the
1817 // range check, and fall through to our fallthrough block.
1818 JTH->HeaderBB = CurMBB;
1819 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
1820
1821 // If we're in the right place, emit the jump table header right now.
1822 if (CurMBB == SwitchMBB) {
1823 if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
1824 return false;
1825 JTH->Emitted = true;
1826 }
1827 return true;
1828}
1829bool IRTranslatorImpl::lowerSwitchRangeWorkItem(
1831 bool FallthroughUnreachable, BranchProbability UnhandledProbs,
1832 MachineBasicBlock *CurMBB, MachineIRBuilder &MIB,
1833 MachineBasicBlock *SwitchMBB) {
1834 using namespace SwitchCG;
1835 const Value *RHS, *LHS, *MHS;
1836 CmpInst::Predicate Pred;
1837 if (I->Low == I->High) {
1838 // Check Cond == I->Low.
1839 Pred = CmpInst::ICMP_EQ;
1840 LHS = Cond;
1841 RHS = I->Low;
1842 MHS = nullptr;
1843 } else {
1844 // Check I->Low <= Cond <= I->High.
1845 Pred = CmpInst::ICMP_SLE;
1846 LHS = I->Low;
1847 MHS = Cond;
1848 RHS = I->High;
1849 }
1850
1851 // If Fallthrough is unreachable, fold away the comparison.
1852 // The false probability is the sum of all unhandled cases.
1853 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
1854 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
1855
1856 emitSwitchCase(CB, SwitchMBB, MIB);
1857 return true;
1858}
1859
1860void IRTranslatorImpl::emitBitTestHeader(SwitchCG::BitTestBlock &B,
1861 MachineBasicBlock *SwitchBB) {
1862 MachineIRBuilder &MIB = *CurBuilder;
1863 MIB.setMBB(*SwitchBB);
1864
1865 // Subtract the minimum value.
1866 Register SwitchOpReg = getOrCreateVReg(*B.SValue);
1867
1868 LLT SwitchOpTy = MRI->getType(SwitchOpReg);
1869 Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
1870 auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
1871
1872 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1873 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1874
1875 LLT MaskTy = SwitchOpTy;
1876 if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
1878 MaskTy = LLT::integer(PtrTy.getSizeInBits());
1879 else {
1880 // Ensure that the type will fit the mask value.
1881 for (const SwitchCG::BitTestCase &Case : B.Cases) {
1882 if (!isUIntN(SwitchOpTy.getSizeInBits(), Case.Mask)) {
1883 // Switch table case range are encoded into series of masks.
1884 // Just use pointer type, it's guaranteed to fit.
1885 MaskTy = LLT::integer(PtrTy.getSizeInBits());
1886 break;
1887 }
1888 }
1889 }
1890 Register SubReg = RangeSub.getReg(0);
1891 if (SwitchOpTy != MaskTy)
1892 SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
1893
1894 B.RegVT = getMVTForLLT(MaskTy);
1895 B.Reg = SubReg;
1896
1897 MachineBasicBlock *MBB = B.Cases[0].ThisBB;
1898
1899 if (!B.FallthroughUnreachable)
1900 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
1901 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
1902
1903 SwitchBB->normalizeSuccProbs();
1904
1905 if (!B.FallthroughUnreachable) {
1906 // Conditional branch to the default block.
1907 auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
1908 auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::integer(1),
1909 RangeSub, RangeCst);
1910 MIB.buildBrCond(RangeCmp, *B.Default);
1911 }
1912
1913 // Avoid emitting unnecessary branches to the next block.
1914 if (MBB != SwitchBB->getNextNode())
1915 MIB.buildBr(*MBB);
1916}
1917
1918void IRTranslatorImpl::emitBitTestCase(SwitchCG::BitTestBlock &BB,
1919 MachineBasicBlock *NextMBB,
1920 BranchProbability BranchProbToNext,
1922 MachineBasicBlock *SwitchBB) {
1923 MachineIRBuilder &MIB = *CurBuilder;
1924 MIB.setMBB(*SwitchBB);
1925
1926 LLT SwitchTy = getLLTForMVT(BB.RegVT);
1927 Register Cmp;
1928 unsigned PopCount = llvm::popcount(B.Mask);
1929 if (PopCount == 1) {
1930 // Testing for a single bit; just compare the shift count with what it
1931 // would need to be to shift a 1 bit in that position.
1932 auto MaskTrailingZeros =
1933 MIB.buildConstant(SwitchTy, llvm::countr_zero(B.Mask));
1935 MaskTrailingZeros)
1936 .getReg(0);
1937 } else if (PopCount == BB.Range) {
1938 // There is only one zero bit in the range, test for it directly.
1939 auto MaskTrailingOnes =
1940 MIB.buildConstant(SwitchTy, llvm::countr_one(B.Mask));
1941 Cmp =
1942 MIB.buildICmp(CmpInst::ICMP_NE, LLT::integer(1), Reg, MaskTrailingOnes)
1943 .getReg(0);
1944 } else {
1945 // Make desired shift.
1946 auto CstOne = MIB.buildConstant(SwitchTy, 1);
1947 auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
1948
1949 // Emit bit tests and jumps.
1950 auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
1951 auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
1952 auto CstZero = MIB.buildConstant(SwitchTy, 0);
1953 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::integer(1), AndOp, CstZero)
1954 .getReg(0);
1955 }
1956
1957 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
1958 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
1959 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
1960 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
1961 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
1962 // one as they are relative probabilities (and thus work more like weights),
1963 // and hence we need to normalize them to let the sum of them become one.
1964 SwitchBB->normalizeSuccProbs();
1965
1966 // Record the fact that the IR edge from the header to the bit test target
1967 // will go through our new block. Neeeded for PHIs to have nodes added.
1968 addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
1969 SwitchBB);
1970
1971 MIB.buildBrCond(Cmp, *B.TargetBB);
1972
1973 // Avoid emitting unnecessary branches to the next block.
1974 if (NextMBB != SwitchBB->getNextNode())
1975 MIB.buildBr(*NextMBB);
1976}
1977
1978bool IRTranslatorImpl::lowerBitTestWorkItem(
1980 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1982 BranchProbability DefaultProb, BranchProbability UnhandledProbs,
1984 bool FallthroughUnreachable) {
1985 using namespace SwitchCG;
1986 MachineFunction *CurMF = SwitchMBB->getParent();
1987 // FIXME: Optimize away range check based on pivot comparisons.
1988 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
1989 // The bit test blocks haven't been inserted yet; insert them here.
1990 for (BitTestCase &BTC : BTB->Cases)
1991 CurMF->insert(BBI, BTC.ThisBB);
1992
1993 // Fill in fields of the BitTestBlock.
1994 BTB->Parent = CurMBB;
1995 BTB->Default = Fallthrough;
1996
1997 BTB->DefaultProb = UnhandledProbs;
1998 // If the cases in bit test don't form a contiguous range, we evenly
1999 // distribute the probability on the edge to Fallthrough to two
2000 // successors of CurMBB.
2001 if (!BTB->ContiguousRange) {
2002 BTB->Prob += DefaultProb / 2;
2003 BTB->DefaultProb -= DefaultProb / 2;
2004 }
2005
2006 if (FallthroughUnreachable)
2007 BTB->FallthroughUnreachable = true;
2008
2009 // If we're in the right place, emit the bit test header right now.
2010 if (CurMBB == SwitchMBB) {
2011 emitBitTestHeader(*BTB, SwitchMBB);
2012 BTB->Emitted = true;
2013 }
2014 return true;
2015}
2016
2017bool IRTranslatorImpl::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
2018 Value *Cond,
2019 MachineBasicBlock *SwitchMBB,
2020 MachineBasicBlock *DefaultMBB,
2021 MachineIRBuilder &MIB) {
2022 using namespace SwitchCG;
2023 MachineFunction *CurMF = FuncInfo.MF;
2024 MachineBasicBlock *NextMBB = nullptr;
2026 if (++BBI != FuncInfo.MF->end())
2027 NextMBB = &*BBI;
2028
2029 if (EnableOpts) {
2030 // Here, we order cases by probability so the most likely case will be
2031 // checked first. However, two clusters can have the same probability in
2032 // which case their relative ordering is non-deterministic. So we use Low
2033 // as a tie-breaker as clusters are guaranteed to never overlap.
2034 llvm::sort(W.FirstCluster, W.LastCluster + 1,
2035 [](const CaseCluster &a, const CaseCluster &b) {
2036 return a.Prob != b.Prob
2037 ? a.Prob > b.Prob
2038 : a.Low->getValue().slt(b.Low->getValue());
2039 });
2040
2041 // Rearrange the case blocks so that the last one falls through if possible
2042 // without changing the order of probabilities.
2043 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
2044 --I;
2045 if (I->Prob > W.LastCluster->Prob)
2046 break;
2047 if (I->Kind == CC_Range && I->MBB == NextMBB) {
2048 std::swap(*I, *W.LastCluster);
2049 break;
2050 }
2051 }
2052 }
2053
2054 // Compute total probability.
2055 BranchProbability DefaultProb = W.DefaultProb;
2056 BranchProbability UnhandledProbs = DefaultProb;
2057 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
2058 UnhandledProbs += I->Prob;
2059
2060 MachineBasicBlock *CurMBB = W.MBB;
2061 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
2062 bool FallthroughUnreachable = false;
2063 MachineBasicBlock *Fallthrough;
2064 if (I == W.LastCluster) {
2065 // For the last cluster, fall through to the default destination.
2066 Fallthrough = DefaultMBB;
2067 FallthroughUnreachable = isa<UnreachableInst>(
2068 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
2069 } else {
2070 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
2071 CurMF->insert(BBI, Fallthrough);
2072 }
2073 UnhandledProbs -= I->Prob;
2074
2075 switch (I->Kind) {
2076 case CC_BitTests: {
2077 if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
2078 DefaultProb, UnhandledProbs, I, Fallthrough,
2079 FallthroughUnreachable)) {
2080 LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
2081 return false;
2082 }
2083 break;
2084 }
2085
2086 case CC_JumpTable: {
2087 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
2088 UnhandledProbs, I, Fallthrough,
2089 FallthroughUnreachable)) {
2090 LLVM_DEBUG(dbgs() << "Failed to lower jump table");
2091 return false;
2092 }
2093 break;
2094 }
2095 case CC_Range: {
2096 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
2097 FallthroughUnreachable, UnhandledProbs,
2098 CurMBB, MIB, SwitchMBB)) {
2099 LLVM_DEBUG(dbgs() << "Failed to lower switch range");
2100 return false;
2101 }
2102 break;
2103 }
2104 }
2105 CurMBB = Fallthrough;
2106 }
2107
2108 return true;
2109}
2110
2111bool IRTranslatorImpl::translateIndirectBr(const User &U,
2112 MachineIRBuilder &MIRBuilder) {
2113 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
2114
2115 const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
2116 MIRBuilder.buildBrIndirect(Tgt);
2117
2118 // Link successors.
2119 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
2120 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
2121 for (const BasicBlock *Succ : successors(&BrInst)) {
2122 // It's legal for indirectbr instructions to have duplicate blocks in the
2123 // destination list. We don't allow this in MIR. Skip anything that's
2124 // already a successor.
2125 if (!AddedSuccessors.insert(Succ).second)
2126 continue;
2127 CurBB.addSuccessor(&getMBB(*Succ));
2128 }
2129
2130 return true;
2131}
2132
2133static bool isSwiftError(const Value *V) {
2134 if (auto Arg = dyn_cast<Argument>(V))
2135 return Arg->hasSwiftErrorAttr();
2136 if (auto AI = dyn_cast<AllocaInst>(V))
2137 return AI->isSwiftError();
2138 return false;
2139}
2140
2141bool IRTranslatorImpl::translateLoad(const User &U,
2142 MachineIRBuilder &MIRBuilder) {
2143 const LoadInst &LI = cast<LoadInst>(U);
2144 TypeSize StoreSize = DL->getTypeStoreSize(LI.getType());
2145 if (StoreSize.isZero())
2146 return true;
2147
2148 ArrayRef<Register> Regs = getOrCreateVRegs(LI);
2149 Register Base = getOrCreateVReg(*LI.getPointerOperand());
2150 AAMDNodes AAInfo = LI.getAAMetadata();
2151
2152 const Value *Ptr = LI.getPointerOperand();
2153
2154 if (CLI->supportSwiftError() && isSwiftError(Ptr)) {
2155 assert(Regs.size() == 1 && "swifterror should be single pointer");
2156 Register VReg =
2157 SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), Ptr);
2158 MIRBuilder.buildCopy(Regs[0], VReg);
2159 return true;
2160 }
2161
2163 TLI->getLoadMemOperandFlags(LI, *DL, AC, LibInfo, OptLevel);
2164 if (AA && !(Flags & MachineMemOperand::MOInvariant)) {
2165 if (AA->pointsToConstantMemory(
2166 MemoryLocation(Ptr, LocationSize::precise(StoreSize), AAInfo))) {
2168 }
2169 }
2170
2171 // Fast-path the common single-register load.
2172 if (Regs.size() == 1) {
2173 auto *MMO = MF->getMachineMemOperand(
2174 MachinePointerInfo(LI.getPointerOperand()), Flags,
2175 MRI->getType(Regs[0]), getMemOpAlign(LI),
2176 MMOMetadata(AAInfo, LI.getMetadata(LLVMContext::MD_range)),
2177 LI.getSyncScopeID(), LI.getOrdering());
2178 MIRBuilder.buildLoad(Regs[0], Base, *MMO);
2179 return true;
2180 }
2181
2182 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
2183 Type *OffsetIRTy = DL->getIndexType(Ptr->getType());
2184 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2185 for (unsigned i = 0; i < Regs.size(); ++i) {
2186 Register Addr;
2187 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i]);
2188
2189 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i]);
2190 Align BaseAlign = getMemOpAlign(LI);
2191 auto *MMO =
2192 MF->getMachineMemOperand(Ptr, Flags, MRI->getType(Regs[i]),
2193 commonAlignment(BaseAlign, Offsets[i]), AAInfo,
2194 LI.getSyncScopeID(), LI.getOrdering());
2195 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
2196 }
2197
2198 return true;
2199}
2200
2201bool IRTranslatorImpl::translateStore(const User &U,
2202 MachineIRBuilder &MIRBuilder) {
2203 const StoreInst &SI = cast<StoreInst>(U);
2204 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()).isZero())
2205 return true;
2206
2207 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
2208 Register Base = getOrCreateVReg(*SI.getPointerOperand());
2209
2210 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
2211 assert(Vals.size() == 1 && "swifterror should be single pointer");
2212
2213 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
2214 SI.getPointerOperand());
2215 MIRBuilder.buildCopy(VReg, Vals[0]);
2216 return true;
2217 }
2218
2219 MachineMemOperand::Flags Flags = TLI->getStoreMemOperandFlags(SI, *DL);
2220 // Fast-path the common single-register store.
2221 if (Vals.size() == 1) {
2222 auto *MMO = MF->getMachineMemOperand(
2223 MachinePointerInfo(SI.getPointerOperand()), Flags,
2224 MRI->getType(Vals[0]), getMemOpAlign(SI), SI.getAAMetadata(),
2225 SI.getSyncScopeID(), SI.getOrdering());
2226 MIRBuilder.buildStore(Vals[0], Base, *MMO);
2227 return true;
2228 }
2229
2230 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
2231 Type *OffsetIRTy = DL->getIndexType(SI.getPointerOperandType());
2232 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2233 for (unsigned i = 0; i < Vals.size(); ++i) {
2234 Register Addr;
2235 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i]);
2236
2237 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i]);
2238 Align BaseAlign = getMemOpAlign(SI);
2239 auto *MMO = MF->getMachineMemOperand(Ptr, Flags, MRI->getType(Vals[i]),
2240 commonAlignment(BaseAlign, Offsets[i]),
2241 SI.getAAMetadata(),
2242 SI.getSyncScopeID(), SI.getOrdering());
2243 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
2244 }
2245 return true;
2246}
2247
2249 const Value *Src = U.getOperand(0);
2250 Type *Int32Ty = Type::getInt32Ty(U.getContext());
2251
2252 // getIndexedOffsetInType is designed for GEPs, so the first index is the
2253 // usual array element rather than looking into the actual aggregate.
2255 Indices.push_back(ConstantInt::get(Int32Ty, 0));
2256
2257 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
2258 for (auto Idx : EVI->indices())
2259 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
2260 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
2261 for (auto Idx : IVI->indices())
2262 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
2263 } else {
2264 llvm::append_range(Indices, drop_begin(U.operands()));
2265 }
2266
2267 return static_cast<uint64_t>(
2268 DL.getIndexedOffsetInType(Src->getType(), Indices));
2269}
2270
2271bool IRTranslatorImpl::translateExtractValue(const User &U,
2272 MachineIRBuilder &MIRBuilder) {
2273 const Value *Src = U.getOperand(0);
2275 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
2276 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
2277 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
2278 auto &DstRegs = allocateVRegs(U);
2279
2280 for (unsigned i = 0; i < DstRegs.size(); ++i)
2281 DstRegs[i] = SrcRegs[Idx++];
2282
2283 return true;
2284}
2285
2286bool IRTranslatorImpl::translateInsertValue(const User &U,
2287 MachineIRBuilder &MIRBuilder) {
2288 const Value *Src = U.getOperand(0);
2290 auto &DstRegs = allocateVRegs(U);
2291 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
2292 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
2293 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
2294 auto *InsertedIt = InsertedRegs.begin();
2295
2296 for (unsigned i = 0; i < DstRegs.size(); ++i) {
2297 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
2298 DstRegs[i] = *InsertedIt++;
2299 else
2300 DstRegs[i] = SrcRegs[i];
2301 }
2302
2303 return true;
2304}
2305
2306bool IRTranslatorImpl::translateSelect(const User &U,
2307 MachineIRBuilder &MIRBuilder) {
2308 Register Tst = getOrCreateVReg(*U.getOperand(0));
2309 ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
2310 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
2311 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
2312
2313 uint32_t Flags = 0;
2314 if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
2316
2317 for (unsigned i = 0; i < ResRegs.size(); ++i) {
2318 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
2319 }
2320
2321 return true;
2322}
2323
2324bool IRTranslatorImpl::translateCopy(const User &U, const Value &V,
2325 MachineIRBuilder &MIRBuilder) {
2326 return translateCopy(U, getOrCreateVReg(V), MIRBuilder);
2327}
2328
2329bool IRTranslatorImpl::translateCopy(const User &U, Register Src,
2330 MachineIRBuilder &MIRBuilder) {
2331 auto &Regs = *VMap.getVRegs(U);
2332 if (Regs.empty()) {
2333 Regs.push_back(Src);
2334 VMap.getOffsets(U)->push_back(0);
2335 } else {
2336 // If we already assigned a vreg for this instruction, we can't change that.
2337 // Emit a copy to satisfy the users we already emitted.
2338 MIRBuilder.buildCopy(Regs[0], Src);
2339 }
2340 return true;
2341}
2342
2343bool IRTranslatorImpl::translateBitCast(const User &U,
2344 MachineIRBuilder &MIRBuilder) {
2345 Type *SrcTy = U.getOperand(0)->getType();
2346 Type *DstTy = U.getType();
2347
2348 // If we're bitcasting to the source type, we can reuse the source vreg.
2349 if (getLLTForType(*SrcTy, *DL) == getLLTForType(*DstTy, *DL)) {
2350 // If the source is a ConstantInt then it was probably created by
2351 // ConstantHoisting and we should leave it alone.
2352 if (isa<ConstantInt>(U.getOperand(0)))
2353 return translateCast(TargetOpcode::G_CONSTANT_FOLD_BARRIER, U,
2354 MIRBuilder);
2355 return translateCopy(U, *U.getOperand(0), MIRBuilder);
2356 }
2357
2358 // Only the scalar byte<->ptr crossing is redirected to G_INTTOPTR/G_PTRTOINT,
2359 // which is the well-typed MIR shape for that boundary. Vector byte<->ptr
2360 // (e.g. <N x b32> -> ptr produced by mixed-type load coalescing) and other
2361 // legacy ptr/non-ptr IR bitcasts (AMDGPU iN<->p3 kernarg packing, etc.)
2362 // keep their historical G_BITCAST lowering — G_INTTOPTR has no vector-src
2363 // -> scalar-ptr form, and downstream passes already handle G_BITCAST.
2364 if (DstTy->isPointerTy() && SrcTy->isByteTy())
2365 return translateCast(TargetOpcode::G_INTTOPTR, U, MIRBuilder);
2366 if (SrcTy->isPointerTy() && DstTy->isByteTy())
2367 return translateCast(TargetOpcode::G_PTRTOINT, U, MIRBuilder);
2368
2369 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
2370}
2371
2372bool IRTranslatorImpl::translateCast(unsigned Opcode, const User &U,
2373 MachineIRBuilder &MIRBuilder) {
2374 if (!mayTranslateUserTypes(U))
2375 return false;
2376
2377 uint32_t Flags = 0;
2378 if (const Instruction *I = dyn_cast<Instruction>(&U))
2380
2381 Register Op = getOrCreateVReg(*U.getOperand(0));
2382 Register Res = getOrCreateVReg(U);
2383 MIRBuilder.buildInstr(Opcode, {Res}, {Op}, Flags);
2384 return true;
2385}
2386
2387bool IRTranslatorImpl::translateGetElementPtr(const User &U,
2388 MachineIRBuilder &MIRBuilder) {
2389 Value &Op0 = *U.getOperand(0);
2390 Register BaseReg = getOrCreateVReg(Op0);
2391 Type *PtrIRTy = Op0.getType();
2392 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
2393 Type *OffsetIRTy = DL->getIndexType(PtrIRTy);
2394 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2395
2396 uint32_t PtrAddFlags = 0;
2397 // Each PtrAdd generated to implement the GEP inherits its nuw, nusw, inbounds
2398 // flags.
2399 if (const Instruction *I = dyn_cast<Instruction>(&U))
2401
2402 auto PtrAddFlagsWithConst = [&](int64_t Offset) {
2403 // For nusw/inbounds GEP with an offset that is nonnegative when interpreted
2404 // as signed, assume there is no unsigned overflow.
2405 if (Offset >= 0 && (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap))
2406 return PtrAddFlags | MachineInstr::MIFlag::NoUWrap;
2407 return PtrAddFlags;
2408 };
2409
2410 // Normalize Vector GEP - all scalar operands should be converted to the
2411 // splat vector.
2412 unsigned VectorWidth = 0;
2413
2414 // True if we should use a splat vector; using VectorWidth alone is not
2415 // sufficient.
2416 bool WantSplatVector = false;
2417 if (auto *VT = dyn_cast<VectorType>(U.getType())) {
2418 VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
2419 // We don't produce 1 x N vectors; those are treated as scalars.
2420 WantSplatVector = VectorWidth > 1;
2421 }
2422
2423 if (cast<GEPOperator>(U).hasAllZeroIndices())
2424 return translateCopy(U, BaseReg, MIRBuilder);
2425
2426 // We might need to splat the base pointer into a vector if the offsets
2427 // are vectors.
2428 if (WantSplatVector && !PtrTy.isVector()) {
2429 BaseReg = MIRBuilder
2430 .buildSplatBuildVector(LLT::fixed_vector(VectorWidth, PtrTy),
2431 BaseReg)
2432 .getReg(0);
2433 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
2434 PtrTy = getLLTForType(*PtrIRTy, *DL);
2435 OffsetIRTy = DL->getIndexType(PtrIRTy);
2436 OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2437 }
2438
2439 int64_t Offset = 0;
2440 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
2441 GTI != E; ++GTI) {
2442 const Value *Idx = GTI.getOperand();
2443 if (StructType *StTy = GTI.getStructTypeOrNull()) {
2444 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
2445 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
2446 continue;
2447 } else {
2448 uint64_t ElementSize = GTI.getSequentialElementStride(*DL);
2449
2450 // If this is a scalar constant or a splat vector of constants,
2451 // handle it quickly.
2452 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
2453 if (std::optional<int64_t> Val = CI->getValue().trySExtValue()) {
2454 Offset += ElementSize * *Val;
2455 continue;
2456 }
2457 }
2458
2459 if (Offset != 0) {
2460 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
2461 BaseReg = MIRBuilder
2462 .buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0),
2463 PtrAddFlagsWithConst(Offset))
2464 .getReg(0);
2465 Offset = 0;
2466 }
2467
2468 Register IdxReg = getOrCreateVReg(*Idx);
2469 LLT IdxTy = MRI->getType(IdxReg);
2470 if (IdxTy != OffsetTy) {
2471 if (!IdxTy.isVector() && WantSplatVector) {
2472 IdxReg = MIRBuilder
2474 IdxReg)
2475 .getReg(0);
2476 }
2477
2478 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
2479 }
2480
2481 // N = N + Idx * ElementSize;
2482 // Avoid doing it for ElementSize of 1.
2483 Register GepOffsetReg;
2484 if (ElementSize != 1) {
2485 auto ElementSizeMIB = MIRBuilder.buildConstant(
2486 getLLTForType(*OffsetIRTy, *DL), ElementSize);
2487
2488 // The multiplication is NUW if the GEP is NUW and NSW if the GEP is
2489 // NUSW.
2490 uint32_t ScaleFlags = PtrAddFlags & MachineInstr::MIFlag::NoUWrap;
2491 if (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap)
2492 ScaleFlags |= MachineInstr::MIFlag::NoSWrap;
2493
2494 GepOffsetReg =
2495 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB, ScaleFlags)
2496 .getReg(0);
2497 } else {
2498 GepOffsetReg = IdxReg;
2499 }
2500
2501 BaseReg =
2502 MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg, PtrAddFlags)
2503 .getReg(0);
2504 }
2505 }
2506
2507 if (Offset != 0) {
2508 auto OffsetMIB =
2509 MIRBuilder.buildConstant(OffsetTy, Offset);
2510
2511 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0),
2512 PtrAddFlagsWithConst(Offset));
2513 return true;
2514 }
2515
2516 return translateCopy(U, BaseReg, MIRBuilder);
2517}
2518
2519bool IRTranslatorImpl::translateMemFunc(const CallInst &CI,
2520 MachineIRBuilder &MIRBuilder,
2521 unsigned Opcode) {
2522 const Value *SrcPtr = CI.getArgOperand(1);
2523 // If the source is undef, then just emit a nop.
2524 if (isa<UndefValue>(SrcPtr))
2525 return true;
2526
2528
2529 unsigned MinPtrSize = UINT_MAX;
2530 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
2531 Register SrcReg = getOrCreateVReg(**AI);
2532 LLT SrcTy = MRI->getType(SrcReg);
2533 if (SrcTy.isPointer())
2534 MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
2535 SrcRegs.push_back(SrcReg);
2536 }
2537
2538 LLT SizeTy = LLT::integer(MinPtrSize);
2539
2540 // The size operand should be the minimum of the pointer sizes.
2541 Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
2542 if (MRI->getType(SizeOpReg) != SizeTy)
2543 SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
2544
2545 auto ICall = MIRBuilder.buildInstr(Opcode);
2546 for (Register SrcReg : SrcRegs)
2547 ICall.addUse(SrcReg);
2548
2549 Align DstAlign;
2550 Align SrcAlign;
2551 unsigned IsVol =
2552 cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1))->getZExtValue();
2553
2554 ConstantInt *CopySize = nullptr;
2555
2556 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
2557 DstAlign = MCI->getDestAlign().valueOrOne();
2558 SrcAlign = MCI->getSourceAlign().valueOrOne();
2559 CopySize = dyn_cast<ConstantInt>(MCI->getArgOperand(2));
2560 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
2561 DstAlign = MMI->getDestAlign().valueOrOne();
2562 SrcAlign = MMI->getSourceAlign().valueOrOne();
2563 CopySize = dyn_cast<ConstantInt>(MMI->getArgOperand(2));
2564 } else {
2565 auto *MSI = cast<MemSetInst>(&CI);
2566 DstAlign = MSI->getDestAlign().valueOrOne();
2567 }
2568
2569 if (Opcode != TargetOpcode::G_MEMCPY_INLINE &&
2570 Opcode != TargetOpcode::G_MEMSET_INLINE) {
2571 // We need to propagate the tail call flag from the IR inst as an argument.
2572 // Otherwise, we have to pessimize and assume later that we cannot tail call
2573 // any memory intrinsics.
2574 ICall.addImm(CI.isTailCall() ? 1 : 0);
2575 }
2576
2577 // Create mem operands to store the alignment and volatile info.
2580 if (IsVol) {
2581 LoadFlags |= MachineMemOperand::MOVolatile;
2582 StoreFlags |= MachineMemOperand::MOVolatile;
2583 }
2584
2585 AAMDNodes AAInfo = CI.getAAMetadata();
2586 if (AA && CopySize &&
2587 AA->pointsToConstantMemory(MemoryLocation(
2588 SrcPtr, LocationSize::precise(CopySize->getZExtValue()), AAInfo))) {
2589 LoadFlags |= MachineMemOperand::MOInvariant;
2590
2591 // FIXME: pointsToConstantMemory probably does not imply dereferenceable,
2592 // but the previous usage implied it did. Probably should check
2593 // isDereferenceableAndAlignedPointer.
2595 }
2596
2597 ICall.addMemOperand(
2598 MF->getMachineMemOperand(MachinePointerInfo(CI.getArgOperand(0)),
2599 StoreFlags, 1, DstAlign, AAInfo));
2600 if (Opcode != TargetOpcode::G_MEMSET &&
2601 Opcode != TargetOpcode::G_MEMSET_INLINE)
2602 ICall.addMemOperand(MF->getMachineMemOperand(
2603 MachinePointerInfo(SrcPtr), LoadFlags, 1, SrcAlign, AAInfo));
2604
2605 return true;
2606}
2607
2608bool IRTranslatorImpl::translateTrap(const CallInst &CI,
2609 MachineIRBuilder &MIRBuilder,
2610 unsigned Opcode) {
2611 StringRef TrapFuncName =
2612 CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
2613 if (TrapFuncName.empty()) {
2614 if (Opcode == TargetOpcode::G_UBSANTRAP) {
2615 uint64_t Code = cast<ConstantInt>(CI.getOperand(0))->getZExtValue();
2616 MIRBuilder.buildInstr(Opcode, {}, ArrayRef<llvm::SrcOp>{Code});
2617 } else {
2618 MIRBuilder.buildInstr(Opcode);
2619 }
2620 return true;
2621 }
2622
2623 CallLowering::CallLoweringInfo Info;
2624 if (Opcode == TargetOpcode::G_UBSANTRAP)
2625 Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
2626 CI.getArgOperand(0)->getType(), 0});
2627
2628 Info.Callee = MachineOperand::CreateES(TrapFuncName.data());
2629 Info.CB = &CI;
2630 Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
2631 return CLI->lowerCall(MIRBuilder, Info);
2632}
2633
2634bool IRTranslatorImpl::translateVectorInterleave2Intrinsic(
2635 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2636 assert(CI.getIntrinsicID() == Intrinsic::vector_interleave2 &&
2637 "This function can only be called on the interleave2 intrinsic!");
2638 // Canonicalize interleave2 to G_SHUFFLE_VECTOR (similar to SelectionDAG).
2639 Register Op0 = getOrCreateVReg(*CI.getOperand(0));
2640 Register Op1 = getOrCreateVReg(*CI.getOperand(1));
2641 Register Res = getOrCreateVReg(CI);
2642
2643 LLT OpTy = MRI->getType(Op0);
2644 MIRBuilder.buildShuffleVector(Res, Op0, Op1,
2646
2647 return true;
2648}
2649
2650bool IRTranslatorImpl::translateVectorDeinterleave2Intrinsic(
2651 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2652 assert(CI.getIntrinsicID() == Intrinsic::vector_deinterleave2 &&
2653 "This function can only be called on the deinterleave2 intrinsic!");
2654 // Canonicalize deinterleave2 to shuffles that extract sub-vectors (similar to
2655 // SelectionDAG).
2656 Register Op = getOrCreateVReg(*CI.getOperand(0));
2657 auto Undef = MIRBuilder.buildUndef(MRI->getType(Op));
2658 ArrayRef<Register> Res = getOrCreateVRegs(CI);
2659
2660 LLT ResTy = MRI->getType(Res[0]);
2661 if (ResTy.isScalar()) {
2662 MIRBuilder.buildExtractVectorElementConstant(Res[0], Op, 0);
2663 MIRBuilder.buildExtractVectorElementConstant(Res[1], Op, 1);
2664
2665 return true;
2666 }
2667
2668 assert(ResTy.isVector() && "Expected vector result type");
2669 MIRBuilder.buildShuffleVector(Res[0], Op, Undef,
2670 createStrideMask(0, 2, ResTy.getNumElements()));
2671 MIRBuilder.buildShuffleVector(Res[1], Op, Undef,
2672 createStrideMask(1, 2, ResTy.getNumElements()));
2673
2674 return true;
2675}
2676
2677void IRTranslatorImpl::getStackGuard(Register DstReg,
2678 MachineIRBuilder &MIRBuilder) {
2679 Value *Global =
2680 TLI->getSDagStackGuard(*MF->getFunction().getParent(), *Libcalls);
2681 if (!Global) {
2682 LLVMContext &Ctx = MIRBuilder.getContext();
2683 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
2684 MIRBuilder.buildUndef(DstReg);
2685 return;
2686 }
2687
2688 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
2689 MRI->setRegClass(DstReg, TRI->getPointerRegClass());
2690 auto MIB =
2691 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
2692
2693 unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
2694 LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
2695
2696 MachinePointerInfo MPInfo(Global);
2699 MachineMemOperand *MemRef = MF->getMachineMemOperand(
2700 MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
2701 MIB.setMemRefs({MemRef});
2702}
2703
2704bool IRTranslatorImpl::translateOverflowIntrinsic(
2705 const CallInst &CI, unsigned Op, MachineIRBuilder &MIRBuilder) {
2706 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
2707 MIRBuilder.buildInstr(
2708 Op, {ResRegs[0], ResRegs[1]},
2709 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
2710
2711 return true;
2712}
2713
2714bool IRTranslatorImpl::translateFixedPointIntrinsic(
2715 unsigned Op, const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2716 Register Dst = getOrCreateVReg(CI);
2717 Register Src0 = getOrCreateVReg(*CI.getOperand(0));
2718 Register Src1 = getOrCreateVReg(*CI.getOperand(1));
2719 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
2720 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
2721 return true;
2722}
2723
2724unsigned IRTranslatorImpl::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
2725 switch (ID) {
2726 default:
2727 break;
2728 case Intrinsic::acos:
2729 return TargetOpcode::G_FACOS;
2730 case Intrinsic::asin:
2731 return TargetOpcode::G_FASIN;
2732 case Intrinsic::atan:
2733 return TargetOpcode::G_FATAN;
2734 case Intrinsic::atan2:
2735 return TargetOpcode::G_FATAN2;
2736 case Intrinsic::bswap:
2737 return TargetOpcode::G_BSWAP;
2738 case Intrinsic::bitreverse:
2739 return TargetOpcode::G_BITREVERSE;
2740 case Intrinsic::fshl:
2741 return TargetOpcode::G_FSHL;
2742 case Intrinsic::fshr:
2743 return TargetOpcode::G_FSHR;
2744 case Intrinsic::ceil:
2745 return TargetOpcode::G_FCEIL;
2746 case Intrinsic::cos:
2747 return TargetOpcode::G_FCOS;
2748 case Intrinsic::cosh:
2749 return TargetOpcode::G_FCOSH;
2750 case Intrinsic::ctpop:
2751 return TargetOpcode::G_CTPOP;
2752 case Intrinsic::exp:
2753 return TargetOpcode::G_FEXP;
2754 case Intrinsic::exp2:
2755 return TargetOpcode::G_FEXP2;
2756 case Intrinsic::exp10:
2757 return TargetOpcode::G_FEXP10;
2758 case Intrinsic::fabs:
2759 return TargetOpcode::G_FABS;
2760 case Intrinsic::copysign:
2761 return TargetOpcode::G_FCOPYSIGN;
2762 case Intrinsic::minnum:
2763 return TargetOpcode::G_FMINNUM;
2764 case Intrinsic::maxnum:
2765 return TargetOpcode::G_FMAXNUM;
2766 case Intrinsic::minimum:
2767 return TargetOpcode::G_FMINIMUM;
2768 case Intrinsic::maximum:
2769 return TargetOpcode::G_FMAXIMUM;
2770 case Intrinsic::minimumnum:
2771 return TargetOpcode::G_FMINIMUMNUM;
2772 case Intrinsic::maximumnum:
2773 return TargetOpcode::G_FMAXIMUMNUM;
2774 case Intrinsic::canonicalize:
2775 return TargetOpcode::G_FCANONICALIZE;
2776 case Intrinsic::floor:
2777 return TargetOpcode::G_FFLOOR;
2778 case Intrinsic::fma:
2779 return TargetOpcode::G_FMA;
2780 case Intrinsic::log:
2781 return TargetOpcode::G_FLOG;
2782 case Intrinsic::log2:
2783 return TargetOpcode::G_FLOG2;
2784 case Intrinsic::log10:
2785 return TargetOpcode::G_FLOG10;
2786 case Intrinsic::ldexp:
2787 return TargetOpcode::G_FLDEXP;
2788 case Intrinsic::nearbyint:
2789 return TargetOpcode::G_FNEARBYINT;
2790 case Intrinsic::pow:
2791 return TargetOpcode::G_FPOW;
2792 case Intrinsic::powi:
2793 return TargetOpcode::G_FPOWI;
2794 case Intrinsic::rint:
2795 return TargetOpcode::G_FRINT;
2796 case Intrinsic::round:
2797 return TargetOpcode::G_INTRINSIC_ROUND;
2798 case Intrinsic::roundeven:
2799 return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
2800 case Intrinsic::sin:
2801 return TargetOpcode::G_FSIN;
2802 case Intrinsic::sinh:
2803 return TargetOpcode::G_FSINH;
2804 case Intrinsic::sqrt:
2805 return TargetOpcode::G_FSQRT;
2806 case Intrinsic::tan:
2807 return TargetOpcode::G_FTAN;
2808 case Intrinsic::tanh:
2809 return TargetOpcode::G_FTANH;
2810 case Intrinsic::trunc:
2811 return TargetOpcode::G_INTRINSIC_TRUNC;
2812 case Intrinsic::readcyclecounter:
2813 return TargetOpcode::G_READCYCLECOUNTER;
2814 case Intrinsic::readsteadycounter:
2815 return TargetOpcode::G_READSTEADYCOUNTER;
2816 case Intrinsic::ptrmask:
2817 return TargetOpcode::G_PTRMASK;
2818 case Intrinsic::lrint:
2819 return TargetOpcode::G_INTRINSIC_LRINT;
2820 case Intrinsic::llrint:
2821 return TargetOpcode::G_INTRINSIC_LLRINT;
2822 // FADD/FMUL require checking the FMF, so are handled elsewhere.
2823 case Intrinsic::vector_reduce_fmin:
2824 return TargetOpcode::G_VECREDUCE_FMIN;
2825 case Intrinsic::vector_reduce_fmax:
2826 return TargetOpcode::G_VECREDUCE_FMAX;
2827 case Intrinsic::vector_reduce_fminimum:
2828 return TargetOpcode::G_VECREDUCE_FMINIMUM;
2829 case Intrinsic::vector_reduce_fmaximum:
2830 return TargetOpcode::G_VECREDUCE_FMAXIMUM;
2831 case Intrinsic::vector_reduce_add:
2832 return TargetOpcode::G_VECREDUCE_ADD;
2833 case Intrinsic::vector_reduce_mul:
2834 return TargetOpcode::G_VECREDUCE_MUL;
2835 case Intrinsic::vector_reduce_and:
2836 return TargetOpcode::G_VECREDUCE_AND;
2837 case Intrinsic::vector_reduce_or:
2838 return TargetOpcode::G_VECREDUCE_OR;
2839 case Intrinsic::vector_reduce_xor:
2840 return TargetOpcode::G_VECREDUCE_XOR;
2841 case Intrinsic::vector_reduce_smax:
2842 return TargetOpcode::G_VECREDUCE_SMAX;
2843 case Intrinsic::vector_reduce_smin:
2844 return TargetOpcode::G_VECREDUCE_SMIN;
2845 case Intrinsic::vector_reduce_umax:
2846 return TargetOpcode::G_VECREDUCE_UMAX;
2847 case Intrinsic::vector_reduce_umin:
2848 return TargetOpcode::G_VECREDUCE_UMIN;
2849 case Intrinsic::experimental_vector_compress:
2850 return TargetOpcode::G_VECTOR_COMPRESS;
2851 case Intrinsic::lround:
2852 return TargetOpcode::G_LROUND;
2853 case Intrinsic::llround:
2854 return TargetOpcode::G_LLROUND;
2855 case Intrinsic::get_fpenv:
2856 return TargetOpcode::G_GET_FPENV;
2857 case Intrinsic::get_fpmode:
2858 return TargetOpcode::G_GET_FPMODE;
2859 }
2861}
2862
2863bool IRTranslatorImpl::translateSimpleIntrinsic(const CallInst &CI,
2864 Intrinsic::ID ID,
2865 MachineIRBuilder &MIRBuilder) {
2866
2867 unsigned Op = getSimpleIntrinsicOpcode(ID);
2868
2869 // Is this a simple intrinsic?
2871 return false;
2872
2873 // Yes. Let's translate it.
2875 for (const auto &Arg : CI.args())
2876 VRegs.push_back(getOrCreateVReg(*Arg));
2877
2878 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
2880 return true;
2881}
2882
2883// TODO: Include ConstainedOps.def when all strict instructions are defined.
2885 switch (ID) {
2886 case Intrinsic::experimental_constrained_fadd:
2887 return TargetOpcode::G_STRICT_FADD;
2888 case Intrinsic::experimental_constrained_fsub:
2889 return TargetOpcode::G_STRICT_FSUB;
2890 case Intrinsic::experimental_constrained_fmul:
2891 return TargetOpcode::G_STRICT_FMUL;
2892 case Intrinsic::experimental_constrained_fdiv:
2893 return TargetOpcode::G_STRICT_FDIV;
2894 case Intrinsic::experimental_constrained_frem:
2895 return TargetOpcode::G_STRICT_FREM;
2896 case Intrinsic::experimental_constrained_fma:
2897 return TargetOpcode::G_STRICT_FMA;
2898 case Intrinsic::experimental_constrained_sqrt:
2899 return TargetOpcode::G_STRICT_FSQRT;
2900 case Intrinsic::experimental_constrained_ldexp:
2901 return TargetOpcode::G_STRICT_FLDEXP;
2902 case Intrinsic::experimental_constrained_fcmp:
2903 return TargetOpcode::G_STRICT_FCMP;
2904 case Intrinsic::experimental_constrained_fcmps:
2905 return TargetOpcode::G_STRICT_FCMPS;
2906 default:
2907 return 0;
2908 }
2909}
2910
2911bool IRTranslatorImpl::translateConstrainedFPIntrinsic(
2912 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
2914
2915 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
2916 if (!Opcode)
2917 return false;
2918
2922
2923 if (Opcode == TargetOpcode::G_STRICT_FCMP ||
2924 Opcode == TargetOpcode::G_STRICT_FCMPS) {
2925 auto *FPCmp = cast<ConstrainedFPCmpIntrinsic>(&FPI);
2926 Register Operand0 = getOrCreateVReg(*FPCmp->getArgOperand(0));
2927 Register Operand1 = getOrCreateVReg(*FPCmp->getArgOperand(1));
2928 Register Result = getOrCreateVReg(FPI);
2929 MIRBuilder.buildInstr(Opcode, {Result}, {}, Flags)
2930 .addPredicate(FPCmp->getPredicate())
2931 .addUse(Operand0)
2932 .addUse(Operand1);
2933 return true;
2934 }
2935
2937 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
2938 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(I)));
2939
2940 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
2941 return true;
2942}
2943
2944std::optional<MCRegister> IRTranslatorImpl::getArgPhysReg(Argument &Arg) {
2945 auto VRegs = getOrCreateVRegs(Arg);
2946 if (VRegs.size() != 1)
2947 return std::nullopt;
2948
2949 // Arguments are lowered as a copy of a livein physical register.
2950 auto *VRegDef = MF->getRegInfo().getVRegDef(VRegs[0]);
2951 if (!VRegDef || !VRegDef->isCopy())
2952 return std::nullopt;
2953 return VRegDef->getOperand(1).getReg().asMCReg();
2954}
2955
2956bool IRTranslatorImpl::translateIfEntryValueArgument(
2957 bool isDeclare, Value *Val, const DILocalVariable *Var,
2958 const DIExpression *Expr, const DebugLoc &DL,
2959 MachineIRBuilder &MIRBuilder) {
2960 auto *Arg = dyn_cast<Argument>(Val);
2961 if (!Arg)
2962 return false;
2963
2964 if (!Expr->isEntryValue())
2965 return false;
2966
2967 std::optional<MCRegister> PhysReg = getArgPhysReg(*Arg);
2968 if (!PhysReg) {
2969 LLVM_DEBUG(dbgs() << "Dropping dbg." << (isDeclare ? "declare" : "value")
2970 << ": expression is entry_value but "
2971 << "couldn't find a physical register\n");
2972 LLVM_DEBUG(dbgs() << *Var << "\n");
2973 return true;
2974 }
2975
2976 if (isDeclare) {
2977 // Append an op deref to account for the fact that this is a dbg_declare.
2978 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
2979 MF->setVariableDbgInfo(Var, Expr, *PhysReg, DL);
2980 } else {
2981 MIRBuilder.buildDirectDbgValue(*PhysReg, Var, Expr);
2982 }
2983
2984 return true;
2985}
2986
2987static unsigned getConvOpcode(Intrinsic::ID ID) {
2988 switch (ID) {
2989 default:
2990 llvm_unreachable("Unexpected intrinsic");
2991 case Intrinsic::experimental_convergence_anchor:
2992 return TargetOpcode::CONVERGENCECTRL_ANCHOR;
2993 case Intrinsic::experimental_convergence_entry:
2994 return TargetOpcode::CONVERGENCECTRL_ENTRY;
2995 case Intrinsic::experimental_convergence_loop:
2996 return TargetOpcode::CONVERGENCECTRL_LOOP;
2997 }
2998}
2999
3000bool IRTranslatorImpl::translateConvergenceControlIntrinsic(
3001 const CallInst &CI, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder) {
3002 MachineInstrBuilder MIB = MIRBuilder.buildInstr(getConvOpcode(ID));
3003 Register OutputReg = getOrCreateConvergenceTokenVReg(CI);
3004 MIB.addDef(OutputReg);
3005
3006 if (ID == Intrinsic::experimental_convergence_loop) {
3008 assert(Bundle && "Expected a convergence control token.");
3009 Register InputReg =
3010 getOrCreateConvergenceTokenVReg(*Bundle->Inputs[0].get());
3011 MIB.addUse(InputReg);
3012 }
3013
3014 return true;
3015}
3016
3017bool IRTranslatorImpl::translateKnownIntrinsic(const CallInst &CI,
3018 Intrinsic::ID ID,
3019 MachineIRBuilder &MIRBuilder) {
3020 if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
3021 if (ORE->enabled()) {
3022 if (MemoryOpRemark::canHandle(MI, *LibInfo)) {
3023 MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
3024 R.visit(MI);
3025 }
3026 }
3027 }
3028
3029 // If this is a simple intrinsic (that is, we just need to add a def of
3030 // a vreg, and uses for each arg operand, then translate it.
3031 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
3032 return true;
3033
3034 switch (ID) {
3035 default:
3036 break;
3037 case Intrinsic::lifetime_start:
3038 case Intrinsic::lifetime_end: {
3039 // No stack colouring in O0, discard region information.
3040 if (MF->getTarget().getOptLevel() == CodeGenOptLevel::None ||
3041 MF->getFunction().hasOptNone())
3042 return true;
3043
3044 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
3045 : TargetOpcode::LIFETIME_END;
3046
3047 const AllocaInst *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0));
3048 if (!AI || !AI->isStaticAlloca())
3049 return true;
3050
3051 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
3052 return true;
3053 }
3054 case Intrinsic::fake_use: {
3056 for (const auto &Arg : CI.args())
3057 llvm::append_range(VRegs, getOrCreateVRegs(*Arg));
3058 MIRBuilder.buildInstr(TargetOpcode::FAKE_USE, {}, VRegs);
3059 MF->setHasFakeUses(true);
3060 return true;
3061 }
3062 case Intrinsic::dbg_declare: {
3063 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
3064 assert(DI.getVariable() && "Missing variable");
3065 translateDbgDeclareRecord(DI.getAddress(), DI.hasArgList(), DI.getVariable(),
3066 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
3067 return true;
3068 }
3069 case Intrinsic::dbg_label: {
3070 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
3071 assert(DI.getLabel() && "Missing label");
3072
3074 MIRBuilder.getDebugLoc()) &&
3075 "Expected inlined-at fields to agree");
3076
3077 MIRBuilder.buildDbgLabel(DI.getLabel());
3078 return true;
3079 }
3080 case Intrinsic::vaend:
3081 // No target I know of cares about va_end. Certainly no in-tree target
3082 // does. Simplest intrinsic ever!
3083 return true;
3084 case Intrinsic::vastart: {
3085 Value *Ptr = CI.getArgOperand(0);
3086 unsigned ListSize = TLI->getVaListSizeInBits(*DL) / 8;
3087 Align Alignment = getKnownAlignment(Ptr, *DL);
3088
3089 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
3090 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
3092 ListSize, Alignment));
3093 return true;
3094 }
3095 case Intrinsic::dbg_assign:
3096 // A dbg.assign is a dbg.value with more information about stack locations,
3097 // typically produced during optimisation of variables with leaked
3098 // addresses. We can treat it like a normal dbg_value intrinsic here; to
3099 // benefit from the full analysis of stack/SSA locations, GlobalISel would
3100 // need to register for and use the AssignmentTrackingAnalysis pass.
3101 [[fallthrough]];
3102 case Intrinsic::dbg_value: {
3103 // This form of DBG_VALUE is target-independent.
3104 const DbgValueInst &DI = cast<DbgValueInst>(CI);
3105 translateDbgValueRecord(DI.getValue(), DI.hasArgList(), DI.getVariable(),
3106 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
3107 return true;
3108 }
3109 case Intrinsic::uadd_with_overflow:
3110 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
3111 case Intrinsic::sadd_with_overflow:
3112 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
3113 case Intrinsic::usub_with_overflow:
3114 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
3115 case Intrinsic::ssub_with_overflow:
3116 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
3117 case Intrinsic::umul_with_overflow:
3118 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
3119 case Intrinsic::smul_with_overflow:
3120 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
3121 case Intrinsic::uadd_sat:
3122 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
3123 case Intrinsic::sadd_sat:
3124 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
3125 case Intrinsic::usub_sat:
3126 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
3127 case Intrinsic::ssub_sat:
3128 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
3129 case Intrinsic::ushl_sat:
3130 return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
3131 case Intrinsic::sshl_sat:
3132 return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
3133 case Intrinsic::umin:
3134 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
3135 case Intrinsic::umax:
3136 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
3137 case Intrinsic::smin:
3138 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
3139 case Intrinsic::smax:
3140 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
3141 case Intrinsic::abs:
3142 // TODO: Preserve "int min is poison" arg in GMIR?
3143 return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
3144 case Intrinsic::smul_fix:
3145 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
3146 case Intrinsic::umul_fix:
3147 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
3148 case Intrinsic::smul_fix_sat:
3149 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
3150 case Intrinsic::umul_fix_sat:
3151 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
3152 case Intrinsic::sdiv_fix:
3153 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
3154 case Intrinsic::udiv_fix:
3155 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
3156 case Intrinsic::sdiv_fix_sat:
3157 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
3158 case Intrinsic::udiv_fix_sat:
3159 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
3160 case Intrinsic::fmuladd: {
3161 const TargetMachine &TM = MF->getTarget();
3162 Register Dst = getOrCreateVReg(CI);
3163 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
3164 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
3165 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
3167 TLI->isFMAFasterThanFMulAndFAdd(*MF,
3168 TLI->getValueType(*DL, CI.getType()))) {
3169 // TODO: Revisit this to see if we should move this part of the
3170 // lowering to the combiner.
3171 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
3173 } else {
3174 LLT Ty = getLLTForType(*CI.getType(), *DL);
3175 auto FMul = MIRBuilder.buildFMul(
3176 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
3177 MIRBuilder.buildFAdd(Dst, FMul, Op2,
3179 }
3180 return true;
3181 }
3182 case Intrinsic::frexp: {
3183 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3184 MIRBuilder.buildFFrexp(VRegs[0], VRegs[1],
3185 getOrCreateVReg(*CI.getArgOperand(0)),
3187 return true;
3188 }
3189 case Intrinsic::modf: {
3190 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3191 MIRBuilder.buildModf(VRegs[0], VRegs[1],
3192 getOrCreateVReg(*CI.getArgOperand(0)),
3194 return true;
3195 }
3196 case Intrinsic::sincos: {
3197 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3198 MIRBuilder.buildFSincos(VRegs[0], VRegs[1],
3199 getOrCreateVReg(*CI.getArgOperand(0)),
3201 return true;
3202 }
3203 case Intrinsic::fptosi_sat:
3204 MIRBuilder.buildFPTOSI_SAT(getOrCreateVReg(CI),
3205 getOrCreateVReg(*CI.getArgOperand(0)));
3206 return true;
3207 case Intrinsic::fptoui_sat:
3208 MIRBuilder.buildFPTOUI_SAT(getOrCreateVReg(CI),
3209 getOrCreateVReg(*CI.getArgOperand(0)));
3210 return true;
3211 case Intrinsic::memcpy_inline:
3212 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
3213 case Intrinsic::memcpy:
3214 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
3215 case Intrinsic::memmove:
3216 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
3217 case Intrinsic::memset:
3218 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
3219 case Intrinsic::memset_inline:
3220 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET_INLINE);
3221 case Intrinsic::eh_typeid_for: {
3222 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
3223 Register Reg = getOrCreateVReg(CI);
3224 unsigned TypeID = MF->getTypeIDFor(GV);
3225 MIRBuilder.buildConstant(Reg, TypeID);
3226 return true;
3227 }
3228 case Intrinsic::objectsize:
3229 llvm_unreachable("llvm.objectsize.* should have been lowered already");
3230
3231 case Intrinsic::is_constant:
3232 llvm_unreachable("llvm.is.constant.* should have been lowered already");
3233
3234 case Intrinsic::stackguard:
3235 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
3236 return true;
3237 case Intrinsic::stackprotector: {
3238 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
3239 Register GuardVal;
3240 if (TLI->useLoadStackGuardNode(*CI.getModule())) {
3241 GuardVal = MRI->createGenericVirtualRegister(PtrTy);
3242 getStackGuard(GuardVal, MIRBuilder);
3243 } else
3244 GuardVal = getOrCreateVReg(*CI.getArgOperand(0)); // The guard's value.
3245
3246 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
3247 int FI = getOrCreateFrameIndex(*Slot);
3248 MF->getFrameInfo().setStackProtectorIndex(FI);
3249
3250 MIRBuilder.buildStore(
3251 GuardVal, getOrCreateVReg(*Slot),
3252 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
3255 PtrTy, Align(8)));
3256 return true;
3257 }
3258 case Intrinsic::stacksave: {
3259 MIRBuilder.buildInstr(TargetOpcode::G_STACKSAVE, {getOrCreateVReg(CI)}, {});
3260 return true;
3261 }
3262 case Intrinsic::stackrestore: {
3263 MIRBuilder.buildInstr(TargetOpcode::G_STACKRESTORE, {},
3264 {getOrCreateVReg(*CI.getArgOperand(0))});
3265 return true;
3266 }
3267 case Intrinsic::cttz:
3268 case Intrinsic::ctlz: {
3269 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
3270 bool isTrailing = ID == Intrinsic::cttz;
3271 unsigned Opcode = isTrailing ? Cst->isZero()
3272 ? TargetOpcode::G_CTTZ
3273 : TargetOpcode::G_CTTZ_ZERO_POISON
3274 : Cst->isZero() ? TargetOpcode::G_CTLZ
3275 : TargetOpcode::G_CTLZ_ZERO_POISON;
3276 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
3277 {getOrCreateVReg(*CI.getArgOperand(0))});
3278 return true;
3279 }
3280 case Intrinsic::invariant_start: {
3281 MIRBuilder.buildUndef(getOrCreateVReg(CI));
3282 return true;
3283 }
3284 case Intrinsic::invariant_end:
3285 return true;
3286 case Intrinsic::expect:
3287 case Intrinsic::expect_with_probability:
3288 case Intrinsic::annotation:
3289 case Intrinsic::ptr_annotation:
3290 case Intrinsic::launder_invariant_group:
3291 case Intrinsic::strip_invariant_group:
3292 case Intrinsic::threadlocal_address: {
3293 // Drop the intrinsic, but forward the value.
3294 MIRBuilder.buildCopy(getOrCreateVReg(CI),
3295 getOrCreateVReg(*CI.getArgOperand(0)));
3296 return true;
3297 }
3298 case Intrinsic::assume:
3299 case Intrinsic::experimental_noalias_scope_decl:
3300 case Intrinsic::var_annotation:
3301 case Intrinsic::sideeffect:
3302 // Discard annotate attributes, assumptions, and artificial side-effects.
3303 return true;
3304 case Intrinsic::read_volatile_register:
3305 case Intrinsic::read_register: {
3306 Value *Arg = CI.getArgOperand(0);
3307 MIRBuilder
3308 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
3309 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
3310 return true;
3311 }
3312 case Intrinsic::write_register: {
3313 Value *Arg = CI.getArgOperand(0);
3314 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
3315 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
3316 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
3317 return true;
3318 }
3319 case Intrinsic::localescape: {
3320 MachineBasicBlock &EntryMBB = MF->front();
3321 StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
3322
3323 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
3324 // is the same on all targets.
3325 for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) {
3326 Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
3327 if (isa<ConstantPointerNull>(Arg))
3328 continue; // Skip null pointers. They represent a hole in index space.
3329
3330 int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
3331 MCSymbol *FrameAllocSym =
3332 MF->getContext().getOrCreateFrameAllocSymbol(EscapedName, Idx);
3333
3334 // This should be inserted at the start of the entry block.
3335 auto LocalEscape =
3336 MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
3337 .addSym(FrameAllocSym)
3338 .addFrameIndex(FI);
3339
3340 EntryMBB.insert(EntryMBB.begin(), LocalEscape);
3341 }
3342
3343 return true;
3344 }
3345 case Intrinsic::vector_reduce_fadd:
3346 case Intrinsic::vector_reduce_fmul: {
3347 // Need to check for the reassoc flag to decide whether we want a
3348 // sequential reduction opcode or not.
3349 Register Dst = getOrCreateVReg(CI);
3350 Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
3351 Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
3352 unsigned Opc = 0;
3353 if (!CI.hasAllowReassoc()) {
3354 // The sequential ordering case.
3355 Opc = ID == Intrinsic::vector_reduce_fadd
3356 ? TargetOpcode::G_VECREDUCE_SEQ_FADD
3357 : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
3358 if (!MRI->getType(VecSrc).isVector())
3359 Opc = ID == Intrinsic::vector_reduce_fadd ? TargetOpcode::G_FADD
3360 : TargetOpcode::G_FMUL;
3361 MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
3363 return true;
3364 }
3365 // We split the operation into a separate G_FADD/G_FMUL + the reduce,
3366 // since the associativity doesn't matter.
3367 unsigned ScalarOpc;
3368 if (ID == Intrinsic::vector_reduce_fadd) {
3369 Opc = TargetOpcode::G_VECREDUCE_FADD;
3370 ScalarOpc = TargetOpcode::G_FADD;
3371 } else {
3372 Opc = TargetOpcode::G_VECREDUCE_FMUL;
3373 ScalarOpc = TargetOpcode::G_FMUL;
3374 }
3375 LLT DstTy = MRI->getType(Dst);
3376 auto Rdx = MIRBuilder.buildInstr(
3377 Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
3378 MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
3380
3381 return true;
3382 }
3383 case Intrinsic::trap:
3384 return translateTrap(CI, MIRBuilder, TargetOpcode::G_TRAP);
3385 case Intrinsic::debugtrap:
3386 return translateTrap(CI, MIRBuilder, TargetOpcode::G_DEBUGTRAP);
3387 case Intrinsic::ubsantrap:
3388 return translateTrap(CI, MIRBuilder, TargetOpcode::G_UBSANTRAP);
3389 case Intrinsic::allow_runtime_check:
3390 case Intrinsic::allow_ubsan_check:
3391 MIRBuilder.buildCopy(getOrCreateVReg(CI),
3392 getOrCreateVReg(*ConstantInt::getTrue(CI.getType())));
3393 return true;
3394 case Intrinsic::amdgcn_cs_chain:
3395 case Intrinsic::amdgcn_call_whole_wave:
3396 return translateCallBase(CI, MIRBuilder);
3397 case Intrinsic::fptrunc_round: {
3399
3400 // Convert the metadata argument to a constant integer
3401 Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(1))->getMetadata();
3402 std::optional<RoundingMode> RoundMode =
3403 convertStrToRoundingMode(cast<MDString>(MD)->getString());
3404
3405 // Add the Rounding mode as an integer
3406 MIRBuilder
3407 .buildInstr(TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND,
3408 {getOrCreateVReg(CI)},
3409 {getOrCreateVReg(*CI.getArgOperand(0))}, Flags)
3410 .addImm((int)*RoundMode);
3411
3412 return true;
3413 }
3414 case Intrinsic::is_fpclass: {
3415 Value *FpValue = CI.getOperand(0);
3416 ConstantInt *TestMaskValue = cast<ConstantInt>(CI.getOperand(1));
3417
3418 MIRBuilder
3419 .buildInstr(TargetOpcode::G_IS_FPCLASS, {getOrCreateVReg(CI)},
3420 {getOrCreateVReg(*FpValue)})
3421 .addImm(TestMaskValue->getZExtValue());
3422
3423 return true;
3424 }
3425 case Intrinsic::set_fpenv: {
3426 Value *FPEnv = CI.getOperand(0);
3427 MIRBuilder.buildSetFPEnv(getOrCreateVReg(*FPEnv));
3428 return true;
3429 }
3430 case Intrinsic::reset_fpenv:
3431 MIRBuilder.buildResetFPEnv();
3432 return true;
3433 case Intrinsic::set_fpmode: {
3434 Value *FPState = CI.getOperand(0);
3435 MIRBuilder.buildSetFPMode(getOrCreateVReg(*FPState));
3436 return true;
3437 }
3438 case Intrinsic::reset_fpmode:
3439 MIRBuilder.buildResetFPMode();
3440 return true;
3441 case Intrinsic::get_rounding:
3442 MIRBuilder.buildGetRounding(getOrCreateVReg(CI));
3443 return true;
3444 case Intrinsic::set_rounding:
3445 MIRBuilder.buildSetRounding(getOrCreateVReg(*CI.getOperand(0)));
3446 return true;
3447 case Intrinsic::vscale: {
3448 MIRBuilder.buildVScale(getOrCreateVReg(CI), 1);
3449 return true;
3450 }
3451 case Intrinsic::scmp:
3452 MIRBuilder.buildSCmp(getOrCreateVReg(CI),
3453 getOrCreateVReg(*CI.getOperand(0)),
3454 getOrCreateVReg(*CI.getOperand(1)));
3455 return true;
3456 case Intrinsic::ucmp:
3457 MIRBuilder.buildUCmp(getOrCreateVReg(CI),
3458 getOrCreateVReg(*CI.getOperand(0)),
3459 getOrCreateVReg(*CI.getOperand(1)));
3460 return true;
3461 case Intrinsic::vector_extract:
3462 return translateExtractVector(CI, MIRBuilder);
3463 case Intrinsic::vector_insert:
3464 return translateInsertVector(CI, MIRBuilder);
3465 case Intrinsic::stepvector: {
3466 MIRBuilder.buildStepVector(getOrCreateVReg(CI), 1);
3467 return true;
3468 }
3469 case Intrinsic::prefetch: {
3470 Value *Addr = CI.getOperand(0);
3471 unsigned RW = cast<ConstantInt>(CI.getOperand(1))->getZExtValue();
3472 unsigned Locality = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
3473 unsigned CacheType = cast<ConstantInt>(CI.getOperand(3))->getZExtValue();
3474
3476 auto &MMO = *MF->getMachineMemOperand(MachinePointerInfo(Addr), Flags,
3477 LLT(), Align());
3478
3479 MIRBuilder.buildPrefetch(getOrCreateVReg(*Addr), RW, Locality, CacheType,
3480 MMO);
3481
3482 return true;
3483 }
3484
3485 case Intrinsic::vector_interleave2:
3486 case Intrinsic::vector_deinterleave2: {
3487 // Both intrinsics have at least one operand.
3488 Value *Op0 = CI.getOperand(0);
3489 LLT ResTy = getLLTForType(*Op0->getType(), MIRBuilder.getDataLayout());
3490 if (!ResTy.isFixedVector())
3491 return false;
3492
3493 if (CI.getIntrinsicID() == Intrinsic::vector_interleave2)
3494 return translateVectorInterleave2Intrinsic(CI, MIRBuilder);
3495
3496 return translateVectorDeinterleave2Intrinsic(CI, MIRBuilder);
3497 }
3498
3499#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
3500 case Intrinsic::INTRINSIC:
3501#include "llvm/IR/ConstrainedOps.def"
3502 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
3503 MIRBuilder);
3504 case Intrinsic::experimental_convergence_anchor:
3505 case Intrinsic::experimental_convergence_entry:
3506 case Intrinsic::experimental_convergence_loop:
3507 return translateConvergenceControlIntrinsic(CI, ID, MIRBuilder);
3508 case Intrinsic::reloc_none: {
3509 Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(0))->getMetadata();
3510 StringRef SymbolName = cast<MDString>(MD)->getString();
3511 MIRBuilder.buildInstr(TargetOpcode::RELOC_NONE)
3513 return true;
3514 }
3515 }
3516 return false;
3517}
3518
3519bool IRTranslatorImpl::translateInlineAsm(const CallBase &CB,
3520 MachineIRBuilder &MIRBuilder) {
3521 if (!mayTranslateUserTypes(CB))
3522 return false;
3523
3524 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
3525
3526 if (!ALI) {
3527 LLVM_DEBUG(
3528 dbgs() << "Inline asm lowering is not supported for this target yet\n");
3529 return false;
3530 }
3531
3532 return ALI->lowerInlineAsm(
3533 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
3534}
3535
3536bool IRTranslatorImpl::translateCallBase(const CallBase &CB,
3537 MachineIRBuilder &MIRBuilder) {
3538 ArrayRef<Register> Res = getOrCreateVRegs(CB);
3539
3541 Register SwiftInVReg = 0;
3542 Register SwiftErrorVReg = 0;
3543 for (const auto &Arg : CB.args()) {
3544 if (CLI->supportSwiftError() && isSwiftError(Arg)) {
3545 assert(SwiftInVReg == 0 && "Expected only one swift error argument");
3546 LLT Ty = getLLTForType(*Arg->getType(), *DL);
3547 SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
3548 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
3549 &CB, &MIRBuilder.getMBB(), Arg));
3550 Args.emplace_back(ArrayRef(SwiftInVReg));
3551 SwiftErrorVReg =
3552 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
3553 continue;
3554 }
3555 Args.push_back(getOrCreateVRegs(*Arg));
3556 }
3557
3558 if (auto *CI = dyn_cast<CallInst>(&CB)) {
3559 if (ORE->enabled()) {
3560 if (MemoryOpRemark::canHandle(CI, *LibInfo)) {
3561 MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
3562 R.visit(CI);
3563 }
3564 }
3565 }
3566
3567 std::optional<CallLowering::PtrAuthInfo> PAI;
3568 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_ptrauth)) {
3569 // Functions should never be ptrauth-called directly.
3570 assert(!CB.getCalledFunction() && "invalid direct ptrauth call");
3571
3572 const Value *Key = Bundle->Inputs[0];
3573 const Value *Discriminator = Bundle->Inputs[1];
3574
3575 // Look through ptrauth constants to try to eliminate the matching bundle
3576 // and turn this into a direct call with no ptrauth.
3577 // CallLowering will use the raw pointer if it doesn't find the PAI.
3578 const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CB.getCalledOperand());
3579 if (!CalleeCPA || !isa<Function>(CalleeCPA->getPointer()) ||
3580 !CalleeCPA->isKnownCompatibleWith(Key, Discriminator, *DL)) {
3581 // If we can't make it direct, package the bundle into PAI.
3582 Register DiscReg = getOrCreateVReg(*Discriminator);
3583 PAI = CallLowering::PtrAuthInfo{cast<ConstantInt>(Key)->getZExtValue(),
3584 DiscReg};
3585 }
3586 }
3587
3588 Register ConvergenceCtrlToken = 0;
3589 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
3590 const auto &Token = *Bundle->Inputs[0].get();
3591 ConvergenceCtrlToken = getOrCreateConvergenceTokenVReg(Token);
3592 }
3593
3594 // We don't set HasCalls on MFI here yet because call lowering may decide to
3595 // optimize into tail calls. Instead, we defer that to selection where a final
3596 // scan is done to check if any instructions are calls.
3597 bool Success = CLI->lowerCall(
3598 MIRBuilder, CB, Res, Args, SwiftErrorVReg, PAI, ConvergenceCtrlToken,
3599 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
3600
3601 // Check if we just inserted a tail call.
3602 if (Success) {
3603 assert(!HasTailCall && "Can't tail call return twice from block?");
3604 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
3605 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
3606 }
3607
3608 return Success;
3609}
3610
3611bool IRTranslatorImpl::translateCall(const User &U,
3612 MachineIRBuilder &MIRBuilder) {
3613 if (!mayTranslateUserTypes(U))
3614 return false;
3615
3616 const CallInst &CI = cast<CallInst>(U);
3617 const Function *F = CI.getCalledFunction();
3618
3619 // FIXME: support Windows dllimport function calls and calls through
3620 // weak symbols.
3621 if (F && (F->hasDLLImportStorageClass() ||
3622 (MF->getTarget().getTargetTriple().isOSWindows() &&
3623 F->hasExternalWeakLinkage())))
3624 return false;
3625
3626 // FIXME: support control flow guard targets.
3628 return false;
3629
3630 // FIXME: support statepoints and related.
3632 return false;
3633
3634 if (CI.isInlineAsm())
3635 return translateInlineAsm(CI, MIRBuilder);
3636
3637 Intrinsic::ID ID = F ? F->getIntrinsicID() : Intrinsic::not_intrinsic;
3638 if (!F || ID == Intrinsic::not_intrinsic) {
3639 if (translateCallBase(CI, MIRBuilder)) {
3640 diagnoseDontCall(CI);
3641 return true;
3642 }
3643 return false;
3644 }
3645
3646 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
3647
3648 if (!MF->getSubtarget().isIntrinsicSupported(ID)) {
3649 const Function &Fn = MF->getFunction();
3650 Fn.getContext().diagnose(
3651 DiagnosticInfoUnsupportedTargetIntrinsic(Fn, ID, CI.getDebugLoc()));
3652 }
3653
3654 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
3655 return true;
3656
3658 TLI->getTgtMemIntrinsic(Infos, CI, *MF, ID);
3659
3660 return translateIntrinsic(CI, ID, MIRBuilder, Infos);
3661}
3662
3663/// Translate a call or callbr to an intrinsic.
3664bool IRTranslatorImpl::translateIntrinsic(
3665 const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder,
3666 ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos) {
3667 if (!MF->getSubtarget().isIntrinsicSupported(ID)) {
3668 const Function &F = MF->getFunction();
3669 F.getContext().diagnose(
3670 DiagnosticInfoUnsupportedTargetIntrinsic(F, ID, CB.getDebugLoc()));
3671 }
3672
3673 ArrayRef<Register> ResultRegs;
3674 if (!CB.getType()->isVoidTy())
3675 ResultRegs = getOrCreateVRegs(CB);
3676
3677 // Ignore the callsite attributes. Backend code is most likely not expecting
3678 // an intrinsic to sometimes have side effects and sometimes not.
3679 MachineInstrBuilder MIB = MIRBuilder.buildIntrinsic(ID, ResultRegs);
3680 if (isa<FPMathOperator>(CB))
3681 MIB->copyIRFlags(CB);
3682
3683 for (const auto &Arg : enumerate(CB.args())) {
3684 // If this is required to be an immediate, don't materialize it in a
3685 // register.
3686 if (CB.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
3687 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
3688 // imm arguments are more convenient than cimm (and realistically
3689 // probably sufficient), so use them.
3690 assert(CI->getBitWidth() <= 64 &&
3691 "large intrinsic immediates not handled");
3692 MIB.addImm(CI->getSExtValue());
3693 } else {
3694 MIB.addFPImm(cast<ConstantFP>(Arg.value()));
3695 }
3696 } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
3697 auto *MD = MDVal->getMetadata();
3698 auto *MDN = dyn_cast<MDNode>(MD);
3699 if (!MDN) {
3700 if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
3701 MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
3702 else // This was probably an MDString.
3703 return false;
3704 }
3705 MIB.addMetadata(MDN);
3706 } else {
3707 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
3708 if (VRegs.size() > 1)
3709 return false;
3710 MIB.addUse(VRegs[0]);
3711 }
3712 }
3713
3714 // Add MachineMemOperands for each memory access described by the target.
3715 for (const auto &Info : TgtMemIntrinsicInfos) {
3716 Align Alignment = Info.align.value_or(
3717 DL->getABITypeAlign(Info.memVT.getTypeForEVT(CB.getContext())));
3718 LLT MemTy = Info.memVT.isSimple()
3719 ? getLLTForMVT(Info.memVT.getSimpleVT())
3720 : LLT::scalar(Info.memVT.getStoreSizeInBits());
3721
3722 // TODO: We currently just fallback to address space 0 if
3723 // getTgtMemIntrinsic didn't yield anything useful.
3724 MachinePointerInfo MPI;
3725 if (Info.ptrVal) {
3726 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
3727 } else if (Info.fallbackAddressSpace) {
3728 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
3729 }
3730 MIB.addMemOperand(MF->getMachineMemOperand(
3731 MPI, Info.flags, MemTy, Alignment, CB.getAAMetadata(), Info.ssid,
3732 Info.order, Info.failureOrder));
3733 }
3734
3735 if (CB.isConvergent()) {
3736 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
3737 auto *Token = Bundle->Inputs[0].get();
3738 Register TokenReg = getOrCreateVReg(*Token);
3739 MIB.addUse(TokenReg, RegState::Implicit);
3740 }
3741 }
3742
3744 MIB->setDeactivationSymbol(*MF, Bundle->Inputs[0].get());
3745
3746 return true;
3747}
3748
3749bool IRTranslatorImpl::findUnwindDestinations(
3750 const BasicBlock *EHPadBB, BranchProbability Prob,
3751 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
3752 &UnwindDests) {
3754 EHPadBB->getParent()->getFunction().getPersonalityFn());
3755 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
3756 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
3757 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
3758 bool IsSEH = isAsynchronousEHPersonality(Personality);
3759
3760 if (IsWasmCXX) {
3761 // Ignore this for now.
3762 return false;
3763 }
3764
3765 while (EHPadBB) {
3767 BasicBlock *NewEHPadBB = nullptr;
3768 if (isa<LandingPadInst>(Pad)) {
3769 // Stop on landingpads. They are not funclets.
3770 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
3771 break;
3772 }
3773 if (isa<CleanupPadInst>(Pad)) {
3774 // Stop on cleanup pads. Cleanups are always funclet entries for all known
3775 // personalities.
3776 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
3777 UnwindDests.back().first->setIsEHScopeEntry();
3778 UnwindDests.back().first->setIsEHFuncletEntry();
3779 break;
3780 }
3781 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
3782 // Add the catchpad handlers to the possible destinations.
3783 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
3784 UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
3785 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
3786 if (IsMSVCCXX || IsCoreCLR)
3787 UnwindDests.back().first->setIsEHFuncletEntry();
3788 if (!IsSEH)
3789 UnwindDests.back().first->setIsEHScopeEntry();
3790 }
3791 NewEHPadBB = CatchSwitch->getUnwindDest();
3792 } else {
3793 continue;
3794 }
3795
3796 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3797 if (BPI && NewEHPadBB)
3798 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
3799 EHPadBB = NewEHPadBB;
3800 }
3801 return true;
3802}
3803
3804bool IRTranslatorImpl::translateInvoke(const User &U,
3805 MachineIRBuilder &MIRBuilder) {
3806 const InvokeInst &I = cast<InvokeInst>(U);
3807 MCContext &Context = MF->getContext();
3808
3809 const BasicBlock *ReturnBB = I.getSuccessor(0);
3810 const BasicBlock *EHPadBB = I.getSuccessor(1);
3811
3812 const Function *Fn = I.getCalledFunction();
3813
3814 // FIXME: support invoking patchpoint and statepoint intrinsics.
3815 if (Fn && Fn->isIntrinsic())
3816 return false;
3817
3818 // FIXME: support whatever these are.
3819 if (I.hasDeoptState())
3820 return false;
3821
3822 // FIXME: support control flow guard targets.
3823 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
3824 return false;
3825
3826 // FIXME: support Windows exception handling.
3827 if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHIIt()))
3828 return false;
3829
3830 // FIXME: support Windows dllimport function calls and calls through
3831 // weak symbols.
3832 if (Fn && (Fn->hasDLLImportStorageClass() ||
3833 (MF->getTarget().getTargetTriple().isOSWindows() &&
3834 Fn->hasExternalWeakLinkage())))
3835 return false;
3836
3837 bool LowerInlineAsm = I.isInlineAsm();
3838 bool NeedEHLabel = true;
3839
3840 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
3841 // the region covered by the try.
3842 MCSymbol *BeginSymbol = nullptr;
3843 if (NeedEHLabel) {
3844 MIRBuilder.buildInstr(TargetOpcode::G_INVOKE_REGION_START);
3845 BeginSymbol = Context.createTempSymbol();
3846 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
3847 }
3848
3849 if (LowerInlineAsm) {
3850 if (!translateInlineAsm(I, MIRBuilder))
3851 return false;
3852 } else if (!translateCallBase(I, MIRBuilder))
3853 return false;
3854
3855 MCSymbol *EndSymbol = nullptr;
3856 if (NeedEHLabel) {
3857 EndSymbol = Context.createTempSymbol();
3858 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
3859 }
3860
3862 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3863 MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
3864 BranchProbability EHPadBBProb =
3865 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3867
3868 if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
3869 return false;
3870
3871 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
3872 &ReturnMBB = getMBB(*ReturnBB);
3873 // Update successor info.
3874 addSuccessorWithProb(InvokeMBB, &ReturnMBB);
3875 for (auto &UnwindDest : UnwindDests) {
3876 UnwindDest.first->setIsEHPad();
3877 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3878 }
3879 InvokeMBB->normalizeSuccProbs();
3880
3881 if (NeedEHLabel) {
3882 assert(BeginSymbol && "Expected a begin symbol!");
3883 assert(EndSymbol && "Expected an end symbol!");
3884 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
3885 }
3886
3887 MIRBuilder.buildBr(ReturnMBB);
3888 return true;
3889}
3890
3891/// The intrinsics currently supported by callbr are implicit control flow
3892/// intrinsics such as amdgcn.kill.
3893bool IRTranslatorImpl::translateCallBr(const User &U,
3894 MachineIRBuilder &MIRBuilder) {
3895 if (!mayTranslateUserTypes(U))
3896 return false; // see translateCall
3897
3898 const CallBrInst &I = cast<CallBrInst>(U);
3899 MachineBasicBlock *CallBrMBB = &MIRBuilder.getMBB();
3900
3901 Intrinsic::ID IID = I.getIntrinsicID();
3902 if (I.isInlineAsm()) {
3903 // FIXME: inline asm is not yet supported for callbr in GlobalISel. As soon
3904 // as we add support, we need to handle the indirect asm targets, see
3905 // SelectionDAGBuilder::visitCallBr().
3906 return false;
3907 }
3908 if (!translateIntrinsic(I, IID, MIRBuilder))
3909 return false;
3910
3911 // Retrieve successors.
3912 SmallPtrSet<BasicBlock *, 8> Dests = {I.getDefaultDest()};
3913 MachineBasicBlock *Return = &getMBB(*I.getDefaultDest());
3914
3915 // Update successor info.
3916 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3917
3918 // Add indirect targets as successors. For intrinsic callbr, these represent
3919 // implicit control flow (e.g., the "kill" path for amdgcn.kill). We mark them
3920 // with setIsInlineAsmBrIndirectTarget so the machine verifier accepts them as
3921 // valid successors, even though they're not from inline asm.
3922 for (BasicBlock *Dest : I.getIndirectDests()) {
3923 MachineBasicBlock &Target = getMBB(*Dest);
3924 Target.setIsInlineAsmBrIndirectTarget();
3925 Target.setLabelMustBeEmitted();
3926 // Don't add duplicate machine successors.
3927 if (Dests.insert(Dest).second)
3928 addSuccessorWithProb(CallBrMBB, &Target, BranchProbability::getZero());
3929 }
3930
3931 CallBrMBB->normalizeSuccProbs();
3932
3933 // Drop into default successor.
3934 MIRBuilder.buildBr(*Return);
3935
3936 return true;
3937}
3938
3939bool IRTranslatorImpl::translateLandingPad(const User &U,
3940 MachineIRBuilder &MIRBuilder) {
3941 const LandingPadInst &LP = cast<LandingPadInst>(U);
3942
3943 MachineBasicBlock &MBB = MIRBuilder.getMBB();
3944
3945 MBB.setIsEHPad();
3946
3947 // If there aren't registers to copy the values into (e.g., during SjLj
3948 // exceptions), then don't bother.
3949 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
3950 if (TLI->getExceptionPointerRegister(
3951 TLI->getTargetMachine().getExceptionModel(), PersonalityFn) == 0 &&
3952 TLI->getExceptionSelectorRegister(
3953 TLI->getTargetMachine().getExceptionModel(), PersonalityFn) == 0)
3954 return true;
3955
3956 // If landingpad's return type is token type, we don't create DAG nodes
3957 // for its exception pointer and selector value. The extraction of exception
3958 // pointer or selector value from token type landingpads is not currently
3959 // supported.
3960 if (LP.getType()->isTokenTy())
3961 return true;
3962
3963 // Add a label to mark the beginning of the landing pad. Deletion of the
3964 // landing pad can thus be detected via the MachineModuleInfo.
3965 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
3966 .addSym(MF->addLandingPad(&MBB));
3967
3968 // If the unwinder does not preserve all registers, ensure that the
3969 // function marks the clobbered registers as used.
3970 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
3971 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
3972 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
3973
3974 LLT Ty = getLLTForType(*LP.getType(), *DL);
3975 Register Undef = MRI->createGenericVirtualRegister(Ty);
3976 MIRBuilder.buildUndef(Undef);
3977
3979 for (Type *Ty : cast<StructType>(LP.getType())->elements())
3980 Tys.push_back(getLLTForType(*Ty, *DL));
3981 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
3982
3983 // Mark exception register as live in.
3984 Register ExceptionReg = TLI->getExceptionPointerRegister(
3985 TLI->getTargetMachine().getExceptionModel(), PersonalityFn);
3986 if (!ExceptionReg)
3987 return false;
3988
3989 MBB.addLiveIn(ExceptionReg);
3990 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
3991 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
3992
3993 Register SelectorReg = TLI->getExceptionSelectorRegister(
3994 TLI->getTargetMachine().getExceptionModel(), PersonalityFn);
3995 if (!SelectorReg)
3996 return false;
3997
3998 MBB.addLiveIn(SelectorReg);
3999 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
4000 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
4001 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
4002
4003 return true;
4004}
4005
4006bool IRTranslatorImpl::translateAlloca(const User &U,
4007 MachineIRBuilder &MIRBuilder) {
4008 auto &AI = cast<AllocaInst>(U);
4009
4010 if (AI.isSwiftError())
4011 return true;
4012
4013 if (AI.isStaticAlloca()) {
4014 Register Res = getOrCreateVReg(AI);
4015 int FI = getOrCreateFrameIndex(AI);
4016 MIRBuilder.buildFrameIndex(Res, FI);
4017 return true;
4018 }
4019
4020 // FIXME: support stack probing for Windows.
4021 if (MF->getTarget().getTargetTriple().isOSWindows())
4022 return false;
4023
4024 // Now we're in the harder dynamic case.
4025 Register NumElts = getOrCreateVReg(*AI.getArraySize());
4026 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
4027 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
4028 if (MRI->getType(NumElts) != IntPtrTy) {
4029 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
4030 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
4031 NumElts = ExtElts;
4032 }
4033
4034 Type *Ty = AI.getAllocatedType();
4035 TypeSize TySize = DL->getTypeAllocSize(Ty);
4036
4037 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
4038 Register TySizeReg;
4039 if (TySize.isScalable()) {
4040 // For scalable types, use vscale * min_value
4041 TySizeReg = MRI->createGenericVirtualRegister(IntPtrTy);
4042 MIRBuilder.buildVScale(TySizeReg, TySize.getKnownMinValue());
4043 } else {
4044 // For fixed types, use a constant
4045 TySizeReg =
4046 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, TySize.getFixedValue()));
4047 }
4048 MIRBuilder.buildMul(AllocSize, NumElts, TySizeReg);
4049
4050 // Round the size of the allocation up to the stack alignment size
4051 // by add SA-1 to the size. This doesn't overflow because we're computing
4052 // an address inside an alloca.
4053 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
4054 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
4055 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
4057 auto AlignCst =
4058 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
4059 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
4060
4061 Align Alignment = AI.getAlign();
4062 if (Alignment <= StackAlign)
4063 Alignment = Align(1);
4064 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
4065
4066 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
4067 assert(MF->getFrameInfo().hasVarSizedObjects());
4068 return true;
4069}
4070
4071bool IRTranslatorImpl::translateVAArg(const User &U,
4072 MachineIRBuilder &MIRBuilder) {
4073 // FIXME: We may need more info about the type. Because of how LLT works,
4074 // we're completely discarding the i64/double distinction here (amongst
4075 // others). Fortunately the ABIs I know of where that matters don't use va_arg
4076 // anyway but that's not guaranteed.
4077 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
4078 {getOrCreateVReg(*U.getOperand(0)),
4079 DL->getABITypeAlign(U.getType()).value()});
4080 return true;
4081}
4082
4083bool IRTranslatorImpl::translateUnreachable(const User &U,
4084 MachineIRBuilder &MIRBuilder) {
4085 auto &UI = cast<UnreachableInst>(U);
4086 if (!UI.shouldLowerToTrap(MF->getTarget().Options.TrapUnreachable,
4087 MF->getTarget().Options.NoTrapAfterNoreturn))
4088 return true;
4089
4090 MIRBuilder.buildTrap();
4091 return true;
4092}
4093
4094bool IRTranslatorImpl::translateInsertElement(const User &U,
4095 MachineIRBuilder &MIRBuilder) {
4096 // If it is a <1 x Ty> vector, use the scalar as it is
4097 // not a legal vector type in LLT.
4098 if (auto *FVT = dyn_cast<FixedVectorType>(U.getType());
4099 FVT && FVT->getNumElements() == 1)
4100 return translateCopy(U, *U.getOperand(1), MIRBuilder);
4101
4102 Register Res = getOrCreateVReg(U);
4103 Register Val = getOrCreateVReg(*U.getOperand(0));
4104 Register Elt = getOrCreateVReg(*U.getOperand(1));
4105 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4106 Register Idx;
4107 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(2))) {
4108 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4109 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4110 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
4111 Idx = getOrCreateVReg(*NewIdxCI);
4112 }
4113 }
4114 if (!Idx)
4115 Idx = getOrCreateVReg(*U.getOperand(2));
4116 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
4117 const LLT VecIdxTy =
4118 MRI->getType(Idx).changeElementSize(PreferredVecIdxWidth);
4119 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
4120 }
4121 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
4122 return true;
4123}
4124
4125bool IRTranslatorImpl::translateInsertVector(const User &U,
4126 MachineIRBuilder &MIRBuilder) {
4127 Register Dst = getOrCreateVReg(U);
4128 Register Vec = getOrCreateVReg(*U.getOperand(0));
4129 Register Elt = getOrCreateVReg(*U.getOperand(1));
4130
4131 ConstantInt *CI = cast<ConstantInt>(U.getOperand(2));
4132 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4133
4134 // Resize Index to preferred index width.
4135 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4136 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4137 CI = ConstantInt::get(CI->getContext(), NewIdx);
4138 }
4139
4140 // If it is a <1 x Ty> vector, we have to use other means.
4141 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getOperand(1)->getType());
4142 ResultType && ResultType->getNumElements() == 1) {
4143 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
4144 InputType && InputType->getNumElements() == 1) {
4145 // We are inserting an illegal fixed vector into an illegal
4146 // fixed vector, use the scalar as it is not a legal vector type
4147 // in LLT.
4148 return translateCopy(U, Vec, MIRBuilder);
4149 }
4150 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
4151 // We are inserting an illegal fixed vector into a legal fixed
4152 // vector, use the scalar as it is not a legal vector type in
4153 // LLT.
4154 Register Idx = getOrCreateVReg(*CI);
4155 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, Idx);
4156 return true;
4157 }
4158 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
4159 // We are inserting an illegal fixed vector into a scalable
4160 // vector, use a scalar element insert.
4161 LLT VecIdxTy = LLT::integer(PreferredVecIdxWidth);
4162 Register Idx = getOrCreateVReg(*CI);
4163 auto ScaledIndex = MIRBuilder.buildMul(
4164 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
4165 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, ScaledIndex);
4166 return true;
4167 }
4168 }
4169
4170 MIRBuilder.buildInsertSubvector(Dst, Vec, Elt, CI->getZExtValue());
4171 return true;
4172}
4173
4174bool IRTranslatorImpl::translateExtractElement(const User &U,
4175 MachineIRBuilder &MIRBuilder) {
4176 // If it is a <1 x Ty> vector, use the scalar as it is
4177 // not a legal vector type in LLT.
4178 if (const FixedVectorType *FVT =
4179 dyn_cast<FixedVectorType>(U.getOperand(0)->getType()))
4180 if (FVT->getNumElements() == 1)
4181 return translateCopy(U, *U.getOperand(0), MIRBuilder);
4182
4183 Register Res = getOrCreateVReg(U);
4184 Register Val = getOrCreateVReg(*U.getOperand(0));
4185 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4186 Register Idx;
4187 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
4188 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4189 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4190 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
4191 Idx = getOrCreateVReg(*NewIdxCI);
4192 }
4193 }
4194 if (!Idx)
4195 Idx = getOrCreateVReg(*U.getOperand(1));
4196 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
4197 const LLT VecIdxTy =
4198 MRI->getType(Idx).changeElementSize(PreferredVecIdxWidth);
4199 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
4200 }
4201 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
4202 return true;
4203}
4204
4205bool IRTranslatorImpl::translateExtractVector(const User &U,
4206 MachineIRBuilder &MIRBuilder) {
4207 Register Res = getOrCreateVReg(U);
4208 Register Vec = getOrCreateVReg(*U.getOperand(0));
4209 ConstantInt *CI = cast<ConstantInt>(U.getOperand(1));
4210 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4211
4212 // Resize Index to preferred index width.
4213 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4214 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4215 CI = ConstantInt::get(CI->getContext(), NewIdx);
4216 }
4217
4218 // If it is a <1 x Ty> vector, we have to use other means.
4219 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getType());
4220 ResultType && ResultType->getNumElements() == 1) {
4221 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
4222 InputType && InputType->getNumElements() == 1) {
4223 // We are extracting an illegal fixed vector from an illegal fixed vector,
4224 // use the scalar as it is not a legal vector type in LLT.
4225 return translateCopy(U, Vec, MIRBuilder);
4226 }
4227 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
4228 // We are extracting an illegal fixed vector from a legal fixed
4229 // vector, use the scalar as it is not a legal vector type in
4230 // LLT.
4231 Register Idx = getOrCreateVReg(*CI);
4232 MIRBuilder.buildExtractVectorElement(Res, Vec, Idx);
4233 return true;
4234 }
4235 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
4236 // We are extracting an illegal fixed vector from a scalable
4237 // vector, use a scalar element extract.
4238 LLT VecIdxTy = LLT::integer(PreferredVecIdxWidth);
4239 Register Idx = getOrCreateVReg(*CI);
4240 auto ScaledIndex = MIRBuilder.buildMul(
4241 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
4242 MIRBuilder.buildExtractVectorElement(Res, Vec, ScaledIndex);
4243 return true;
4244 }
4245 }
4246
4247 MIRBuilder.buildExtractSubvector(Res, Vec, CI->getZExtValue());
4248 return true;
4249}
4250
4251bool IRTranslatorImpl::translateShuffleVector(const User &U,
4252 MachineIRBuilder &MIRBuilder) {
4253 // A ShuffleVector that operates on scalable vectors is a splat vector where
4254 // the value of the splat vector is the 0th element of the first operand,
4255 // since the index mask operand is the zeroinitializer (undef and
4256 // poison are treated as zeroinitializer here).
4257 if (U.getOperand(0)->getType()->isScalableTy()) {
4258 Register Val = getOrCreateVReg(*U.getOperand(0));
4259 auto SplatVal = MIRBuilder.buildExtractVectorElementConstant(
4260 MRI->getType(Val).getElementType(), Val, 0);
4261 MIRBuilder.buildSplatVector(getOrCreateVReg(U), SplatVal);
4262 return true;
4263 }
4264
4265 ArrayRef<int> Mask;
4266 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
4267 Mask = SVI->getShuffleMask();
4268 else
4269 Mask = cast<ConstantExpr>(U).getShuffleMask();
4270
4271 // As GISel does not represent <1 x > vectors as a separate type from scalars,
4272 // we transform shuffle_vector with a scalar output to an
4273 // ExtractVectorElement. If the input type is also scalar it becomes a Copy.
4274 unsigned DstElts = cast<FixedVectorType>(U.getType())->getNumElements();
4275 unsigned SrcElts =
4276 cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements();
4277 if (DstElts == 1) {
4278 unsigned M = Mask[0];
4279 if (SrcElts == 1) {
4280 if (M == 0 || M == 1)
4281 return translateCopy(U, *U.getOperand(M), MIRBuilder);
4282 MIRBuilder.buildUndef(getOrCreateVReg(U));
4283 } else {
4284 Register Dst = getOrCreateVReg(U);
4285 if (M < SrcElts) {
4287 Dst, getOrCreateVReg(*U.getOperand(0)), M);
4288 } else if (M < SrcElts * 2) {
4290 Dst, getOrCreateVReg(*U.getOperand(1)), M - SrcElts);
4291 } else {
4292 MIRBuilder.buildUndef(Dst);
4293 }
4294 }
4295 return true;
4296 }
4297
4298 // A single element src is transformed to a build_vector.
4299 if (SrcElts == 1) {
4302 for (int M : Mask) {
4303 LLT SrcTy = getLLTForType(*U.getOperand(0)->getType(), *DL);
4304 if (M == 0 || M == 1) {
4305 Ops.push_back(getOrCreateVReg(*U.getOperand(M)));
4306 } else {
4307 if (!Undef.isValid()) {
4308 Undef = MRI->createGenericVirtualRegister(SrcTy);
4309 MIRBuilder.buildUndef(Undef);
4310 }
4311 Ops.push_back(Undef);
4312 }
4313 }
4314 MIRBuilder.buildBuildVector(getOrCreateVReg(U), Ops);
4315 return true;
4316 }
4317
4318 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
4319 MIRBuilder
4320 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
4321 {getOrCreateVReg(*U.getOperand(0)),
4322 getOrCreateVReg(*U.getOperand(1))})
4323 .addShuffleMask(MaskAlloc);
4324 return true;
4325}
4326
4327bool IRTranslatorImpl::translatePHI(const User &U,
4328 MachineIRBuilder &MIRBuilder) {
4329 const PHINode &PI = cast<PHINode>(U);
4330
4331 SmallVector<MachineInstr *, 4> Insts;
4332 for (auto Reg : getOrCreateVRegs(PI)) {
4333 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
4334 Insts.push_back(MIB.getInstr());
4335 }
4336
4337 PendingPHIs.emplace_back(&PI, std::move(Insts));
4338 return true;
4339}
4340
4341bool IRTranslatorImpl::translateAtomicCmpXchg(const User &U,
4342 MachineIRBuilder &MIRBuilder) {
4343 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
4344
4345 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
4346
4347 auto Res = getOrCreateVRegs(I);
4348 Register OldValRes = Res[0];
4349 Register SuccessRes = Res[1];
4350 Register Addr = getOrCreateVReg(*I.getPointerOperand());
4351 Register Cmp = getOrCreateVReg(*I.getCompareOperand());
4352 Register NewVal = getOrCreateVReg(*I.getNewValOperand());
4353
4355 OldValRes, SuccessRes, Addr, Cmp, NewVal,
4356 *MF->getMachineMemOperand(
4357 MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
4358 getMemOpAlign(I), I.getAAMetadata(), I.getSyncScopeID(),
4359 I.getSuccessOrdering(), I.getFailureOrdering()));
4360 return true;
4361}
4362
4363bool IRTranslatorImpl::translateAtomicRMW(const User &U,
4364 MachineIRBuilder &MIRBuilder) {
4365 if (!mayTranslateUserTypes(U))
4366 return false;
4367
4368 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
4369 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
4370
4371 Register Res = getOrCreateVReg(I);
4372 Register Addr = getOrCreateVReg(*I.getPointerOperand());
4373 Register Val = getOrCreateVReg(*I.getValOperand());
4374
4375 unsigned Opcode = 0;
4376 switch (I.getOperation()) {
4377 default:
4378 return false;
4380 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
4381 break;
4382 case AtomicRMWInst::Add:
4383 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
4384 break;
4385 case AtomicRMWInst::Sub:
4386 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
4387 break;
4388 case AtomicRMWInst::And:
4389 Opcode = TargetOpcode::G_ATOMICRMW_AND;
4390 break;
4392 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
4393 break;
4394 case AtomicRMWInst::Or:
4395 Opcode = TargetOpcode::G_ATOMICRMW_OR;
4396 break;
4397 case AtomicRMWInst::Xor:
4398 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
4399 break;
4400 case AtomicRMWInst::Max:
4401 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
4402 break;
4403 case AtomicRMWInst::Min:
4404 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
4405 break;
4407 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
4408 break;
4410 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
4411 break;
4413 Opcode = TargetOpcode::G_ATOMICRMW_FADD;
4414 break;
4416 Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
4417 break;
4419 Opcode = TargetOpcode::G_ATOMICRMW_FMAX;
4420 break;
4422 Opcode = TargetOpcode::G_ATOMICRMW_FMIN;
4423 break;
4425 Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUM;
4426 break;
4428 Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUM;
4429 break;
4431 Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUMNUM;
4432 break;
4434 Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUMNUM;
4435 break;
4437 Opcode = TargetOpcode::G_ATOMICRMW_UINC_WRAP;
4438 break;
4440 Opcode = TargetOpcode::G_ATOMICRMW_UDEC_WRAP;
4441 break;
4443 Opcode = TargetOpcode::G_ATOMICRMW_USUB_COND;
4444 break;
4446 Opcode = TargetOpcode::G_ATOMICRMW_USUB_SAT;
4447 break;
4448 }
4449
4450 MIRBuilder.buildAtomicRMW(
4451 Opcode, Res, Addr, Val,
4452 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4453 Flags, MRI->getType(Val), getMemOpAlign(I),
4454 I.getAAMetadata(), I.getSyncScopeID(),
4455 I.getOrdering()));
4456 return true;
4457}
4458
4459bool IRTranslatorImpl::translateFence(const User &U,
4460 MachineIRBuilder &MIRBuilder) {
4461 const FenceInst &Fence = cast<FenceInst>(U);
4462 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
4463 Fence.getSyncScopeID());
4464 return true;
4465}
4466
4467bool IRTranslatorImpl::translateFreeze(const User &U,
4468 MachineIRBuilder &MIRBuilder) {
4469 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
4470 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
4471
4472 assert(DstRegs.size() == SrcRegs.size() &&
4473 "Freeze with different source and destination type?");
4474
4475 for (unsigned I = 0; I < DstRegs.size(); ++I) {
4476 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
4477 }
4478
4479 return true;
4480}
4481
4482void IRTranslatorImpl::finishPendingPhis() {
4483#ifndef NDEBUG
4484 DILocationVerifier Verifier;
4485 GISelObserverWrapper WrapperObserver(&Verifier);
4486 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
4487#endif // ifndef NDEBUG
4488 for (auto &Phi : PendingPHIs) {
4489 const PHINode *PI = Phi.first;
4490 if (PI->getType()->isEmptyTy())
4491 continue;
4492 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
4493 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
4494 EntryBuilder->setDebugLoc(PI->getDebugLoc());
4495#ifndef NDEBUG
4496 Verifier.setCurrentInst(PI);
4497#endif // ifndef NDEBUG
4498
4499 SmallPtrSet<const MachineBasicBlock *, 16> SeenPreds;
4500 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
4501 auto IRPred = PI->getIncomingBlock(i);
4502 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
4503 for (auto *Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
4504 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
4505 continue;
4506 SeenPreds.insert(Pred);
4507 for (unsigned j = 0; j < ValRegs.size(); ++j) {
4508 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
4509 MIB.addUse(ValRegs[j]);
4510 MIB.addMBB(Pred);
4511 }
4512 }
4513 }
4514 }
4515}
4516
4517void IRTranslatorImpl::translateDbgValueRecord(Value *V, bool HasArgList,
4518 const DILocalVariable *Variable,
4519 const DIExpression *Expression,
4520 const DebugLoc &DL,
4521 MachineIRBuilder &MIRBuilder) {
4522 assert(Variable->isValidLocationForIntrinsic(DL) &&
4523 "Expected inlined-at fields to agree");
4524 // Act as if we're handling a debug intrinsic.
4525 MIRBuilder.setDebugLoc(DL);
4526
4527 if (!V || HasArgList) {
4528 // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
4529 // terminate any prior location.
4530 MIRBuilder.buildIndirectDbgValue(0, Variable, Expression);
4531 return;
4532 }
4533
4534 if (const auto *CI = dyn_cast<Constant>(V)) {
4535 MIRBuilder.buildConstDbgValue(*CI, Variable, Expression);
4536 return;
4537 }
4538
4539 if (auto *AI = dyn_cast<AllocaInst>(V);
4540 AI && AI->isStaticAlloca() && Expression->startsWithDeref()) {
4541 // If the value is an alloca and the expression starts with a
4542 // dereference, track a stack slot instead of a register, as registers
4543 // may be clobbered.
4544 auto ExprOperands = Expression->getElements();
4545 auto *ExprDerefRemoved =
4546 DIExpression::get(AI->getContext(), ExprOperands.drop_front());
4547 MIRBuilder.buildFIDbgValue(getOrCreateFrameIndex(*AI), Variable,
4548 ExprDerefRemoved);
4549 return;
4550 }
4551 if (translateIfEntryValueArgument(false, V, Variable, Expression, DL,
4552 MIRBuilder))
4553 return;
4554 for (Register Reg : getOrCreateVRegs(*V)) {
4555 // FIXME: This does not handle register-indirect values at offset 0. The
4556 // direct/indirect thing shouldn't really be handled by something as
4557 // implicit as reg+noreg vs reg+imm in the first place, but it seems
4558 // pretty baked in right now.
4559 MIRBuilder.buildDirectDbgValue(Reg, Variable, Expression);
4560 }
4561}
4562
4563void IRTranslatorImpl::translateDbgDeclareRecord(
4564 Value *Address, bool HasArgList, const DILocalVariable *Variable,
4565 const DIExpression *Expression, const DebugLoc &DL,
4566 MachineIRBuilder &MIRBuilder) {
4567 if (!Address || isa<UndefValue>(Address)) {
4568 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *Variable << "\n");
4569 return;
4570 }
4571
4572 assert(Variable->isValidLocationForIntrinsic(DL) &&
4573 "Expected inlined-at fields to agree");
4574 auto AI = dyn_cast<AllocaInst>(Address);
4575 if (AI && AI->isStaticAlloca()) {
4576 // Static allocas are tracked at the MF level, no need for DBG_VALUE
4577 // instructions (in fact, they get ignored if they *do* exist).
4578 MF->setVariableDbgInfo(Variable, Expression,
4579 getOrCreateFrameIndex(*AI), DL);
4580 return;
4581 }
4582
4583 if (translateIfEntryValueArgument(true, Address, Variable,
4584 Expression, DL,
4585 MIRBuilder))
4586 return;
4587
4588 // A dbg.declare describes the address of a source variable, so lower it
4589 // into an indirect DBG_VALUE.
4590 MIRBuilder.setDebugLoc(DL);
4591 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), Variable,
4592 Expression);
4593}
4594
4595void IRTranslatorImpl::translateDbgInfo(const Instruction &Inst,
4596 MachineIRBuilder &MIRBuilder) {
4597 for (DbgRecord &DR : Inst.getDbgRecordRange()) {
4598 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
4599 MIRBuilder.setDebugLoc(DLR->getDebugLoc());
4600 assert(DLR->getLabel() && "Missing label");
4601 assert(DLR->getLabel()->isValidLocationForIntrinsic(
4602 MIRBuilder.getDebugLoc()) &&
4603 "Expected inlined-at fields to agree");
4604 MIRBuilder.buildDbgLabel(DLR->getLabel());
4605 continue;
4606 }
4607 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
4608 const DILocalVariable *Variable = DVR.getVariable();
4609 const DIExpression *Expression = DVR.getExpression();
4610 Value *V = DVR.getVariableLocationOp(0);
4611 if (DVR.isDbgDeclare())
4612 translateDbgDeclareRecord(V, DVR.hasArgList(), Variable, Expression,
4613 DVR.getDebugLoc(), MIRBuilder);
4614 else
4615 translateDbgValueRecord(V, DVR.hasArgList(), Variable, Expression,
4616 DVR.getDebugLoc(), MIRBuilder);
4617 }
4618}
4619
4620bool IRTranslatorImpl::translate(const Instruction &Inst) {
4621 CurBuilder->setDebugLoc(Inst.getDebugLoc());
4622 CurBuilder->setPCSections(Inst.getMetadata(LLVMContext::MD_pcsections));
4623 CurBuilder->setMMRAMetadata(Inst.getMetadata(LLVMContext::MD_mmra));
4624
4625 if (TLI->fallBackToDAGISel(Inst))
4626 return false;
4627
4628 switch (Inst.getOpcode()) {
4629#define HANDLE_INST(NUM, OPCODE, CLASS) \
4630 case Instruction::OPCODE: \
4631 return translate##OPCODE(Inst, *CurBuilder.get());
4632#include "llvm/IR/Instruction.def"
4633 default:
4634 return false;
4635 }
4636}
4637
4638bool IRTranslatorImpl::translate(const Constant &C, Register Reg) {
4639 // We only emit constants into the entry block from here. To prevent jumpy
4640 // debug behaviour remove debug line.
4641 if (auto CurrInstDL = CurBuilder->getDL())
4642 EntryBuilder->setDebugLoc(DebugLoc());
4643
4644 if (auto CI = dyn_cast<ConstantInt>(&C)) {
4645 // buildConstant expects a to-be-splatted scalar ConstantInt.
4646 if (isa<VectorType>(CI->getType()))
4647 CI = ConstantInt::get(CI->getContext(), CI->getValue());
4648 EntryBuilder->buildConstant(Reg, *CI);
4649 } else if (auto CB = dyn_cast<ConstantByte>(&C)) {
4650 // Byte constants share G_CONSTANT with integers; the destination Reg's
4651 // LLT (an integer LLT, see getLLTForType) determines vector splatting.
4652 EntryBuilder->buildConstant(Reg, CB->getValue());
4653 } else if (auto CF = dyn_cast<ConstantFP>(&C)) {
4654 // buildFConstant expects a to-be-splatted scalar ConstantFP.
4655 if (isa<VectorType>(CF->getType()))
4656 CF = ConstantFP::get(CF->getContext(), CF->getValue());
4657 EntryBuilder->buildFConstant(Reg, *CF);
4658 } else if (isa<UndefValue>(C))
4659 EntryBuilder->buildUndef(Reg);
4660 else if (isa<ConstantPointerNull>(C))
4661 EntryBuilder->buildConstant(Reg, 0);
4662 else if (auto GV = dyn_cast<GlobalValue>(&C))
4663 EntryBuilder->buildGlobalValue(Reg, GV);
4664 else if (auto CPA = dyn_cast<ConstantPtrAuth>(&C)) {
4665 Register Addr = getOrCreateVReg(*CPA->getPointer());
4666 Register AddrDisc = getOrCreateVReg(*CPA->getAddrDiscriminator());
4667 EntryBuilder->buildConstantPtrAuth(Reg, CPA, Addr, AddrDisc);
4668 } else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
4669 Constant &Elt = *CAZ->getElementValue(0u);
4670 if (isa<ScalableVectorType>(CAZ->getType())) {
4671 EntryBuilder->buildSplatVector(Reg, getOrCreateVReg(Elt));
4672 return true;
4673 }
4674 // Return the scalar if it is a <1 x Ty> vector.
4675 unsigned NumElts = CAZ->getElementCount().getFixedValue();
4676 if (NumElts == 1)
4677 return translateCopy(C, Elt, *EntryBuilder);
4678 // All elements are zero so we can just use the first one.
4679 EntryBuilder->buildSplatBuildVector(Reg, getOrCreateVReg(Elt));
4680 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
4681 // Return the scalar if it is a <1 x Ty> vector.
4682 if (CV->getNumElements() == 1)
4683 return translateCopy(C, *CV->getElementAsConstant(0), *EntryBuilder);
4685 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
4686 Constant &Elt = *CV->getElementAsConstant(i);
4687 Ops.push_back(getOrCreateVReg(Elt));
4688 }
4689 EntryBuilder->buildBuildVector(Reg, Ops);
4690 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
4691 switch(CE->getOpcode()) {
4692#define HANDLE_INST(NUM, OPCODE, CLASS) \
4693 case Instruction::OPCODE: \
4694 return translate##OPCODE(*CE, *EntryBuilder.get());
4695#include "llvm/IR/Instruction.def"
4696 default:
4697 return false;
4698 }
4699 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
4700 if (CV->getNumOperands() == 1)
4701 return translateCopy(C, *CV->getOperand(0), *EntryBuilder);
4703 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
4704 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
4705 }
4706 EntryBuilder->buildBuildVector(Reg, Ops);
4707 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
4708 EntryBuilder->buildBlockAddress(Reg, BA);
4709 } else
4710 return false;
4711
4712 return true;
4713}
4714
4715bool IRTranslatorImpl::mayTranslateUserTypes(const User &U) const {
4716 const TargetMachine &TM = TLI->getTargetMachine();
4717 if (LLT::getUseExtended())
4718 return true;
4719
4720 // BF16 cannot currently be represented by default LLT. To avoid miscompiles
4721 // we prevent any instructions using them by default in all targets that do
4722 // not explicitly enable it via LLT::setUseExtended(true).
4723 // SPIRV target is exception.
4724 return TM.getTargetTriple().isSPIRV() ||
4725 (!U.getType()->getScalarType()->isBFloatTy() &&
4726 !any_of(U.operands(), [](Value *V) {
4727 return V->getType()->getScalarType()->isBFloatTy();
4728 }));
4729}
4730
4731bool IRTranslatorImpl::finalizeBasicBlock(const BasicBlock &BB,
4733 for (auto &BTB : SL->BitTestCases) {
4734 // Emit header first, if it wasn't already emitted.
4735 if (!BTB.Emitted)
4736 emitBitTestHeader(BTB, BTB.Parent);
4737
4738 BranchProbability UnhandledProb = BTB.Prob;
4739 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
4740 UnhandledProb -= BTB.Cases[j].ExtraProb;
4741 // Set the current basic block to the mbb we wish to insert the code into
4742 MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
4743 // If all cases cover a contiguous range, it is not necessary to jump to
4744 // the default block after the last bit test fails. This is because the
4745 // range check during bit test header creation has guaranteed that every
4746 // case here doesn't go outside the range. In this case, there is no need
4747 // to perform the last bit test, as it will always be true. Instead, make
4748 // the second-to-last bit-test fall through to the target of the last bit
4749 // test, and delete the last bit test.
4750
4751 MachineBasicBlock *NextMBB;
4752 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
4753 // Second-to-last bit-test with contiguous range: fall through to the
4754 // target of the final bit test.
4755 NextMBB = BTB.Cases[j + 1].TargetBB;
4756 } else if (j + 1 == ej) {
4757 // For the last bit test, fall through to Default.
4758 NextMBB = BTB.Default;
4759 } else {
4760 // Otherwise, fall through to the next bit test.
4761 NextMBB = BTB.Cases[j + 1].ThisBB;
4762 }
4763
4764 emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
4765
4766 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
4767 // We need to record the replacement phi edge here that normally
4768 // happens in emitBitTestCase before we delete the case, otherwise the
4769 // phi edge will be lost.
4770 addMachineCFGPred({BTB.Parent->getBasicBlock(),
4771 BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
4772 MBB);
4773 // Since we're not going to use the final bit test, remove it.
4774 BTB.Cases.pop_back();
4775 break;
4776 }
4777 }
4778 // This is "default" BB. We have two jumps to it. From "header" BB and from
4779 // last "case" BB, unless the latter was skipped.
4780 CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
4781 BTB.Default->getBasicBlock()};
4782 addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
4783 if (!BTB.ContiguousRange) {
4784 addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
4785 }
4786 }
4787 SL->BitTestCases.clear();
4788
4789 for (auto &JTCase : SL->JTCases) {
4790 // Emit header first, if it wasn't already emitted.
4791 if (!JTCase.first.Emitted)
4792 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
4793
4794 emitJumpTable(JTCase.second, JTCase.second.MBB);
4795 }
4796 SL->JTCases.clear();
4797
4798 for (auto &SwCase : SL->SwitchCases)
4799 emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
4800 SL->SwitchCases.clear();
4801
4802 // Check if we need to generate stack-protector guard checks.
4803 if (SPInfo->shouldEmitSDCheck(BB)) {
4804 bool FunctionBasedInstrumentation =
4805 TLI->getSSPStackGuardCheck(*MF->getFunction().getParent(), *Libcalls);
4806 SPDescriptor.initialize(&BB, &MBB, FunctionBasedInstrumentation);
4807 }
4808 // Handle stack protector.
4809 if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
4810 LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n");
4811 return false;
4812 } else if (SPDescriptor.shouldEmitStackProtector()) {
4813 MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB();
4814 MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB();
4815
4816 // Find the split point to split the parent mbb. At the same time copy all
4817 // physical registers used in the tail of parent mbb into virtual registers
4818 // before the split point and back into physical registers after the split
4819 // point. This prevents us needing to deal with Live-ins and many other
4820 // register allocation issues caused by us splitting the parent mbb. The
4821 // register allocator will clean up said virtual copies later on.
4823 ParentMBB, *MF->getSubtarget().getInstrInfo());
4824
4825 // Splice the terminator of ParentMBB into SuccessMBB.
4826 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
4827 ParentMBB->end());
4828
4829 // Add compare/jump on neq/jump to the parent BB.
4830 if (!emitSPDescriptorParent(SPDescriptor, ParentMBB))
4831 return false;
4832
4833 // CodeGen Failure MBB if we have not codegened it yet.
4834 MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB();
4835 if (FailureMBB->empty()) {
4836 if (!emitSPDescriptorFailure(SPDescriptor, FailureMBB))
4837 return false;
4838 }
4839
4840 // Clear the Per-BB State.
4841 SPDescriptor.resetPerBBState();
4842 }
4843 return true;
4844}
4845
4846bool IRTranslatorImpl::emitSPDescriptorParent(StackProtectorDescriptor &SPD,
4847 MachineBasicBlock *ParentBB) {
4848 CurBuilder->setInsertPt(*ParentBB, ParentBB->end());
4849 // First create the loads to the guard/stack slot for the comparison.
4850 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
4851 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
4852 LLT PtrMemTy = getLLTForMVT(TLI->getPointerMemTy(*DL));
4853
4854 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
4855 int FI = MFI.getStackProtectorIndex();
4856
4857 Register Guard;
4858 Register StackSlotPtr = CurBuilder->buildFrameIndex(PtrTy, FI).getReg(0);
4859 const Module &M = *ParentBB->getParent()->getFunction().getParent();
4860 Align Align = DL->getPrefTypeAlign(PointerType::getUnqual(M.getContext()));
4861
4862 // Generate code to load the content of the guard slot.
4863 Register GuardVal =
4864 CurBuilder
4865 ->buildLoad(PtrMemTy, StackSlotPtr,
4866 MachinePointerInfo::getFixedStack(*MF, FI), Align,
4868 .getReg(0);
4869
4870 // Retrieve guard check function, nullptr if instrumentation is inlined.
4871 if (const Function *GuardCheckFn = TLI->getSSPStackGuardCheck(M, *Libcalls)) {
4872 // This path is currently untestable on GlobalISel, since the only platform
4873 // that needs this seems to be Windows, and we fall back on that currently.
4874 // The code still lives here in case that changes.
4875 // Silence warning about unused variable until the code below that uses
4876 // 'GuardCheckFn' is enabled.
4877 (void)GuardCheckFn;
4878 return false;
4879#if 0
4880 // The target provides a guard check function to validate the guard value.
4881 // Generate a call to that function with the content of the guard slot as
4882 // argument.
4883 FunctionType *FnTy = GuardCheckFn->getFunctionType();
4884 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
4885 ISD::ArgFlagsTy Flags;
4886 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
4887 Flags.setInReg();
4888 CallLowering::ArgInfo GuardArgInfo(
4889 {GuardVal, FnTy->getParamType(0), {Flags}});
4890
4891 CallLowering::CallLoweringInfo Info;
4892 Info.OrigArgs.push_back(GuardArgInfo);
4893 Info.CallConv = GuardCheckFn->getCallingConv();
4894 Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0);
4895 Info.OrigRet = {Register(), FnTy->getReturnType()};
4896 if (!CLI->lowerCall(MIRBuilder, Info)) {
4897 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n");
4898 return false;
4899 }
4900 return true;
4901#endif
4902 }
4903
4904 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
4905 // Otherwise, emit a volatile load to retrieve the stack guard value.
4906 if (TLI->useLoadStackGuardNode(*ParentBB->getBasicBlock()->getModule())) {
4907 Guard = MRI->createGenericVirtualRegister(PtrMemTy);
4908 getStackGuard(Guard, *CurBuilder);
4909 } else {
4910 // TODO: test using android subtarget when we support @llvm.thread.pointer.
4911 const Value *IRGuard = TLI->getSDagStackGuard(M, *Libcalls);
4912 Register GuardPtr = getOrCreateVReg(*IRGuard);
4913
4914 Guard = CurBuilder
4915 ->buildLoad(PtrMemTy, GuardPtr,
4916 MachinePointerInfo::getFixedStack(*MF, FI), Align,
4919 .getReg(0);
4920 }
4921
4922 // Perform the comparison.
4923 auto Cmp =
4924 CurBuilder->buildICmp(CmpInst::ICMP_NE, LLT::integer(1), Guard, GuardVal);
4925 // If the guard/stackslot do not equal, branch to failure MBB.
4926 CurBuilder->buildBrCond(Cmp, *SPD.getFailureMBB());
4927 // Otherwise branch to success MBB.
4928 CurBuilder->buildBr(*SPD.getSuccessMBB());
4929 return true;
4930}
4931
4932bool IRTranslatorImpl::emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
4933 MachineBasicBlock *FailureBB) {
4934 const RTLIB::LibcallImpl LibcallImpl =
4935 Libcalls->getLibcallImpl(RTLIB::STACKPROTECTOR_CHECK_FAIL);
4936 if (LibcallImpl == RTLIB::Unsupported)
4937 return false;
4938
4939 CurBuilder->setInsertPt(*FailureBB, FailureBB->end());
4940
4941 CallLowering::CallLoweringInfo Info;
4942 Info.CallConv = Libcalls->getLibcallImplCallingConv(LibcallImpl);
4943
4944 StringRef LibcallName =
4946 Info.Callee = MachineOperand::CreateES(LibcallName.data());
4947 Info.OrigRet = {Register(), Type::getVoidTy(MF->getFunction().getContext()),
4948 0};
4949 if (!CLI->lowerCall(*CurBuilder, Info)) {
4950 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n");
4951 return false;
4952 }
4953
4954 // Emit a trap instruction if we are required to do so.
4955 const TargetOptions &TargetOpts = TLI->getTargetMachine().Options;
4956 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
4957 CurBuilder->buildInstr(TargetOpcode::G_TRAP);
4958
4959 return true;
4960}
4961
4962void IRTranslatorImpl::finalizeFunction() {
4963 // Release the memory used by the different maps we
4964 // needed during the translation.
4965 PendingPHIs.clear();
4966 VMap.reset();
4967 FrameIndices.clear();
4968 MachinePreds.clear();
4969 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
4970 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
4971 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
4972 EntryBuilder.reset();
4973 CurBuilder.reset();
4974 FuncInfo.clear();
4975 SPDescriptor.resetPerFunctionState();
4976}
4977
4978/// Returns true if a BasicBlock \p BB within a variadic function contains a
4979/// variadic musttail call.
4980static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
4981 if (!IsVarArg)
4982 return false;
4983
4984 // Walk the block backwards, because tail calls usually only appear at the end
4985 // of a block.
4986 return llvm::any_of(llvm::reverse(BB), [](const Instruction &I) {
4987 const auto *CI = dyn_cast<CallInst>(&I);
4988 return CI && CI->isMustTailCall();
4989 });
4990}
4991
4993 MachineFunction &CurMF, function_ref<GISelCSEInfo *()> GetCSEInfo,
4994 bool ShouldSkipOpts, function_ref<AAResults *()> GetAAResults,
4996 function_ref<AssumptionCache *()> GetAC, TargetLibraryInfo *LibraryInfo,
4997 const LibcallLoweringInfo *LibcallInfo, SSPLayoutInfo *StackProtectorInfo) {
4998 MF = &CurMF;
4999 const Function &F = MF->getFunction();
5000 ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
5001 CLI = MF->getSubtarget().getCallLowering();
5002 SPInfo = StackProtectorInfo;
5003
5004 if (CLI->fallBackToDAGISel(*MF)) {
5005 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
5006 F.getSubprogram(), &F.getEntryBlock());
5007 R << "unable to lower function: "
5008 << ore::NV("Prototype", F.getFunctionType());
5009
5010 reportTranslationError(*MF, *ORE, R);
5011 return false;
5012 }
5013
5014 // Set the CSEConfig and run the analysis.
5015 GISelCSEInfo *CSEInfo = nullptr;
5016
5017 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
5019 : true;
5020
5021 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
5022 TLI = Subtarget.getTargetLowering();
5023
5024 if (EnableCSE) {
5025 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
5026 CSEInfo = GetCSEInfo();
5027 EntryBuilder->setCSEInfo(CSEInfo);
5028 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
5029 CurBuilder->setCSEInfo(CSEInfo);
5030 } else {
5031 EntryBuilder = std::make_unique<MachineIRBuilder>();
5032 CurBuilder = std::make_unique<MachineIRBuilder>();
5033 }
5034 CLI = Subtarget.getCallLowering();
5035 CurBuilder->setMF(*MF);
5036 EntryBuilder->setMF(*MF);
5037 MRI = &MF->getRegInfo();
5038 DL = &F.getDataLayout();
5039 const TargetMachine &TM = MF->getTarget();
5040 EnableOpts = OptLevel != CodeGenOptLevel::None && !ShouldSkipOpts;
5041 FuncInfo.MF = MF;
5042 if (EnableOpts) {
5043 AA = GetAAResults();
5044 FuncInfo.BPI = GetBPI();
5045 AC = GetAC();
5046 } else {
5047 AA = nullptr;
5048 FuncInfo.BPI = nullptr;
5049 AC = nullptr;
5050 }
5051 LibInfo = LibraryInfo;
5052 Libcalls = LibcallInfo;
5053
5054 FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
5055
5056 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
5057 SL->init(*TLI, TM, *DL);
5058
5059 assert(PendingPHIs.empty() && "stale PHIs");
5060
5061 // Targets which want to use big endian can enable it using
5062 // enableBigEndian()
5063 if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
5064 // Currently we don't properly handle big endian code.
5065 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
5066 F.getSubprogram(), &F.getEntryBlock());
5067 R << "unable to translate in big endian mode";
5068 reportTranslationError(*MF, *ORE, R);
5069 return false;
5070 }
5071
5072 // Release the per-function state when we return, whether we succeeded or not.
5073 llvm::scope_exit FinalizeOnReturn([this]() { finalizeFunction(); });
5074
5075 // Setup a separate basic-block for the arguments and constants
5076 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
5077 MF->push_back(EntryBB);
5078 EntryBuilder->setMBB(*EntryBB);
5079
5080 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHIIt()->getDebugLoc();
5081 SwiftError.setFunction(CurMF);
5082 SwiftError.createEntriesInEntryBlock(DbgLoc);
5083
5084 bool IsVarArg = F.isVarArg();
5085 bool HasMustTailInVarArgFn = false;
5086
5087 // Create all blocks, in IR order, to preserve the layout.
5088 FuncInfo.MBBMap.resize(F.getMaxBlockNumber());
5089 for (const BasicBlock &BB: F) {
5090 auto *&MBB = FuncInfo.MBBMap[BB.getNumber()];
5091
5092 MBB = MF->CreateMachineBasicBlock(&BB);
5093 MF->push_back(MBB);
5094
5095 // Only mark the block if the BlockAddress actually has users. The
5096 // hasAddressTaken flag may be stale if the BlockAddress was optimized away
5097 // but the constant still exists in the uniquing table.
5098 if (BB.hasAddressTaken()) {
5099 if (BlockAddress *BA = BlockAddress::lookup(&BB))
5100 if (!BA->hasZeroLiveUses())
5101 MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
5102 }
5103
5104 if (!HasMustTailInVarArgFn)
5105 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
5106 }
5107
5108 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
5109
5110 // Make our arguments/constants entry block fallthrough to the IR entry block.
5111 EntryBB->addSuccessor(&getMBB(F.front()));
5112
5113 // Lower the actual args into this basic block.
5114 SmallVector<ArrayRef<Register>, 8> VRegArgs;
5115 for (const Argument &Arg: F.args()) {
5116 if (DL->getTypeStoreSize(Arg.getType()).isZero())
5117 continue; // Don't handle zero sized types.
5118 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
5119 VRegArgs.push_back(VRegs);
5120
5121 if (CLI->supportSwiftError() && Arg.hasSwiftErrorAttr()) {
5122 assert(VRegs.size() == 1 && "Too many vregs for Swift error");
5123 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
5124 }
5125 }
5126
5127 if (!CLI->lowerFormalArguments(*EntryBuilder, F, VRegArgs, FuncInfo)) {
5128 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
5129 F.getSubprogram(), &F.getEntryBlock());
5130 R << "unable to lower arguments: "
5131 << ore::NV("Prototype", F.getFunctionType());
5132 reportTranslationError(*MF, *ORE, R);
5133 return false;
5134 }
5135
5136 // Need to visit defs before uses when translating instructions.
5137 GISelObserverWrapper WrapperObserver;
5138 if (EnableCSE && CSEInfo)
5139 WrapperObserver.addObserver(CSEInfo);
5140 {
5142#ifndef NDEBUG
5143 DILocationVerifier Verifier;
5144 WrapperObserver.addObserver(&Verifier);
5145#endif // ifndef NDEBUG
5146 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
5147 for (const BasicBlock *BB : RPOT) {
5148 MachineBasicBlock &MBB = getMBB(*BB);
5149 // Set the insertion point of all the following translations to
5150 // the end of this basic block.
5151 CurBuilder->setMBB(MBB);
5152 HasTailCall = false;
5153 for (const Instruction &Inst : *BB) {
5154 // If we translated a tail call in the last step, then we know
5155 // everything after the call is either a return, or something that is
5156 // handled by the call itself. (E.g. a lifetime marker or assume
5157 // intrinsic.) In this case, we should stop translating the block and
5158 // move on.
5159 if (HasTailCall)
5160 break;
5161#ifndef NDEBUG
5162 Verifier.setCurrentInst(&Inst);
5163#endif // ifndef NDEBUG
5164
5165 // Translate any debug-info attached to the instruction.
5166 translateDbgInfo(Inst, *CurBuilder);
5167
5168 if (translate(Inst))
5169 continue;
5170
5171 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
5172 Inst.getDebugLoc(), BB);
5173 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
5174
5175 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
5176 std::string InstStrStorage;
5177 raw_string_ostream InstStr(InstStrStorage);
5178 InstStr << Inst;
5179
5180 R << ": '" << InstStrStorage << "'";
5181 }
5182
5183 reportTranslationError(*MF, *ORE, R);
5184 return false;
5185 }
5186
5187 if (!finalizeBasicBlock(*BB, MBB)) {
5188 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
5189 BB->getTerminator()->getDebugLoc(), BB);
5190 R << "unable to translate basic block";
5191 reportTranslationError(*MF, *ORE, R);
5192 return false;
5193 }
5194 }
5195#ifndef NDEBUG
5196 WrapperObserver.removeObserver(&Verifier);
5197#endif
5198 }
5199
5200 finishPendingPhis();
5201
5202 SwiftError.propagateVRegs();
5203
5204 // Merge the argument lowering and constants block with its single
5205 // successor, the LLVM-IR entry block. We want the basic block to
5206 // be maximal.
5207 assert(EntryBB->succ_size() == 1 &&
5208 "Custom BB used for lowering should have only one successor");
5209 // Get the successor of the current entry block.
5210 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
5211 assert(NewEntryBB.pred_size() == 1 &&
5212 "LLVM-IR entry block has a predecessor!?");
5213 // Move all the instruction from the current entry block to the
5214 // new entry block.
5215 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
5216 EntryBB->end());
5217
5218 // Update the live-in information for the new entry block.
5219 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
5220 NewEntryBB.addLiveIn(LiveIn);
5221 NewEntryBB.sortUniqueLiveIns();
5222
5223 // Get rid of the now empty basic block.
5224 EntryBB->removeSuccessor(&NewEntryBB);
5225 MF->remove(EntryBB);
5226 MF->deleteMachineBasicBlock(EntryBB);
5227
5228 assert(&MF->front() == &NewEntryBB &&
5229 "New entry wasn't next in the list of basic block!");
5230
5231 // Initialize stack protector information.
5232 SPInfo->copyToMachineFrameInfo(MF->getFrameInfo());
5233
5234 return false;
5235}
5236
5238 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
5239 Function &F = MF.getFunction();
5240
5241 bool ShouldSkipOpts = skipFunction(MF.getFunction());
5242 return Impl->runOnMachineFunction(
5243 MF,
5244 [&]() {
5248 return &Wrapper.get(TPC.getCSEConfig());
5249 },
5250 ShouldSkipOpts,
5251 [&]() { return &getAnalysis<AAResultsWrapperPass>().getAAResults(); },
5252 [&]() {
5254 },
5255 [&]() {
5256 return &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
5257 MF.getFunction());
5258 },
5260 &getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
5261 *F.getParent(), Subtarget),
5262 &getAnalysis<StackProtector>().getLayoutInfo());
5263}
5264
5266 : Impl(std::make_unique<IRTranslatorImpl>(OptLevel)) {}
5267
5270
5273 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
5274 Function &F = MF.getFunction();
5275
5276 bool ShouldSkipOpts = MF.getFunction().hasOptNone();
5278 .getManager();
5279 auto &MAMProxy =
5281 const ModuleLibcallLoweringInfo *MLLI =
5282 MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(*F.getParent());
5283 if (!MLLI)
5285 "LibcallLoweringModuleAnalysis must be available for IRTranslator");
5286 Impl->runOnMachineFunction(
5287 MF, [&]() { return MFAM.getResult<GISelCSEAnalysis>(MF).get(); },
5288 ShouldSkipOpts, [&]() { return &FAM.getResult<AAManager>(F); },
5289 [&]() { return &FAM.getResult<BranchProbabilityAnalysis>(F); },
5290 [&]() { return &FAM.getResult<AssumptionAnalysis>(F); },
5291 &FAM.getResult<TargetLibraryAnalysis>(F),
5292 &getLibcallLowering(*MLLI, Subtarget),
5293 &FAM.getResult<SSPLayoutAnalysis>(F));
5294
5296}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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
static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB)
Returns true if a BasicBlock BB within a variadic function contains a variadic musttail call.
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
IRTranslator LLVM IR static false void reportTranslationError(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R)
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[]
static LVOptions Options
Definition LVOptions.cpp:25
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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
FunctionAnalysisManager FAM
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
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
A manager for alias analyses.
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:1077
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.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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
LLVM_ABI bool hasSwiftErrorAttr() const
Return true if this argument has the swifterror attribute.
Definition Function.cpp:147
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
@ 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
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ 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:672
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...
The address of a basic block.
Definition Constants.h:1088
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Legacy analysis pass which computes BlockFrequencyInfo.
Analysis pass which computes BranchProbabilityInfo.
Legacy analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getUnknown()
static constexpr 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:740
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
bool isFPPredicate() const
Definition InstrTypes.h:845
bool isIntPredicate() const
Definition InstrTypes.h:846
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
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:219
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
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:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
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:64
Value * getAddress() const
DILabel * getLabel() const
DebugLoc getDebugLoc() const
Value * getValue(unsigned OpIdx=0) const
DILocalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
A debug info location.
Definition DebugLoc.h:126
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:134
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:193
const BasicBlock & getEntryBlock() const
Definition Function.h:793
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:695
Constant * getPersonalityFn() const
Get the personality function associated with this function.
const Function & getFunction() const
Definition Function.h:166
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:251
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:685
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
The actual analysis pass wrapper.
Definition CSEInfo.h:243
Simple wrapper that does the following.
Definition CSEInfo.h:213
The CSE Analysis object.
Definition CSEInfo.h:72
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
IRTranslatorImpl(CodeGenOptLevel OptLevel=CodeGenOptLevel::None)
bool runOnMachineFunction(MachineFunction &MF, function_ref< GISelCSEInfo *()> GetCSEInfo, bool ShouldSkipOpts, function_ref< AAResults *()> GetAAResults, function_ref< BranchProbabilityInfo *()> GetBPI, function_ref< AssumptionCache *()> GetAC, TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallInfo, SSPLayoutInfo *StackProtectorInfo)
IRTranslatorLegacy(CodeGenOptLevel OptLevel=CodeGenOptLevel::None)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
~IRTranslatorLegacy() override
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
IRTranslatorPass(CodeGenOptLevel OptLevel)
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.
static bool getUseExtended()
constexpr bool isScalar() const
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.
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.
static constexpr LLT token()
Get a low-level token; just a scalar with zero bits (or no size).
static LLT integer(unsigned SizeInBits)
LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Tracks which library functions to use for a particular subtarget or function.
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:1567
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.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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 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 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 & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
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 & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
LLVM_ABI void copyIRFlags(const Instruction &I)
Copy all flags to MachineInst MIFlags.
static LLVM_ABI uint32_t copyFlagsFromInstruction(const Instruction &I)
LLVM_ABI void setDeactivationSymbol(MachineFunction &MF, Value *DS)
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)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
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(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Class to install both of the above.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
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.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:397
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
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
SwitchLowering(FunctionLoweringInfo &funcinfo)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
TargetOptions Options
const Target & getTarget() const
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.
FPOpFusion::FPOpFusionMode AllowFPOpFusion
AllowFPOpFusion - This flag is set by the -fp-contract=xxx option.
Target-Independent Code Generator Pass Configuration Options.
virtual std::unique_ptr< CSEConfigBase > getCSEConfig() const
Returns the CSEConfig object to use for the current optimization level.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const CallLowering * getCallLowering() const
virtual const TargetLowering * getTargetLowering() const
bool isSPIRV() const
Tests whether the target is SPIR-V (32/64-bit/Logical).
Definition Triple.h:973
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getZero()
Definition TypeSize.h:349
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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:180
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:319
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
BasicBlock * getSuccessor(unsigned i=0) const
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr bool isZero() const
Definition TypeSize.h:153
An efficient, type-erasing, non-owning reference to a callable.
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.
Pass manager infrastructure for declaring and invalidating analyses.
#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 char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Offsets
Offsets in bytes from the start of the input buffer.
LLVM_ABI 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:51
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:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:578
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Undef
Value of the register doesn't matter.
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:2554
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:315
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:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI 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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:204
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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:248
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
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:1746
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:407
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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:149
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:74
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1137
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:2052
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
IntPtrTy
Definition InstrProf.h:82
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:25
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI void computeValueLLTs(const DataLayout &DL, Type &Ty, SmallVectorImpl< LLT > &ValueLLTs, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
computeValueLLTs - Given an LLVM IR type, compute a sequence of LLTs that represent all the individua...
Definition Analysis.cpp:153
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:181
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.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
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)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
Register Reg
The virtual register containing the index of the jump table entry to jump to.
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
unsigned JTI
The JumpTableIndex for this jump table in the function.
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.