1//===- SelectionDAGBuilder.h - Selection-DAG building -----------*- 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//
9// This implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
14#define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
15
16#include "StatepointLowering.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
22#include "llvm/CodeGen/CodeGenCommonISel.h"
23#include "llvm/CodeGen/ISDOpcodes.h"
24#include "llvm/CodeGen/SelectionDAGNodes.h"
25#include "llvm/CodeGen/SwitchLoweringUtils.h"
26#include "llvm/CodeGen/TargetLowering.h"
27#include "llvm/CodeGen/ValueTypes.h"
28#include "llvm/CodeGenTypes/MachineValueType.h"
29#include "llvm/IR/DebugLoc.h"
30#include "llvm/IR/Instruction.h"
31#include "llvm/Support/BranchProbability.h"
32#include "llvm/Support/CodeGen.h"
33#include "llvm/Support/ErrorHandling.h"
34#include <algorithm>
35#include <cassert>
36#include <cstdint>
37#include <optional>
38#include <utility>
39#include <vector>
40
41namespace llvm {
42
43class AAResults;
44class AllocaInst;
45class AtomicCmpXchgInst;
46class AtomicRMWInst;
47class AssumptionCache;
48class BasicBlock;
49class CallInst;
50class CallBrInst;
51class CatchPadInst;
52class CatchReturnInst;
53class CatchSwitchInst;
54class CondBrInst;
55class CleanupPadInst;
56class CleanupReturnInst;
57class Constant;
58class ConstrainedFPIntrinsic;
59class DataLayout;
60class DIExpression;
61class DILocalVariable;
62class DILocation;
63class FenceInst;
64class FunctionLoweringInfo;
65class GCFunctionInfo;
66class GCRelocateInst;
67class GCResultInst;
68class GCStatepointInst;
69class IndirectBrInst;
70class InvokeInst;
71class LandingPadInst;
72class LLVMContext;
73class LoadInst;
74class MachineBasicBlock;
75class PHINode;
76class ResumeInst;
77class ReturnInst;
78class SDDbgValue;
79class SelectionDAG;
80class StoreInst;
81class SwiftErrorValueTracking;
82class SwitchInst;
83class TargetLibraryInfo;
84class TargetMachine;
85class Type;
86class VAArgInst;
87class UnreachableInst;
88class Use;
89class User;
90class Value;
91
92//===----------------------------------------------------------------------===//
93/// SelectionDAGBuilder - This is the common target-independent lowering
94/// implementation that is parameterized by a TargetLowering object.
95///
96class SelectionDAGBuilder {
97 /// The current instruction being visited.
98 const Instruction *CurInst = nullptr;
99
100 DenseMap<const Value*, SDValue> NodeMap;
101
102 /// Maps argument value for unused arguments. This is used
103 /// to preserve debug information for incoming arguments.
104 DenseMap<const Value*, SDValue> UnusedArgNodeMap;
105
106 /// Helper type for DanglingDebugInfoMap.
107 class DanglingDebugInfo {
108 unsigned SDNodeOrder = 0;
109
110 public:
111 DILocalVariable *Variable;
112 DIExpression *Expression;
113 DebugLoc dl;
114 DanglingDebugInfo() = default;
115 DanglingDebugInfo(DILocalVariable *Var, DIExpression *Expr, DebugLoc DL,
116 unsigned SDNO)
117 : SDNodeOrder(SDNO), Variable(Var), Expression(Expr),
118 dl(std::move(DL)) {}
119
120 DILocalVariable *getVariable() const { return Variable; }
121 DIExpression *getExpression() const { return Expression; }
122 DebugLoc getDebugLoc() const { return dl; }
123 unsigned getSDNodeOrder() const { return SDNodeOrder; }
124
125 /// Helper for printing DanglingDebugInfo. This hoop-jumping is to
126 /// store a Value pointer, so that we can print a whole DDI as one object.
127 /// Call SelectionDAGBuilder::printDDI instead of using directly.
128 struct Print {
129 Print(const Value *V, const DanglingDebugInfo &DDI) : V(V), DDI(DDI) {}
130 const Value *V;
131 const DanglingDebugInfo &DDI;
132 friend raw_ostream &operator<<(raw_ostream &OS,
133 const DanglingDebugInfo::Print &P) {
134 OS << "DDI(var=" << *P.DDI.getVariable();
135 if (P.V)
136 OS << ", val=" << *P.V;
137 else
138 OS << ", val=nullptr";
139
140 OS << ", expr=" << *P.DDI.getExpression()
141 << ", order=" << P.DDI.getSDNodeOrder()
142 << ", loc=" << P.DDI.getDebugLoc() << ")";
143 return OS;
144 }
145 };
146 };
147
148 /// Returns an object that defines `raw_ostream &operator<<` for printing.
149 /// Usage example:
150 //// errs() << printDDI(MyDanglingInfo) << " is dangling\n";
151 DanglingDebugInfo::Print printDDI(const Value *V,
152 const DanglingDebugInfo &DDI) {
153 return DanglingDebugInfo::Print(V, DDI);
154 }
155
156 /// Helper type for DanglingDebugInfoMap.
157 typedef std::vector<DanglingDebugInfo> DanglingDebugInfoVector;
158
159 /// Keeps track of dbg_values for which we have not yet seen the referent.
160 /// We defer handling these until we do see it.
161 MapVector<const Value*, DanglingDebugInfoVector> DanglingDebugInfoMap;
162
163 /// Cache the module flag for whether we should use debug-info assignment
164 /// tracking.
165 bool AssignmentTrackingEnabled = false;
166
167 /// Cache whether a debug value can name the address of a global directly,
168 /// rather than holding out for a register with it.
169 bool CanDescribeGlobalAddressInLocationList = false;
170
171public:
172 /// Loads are not emitted to the program immediately. We bunch them up and
173 /// then emit token factor nodes when possible. This allows us to get simple
174 /// disambiguation between loads without worrying about alias analysis.
175 SmallVector<SDValue, 8> PendingLoads;
176
177 /// State used while lowering a statepoint sequence (gc_statepoint,
178 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details.
179 StatepointLoweringState StatepointLowering;
180
181private:
182 /// CopyToReg nodes that copy values to virtual registers for export to other
183 /// blocks need to be emitted before any terminator instruction, but they have
184 /// no other ordering requirements. We bunch them up and the emit a single
185 /// tokenfactor for them just before terminator instructions.
186 SmallVector<SDValue, 8> PendingExports;
187
188 /// Similar to loads, nodes corresponding to constrained FP intrinsics are
189 /// bunched up and emitted when necessary. These can be moved across each
190 /// other and any (normal) memory operation (load or store), but not across
191 /// calls or instructions having unspecified side effects. As a special
192 /// case, constrained FP intrinsics using fpexcept.strict may not be deleted
193 /// even if otherwise unused, so they need to be chained before any
194 /// terminator instruction (like PendingExports). We track the latter
195 /// set of nodes in a separate list.
196 SmallVector<SDValue, 8> PendingConstrainedFP;
197 SmallVector<SDValue, 8> PendingConstrainedFPStrict;
198
199 /// Update root to include all chains from the Pending list.
200 SDValue updateRoot(SmallVectorImpl<SDValue> &Pending);
201
202 /// Given a node representing a floating-point operation and its specified
203 /// exception behavior, this either updates the root or stores the node in
204 /// a list to be added to chains latter.
205 void pushFPOpOutChain(SDValue Result, fp::ExceptionBehavior EB);
206
207 /// A unique monotonically increasing number used to order the SDNodes we
208 /// create.
209 unsigned SDNodeOrder;
210
211 /// Emit comparison and split W into two subtrees.
212 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
213 const SwitchCG::SwitchWorkListItem &W, Value *Cond,
214 MachineBasicBlock *SwitchMBB);
215
216 /// Lower W.
217 void lowerWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
218 MachineBasicBlock *SwitchMBB,
219 MachineBasicBlock *DefaultMBB);
220
221 /// Peel the top probability case if it exceeds the threshold
222 MachineBasicBlock *
223 peelDominantCaseCluster(const SwitchInst &SI,
224 SwitchCG::CaseClusterVector &Clusters,
225 BranchProbability &PeeledCaseProb);
226
227private:
228 const TargetMachine &TM;
229
230public:
231 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
232 /// nodes without a corresponding SDNode.
233 static const unsigned LowestSDNodeOrder = 1;
234
235 SelectionDAG &DAG;
236 BatchAAResults *BatchAA = nullptr;
237 AssumptionCache *AC = nullptr;
238 const TargetLibraryInfo *LibInfo = nullptr;
239 const TargetTransformInfo *TTI = nullptr;
240
241 class SDAGSwitchLowering : public SwitchCG::SwitchLowering {
242 public:
243 SDAGSwitchLowering(SelectionDAGBuilder *sdb, FunctionLoweringInfo &funcinfo)
244 : SwitchCG::SwitchLowering(funcinfo), SDB(sdb) {}
245
246 void addSuccessorWithProb(
247 MachineBasicBlock *Src, MachineBasicBlock *Dst,
248 BranchProbability Prob = BranchProbability::getUnknown()) override {
249 SDB->addSuccessorWithProb(Src, Dst, Prob);
250 }
251
252 private:
253 SelectionDAGBuilder *SDB = nullptr;
254 };
255
256 // Data related to deferred switch lowerings. Used to construct additional
257 // Basic Blocks in SelectionDAGISel::FinishBasicBlock.
258 std::unique_ptr<SDAGSwitchLowering> SL;
259
260 /// A StackProtectorDescriptor structure used to communicate stack protector
261 /// information in between SelectBasicBlock and FinishBasicBlock.
262 StackProtectorDescriptor SPDescriptor;
263
264 // Emit PHI-node-operand constants only once even if used by multiple
265 // PHI nodes.
266 DenseMap<const Constant *, Register> ConstantsOut;
267
268 /// Information about the function as a whole.
269 FunctionLoweringInfo &FuncInfo;
270
271 /// Information about the swifterror values used throughout the function.
272 SwiftErrorValueTracking &SwiftError;
273
274 /// Garbage collection metadata for the function.
275 GCFunctionInfo *GFI = nullptr;
276
277 /// Map a landing pad to the call site indexes.
278 DenseMap<MachineBasicBlock *, SmallVector<unsigned, 4>> LPadToCallSiteMap;
279
280 /// This is set to true if a call in the current block has been translated as
281 /// a tail call. In this case, no subsequent DAG nodes should be created.
282 bool HasTailCall = false;
283
284 LLVMContext *Context = nullptr;
285
286 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
287 SwiftErrorValueTracking &swifterror, CodeGenOptLevel ol)
288 : SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), DAG(dag),
289 SL(std::make_unique<SDAGSwitchLowering>(args: this, args&: funcinfo)),
290 FuncInfo(funcinfo), SwiftError(swifterror) {}
291
292 void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC,
293 const TargetLibraryInfo *li, const TargetTransformInfo &TTI);
294
295 /// Clear out the current SelectionDAG and the associated state and prepare
296 /// this SelectionDAGBuilder object to be used for a new block. This doesn't
297 /// clear out information about additional blocks that are needed to complete
298 /// switch lowering or PHI node updating; that information is cleared out as
299 /// it is consumed.
300 void clear();
301
302 /// Clear the dangling debug information map. This function is separated from
303 /// the clear so that debug information that is dangling in a basic block can
304 /// be properly resolved in a different basic block. This allows the
305 /// SelectionDAG to resolve dangling debug information attached to PHI nodes.
306 void clearDanglingDebugInfo();
307
308 /// Return the current virtual root of the Selection DAG, flushing any
309 /// PendingLoad items. This must be done before emitting a store or any other
310 /// memory node that may need to be ordered after any prior load instructions.
311 SDValue getMemoryRoot();
312
313 /// Return the current virtual root of the Selection DAG, flushing
314 /// PendingConstrainedFP or PendingConstrainedFPStrict items if the new
315 /// exception behavior (specified by \p EB) differs from that of the pending
316 /// instructions. This must be done before emitting constrained FP operation
317 /// call.
318 SDValue getFPOperationRoot(fp::ExceptionBehavior EB);
319
320 /// Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict)
321 /// items. This must be done before emitting any call other any other node
322 /// that may need to be ordered after FP instructions due to other side
323 /// effects.
324 SDValue getRoot();
325
326 /// Similar to getRoot, but instead of flushing all the PendingLoad items,
327 /// flush all the PendingExports (and PendingConstrainedFPStrict) items.
328 /// It is necessary to do this before emitting a terminator instruction.
329 SDValue getControlRoot();
330
331 SDLoc getCurSDLoc() const {
332 return SDLoc(CurInst, SDNodeOrder);
333 }
334
335 DebugLoc getCurDebugLoc() const {
336 return CurInst ? CurInst->getDebugLoc() : DebugLoc();
337 }
338
339 void CopyValueToVirtualRegister(const Value *V, Register Reg,
340 ISD::NodeType ExtendType = ISD::ANY_EXTEND);
341
342 void visit(const Instruction &I);
343 void visitDbgInfo(const Instruction &I);
344
345 void visit(unsigned Opcode, const User &I);
346
347 /// If there was virtual register allocated for the value V emit CopyFromReg
348 /// of the specified type Ty. Return empty SDValue() otherwise.
349 SDValue getCopyFromRegs(const Value *V, Type *Ty);
350
351 /// Register a dbg_value which relies on a Value which we have not yet seen.
352 void addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
353 DILocalVariable *Var, DIExpression *Expr,
354 bool IsVariadic, DebugLoc DL, unsigned Order);
355
356 /// If we have dangling debug info that describes \p Variable, or an
357 /// overlapping part of variable considering the \p Expr, then this method
358 /// will drop that debug info as it isn't valid any longer.
359 void dropDanglingDebugInfo(const DILocalVariable *Variable,
360 const DIExpression *Expr);
361
362 /// If we saw an earlier dbg_value referring to V, generate the debug data
363 /// structures now that we've seen its definition.
364 void resolveDanglingDebugInfo(const Value *V, SDValue Val);
365
366 /// For the given dangling debuginfo record, perform last-ditch efforts to
367 /// resolve the debuginfo to something that is represented in this DAG. If
368 /// this cannot be done, produce an Undef debug value record.
369 void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI);
370
371 /// For a given list of Values, attempt to create and record a SDDbgValue in
372 /// the SelectionDAG.
373 bool handleDebugValue(ArrayRef<const Value *> Values, DILocalVariable *Var,
374 DIExpression *Expr, DebugLoc DbgLoc, unsigned Order,
375 bool IsVariadic);
376
377 /// Create a record for a kill location debug intrinsic.
378 void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr,
379 DebugLoc DbgLoc, unsigned Order);
380
381 void handleDebugDeclare(Value *Address, DILocalVariable *Variable,
382 DIExpression *Expression, DebugLoc DL);
383
384 /// Evict any dangling debug information, attempting to salvage it first.
385 void resolveOrClearDbgInfo();
386
387 SDValue getValue(const Value *V);
388
389 SDValue getNonRegisterValue(const Value *V);
390 SDValue getValueImpl(const Value *V);
391
392 void setValue(const Value *V, SDValue NewN) {
393 SDValue &N = NodeMap[V];
394 assert(!N.getNode() && "Already set a value for this node!");
395 N = NewN;
396 }
397
398 void setUnusedArgValue(const Value *V, SDValue NewN) {
399 SDValue &N = UnusedArgNodeMap[V];
400 assert(!N.getNode() && "Already set a value for this node!");
401 N = NewN;
402 }
403
404 void setValueToPoison(const Value *V, const SDLoc &dl);
405
406 bool shouldKeepJumpConditionsTogether(
407 const FunctionLoweringInfo &FuncInfo, const CondBrInst &I,
408 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
409 TargetLoweringBase::CondMergingParams Params) const;
410
411 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
412 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
413 MachineBasicBlock *SwitchBB,
414 Instruction::BinaryOps Opc, BranchProbability TProb,
415 BranchProbability FProb, bool InvertCond);
416 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
417 MachineBasicBlock *FBB,
418 MachineBasicBlock *CurBB,
419 MachineBasicBlock *SwitchBB,
420 BranchProbability TProb, BranchProbability FProb,
421 bool InvertCond);
422 bool ShouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
423 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
424 void CopyToExportRegsIfNeeded(const Value *V);
425 void ExportFromCurrentBlock(const Value *V);
426 void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall,
427 bool IsMustTailCall, const BasicBlock *EHPadBB = nullptr,
428 const TargetLowering::PtrAuthInfo *PAI = nullptr);
429
430 // Check some of the target-independent constraints for tail calls. This does
431 // not iterate over the call arguments.
432 bool canTailCall(const CallBase &CB) const;
433
434 // Lower range metadata from 0 to N to assert zext to an integer of nearest
435 // floor power of two.
436 SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I,
437 SDValue Op);
438
439 // Lower nofpclass attributes to AssertNoFPClass
440 SDValue lowerNoFPClassToAssertNoFPClass(SelectionDAG &DAG,
441 const Instruction &I, SDValue Op);
442
443 void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI,
444 const CallBase *Call, unsigned ArgIdx,
445 unsigned NumArgs, SDValue Callee,
446 Type *ReturnTy, AttributeSet RetAttrs,
447 bool IsPatchPoint);
448
449 std::pair<SDValue, SDValue>
450 lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
451 const BasicBlock *EHPadBB = nullptr);
452
453 /// When an MBB was split during scheduling, update the
454 /// references that need to refer to the last resulting block.
455 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
456
457 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes
458 /// of lowering into a STATEPOINT node.
459 struct StatepointLoweringInfo {
460 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set
461 /// of gc pointers this STATEPOINT has to relocate.
462 SmallVector<const Value *, 16> Bases;
463 SmallVector<const Value *, 16> Ptrs;
464
465 /// The set of gc.relocate calls associated with this gc.statepoint.
466 SmallVector<const GCRelocateInst *, 16> GCRelocates;
467
468 /// The full list of gc-live arguments to the gc.statepoint being lowered.
469 ArrayRef<const Use> GCLives;
470
471 /// The gc.statepoint instruction.
472 const Instruction *StatepointInstr = nullptr;
473
474 /// The list of gc transition arguments present in the gc.statepoint being
475 /// lowered.
476 ArrayRef<const Use> GCTransitionArgs;
477
478 /// The ID that the resulting STATEPOINT instruction has to report.
479 uint64_t ID = -1;
480
481 /// Information regarding the underlying call instruction.
482 TargetLowering::CallLoweringInfo CLI;
483
484 /// The deoptimization state associated with this gc.statepoint call, if
485 /// any.
486 ArrayRef<const Use> DeoptState;
487
488 /// Flags associated with the meta arguments being lowered.
489 uint64_t StatepointFlags = -1;
490
491 /// The number of patchable bytes the call needs to get lowered into.
492 unsigned NumPatchBytes = -1;
493
494 /// The exception handling unwind destination, in case this represents an
495 /// invoke of gc.statepoint.
496 const BasicBlock *EHPadBB = nullptr;
497
498 explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {}
499 };
500
501 /// Lower \p SLI into a STATEPOINT instruction.
502 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI);
503
504 // This function is responsible for the whole statepoint lowering process.
505 // It uniformly handles invoke and call statepoints.
506 void LowerStatepoint(const GCStatepointInst &I,
507 const BasicBlock *EHPadBB = nullptr);
508
509 void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee,
510 const BasicBlock *EHPadBB);
511
512 void LowerDeoptimizeCall(const CallInst *CI);
513 void LowerDeoptimizingReturn();
514
515 void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee,
516 const BasicBlock *EHPadBB,
517 bool VarArgDisallowed,
518 bool ForceVoidReturnTy);
519
520 void LowerCallSiteWithPtrAuthBundle(const CallBase &CB,
521 const BasicBlock *EHPadBB);
522
523 /// Returns the type of FrameIndex and TargetFrameIndex nodes.
524 MVT getFrameIndexTy() {
525 return DAG.getTargetLoweringInfo().getFrameIndexTy(DL: DAG.getDataLayout());
526 }
527
528private:
529 // Terminator instructions.
530 void visitRet(const ReturnInst &I);
531 void visitUncondBr(const UncondBrInst &I);
532 void visitCondBr(const CondBrInst &I);
533 void visitSwitch(const SwitchInst &I);
534 void visitIndirectBr(const IndirectBrInst &I);
535 void visitUnreachable(const UnreachableInst &I);
536 void visitCleanupRet(const CleanupReturnInst &I);
537 void visitCatchSwitch(const CatchSwitchInst &I);
538 void visitCatchRet(const CatchReturnInst &I);
539 void visitCatchPad(const CatchPadInst &I);
540 void visitCleanupPad(const CleanupPadInst &CPI);
541
542 BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
543 const MachineBasicBlock *Dst) const;
544 void addSuccessorWithProb(
545 MachineBasicBlock *Src, MachineBasicBlock *Dst,
546 BranchProbability Prob = BranchProbability::getUnknown());
547
548public:
549 void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB);
550 void visitSPDescriptorParent(StackProtectorDescriptor &SPD,
551 MachineBasicBlock *ParentBB);
552 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD);
553 void visitBitTestHeader(SwitchCG::BitTestBlock &B,
554 MachineBasicBlock *SwitchBB);
555 void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB,
556 BranchProbability BranchProbToNext, Register Reg,
557 SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB);
558 void visitJumpTable(SwitchCG::JumpTable &JT);
559 void visitJumpTableHeader(SwitchCG::JumpTable &JT,
560 SwitchCG::JumpTableHeader &JTH,
561 MachineBasicBlock *SwitchBB);
562
563private:
564 // These all get lowered before this pass.
565 void visitInvoke(const InvokeInst &I);
566 void visitCallBrLandingPad(const CallInst &I);
567 void visitResume(const ResumeInst &I);
568
569 void visitCallBr(const CallBrInst &I);
570 void visitCallBrIntrinsic(const CallBrInst &I);
571
572 void visitUnary(const User &I, unsigned Opcode);
573 void visitFNeg(const User &I) { visitUnary(I, Opcode: ISD::FNEG); }
574
575 void visitBinary(const User &I, unsigned Opcode);
576 void visitShift(const User &I, unsigned Opcode);
577 void visitAdd(const User &I) { visitBinary(I, Opcode: ISD::ADD); }
578 void visitFAdd(const User &I) { visitBinary(I, Opcode: ISD::FADD); }
579 void visitSub(const User &I) { visitBinary(I, Opcode: ISD::SUB); }
580 void visitFSub(const User &I) { visitBinary(I, Opcode: ISD::FSUB); }
581 void visitMul(const User &I) { visitBinary(I, Opcode: ISD::MUL); }
582 void visitFMul(const User &I) { visitBinary(I, Opcode: ISD::FMUL); }
583 void visitURem(const User &I) { visitBinary(I, Opcode: ISD::UREM); }
584 void visitSRem(const User &I) { visitBinary(I, Opcode: ISD::SREM); }
585 void visitFRem(const User &I) { visitBinary(I, Opcode: ISD::FREM); }
586 void visitUDiv(const User &I) { visitBinary(I, Opcode: ISD::UDIV); }
587 void visitSDiv(const User &I);
588 void visitFDiv(const User &I) { visitBinary(I, Opcode: ISD::FDIV); }
589 void visitAnd (const User &I) { visitBinary(I, Opcode: ISD::AND); }
590 void visitOr (const User &I) { visitBinary(I, Opcode: ISD::OR); }
591 void visitXor (const User &I) { visitBinary(I, Opcode: ISD::XOR); }
592 void visitShl (const User &I) { visitShift(I, Opcode: ISD::SHL); }
593 void visitLShr(const User &I) { visitShift(I, Opcode: ISD::SRL); }
594 void visitAShr(const User &I) { visitShift(I, Opcode: ISD::SRA); }
595 void visitICmp(const ICmpInst &I);
596 void visitFCmp(const FCmpInst &I);
597 // Visit the conversion instructions
598 void visitTrunc(const User &I);
599 void visitZExt(const User &I);
600 void visitSExt(const User &I);
601 void visitFPTrunc(const User &I);
602 void visitFPExt(const User &I);
603 void visitFPToUI(const User &I);
604 void visitFPToSI(const User &I);
605 void visitUIToFP(const User &I);
606 void visitSIToFP(const User &I);
607 void visitPtrToAddr(const User &I);
608 void visitPtrToInt(const User &I);
609 void visitIntToPtr(const User &I);
610 void visitBitCast(const User &I);
611 void visitAddrSpaceCast(const User &I);
612
613 void visitExtractElement(const User &I);
614 void visitInsertElement(const User &I);
615 void visitShuffleVector(const User &I);
616
617 void visitExtractValue(const ExtractValueInst &I);
618 void visitInsertValue(const InsertValueInst &I);
619 void visitLandingPad(const LandingPadInst &LP);
620
621 void visitGetElementPtr(const User &I);
622 void visitSelect(const User &I);
623
624 void visitBitInsert(const User &I);
625 void visitBitExtract(const User &I);
626
627 void visitAlloca(const AllocaInst &I);
628 void visitLoad(const LoadInst &I);
629 void visitStore(const StoreInst &I);
630 void visitMaskedLoad(const CallInst &I, bool IsExpanding = false);
631 void visitMaskedStore(const CallInst &I, bool IsCompressing = false);
632 void visitMaskedGather(const CallInst &I);
633 void visitMaskedScatter(const CallInst &I);
634 void visitSpeculativeLoad(const CallInst &I);
635 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
636 void visitAtomicRMW(const AtomicRMWInst &I);
637 void visitFence(const FenceInst &I);
638 void visitPHI(const PHINode &I);
639 void visitCall(const CallInst &I);
640 bool visitMemCmpBCmpCall(const CallInst &I);
641 bool visitMemCCpyCall(const CallInst &I);
642 bool visitMemPCpyCall(const CallInst &I);
643 bool visitMemChrCall(const CallInst &I);
644 bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
645 bool visitStrCmpCall(const CallInst &I);
646 bool visitStrLenCall(const CallInst &I);
647 bool visitStrNLenCall(const CallInst &I);
648 bool visitStrstrCall(const CallInst &I);
649 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
650 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode);
651 void visitAtomicLoad(const LoadInst &I);
652 void visitAtomicStore(const StoreInst &I);
653 void visitLoadFromSwiftError(const LoadInst &I);
654 void visitStoreToSwiftError(const StoreInst &I);
655 void visitFreeze(const FreezeInst &I);
656
657 void visitInlineAsm(const CallBase &Call,
658 const BasicBlock *EHPadBB = nullptr);
659
660 bool visitEntryValueDbgValue(ArrayRef<const Value *> Values,
661 DILocalVariable *Variable, DIExpression *Expr,
662 DebugLoc DbgLoc);
663 void visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
664 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
665 void visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI);
666 void visitConvergenceControl(const CallInst &I, unsigned Intrinsic);
667 void visitVectorHistogram(const CallInst &I, unsigned IntrinsicID);
668 void visitVectorExtractLastActive(const CallInst &I, unsigned Intrinsic);
669 void visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
670 const SmallVectorImpl<SDValue> &OpValues);
671 void visitVPLoadFF(const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
672 const SmallVectorImpl<SDValue> &OpValues);
673 void visitVPStore(const VPIntrinsic &VPIntrin,
674 const SmallVectorImpl<SDValue> &OpValues);
675 void visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
676 const SmallVectorImpl<SDValue> &OpValues);
677 void visitVPScatter(const VPIntrinsic &VPIntrin,
678 const SmallVectorImpl<SDValue> &OpValues);
679 void visitVPStridedLoad(const VPIntrinsic &VPIntrin, EVT VT,
680 const SmallVectorImpl<SDValue> &OpValues);
681 void visitVPStridedStore(const VPIntrinsic &VPIntrin,
682 const SmallVectorImpl<SDValue> &OpValues);
683 void visitVectorPredicationIntrinsic(const VPIntrinsic &VPIntrin);
684
685 void visitVAStart(const CallInst &I);
686 void visitVAArg(const VAArgInst &I);
687 void visitVAEnd(const CallInst &I);
688 void visitVACopy(const CallInst &I);
689 void visitStackmap(const CallInst &I);
690 void visitPatchpoint(const CallBase &CB, const BasicBlock *EHPadBB = nullptr);
691
692 // These two are implemented in StatepointLowering.cpp
693 void visitGCRelocate(const GCRelocateInst &Relocate);
694 void visitGCResult(const GCResultInst &I);
695
696 void visitVectorReduce(const CallInst &I, unsigned Intrinsic);
697 void visitVectorReverse(const CallInst &I);
698 void visitVectorSplice(const CallInst &I);
699 void visitVectorInterleave(const CallInst &I, unsigned Factor);
700 void visitVectorDeinterleave(const CallInst &I, unsigned Factor);
701 void visitStepVector(const CallInst &I);
702
703 void visitUserOp1(const Instruction &I) {
704 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
705 }
706 void visitUserOp2(const Instruction &I) {
707 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
708 }
709
710 void processIntegerCallValue(const Instruction &I,
711 SDValue Value, bool IsSigned);
712
713 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
714
715 void emitInlineAsmError(const CallBase &Call, const Twine &Message);
716
717 /// An enum that states to emit func argument dbg value the kind of intrinsic
718 /// it originally had. This controls the internal behavior of
719 /// EmitFuncArgumentDbgValue.
720 enum class FuncArgumentDbgValueKind {
721 Value, // This was originally a llvm.dbg.value.
722 Declare, // This was originally a llvm.dbg.declare.
723 };
724
725 /// If V is an function argument then create corresponding DBG_VALUE machine
726 /// instruction for it now. At the end of instruction selection, they will be
727 /// inserted to the entry BB.
728 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable,
729 DIExpression *Expr, DILocation *DL,
730 FuncArgumentDbgValueKind Kind,
731 const SDValue &N);
732
733 /// Return the next block after MBB, or nullptr if there is none.
734 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB);
735
736 /// Update the DAG and DAG builder with the relevant information after
737 /// a new root node has been created which could be a tail call.
738 void updateDAGForMaybeTailCall(SDValue MaybeTC);
739
740 /// Return the appropriate SDDbgValue based on N.
741 SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable,
742 DIExpression *Expr, const DebugLoc &dl,
743 unsigned DbgSDNodeOrder);
744
745public:
746 SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB,
747 MCSymbol *&BeginLabel);
748
749private:
750 SDValue lowerEndEH(SDValue Chain, const InvokeInst *II,
751 const BasicBlock *EHPadBB, MCSymbol *BeginLabel);
752
753 std::pair<bool, bool> getTargetIntrinsicCallProperties(const CallBase &I);
754 SmallVector<SDValue, 8> getTargetIntrinsicOperands(
755 const CallBase &I, bool HasChain, bool OnlyLoad,
756 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo = nullptr);
757 SDVTList getTargetIntrinsicVTList(const CallBase &I, bool HasChain);
758 SDValue getTargetNonMemIntrinsicNode(const Type &IntrinsicVT, bool HasChain,
759 ArrayRef<SDValue> Ops,
760 const SDVTList &VTs);
761 SDValue handleTargetIntrinsicRet(const CallBase &I, bool HasChain,
762 bool OnlyLoad, SDValue Result);
763};
764
765/// This struct represents the registers (physical or virtual)
766/// that a particular set of values is assigned, and the type information about
767/// the value. The most common situation is to represent one value at a time,
768/// but struct or array values are handled element-wise as multiple values. The
769/// splitting of aggregates is performed recursively, so that we never have
770/// aggregate-typed registers. The values at this point do not necessarily have
771/// legal types, so each value may require one or more registers of some legal
772/// type.
773///
774struct RegsForValue {
775 /// The value types of the values, which may not be legal, and
776 /// may need be promoted or synthesized from one or more registers.
777 SmallVector<EVT, 4> ValueVTs;
778
779 /// The value types of the registers. This is the same size as ValueVTs and it
780 /// records, for each value, what the type of the assigned register or
781 /// registers are. (Individual values are never synthesized from more than one
782 /// type of register.)
783 ///
784 /// With virtual registers, the contents of RegVTs is redundant with TLI's
785 /// getRegisterType member function, however when with physical registers
786 /// it is necessary to have a separate record of the types.
787 SmallVector<MVT, 4> RegVTs;
788
789 /// This list holds the registers assigned to the values.
790 /// Each legal or promoted value requires one register, and each
791 /// expanded value requires multiple registers.
792 SmallVector<Register, 4> Regs;
793
794 /// This list holds the number of registers for each value.
795 SmallVector<unsigned, 4> RegCount;
796
797 /// Records if this value needs to be treated in an ABI dependant manner,
798 /// different to normal type legalization.
799 std::optional<CallingConv::ID> CallConv;
800
801 RegsForValue() = default;
802 RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt, EVT valuevt,
803 std::optional<CallingConv::ID> CC = std::nullopt);
804 RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
805 const DataLayout &DL, Register Reg, Type *Ty,
806 std::optional<CallingConv::ID> CC);
807
808 bool isABIMangled() const { return CallConv.has_value(); }
809
810 /// Emit a series of CopyFromReg nodes that copies from this value and returns
811 /// the result as a ValueVTs value. This uses Chain/Flag as the input and
812 /// updates them for the output Chain/Flag. If the Flag pointer is NULL, no
813 /// flag is used.
814 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
815 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
816 const Value *V = nullptr) const;
817
818 /// Emit a series of CopyToReg nodes that copies the specified value into the
819 /// registers specified by this object. This uses Chain/Flag as the input and
820 /// updates them for the output Chain/Flag. If the Flag pointer is nullptr, no
821 /// flag is used. If V is not nullptr, then it is used in printing better
822 /// diagnostic messages on error.
823 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl,
824 SDValue &Chain, SDValue *Glue, const Value *V = nullptr,
825 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
826
827 /// Add this value to the specified inlineasm node operand list. This adds the
828 /// code marker, matching input operand index (if applicable), and includes
829 /// the number of values added into it.
830 void AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
831 unsigned MatchingIdx, const SDLoc &dl,
832 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
833
834 /// Check if the total RegCount is greater than one.
835 bool occupiesMultipleRegs() const {
836 return std::accumulate(first: RegCount.begin(), last: RegCount.end(), init: 0) > 1;
837 }
838
839 /// Return a list of registers and their sizes.
840 SmallVector<std::pair<Register, TypeSize>, 4> getRegsAndSizes() const;
841};
842
843} // end namespace llvm
844
845#endif // LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
846