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