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