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