LLVM 17.0.0git
SelectionDAGBuilder.h
Go to the documentation of this file.
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"
28#include "llvm/IR/DebugLoc.h"
29#include "llvm/IR/Instruction.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 BranchInst;
50class CallInst;
51class CallBrInst;
52class CatchPadInst;
53class CatchReturnInst;
54class CatchSwitchInst;
55class CleanupPadInst;
56class CleanupReturnInst;
57class Constant;
58class ConstrainedFPIntrinsic;
59class DbgValueInst;
60class DataLayout;
61class DIExpression;
62class DILocalVariable;
63class DILocation;
64class FenceInst;
65class FunctionLoweringInfo;
66class GCFunctionInfo;
67class GCRelocateInst;
68class GCResultInst;
69class GCStatepointInst;
70class IndirectBrInst;
71class InvokeInst;
72class LandingPadInst;
73class LLVMContext;
74class LoadInst;
75class MachineBasicBlock;
76class PHINode;
77class ResumeInst;
78class ReturnInst;
79class SDDbgValue;
80class SelectionDAG;
81class StoreInst;
82class SwiftErrorValueTracking;
83class SwitchInst;
84class TargetLibraryInfo;
85class TargetMachine;
86class Type;
87class VAArgInst;
88class UnreachableInst;
89class Use;
90class User;
91class Value;
92
93//===----------------------------------------------------------------------===//
94/// SelectionDAGBuilder - This is the common target-independent lowering
95/// implementation that is parameterized by a TargetLowering object.
96///
98 /// The current instruction being visited.
99 const Instruction *CurInst = nullptr;
100
102
103 /// Maps argument value for unused arguments. This is used
104 /// to preserve debug information for incoming arguments.
105 DenseMap<const Value*, SDValue> UnusedArgNodeMap;
106
107 /// Helper type for DanglingDebugInfoMap.
108 class DanglingDebugInfo {
109 using DbgValTy = const DbgValueInst *;
110 using VarLocTy = const VarLocInfo *;
112 unsigned SDNodeOrder = 0;
113
114 public:
115 DanglingDebugInfo() = default;
116 DanglingDebugInfo(const DbgValueInst *DI, unsigned SDNO)
117 : Info(DI), SDNodeOrder(SDNO) {}
118 DanglingDebugInfo(const VarLocInfo *VarLoc, unsigned SDNO)
119 : Info(VarLoc), SDNodeOrder(SDNO) {}
120
121 DILocalVariable *getVariable(const FunctionVarLocs *Locs) const {
122 if (Info.is<VarLocTy>())
123 return Locs->getDILocalVariable(Info.get<VarLocTy>()->VariableID);
124 return Info.get<DbgValTy>()->getVariable();
125 }
126 DIExpression *getExpression() const {
127 if (Info.is<VarLocTy>())
128 return Info.get<VarLocTy>()->Expr;
129 return Info.get<DbgValTy>()->getExpression();
130 }
131 Value *getVariableLocationOp(unsigned Idx) const {
132 assert(Idx == 0 && "Dangling variadic debug values not supported yet");
133 if (Info.is<VarLocTy>())
134 return Info.get<VarLocTy>()->Values.getVariableLocationOp(Idx);
135 return Info.get<DbgValTy>()->getVariableLocationOp(Idx);
136 }
137 DebugLoc getDebugLoc() const {
138 if (Info.is<VarLocTy>())
139 return Info.get<VarLocTy>()->DL;
140 return Info.get<DbgValTy>()->getDebugLoc();
141 }
142 unsigned getSDNodeOrder() const { return SDNodeOrder; }
143
144 /// Helper for printing DanglingDebugInfo. This hoop-jumping is to
145 /// accommodate the fact that an argument is required for getVariable.
146 /// Call SelectionDAGBuilder::printDDI instead of using directly.
147 struct Print {
148 Print(const DanglingDebugInfo &DDI, const FunctionVarLocs *VarLocs)
149 : DDI(DDI), VarLocs(VarLocs) {}
150 const DanglingDebugInfo &DDI;
154 OS << "DDI(var=" << *P.DDI.getVariable(P.VarLocs)
155 << ", val= " << *P.DDI.getVariableLocationOp(0)
156 << ", expr=" << *P.DDI.getExpression()
157 << ", order=" << P.DDI.getSDNodeOrder()
158 << ", loc=" << P.DDI.getDebugLoc() << ")";
159 return OS;
160 }
161 };
162 };
163
164 /// Returns an object that defines `raw_ostream &operator<<` for printing.
165 /// Usage example:
166 //// errs() << printDDI(MyDanglingInfo) << " is dangling\n";
167 DanglingDebugInfo::Print printDDI(const DanglingDebugInfo &DDI) {
168 return DanglingDebugInfo::Print(DDI, DAG.getFunctionVarLocs());
169 }
170
171 /// Helper type for DanglingDebugInfoMap.
172 typedef std::vector<DanglingDebugInfo> DanglingDebugInfoVector;
173
174 /// Keeps track of dbg_values for which we have not yet seen the referent.
175 /// We defer handling these until we do see it.
176 MapVector<const Value*, DanglingDebugInfoVector> DanglingDebugInfoMap;
177
178 /// Cache the module flag for whether we should use debug-info assignment
179 /// tracking.
180 bool AssignmentTrackingEnabled = false;
181
182public:
183 /// Loads are not emitted to the program immediately. We bunch them up and
184 /// then emit token factor nodes when possible. This allows us to get simple
185 /// disambiguation between loads without worrying about alias analysis.
187
188 /// State used while lowering a statepoint sequence (gc_statepoint,
189 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details.
191
192private:
193 /// CopyToReg nodes that copy values to virtual registers for export to other
194 /// blocks need to be emitted before any terminator instruction, but they have
195 /// no other ordering requirements. We bunch them up and the emit a single
196 /// tokenfactor for them just before terminator instructions.
197 SmallVector<SDValue, 8> PendingExports;
198
199 /// Similar to loads, nodes corresponding to constrained FP intrinsics are
200 /// bunched up and emitted when necessary. These can be moved across each
201 /// other and any (normal) memory operation (load or store), but not across
202 /// calls or instructions having unspecified side effects. As a special
203 /// case, constrained FP intrinsics using fpexcept.strict may not be deleted
204 /// even if otherwise unused, so they need to be chained before any
205 /// terminator instruction (like PendingExports). We track the latter
206 /// set of nodes in a separate list.
207 SmallVector<SDValue, 8> PendingConstrainedFP;
208 SmallVector<SDValue, 8> PendingConstrainedFPStrict;
209
210 /// Update root to include all chains from the Pending list.
211 SDValue updateRoot(SmallVectorImpl<SDValue> &Pending);
212
213 /// A unique monotonically increasing number used to order the SDNodes we
214 /// create.
215 unsigned SDNodeOrder;
216
217 /// Determine the rank by weight of CC in [First,Last]. If CC has more weight
218 /// than each cluster in the range, its rank is 0.
219 unsigned caseClusterRank(const SwitchCG::CaseCluster &CC,
222
223 /// Emit comparison and split W into two subtrees.
224 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
226 MachineBasicBlock *SwitchMBB);
227
228 /// Lower W.
229 void lowerWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
230 MachineBasicBlock *SwitchMBB,
231 MachineBasicBlock *DefaultMBB);
232
233 /// Peel the top probability case if it exceeds the threshold
235 peelDominantCaseCluster(const SwitchInst &SI,
237 BranchProbability &PeeledCaseProb);
238
239private:
240 const TargetMachine &TM;
241
242public:
243 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
244 /// nodes without a corresponding SDNode.
245 static const unsigned LowestSDNodeOrder = 1;
246
248 AAResults *AA = nullptr;
249 AssumptionCache *AC = nullptr;
251
253 public:
255 : SwitchCG::SwitchLowering(funcinfo), SDB(sdb) {}
256
260 SDB->addSuccessorWithProb(Src, Dst, Prob);
261 }
262
263 private:
265 };
266
267 // Data related to deferred switch lowerings. Used to construct additional
268 // Basic Blocks in SelectionDAGISel::FinishBasicBlock.
269 std::unique_ptr<SDAGSwitchLowering> SL;
270
271 /// A StackProtectorDescriptor structure used to communicate stack protector
272 /// information in between SelectBasicBlock and FinishBasicBlock.
274
275 // Emit PHI-node-operand constants only once even if used by multiple
276 // PHI nodes.
278
279 /// Information about the function as a whole.
281
282 /// Information about the swifterror values used throughout the function.
284
285 /// Garbage collection metadata for the function.
287
288 /// Map a landing pad to the call site indexes.
290
291 /// This is set to true if a call in the current block has been translated as
292 /// a tail call. In this case, no subsequent DAG nodes should be created.
293 bool HasTailCall = false;
294
296
299 : SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), DAG(dag),
300 SL(std::make_unique<SDAGSwitchLowering>(this, funcinfo)), FuncInfo(funcinfo),
301 SwiftError(swifterror) {}
302
304 const TargetLibraryInfo *li);
305
306 /// Clear out the current SelectionDAG and the associated state and prepare
307 /// this SelectionDAGBuilder object to be used for a new block. This doesn't
308 /// clear out information about additional blocks that are needed to complete
309 /// switch lowering or PHI node updating; that information is cleared out as
310 /// it is consumed.
311 void clear();
312
313 /// Clear the dangling debug information map. This function is separated from
314 /// the clear so that debug information that is dangling in a basic block can
315 /// be properly resolved in a different basic block. This allows the
316 /// SelectionDAG to resolve dangling debug information attached to PHI nodes.
318
319 /// Return the current virtual root of the Selection DAG, flushing any
320 /// PendingLoad items. This must be done before emitting a store or any other
321 /// memory node that may need to be ordered after any prior load instructions.
323
324 /// Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict)
325 /// items. This must be done before emitting any call other any other node
326 /// that may need to be ordered after FP instructions due to other side
327 /// effects.
329
330 /// Similar to getRoot, but instead of flushing all the PendingLoad items,
331 /// flush all the PendingExports (and PendingConstrainedFPStrict) items.
332 /// It is necessary to do this before emitting a terminator instruction.
334
336 return SDLoc(CurInst, SDNodeOrder);
337 }
338
340 return CurInst ? CurInst->getDebugLoc() : DebugLoc();
341 }
342
343 void CopyValueToVirtualRegister(const Value *V, unsigned Reg,
344 ISD::NodeType ExtendType = ISD::ANY_EXTEND);
345
346 void visit(const Instruction &I);
347
348 void visit(unsigned Opcode, const User &I);
349
350 /// If there was virtual register allocated for the value V emit CopyFromReg
351 /// of the specified type Ty. Return empty SDValue() otherwise.
352 SDValue getCopyFromRegs(const Value *V, Type *Ty);
353
354 /// Register a dbg_value which relies on a Value which we have not yet seen.
355 void addDanglingDebugInfo(const DbgValueInst *DI, unsigned Order);
356 void addDanglingDebugInfo(const VarLocInfo *VarLoc, unsigned Order);
357
358 /// If we have dangling debug info that describes \p Variable, or an
359 /// overlapping part of variable considering the \p Expr, then this method
360 /// will drop that debug info as it isn't valid any longer.
361 void dropDanglingDebugInfo(const DILocalVariable *Variable,
362 const DIExpression *Expr);
363
364 /// If we saw an earlier dbg_value referring to V, generate the debug data
365 /// structures now that we've seen its definition.
366 void resolveDanglingDebugInfo(const Value *V, SDValue Val);
367
368 /// For the given dangling debuginfo record, perform last-ditch efforts to
369 /// resolve the debuginfo to something that is represented in this DAG. If
370 /// this cannot be done, produce an Undef debug value record.
371 void salvageUnresolvedDbgValue(DanglingDebugInfo &DDI);
372
373 /// For a given list of Values, attempt to create and record a SDDbgValue in
374 /// the SelectionDAG.
376 DIExpression *Expr, DebugLoc DbgLoc, unsigned Order,
377 bool IsVariadic);
378
379 /// Evict any dangling debug information, attempting to salvage it first.
381
382 SDValue getValue(const Value *V);
383
385 SDValue getValueImpl(const Value *V);
386
387 void setValue(const Value *V, SDValue NewN) {
388 SDValue &N = NodeMap[V];
389 assert(!N.getNode() && "Already set a value for this node!");
390 N = NewN;
391 }
392
393 void setUnusedArgValue(const Value *V, SDValue NewN) {
394 SDValue &N = UnusedArgNodeMap[V];
395 assert(!N.getNode() && "Already set a value for this node!");
396 N = NewN;
397 }
398
401 MachineBasicBlock *SwitchBB,
403 BranchProbability FProb, bool InvertCond);
406 MachineBasicBlock *CurBB,
407 MachineBasicBlock *SwitchBB,
409 bool InvertCond);
410 bool ShouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
411 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
412 void CopyToExportRegsIfNeeded(const Value *V);
413 void ExportFromCurrentBlock(const Value *V);
414 void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall,
415 bool IsMustTailCall, const BasicBlock *EHPadBB = nullptr);
416
417 // Lower range metadata from 0 to N to assert zext to an integer of nearest
418 // floor power of two.
420 SDValue Op);
421
423 const CallBase *Call, unsigned ArgIdx,
424 unsigned NumArgs, SDValue Callee,
425 Type *ReturnTy, bool IsPatchPoint);
426
427 std::pair<SDValue, SDValue>
429 const BasicBlock *EHPadBB = nullptr);
430
431 /// When an MBB was split during scheduling, update the
432 /// references that need to refer to the last resulting block.
434
435 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes
436 /// of lowering into a STATEPOINT node.
438 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set
439 /// of gc pointers this STATEPOINT has to relocate.
442
443 /// The set of gc.relocate calls associated with this gc.statepoint.
445
446 /// The full list of gc arguments to the gc.statepoint being lowered.
448
449 /// The gc.statepoint instruction.
450 const Instruction *StatepointInstr = nullptr;
451
452 /// The list of gc transition arguments present in the gc.statepoint being
453 /// lowered.
455
456 /// The ID that the resulting STATEPOINT instruction has to report.
457 unsigned ID = -1;
458
459 /// Information regarding the underlying call instruction.
461
462 /// The deoptimization state associated with this gc.statepoint call, if
463 /// any.
465
466 /// Flags associated with the meta arguments being lowered.
468
469 /// The number of patchable bytes the call needs to get lowered into.
470 unsigned NumPatchBytes = -1;
471
472 /// The exception handling unwind destination, in case this represents an
473 /// invoke of gc.statepoint.
474 const BasicBlock *EHPadBB = nullptr;
475
477 };
478
479 /// Lower \p SLI into a STATEPOINT instruction.
480 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI);
481
482 // This function is responsible for the whole statepoint lowering process.
483 // It uniformly handles invoke and call statepoints.
485 const BasicBlock *EHPadBB = nullptr);
486
488 const BasicBlock *EHPadBB);
489
490 void LowerDeoptimizeCall(const CallInst *CI);
492
494 const BasicBlock *EHPadBB,
495 bool VarArgDisallowed,
496 bool ForceVoidReturnTy);
497
498 /// Returns the type of FrameIndex and TargetFrameIndex nodes.
501 }
502
503private:
504 // Terminator instructions.
505 void visitRet(const ReturnInst &I);
506 void visitBr(const BranchInst &I);
507 void visitSwitch(const SwitchInst &I);
508 void visitIndirectBr(const IndirectBrInst &I);
509 void visitUnreachable(const UnreachableInst &I);
510 void visitCleanupRet(const CleanupReturnInst &I);
511 void visitCatchSwitch(const CatchSwitchInst &I);
512 void visitCatchRet(const CatchReturnInst &I);
513 void visitCatchPad(const CatchPadInst &I);
514 void visitCleanupPad(const CleanupPadInst &CPI);
515
516 BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
517 const MachineBasicBlock *Dst) const;
518 void addSuccessorWithProb(
521
522public:
525 MachineBasicBlock *ParentBB);
528 MachineBasicBlock *SwitchBB);
530 BranchProbability BranchProbToNext, unsigned Reg,
535 MachineBasicBlock *SwitchBB);
536
537private:
538 // These all get lowered before this pass.
539 void visitInvoke(const InvokeInst &I);
540 void visitCallBr(const CallBrInst &I);
541 void visitCallBrLandingPad(const CallInst &I);
542 void visitResume(const ResumeInst &I);
543
544 void visitUnary(const User &I, unsigned Opcode);
545 void visitFNeg(const User &I) { visitUnary(I, ISD::FNEG); }
546
547 void visitBinary(const User &I, unsigned Opcode);
548 void visitShift(const User &I, unsigned Opcode);
549 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
550 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
551 void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
552 void visitFSub(const User &I) { visitBinary(I, ISD::FSUB); }
553 void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
554 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
555 void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
556 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
557 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
558 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
559 void visitSDiv(const User &I);
560 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
561 void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
562 void visitOr (const User &I) { visitBinary(I, ISD::OR); }
563 void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
564 void visitShl (const User &I) { visitShift(I, ISD::SHL); }
565 void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
566 void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
567 void visitICmp(const User &I);
568 void visitFCmp(const User &I);
569 // Visit the conversion instructions
570 void visitTrunc(const User &I);
571 void visitZExt(const User &I);
572 void visitSExt(const User &I);
573 void visitFPTrunc(const User &I);
574 void visitFPExt(const User &I);
575 void visitFPToUI(const User &I);
576 void visitFPToSI(const User &I);
577 void visitUIToFP(const User &I);
578 void visitSIToFP(const User &I);
579 void visitPtrToInt(const User &I);
580 void visitIntToPtr(const User &I);
581 void visitBitCast(const User &I);
582 void visitAddrSpaceCast(const User &I);
583
584 void visitExtractElement(const User &I);
585 void visitInsertElement(const User &I);
586 void visitShuffleVector(const User &I);
587
588 void visitExtractValue(const ExtractValueInst &I);
589 void visitInsertValue(const InsertValueInst &I);
590 void visitLandingPad(const LandingPadInst &LP);
591
592 void visitGetElementPtr(const User &I);
593 void visitSelect(const User &I);
594
595 void visitAlloca(const AllocaInst &I);
596 void visitLoad(const LoadInst &I);
597 void visitStore(const StoreInst &I);
598 void visitMaskedLoad(const CallInst &I, bool IsExpanding = false);
599 void visitMaskedStore(const CallInst &I, bool IsCompressing = false);
600 void visitMaskedGather(const CallInst &I);
601 void visitMaskedScatter(const CallInst &I);
602 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
603 void visitAtomicRMW(const AtomicRMWInst &I);
604 void visitFence(const FenceInst &I);
605 void visitPHI(const PHINode &I);
606 void visitCall(const CallInst &I);
607 bool visitMemCmpBCmpCall(const CallInst &I);
608 bool visitMemPCpyCall(const CallInst &I);
609 bool visitMemChrCall(const CallInst &I);
610 bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
611 bool visitStrCmpCall(const CallInst &I);
612 bool visitStrLenCall(const CallInst &I);
613 bool visitStrNLenCall(const CallInst &I);
614 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
615 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode);
616 void visitAtomicLoad(const LoadInst &I);
617 void visitAtomicStore(const StoreInst &I);
618 void visitLoadFromSwiftError(const LoadInst &I);
619 void visitStoreToSwiftError(const StoreInst &I);
620 void visitFreeze(const FreezeInst &I);
621
622 void visitInlineAsm(const CallBase &Call,
623 const BasicBlock *EHPadBB = nullptr);
624 void visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
625 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
626 void visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI);
627 void visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
628 SmallVector<SDValue, 7> &OpValues);
629 void visitVPStore(const VPIntrinsic &VPIntrin,
630 SmallVector<SDValue, 7> &OpValues);
631 void visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
632 SmallVector<SDValue, 7> &OpValues);
633 void visitVPScatter(const VPIntrinsic &VPIntrin,
634 SmallVector<SDValue, 7> &OpValues);
635 void visitVPStridedLoad(const VPIntrinsic &VPIntrin, EVT VT,
636 SmallVectorImpl<SDValue> &OpValues);
637 void visitVPStridedStore(const VPIntrinsic &VPIntrin,
638 SmallVectorImpl<SDValue> &OpValues);
639 void visitVPCmp(const VPCmpIntrinsic &VPIntrin);
640 void visitVectorPredicationIntrinsic(const VPIntrinsic &VPIntrin);
641
642 void visitVAStart(const CallInst &I);
643 void visitVAArg(const VAArgInst &I);
644 void visitVAEnd(const CallInst &I);
645 void visitVACopy(const CallInst &I);
646 void visitStackmap(const CallInst &I);
647 void visitPatchpoint(const CallBase &CB, const BasicBlock *EHPadBB = nullptr);
648
649 // These two are implemented in StatepointLowering.cpp
650 void visitGCRelocate(const GCRelocateInst &Relocate);
651 void visitGCResult(const GCResultInst &I);
652
653 void visitVectorReduce(const CallInst &I, unsigned Intrinsic);
654 void visitVectorReverse(const CallInst &I);
655 void visitVectorSplice(const CallInst &I);
656 void visitVectorInterleave(const CallInst &I);
657 void visitVectorDeinterleave(const CallInst &I);
658 void visitStepVector(const CallInst &I);
659
660 void visitUserOp1(const Instruction &I) {
661 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
662 }
663 void visitUserOp2(const Instruction &I) {
664 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
665 }
666
667 void processIntegerCallValue(const Instruction &I,
668 SDValue Value, bool IsSigned);
669
670 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
671
672 void emitInlineAsmError(const CallBase &Call, const Twine &Message);
673
674 /// An enum that states to emit func argument dbg value the kind of intrinsic
675 /// it originally had. This controls the internal behavior of
676 /// EmitFuncArgumentDbgValue.
677 enum class FuncArgumentDbgValueKind {
678 Value, // This was originally a llvm.dbg.value.
679 Declare, // This was originally a llvm.dbg.declare.
680 };
681
682 /// If V is an function argument then create corresponding DBG_VALUE machine
683 /// instruction for it now. At the end of instruction selection, they will be
684 /// inserted to the entry BB.
685 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable,
686 DIExpression *Expr, DILocation *DL,
687 FuncArgumentDbgValueKind Kind,
688 const SDValue &N);
689
690 /// Return the next block after MBB, or nullptr if there is none.
691 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB);
692
693 /// Update the DAG and DAG builder with the relevant information after
694 /// a new root node has been created which could be a tail call.
695 void updateDAGForMaybeTailCall(SDValue MaybeTC);
696
697 /// Return the appropriate SDDbgValue based on N.
698 SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable,
699 DIExpression *Expr, const DebugLoc &dl,
700 unsigned DbgSDNodeOrder);
701
702 /// Lowers CallInst to an external symbol.
703 void lowerCallToExternalSymbol(const CallInst &I, const char *FunctionName);
704
705 SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB,
706 MCSymbol *&BeginLabel);
707 SDValue lowerEndEH(SDValue Chain, const InvokeInst *II,
708 const BasicBlock *EHPadBB, MCSymbol *BeginLabel);
709};
710
711/// This struct represents the registers (physical or virtual)
712/// that a particular set of values is assigned, and the type information about
713/// the value. The most common situation is to represent one value at a time,
714/// but struct or array values are handled element-wise as multiple values. The
715/// splitting of aggregates is performed recursively, so that we never have
716/// aggregate-typed registers. The values at this point do not necessarily have
717/// legal types, so each value may require one or more registers of some legal
718/// type.
719///
721 /// The value types of the values, which may not be legal, and
722 /// may need be promoted or synthesized from one or more registers.
724
725 /// The value types of the registers. This is the same size as ValueVTs and it
726 /// records, for each value, what the type of the assigned register or
727 /// registers are. (Individual values are never synthesized from more than one
728 /// type of register.)
729 ///
730 /// With virtual registers, the contents of RegVTs is redundant with TLI's
731 /// getRegisterType member function, however when with physical registers
732 /// it is necessary to have a separate record of the types.
734
735 /// This list holds the registers assigned to the values.
736 /// Each legal or promoted value requires one register, and each
737 /// expanded value requires multiple registers.
739
740 /// This list holds the number of registers for each value.
742
743 /// Records if this value needs to be treated in an ABI dependant manner,
744 /// different to normal type legalization.
745 std::optional<CallingConv::ID> CallConv;
746
747 RegsForValue() = default;
748 RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt, EVT valuevt,
749 std::optional<CallingConv::ID> CC = std::nullopt);
750 RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
751 const DataLayout &DL, unsigned Reg, Type *Ty,
752 std::optional<CallingConv::ID> CC);
753
754 bool isABIMangled() const { return CallConv.has_value(); }
755
756 /// Add the specified values to this one.
757 void append(const RegsForValue &RHS) {
758 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
759 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
760 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
761 RegCount.push_back(RHS.Regs.size());
762 }
763
764 /// Emit a series of CopyFromReg nodes that copies from this value and returns
765 /// the result as a ValueVTs value. This uses Chain/Flag as the input and
766 /// updates them for the output Chain/Flag. If the Flag pointer is NULL, no
767 /// flag is used.
769 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
770 const Value *V = nullptr) const;
771
772 /// Emit a series of CopyToReg nodes that copies the specified value into the
773 /// registers specified by this object. This uses Chain/Flag as the input and
774 /// updates them for the output Chain/Flag. If the Flag pointer is nullptr, no
775 /// flag is used. If V is not nullptr, then it is used in printing better
776 /// diagnostic messages on error.
777 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl,
778 SDValue &Chain, SDValue *Flag, const Value *V = nullptr,
779 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
780
781 /// Add this value to the specified inlineasm node operand list. This adds the
782 /// code marker, matching input operand index (if applicable), and includes
783 /// the number of values added into it.
784 void AddInlineAsmOperands(unsigned Code, bool HasMatching,
785 unsigned MatchingIdx, const SDLoc &dl,
786 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
787
788 /// Check if the total RegCount is greater than one.
789 bool occupiesMultipleRegs() const {
790 return std::accumulate(RegCount.begin(), RegCount.end(), 0) > 1;
791 }
792
793 /// Return a list of registers and their sizes.
795};
796
797} // end namespace llvm
798
799#endif // LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
amdgpu Simplify well known AMD library false FunctionCallee Callee
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
RelocType Type
Definition: COFFYAML.cpp:390
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned Reg
This file implements a map that provides insertion order iteration.
typename CallsiteContextGraph< DerivedCCG, FuncTy, CallTy >::FuncInfo FuncInfo
#define P(N)
const char LLVMTargetMachineRef TM
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallVector class.
This file describes how to lower LLVM code to machine code.
Value * RHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
Conditional or Unconditional Branch instruction.
static BranchProbability getUnknown()
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1186
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
DWARF expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
This represents the llvm.dbg.value instruction.
A debug info location.
Definition: DebugLoc.h:33
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Data structure describing the variable locations in a function.
DILocalVariable * getDILocalVariable(const VarLocInfo *Loc) const
Return the DILocalVariable for the location definition represented by ID.
Garbage collection metadata for a single function.
Definition: GCMetadata.h:77
Represents a gc.statepoint intrinsic call.
Definition: Statepoint.h:61
Indirect Branch Instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:358
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Machine Value Type.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:118
Resume the propagation of an exception.
Return a value (possibly void), from a function.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDAGSwitchLowering(SelectionDAGBuilder *sdb, FunctionLoweringInfo &funcinfo)
void addSuccessorWithProb(MachineBasicBlock *Src, MachineBasicBlock *Dst, BranchProbability Prob=BranchProbability::getUnknown()) override
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
void clearDanglingDebugInfo()
Clear the dangling debug information map.
StackProtectorDescriptor SPDescriptor
A StackProtectorDescriptor structure used to communicate stack protector information in between Selec...
SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, SwiftErrorValueTracking &swifterror, CodeGenOpt::Level ol)
void clear()
Clear out the current SelectionDAG and the associated state and prepare this SelectionDAGBuilder obje...
MVT getFrameIndexTy()
Returns the type of FrameIndex and TargetFrameIndex nodes.
void visitBitTestHeader(SwitchCG::BitTestBlock &B, MachineBasicBlock *SwitchBB)
visitBitTestHeader - This function emits necessary code to produce value suitable for "bit tests"
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
std::unique_ptr< SDAGSwitchLowering > SL
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
bool HasTailCall
This is set to true if a call in the current block has been translated as a tail call.
bool ShouldEmitAsBranches(const std::vector< SwitchCG::CaseBlock > &Cases)
If the set of cases should be emitted as a series of branches, return true.
void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
EmitBranchForMergedCondition - Helper method for FindMergedConditions.
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
SwiftErrorValueTracking & SwiftError
Information about the swifterror values used throughout the function.
SDValue getNonRegisterValue(const Value *V)
getNonRegisterValue - Return an SDValue for the given Value, but don't look in FuncInfo....
void CopyValueToVirtualRegister(const Value *V, unsigned Reg, ISD::NodeType ExtendType=ISD::ANY_EXTEND)
DenseMap< MachineBasicBlock *, SmallVector< unsigned, 4 > > LPadToCallSiteMap
Map a landing pad to the call site indexes.
void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB, bool VarArgDisallowed, bool ForceVoidReturnTy)
void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, BranchProbability BranchProbToNext, unsigned Reg, SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB)
visitBitTestCase - this function produces one "bit test"
void setUnusedArgValue(const Value *V, SDValue NewN)
void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, bool IsMustTailCall, const BasicBlock *EHPadBB=nullptr)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void init(GCFunctionInfo *gfi, AAResults *AA, AssumptionCache *AC, const TargetLibraryInfo *li)
DenseMap< const Constant *, unsigned > ConstantsOut
SmallVector< SDValue, 8 > PendingLoads
Loads are not emitted to the program immediately.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
SDValue getRoot()
Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) items.
void ExportFromCurrentBlock(const Value *V)
ExportFromCurrentBlock - If this condition isn't known to be exported from the current basic block,...
void salvageUnresolvedDbgValue(DanglingDebugInfo &DDI)
For the given dangling debuginfo record, perform last-ditch efforts to resolve the debuginfo to somet...
void resolveOrClearDbgInfo()
Evict any dangling debug information, attempting to salvage it first.
std::pair< SDValue, SDValue > lowerInvokable(TargetLowering::CallLoweringInfo &CLI, const BasicBlock *EHPadBB=nullptr)
SDValue getMemoryRoot()
Return the current virtual root of the Selection DAG, flushing any PendingLoad items.
void resolveDanglingDebugInfo(const Value *V, SDValue Val)
If we saw an earlier dbg_value referring to V, generate the debug data structures now that we've seen...
void visit(const Instruction &I)
void dropDanglingDebugInfo(const DILocalVariable *Variable, const DIExpression *Expr)
If we have dangling debug info that describes Variable, or an overlapping part of variable considerin...
SDValue getCopyFromRegs(const Value *V, Type *Ty)
If there was virtual register allocated for the value V emit CopyFromReg of the specified type Ty.
void CopyToExportRegsIfNeeded(const Value *V)
CopyToExportRegsIfNeeded - If the given value has virtual registers created for it,...
void visitJumpTable(SwitchCG::JumpTable &JT)
visitJumpTable - Emit JumpTable node in the current MBB
void visitJumpTableHeader(SwitchCG::JumpTable &JT, SwitchCG::JumpTableHeader &JTH, MachineBasicBlock *SwitchBB)
visitJumpTableHeader - This function emits necessary code to produce index in the JumpTable from swit...
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
static const unsigned LowestSDNodeOrder
Lowest valid SDNodeOrder.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, Instruction::BinaryOps Opc, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
const TargetLibraryInfo * LibInfo
void addDanglingDebugInfo(const DbgValueInst *DI, unsigned Order)
Register a dbg_value which relies on a Value which we have not yet seen.
bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB)
void visitSPDescriptorParent(StackProtectorDescriptor &SPD, MachineBasicBlock *ParentBB)
Codegen a new tail for a stack protector check ParentMBB which has had its tail spliced into a stack ...
bool handleDebugValue(ArrayRef< const Value * > Values, DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, bool IsVariadic)
For a given list of Values, attempt to create and record a SDDbgValue in the SelectionDAG.
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last)
When an MBB was split during scheduling, update the references that need to refer to the last resulti...
SDValue getValueImpl(const Value *V)
getValueImpl - Helper function for getValue and getNonRegisterValue.
void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB)
visitSwitchCase - Emits the necessary code to represent a single node in the binary search tree resul...
SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI)
Lower SLI into a STATEPOINT instruction.
void visitSPDescriptorFailure(StackProtectorDescriptor &SPD)
Codegen the failure basic block for a stack protector check.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:225
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:478
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:472
const FunctionVarLocs * getFunctionVarLocs() const
Returns the result of the AssignmentTrackingAnalysis pass if it's available, otherwise return nullptr...
Definition: SelectionDAG.h:484
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:687
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
This class tracks both per-statepoint and per-selectiondag information.
SwitchLowering(FunctionLoweringInfo &funcinfo)
Multiway switch.
Provides information about what library functions are available for the current target.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
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.
Definition: TargetMachine.h:78
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This function has undefined behavior.
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Level
Code generation optimization level.
Definition: CodeGen.h:57
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:40
@ ADD
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:239
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:779
@ FADD
Simple binary floating point operators.
Definition: ISDOpcodes.h:390
@ FNEG
Perform various unary floating-point operations inspired by libm.
Definition: ISDOpcodes.h:923
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
@ SHL
Shift and rotation operations.
Definition: ISDOpcodes.h:704
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:679
std::vector< CaseCluster > CaseClusterVector
CaseClusterVector::iterator CaseClusterIt
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
StatepointFlags
The statepoint intrinsic accepts a set of flags as its third argument.
Definition: Statepoint.h:39
Definition: BitVector.h:858
#define N
Extended Value Type.
Definition: ValueTypes.h:34
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
SmallVector< unsigned, 4 > Regs
This list holds the registers assigned to the values.
RegsForValue()=default
SmallVector< unsigned, 4 > RegCount
This list holds the number of registers for each value.
SmallVector< EVT, 4 > ValueVTs
The value types of the values, which may not be legal, and may need be promoted or synthesized from o...
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Flag, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
SmallVector< std::pair< unsigned, TypeSize >, 4 > getRegsAndSizes() const
Return a list of registers and their sizes.
void append(const RegsForValue &RHS)
Add the specified values to this one.
void AddInlineAsmOperands(unsigned Code, bool HasMatching, unsigned MatchingIdx, const SDLoc &dl, SelectionDAG &DAG, std::vector< SDValue > &Ops) const
Add this value to the specified inlineasm node operand list.
SmallVector< MVT, 4 > RegVTs
The value types of the registers.
std::optional< CallingConv::ID > CallConv
Records if this value needs to be treated in an ABI dependant manner, different to normal type legali...
bool occupiesMultipleRegs() const
Check if the total RegCount is greater than one.
SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, const SDLoc &dl, SDValue &Chain, SDValue *Flag, const Value *V=nullptr) const
Emit a series of CopyFromReg nodes that copies from this value and returns the result as a ValueVTs v...
friend raw_ostream & operator<<(raw_ostream &OS, const DanglingDebugInfo::Print &P)
Print(const DanglingDebugInfo &DDI, const FunctionVarLocs *VarLocs)
Describes a gc.statepoint or a gc.statepoint like thing for the purposes of lowering into a STATEPOIN...
unsigned NumPatchBytes
The number of patchable bytes the call needs to get lowered into.
ArrayRef< const Use > GCTransitionArgs
The list of gc transition arguments present in the gc.statepoint being lowered.
const BasicBlock * EHPadBB
The exception handling unwind destination, in case this represents an invoke of gc....
ArrayRef< const Use > DeoptState
The deoptimization state associated with this gc.statepoint call, if any.
TargetLowering::CallLoweringInfo CLI
Information regarding the underlying call instruction.
SmallVector< const GCRelocateInst *, 16 > GCRelocates
The set of gc.relocate calls associated with this gc.statepoint.
const Instruction * StatepointInstr
The gc.statepoint instruction.
ArrayRef< const Use > GCArgs
The full list of gc arguments to the gc.statepoint being lowered.
SmallVector< const Value *, 16 > Bases
Bases[i] is the base pointer for Ptrs[i].
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
A cluster of case labels.
This structure contains all information that is necessary for lowering calls.
Variable location definition used by FunctionVarLocs.