1 //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
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
7 //===----------------------------------------------------------------------===//
9 // This implements the SelectionDAGISel class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAGISel.h"
14 #include "ScheduleDAGSDNodes.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/CodeGen/FastISel.h"
34 #include "llvm/CodeGen/FunctionLoweringInfo.h"
35 #include "llvm/CodeGen/GCMetadata.h"
36 #include "llvm/CodeGen/ISDOpcodes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachinePassRegistry.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/SchedulerRegistry.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/StackProtector.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetLowering.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/BasicBlock.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfoMetadata.h"
61 #include "llvm/IR/DebugLoc.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Dominators.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/InlineAsm.h"
66 #include "llvm/IR/InstIterator.h"
67 #include "llvm/IR/InstrTypes.h"
68 #include "llvm/IR/Instruction.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/IR/IntrinsicInst.h"
71 #include "llvm/IR/Intrinsics.h"
72 #include "llvm/IR/Metadata.h"
73 #include "llvm/IR/Type.h"
74 #include "llvm/IR/User.h"
75 #include "llvm/IR/Value.h"
76 #include "llvm/MC/MCInstrDesc.h"
77 #include "llvm/MC/MCRegisterInfo.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MachineValueType.h"
88 #include "llvm/Support/Timer.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetIntrinsicInfo.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
104 using namespace llvm
;
106 #define DEBUG_TYPE "isel"
108 STATISTIC(NumFastIselFailures
, "Number of instructions fast isel failed on");
109 STATISTIC(NumFastIselSuccess
, "Number of instructions fast isel selected");
110 STATISTIC(NumFastIselBlocks
, "Number of blocks selected entirely by fast isel");
111 STATISTIC(NumDAGBlocks
, "Number of blocks selected using DAG");
112 STATISTIC(NumDAGIselRetries
,"Number of times dag isel has to try another path");
113 STATISTIC(NumEntryBlocks
, "Number of entry blocks encountered");
114 STATISTIC(NumFastIselFailLowerArguments
,
115 "Number of entry blocks where fast isel failed to lower arguments");
117 static cl::opt
<int> EnableFastISelAbort(
118 "fast-isel-abort", cl::Hidden
,
119 cl::desc("Enable abort calls when \"fast\" instruction selection "
120 "fails to lower an instruction: 0 disable the abort, 1 will "
121 "abort but for args, calls and terminators, 2 will also "
122 "abort for argument lowering, and 3 will never fallback "
123 "to SelectionDAG."));
125 static cl::opt
<bool> EnableFastISelFallbackReport(
126 "fast-isel-report-on-fallback", cl::Hidden
,
127 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
128 "falls back to SelectionDAG."));
132 cl::desc("use Machine Branch Probability Info"),
133 cl::init(true), cl::Hidden
);
136 static cl::opt
<std::string
>
137 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden
,
138 cl::desc("Only display the basic block whose name "
139 "matches this for all view-*-dags options"));
141 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden
,
142 cl::desc("Pop up a window to show dags before the first "
143 "dag combine pass"));
145 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden
,
146 cl::desc("Pop up a window to show dags before legalize types"));
148 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden
,
149 cl::desc("Pop up a window to show dags before legalize"));
151 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden
,
152 cl::desc("Pop up a window to show dags before the second "
153 "dag combine pass"));
155 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden
,
156 cl::desc("Pop up a window to show dags before the post legalize types"
157 " dag combine pass"));
159 ViewISelDAGs("view-isel-dags", cl::Hidden
,
160 cl::desc("Pop up a window to show isel dags as they are selected"));
162 ViewSchedDAGs("view-sched-dags", cl::Hidden
,
163 cl::desc("Pop up a window to show sched dags as they are processed"));
165 ViewSUnitDAGs("view-sunit-dags", cl::Hidden
,
166 cl::desc("Pop up a window to show SUnit dags after they are processed"));
168 static const bool ViewDAGCombine1
= false,
169 ViewLegalizeTypesDAGs
= false, ViewLegalizeDAGs
= false,
170 ViewDAGCombine2
= false,
171 ViewDAGCombineLT
= false,
172 ViewISelDAGs
= false, ViewSchedDAGs
= false,
173 ViewSUnitDAGs
= false;
176 //===---------------------------------------------------------------------===//
178 /// RegisterScheduler class - Track the registration of instruction schedulers.
180 //===---------------------------------------------------------------------===//
181 MachinePassRegistry
<RegisterScheduler::FunctionPassCtor
>
182 RegisterScheduler::Registry
;
184 //===---------------------------------------------------------------------===//
186 /// ISHeuristic command line option for instruction schedulers.
188 //===---------------------------------------------------------------------===//
189 static cl::opt
<RegisterScheduler::FunctionPassCtor
, false,
190 RegisterPassParser
<RegisterScheduler
>>
191 ISHeuristic("pre-RA-sched",
192 cl::init(&createDefaultScheduler
), cl::Hidden
,
193 cl::desc("Instruction schedulers available (before register"
196 static RegisterScheduler
197 defaultListDAGScheduler("default", "Best scheduler for the target",
198 createDefaultScheduler
);
202 //===--------------------------------------------------------------------===//
203 /// This class is used by SelectionDAGISel to temporarily override
204 /// the optimization level on a per-function basis.
205 class OptLevelChanger
{
206 SelectionDAGISel
&IS
;
207 CodeGenOpt::Level SavedOptLevel
;
211 OptLevelChanger(SelectionDAGISel
&ISel
,
212 CodeGenOpt::Level NewOptLevel
) : IS(ISel
) {
213 SavedOptLevel
= IS
.OptLevel
;
214 if (NewOptLevel
== SavedOptLevel
)
216 IS
.OptLevel
= NewOptLevel
;
217 IS
.TM
.setOptLevel(NewOptLevel
);
218 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
219 << IS
.MF
->getFunction().getName() << "\n");
220 LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
<< " ; After: -O"
221 << NewOptLevel
<< "\n");
222 SavedFastISel
= IS
.TM
.Options
.EnableFastISel
;
223 if (NewOptLevel
== CodeGenOpt::None
) {
224 IS
.TM
.setFastISel(IS
.TM
.getO0WantsFastISel());
226 dbgs() << "\tFastISel is "
227 << (IS
.TM
.Options
.EnableFastISel
? "enabled" : "disabled")
233 if (IS
.OptLevel
== SavedOptLevel
)
235 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
236 << IS
.MF
->getFunction().getName() << "\n");
237 LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS
.OptLevel
<< " ; After: -O"
238 << SavedOptLevel
<< "\n");
239 IS
.OptLevel
= SavedOptLevel
;
240 IS
.TM
.setOptLevel(SavedOptLevel
);
241 IS
.TM
.setFastISel(SavedFastISel
);
245 //===--------------------------------------------------------------------===//
246 /// createDefaultScheduler - This creates an instruction scheduler appropriate
248 ScheduleDAGSDNodes
* createDefaultScheduler(SelectionDAGISel
*IS
,
249 CodeGenOpt::Level OptLevel
) {
250 const TargetLowering
*TLI
= IS
->TLI
;
251 const TargetSubtargetInfo
&ST
= IS
->MF
->getSubtarget();
253 // Try first to see if the Target has its own way of selecting a scheduler
254 if (auto *SchedulerCtor
= ST
.getDAGScheduler(OptLevel
)) {
255 return SchedulerCtor(IS
, OptLevel
);
258 if (OptLevel
== CodeGenOpt::None
||
259 (ST
.enableMachineScheduler() && ST
.enableMachineSchedDefaultSched()) ||
260 TLI
->getSchedulingPreference() == Sched::Source
)
261 return createSourceListDAGScheduler(IS
, OptLevel
);
262 if (TLI
->getSchedulingPreference() == Sched::RegPressure
)
263 return createBURRListDAGScheduler(IS
, OptLevel
);
264 if (TLI
->getSchedulingPreference() == Sched::Hybrid
)
265 return createHybridListDAGScheduler(IS
, OptLevel
);
266 if (TLI
->getSchedulingPreference() == Sched::VLIW
)
267 return createVLIWDAGScheduler(IS
, OptLevel
);
268 assert(TLI
->getSchedulingPreference() == Sched::ILP
&&
269 "Unknown sched type!");
270 return createILPListDAGScheduler(IS
, OptLevel
);
273 } // end namespace llvm
275 // EmitInstrWithCustomInserter - This method should be implemented by targets
276 // that mark instructions with the 'usesCustomInserter' flag. These
277 // instructions are special in various ways, which require special support to
278 // insert. The specified MachineInstr is created but not inserted into any
279 // basic blocks, and this method is called to expand it into a sequence of
280 // instructions, potentially also creating new basic blocks and control flow.
281 // When new basic blocks are inserted and the edges from MBB to its successors
282 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
285 TargetLowering::EmitInstrWithCustomInserter(MachineInstr
&MI
,
286 MachineBasicBlock
*MBB
) const {
288 dbgs() << "If a target marks an instruction with "
289 "'usesCustomInserter', it must implement "
290 "TargetLowering::EmitInstrWithCustomInserter!";
292 llvm_unreachable(nullptr);
295 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr
&MI
,
296 SDNode
*Node
) const {
297 assert(!MI
.hasPostISelHook() &&
298 "If a target marks an instruction with 'hasPostISelHook', "
299 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
302 //===----------------------------------------------------------------------===//
303 // SelectionDAGISel code
304 //===----------------------------------------------------------------------===//
306 SelectionDAGISel::SelectionDAGISel(TargetMachine
&tm
,
307 CodeGenOpt::Level OL
) :
308 MachineFunctionPass(ID
), TM(tm
),
309 FuncInfo(new FunctionLoweringInfo()),
310 CurDAG(new SelectionDAG(tm
, OL
)),
311 SDB(new SelectionDAGBuilder(*CurDAG
, *FuncInfo
, OL
)),
315 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
316 initializeBranchProbabilityInfoWrapperPassPass(
317 *PassRegistry::getPassRegistry());
318 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
319 initializeTargetLibraryInfoWrapperPassPass(
320 *PassRegistry::getPassRegistry());
323 SelectionDAGISel::~SelectionDAGISel() {
329 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage
&AU
) const {
330 if (OptLevel
!= CodeGenOpt::None
)
331 AU
.addRequired
<AAResultsWrapperPass
>();
332 AU
.addRequired
<GCModuleInfo
>();
333 AU
.addRequired
<StackProtector
>();
334 AU
.addPreserved
<GCModuleInfo
>();
335 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
336 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
337 if (UseMBPI
&& OptLevel
!= CodeGenOpt::None
)
338 AU
.addRequired
<BranchProbabilityInfoWrapperPass
>();
339 MachineFunctionPass::getAnalysisUsage(AU
);
342 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
343 /// may trap on it. In this case we have to split the edge so that the path
344 /// through the predecessor block that doesn't go to the phi block doesn't
345 /// execute the possibly trapping instruction. If available, we pass domtree
346 /// and loop info to be updated when we split critical edges. This is because
347 /// SelectionDAGISel preserves these analyses.
348 /// This is required for correctness, so it must be done at -O0.
350 static void SplitCriticalSideEffectEdges(Function
&Fn
, DominatorTree
*DT
,
352 // Loop for blocks with phi nodes.
353 for (BasicBlock
&BB
: Fn
) {
354 PHINode
*PN
= dyn_cast
<PHINode
>(BB
.begin());
358 // For each block with a PHI node, check to see if any of the input values
359 // are potentially trapping constant expressions. Constant expressions are
360 // the only potentially trapping value that can occur as the argument to a
362 for (BasicBlock::iterator I
= BB
.begin(); (PN
= dyn_cast
<PHINode
>(I
)); ++I
)
363 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
364 ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(PN
->getIncomingValue(i
));
365 if (!CE
|| !CE
->canTrap()) continue;
367 // The only case we have to worry about is when the edge is critical.
368 // Since this block has a PHI Node, we assume it has multiple input
369 // edges: check to see if the pred has multiple successors.
370 BasicBlock
*Pred
= PN
->getIncomingBlock(i
);
371 if (Pred
->getTerminator()->getNumSuccessors() == 1)
374 // Okay, we have to split this edge.
376 Pred
->getTerminator(), GetSuccessorNumber(Pred
, &BB
),
377 CriticalEdgeSplittingOptions(DT
, LI
).setMergeIdenticalEdges());
383 static void computeUsesMSVCFloatingPoint(const Triple
&TT
, const Function
&F
,
384 MachineModuleInfo
&MMI
) {
385 // Only needed for MSVC
386 if (!TT
.isKnownWindowsMSVCEnvironment())
389 // If it's already set, nothing to do.
390 if (MMI
.usesMSVCFloatingPoint())
393 for (const Instruction
&I
: instructions(F
)) {
394 if (I
.getType()->isFPOrFPVectorTy()) {
395 MMI
.setUsesMSVCFloatingPoint(true);
398 for (const auto &Op
: I
.operands()) {
399 if (Op
->getType()->isFPOrFPVectorTy()) {
400 MMI
.setUsesMSVCFloatingPoint(true);
407 bool SelectionDAGISel::runOnMachineFunction(MachineFunction
&mf
) {
408 // If we already selected that function, we do not need to run SDISel.
409 if (mf
.getProperties().hasProperty(
410 MachineFunctionProperties::Property::Selected
))
412 // Do some sanity-checking on the command-line options.
413 assert((!EnableFastISelAbort
|| TM
.Options
.EnableFastISel
) &&
414 "-fast-isel-abort > 0 requires -fast-isel");
416 const Function
&Fn
= mf
.getFunction();
419 // Reset the target options before resetting the optimization
421 // FIXME: This is a horrible hack and should be processed via
422 // codegen looking at the optimization level explicitly when
423 // it wants to look at it.
424 TM
.resetTargetOptions(Fn
);
425 // Reset OptLevel to None for optnone functions.
426 CodeGenOpt::Level NewOptLevel
= OptLevel
;
427 if (OptLevel
!= CodeGenOpt::None
&& skipFunction(Fn
))
428 NewOptLevel
= CodeGenOpt::None
;
429 OptLevelChanger
OLC(*this, NewOptLevel
);
431 TII
= MF
->getSubtarget().getInstrInfo();
432 TLI
= MF
->getSubtarget().getTargetLowering();
433 RegInfo
= &MF
->getRegInfo();
434 LibInfo
= &getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI();
435 GFI
= Fn
.hasGC() ? &getAnalysis
<GCModuleInfo
>().getFunctionInfo(Fn
) : nullptr;
436 ORE
= make_unique
<OptimizationRemarkEmitter
>(&Fn
);
437 auto *DTWP
= getAnalysisIfAvailable
<DominatorTreeWrapperPass
>();
438 DominatorTree
*DT
= DTWP
? &DTWP
->getDomTree() : nullptr;
439 auto *LIWP
= getAnalysisIfAvailable
<LoopInfoWrapperPass
>();
440 LoopInfo
*LI
= LIWP
? &LIWP
->getLoopInfo() : nullptr;
442 LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn
.getName() << "\n");
444 SplitCriticalSideEffectEdges(const_cast<Function
&>(Fn
), DT
, LI
);
446 CurDAG
->init(*MF
, *ORE
, this, LibInfo
,
447 getAnalysisIfAvailable
<LegacyDivergenceAnalysis
>());
448 FuncInfo
->set(Fn
, *MF
, CurDAG
);
450 // Now get the optional analyzes if we want to.
451 // This is based on the possibly changed OptLevel (after optnone is taken
452 // into account). That's unfortunate but OK because it just means we won't
453 // ask for passes that have been required anyway.
455 if (UseMBPI
&& OptLevel
!= CodeGenOpt::None
)
456 FuncInfo
->BPI
= &getAnalysis
<BranchProbabilityInfoWrapperPass
>().getBPI();
458 FuncInfo
->BPI
= nullptr;
460 if (OptLevel
!= CodeGenOpt::None
)
461 AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
465 SDB
->init(GFI
, AA
, LibInfo
);
467 MF
->setHasInlineAsm(false);
469 FuncInfo
->SplitCSR
= false;
471 // We split CSR if the target supports it for the given function
472 // and the function has only return exits.
473 if (OptLevel
!= CodeGenOpt::None
&& TLI
->supportSplitCSR(MF
)) {
474 FuncInfo
->SplitCSR
= true;
476 // Collect all the return blocks.
477 for (const BasicBlock
&BB
: Fn
) {
478 if (!succ_empty(&BB
))
481 const Instruction
*Term
= BB
.getTerminator();
482 if (isa
<UnreachableInst
>(Term
) || isa
<ReturnInst
>(Term
))
485 // Bail out if the exit block is not Return nor Unreachable.
486 FuncInfo
->SplitCSR
= false;
491 MachineBasicBlock
*EntryMBB
= &MF
->front();
492 if (FuncInfo
->SplitCSR
)
493 // This performs initialization so lowering for SplitCSR will be correct.
494 TLI
->initializeSplitCSR(EntryMBB
);
496 SelectAllBasicBlocks(Fn
);
497 if (FastISelFailed
&& EnableFastISelFallbackReport
) {
498 DiagnosticInfoISelFallback
DiagFallback(Fn
);
499 Fn
.getContext().diagnose(DiagFallback
);
502 // If the first basic block in the function has live ins that need to be
503 // copied into vregs, emit the copies into the top of the block before
504 // emitting the code for the block.
505 const TargetRegisterInfo
&TRI
= *MF
->getSubtarget().getRegisterInfo();
506 RegInfo
->EmitLiveInCopies(EntryMBB
, TRI
, *TII
);
508 // Insert copies in the entry block and the return blocks.
509 if (FuncInfo
->SplitCSR
) {
510 SmallVector
<MachineBasicBlock
*, 4> Returns
;
511 // Collect all the return blocks.
512 for (MachineBasicBlock
&MBB
: mf
) {
513 if (!MBB
.succ_empty())
516 MachineBasicBlock::iterator Term
= MBB
.getFirstTerminator();
517 if (Term
!= MBB
.end() && Term
->isReturn()) {
518 Returns
.push_back(&MBB
);
522 TLI
->insertCopiesSplitCSR(EntryMBB
, Returns
);
525 DenseMap
<unsigned, unsigned> LiveInMap
;
526 if (!FuncInfo
->ArgDbgValues
.empty())
527 for (std::pair
<unsigned, unsigned> LI
: RegInfo
->liveins())
529 LiveInMap
.insert(LI
);
531 // Insert DBG_VALUE instructions for function arguments to the entry block.
532 for (unsigned i
= 0, e
= FuncInfo
->ArgDbgValues
.size(); i
!= e
; ++i
) {
533 MachineInstr
*MI
= FuncInfo
->ArgDbgValues
[e
-i
-1];
534 bool hasFI
= MI
->getOperand(0).isFI();
536 hasFI
? TRI
.getFrameRegister(*MF
) : MI
->getOperand(0).getReg();
537 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
538 EntryMBB
->insert(EntryMBB
->begin(), MI
);
540 MachineInstr
*Def
= RegInfo
->getVRegDef(Reg
);
542 MachineBasicBlock::iterator InsertPos
= Def
;
543 // FIXME: VR def may not be in entry block.
544 Def
->getParent()->insert(std::next(InsertPos
), MI
);
546 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
547 << TargetRegisterInfo::virtReg2Index(Reg
) << "\n");
550 // If Reg is live-in then update debug info to track its copy in a vreg.
551 DenseMap
<unsigned, unsigned>::iterator LDI
= LiveInMap
.find(Reg
);
552 if (LDI
!= LiveInMap
.end()) {
553 assert(!hasFI
&& "There's no handling of frame pointer updating here yet "
555 MachineInstr
*Def
= RegInfo
->getVRegDef(LDI
->second
);
556 MachineBasicBlock::iterator InsertPos
= Def
;
557 const MDNode
*Variable
= MI
->getDebugVariable();
558 const MDNode
*Expr
= MI
->getDebugExpression();
559 DebugLoc DL
= MI
->getDebugLoc();
560 bool IsIndirect
= MI
->isIndirectDebugValue();
562 assert(MI
->getOperand(1).getImm() == 0 &&
563 "DBG_VALUE with nonzero offset");
564 assert(cast
<DILocalVariable
>(Variable
)->isValidLocationForIntrinsic(DL
) &&
565 "Expected inlined-at fields to agree");
566 // Def is never a terminator here, so it is ok to increment InsertPos.
567 BuildMI(*EntryMBB
, ++InsertPos
, DL
, TII
->get(TargetOpcode::DBG_VALUE
),
568 IsIndirect
, LDI
->second
, Variable
, Expr
);
570 // If this vreg is directly copied into an exported register then
571 // that COPY instructions also need DBG_VALUE, if it is the only
572 // user of LDI->second.
573 MachineInstr
*CopyUseMI
= nullptr;
574 for (MachineRegisterInfo::use_instr_iterator
575 UI
= RegInfo
->use_instr_begin(LDI
->second
),
576 E
= RegInfo
->use_instr_end(); UI
!= E
; ) {
577 MachineInstr
*UseMI
= &*(UI
++);
578 if (UseMI
->isDebugValue()) continue;
579 if (UseMI
->isCopy() && !CopyUseMI
&& UseMI
->getParent() == EntryMBB
) {
580 CopyUseMI
= UseMI
; continue;
582 // Otherwise this is another use or second copy use.
583 CopyUseMI
= nullptr; break;
586 // Use MI's debug location, which describes where Variable was
587 // declared, rather than whatever is attached to CopyUseMI.
588 MachineInstr
*NewMI
=
589 BuildMI(*MF
, DL
, TII
->get(TargetOpcode::DBG_VALUE
), IsIndirect
,
590 CopyUseMI
->getOperand(0).getReg(), Variable
, Expr
);
591 MachineBasicBlock::iterator Pos
= CopyUseMI
;
592 EntryMBB
->insertAfter(Pos
, NewMI
);
597 // Determine if there are any calls in this machine function.
598 MachineFrameInfo
&MFI
= MF
->getFrameInfo();
599 for (const auto &MBB
: *MF
) {
600 if (MFI
.hasCalls() && MF
->hasInlineAsm())
603 for (const auto &MI
: MBB
) {
604 const MCInstrDesc
&MCID
= TII
->get(MI
.getOpcode());
605 if ((MCID
.isCall() && !MCID
.isReturn()) ||
606 MI
.isStackAligningInlineAsm()) {
607 MFI
.setHasCalls(true);
609 if (MI
.isInlineAsm()) {
610 MF
->setHasInlineAsm(true);
615 // Determine if there is a call to setjmp in the machine function.
616 MF
->setExposesReturnsTwice(Fn
.callsFunctionThatReturnsTwice());
618 // Determine if floating point is used for msvc
619 computeUsesMSVCFloatingPoint(TM
.getTargetTriple(), Fn
, MF
->getMMI());
621 // Replace forward-declared registers with the registers containing
622 // the desired value.
623 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
624 for (DenseMap
<unsigned, unsigned>::iterator
625 I
= FuncInfo
->RegFixups
.begin(), E
= FuncInfo
->RegFixups
.end();
627 unsigned From
= I
->first
;
628 unsigned To
= I
->second
;
629 // If To is also scheduled to be replaced, find what its ultimate
632 DenseMap
<unsigned, unsigned>::iterator J
= FuncInfo
->RegFixups
.find(To
);
636 // Make sure the new register has a sufficiently constrained register class.
637 if (TargetRegisterInfo::isVirtualRegister(From
) &&
638 TargetRegisterInfo::isVirtualRegister(To
))
639 MRI
.constrainRegClass(To
, MRI
.getRegClass(From
));
643 // Replacing one register with another won't touch the kill flags.
644 // We need to conservatively clear the kill flags as a kill on the old
645 // register might dominate existing uses of the new register.
646 if (!MRI
.use_empty(To
))
647 MRI
.clearKillFlags(From
);
648 MRI
.replaceRegWith(From
, To
);
651 TLI
->finalizeLowering(*MF
);
653 // Release function-specific state. SDB and CurDAG are already cleared
657 LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
658 LLVM_DEBUG(MF
->print(dbgs()));
663 static void reportFastISelFailure(MachineFunction
&MF
,
664 OptimizationRemarkEmitter
&ORE
,
665 OptimizationRemarkMissed
&R
,
667 // Print the function name explicitly if we don't have a debug location (which
668 // makes the diagnostic less useful) or if we're going to emit a raw error.
669 if (!R
.getLocation().isValid() || ShouldAbort
)
670 R
<< (" (in function: " + MF
.getName() + ")").str();
673 report_fatal_error(R
.getMsg());
678 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin
,
679 BasicBlock::const_iterator End
,
681 // Allow creating illegal types during DAG building for the basic block.
682 CurDAG
->NewNodesMustHaveLegalTypes
= false;
684 // Lower the instructions. If a call is emitted as a tail call, cease emitting
685 // nodes for this block.
686 for (BasicBlock::const_iterator I
= Begin
; I
!= End
&& !SDB
->HasTailCall
; ++I
) {
687 if (!ElidedArgCopyInstrs
.count(&*I
))
691 // Make sure the root of the DAG is up-to-date.
692 CurDAG
->setRoot(SDB
->getControlRoot());
693 HadTailCall
= SDB
->HasTailCall
;
694 SDB
->resolveOrClearDbgInfo();
697 // Final step, emit the lowered DAG as machine code.
701 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
702 SmallPtrSet
<SDNode
*, 16> VisitedNodes
;
703 SmallVector
<SDNode
*, 128> Worklist
;
705 Worklist
.push_back(CurDAG
->getRoot().getNode());
710 SDNode
*N
= Worklist
.pop_back_val();
712 // If we've already seen this node, ignore it.
713 if (!VisitedNodes
.insert(N
).second
)
716 // Otherwise, add all chain operands to the worklist.
717 for (const SDValue
&Op
: N
->op_values())
718 if (Op
.getValueType() == MVT::Other
)
719 Worklist
.push_back(Op
.getNode());
721 // If this is a CopyToReg with a vreg dest, process it.
722 if (N
->getOpcode() != ISD::CopyToReg
)
725 unsigned DestReg
= cast
<RegisterSDNode
>(N
->getOperand(1))->getReg();
726 if (!TargetRegisterInfo::isVirtualRegister(DestReg
))
729 // Ignore non-integer values.
730 SDValue Src
= N
->getOperand(2);
731 EVT SrcVT
= Src
.getValueType();
732 if (!SrcVT
.isInteger())
735 unsigned NumSignBits
= CurDAG
->ComputeNumSignBits(Src
);
736 Known
= CurDAG
->computeKnownBits(Src
);
737 FuncInfo
->AddLiveOutRegInfo(DestReg
, NumSignBits
, Known
);
738 } while (!Worklist
.empty());
741 void SelectionDAGISel::CodeGenAndEmitDAG() {
742 StringRef GroupName
= "sdag";
743 StringRef GroupDescription
= "Instruction Selection and Scheduling";
744 std::string BlockName
;
745 int BlockNumber
= -1;
747 bool MatchFilterBB
= false; (void)MatchFilterBB
;
749 TargetTransformInfo
&TTI
=
750 getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(*FuncInfo
->Fn
);
753 // Pre-type legalization allow creation of any node types.
754 CurDAG
->NewNodesMustHaveLegalTypes
= false;
757 MatchFilterBB
= (FilterDAGBasicBlockName
.empty() ||
758 FilterDAGBasicBlockName
==
759 FuncInfo
->MBB
->getBasicBlock()->getName());
762 if (ViewDAGCombine1
|| ViewLegalizeTypesDAGs
|| ViewLegalizeDAGs
||
763 ViewDAGCombine2
|| ViewDAGCombineLT
|| ViewISelDAGs
|| ViewSchedDAGs
||
767 BlockNumber
= FuncInfo
->MBB
->getNumber();
769 (MF
->getName() + ":" + FuncInfo
->MBB
->getBasicBlock()->getName()).str();
771 LLVM_DEBUG(dbgs() << "Initial selection DAG: "
772 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
776 if (ViewDAGCombine1
&& MatchFilterBB
)
777 CurDAG
->viewGraph("dag-combine1 input for " + BlockName
);
779 // Run the DAG combiner in pre-legalize mode.
781 NamedRegionTimer
T("combine1", "DAG Combining 1", GroupName
,
782 GroupDescription
, TimePassesIsEnabled
);
783 CurDAG
->Combine(BeforeLegalizeTypes
, AA
, OptLevel
);
787 if (TTI
.hasBranchDivergence())
788 CurDAG
->VerifyDAGDiverence();
791 LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
792 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
796 // Second step, hack on the DAG until it only uses operations and types that
797 // the target supports.
798 if (ViewLegalizeTypesDAGs
&& MatchFilterBB
)
799 CurDAG
->viewGraph("legalize-types input for " + BlockName
);
803 NamedRegionTimer
T("legalize_types", "Type Legalization", GroupName
,
804 GroupDescription
, TimePassesIsEnabled
);
805 Changed
= CurDAG
->LegalizeTypes();
809 if (TTI
.hasBranchDivergence())
810 CurDAG
->VerifyDAGDiverence();
813 LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
814 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
818 // Only allow creation of legal node types.
819 CurDAG
->NewNodesMustHaveLegalTypes
= true;
822 if (ViewDAGCombineLT
&& MatchFilterBB
)
823 CurDAG
->viewGraph("dag-combine-lt input for " + BlockName
);
825 // Run the DAG combiner in post-type-legalize mode.
827 NamedRegionTimer
T("combine_lt", "DAG Combining after legalize types",
828 GroupName
, GroupDescription
, TimePassesIsEnabled
);
829 CurDAG
->Combine(AfterLegalizeTypes
, AA
, OptLevel
);
833 if (TTI
.hasBranchDivergence())
834 CurDAG
->VerifyDAGDiverence();
837 LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
838 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
844 NamedRegionTimer
T("legalize_vec", "Vector Legalization", GroupName
,
845 GroupDescription
, TimePassesIsEnabled
);
846 Changed
= CurDAG
->LegalizeVectors();
850 LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
851 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
856 NamedRegionTimer
T("legalize_types2", "Type Legalization 2", GroupName
,
857 GroupDescription
, TimePassesIsEnabled
);
858 CurDAG
->LegalizeTypes();
861 LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
862 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
866 if (ViewDAGCombineLT
&& MatchFilterBB
)
867 CurDAG
->viewGraph("dag-combine-lv input for " + BlockName
);
869 // Run the DAG combiner in post-type-legalize mode.
871 NamedRegionTimer
T("combine_lv", "DAG Combining after legalize vectors",
872 GroupName
, GroupDescription
, TimePassesIsEnabled
);
873 CurDAG
->Combine(AfterLegalizeVectorOps
, AA
, OptLevel
);
876 LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
877 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
882 if (TTI
.hasBranchDivergence())
883 CurDAG
->VerifyDAGDiverence();
887 if (ViewLegalizeDAGs
&& MatchFilterBB
)
888 CurDAG
->viewGraph("legalize input for " + BlockName
);
891 NamedRegionTimer
T("legalize", "DAG Legalization", GroupName
,
892 GroupDescription
, TimePassesIsEnabled
);
897 if (TTI
.hasBranchDivergence())
898 CurDAG
->VerifyDAGDiverence();
901 LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
902 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
906 if (ViewDAGCombine2
&& MatchFilterBB
)
907 CurDAG
->viewGraph("dag-combine2 input for " + BlockName
);
909 // Run the DAG combiner in post-legalize mode.
911 NamedRegionTimer
T("combine2", "DAG Combining 2", GroupName
,
912 GroupDescription
, TimePassesIsEnabled
);
913 CurDAG
->Combine(AfterLegalizeDAG
, AA
, OptLevel
);
917 if (TTI
.hasBranchDivergence())
918 CurDAG
->VerifyDAGDiverence();
921 LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
922 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
926 if (OptLevel
!= CodeGenOpt::None
)
927 ComputeLiveOutVRegInfo();
929 if (ViewISelDAGs
&& MatchFilterBB
)
930 CurDAG
->viewGraph("isel input for " + BlockName
);
932 // Third, instruction select all of the operations to machine code, adding the
933 // code to the MachineBasicBlock.
935 NamedRegionTimer
T("isel", "Instruction Selection", GroupName
,
936 GroupDescription
, TimePassesIsEnabled
);
937 DoInstructionSelection();
940 LLVM_DEBUG(dbgs() << "Selected selection DAG: "
941 << printMBBReference(*FuncInfo
->MBB
) << " '" << BlockName
945 if (ViewSchedDAGs
&& MatchFilterBB
)
946 CurDAG
->viewGraph("scheduler input for " + BlockName
);
948 // Schedule machine code.
949 ScheduleDAGSDNodes
*Scheduler
= CreateScheduler();
951 NamedRegionTimer
T("sched", "Instruction Scheduling", GroupName
,
952 GroupDescription
, TimePassesIsEnabled
);
953 Scheduler
->Run(CurDAG
, FuncInfo
->MBB
);
956 if (ViewSUnitDAGs
&& MatchFilterBB
)
957 Scheduler
->viewGraph();
959 // Emit machine code to BB. This can change 'BB' to the last block being
961 MachineBasicBlock
*FirstMBB
= FuncInfo
->MBB
, *LastMBB
;
963 NamedRegionTimer
T("emit", "Instruction Creation", GroupName
,
964 GroupDescription
, TimePassesIsEnabled
);
966 // FuncInfo->InsertPt is passed by reference and set to the end of the
967 // scheduled instructions.
968 LastMBB
= FuncInfo
->MBB
= Scheduler
->EmitSchedule(FuncInfo
->InsertPt
);
971 // If the block was split, make sure we update any references that are used to
972 // update PHI nodes later on.
973 if (FirstMBB
!= LastMBB
)
974 SDB
->UpdateSplitBlock(FirstMBB
, LastMBB
);
976 // Free the scheduler state.
978 NamedRegionTimer
T("cleanup", "Instruction Scheduling Cleanup", GroupName
,
979 GroupDescription
, TimePassesIsEnabled
);
983 // Free the SelectionDAG state, now that we're finished with it.
989 /// ISelUpdater - helper class to handle updates of the instruction selection
991 class ISelUpdater
: public SelectionDAG::DAGUpdateListener
{
992 SelectionDAG::allnodes_iterator
&ISelPosition
;
995 ISelUpdater(SelectionDAG
&DAG
, SelectionDAG::allnodes_iterator
&isp
)
996 : SelectionDAG::DAGUpdateListener(DAG
), ISelPosition(isp
) {}
998 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
999 /// deleted is the current ISelPosition node, update ISelPosition.
1001 void NodeDeleted(SDNode
*N
, SDNode
*E
) override
{
1002 if (ISelPosition
== SelectionDAG::allnodes_iterator(N
))
1007 } // end anonymous namespace
1009 // This function is used to enforce the topological node id property
1010 // property leveraged during Instruction selection. Before selection all
1011 // nodes are given a non-negative id such that all nodes have a larger id than
1012 // their operands. As this holds transitively we can prune checks that a node N
1013 // is a predecessor of M another by not recursively checking through M's
1014 // operands if N's ID is larger than M's ID. This is significantly improves
1015 // performance of for various legality checks (e.g. IsLegalToFold /
1018 // However, when we fuse multiple nodes into a single node
1019 // during selection we may induce a predecessor relationship between inputs and
1020 // outputs of distinct nodes being merged violating the topological property.
1021 // Should a fused node have a successor which has yet to be selected, our
1022 // legality checks would be incorrect. To avoid this we mark all unselected
1023 // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x =>
1024 // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1025 // We use bit-negation to more clearly enforce that node id -1 can only be
1026 // achieved by selected nodes). As the conversion is reversable the original Id,
1027 // topological pruning can still be leveraged when looking for unselected nodes.
1028 // This method is call internally in all ISel replacement calls.
1029 void SelectionDAGISel::EnforceNodeIdInvariant(SDNode
*Node
) {
1030 SmallVector
<SDNode
*, 4> Nodes
;
1031 Nodes
.push_back(Node
);
1033 while (!Nodes
.empty()) {
1034 SDNode
*N
= Nodes
.pop_back_val();
1035 for (auto *U
: N
->uses()) {
1036 auto UId
= U
->getNodeId();
1038 InvalidateNodeId(U
);
1045 // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a
1046 // NodeId with the equivalent node id which is invalid for topological
1048 void SelectionDAGISel::InvalidateNodeId(SDNode
*N
) {
1049 int InvalidId
= -(N
->getNodeId() + 1);
1050 N
->setNodeId(InvalidId
);
1053 // getUninvalidatedNodeId - get original uninvalidated node id.
1054 int SelectionDAGISel::getUninvalidatedNodeId(SDNode
*N
) {
1055 int Id
= N
->getNodeId();
1061 void SelectionDAGISel::DoInstructionSelection() {
1062 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1063 << printMBBReference(*FuncInfo
->MBB
) << " '"
1064 << FuncInfo
->MBB
->getName() << "'\n");
1066 PreprocessISelDAG();
1068 // Select target instructions for the DAG.
1070 // Number all nodes with a topological order and set DAGSize.
1071 DAGSize
= CurDAG
->AssignTopologicalOrder();
1073 // Create a dummy node (which is not added to allnodes), that adds
1074 // a reference to the root node, preventing it from being deleted,
1075 // and tracking any changes of the root.
1076 HandleSDNode
Dummy(CurDAG
->getRoot());
1077 SelectionDAG::allnodes_iterator
ISelPosition (CurDAG
->getRoot().getNode());
1080 // Make sure that ISelPosition gets properly updated when nodes are deleted
1081 // in calls made from this function.
1082 ISelUpdater
ISU(*CurDAG
, ISelPosition
);
1084 // The AllNodes list is now topological-sorted. Visit the
1085 // nodes by starting at the end of the list (the root of the
1086 // graph) and preceding back toward the beginning (the entry
1088 while (ISelPosition
!= CurDAG
->allnodes_begin()) {
1089 SDNode
*Node
= &*--ISelPosition
;
1090 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1091 // but there are currently some corner cases that it misses. Also, this
1092 // makes it theoretically possible to disable the DAGCombiner.
1093 if (Node
->use_empty())
1097 SmallVector
<SDNode
*, 4> Nodes
;
1098 Nodes
.push_back(Node
);
1100 while (!Nodes
.empty()) {
1101 auto N
= Nodes
.pop_back_val();
1102 if (N
->getOpcode() == ISD::TokenFactor
|| N
->getNodeId() < 0)
1104 for (const SDValue
&Op
: N
->op_values()) {
1105 if (Op
->getOpcode() == ISD::TokenFactor
)
1106 Nodes
.push_back(Op
.getNode());
1108 // We rely on topological ordering of node ids for checking for
1109 // cycles when fusing nodes during selection. All unselected nodes
1110 // successors of an already selected node should have a negative id.
1111 // This assertion will catch such cases. If this assertion triggers
1112 // it is likely you using DAG-level Value/Node replacement functions
1113 // (versus equivalent ISEL replacement) in backend-specific
1114 // selections. See comment in EnforceNodeIdInvariant for more
1116 assert(Op
->getNodeId() != -1 &&
1117 "Node has already selected predecessor node");
1123 // When we are using non-default rounding modes or FP exception behavior
1124 // FP operations are represented by StrictFP pseudo-operations. They
1125 // need to be simplified here so that the target-specific instruction
1126 // selectors know how to handle them.
1128 // If the current node is a strict FP pseudo-op, the isStrictFPOp()
1129 // function will provide the corresponding normal FP opcode to which the
1130 // node should be mutated.
1132 // FIXME: The backends need a way to handle FP constraints.
1133 if (Node
->isStrictFPOpcode())
1134 Node
= CurDAG
->mutateStrictFPToFP(Node
);
1136 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1137 Node
->dump(CurDAG
));
1142 CurDAG
->setRoot(Dummy
.getValue());
1145 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1147 PostprocessISelDAG();
1150 static bool hasExceptionPointerOrCodeUser(const CatchPadInst
*CPI
) {
1151 for (const User
*U
: CPI
->users()) {
1152 if (const IntrinsicInst
*EHPtrCall
= dyn_cast
<IntrinsicInst
>(U
)) {
1153 Intrinsic::ID IID
= EHPtrCall
->getIntrinsicID();
1154 if (IID
== Intrinsic::eh_exceptionpointer
||
1155 IID
== Intrinsic::eh_exceptioncode
)
1162 // wasm.landingpad.index intrinsic is for associating a landing pad index number
1163 // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1164 // and store the mapping in the function.
1165 static void mapWasmLandingPadIndex(MachineBasicBlock
*MBB
,
1166 const CatchPadInst
*CPI
) {
1167 MachineFunction
*MF
= MBB
->getParent();
1168 // In case of single catch (...), we don't emit LSDA, so we don't need
1169 // this information.
1170 bool IsSingleCatchAllClause
=
1171 CPI
->getNumArgOperands() == 1 &&
1172 cast
<Constant
>(CPI
->getArgOperand(0))->isNullValue();
1173 if (!IsSingleCatchAllClause
) {
1174 // Create a mapping from landing pad label to landing pad index.
1175 bool IntrFound
= false;
1176 for (const User
*U
: CPI
->users()) {
1177 if (const auto *Call
= dyn_cast
<IntrinsicInst
>(U
)) {
1178 Intrinsic::ID IID
= Call
->getIntrinsicID();
1179 if (IID
== Intrinsic::wasm_landingpad_index
) {
1180 Value
*IndexArg
= Call
->getArgOperand(1);
1181 int Index
= cast
<ConstantInt
>(IndexArg
)->getZExtValue();
1182 MF
->setWasmLandingPadIndex(MBB
, Index
);
1188 assert(IntrFound
&& "wasm.landingpad.index intrinsic not found!");
1193 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1194 /// do other setup for EH landing-pad blocks.
1195 bool SelectionDAGISel::PrepareEHLandingPad() {
1196 MachineBasicBlock
*MBB
= FuncInfo
->MBB
;
1197 const Constant
*PersonalityFn
= FuncInfo
->Fn
->getPersonalityFn();
1198 const BasicBlock
*LLVMBB
= MBB
->getBasicBlock();
1199 const TargetRegisterClass
*PtrRC
=
1200 TLI
->getRegClassFor(TLI
->getPointerTy(CurDAG
->getDataLayout()));
1202 auto Pers
= classifyEHPersonality(PersonalityFn
);
1204 // Catchpads have one live-in register, which typically holds the exception
1206 if (isFuncletEHPersonality(Pers
)) {
1207 if (const auto *CPI
= dyn_cast
<CatchPadInst
>(LLVMBB
->getFirstNonPHI())) {
1208 if (hasExceptionPointerOrCodeUser(CPI
)) {
1209 // Get or create the virtual register to hold the pointer or code. Mark
1210 // the live in physreg and copy into the vreg.
1211 MCPhysReg EHPhysReg
= TLI
->getExceptionPointerRegister(PersonalityFn
);
1212 assert(EHPhysReg
&& "target lacks exception pointer register");
1213 MBB
->addLiveIn(EHPhysReg
);
1214 unsigned VReg
= FuncInfo
->getCatchPadExceptionPointerVReg(CPI
, PtrRC
);
1215 BuildMI(*MBB
, FuncInfo
->InsertPt
, SDB
->getCurDebugLoc(),
1216 TII
->get(TargetOpcode::COPY
), VReg
)
1217 .addReg(EHPhysReg
, RegState::Kill
);
1223 // Add a label to mark the beginning of the landing pad. Deletion of the
1224 // landing pad can thus be detected via the MachineModuleInfo.
1225 MCSymbol
*Label
= MF
->addLandingPad(MBB
);
1227 const MCInstrDesc
&II
= TII
->get(TargetOpcode::EH_LABEL
);
1228 BuildMI(*MBB
, FuncInfo
->InsertPt
, SDB
->getCurDebugLoc(), II
)
1231 if (Pers
== EHPersonality::Wasm_CXX
) {
1232 if (const auto *CPI
= dyn_cast
<CatchPadInst
>(LLVMBB
->getFirstNonPHI()))
1233 mapWasmLandingPadIndex(MBB
, CPI
);
1235 // Assign the call site to the landing pad's begin label.
1236 MF
->setCallSiteLandingPad(Label
, SDB
->LPadToCallSiteMap
[MBB
]);
1237 // Mark exception register as live in.
1238 if (unsigned Reg
= TLI
->getExceptionPointerRegister(PersonalityFn
))
1239 FuncInfo
->ExceptionPointerVirtReg
= MBB
->addLiveIn(Reg
, PtrRC
);
1240 // Mark exception selector register as live in.
1241 if (unsigned Reg
= TLI
->getExceptionSelectorRegister(PersonalityFn
))
1242 FuncInfo
->ExceptionSelectorVirtReg
= MBB
->addLiveIn(Reg
, PtrRC
);
1248 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1249 /// side-effect free and is either dead or folded into a generated instruction.
1250 /// Return false if it needs to be emitted.
1251 static bool isFoldedOrDeadInstruction(const Instruction
*I
,
1252 FunctionLoweringInfo
*FuncInfo
) {
1253 return !I
->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1254 !I
->isTerminator() && // Terminators aren't folded.
1255 !isa
<DbgInfoIntrinsic
>(I
) && // Debug instructions aren't folded.
1256 !I
->isEHPad() && // EH pad instructions aren't folded.
1257 !FuncInfo
->isExportedInst(I
); // Exported instrs must be computed.
1260 /// Set up SwiftErrorVals by going through the function. If the function has
1261 /// swifterror argument, it will be the first entry.
1262 static void setupSwiftErrorVals(const Function
&Fn
, const TargetLowering
*TLI
,
1263 FunctionLoweringInfo
*FuncInfo
) {
1264 if (!TLI
->supportSwiftError())
1267 FuncInfo
->SwiftErrorVals
.clear();
1268 FuncInfo
->SwiftErrorVRegDefMap
.clear();
1269 FuncInfo
->SwiftErrorVRegUpwardsUse
.clear();
1270 FuncInfo
->SwiftErrorVRegDefUses
.clear();
1271 FuncInfo
->SwiftErrorArg
= nullptr;
1273 // Check if function has a swifterror argument.
1274 bool HaveSeenSwiftErrorArg
= false;
1275 for (Function::const_arg_iterator AI
= Fn
.arg_begin(), AE
= Fn
.arg_end();
1277 if (AI
->hasSwiftErrorAttr()) {
1278 assert(!HaveSeenSwiftErrorArg
&&
1279 "Must have only one swifterror parameter");
1280 (void)HaveSeenSwiftErrorArg
; // silence warning.
1281 HaveSeenSwiftErrorArg
= true;
1282 FuncInfo
->SwiftErrorArg
= &*AI
;
1283 FuncInfo
->SwiftErrorVals
.push_back(&*AI
);
1286 for (const auto &LLVMBB
: Fn
)
1287 for (const auto &Inst
: LLVMBB
) {
1288 if (const AllocaInst
*Alloca
= dyn_cast
<AllocaInst
>(&Inst
))
1289 if (Alloca
->isSwiftError())
1290 FuncInfo
->SwiftErrorVals
.push_back(Alloca
);
1294 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo
*FuncInfo
,
1296 const TargetLowering
*TLI
,
1297 const TargetInstrInfo
*TII
,
1298 SelectionDAGBuilder
*SDB
) {
1299 if (!TLI
->supportSwiftError())
1302 // We only need to do this when we have swifterror parameter or swifterror
1304 if (FuncInfo
->SwiftErrorVals
.empty())
1307 assert(FuncInfo
->MBB
== &*FuncInfo
->MF
->begin() &&
1308 "expected to insert into entry block");
1309 auto &DL
= FuncInfo
->MF
->getDataLayout();
1310 auto const *RC
= TLI
->getRegClassFor(TLI
->getPointerTy(DL
));
1311 for (const auto *SwiftErrorVal
: FuncInfo
->SwiftErrorVals
) {
1312 // We will always generate a copy from the argument. It is always used at
1313 // least by the 'return' of the swifterror.
1314 if (FuncInfo
->SwiftErrorArg
&& FuncInfo
->SwiftErrorArg
== SwiftErrorVal
)
1316 unsigned VReg
= FuncInfo
->MF
->getRegInfo().createVirtualRegister(RC
);
1317 // Assign Undef to Vreg. We construct MI directly to make sure it works
1319 BuildMI(*FuncInfo
->MBB
, FuncInfo
->MBB
->getFirstNonPHI(),
1320 SDB
->getCurDebugLoc(), TII
->get(TargetOpcode::IMPLICIT_DEF
),
1323 // Keep FastIS informed about the value we just inserted.
1325 FastIS
->setLastLocalValue(&*std::prev(FuncInfo
->InsertPt
));
1327 FuncInfo
->setCurrentSwiftErrorVReg(FuncInfo
->MBB
, SwiftErrorVal
, VReg
);
1331 /// Collect llvm.dbg.declare information. This is done after argument lowering
1332 /// in case the declarations refer to arguments.
1333 static void processDbgDeclares(FunctionLoweringInfo
*FuncInfo
) {
1334 MachineFunction
*MF
= FuncInfo
->MF
;
1335 const DataLayout
&DL
= MF
->getDataLayout();
1336 for (const BasicBlock
&BB
: *FuncInfo
->Fn
) {
1337 for (const Instruction
&I
: BB
) {
1338 const DbgDeclareInst
*DI
= dyn_cast
<DbgDeclareInst
>(&I
);
1342 assert(DI
->getVariable() && "Missing variable");
1343 assert(DI
->getDebugLoc() && "Missing location");
1344 const Value
*Address
= DI
->getAddress();
1348 // Look through casts and constant offset GEPs. These mostly come from
1350 APInt
Offset(DL
.getTypeSizeInBits(Address
->getType()), 0);
1351 Address
= Address
->stripAndAccumulateInBoundsConstantOffsets(DL
, Offset
);
1353 // Check if the variable is a static alloca or a byval or inalloca
1354 // argument passed in memory. If it is not, then we will ignore this
1355 // intrinsic and handle this during isel like dbg.value.
1356 int FI
= std::numeric_limits
<int>::max();
1357 if (const auto *AI
= dyn_cast
<AllocaInst
>(Address
)) {
1358 auto SI
= FuncInfo
->StaticAllocaMap
.find(AI
);
1359 if (SI
!= FuncInfo
->StaticAllocaMap
.end())
1361 } else if (const auto *Arg
= dyn_cast
<Argument
>(Address
))
1362 FI
= FuncInfo
->getArgumentFrameIndex(Arg
);
1364 if (FI
== std::numeric_limits
<int>::max())
1367 DIExpression
*Expr
= DI
->getExpression();
1368 if (Offset
.getBoolValue())
1369 Expr
= DIExpression::prepend(Expr
, DIExpression::NoDeref
,
1370 Offset
.getZExtValue());
1371 MF
->setVariableDbgInfo(DI
->getVariable(), Expr
, FI
, DI
->getDebugLoc());
1376 /// Propagate swifterror values through the machine function CFG.
1377 static void propagateSwiftErrorVRegs(FunctionLoweringInfo
*FuncInfo
) {
1378 auto *TLI
= FuncInfo
->TLI
;
1379 if (!TLI
->supportSwiftError())
1382 // We only need to do this when we have swifterror parameter or swifterror
1384 if (FuncInfo
->SwiftErrorVals
.empty())
1387 // For each machine basic block in reverse post order.
1388 ReversePostOrderTraversal
<MachineFunction
*> RPOT(FuncInfo
->MF
);
1389 for (MachineBasicBlock
*MBB
: RPOT
) {
1390 // For each swifterror value in the function.
1391 for(const auto *SwiftErrorVal
: FuncInfo
->SwiftErrorVals
) {
1392 auto Key
= std::make_pair(MBB
, SwiftErrorVal
);
1393 auto UUseIt
= FuncInfo
->SwiftErrorVRegUpwardsUse
.find(Key
);
1394 auto VRegDefIt
= FuncInfo
->SwiftErrorVRegDefMap
.find(Key
);
1395 bool UpwardsUse
= UUseIt
!= FuncInfo
->SwiftErrorVRegUpwardsUse
.end();
1396 unsigned UUseVReg
= UpwardsUse
? UUseIt
->second
: 0;
1397 bool DownwardDef
= VRegDefIt
!= FuncInfo
->SwiftErrorVRegDefMap
.end();
1398 assert(!(UpwardsUse
&& !DownwardDef
) &&
1399 "We can't have an upwards use but no downwards def");
1401 // If there is no upwards exposed use and an entry for the swifterror in
1402 // the def map for this value we don't need to do anything: We already
1403 // have a downward def for this basic block.
1404 if (!UpwardsUse
&& DownwardDef
)
1407 // Otherwise we either have an upwards exposed use vreg that we need to
1408 // materialize or need to forward the downward def from predecessors.
1410 // Check whether we have a single vreg def from all predecessors.
1411 // Otherwise we need a phi.
1412 SmallVector
<std::pair
<MachineBasicBlock
*, unsigned>, 4> VRegs
;
1413 SmallSet
<const MachineBasicBlock
*, 8> Visited
;
1414 for (auto *Pred
: MBB
->predecessors()) {
1415 if (!Visited
.insert(Pred
).second
)
1417 VRegs
.push_back(std::make_pair(
1418 Pred
, FuncInfo
->getOrCreateSwiftErrorVReg(Pred
, SwiftErrorVal
)));
1421 // We have a self-edge.
1422 // If there was no upwards use in this basic block there is now one: the
1423 // phi needs to use it self.
1426 UUseIt
= FuncInfo
->SwiftErrorVRegUpwardsUse
.find(Key
);
1427 assert(UUseIt
!= FuncInfo
->SwiftErrorVRegUpwardsUse
.end());
1428 UUseVReg
= UUseIt
->second
;
1432 // We need a phi node if we have more than one predecessor with different
1435 VRegs
.size() >= 1 &&
1437 VRegs
.begin(), VRegs
.end(),
1438 [&](const std::pair
<const MachineBasicBlock
*, unsigned> &V
)
1439 -> bool { return V
.second
!= VRegs
[0].second
; }) !=
1442 // If there is no upwards exposed used and we don't need a phi just
1443 // forward the swifterror vreg from the predecessor(s).
1444 if (!UpwardsUse
&& !needPHI
) {
1445 assert(!VRegs
.empty() &&
1446 "No predecessors? The entry block should bail out earlier");
1447 // Just forward the swifterror vreg from the predecessor(s).
1448 FuncInfo
->setCurrentSwiftErrorVReg(MBB
, SwiftErrorVal
, VRegs
[0].second
);
1452 auto DLoc
= isa
<Instruction
>(SwiftErrorVal
)
1453 ? cast
<Instruction
>(SwiftErrorVal
)->getDebugLoc()
1455 const auto *TII
= FuncInfo
->MF
->getSubtarget().getInstrInfo();
1457 // If we don't need a phi create a copy to the upward exposed vreg.
1460 assert(!VRegs
.empty() &&
1461 "No predecessors? Is the Calling Convention correct?");
1462 unsigned DestReg
= UUseVReg
;
1463 BuildMI(*MBB
, MBB
->getFirstNonPHI(), DLoc
, TII
->get(TargetOpcode::COPY
),
1465 .addReg(VRegs
[0].second
);
1469 // We need a phi: if there is an upwards exposed use we already have a
1470 // destination virtual register number otherwise we generate a new one.
1471 auto &DL
= FuncInfo
->MF
->getDataLayout();
1472 auto const *RC
= TLI
->getRegClassFor(TLI
->getPointerTy(DL
));
1474 UpwardsUse
? UUseVReg
1475 : FuncInfo
->MF
->getRegInfo().createVirtualRegister(RC
);
1476 MachineInstrBuilder SwiftErrorPHI
=
1477 BuildMI(*MBB
, MBB
->getFirstNonPHI(), DLoc
,
1478 TII
->get(TargetOpcode::PHI
), PHIVReg
);
1479 for (auto BBRegPair
: VRegs
) {
1480 SwiftErrorPHI
.addReg(BBRegPair
.second
).addMBB(BBRegPair
.first
);
1483 // We did not have a definition in this block before: store the phi's vreg
1484 // as this block downward exposed def.
1486 FuncInfo
->setCurrentSwiftErrorVReg(MBB
, SwiftErrorVal
, PHIVReg
);
1491 static void preassignSwiftErrorRegs(const TargetLowering
*TLI
,
1492 FunctionLoweringInfo
*FuncInfo
,
1493 BasicBlock::const_iterator Begin
,
1494 BasicBlock::const_iterator End
) {
1495 if (!TLI
->supportSwiftError() || FuncInfo
->SwiftErrorVals
.empty())
1498 // Iterator over instructions and assign vregs to swifterror defs and uses.
1499 for (auto It
= Begin
; It
!= End
; ++It
) {
1500 ImmutableCallSite
CS(&*It
);
1502 // A call-site with a swifterror argument is both use and def.
1503 const Value
*SwiftErrorAddr
= nullptr;
1504 for (auto &Arg
: CS
.args()) {
1505 if (!Arg
->isSwiftError())
1507 // Use of swifterror.
1508 assert(!SwiftErrorAddr
&& "Cannot have multiple swifterror arguments");
1509 SwiftErrorAddr
= &*Arg
;
1510 assert(SwiftErrorAddr
->isSwiftError() &&
1511 "Must have a swifterror value argument");
1512 unsigned VReg
; bool CreatedReg
;
1513 std::tie(VReg
, CreatedReg
) = FuncInfo
->getOrCreateSwiftErrorVRegUseAt(
1514 &*It
, FuncInfo
->MBB
, SwiftErrorAddr
);
1517 if (!SwiftErrorAddr
)
1520 // Def of swifterror.
1521 unsigned VReg
; bool CreatedReg
;
1522 std::tie(VReg
, CreatedReg
) =
1523 FuncInfo
->getOrCreateSwiftErrorVRegDefAt(&*It
);
1525 FuncInfo
->setCurrentSwiftErrorVReg(FuncInfo
->MBB
, SwiftErrorAddr
, VReg
);
1528 } else if (const LoadInst
*LI
= dyn_cast
<const LoadInst
>(&*It
)) {
1529 const Value
*V
= LI
->getOperand(0);
1530 if (!V
->isSwiftError())
1533 unsigned VReg
; bool CreatedReg
;
1534 std::tie(VReg
, CreatedReg
) =
1535 FuncInfo
->getOrCreateSwiftErrorVRegUseAt(LI
, FuncInfo
->MBB
, V
);
1538 // A store is a def.
1539 } else if (const StoreInst
*SI
= dyn_cast
<const StoreInst
>(&*It
)) {
1540 const Value
*SwiftErrorAddr
= SI
->getOperand(1);
1541 if (!SwiftErrorAddr
->isSwiftError())
1544 // Def of swifterror.
1545 unsigned VReg
; bool CreatedReg
;
1546 std::tie(VReg
, CreatedReg
) =
1547 FuncInfo
->getOrCreateSwiftErrorVRegDefAt(&*It
);
1549 FuncInfo
->setCurrentSwiftErrorVReg(FuncInfo
->MBB
, SwiftErrorAddr
, VReg
);
1551 // A return in a swiferror returning function is a use.
1552 } else if (const ReturnInst
*R
= dyn_cast
<const ReturnInst
>(&*It
)) {
1553 const Function
*F
= R
->getParent()->getParent();
1554 if(!F
->getAttributes().hasAttrSomewhere(Attribute::SwiftError
))
1557 unsigned VReg
; bool CreatedReg
;
1558 std::tie(VReg
, CreatedReg
) = FuncInfo
->getOrCreateSwiftErrorVRegUseAt(
1559 R
, FuncInfo
->MBB
, FuncInfo
->SwiftErrorArg
);
1565 void SelectionDAGISel::SelectAllBasicBlocks(const Function
&Fn
) {
1566 FastISelFailed
= false;
1567 // Initialize the Fast-ISel state, if needed.
1568 FastISel
*FastIS
= nullptr;
1569 if (TM
.Options
.EnableFastISel
) {
1570 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1571 FastIS
= TLI
->createFastISel(*FuncInfo
, LibInfo
);
1574 setupSwiftErrorVals(Fn
, TLI
, FuncInfo
);
1576 ReversePostOrderTraversal
<const Function
*> RPOT(&Fn
);
1578 // Lower arguments up front. An RPO iteration always visits the entry block
1580 assert(*RPOT
.begin() == &Fn
.getEntryBlock());
1583 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1584 FuncInfo
->MBB
= FuncInfo
->MBBMap
[&Fn
.getEntryBlock()];
1585 FuncInfo
->InsertPt
= FuncInfo
->MBB
->begin();
1587 CurDAG
->setFunctionLoweringInfo(FuncInfo
);
1592 // See if fast isel can lower the arguments.
1593 FastIS
->startNewBlock();
1594 if (!FastIS
->lowerArguments()) {
1595 FastISelFailed
= true;
1596 // Fast isel failed to lower these arguments
1597 ++NumFastIselFailLowerArguments
;
1599 OptimizationRemarkMissed
R("sdagisel", "FastISelFailure",
1601 &Fn
.getEntryBlock());
1602 R
<< "FastISel didn't lower all arguments: "
1603 << ore::NV("Prototype", Fn
.getType());
1604 reportFastISelFailure(*MF
, *ORE
, R
, EnableFastISelAbort
> 1);
1606 // Use SelectionDAG argument lowering
1608 CurDAG
->setRoot(SDB
->getControlRoot());
1610 CodeGenAndEmitDAG();
1613 // If we inserted any instructions at the beginning, make a note of
1614 // where they are, so we can be sure to emit subsequent instructions
1616 if (FuncInfo
->InsertPt
!= FuncInfo
->MBB
->begin())
1617 FastIS
->setLastLocalValue(&*std::prev(FuncInfo
->InsertPt
));
1619 FastIS
->setLastLocalValue(nullptr);
1621 createSwiftErrorEntriesInEntryBlock(FuncInfo
, FastIS
, TLI
, TII
, SDB
);
1623 processDbgDeclares(FuncInfo
);
1625 // Iterate over all basic blocks in the function.
1626 StackProtector
&SP
= getAnalysis
<StackProtector
>();
1627 for (const BasicBlock
*LLVMBB
: RPOT
) {
1628 if (OptLevel
!= CodeGenOpt::None
) {
1629 bool AllPredsVisited
= true;
1630 for (const_pred_iterator PI
= pred_begin(LLVMBB
), PE
= pred_end(LLVMBB
);
1632 if (!FuncInfo
->VisitedBBs
.count(*PI
)) {
1633 AllPredsVisited
= false;
1638 if (AllPredsVisited
) {
1639 for (const PHINode
&PN
: LLVMBB
->phis())
1640 FuncInfo
->ComputePHILiveOutRegInfo(&PN
);
1642 for (const PHINode
&PN
: LLVMBB
->phis())
1643 FuncInfo
->InvalidatePHILiveOutRegInfo(&PN
);
1646 FuncInfo
->VisitedBBs
.insert(LLVMBB
);
1649 BasicBlock::const_iterator
const Begin
=
1650 LLVMBB
->getFirstNonPHI()->getIterator();
1651 BasicBlock::const_iterator
const End
= LLVMBB
->end();
1652 BasicBlock::const_iterator BI
= End
;
1654 FuncInfo
->MBB
= FuncInfo
->MBBMap
[LLVMBB
];
1656 continue; // Some blocks like catchpads have no code or MBB.
1658 // Insert new instructions after any phi or argument setup code.
1659 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
1661 // Setup an EH landing-pad block.
1662 FuncInfo
->ExceptionPointerVirtReg
= 0;
1663 FuncInfo
->ExceptionSelectorVirtReg
= 0;
1664 if (LLVMBB
->isEHPad())
1665 if (!PrepareEHLandingPad())
1668 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1670 if (LLVMBB
!= &Fn
.getEntryBlock())
1671 FastIS
->startNewBlock();
1673 unsigned NumFastIselRemaining
= std::distance(Begin
, End
);
1675 // Pre-assign swifterror vregs.
1676 preassignSwiftErrorRegs(TLI
, FuncInfo
, Begin
, End
);
1678 // Do FastISel on as many instructions as possible.
1679 for (; BI
!= Begin
; --BI
) {
1680 const Instruction
*Inst
= &*std::prev(BI
);
1682 // If we no longer require this instruction, skip it.
1683 if (isFoldedOrDeadInstruction(Inst
, FuncInfo
) ||
1684 ElidedArgCopyInstrs
.count(Inst
)) {
1685 --NumFastIselRemaining
;
1689 // Bottom-up: reset the insert pos at the top, after any local-value
1691 FastIS
->recomputeInsertPt();
1693 // Try to select the instruction with FastISel.
1694 if (FastIS
->selectInstruction(Inst
)) {
1695 --NumFastIselRemaining
;
1696 ++NumFastIselSuccess
;
1697 // If fast isel succeeded, skip over all the folded instructions, and
1698 // then see if there is a load right before the selected instructions.
1699 // Try to fold the load if so.
1700 const Instruction
*BeforeInst
= Inst
;
1701 while (BeforeInst
!= &*Begin
) {
1702 BeforeInst
= &*std::prev(BasicBlock::const_iterator(BeforeInst
));
1703 if (!isFoldedOrDeadInstruction(BeforeInst
, FuncInfo
))
1706 if (BeforeInst
!= Inst
&& isa
<LoadInst
>(BeforeInst
) &&
1707 BeforeInst
->hasOneUse() &&
1708 FastIS
->tryToFoldLoad(cast
<LoadInst
>(BeforeInst
), Inst
)) {
1709 // If we succeeded, don't re-select the load.
1710 BI
= std::next(BasicBlock::const_iterator(BeforeInst
));
1711 --NumFastIselRemaining
;
1712 ++NumFastIselSuccess
;
1717 FastISelFailed
= true;
1719 // Then handle certain instructions as single-LLVM-Instruction blocks.
1720 // We cannot separate out GCrelocates to their own blocks since we need
1721 // to keep track of gc-relocates for a particular gc-statepoint. This is
1722 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1724 if (isa
<CallInst
>(Inst
) && !isStatepoint(Inst
) && !isGCRelocate(Inst
)) {
1725 OptimizationRemarkMissed
R("sdagisel", "FastISelFailure",
1726 Inst
->getDebugLoc(), LLVMBB
);
1728 R
<< "FastISel missed call";
1730 if (R
.isEnabled() || EnableFastISelAbort
) {
1731 std::string InstStrStorage
;
1732 raw_string_ostream
InstStr(InstStrStorage
);
1735 R
<< ": " << InstStr
.str();
1738 reportFastISelFailure(*MF
, *ORE
, R
, EnableFastISelAbort
> 2);
1740 if (!Inst
->getType()->isVoidTy() && !Inst
->getType()->isTokenTy() &&
1741 !Inst
->use_empty()) {
1742 unsigned &R
= FuncInfo
->ValueMap
[Inst
];
1744 R
= FuncInfo
->CreateRegs(Inst
->getType());
1747 bool HadTailCall
= false;
1748 MachineBasicBlock::iterator SavedInsertPt
= FuncInfo
->InsertPt
;
1749 SelectBasicBlock(Inst
->getIterator(), BI
, HadTailCall
);
1751 // If the call was emitted as a tail call, we're done with the block.
1752 // We also need to delete any previously emitted instructions.
1754 FastIS
->removeDeadCode(SavedInsertPt
, FuncInfo
->MBB
->end());
1759 // Recompute NumFastIselRemaining as Selection DAG instruction
1760 // selection may have handled the call, input args, etc.
1761 unsigned RemainingNow
= std::distance(Begin
, BI
);
1762 NumFastIselFailures
+= NumFastIselRemaining
- RemainingNow
;
1763 NumFastIselRemaining
= RemainingNow
;
1767 OptimizationRemarkMissed
R("sdagisel", "FastISelFailure",
1768 Inst
->getDebugLoc(), LLVMBB
);
1770 bool ShouldAbort
= EnableFastISelAbort
;
1771 if (Inst
->isTerminator()) {
1772 // Use a different message for terminator misses.
1773 R
<< "FastISel missed terminator";
1774 // Don't abort for terminator unless the level is really high
1775 ShouldAbort
= (EnableFastISelAbort
> 2);
1777 R
<< "FastISel missed";
1780 if (R
.isEnabled() || EnableFastISelAbort
) {
1781 std::string InstStrStorage
;
1782 raw_string_ostream
InstStr(InstStrStorage
);
1784 R
<< ": " << InstStr
.str();
1787 reportFastISelFailure(*MF
, *ORE
, R
, ShouldAbort
);
1789 NumFastIselFailures
+= NumFastIselRemaining
;
1793 FastIS
->recomputeInsertPt();
1796 if (SP
.shouldEmitSDCheck(*LLVMBB
)) {
1797 bool FunctionBasedInstrumentation
=
1798 TLI
->getSSPStackGuardCheck(*Fn
.getParent());
1799 SDB
->SPDescriptor
.initialize(LLVMBB
, FuncInfo
->MBBMap
[LLVMBB
],
1800 FunctionBasedInstrumentation
);
1806 ++NumFastIselBlocks
;
1809 // Run SelectionDAG instruction selection on the remainder of the block
1810 // not handled by FastISel. If FastISel is not run, this is the entire
1813 SelectBasicBlock(Begin
, BI
, HadTailCall
);
1815 // But if FastISel was run, we already selected some of the block.
1816 // If we emitted a tail-call, we need to delete any previously emitted
1817 // instruction that follows it.
1818 if (HadTailCall
&& FuncInfo
->InsertPt
!= FuncInfo
->MBB
->end())
1819 FastIS
->removeDeadCode(FuncInfo
->InsertPt
, FuncInfo
->MBB
->end());
1823 FastIS
->finishBasicBlock();
1825 FuncInfo
->PHINodesToUpdate
.clear();
1826 ElidedArgCopyInstrs
.clear();
1829 SP
.copyToMachineFrameInfo(MF
->getFrameInfo());
1831 propagateSwiftErrorVRegs(FuncInfo
);
1834 SDB
->clearDanglingDebugInfo();
1835 SDB
->SPDescriptor
.resetPerFunctionState();
1838 /// Given that the input MI is before a partial terminator sequence TSeq, return
1839 /// true if M + TSeq also a partial terminator sequence.
1841 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1842 /// lowering copy vregs into physical registers, which are then passed into
1843 /// terminator instructors so we can satisfy ABI constraints. A partial
1844 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1845 /// may be the whole terminator sequence).
1846 static bool MIIsInTerminatorSequence(const MachineInstr
&MI
) {
1847 // If we do not have a copy or an implicit def, we return true if and only if
1848 // MI is a debug value.
1849 if (!MI
.isCopy() && !MI
.isImplicitDef())
1850 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1851 // physical registers if there is debug info associated with the terminator
1852 // of our mbb. We want to include said debug info in our terminator
1853 // sequence, so we return true in that case.
1854 return MI
.isDebugValue();
1856 // We have left the terminator sequence if we are not doing one of the
1859 // 1. Copying a vreg into a physical register.
1860 // 2. Copying a vreg into a vreg.
1861 // 3. Defining a register via an implicit def.
1863 // OPI should always be a register definition...
1864 MachineInstr::const_mop_iterator OPI
= MI
.operands_begin();
1865 if (!OPI
->isReg() || !OPI
->isDef())
1868 // Defining any register via an implicit def is always ok.
1869 if (MI
.isImplicitDef())
1872 // Grab the copy source...
1873 MachineInstr::const_mop_iterator OPI2
= OPI
;
1875 assert(OPI2
!= MI
.operands_end()
1876 && "Should have a copy implying we should have 2 arguments.");
1878 // Make sure that the copy dest is not a vreg when the copy source is a
1879 // physical register.
1880 if (!OPI2
->isReg() ||
1881 (!TargetRegisterInfo::isPhysicalRegister(OPI
->getReg()) &&
1882 TargetRegisterInfo::isPhysicalRegister(OPI2
->getReg())))
1888 /// Find the split point at which to splice the end of BB into its success stack
1889 /// protector check machine basic block.
1891 /// On many platforms, due to ABI constraints, terminators, even before register
1892 /// allocation, use physical registers. This creates an issue for us since
1893 /// physical registers at this point can not travel across basic
1894 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1895 /// when they enter functions and moves them through a sequence of copies back
1896 /// into the physical registers right before the terminator creating a
1897 /// ``Terminator Sequence''. This function is searching for the beginning of the
1898 /// terminator sequence so that we can ensure that we splice off not just the
1899 /// terminator, but additionally the copies that move the vregs into the
1900 /// physical registers.
1901 static MachineBasicBlock::iterator
1902 FindSplitPointForStackProtector(MachineBasicBlock
*BB
) {
1903 MachineBasicBlock::iterator SplitPoint
= BB
->getFirstTerminator();
1905 if (SplitPoint
== BB
->begin())
1908 MachineBasicBlock::iterator Start
= BB
->begin();
1909 MachineBasicBlock::iterator Previous
= SplitPoint
;
1912 while (MIIsInTerminatorSequence(*Previous
)) {
1913 SplitPoint
= Previous
;
1914 if (Previous
== Start
)
1923 SelectionDAGISel::FinishBasicBlock() {
1924 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1925 << FuncInfo
->PHINodesToUpdate
.size() << "\n";
1926 for (unsigned i
= 0, e
= FuncInfo
->PHINodesToUpdate
.size(); i
!= e
;
1928 << "Node " << i
<< " : (" << FuncInfo
->PHINodesToUpdate
[i
].first
1929 << ", " << FuncInfo
->PHINodesToUpdate
[i
].second
<< ")\n");
1931 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1932 // PHI nodes in successors.
1933 for (unsigned i
= 0, e
= FuncInfo
->PHINodesToUpdate
.size(); i
!= e
; ++i
) {
1934 MachineInstrBuilder
PHI(*MF
, FuncInfo
->PHINodesToUpdate
[i
].first
);
1935 assert(PHI
->isPHI() &&
1936 "This is not a machine PHI node that we are updating!");
1937 if (!FuncInfo
->MBB
->isSuccessor(PHI
->getParent()))
1939 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[i
].second
).addMBB(FuncInfo
->MBB
);
1942 // Handle stack protector.
1943 if (SDB
->SPDescriptor
.shouldEmitFunctionBasedCheckStackProtector()) {
1944 // The target provides a guard check function. There is no need to
1945 // generate error handling code or to split current basic block.
1946 MachineBasicBlock
*ParentMBB
= SDB
->SPDescriptor
.getParentMBB();
1948 // Add load and check to the basicblock.
1949 FuncInfo
->MBB
= ParentMBB
;
1950 FuncInfo
->InsertPt
=
1951 FindSplitPointForStackProtector(ParentMBB
);
1952 SDB
->visitSPDescriptorParent(SDB
->SPDescriptor
, ParentMBB
);
1953 CurDAG
->setRoot(SDB
->getRoot());
1955 CodeGenAndEmitDAG();
1957 // Clear the Per-BB State.
1958 SDB
->SPDescriptor
.resetPerBBState();
1959 } else if (SDB
->SPDescriptor
.shouldEmitStackProtector()) {
1960 MachineBasicBlock
*ParentMBB
= SDB
->SPDescriptor
.getParentMBB();
1961 MachineBasicBlock
*SuccessMBB
= SDB
->SPDescriptor
.getSuccessMBB();
1963 // Find the split point to split the parent mbb. At the same time copy all
1964 // physical registers used in the tail of parent mbb into virtual registers
1965 // before the split point and back into physical registers after the split
1966 // point. This prevents us needing to deal with Live-ins and many other
1967 // register allocation issues caused by us splitting the parent mbb. The
1968 // register allocator will clean up said virtual copies later on.
1969 MachineBasicBlock::iterator SplitPoint
=
1970 FindSplitPointForStackProtector(ParentMBB
);
1972 // Splice the terminator of ParentMBB into SuccessMBB.
1973 SuccessMBB
->splice(SuccessMBB
->end(), ParentMBB
,
1977 // Add compare/jump on neq/jump to the parent BB.
1978 FuncInfo
->MBB
= ParentMBB
;
1979 FuncInfo
->InsertPt
= ParentMBB
->end();
1980 SDB
->visitSPDescriptorParent(SDB
->SPDescriptor
, ParentMBB
);
1981 CurDAG
->setRoot(SDB
->getRoot());
1983 CodeGenAndEmitDAG();
1985 // CodeGen Failure MBB if we have not codegened it yet.
1986 MachineBasicBlock
*FailureMBB
= SDB
->SPDescriptor
.getFailureMBB();
1987 if (FailureMBB
->empty()) {
1988 FuncInfo
->MBB
= FailureMBB
;
1989 FuncInfo
->InsertPt
= FailureMBB
->end();
1990 SDB
->visitSPDescriptorFailure(SDB
->SPDescriptor
);
1991 CurDAG
->setRoot(SDB
->getRoot());
1993 CodeGenAndEmitDAG();
1996 // Clear the Per-BB State.
1997 SDB
->SPDescriptor
.resetPerBBState();
2000 // Lower each BitTestBlock.
2001 for (auto &BTB
: SDB
->BitTestCases
) {
2002 // Lower header first, if it wasn't already lowered
2004 // Set the current basic block to the mbb we wish to insert the code into
2005 FuncInfo
->MBB
= BTB
.Parent
;
2006 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2008 SDB
->visitBitTestHeader(BTB
, FuncInfo
->MBB
);
2009 CurDAG
->setRoot(SDB
->getRoot());
2011 CodeGenAndEmitDAG();
2014 BranchProbability UnhandledProb
= BTB
.Prob
;
2015 for (unsigned j
= 0, ej
= BTB
.Cases
.size(); j
!= ej
; ++j
) {
2016 UnhandledProb
-= BTB
.Cases
[j
].ExtraProb
;
2017 // Set the current basic block to the mbb we wish to insert the code into
2018 FuncInfo
->MBB
= BTB
.Cases
[j
].ThisBB
;
2019 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2022 // If all cases cover a contiguous range, it is not necessary to jump to
2023 // the default block after the last bit test fails. This is because the
2024 // range check during bit test header creation has guaranteed that every
2025 // case here doesn't go outside the range. In this case, there is no need
2026 // to perform the last bit test, as it will always be true. Instead, make
2027 // the second-to-last bit-test fall through to the target of the last bit
2028 // test, and delete the last bit test.
2030 MachineBasicBlock
*NextMBB
;
2031 if (BTB
.ContiguousRange
&& j
+ 2 == ej
) {
2032 // Second-to-last bit-test with contiguous range: fall through to the
2033 // target of the final bit test.
2034 NextMBB
= BTB
.Cases
[j
+ 1].TargetBB
;
2035 } else if (j
+ 1 == ej
) {
2036 // For the last bit test, fall through to Default.
2037 NextMBB
= BTB
.Default
;
2039 // Otherwise, fall through to the next bit test.
2040 NextMBB
= BTB
.Cases
[j
+ 1].ThisBB
;
2043 SDB
->visitBitTestCase(BTB
, NextMBB
, UnhandledProb
, BTB
.Reg
, BTB
.Cases
[j
],
2046 CurDAG
->setRoot(SDB
->getRoot());
2048 CodeGenAndEmitDAG();
2050 if (BTB
.ContiguousRange
&& j
+ 2 == ej
) {
2051 // Since we're not going to use the final bit test, remove it.
2052 BTB
.Cases
.pop_back();
2058 for (unsigned pi
= 0, pe
= FuncInfo
->PHINodesToUpdate
.size();
2060 MachineInstrBuilder
PHI(*MF
, FuncInfo
->PHINodesToUpdate
[pi
].first
);
2061 MachineBasicBlock
*PHIBB
= PHI
->getParent();
2062 assert(PHI
->isPHI() &&
2063 "This is not a machine PHI node that we are updating!");
2064 // This is "default" BB. We have two jumps to it. From "header" BB and
2065 // from last "case" BB, unless the latter was skipped.
2066 if (PHIBB
== BTB
.Default
) {
2067 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pi
].second
).addMBB(BTB
.Parent
);
2068 if (!BTB
.ContiguousRange
) {
2069 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pi
].second
)
2070 .addMBB(BTB
.Cases
.back().ThisBB
);
2073 // One of "cases" BB.
2074 for (unsigned j
= 0, ej
= BTB
.Cases
.size();
2076 MachineBasicBlock
* cBB
= BTB
.Cases
[j
].ThisBB
;
2077 if (cBB
->isSuccessor(PHIBB
))
2078 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pi
].second
).addMBB(cBB
);
2082 SDB
->BitTestCases
.clear();
2084 // If the JumpTable record is filled in, then we need to emit a jump table.
2085 // Updating the PHI nodes is tricky in this case, since we need to determine
2086 // whether the PHI is a successor of the range check MBB or the jump table MBB
2087 for (unsigned i
= 0, e
= SDB
->JTCases
.size(); i
!= e
; ++i
) {
2088 // Lower header first, if it wasn't already lowered
2089 if (!SDB
->JTCases
[i
].first
.Emitted
) {
2090 // Set the current basic block to the mbb we wish to insert the code into
2091 FuncInfo
->MBB
= SDB
->JTCases
[i
].first
.HeaderBB
;
2092 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2094 SDB
->visitJumpTableHeader(SDB
->JTCases
[i
].second
, SDB
->JTCases
[i
].first
,
2096 CurDAG
->setRoot(SDB
->getRoot());
2098 CodeGenAndEmitDAG();
2101 // Set the current basic block to the mbb we wish to insert the code into
2102 FuncInfo
->MBB
= SDB
->JTCases
[i
].second
.MBB
;
2103 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2105 SDB
->visitJumpTable(SDB
->JTCases
[i
].second
);
2106 CurDAG
->setRoot(SDB
->getRoot());
2108 CodeGenAndEmitDAG();
2111 for (unsigned pi
= 0, pe
= FuncInfo
->PHINodesToUpdate
.size();
2113 MachineInstrBuilder
PHI(*MF
, FuncInfo
->PHINodesToUpdate
[pi
].first
);
2114 MachineBasicBlock
*PHIBB
= PHI
->getParent();
2115 assert(PHI
->isPHI() &&
2116 "This is not a machine PHI node that we are updating!");
2117 // "default" BB. We can go there only from header BB.
2118 if (PHIBB
== SDB
->JTCases
[i
].second
.Default
)
2119 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pi
].second
)
2120 .addMBB(SDB
->JTCases
[i
].first
.HeaderBB
);
2121 // JT BB. Just iterate over successors here
2122 if (FuncInfo
->MBB
->isSuccessor(PHIBB
))
2123 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pi
].second
).addMBB(FuncInfo
->MBB
);
2126 SDB
->JTCases
.clear();
2128 // If we generated any switch lowering information, build and codegen any
2129 // additional DAGs necessary.
2130 for (unsigned i
= 0, e
= SDB
->SwitchCases
.size(); i
!= e
; ++i
) {
2131 // Set the current basic block to the mbb we wish to insert the code into
2132 FuncInfo
->MBB
= SDB
->SwitchCases
[i
].ThisBB
;
2133 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2135 // Determine the unique successors.
2136 SmallVector
<MachineBasicBlock
*, 2> Succs
;
2137 Succs
.push_back(SDB
->SwitchCases
[i
].TrueBB
);
2138 if (SDB
->SwitchCases
[i
].TrueBB
!= SDB
->SwitchCases
[i
].FalseBB
)
2139 Succs
.push_back(SDB
->SwitchCases
[i
].FalseBB
);
2141 // Emit the code. Note that this could result in FuncInfo->MBB being split.
2142 SDB
->visitSwitchCase(SDB
->SwitchCases
[i
], FuncInfo
->MBB
);
2143 CurDAG
->setRoot(SDB
->getRoot());
2145 CodeGenAndEmitDAG();
2147 // Remember the last block, now that any splitting is done, for use in
2148 // populating PHI nodes in successors.
2149 MachineBasicBlock
*ThisBB
= FuncInfo
->MBB
;
2151 // Handle any PHI nodes in successors of this chunk, as if we were coming
2152 // from the original BB before switch expansion. Note that PHI nodes can
2153 // occur multiple times in PHINodesToUpdate. We have to be very careful to
2154 // handle them the right number of times.
2155 for (unsigned i
= 0, e
= Succs
.size(); i
!= e
; ++i
) {
2156 FuncInfo
->MBB
= Succs
[i
];
2157 FuncInfo
->InsertPt
= FuncInfo
->MBB
->end();
2158 // FuncInfo->MBB may have been removed from the CFG if a branch was
2160 if (ThisBB
->isSuccessor(FuncInfo
->MBB
)) {
2161 for (MachineBasicBlock::iterator
2162 MBBI
= FuncInfo
->MBB
->begin(), MBBE
= FuncInfo
->MBB
->end();
2163 MBBI
!= MBBE
&& MBBI
->isPHI(); ++MBBI
) {
2164 MachineInstrBuilder
PHI(*MF
, MBBI
);
2165 // This value for this PHI node is recorded in PHINodesToUpdate.
2166 for (unsigned pn
= 0; ; ++pn
) {
2167 assert(pn
!= FuncInfo
->PHINodesToUpdate
.size() &&
2168 "Didn't find PHI entry!");
2169 if (FuncInfo
->PHINodesToUpdate
[pn
].first
== PHI
) {
2170 PHI
.addReg(FuncInfo
->PHINodesToUpdate
[pn
].second
).addMBB(ThisBB
);
2178 SDB
->SwitchCases
.clear();
2181 /// Create the scheduler. If a specific scheduler was specified
2182 /// via the SchedulerRegistry, use it, otherwise select the
2183 /// one preferred by the target.
2185 ScheduleDAGSDNodes
*SelectionDAGISel::CreateScheduler() {
2186 return ISHeuristic(this, OptLevel
);
2189 //===----------------------------------------------------------------------===//
2190 // Helper functions used by the generated instruction selector.
2191 //===----------------------------------------------------------------------===//
2192 // Calls to these methods are generated by tblgen.
2194 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
2195 /// the dag combiner simplified the 255, we still want to match. RHS is the
2196 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2197 /// specified in the .td file (e.g. 255).
2198 bool SelectionDAGISel::CheckAndMask(SDValue LHS
, ConstantSDNode
*RHS
,
2199 int64_t DesiredMaskS
) const {
2200 const APInt
&ActualMask
= RHS
->getAPIntValue();
2201 const APInt
&DesiredMask
= APInt(LHS
.getValueSizeInBits(), DesiredMaskS
);
2203 // If the actual mask exactly matches, success!
2204 if (ActualMask
== DesiredMask
)
2207 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2208 if (!ActualMask
.isSubsetOf(DesiredMask
))
2211 // Otherwise, the DAG Combiner may have proven that the value coming in is
2212 // either already zero or is not demanded. Check for known zero input bits.
2213 APInt NeededMask
= DesiredMask
& ~ActualMask
;
2214 if (CurDAG
->MaskedValueIsZero(LHS
, NeededMask
))
2217 // TODO: check to see if missing bits are just not demanded.
2219 // Otherwise, this pattern doesn't match.
2223 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
2224 /// the dag combiner simplified the 255, we still want to match. RHS is the
2225 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2226 /// specified in the .td file (e.g. 255).
2227 bool SelectionDAGISel::CheckOrMask(SDValue LHS
, ConstantSDNode
*RHS
,
2228 int64_t DesiredMaskS
) const {
2229 const APInt
&ActualMask
= RHS
->getAPIntValue();
2230 const APInt
&DesiredMask
= APInt(LHS
.getValueSizeInBits(), DesiredMaskS
);
2232 // If the actual mask exactly matches, success!
2233 if (ActualMask
== DesiredMask
)
2236 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2237 if (!ActualMask
.isSubsetOf(DesiredMask
))
2240 // Otherwise, the DAG Combiner may have proven that the value coming in is
2241 // either already zero or is not demanded. Check for known zero input bits.
2242 APInt NeededMask
= DesiredMask
& ~ActualMask
;
2243 KnownBits Known
= CurDAG
->computeKnownBits(LHS
);
2245 // If all the missing bits in the or are already known to be set, match!
2246 if (NeededMask
.isSubsetOf(Known
.One
))
2249 // TODO: check to see if missing bits are just not demanded.
2251 // Otherwise, this pattern doesn't match.
2255 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2256 /// by tblgen. Others should not call it.
2257 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector
<SDValue
> &Ops
,
2259 std::vector
<SDValue
> InOps
;
2260 std::swap(InOps
, Ops
);
2262 Ops
.push_back(InOps
[InlineAsm::Op_InputChain
]); // 0
2263 Ops
.push_back(InOps
[InlineAsm::Op_AsmString
]); // 1
2264 Ops
.push_back(InOps
[InlineAsm::Op_MDNode
]); // 2, !srcloc
2265 Ops
.push_back(InOps
[InlineAsm::Op_ExtraInfo
]); // 3 (SideEffect, AlignStack)
2267 unsigned i
= InlineAsm::Op_FirstOperand
, e
= InOps
.size();
2268 if (InOps
[e
-1].getValueType() == MVT::Glue
)
2269 --e
; // Don't process a glue operand if it is here.
2272 unsigned Flags
= cast
<ConstantSDNode
>(InOps
[i
])->getZExtValue();
2273 if (!InlineAsm::isMemKind(Flags
)) {
2274 // Just skip over this operand, copying the operands verbatim.
2275 Ops
.insert(Ops
.end(), InOps
.begin()+i
,
2276 InOps
.begin()+i
+InlineAsm::getNumOperandRegisters(Flags
) + 1);
2277 i
+= InlineAsm::getNumOperandRegisters(Flags
) + 1;
2279 assert(InlineAsm::getNumOperandRegisters(Flags
) == 1 &&
2280 "Memory operand with multiple values?");
2282 unsigned TiedToOperand
;
2283 if (InlineAsm::isUseOperandTiedToDef(Flags
, TiedToOperand
)) {
2284 // We need the constraint ID from the operand this is tied to.
2285 unsigned CurOp
= InlineAsm::Op_FirstOperand
;
2286 Flags
= cast
<ConstantSDNode
>(InOps
[CurOp
])->getZExtValue();
2287 for (; TiedToOperand
; --TiedToOperand
) {
2288 CurOp
+= InlineAsm::getNumOperandRegisters(Flags
)+1;
2289 Flags
= cast
<ConstantSDNode
>(InOps
[CurOp
])->getZExtValue();
2293 // Otherwise, this is a memory operand. Ask the target to select it.
2294 std::vector
<SDValue
> SelOps
;
2295 unsigned ConstraintID
= InlineAsm::getMemoryConstraintID(Flags
);
2296 if (SelectInlineAsmMemoryOperand(InOps
[i
+1], ConstraintID
, SelOps
))
2297 report_fatal_error("Could not match memory address. Inline asm"
2300 // Add this to the output node.
2302 InlineAsm::getFlagWord(InlineAsm::Kind_Mem
, SelOps
.size());
2303 NewFlags
= InlineAsm::getFlagWordForMem(NewFlags
, ConstraintID
);
2304 Ops
.push_back(CurDAG
->getTargetConstant(NewFlags
, DL
, MVT::i32
));
2305 Ops
.insert(Ops
.end(), SelOps
.begin(), SelOps
.end());
2310 // Add the glue input back if present.
2311 if (e
!= InOps
.size())
2312 Ops
.push_back(InOps
.back());
2315 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2318 static SDNode
*findGlueUse(SDNode
*N
) {
2319 unsigned FlagResNo
= N
->getNumValues()-1;
2320 for (SDNode::use_iterator I
= N
->use_begin(), E
= N
->use_end(); I
!= E
; ++I
) {
2321 SDUse
&Use
= I
.getUse();
2322 if (Use
.getResNo() == FlagResNo
)
2323 return Use
.getUser();
2328 /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2329 /// beyond "ImmedUse". We may ignore chains as they are checked separately.
2330 static bool findNonImmUse(SDNode
*Root
, SDNode
*Def
, SDNode
*ImmedUse
,
2331 bool IgnoreChains
) {
2332 SmallPtrSet
<const SDNode
*, 16> Visited
;
2333 SmallVector
<const SDNode
*, 16> WorkList
;
2334 // Only check if we have non-immediate uses of Def.
2335 if (ImmedUse
->isOnlyUserOf(Def
))
2338 // We don't care about paths to Def that go through ImmedUse so mark it
2339 // visited and mark non-def operands as used.
2340 Visited
.insert(ImmedUse
);
2341 for (const SDValue
&Op
: ImmedUse
->op_values()) {
2342 SDNode
*N
= Op
.getNode();
2343 // Ignore chain deps (they are validated by
2344 // HandleMergeInputChains) and immediate uses
2345 if ((Op
.getValueType() == MVT::Other
&& IgnoreChains
) || N
== Def
)
2347 if (!Visited
.insert(N
).second
)
2349 WorkList
.push_back(N
);
2352 // Initialize worklist to operands of Root.
2353 if (Root
!= ImmedUse
) {
2354 for (const SDValue
&Op
: Root
->op_values()) {
2355 SDNode
*N
= Op
.getNode();
2356 // Ignore chains (they are validated by HandleMergeInputChains)
2357 if ((Op
.getValueType() == MVT::Other
&& IgnoreChains
) || N
== Def
)
2359 if (!Visited
.insert(N
).second
)
2361 WorkList
.push_back(N
);
2365 return SDNode::hasPredecessorHelper(Def
, Visited
, WorkList
, 0, true);
2368 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2369 /// operand node N of U during instruction selection that starts at Root.
2370 bool SelectionDAGISel::IsProfitableToFold(SDValue N
, SDNode
*U
,
2371 SDNode
*Root
) const {
2372 if (OptLevel
== CodeGenOpt::None
) return false;
2373 return N
.hasOneUse();
2376 /// IsLegalToFold - Returns true if the specific operand node N of
2377 /// U can be folded during instruction selection that starts at Root.
2378 bool SelectionDAGISel::IsLegalToFold(SDValue N
, SDNode
*U
, SDNode
*Root
,
2379 CodeGenOpt::Level OptLevel
,
2380 bool IgnoreChains
) {
2381 if (OptLevel
== CodeGenOpt::None
) return false;
2383 // If Root use can somehow reach N through a path that that doesn't contain
2384 // U then folding N would create a cycle. e.g. In the following
2385 // diagram, Root can reach N through X. If N is folded into Root, then
2386 // X is both a predecessor and a successor of U.
2397 // * indicates nodes to be folded together.
2399 // If Root produces glue, then it gets (even more) interesting. Since it
2400 // will be "glued" together with its glue use in the scheduler, we need to
2401 // check if it might reach N.
2420 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2421 // (call it Fold), then X is a predecessor of GU and a successor of
2422 // Fold. But since Fold and GU are glued together, this will create
2423 // a cycle in the scheduling graph.
2425 // If the node has glue, walk down the graph to the "lowest" node in the
2427 EVT VT
= Root
->getValueType(Root
->getNumValues()-1);
2428 while (VT
== MVT::Glue
) {
2429 SDNode
*GU
= findGlueUse(Root
);
2433 VT
= Root
->getValueType(Root
->getNumValues()-1);
2435 // If our query node has a glue result with a use, we've walked up it. If
2436 // the user (which has already been selected) has a chain or indirectly uses
2437 // the chain, HandleMergeInputChains will not consider it. Because of
2438 // this, we cannot ignore chains in this predicate.
2439 IgnoreChains
= false;
2442 return !findNonImmUse(Root
, N
.getNode(), U
, IgnoreChains
);
2445 void SelectionDAGISel::Select_INLINEASM(SDNode
*N
, bool Branch
) {
2448 std::vector
<SDValue
> Ops(N
->op_begin(), N
->op_end());
2449 SelectInlineAsmMemoryOperands(Ops
, DL
);
2451 const EVT VTs
[] = {MVT::Other
, MVT::Glue
};
2452 SDValue New
= CurDAG
->getNode(Branch
? ISD::INLINEASM_BR
: ISD::INLINEASM
, DL
, VTs
, Ops
);
2454 ReplaceUses(N
, New
.getNode());
2455 CurDAG
->RemoveDeadNode(N
);
2458 void SelectionDAGISel::Select_READ_REGISTER(SDNode
*Op
) {
2460 MDNodeSDNode
*MD
= dyn_cast
<MDNodeSDNode
>(Op
->getOperand(1));
2461 const MDString
*RegStr
= dyn_cast
<MDString
>(MD
->getMD()->getOperand(0));
2463 TLI
->getRegisterByName(RegStr
->getString().data(), Op
->getValueType(0),
2465 SDValue New
= CurDAG
->getCopyFromReg(
2466 Op
->getOperand(0), dl
, Reg
, Op
->getValueType(0));
2468 ReplaceUses(Op
, New
.getNode());
2469 CurDAG
->RemoveDeadNode(Op
);
2472 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode
*Op
) {
2474 MDNodeSDNode
*MD
= dyn_cast
<MDNodeSDNode
>(Op
->getOperand(1));
2475 const MDString
*RegStr
= dyn_cast
<MDString
>(MD
->getMD()->getOperand(0));
2476 unsigned Reg
= TLI
->getRegisterByName(RegStr
->getString().data(),
2477 Op
->getOperand(2).getValueType(),
2479 SDValue New
= CurDAG
->getCopyToReg(
2480 Op
->getOperand(0), dl
, Reg
, Op
->getOperand(2));
2482 ReplaceUses(Op
, New
.getNode());
2483 CurDAG
->RemoveDeadNode(Op
);
2486 void SelectionDAGISel::Select_UNDEF(SDNode
*N
) {
2487 CurDAG
->SelectNodeTo(N
, TargetOpcode::IMPLICIT_DEF
, N
->getValueType(0));
2490 /// GetVBR - decode a vbr encoding whose top bit is set.
2491 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline uint64_t
2492 GetVBR(uint64_t Val
, const unsigned char *MatcherTable
, unsigned &Idx
) {
2493 assert(Val
>= 128 && "Not a VBR");
2494 Val
&= 127; // Remove first vbr bit.
2499 NextBits
= MatcherTable
[Idx
++];
2500 Val
|= (NextBits
&127) << Shift
;
2502 } while (NextBits
& 128);
2507 /// When a match is complete, this method updates uses of interior chain results
2508 /// to use the new results.
2509 void SelectionDAGISel::UpdateChains(
2510 SDNode
*NodeToMatch
, SDValue InputChain
,
2511 SmallVectorImpl
<SDNode
*> &ChainNodesMatched
, bool isMorphNodeTo
) {
2512 SmallVector
<SDNode
*, 4> NowDeadNodes
;
2514 // Now that all the normal results are replaced, we replace the chain and
2515 // glue results if present.
2516 if (!ChainNodesMatched
.empty()) {
2517 assert(InputChain
.getNode() &&
2518 "Matched input chains but didn't produce a chain");
2519 // Loop over all of the nodes we matched that produced a chain result.
2520 // Replace all the chain results with the final chain we ended up with.
2521 for (unsigned i
= 0, e
= ChainNodesMatched
.size(); i
!= e
; ++i
) {
2522 SDNode
*ChainNode
= ChainNodesMatched
[i
];
2523 // If ChainNode is null, it's because we replaced it on a previous
2524 // iteration and we cleared it out of the map. Just skip it.
2528 assert(ChainNode
->getOpcode() != ISD::DELETED_NODE
&&
2529 "Deleted node left in chain");
2531 // Don't replace the results of the root node if we're doing a
2533 if (ChainNode
== NodeToMatch
&& isMorphNodeTo
)
2536 SDValue ChainVal
= SDValue(ChainNode
, ChainNode
->getNumValues()-1);
2537 if (ChainVal
.getValueType() == MVT::Glue
)
2538 ChainVal
= ChainVal
.getValue(ChainVal
->getNumValues()-2);
2539 assert(ChainVal
.getValueType() == MVT::Other
&& "Not a chain?");
2540 SelectionDAG::DAGNodeDeletedListener
NDL(
2541 *CurDAG
, [&](SDNode
*N
, SDNode
*E
) {
2542 std::replace(ChainNodesMatched
.begin(), ChainNodesMatched
.end(), N
,
2543 static_cast<SDNode
*>(nullptr));
2545 if (ChainNode
->getOpcode() != ISD::TokenFactor
)
2546 ReplaceUses(ChainVal
, InputChain
);
2548 // If the node became dead and we haven't already seen it, delete it.
2549 if (ChainNode
!= NodeToMatch
&& ChainNode
->use_empty() &&
2550 !std::count(NowDeadNodes
.begin(), NowDeadNodes
.end(), ChainNode
))
2551 NowDeadNodes
.push_back(ChainNode
);
2555 if (!NowDeadNodes
.empty())
2556 CurDAG
->RemoveDeadNodes(NowDeadNodes
);
2558 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2561 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2562 /// operation for when the pattern matched at least one node with a chains. The
2563 /// input vector contains a list of all of the chained nodes that we match. We
2564 /// must determine if this is a valid thing to cover (i.e. matching it won't
2565 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2566 /// be used as the input node chain for the generated nodes.
2568 HandleMergeInputChains(SmallVectorImpl
<SDNode
*> &ChainNodesMatched
,
2569 SelectionDAG
*CurDAG
) {
2571 SmallPtrSet
<const SDNode
*, 16> Visited
;
2572 SmallVector
<const SDNode
*, 8> Worklist
;
2573 SmallVector
<SDValue
, 3> InputChains
;
2574 unsigned int Max
= 8192;
2576 // Quick exit on trivial merge.
2577 if (ChainNodesMatched
.size() == 1)
2578 return ChainNodesMatched
[0]->getOperand(0);
2580 // Add chains that aren't already added (internal). Peek through
2582 std::function
<void(const SDValue
)> AddChains
= [&](const SDValue V
) {
2583 if (V
.getValueType() != MVT::Other
)
2585 if (V
->getOpcode() == ISD::EntryToken
)
2587 if (!Visited
.insert(V
.getNode()).second
)
2589 if (V
->getOpcode() == ISD::TokenFactor
) {
2590 for (const SDValue
&Op
: V
->op_values())
2593 InputChains
.push_back(V
);
2596 for (auto *N
: ChainNodesMatched
) {
2597 Worklist
.push_back(N
);
2601 while (!Worklist
.empty())
2602 AddChains(Worklist
.pop_back_val()->getOperand(0));
2604 // Skip the search if there are no chain dependencies.
2605 if (InputChains
.size() == 0)
2606 return CurDAG
->getEntryNode();
2608 // If one of these chains is a successor of input, we must have a
2609 // node that is both the predecessor and successor of the
2610 // to-be-merged nodes. Fail.
2612 for (SDValue V
: InputChains
)
2613 Worklist
.push_back(V
.getNode());
2615 for (auto *N
: ChainNodesMatched
)
2616 if (SDNode::hasPredecessorHelper(N
, Visited
, Worklist
, Max
, true))
2619 // Return merged chain.
2620 if (InputChains
.size() == 1)
2621 return InputChains
[0];
2622 return CurDAG
->getNode(ISD::TokenFactor
, SDLoc(ChainNodesMatched
[0]),
2623 MVT::Other
, InputChains
);
2626 /// MorphNode - Handle morphing a node in place for the selector.
2627 SDNode
*SelectionDAGISel::
2628 MorphNode(SDNode
*Node
, unsigned TargetOpc
, SDVTList VTList
,
2629 ArrayRef
<SDValue
> Ops
, unsigned EmitNodeInfo
) {
2630 // It is possible we're using MorphNodeTo to replace a node with no
2631 // normal results with one that has a normal result (or we could be
2632 // adding a chain) and the input could have glue and chains as well.
2633 // In this case we need to shift the operands down.
2634 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2635 // than the old isel though.
2636 int OldGlueResultNo
= -1, OldChainResultNo
= -1;
2638 unsigned NTMNumResults
= Node
->getNumValues();
2639 if (Node
->getValueType(NTMNumResults
-1) == MVT::Glue
) {
2640 OldGlueResultNo
= NTMNumResults
-1;
2641 if (NTMNumResults
!= 1 &&
2642 Node
->getValueType(NTMNumResults
-2) == MVT::Other
)
2643 OldChainResultNo
= NTMNumResults
-2;
2644 } else if (Node
->getValueType(NTMNumResults
-1) == MVT::Other
)
2645 OldChainResultNo
= NTMNumResults
-1;
2647 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2648 // that this deletes operands of the old node that become dead.
2649 SDNode
*Res
= CurDAG
->MorphNodeTo(Node
, ~TargetOpc
, VTList
, Ops
);
2651 // MorphNodeTo can operate in two ways: if an existing node with the
2652 // specified operands exists, it can just return it. Otherwise, it
2653 // updates the node in place to have the requested operands.
2655 // If we updated the node in place, reset the node ID. To the isel,
2656 // this should be just like a newly allocated machine node.
2660 unsigned ResNumResults
= Res
->getNumValues();
2661 // Move the glue if needed.
2662 if ((EmitNodeInfo
& OPFL_GlueOutput
) && OldGlueResultNo
!= -1 &&
2663 (unsigned)OldGlueResultNo
!= ResNumResults
-1)
2664 ReplaceUses(SDValue(Node
, OldGlueResultNo
),
2665 SDValue(Res
, ResNumResults
- 1));
2667 if ((EmitNodeInfo
& OPFL_GlueOutput
) != 0)
2670 // Move the chain reference if needed.
2671 if ((EmitNodeInfo
& OPFL_Chain
) && OldChainResultNo
!= -1 &&
2672 (unsigned)OldChainResultNo
!= ResNumResults
-1)
2673 ReplaceUses(SDValue(Node
, OldChainResultNo
),
2674 SDValue(Res
, ResNumResults
- 1));
2676 // Otherwise, no replacement happened because the node already exists. Replace
2677 // Uses of the old node with the new one.
2679 ReplaceNode(Node
, Res
);
2681 EnforceNodeIdInvariant(Res
);
2687 /// CheckSame - Implements OP_CheckSame.
2688 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2689 CheckSame(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2691 const SmallVectorImpl
<std::pair
<SDValue
, SDNode
*>> &RecordedNodes
) {
2692 // Accept if it is exactly the same as a previously recorded node.
2693 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
2694 assert(RecNo
< RecordedNodes
.size() && "Invalid CheckSame");
2695 return N
== RecordedNodes
[RecNo
].first
;
2698 /// CheckChildSame - Implements OP_CheckChildXSame.
2699 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2700 CheckChildSame(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2702 const SmallVectorImpl
<std::pair
<SDValue
, SDNode
*>> &RecordedNodes
,
2704 if (ChildNo
>= N
.getNumOperands())
2705 return false; // Match fails if out of range child #.
2706 return ::CheckSame(MatcherTable
, MatcherIndex
, N
.getOperand(ChildNo
),
2710 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2711 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2712 CheckPatternPredicate(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2713 const SelectionDAGISel
&SDISel
) {
2714 return SDISel
.CheckPatternPredicate(MatcherTable
[MatcherIndex
++]);
2717 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2718 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2719 CheckNodePredicate(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2720 const SelectionDAGISel
&SDISel
, SDNode
*N
) {
2721 return SDISel
.CheckNodePredicate(N
, MatcherTable
[MatcherIndex
++]);
2724 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2725 CheckOpcode(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2727 uint16_t Opc
= MatcherTable
[MatcherIndex
++];
2728 Opc
|= (unsigned short)MatcherTable
[MatcherIndex
++] << 8;
2729 return N
->getOpcode() == Opc
;
2732 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2733 CheckType(const unsigned char *MatcherTable
, unsigned &MatcherIndex
, SDValue N
,
2734 const TargetLowering
*TLI
, const DataLayout
&DL
) {
2735 MVT::SimpleValueType VT
= (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
2736 if (N
.getValueType() == VT
) return true;
2738 // Handle the case when VT is iPTR.
2739 return VT
== MVT::iPTR
&& N
.getValueType() == TLI
->getPointerTy(DL
);
2742 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2743 CheckChildType(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2744 SDValue N
, const TargetLowering
*TLI
, const DataLayout
&DL
,
2746 if (ChildNo
>= N
.getNumOperands())
2747 return false; // Match fails if out of range child #.
2748 return ::CheckType(MatcherTable
, MatcherIndex
, N
.getOperand(ChildNo
), TLI
,
2752 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2753 CheckCondCode(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2755 return cast
<CondCodeSDNode
>(N
)->get() ==
2756 (ISD::CondCode
)MatcherTable
[MatcherIndex
++];
2759 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2760 CheckValueType(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2761 SDValue N
, const TargetLowering
*TLI
, const DataLayout
&DL
) {
2762 MVT::SimpleValueType VT
= (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
2763 if (cast
<VTSDNode
>(N
)->getVT() == VT
)
2766 // Handle the case when VT is iPTR.
2767 return VT
== MVT::iPTR
&& cast
<VTSDNode
>(N
)->getVT() == TLI
->getPointerTy(DL
);
2770 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2771 CheckInteger(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2773 int64_t Val
= MatcherTable
[MatcherIndex
++];
2775 Val
= GetVBR(Val
, MatcherTable
, MatcherIndex
);
2777 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
);
2778 return C
&& C
->getSExtValue() == Val
;
2781 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2782 CheckChildInteger(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2783 SDValue N
, unsigned ChildNo
) {
2784 if (ChildNo
>= N
.getNumOperands())
2785 return false; // Match fails if out of range child #.
2786 return ::CheckInteger(MatcherTable
, MatcherIndex
, N
.getOperand(ChildNo
));
2789 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2790 CheckAndImm(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2791 SDValue N
, const SelectionDAGISel
&SDISel
) {
2792 int64_t Val
= MatcherTable
[MatcherIndex
++];
2794 Val
= GetVBR(Val
, MatcherTable
, MatcherIndex
);
2796 if (N
->getOpcode() != ISD::AND
) return false;
2798 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
2799 return C
&& SDISel
.CheckAndMask(N
.getOperand(0), C
, Val
);
2802 LLVM_ATTRIBUTE_ALWAYS_INLINE
static inline bool
2803 CheckOrImm(const unsigned char *MatcherTable
, unsigned &MatcherIndex
,
2804 SDValue N
, const SelectionDAGISel
&SDISel
) {
2805 int64_t Val
= MatcherTable
[MatcherIndex
++];
2807 Val
= GetVBR(Val
, MatcherTable
, MatcherIndex
);
2809 if (N
->getOpcode() != ISD::OR
) return false;
2811 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
2812 return C
&& SDISel
.CheckOrMask(N
.getOperand(0), C
, Val
);
2815 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2816 /// scope, evaluate the current node. If the current predicate is known to
2817 /// fail, set Result=true and return anything. If the current predicate is
2818 /// known to pass, set Result=false and return the MatcherIndex to continue
2819 /// with. If the current predicate is unknown, set Result=false and return the
2820 /// MatcherIndex to continue with.
2821 static unsigned IsPredicateKnownToFail(const unsigned char *Table
,
2822 unsigned Index
, SDValue N
,
2824 const SelectionDAGISel
&SDISel
,
2825 SmallVectorImpl
<std::pair
<SDValue
, SDNode
*>> &RecordedNodes
) {
2826 switch (Table
[Index
++]) {
2829 return Index
-1; // Could not evaluate this predicate.
2830 case SelectionDAGISel::OPC_CheckSame
:
2831 Result
= !::CheckSame(Table
, Index
, N
, RecordedNodes
);
2833 case SelectionDAGISel::OPC_CheckChild0Same
:
2834 case SelectionDAGISel::OPC_CheckChild1Same
:
2835 case SelectionDAGISel::OPC_CheckChild2Same
:
2836 case SelectionDAGISel::OPC_CheckChild3Same
:
2837 Result
= !::CheckChildSame(Table
, Index
, N
, RecordedNodes
,
2838 Table
[Index
-1] - SelectionDAGISel::OPC_CheckChild0Same
);
2840 case SelectionDAGISel::OPC_CheckPatternPredicate
:
2841 Result
= !::CheckPatternPredicate(Table
, Index
, SDISel
);
2843 case SelectionDAGISel::OPC_CheckPredicate
:
2844 Result
= !::CheckNodePredicate(Table
, Index
, SDISel
, N
.getNode());
2846 case SelectionDAGISel::OPC_CheckOpcode
:
2847 Result
= !::CheckOpcode(Table
, Index
, N
.getNode());
2849 case SelectionDAGISel::OPC_CheckType
:
2850 Result
= !::CheckType(Table
, Index
, N
, SDISel
.TLI
,
2851 SDISel
.CurDAG
->getDataLayout());
2853 case SelectionDAGISel::OPC_CheckTypeRes
: {
2854 unsigned Res
= Table
[Index
++];
2855 Result
= !::CheckType(Table
, Index
, N
.getValue(Res
), SDISel
.TLI
,
2856 SDISel
.CurDAG
->getDataLayout());
2859 case SelectionDAGISel::OPC_CheckChild0Type
:
2860 case SelectionDAGISel::OPC_CheckChild1Type
:
2861 case SelectionDAGISel::OPC_CheckChild2Type
:
2862 case SelectionDAGISel::OPC_CheckChild3Type
:
2863 case SelectionDAGISel::OPC_CheckChild4Type
:
2864 case SelectionDAGISel::OPC_CheckChild5Type
:
2865 case SelectionDAGISel::OPC_CheckChild6Type
:
2866 case SelectionDAGISel::OPC_CheckChild7Type
:
2867 Result
= !::CheckChildType(
2868 Table
, Index
, N
, SDISel
.TLI
, SDISel
.CurDAG
->getDataLayout(),
2869 Table
[Index
- 1] - SelectionDAGISel::OPC_CheckChild0Type
);
2871 case SelectionDAGISel::OPC_CheckCondCode
:
2872 Result
= !::CheckCondCode(Table
, Index
, N
);
2874 case SelectionDAGISel::OPC_CheckValueType
:
2875 Result
= !::CheckValueType(Table
, Index
, N
, SDISel
.TLI
,
2876 SDISel
.CurDAG
->getDataLayout());
2878 case SelectionDAGISel::OPC_CheckInteger
:
2879 Result
= !::CheckInteger(Table
, Index
, N
);
2881 case SelectionDAGISel::OPC_CheckChild0Integer
:
2882 case SelectionDAGISel::OPC_CheckChild1Integer
:
2883 case SelectionDAGISel::OPC_CheckChild2Integer
:
2884 case SelectionDAGISel::OPC_CheckChild3Integer
:
2885 case SelectionDAGISel::OPC_CheckChild4Integer
:
2886 Result
= !::CheckChildInteger(Table
, Index
, N
,
2887 Table
[Index
-1] - SelectionDAGISel::OPC_CheckChild0Integer
);
2889 case SelectionDAGISel::OPC_CheckAndImm
:
2890 Result
= !::CheckAndImm(Table
, Index
, N
, SDISel
);
2892 case SelectionDAGISel::OPC_CheckOrImm
:
2893 Result
= !::CheckOrImm(Table
, Index
, N
, SDISel
);
2901 /// FailIndex - If this match fails, this is the index to continue with.
2904 /// NodeStack - The node stack when the scope was formed.
2905 SmallVector
<SDValue
, 4> NodeStack
;
2907 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2908 unsigned NumRecordedNodes
;
2910 /// NumMatchedMemRefs - The number of matched memref entries.
2911 unsigned NumMatchedMemRefs
;
2913 /// InputChain/InputGlue - The current chain/glue
2914 SDValue InputChain
, InputGlue
;
2916 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2917 bool HasChainNodesMatched
;
2920 /// \A DAG update listener to keep the matching state
2921 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2922 /// change the DAG while matching. X86 addressing mode matcher is an example
2924 class MatchStateUpdater
: public SelectionDAG::DAGUpdateListener
2926 SDNode
**NodeToMatch
;
2927 SmallVectorImpl
<std::pair
<SDValue
, SDNode
*>> &RecordedNodes
;
2928 SmallVectorImpl
<MatchScope
> &MatchScopes
;
2931 MatchStateUpdater(SelectionDAG
&DAG
, SDNode
**NodeToMatch
,
2932 SmallVectorImpl
<std::pair
<SDValue
, SDNode
*>> &RN
,
2933 SmallVectorImpl
<MatchScope
> &MS
)
2934 : SelectionDAG::DAGUpdateListener(DAG
), NodeToMatch(NodeToMatch
),
2935 RecordedNodes(RN
), MatchScopes(MS
) {}
2937 void NodeDeleted(SDNode
*N
, SDNode
*E
) override
{
2938 // Some early-returns here to avoid the search if we deleted the node or
2939 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2940 // do, so it's unnecessary to update matching state at that point).
2941 // Neither of these can occur currently because we only install this
2942 // update listener during matching a complex patterns.
2943 if (!E
|| E
->isMachineOpcode())
2945 // Check if NodeToMatch was updated.
2946 if (N
== *NodeToMatch
)
2948 // Performing linear search here does not matter because we almost never
2949 // run this code. You'd have to have a CSE during complex pattern
2951 for (auto &I
: RecordedNodes
)
2952 if (I
.first
.getNode() == N
)
2955 for (auto &I
: MatchScopes
)
2956 for (auto &J
: I
.NodeStack
)
2957 if (J
.getNode() == N
)
2962 } // end anonymous namespace
2964 void SelectionDAGISel::SelectCodeCommon(SDNode
*NodeToMatch
,
2965 const unsigned char *MatcherTable
,
2966 unsigned TableSize
) {
2967 // FIXME: Should these even be selected? Handle these cases in the caller?
2968 switch (NodeToMatch
->getOpcode()) {
2971 case ISD::EntryToken
: // These nodes remain the same.
2972 case ISD::BasicBlock
:
2974 case ISD::RegisterMask
:
2975 case ISD::HANDLENODE
:
2976 case ISD::MDNODE_SDNODE
:
2977 case ISD::TargetConstant
:
2978 case ISD::TargetConstantFP
:
2979 case ISD::TargetConstantPool
:
2980 case ISD::TargetFrameIndex
:
2981 case ISD::TargetExternalSymbol
:
2983 case ISD::TargetBlockAddress
:
2984 case ISD::TargetJumpTable
:
2985 case ISD::TargetGlobalTLSAddress
:
2986 case ISD::TargetGlobalAddress
:
2987 case ISD::TokenFactor
:
2988 case ISD::CopyFromReg
:
2989 case ISD::CopyToReg
:
2991 case ISD::ANNOTATION_LABEL
:
2992 case ISD::LIFETIME_START
:
2993 case ISD::LIFETIME_END
:
2994 NodeToMatch
->setNodeId(-1); // Mark selected.
2996 case ISD::AssertSext
:
2997 case ISD::AssertZext
:
2998 ReplaceUses(SDValue(NodeToMatch
, 0), NodeToMatch
->getOperand(0));
2999 CurDAG
->RemoveDeadNode(NodeToMatch
);
3001 case ISD::INLINEASM
:
3002 case ISD::INLINEASM_BR
:
3003 Select_INLINEASM(NodeToMatch
,
3004 NodeToMatch
->getOpcode() == ISD::INLINEASM_BR
);
3006 case ISD::READ_REGISTER
:
3007 Select_READ_REGISTER(NodeToMatch
);
3009 case ISD::WRITE_REGISTER
:
3010 Select_WRITE_REGISTER(NodeToMatch
);
3013 Select_UNDEF(NodeToMatch
);
3017 assert(!NodeToMatch
->isMachineOpcode() && "Node already selected!");
3019 // Set up the node stack with NodeToMatch as the only node on the stack.
3020 SmallVector
<SDValue
, 8> NodeStack
;
3021 SDValue N
= SDValue(NodeToMatch
, 0);
3022 NodeStack
.push_back(N
);
3024 // MatchScopes - Scopes used when matching, if a match failure happens, this
3025 // indicates where to continue checking.
3026 SmallVector
<MatchScope
, 8> MatchScopes
;
3028 // RecordedNodes - This is the set of nodes that have been recorded by the
3029 // state machine. The second value is the parent of the node, or null if the
3030 // root is recorded.
3031 SmallVector
<std::pair
<SDValue
, SDNode
*>, 8> RecordedNodes
;
3033 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3035 SmallVector
<MachineMemOperand
*, 2> MatchedMemRefs
;
3037 // These are the current input chain and glue for use when generating nodes.
3038 // Various Emit operations change these. For example, emitting a copytoreg
3039 // uses and updates these.
3040 SDValue InputChain
, InputGlue
;
3042 // ChainNodesMatched - If a pattern matches nodes that have input/output
3043 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3044 // which ones they are. The result is captured into this list so that we can
3045 // update the chain results when the pattern is complete.
3046 SmallVector
<SDNode
*, 3> ChainNodesMatched
;
3048 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3050 // Determine where to start the interpreter. Normally we start at opcode #0,
3051 // but if the state machine starts with an OPC_SwitchOpcode, then we
3052 // accelerate the first lookup (which is guaranteed to be hot) with the
3053 // OpcodeOffset table.
3054 unsigned MatcherIndex
= 0;
3056 if (!OpcodeOffset
.empty()) {
3057 // Already computed the OpcodeOffset table, just index into it.
3058 if (N
.getOpcode() < OpcodeOffset
.size())
3059 MatcherIndex
= OpcodeOffset
[N
.getOpcode()];
3060 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex
<< "\n");
3062 } else if (MatcherTable
[0] == OPC_SwitchOpcode
) {
3063 // Otherwise, the table isn't computed, but the state machine does start
3064 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3065 // is the first time we're selecting an instruction.
3068 // Get the size of this case.
3069 unsigned CaseSize
= MatcherTable
[Idx
++];
3071 CaseSize
= GetVBR(CaseSize
, MatcherTable
, Idx
);
3072 if (CaseSize
== 0) break;
3074 // Get the opcode, add the index to the table.
3075 uint16_t Opc
= MatcherTable
[Idx
++];
3076 Opc
|= (unsigned short)MatcherTable
[Idx
++] << 8;
3077 if (Opc
>= OpcodeOffset
.size())
3078 OpcodeOffset
.resize((Opc
+1)*2);
3079 OpcodeOffset
[Opc
] = Idx
;
3083 // Okay, do the lookup for the first opcode.
3084 if (N
.getOpcode() < OpcodeOffset
.size())
3085 MatcherIndex
= OpcodeOffset
[N
.getOpcode()];
3089 assert(MatcherIndex
< TableSize
&& "Invalid index");
3091 unsigned CurrentOpcodeIndex
= MatcherIndex
;
3093 BuiltinOpcodes Opcode
= (BuiltinOpcodes
)MatcherTable
[MatcherIndex
++];
3096 // Okay, the semantics of this operation are that we should push a scope
3097 // then evaluate the first child. However, pushing a scope only to have
3098 // the first check fail (which then pops it) is inefficient. If we can
3099 // determine immediately that the first check (or first several) will
3100 // immediately fail, don't even bother pushing a scope for them.
3104 unsigned NumToSkip
= MatcherTable
[MatcherIndex
++];
3105 if (NumToSkip
& 128)
3106 NumToSkip
= GetVBR(NumToSkip
, MatcherTable
, MatcherIndex
);
3107 // Found the end of the scope with no match.
3108 if (NumToSkip
== 0) {
3113 FailIndex
= MatcherIndex
+NumToSkip
;
3115 unsigned MatcherIndexOfPredicate
= MatcherIndex
;
3116 (void)MatcherIndexOfPredicate
; // silence warning.
3118 // If we can't evaluate this predicate without pushing a scope (e.g. if
3119 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3120 // push the scope and evaluate the full predicate chain.
3122 MatcherIndex
= IsPredicateKnownToFail(MatcherTable
, MatcherIndex
, N
,
3123 Result
, *this, RecordedNodes
);
3128 dbgs() << " Skipped scope entry (due to false predicate) at "
3129 << "index " << MatcherIndexOfPredicate
<< ", continuing at "
3130 << FailIndex
<< "\n");
3131 ++NumDAGIselRetries
;
3133 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3134 // move to the next case.
3135 MatcherIndex
= FailIndex
;
3138 // If the whole scope failed to match, bail.
3139 if (FailIndex
== 0) break;
3141 // Push a MatchScope which indicates where to go if the first child fails
3143 MatchScope NewEntry
;
3144 NewEntry
.FailIndex
= FailIndex
;
3145 NewEntry
.NodeStack
.append(NodeStack
.begin(), NodeStack
.end());
3146 NewEntry
.NumRecordedNodes
= RecordedNodes
.size();
3147 NewEntry
.NumMatchedMemRefs
= MatchedMemRefs
.size();
3148 NewEntry
.InputChain
= InputChain
;
3149 NewEntry
.InputGlue
= InputGlue
;
3150 NewEntry
.HasChainNodesMatched
= !ChainNodesMatched
.empty();
3151 MatchScopes
.push_back(NewEntry
);
3154 case OPC_RecordNode
: {
3155 // Remember this node, it may end up being an operand in the pattern.
3156 SDNode
*Parent
= nullptr;
3157 if (NodeStack
.size() > 1)
3158 Parent
= NodeStack
[NodeStack
.size()-2].getNode();
3159 RecordedNodes
.push_back(std::make_pair(N
, Parent
));
3163 case OPC_RecordChild0
: case OPC_RecordChild1
:
3164 case OPC_RecordChild2
: case OPC_RecordChild3
:
3165 case OPC_RecordChild4
: case OPC_RecordChild5
:
3166 case OPC_RecordChild6
: case OPC_RecordChild7
: {
3167 unsigned ChildNo
= Opcode
-OPC_RecordChild0
;
3168 if (ChildNo
>= N
.getNumOperands())
3169 break; // Match fails if out of range child #.
3171 RecordedNodes
.push_back(std::make_pair(N
->getOperand(ChildNo
),
3175 case OPC_RecordMemRef
:
3176 if (auto *MN
= dyn_cast
<MemSDNode
>(N
))
3177 MatchedMemRefs
.push_back(MN
->getMemOperand());
3179 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N
->dump(CurDAG
);
3185 case OPC_CaptureGlueInput
:
3186 // If the current node has an input glue, capture it in InputGlue.
3187 if (N
->getNumOperands() != 0 &&
3188 N
->getOperand(N
->getNumOperands()-1).getValueType() == MVT::Glue
)
3189 InputGlue
= N
->getOperand(N
->getNumOperands()-1);
3192 case OPC_MoveChild
: {
3193 unsigned ChildNo
= MatcherTable
[MatcherIndex
++];
3194 if (ChildNo
>= N
.getNumOperands())
3195 break; // Match fails if out of range child #.
3196 N
= N
.getOperand(ChildNo
);
3197 NodeStack
.push_back(N
);
3201 case OPC_MoveChild0
: case OPC_MoveChild1
:
3202 case OPC_MoveChild2
: case OPC_MoveChild3
:
3203 case OPC_MoveChild4
: case OPC_MoveChild5
:
3204 case OPC_MoveChild6
: case OPC_MoveChild7
: {
3205 unsigned ChildNo
= Opcode
-OPC_MoveChild0
;
3206 if (ChildNo
>= N
.getNumOperands())
3207 break; // Match fails if out of range child #.
3208 N
= N
.getOperand(ChildNo
);
3209 NodeStack
.push_back(N
);
3213 case OPC_MoveParent
:
3214 // Pop the current node off the NodeStack.
3215 NodeStack
.pop_back();
3216 assert(!NodeStack
.empty() && "Node stack imbalance!");
3217 N
= NodeStack
.back();
3221 if (!::CheckSame(MatcherTable
, MatcherIndex
, N
, RecordedNodes
)) break;
3224 case OPC_CheckChild0Same
: case OPC_CheckChild1Same
:
3225 case OPC_CheckChild2Same
: case OPC_CheckChild3Same
:
3226 if (!::CheckChildSame(MatcherTable
, MatcherIndex
, N
, RecordedNodes
,
3227 Opcode
-OPC_CheckChild0Same
))
3231 case OPC_CheckPatternPredicate
:
3232 if (!::CheckPatternPredicate(MatcherTable
, MatcherIndex
, *this)) break;
3234 case OPC_CheckPredicate
:
3235 if (!::CheckNodePredicate(MatcherTable
, MatcherIndex
, *this,
3239 case OPC_CheckPredicateWithOperands
: {
3240 unsigned OpNum
= MatcherTable
[MatcherIndex
++];
3241 SmallVector
<SDValue
, 8> Operands
;
3243 for (unsigned i
= 0; i
< OpNum
; ++i
)
3244 Operands
.push_back(RecordedNodes
[MatcherTable
[MatcherIndex
++]].first
);
3246 unsigned PredNo
= MatcherTable
[MatcherIndex
++];
3247 if (!CheckNodePredicateWithOperands(N
.getNode(), PredNo
, Operands
))
3251 case OPC_CheckComplexPat
: {
3252 unsigned CPNum
= MatcherTable
[MatcherIndex
++];
3253 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3254 assert(RecNo
< RecordedNodes
.size() && "Invalid CheckComplexPat");
3256 // If target can modify DAG during matching, keep the matching state
3258 std::unique_ptr
<MatchStateUpdater
> MSU
;
3259 if (ComplexPatternFuncMutatesDAG())
3260 MSU
.reset(new MatchStateUpdater(*CurDAG
, &NodeToMatch
, RecordedNodes
,
3263 if (!CheckComplexPattern(NodeToMatch
, RecordedNodes
[RecNo
].second
,
3264 RecordedNodes
[RecNo
].first
, CPNum
,
3269 case OPC_CheckOpcode
:
3270 if (!::CheckOpcode(MatcherTable
, MatcherIndex
, N
.getNode())) break;
3274 if (!::CheckType(MatcherTable
, MatcherIndex
, N
, TLI
,
3275 CurDAG
->getDataLayout()))
3279 case OPC_CheckTypeRes
: {
3280 unsigned Res
= MatcherTable
[MatcherIndex
++];
3281 if (!::CheckType(MatcherTable
, MatcherIndex
, N
.getValue(Res
), TLI
,
3282 CurDAG
->getDataLayout()))
3287 case OPC_SwitchOpcode
: {
3288 unsigned CurNodeOpcode
= N
.getOpcode();
3289 unsigned SwitchStart
= MatcherIndex
-1; (void)SwitchStart
;
3292 // Get the size of this case.
3293 CaseSize
= MatcherTable
[MatcherIndex
++];
3295 CaseSize
= GetVBR(CaseSize
, MatcherTable
, MatcherIndex
);
3296 if (CaseSize
== 0) break;
3298 uint16_t Opc
= MatcherTable
[MatcherIndex
++];
3299 Opc
|= (unsigned short)MatcherTable
[MatcherIndex
++] << 8;
3301 // If the opcode matches, then we will execute this case.
3302 if (CurNodeOpcode
== Opc
)
3305 // Otherwise, skip over this case.
3306 MatcherIndex
+= CaseSize
;
3309 // If no cases matched, bail out.
3310 if (CaseSize
== 0) break;
3312 // Otherwise, execute the case we found.
3313 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
<< " to "
3314 << MatcherIndex
<< "\n");
3318 case OPC_SwitchType
: {
3319 MVT CurNodeVT
= N
.getSimpleValueType();
3320 unsigned SwitchStart
= MatcherIndex
-1; (void)SwitchStart
;
3323 // Get the size of this case.
3324 CaseSize
= MatcherTable
[MatcherIndex
++];
3326 CaseSize
= GetVBR(CaseSize
, MatcherTable
, MatcherIndex
);
3327 if (CaseSize
== 0) break;
3329 MVT CaseVT
= (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
3330 if (CaseVT
== MVT::iPTR
)
3331 CaseVT
= TLI
->getPointerTy(CurDAG
->getDataLayout());
3333 // If the VT matches, then we will execute this case.
3334 if (CurNodeVT
== CaseVT
)
3337 // Otherwise, skip over this case.
3338 MatcherIndex
+= CaseSize
;
3341 // If no cases matched, bail out.
3342 if (CaseSize
== 0) break;
3344 // Otherwise, execute the case we found.
3345 LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT
).getEVTString()
3346 << "] from " << SwitchStart
<< " to " << MatcherIndex
3350 case OPC_CheckChild0Type
: case OPC_CheckChild1Type
:
3351 case OPC_CheckChild2Type
: case OPC_CheckChild3Type
:
3352 case OPC_CheckChild4Type
: case OPC_CheckChild5Type
:
3353 case OPC_CheckChild6Type
: case OPC_CheckChild7Type
:
3354 if (!::CheckChildType(MatcherTable
, MatcherIndex
, N
, TLI
,
3355 CurDAG
->getDataLayout(),
3356 Opcode
- OPC_CheckChild0Type
))
3359 case OPC_CheckCondCode
:
3360 if (!::CheckCondCode(MatcherTable
, MatcherIndex
, N
)) break;
3362 case OPC_CheckValueType
:
3363 if (!::CheckValueType(MatcherTable
, MatcherIndex
, N
, TLI
,
3364 CurDAG
->getDataLayout()))
3367 case OPC_CheckInteger
:
3368 if (!::CheckInteger(MatcherTable
, MatcherIndex
, N
)) break;
3370 case OPC_CheckChild0Integer
: case OPC_CheckChild1Integer
:
3371 case OPC_CheckChild2Integer
: case OPC_CheckChild3Integer
:
3372 case OPC_CheckChild4Integer
:
3373 if (!::CheckChildInteger(MatcherTable
, MatcherIndex
, N
,
3374 Opcode
-OPC_CheckChild0Integer
)) break;
3376 case OPC_CheckAndImm
:
3377 if (!::CheckAndImm(MatcherTable
, MatcherIndex
, N
, *this)) break;
3379 case OPC_CheckOrImm
:
3380 if (!::CheckOrImm(MatcherTable
, MatcherIndex
, N
, *this)) break;
3383 case OPC_CheckFoldableChainNode
: {
3384 assert(NodeStack
.size() != 1 && "No parent node");
3385 // Verify that all intermediate nodes between the root and this one have
3387 bool HasMultipleUses
= false;
3388 for (unsigned i
= 1, e
= NodeStack
.size()-1; i
!= e
; ++i
)
3389 if (!NodeStack
[i
].getNode()->hasOneUse()) {
3390 HasMultipleUses
= true;
3393 if (HasMultipleUses
) break;
3395 // Check to see that the target thinks this is profitable to fold and that
3396 // we can fold it without inducing cycles in the graph.
3397 if (!IsProfitableToFold(N
, NodeStack
[NodeStack
.size()-2].getNode(),
3399 !IsLegalToFold(N
, NodeStack
[NodeStack
.size()-2].getNode(),
3400 NodeToMatch
, OptLevel
,
3401 true/*We validate our own chains*/))
3406 case OPC_EmitInteger
: {
3407 MVT::SimpleValueType VT
=
3408 (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
3409 int64_t Val
= MatcherTable
[MatcherIndex
++];
3411 Val
= GetVBR(Val
, MatcherTable
, MatcherIndex
);
3412 RecordedNodes
.push_back(std::pair
<SDValue
, SDNode
*>(
3413 CurDAG
->getTargetConstant(Val
, SDLoc(NodeToMatch
),
3417 case OPC_EmitRegister
: {
3418 MVT::SimpleValueType VT
=
3419 (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
3420 unsigned RegNo
= MatcherTable
[MatcherIndex
++];
3421 RecordedNodes
.push_back(std::pair
<SDValue
, SDNode
*>(
3422 CurDAG
->getRegister(RegNo
, VT
), nullptr));
3425 case OPC_EmitRegister2
: {
3426 // For targets w/ more than 256 register names, the register enum
3427 // values are stored in two bytes in the matcher table (just like
3429 MVT::SimpleValueType VT
=
3430 (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
3431 unsigned RegNo
= MatcherTable
[MatcherIndex
++];
3432 RegNo
|= MatcherTable
[MatcherIndex
++] << 8;
3433 RecordedNodes
.push_back(std::pair
<SDValue
, SDNode
*>(
3434 CurDAG
->getRegister(RegNo
, VT
), nullptr));
3438 case OPC_EmitConvertToTarget
: {
3439 // Convert from IMM/FPIMM to target version.
3440 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3441 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitConvertToTarget");
3442 SDValue Imm
= RecordedNodes
[RecNo
].first
;
3444 if (Imm
->getOpcode() == ISD::Constant
) {
3445 const ConstantInt
*Val
=cast
<ConstantSDNode
>(Imm
)->getConstantIntValue();
3446 Imm
= CurDAG
->getTargetConstant(*Val
, SDLoc(NodeToMatch
),
3447 Imm
.getValueType());
3448 } else if (Imm
->getOpcode() == ISD::ConstantFP
) {
3449 const ConstantFP
*Val
=cast
<ConstantFPSDNode
>(Imm
)->getConstantFPValue();
3450 Imm
= CurDAG
->getTargetConstantFP(*Val
, SDLoc(NodeToMatch
),
3451 Imm
.getValueType());
3454 RecordedNodes
.push_back(std::make_pair(Imm
, RecordedNodes
[RecNo
].second
));
3458 case OPC_EmitMergeInputChains1_0
: // OPC_EmitMergeInputChains, 1, 0
3459 case OPC_EmitMergeInputChains1_1
: // OPC_EmitMergeInputChains, 1, 1
3460 case OPC_EmitMergeInputChains1_2
: { // OPC_EmitMergeInputChains, 1, 2
3461 // These are space-optimized forms of OPC_EmitMergeInputChains.
3462 assert(!InputChain
.getNode() &&
3463 "EmitMergeInputChains should be the first chain producing node");
3464 assert(ChainNodesMatched
.empty() &&
3465 "Should only have one EmitMergeInputChains per match");
3467 // Read all of the chained nodes.
3468 unsigned RecNo
= Opcode
- OPC_EmitMergeInputChains1_0
;
3469 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitMergeInputChains");
3470 ChainNodesMatched
.push_back(RecordedNodes
[RecNo
].first
.getNode());
3472 // FIXME: What if other value results of the node have uses not matched
3474 if (ChainNodesMatched
.back() != NodeToMatch
&&
3475 !RecordedNodes
[RecNo
].first
.hasOneUse()) {
3476 ChainNodesMatched
.clear();
3480 // Merge the input chains if they are not intra-pattern references.
3481 InputChain
= HandleMergeInputChains(ChainNodesMatched
, CurDAG
);
3483 if (!InputChain
.getNode())
3484 break; // Failed to merge.
3488 case OPC_EmitMergeInputChains
: {
3489 assert(!InputChain
.getNode() &&
3490 "EmitMergeInputChains should be the first chain producing node");
3491 // This node gets a list of nodes we matched in the input that have
3492 // chains. We want to token factor all of the input chains to these nodes
3493 // together. However, if any of the input chains is actually one of the
3494 // nodes matched in this pattern, then we have an intra-match reference.
3495 // Ignore these because the newly token factored chain should not refer to
3497 unsigned NumChains
= MatcherTable
[MatcherIndex
++];
3498 assert(NumChains
!= 0 && "Can't TF zero chains");
3500 assert(ChainNodesMatched
.empty() &&
3501 "Should only have one EmitMergeInputChains per match");
3503 // Read all of the chained nodes.
3504 for (unsigned i
= 0; i
!= NumChains
; ++i
) {
3505 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3506 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitMergeInputChains");
3507 ChainNodesMatched
.push_back(RecordedNodes
[RecNo
].first
.getNode());
3509 // FIXME: What if other value results of the node have uses not matched
3511 if (ChainNodesMatched
.back() != NodeToMatch
&&
3512 !RecordedNodes
[RecNo
].first
.hasOneUse()) {
3513 ChainNodesMatched
.clear();
3518 // If the inner loop broke out, the match fails.
3519 if (ChainNodesMatched
.empty())
3522 // Merge the input chains if they are not intra-pattern references.
3523 InputChain
= HandleMergeInputChains(ChainNodesMatched
, CurDAG
);
3525 if (!InputChain
.getNode())
3526 break; // Failed to merge.
3531 case OPC_EmitCopyToReg
: {
3532 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3533 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitCopyToReg");
3534 unsigned DestPhysReg
= MatcherTable
[MatcherIndex
++];
3536 if (!InputChain
.getNode())
3537 InputChain
= CurDAG
->getEntryNode();
3539 InputChain
= CurDAG
->getCopyToReg(InputChain
, SDLoc(NodeToMatch
),
3540 DestPhysReg
, RecordedNodes
[RecNo
].first
,
3543 InputGlue
= InputChain
.getValue(1);
3547 case OPC_EmitNodeXForm
: {
3548 unsigned XFormNo
= MatcherTable
[MatcherIndex
++];
3549 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3550 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitNodeXForm");
3551 SDValue Res
= RunSDNodeXForm(RecordedNodes
[RecNo
].first
, XFormNo
);
3552 RecordedNodes
.push_back(std::pair
<SDValue
,SDNode
*>(Res
, nullptr));
3555 case OPC_Coverage
: {
3556 // This is emitted right before MorphNode/EmitNode.
3557 // So it should be safe to assume that this node has been selected
3558 unsigned index
= MatcherTable
[MatcherIndex
++];
3559 index
|= (MatcherTable
[MatcherIndex
++] << 8);
3560 dbgs() << "COVERED: " << getPatternForIndex(index
) << "\n";
3561 dbgs() << "INCLUDED: " << getIncludePathForIndex(index
) << "\n";
3565 case OPC_EmitNode
: case OPC_MorphNodeTo
:
3566 case OPC_EmitNode0
: case OPC_EmitNode1
: case OPC_EmitNode2
:
3567 case OPC_MorphNodeTo0
: case OPC_MorphNodeTo1
: case OPC_MorphNodeTo2
: {
3568 uint16_t TargetOpc
= MatcherTable
[MatcherIndex
++];
3569 TargetOpc
|= (unsigned short)MatcherTable
[MatcherIndex
++] << 8;
3570 unsigned EmitNodeInfo
= MatcherTable
[MatcherIndex
++];
3571 // Get the result VT list.
3573 // If this is one of the compressed forms, get the number of VTs based
3574 // on the Opcode. Otherwise read the next byte from the table.
3575 if (Opcode
>= OPC_MorphNodeTo0
&& Opcode
<= OPC_MorphNodeTo2
)
3576 NumVTs
= Opcode
- OPC_MorphNodeTo0
;
3577 else if (Opcode
>= OPC_EmitNode0
&& Opcode
<= OPC_EmitNode2
)
3578 NumVTs
= Opcode
- OPC_EmitNode0
;
3580 NumVTs
= MatcherTable
[MatcherIndex
++];
3581 SmallVector
<EVT
, 4> VTs
;
3582 for (unsigned i
= 0; i
!= NumVTs
; ++i
) {
3583 MVT::SimpleValueType VT
=
3584 (MVT::SimpleValueType
)MatcherTable
[MatcherIndex
++];
3585 if (VT
== MVT::iPTR
)
3586 VT
= TLI
->getPointerTy(CurDAG
->getDataLayout()).SimpleTy
;
3590 if (EmitNodeInfo
& OPFL_Chain
)
3591 VTs
.push_back(MVT::Other
);
3592 if (EmitNodeInfo
& OPFL_GlueOutput
)
3593 VTs
.push_back(MVT::Glue
);
3595 // This is hot code, so optimize the two most common cases of 1 and 2
3598 if (VTs
.size() == 1)
3599 VTList
= CurDAG
->getVTList(VTs
[0]);
3600 else if (VTs
.size() == 2)
3601 VTList
= CurDAG
->getVTList(VTs
[0], VTs
[1]);
3603 VTList
= CurDAG
->getVTList(VTs
);
3605 // Get the operand list.
3606 unsigned NumOps
= MatcherTable
[MatcherIndex
++];
3607 SmallVector
<SDValue
, 8> Ops
;
3608 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
3609 unsigned RecNo
= MatcherTable
[MatcherIndex
++];
3611 RecNo
= GetVBR(RecNo
, MatcherTable
, MatcherIndex
);
3613 assert(RecNo
< RecordedNodes
.size() && "Invalid EmitNode");
3614 Ops
.push_back(RecordedNodes
[RecNo
].first
);
3617 // If there are variadic operands to add, handle them now.
3618 if (EmitNodeInfo
& OPFL_VariadicInfo
) {
3619 // Determine the start index to copy from.
3620 unsigned FirstOpToCopy
= getNumFixedFromVariadicInfo(EmitNodeInfo
);
3621 FirstOpToCopy
+= (EmitNodeInfo
& OPFL_Chain
) ? 1 : 0;
3622 assert(NodeToMatch
->getNumOperands() >= FirstOpToCopy
&&
3623 "Invalid variadic node");
3624 // Copy all of the variadic operands, not including a potential glue
3626 for (unsigned i
= FirstOpToCopy
, e
= NodeToMatch
->getNumOperands();
3628 SDValue V
= NodeToMatch
->getOperand(i
);
3629 if (V
.getValueType() == MVT::Glue
) break;
3634 // If this has chain/glue inputs, add them.
3635 if (EmitNodeInfo
& OPFL_Chain
)
3636 Ops
.push_back(InputChain
);
3637 if ((EmitNodeInfo
& OPFL_GlueInput
) && InputGlue
.getNode() != nullptr)
3638 Ops
.push_back(InputGlue
);
3641 MachineSDNode
*Res
= nullptr;
3642 bool IsMorphNodeTo
= Opcode
== OPC_MorphNodeTo
||
3643 (Opcode
>= OPC_MorphNodeTo0
&& Opcode
<= OPC_MorphNodeTo2
);
3644 if (!IsMorphNodeTo
) {
3645 // If this is a normal EmitNode command, just create the new node and
3646 // add the results to the RecordedNodes list.
3647 Res
= CurDAG
->getMachineNode(TargetOpc
, SDLoc(NodeToMatch
),
3650 // Add all the non-glue/non-chain results to the RecordedNodes list.
3651 for (unsigned i
= 0, e
= VTs
.size(); i
!= e
; ++i
) {
3652 if (VTs
[i
] == MVT::Other
|| VTs
[i
] == MVT::Glue
) break;
3653 RecordedNodes
.push_back(std::pair
<SDValue
,SDNode
*>(SDValue(Res
, i
),
3657 assert(NodeToMatch
->getOpcode() != ISD::DELETED_NODE
&&
3658 "NodeToMatch was removed partway through selection");
3659 SelectionDAG::DAGNodeDeletedListener
NDL(*CurDAG
, [&](SDNode
*N
,
3661 CurDAG
->salvageDebugInfo(*N
);
3662 auto &Chain
= ChainNodesMatched
;
3663 assert((!E
|| !is_contained(Chain
, N
)) &&
3664 "Chain node replaced during MorphNode");
3665 Chain
.erase(std::remove(Chain
.begin(), Chain
.end(), N
), Chain
.end());
3667 Res
= cast
<MachineSDNode
>(MorphNode(NodeToMatch
, TargetOpc
, VTList
,
3668 Ops
, EmitNodeInfo
));
3671 // If the node had chain/glue results, update our notion of the current
3673 if (EmitNodeInfo
& OPFL_GlueOutput
) {
3674 InputGlue
= SDValue(Res
, VTs
.size()-1);
3675 if (EmitNodeInfo
& OPFL_Chain
)
3676 InputChain
= SDValue(Res
, VTs
.size()-2);
3677 } else if (EmitNodeInfo
& OPFL_Chain
)
3678 InputChain
= SDValue(Res
, VTs
.size()-1);
3680 // If the OPFL_MemRefs glue is set on this node, slap all of the
3681 // accumulated memrefs onto it.
3683 // FIXME: This is vastly incorrect for patterns with multiple outputs
3684 // instructions that access memory and for ComplexPatterns that match
3686 if (EmitNodeInfo
& OPFL_MemRefs
) {
3687 // Only attach load or store memory operands if the generated
3688 // instruction may load or store.
3689 const MCInstrDesc
&MCID
= TII
->get(TargetOpc
);
3690 bool mayLoad
= MCID
.mayLoad();
3691 bool mayStore
= MCID
.mayStore();
3693 // We expect to have relatively few of these so just filter them into a
3694 // temporary buffer so that we can easily add them to the instruction.
3695 SmallVector
<MachineMemOperand
*, 4> FilteredMemRefs
;
3696 for (MachineMemOperand
*MMO
: MatchedMemRefs
) {
3697 if (MMO
->isLoad()) {
3699 FilteredMemRefs
.push_back(MMO
);
3700 } else if (MMO
->isStore()) {
3702 FilteredMemRefs
.push_back(MMO
);
3704 FilteredMemRefs
.push_back(MMO
);
3708 CurDAG
->setNodeMemRefs(Res
, FilteredMemRefs
);
3711 LLVM_DEBUG(if (!MatchedMemRefs
.empty() && Res
->memoperands_empty()) dbgs()
3712 << " Dropping mem operands\n";
3713 dbgs() << " " << (IsMorphNodeTo
? "Morphed" : "Created")
3715 Res
->dump(CurDAG
););
3717 // If this was a MorphNodeTo then we're completely done!
3718 if (IsMorphNodeTo
) {
3719 // Update chain uses.
3720 UpdateChains(Res
, InputChain
, ChainNodesMatched
, true);
3726 case OPC_CompleteMatch
: {
3727 // The match has been completed, and any new nodes (if any) have been
3728 // created. Patch up references to the matched dag to use the newly
3730 unsigned NumResults
= MatcherTable
[MatcherIndex
++];
3732 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3733 unsigned ResSlot
= MatcherTable
[MatcherIndex
++];
3735 ResSlot
= GetVBR(ResSlot
, MatcherTable
, MatcherIndex
);
3737 assert(ResSlot
< RecordedNodes
.size() && "Invalid CompleteMatch");
3738 SDValue Res
= RecordedNodes
[ResSlot
].first
;
3740 assert(i
< NodeToMatch
->getNumValues() &&
3741 NodeToMatch
->getValueType(i
) != MVT::Other
&&
3742 NodeToMatch
->getValueType(i
) != MVT::Glue
&&
3743 "Invalid number of results to complete!");
3744 assert((NodeToMatch
->getValueType(i
) == Res
.getValueType() ||
3745 NodeToMatch
->getValueType(i
) == MVT::iPTR
||
3746 Res
.getValueType() == MVT::iPTR
||
3747 NodeToMatch
->getValueType(i
).getSizeInBits() ==
3748 Res
.getValueSizeInBits()) &&
3749 "invalid replacement");
3750 ReplaceUses(SDValue(NodeToMatch
, i
), Res
);
3753 // Update chain uses.
3754 UpdateChains(NodeToMatch
, InputChain
, ChainNodesMatched
, false);
3756 // If the root node defines glue, we need to update it to the glue result.
3757 // TODO: This never happens in our tests and I think it can be removed /
3758 // replaced with an assert, but if we do it this the way the change is
3760 if (NodeToMatch
->getValueType(NodeToMatch
->getNumValues() - 1) ==
3762 InputGlue
.getNode())
3763 ReplaceUses(SDValue(NodeToMatch
, NodeToMatch
->getNumValues() - 1),
3766 assert(NodeToMatch
->use_empty() &&
3767 "Didn't replace all uses of the node?");
3768 CurDAG
->RemoveDeadNode(NodeToMatch
);
3774 // If the code reached this point, then the match failed. See if there is
3775 // another child to try in the current 'Scope', otherwise pop it until we
3776 // find a case to check.
3777 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
3779 ++NumDAGIselRetries
;
3781 if (MatchScopes
.empty()) {
3782 CannotYetSelect(NodeToMatch
);
3786 // Restore the interpreter state back to the point where the scope was
3788 MatchScope
&LastScope
= MatchScopes
.back();
3789 RecordedNodes
.resize(LastScope
.NumRecordedNodes
);
3791 NodeStack
.append(LastScope
.NodeStack
.begin(), LastScope
.NodeStack
.end());
3792 N
= NodeStack
.back();
3794 if (LastScope
.NumMatchedMemRefs
!= MatchedMemRefs
.size())
3795 MatchedMemRefs
.resize(LastScope
.NumMatchedMemRefs
);
3796 MatcherIndex
= LastScope
.FailIndex
;
3798 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex
<< "\n");
3800 InputChain
= LastScope
.InputChain
;
3801 InputGlue
= LastScope
.InputGlue
;
3802 if (!LastScope
.HasChainNodesMatched
)
3803 ChainNodesMatched
.clear();
3805 // Check to see what the offset is at the new MatcherIndex. If it is zero
3806 // we have reached the end of this scope, otherwise we have another child
3807 // in the current scope to try.
3808 unsigned NumToSkip
= MatcherTable
[MatcherIndex
++];
3809 if (NumToSkip
& 128)
3810 NumToSkip
= GetVBR(NumToSkip
, MatcherTable
, MatcherIndex
);
3812 // If we have another child in this scope to match, update FailIndex and
3814 if (NumToSkip
!= 0) {
3815 LastScope
.FailIndex
= MatcherIndex
+NumToSkip
;
3819 // End of this scope, pop it and try the next child in the containing
3821 MatchScopes
.pop_back();
3826 bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode
*N
) const {
3827 assert(N
->getOpcode() == ISD::OR
&& "Unexpected opcode");
3828 auto *C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
3832 // Detect when "or" is used to add an offset to a stack object.
3833 if (auto *FN
= dyn_cast
<FrameIndexSDNode
>(N
->getOperand(0))) {
3834 MachineFrameInfo
&MFI
= MF
->getFrameInfo();
3835 unsigned A
= MFI
.getObjectAlignment(FN
->getIndex());
3836 assert(isPowerOf2_32(A
) && "Unexpected alignment");
3837 int32_t Off
= C
->getSExtValue();
3838 // If the alleged offset fits in the zero bits guaranteed by
3839 // the alignment, then this or is really an add.
3840 return (Off
>= 0) && (((A
- 1) & Off
) == unsigned(Off
));
3845 void SelectionDAGISel::CannotYetSelect(SDNode
*N
) {
3847 raw_string_ostream
Msg(msg
);
3848 Msg
<< "Cannot select: ";
3850 if (N
->getOpcode() != ISD::INTRINSIC_W_CHAIN
&&
3851 N
->getOpcode() != ISD::INTRINSIC_WO_CHAIN
&&
3852 N
->getOpcode() != ISD::INTRINSIC_VOID
) {
3853 N
->printrFull(Msg
, CurDAG
);
3854 Msg
<< "\nIn function: " << MF
->getName();
3856 bool HasInputChain
= N
->getOperand(0).getValueType() == MVT::Other
;
3858 cast
<ConstantSDNode
>(N
->getOperand(HasInputChain
))->getZExtValue();
3859 if (iid
< Intrinsic::num_intrinsics
)
3860 Msg
<< "intrinsic %" << Intrinsic::getName((Intrinsic::ID
)iid
, None
);
3861 else if (const TargetIntrinsicInfo
*TII
= TM
.getIntrinsicInfo())
3862 Msg
<< "target intrinsic %" << TII
->getName(iid
);
3864 Msg
<< "unknown intrinsic #" << iid
;
3866 report_fatal_error(Msg
.str());
3869 char SelectionDAGISel::ID
= 0;