1 //===- SelectionDAGBuilder.h - Selection-DAG building -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 14 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 15 16 #include "StatepointLowering.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/MapVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/CodeGen/ISDOpcodes.h" 23 #include "llvm/CodeGen/SelectionDAGNodes.h" 24 #include "llvm/CodeGen/SwitchLoweringUtils.h" 25 #include "llvm/CodeGen/TargetLowering.h" 26 #include "llvm/CodeGen/ValueTypes.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Statepoint.h" 30 #include "llvm/Support/BranchProbability.h" 31 #include "llvm/Support/CodeGen.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MachineValueType.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstdint> 37 #include <utility> 38 #include <vector> 39 40 namespace llvm { 41 42 class AllocaInst; 43 class AtomicCmpXchgInst; 44 class AtomicRMWInst; 45 class BasicBlock; 46 class BranchInst; 47 class CallInst; 48 class CallBrInst; 49 class CatchPadInst; 50 class CatchReturnInst; 51 class CatchSwitchInst; 52 class CleanupPadInst; 53 class CleanupReturnInst; 54 class Constant; 55 class ConstrainedFPIntrinsic; 56 class DbgValueInst; 57 class DataLayout; 58 class DIExpression; 59 class DILocalVariable; 60 class DILocation; 61 class FenceInst; 62 class FunctionLoweringInfo; 63 class GCFunctionInfo; 64 class GCRelocateInst; 65 class GCResultInst; 66 class IndirectBrInst; 67 class InvokeInst; 68 class LandingPadInst; 69 class LLVMContext; 70 class LoadInst; 71 class MachineBasicBlock; 72 class PHINode; 73 class ResumeInst; 74 class ReturnInst; 75 class SDDbgValue; 76 class SelectionDAG; 77 class StoreInst; 78 class SwiftErrorValueTracking; 79 class SwitchInst; 80 class TargetLibraryInfo; 81 class TargetMachine; 82 class Type; 83 class VAArgInst; 84 class UnreachableInst; 85 class Use; 86 class User; 87 class Value; 88 89 //===----------------------------------------------------------------------===// 90 /// SelectionDAGBuilder - This is the common target-independent lowering 91 /// implementation that is parameterized by a TargetLowering object. 92 /// 93 class SelectionDAGBuilder { 94 /// The current instruction being visited. 95 const Instruction *CurInst = nullptr; 96 97 DenseMap<const Value*, SDValue> NodeMap; 98 99 /// Maps argument value for unused arguments. This is used 100 /// to preserve debug information for incoming arguments. 101 DenseMap<const Value*, SDValue> UnusedArgNodeMap; 102 103 /// Helper type for DanglingDebugInfoMap. 104 class DanglingDebugInfo { 105 const DbgValueInst* DI = nullptr; 106 DebugLoc dl; 107 unsigned SDNodeOrder = 0; 108 109 public: 110 DanglingDebugInfo() = default; 111 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) 112 : DI(di), dl(std::move(DL)), SDNodeOrder(SDNO) {} 113 114 const DbgValueInst* getDI() { return DI; } 115 DebugLoc getdl() { return dl; } 116 unsigned getSDNodeOrder() { return SDNodeOrder; } 117 }; 118 119 /// Helper type for DanglingDebugInfoMap. 120 typedef std::vector<DanglingDebugInfo> DanglingDebugInfoVector; 121 122 /// Keeps track of dbg_values for which we have not yet seen the referent. 123 /// We defer handling these until we do see it. 124 MapVector<const Value*, DanglingDebugInfoVector> DanglingDebugInfoMap; 125 126 public: 127 /// Loads are not emitted to the program immediately. We bunch them up and 128 /// then emit token factor nodes when possible. This allows us to get simple 129 /// disambiguation between loads without worrying about alias analysis. 130 SmallVector<SDValue, 8> PendingLoads; 131 132 /// State used while lowering a statepoint sequence (gc_statepoint, 133 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details. 134 StatepointLoweringState StatepointLowering; 135 136 private: 137 /// CopyToReg nodes that copy values to virtual registers for export to other 138 /// blocks need to be emitted before any terminator instruction, but they have 139 /// no other ordering requirements. We bunch them up and the emit a single 140 /// tokenfactor for them just before terminator instructions. 141 SmallVector<SDValue, 8> PendingExports; 142 143 /// Similar to loads, nodes corresponding to constrained FP intrinsics are 144 /// bunched up and emitted when necessary. These can be moved across each 145 /// other and any (normal) memory operation (load or store), but not across 146 /// calls or instructions having unspecified side effects. As a special 147 /// case, constrained FP intrinsics using fpexcept.strict may not be deleted 148 /// even if otherwise unused, so they need to be chained before any 149 /// terminator instruction (like PendingExports). We track the latter 150 /// set of nodes in a separate list. 151 SmallVector<SDValue, 8> PendingConstrainedFP; 152 SmallVector<SDValue, 8> PendingConstrainedFPStrict; 153 154 /// Update root to include all chains from the Pending list. 155 SDValue updateRoot(SmallVectorImpl<SDValue> &Pending); 156 157 /// A unique monotonically increasing number used to order the SDNodes we 158 /// create. 159 unsigned SDNodeOrder; 160 161 /// Determine the rank by weight of CC in [First,Last]. If CC has more weight 162 /// than each cluster in the range, its rank is 0. 163 unsigned caseClusterRank(const SwitchCG::CaseCluster &CC, 164 SwitchCG::CaseClusterIt First, 165 SwitchCG::CaseClusterIt Last); 166 167 /// Emit comparison and split W into two subtrees. 168 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList, 169 const SwitchCG::SwitchWorkListItem &W, Value *Cond, 170 MachineBasicBlock *SwitchMBB); 171 172 /// Lower W. 173 void lowerWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond, 174 MachineBasicBlock *SwitchMBB, 175 MachineBasicBlock *DefaultMBB); 176 177 /// Peel the top probability case if it exceeds the threshold 178 MachineBasicBlock * 179 peelDominantCaseCluster(const SwitchInst &SI, 180 SwitchCG::CaseClusterVector &Clusters, 181 BranchProbability &PeeledCaseProb); 182 183 /// A class which encapsulates all of the information needed to generate a 184 /// stack protector check and signals to isel via its state being initialized 185 /// that a stack protector needs to be generated. 186 /// 187 /// *NOTE* The following is a high level documentation of SelectionDAG Stack 188 /// Protector Generation. The reason that it is placed here is for a lack of 189 /// other good places to stick it. 190 /// 191 /// High Level Overview of SelectionDAG Stack Protector Generation: 192 /// 193 /// Previously, generation of stack protectors was done exclusively in the 194 /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated 195 /// splitting basic blocks at the IR level to create the success/failure basic 196 /// blocks in the tail of the basic block in question. As a result of this, 197 /// calls that would have qualified for the sibling call optimization were no 198 /// longer eligible for optimization since said calls were no longer right in 199 /// the "tail position" (i.e. the immediate predecessor of a ReturnInst 200 /// instruction). 201 /// 202 /// Then it was noticed that since the sibling call optimization causes the 203 /// callee to reuse the caller's stack, if we could delay the generation of 204 /// the stack protector check until later in CodeGen after the sibling call 205 /// decision was made, we get both the tail call optimization and the stack 206 /// protector check! 207 /// 208 /// A few goals in solving this problem were: 209 /// 210 /// 1. Preserve the architecture independence of stack protector generation. 211 /// 212 /// 2. Preserve the normal IR level stack protector check for platforms like 213 /// OpenBSD for which we support platform-specific stack protector 214 /// generation. 215 /// 216 /// The main problem that guided the present solution is that one can not 217 /// solve this problem in an architecture independent manner at the IR level 218 /// only. This is because: 219 /// 220 /// 1. The decision on whether or not to perform a sibling call on certain 221 /// platforms (for instance i386) requires lower level information 222 /// related to available registers that can not be known at the IR level. 223 /// 224 /// 2. Even if the previous point were not true, the decision on whether to 225 /// perform a tail call is done in LowerCallTo in SelectionDAG which 226 /// occurs after the Stack Protector Pass. As a result, one would need to 227 /// put the relevant callinst into the stack protector check success 228 /// basic block (where the return inst is placed) and then move it back 229 /// later at SelectionDAG/MI time before the stack protector check if the 230 /// tail call optimization failed. The MI level option was nixed 231 /// immediately since it would require platform-specific pattern 232 /// matching. The SelectionDAG level option was nixed because 233 /// SelectionDAG only processes one IR level basic block at a time 234 /// implying one could not create a DAG Combine to move the callinst. 235 /// 236 /// To get around this problem a few things were realized: 237 /// 238 /// 1. While one can not handle multiple IR level basic blocks at the 239 /// SelectionDAG Level, one can generate multiple machine basic blocks 240 /// for one IR level basic block. This is how we handle bit tests and 241 /// switches. 242 /// 243 /// 2. At the MI level, tail calls are represented via a special return 244 /// MIInst called "tcreturn". Thus if we know the basic block in which we 245 /// wish to insert the stack protector check, we get the correct behavior 246 /// by always inserting the stack protector check right before the return 247 /// statement. This is a "magical transformation" since no matter where 248 /// the stack protector check intrinsic is, we always insert the stack 249 /// protector check code at the end of the BB. 250 /// 251 /// Given the aforementioned constraints, the following solution was devised: 252 /// 253 /// 1. On platforms that do not support SelectionDAG stack protector check 254 /// generation, allow for the normal IR level stack protector check 255 /// generation to continue. 256 /// 257 /// 2. On platforms that do support SelectionDAG stack protector check 258 /// generation: 259 /// 260 /// a. Use the IR level stack protector pass to decide if a stack 261 /// protector is required/which BB we insert the stack protector check 262 /// in by reusing the logic already therein. If we wish to generate a 263 /// stack protector check in a basic block, we place a special IR 264 /// intrinsic called llvm.stackprotectorcheck right before the BB's 265 /// returninst or if there is a callinst that could potentially be 266 /// sibling call optimized, before the call inst. 267 /// 268 /// b. Then when a BB with said intrinsic is processed, we codegen the BB 269 /// normally via SelectBasicBlock. In said process, when we visit the 270 /// stack protector check, we do not actually emit anything into the 271 /// BB. Instead, we just initialize the stack protector descriptor 272 /// class (which involves stashing information/creating the success 273 /// mbbb and the failure mbb if we have not created one for this 274 /// function yet) and export the guard variable that we are going to 275 /// compare. 276 /// 277 /// c. After we finish selecting the basic block, in FinishBasicBlock if 278 /// the StackProtectorDescriptor attached to the SelectionDAGBuilder is 279 /// initialized, we produce the validation code with one of these 280 /// techniques: 281 /// 1) with a call to a guard check function 282 /// 2) with inlined instrumentation 283 /// 284 /// 1) We insert a call to the check function before the terminator. 285 /// 286 /// 2) We first find a splice point in the parent basic block 287 /// before the terminator and then splice the terminator of said basic 288 /// block into the success basic block. Then we code-gen a new tail for 289 /// the parent basic block consisting of the two loads, the comparison, 290 /// and finally two branches to the success/failure basic blocks. We 291 /// conclude by code-gening the failure basic block if we have not 292 /// code-gened it already (all stack protector checks we generate in 293 /// the same function, use the same failure basic block). 294 class StackProtectorDescriptor { 295 public: 296 StackProtectorDescriptor() = default; 297 298 /// Returns true if all fields of the stack protector descriptor are 299 /// initialized implying that we should/are ready to emit a stack protector. 300 bool shouldEmitStackProtector() const { 301 return ParentMBB && SuccessMBB && FailureMBB; 302 } 303 304 bool shouldEmitFunctionBasedCheckStackProtector() const { 305 return ParentMBB && !SuccessMBB && !FailureMBB; 306 } 307 308 /// Initialize the stack protector descriptor structure for a new basic 309 /// block. 310 void initialize(const BasicBlock *BB, MachineBasicBlock *MBB, 311 bool FunctionBasedInstrumentation) { 312 // Make sure we are not initialized yet. 313 assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is " 314 "already initialized!"); 315 ParentMBB = MBB; 316 if (!FunctionBasedInstrumentation) { 317 SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true); 318 FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB); 319 } 320 } 321 322 /// Reset state that changes when we handle different basic blocks. 323 /// 324 /// This currently includes: 325 /// 326 /// 1. The specific basic block we are generating a 327 /// stack protector for (ParentMBB). 328 /// 329 /// 2. The successor machine basic block that will contain the tail of 330 /// parent mbb after we create the stack protector check (SuccessMBB). This 331 /// BB is visited only on stack protector check success. 332 void resetPerBBState() { 333 ParentMBB = nullptr; 334 SuccessMBB = nullptr; 335 } 336 337 /// Reset state that only changes when we switch functions. 338 /// 339 /// This currently includes: 340 /// 341 /// 1. FailureMBB since we reuse the failure code path for all stack 342 /// protector checks created in an individual function. 343 /// 344 /// 2.The guard variable since the guard variable we are checking against is 345 /// always the same. 346 void resetPerFunctionState() { 347 FailureMBB = nullptr; 348 } 349 350 MachineBasicBlock *getParentMBB() { return ParentMBB; } 351 MachineBasicBlock *getSuccessMBB() { return SuccessMBB; } 352 MachineBasicBlock *getFailureMBB() { return FailureMBB; } 353 354 private: 355 /// The basic block for which we are generating the stack protector. 356 /// 357 /// As a result of stack protector generation, we will splice the 358 /// terminators of this basic block into the successor mbb SuccessMBB and 359 /// replace it with a compare/branch to the successor mbbs 360 /// SuccessMBB/FailureMBB depending on whether or not the stack protector 361 /// was violated. 362 MachineBasicBlock *ParentMBB = nullptr; 363 364 /// A basic block visited on stack protector check success that contains the 365 /// terminators of ParentMBB. 366 MachineBasicBlock *SuccessMBB = nullptr; 367 368 /// This basic block visited on stack protector check failure that will 369 /// contain a call to __stack_chk_fail(). 370 MachineBasicBlock *FailureMBB = nullptr; 371 372 /// Add a successor machine basic block to ParentMBB. If the successor mbb 373 /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic 374 /// block will be created. Assign a large weight if IsLikely is true. 375 MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB, 376 MachineBasicBlock *ParentMBB, 377 bool IsLikely, 378 MachineBasicBlock *SuccMBB = nullptr); 379 }; 380 381 private: 382 const TargetMachine &TM; 383 384 public: 385 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling 386 /// nodes without a corresponding SDNode. 387 static const unsigned LowestSDNodeOrder = 1; 388 389 SelectionDAG &DAG; 390 const DataLayout *DL = nullptr; 391 AliasAnalysis *AA = nullptr; 392 const TargetLibraryInfo *LibInfo; 393 394 class SDAGSwitchLowering : public SwitchCG::SwitchLowering { 395 public: 396 SDAGSwitchLowering(SelectionDAGBuilder *sdb, FunctionLoweringInfo &funcinfo) 397 : SwitchCG::SwitchLowering(funcinfo), SDB(sdb) {} 398 399 virtual void addSuccessorWithProb( 400 MachineBasicBlock *Src, MachineBasicBlock *Dst, 401 BranchProbability Prob = BranchProbability::getUnknown()) override { 402 SDB->addSuccessorWithProb(Src, Dst, Prob); 403 } 404 405 private: 406 SelectionDAGBuilder *SDB; 407 }; 408 409 std::unique_ptr<SDAGSwitchLowering> SL; 410 411 /// A StackProtectorDescriptor structure used to communicate stack protector 412 /// information in between SelectBasicBlock and FinishBasicBlock. 413 StackProtectorDescriptor SPDescriptor; 414 415 // Emit PHI-node-operand constants only once even if used by multiple 416 // PHI nodes. 417 DenseMap<const Constant *, unsigned> ConstantsOut; 418 419 /// Information about the function as a whole. 420 FunctionLoweringInfo &FuncInfo; 421 422 /// Information about the swifterror values used throughout the function. 423 SwiftErrorValueTracking &SwiftError; 424 425 /// Garbage collection metadata for the function. 426 GCFunctionInfo *GFI; 427 428 /// Map a landing pad to the call site indexes. 429 DenseMap<MachineBasicBlock *, SmallVector<unsigned, 4>> LPadToCallSiteMap; 430 431 /// This is set to true if a call in the current block has been translated as 432 /// a tail call. In this case, no subsequent DAG nodes should be created. 433 bool HasTailCall = false; 434 435 LLVMContext *Context; 436 437 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, 438 SwiftErrorValueTracking &swifterror, CodeGenOpt::Level ol) 439 : SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), DAG(dag), 440 SL(std::make_unique<SDAGSwitchLowering>(this, funcinfo)), FuncInfo(funcinfo), 441 SwiftError(swifterror) {} 442 443 void init(GCFunctionInfo *gfi, AliasAnalysis *AA, 444 const TargetLibraryInfo *li); 445 446 /// Clear out the current SelectionDAG and the associated state and prepare 447 /// this SelectionDAGBuilder object to be used for a new block. This doesn't 448 /// clear out information about additional blocks that are needed to complete 449 /// switch lowering or PHI node updating; that information is cleared out as 450 /// it is consumed. 451 void clear(); 452 453 /// Clear the dangling debug information map. This function is separated from 454 /// the clear so that debug information that is dangling in a basic block can 455 /// be properly resolved in a different basic block. This allows the 456 /// SelectionDAG to resolve dangling debug information attached to PHI nodes. 457 void clearDanglingDebugInfo(); 458 459 /// Return the current virtual root of the Selection DAG, flushing any 460 /// PendingLoad items. This must be done before emitting a store or any other 461 /// memory node that may need to be ordered after any prior load instructions. 462 SDValue getMemoryRoot(); 463 464 /// Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) 465 /// items. This must be done before emitting any call other any other node 466 /// that may need to be ordered after FP instructions due to other side 467 /// effects. 468 SDValue getRoot(); 469 470 /// Similar to getRoot, but instead of flushing all the PendingLoad items, 471 /// flush all the PendingExports (and PendingConstrainedFPStrict) items. 472 /// It is necessary to do this before emitting a terminator instruction. 473 SDValue getControlRoot(); 474 475 SDLoc getCurSDLoc() const { 476 return SDLoc(CurInst, SDNodeOrder); 477 } 478 479 DebugLoc getCurDebugLoc() const { 480 return CurInst ? CurInst->getDebugLoc() : DebugLoc(); 481 } 482 483 void CopyValueToVirtualRegister(const Value *V, unsigned Reg); 484 485 void visit(const Instruction &I); 486 487 void visit(unsigned Opcode, const User &I); 488 489 /// If there was virtual register allocated for the value V emit CopyFromReg 490 /// of the specified type Ty. Return empty SDValue() otherwise. 491 SDValue getCopyFromRegs(const Value *V, Type *Ty); 492 493 /// If we have dangling debug info that describes \p Variable, or an 494 /// overlapping part of variable considering the \p Expr, then this method 495 /// will drop that debug info as it isn't valid any longer. 496 void dropDanglingDebugInfo(const DILocalVariable *Variable, 497 const DIExpression *Expr); 498 499 /// If we saw an earlier dbg_value referring to V, generate the debug data 500 /// structures now that we've seen its definition. 501 void resolveDanglingDebugInfo(const Value *V, SDValue Val); 502 503 /// For the given dangling debuginfo record, perform last-ditch efforts to 504 /// resolve the debuginfo to something that is represented in this DAG. If 505 /// this cannot be done, produce an Undef debug value record. 506 void salvageUnresolvedDbgValue(DanglingDebugInfo &DDI); 507 508 /// For a given Value, attempt to create and record a SDDbgValue in the 509 /// SelectionDAG. 510 bool handleDebugValue(const Value *V, DILocalVariable *Var, 511 DIExpression *Expr, DebugLoc CurDL, 512 DebugLoc InstDL, unsigned Order); 513 514 /// Evict any dangling debug information, attempting to salvage it first. 515 void resolveOrClearDbgInfo(); 516 517 SDValue getValue(const Value *V); 518 519 /// Return the SDNode for the specified IR value if it exists. 520 SDNode *getNodeForIRValue(const Value *V) { 521 if (NodeMap.find(V) == NodeMap.end()) 522 return nullptr; 523 return NodeMap[V].getNode(); 524 } 525 526 SDValue getNonRegisterValue(const Value *V); 527 SDValue getValueImpl(const Value *V); 528 529 void setValue(const Value *V, SDValue NewN) { 530 SDValue &N = NodeMap[V]; 531 assert(!N.getNode() && "Already set a value for this node!"); 532 N = NewN; 533 } 534 535 void setUnusedArgValue(const Value *V, SDValue NewN) { 536 SDValue &N = UnusedArgNodeMap[V]; 537 assert(!N.getNode() && "Already set a value for this node!"); 538 N = NewN; 539 } 540 541 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, 542 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 543 MachineBasicBlock *SwitchBB, 544 Instruction::BinaryOps Opc, BranchProbability TProb, 545 BranchProbability FProb, bool InvertCond); 546 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, 547 MachineBasicBlock *FBB, 548 MachineBasicBlock *CurBB, 549 MachineBasicBlock *SwitchBB, 550 BranchProbability TProb, BranchProbability FProb, 551 bool InvertCond); 552 bool ShouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases); 553 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB); 554 void CopyToExportRegsIfNeeded(const Value *V); 555 void ExportFromCurrentBlock(const Value *V); 556 void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, 557 const BasicBlock *EHPadBB = nullptr); 558 559 // Lower range metadata from 0 to N to assert zext to an integer of nearest 560 // floor power of two. 561 SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, 562 SDValue Op); 563 564 void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, 565 const CallBase *Call, unsigned ArgIdx, 566 unsigned NumArgs, SDValue Callee, 567 Type *ReturnTy, bool IsPatchPoint); 568 569 std::pair<SDValue, SDValue> 570 lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 571 const BasicBlock *EHPadBB = nullptr); 572 573 /// When an MBB was split during scheduling, update the 574 /// references that need to refer to the last resulting block. 575 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last); 576 577 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes 578 /// of lowering into a STATEPOINT node. 579 struct StatepointLoweringInfo { 580 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set 581 /// of gc pointers this STATEPOINT has to relocate. 582 SmallVector<const Value *, 16> Bases; 583 SmallVector<const Value *, 16> Ptrs; 584 585 /// The set of gc.relocate calls associated with this gc.statepoint. 586 SmallVector<const GCRelocateInst *, 16> GCRelocates; 587 588 /// The full list of gc arguments to the gc.statepoint being lowered. 589 ArrayRef<const Use> GCArgs; 590 591 /// The gc.statepoint instruction. 592 const Instruction *StatepointInstr = nullptr; 593 594 /// The list of gc transition arguments present in the gc.statepoint being 595 /// lowered. 596 ArrayRef<const Use> GCTransitionArgs; 597 598 /// The ID that the resulting STATEPOINT instruction has to report. 599 unsigned ID = -1; 600 601 /// Information regarding the underlying call instruction. 602 TargetLowering::CallLoweringInfo CLI; 603 604 /// The deoptimization state associated with this gc.statepoint call, if 605 /// any. 606 ArrayRef<const Use> DeoptState; 607 608 /// Flags associated with the meta arguments being lowered. 609 uint64_t StatepointFlags = -1; 610 611 /// The number of patchable bytes the call needs to get lowered into. 612 unsigned NumPatchBytes = -1; 613 614 /// The exception handling unwind destination, in case this represents an 615 /// invoke of gc.statepoint. 616 const BasicBlock *EHPadBB = nullptr; 617 618 explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {} 619 }; 620 621 /// Lower \p SLI into a STATEPOINT instruction. 622 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI); 623 624 // This function is responsible for the whole statepoint lowering process. 625 // It uniformly handles invoke and call statepoints. 626 void LowerStatepoint(ImmutableStatepoint ISP, 627 const BasicBlock *EHPadBB = nullptr); 628 629 void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, 630 const BasicBlock *EHPadBB); 631 632 void LowerDeoptimizeCall(const CallInst *CI); 633 void LowerDeoptimizingReturn(); 634 635 void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee, 636 const BasicBlock *EHPadBB, 637 bool VarArgDisallowed, 638 bool ForceVoidReturnTy); 639 640 /// Returns the type of FrameIndex and TargetFrameIndex nodes. 641 MVT getFrameIndexTy() { 642 return DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()); 643 } 644 645 private: 646 // Terminator instructions. 647 void visitRet(const ReturnInst &I); 648 void visitBr(const BranchInst &I); 649 void visitSwitch(const SwitchInst &I); 650 void visitIndirectBr(const IndirectBrInst &I); 651 void visitUnreachable(const UnreachableInst &I); 652 void visitCleanupRet(const CleanupReturnInst &I); 653 void visitCatchSwitch(const CatchSwitchInst &I); 654 void visitCatchRet(const CatchReturnInst &I); 655 void visitCatchPad(const CatchPadInst &I); 656 void visitCleanupPad(const CleanupPadInst &CPI); 657 658 BranchProbability getEdgeProbability(const MachineBasicBlock *Src, 659 const MachineBasicBlock *Dst) const; 660 void addSuccessorWithProb( 661 MachineBasicBlock *Src, MachineBasicBlock *Dst, 662 BranchProbability Prob = BranchProbability::getUnknown()); 663 664 public: 665 void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB); 666 void visitSPDescriptorParent(StackProtectorDescriptor &SPD, 667 MachineBasicBlock *ParentBB); 668 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD); 669 void visitBitTestHeader(SwitchCG::BitTestBlock &B, 670 MachineBasicBlock *SwitchBB); 671 void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, 672 BranchProbability BranchProbToNext, unsigned Reg, 673 SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB); 674 void visitJumpTable(SwitchCG::JumpTable &JT); 675 void visitJumpTableHeader(SwitchCG::JumpTable &JT, 676 SwitchCG::JumpTableHeader &JTH, 677 MachineBasicBlock *SwitchBB); 678 679 private: 680 // These all get lowered before this pass. 681 void visitInvoke(const InvokeInst &I); 682 void visitCallBr(const CallBrInst &I); 683 void visitResume(const ResumeInst &I); 684 685 void visitUnary(const User &I, unsigned Opcode); 686 void visitFNeg(const User &I) { visitUnary(I, ISD::FNEG); } 687 688 void visitBinary(const User &I, unsigned Opcode); 689 void visitShift(const User &I, unsigned Opcode); 690 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); } 691 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); } 692 void visitSub(const User &I) { visitBinary(I, ISD::SUB); } 693 void visitFSub(const User &I); 694 void visitMul(const User &I) { visitBinary(I, ISD::MUL); } 695 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); } 696 void visitURem(const User &I) { visitBinary(I, ISD::UREM); } 697 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); } 698 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); } 699 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); } 700 void visitSDiv(const User &I); 701 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); } 702 void visitAnd (const User &I) { visitBinary(I, ISD::AND); } 703 void visitOr (const User &I) { visitBinary(I, ISD::OR); } 704 void visitXor (const User &I) { visitBinary(I, ISD::XOR); } 705 void visitShl (const User &I) { visitShift(I, ISD::SHL); } 706 void visitLShr(const User &I) { visitShift(I, ISD::SRL); } 707 void visitAShr(const User &I) { visitShift(I, ISD::SRA); } 708 void visitICmp(const User &I); 709 void visitFCmp(const User &I); 710 // Visit the conversion instructions 711 void visitTrunc(const User &I); 712 void visitZExt(const User &I); 713 void visitSExt(const User &I); 714 void visitFPTrunc(const User &I); 715 void visitFPExt(const User &I); 716 void visitFPToUI(const User &I); 717 void visitFPToSI(const User &I); 718 void visitUIToFP(const User &I); 719 void visitSIToFP(const User &I); 720 void visitPtrToInt(const User &I); 721 void visitIntToPtr(const User &I); 722 void visitBitCast(const User &I); 723 void visitAddrSpaceCast(const User &I); 724 725 void visitExtractElement(const User &I); 726 void visitInsertElement(const User &I); 727 void visitShuffleVector(const User &I); 728 729 void visitExtractValue(const User &I); 730 void visitInsertValue(const User &I); 731 void visitLandingPad(const LandingPadInst &LP); 732 733 void visitGetElementPtr(const User &I); 734 void visitSelect(const User &I); 735 736 void visitAlloca(const AllocaInst &I); 737 void visitLoad(const LoadInst &I); 738 void visitStore(const StoreInst &I); 739 void visitMaskedLoad(const CallInst &I, bool IsExpanding = false); 740 void visitMaskedStore(const CallInst &I, bool IsCompressing = false); 741 void visitMaskedGather(const CallInst &I); 742 void visitMaskedScatter(const CallInst &I); 743 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I); 744 void visitAtomicRMW(const AtomicRMWInst &I); 745 void visitFence(const FenceInst &I); 746 void visitPHI(const PHINode &I); 747 void visitCall(const CallInst &I); 748 bool visitMemCmpCall(const CallInst &I); 749 bool visitMemPCpyCall(const CallInst &I); 750 bool visitMemChrCall(const CallInst &I); 751 bool visitStrCpyCall(const CallInst &I, bool isStpcpy); 752 bool visitStrCmpCall(const CallInst &I); 753 bool visitStrLenCall(const CallInst &I); 754 bool visitStrNLenCall(const CallInst &I); 755 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode); 756 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode); 757 void visitAtomicLoad(const LoadInst &I); 758 void visitAtomicStore(const StoreInst &I); 759 void visitLoadFromSwiftError(const LoadInst &I); 760 void visitStoreToSwiftError(const StoreInst &I); 761 void visitFreeze(const FreezeInst &I); 762 763 void visitInlineAsm(const CallBase &Call); 764 void visitIntrinsicCall(const CallInst &I, unsigned Intrinsic); 765 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic); 766 void visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI); 767 768 void visitVAStart(const CallInst &I); 769 void visitVAArg(const VAArgInst &I); 770 void visitVAEnd(const CallInst &I); 771 void visitVACopy(const CallInst &I); 772 void visitStackmap(const CallInst &I); 773 void visitPatchpoint(const CallBase &CB, const BasicBlock *EHPadBB = nullptr); 774 775 // These two are implemented in StatepointLowering.cpp 776 void visitGCRelocate(const GCRelocateInst &Relocate); 777 void visitGCResult(const GCResultInst &I); 778 779 void visitVectorReduce(const CallInst &I, unsigned Intrinsic); 780 781 void visitUserOp1(const Instruction &I) { 782 llvm_unreachable("UserOp1 should not exist at instruction selection time!"); 783 } 784 void visitUserOp2(const Instruction &I) { 785 llvm_unreachable("UserOp2 should not exist at instruction selection time!"); 786 } 787 788 void processIntegerCallValue(const Instruction &I, 789 SDValue Value, bool IsSigned); 790 791 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB); 792 793 void emitInlineAsmError(const CallBase &Call, const Twine &Message); 794 795 /// If V is an function argument then create corresponding DBG_VALUE machine 796 /// instruction for it now. At the end of instruction selection, they will be 797 /// inserted to the entry BB. 798 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable, 799 DIExpression *Expr, DILocation *DL, 800 bool IsDbgDeclare, const SDValue &N); 801 802 /// Return the next block after MBB, or nullptr if there is none. 803 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB); 804 805 /// Update the DAG and DAG builder with the relevant information after 806 /// a new root node has been created which could be a tail call. 807 void updateDAGForMaybeTailCall(SDValue MaybeTC); 808 809 /// Return the appropriate SDDbgValue based on N. 810 SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable, 811 DIExpression *Expr, const DebugLoc &dl, 812 unsigned DbgSDNodeOrder); 813 814 /// Lowers CallInst to an external symbol. 815 void lowerCallToExternalSymbol(const CallInst &I, const char *FunctionName); 816 }; 817 818 /// This struct represents the registers (physical or virtual) 819 /// that a particular set of values is assigned, and the type information about 820 /// the value. The most common situation is to represent one value at a time, 821 /// but struct or array values are handled element-wise as multiple values. The 822 /// splitting of aggregates is performed recursively, so that we never have 823 /// aggregate-typed registers. The values at this point do not necessarily have 824 /// legal types, so each value may require one or more registers of some legal 825 /// type. 826 /// 827 struct RegsForValue { 828 /// The value types of the values, which may not be legal, and 829 /// may need be promoted or synthesized from one or more registers. 830 SmallVector<EVT, 4> ValueVTs; 831 832 /// The value types of the registers. This is the same size as ValueVTs and it 833 /// records, for each value, what the type of the assigned register or 834 /// registers are. (Individual values are never synthesized from more than one 835 /// type of register.) 836 /// 837 /// With virtual registers, the contents of RegVTs is redundant with TLI's 838 /// getRegisterType member function, however when with physical registers 839 /// it is necessary to have a separate record of the types. 840 SmallVector<MVT, 4> RegVTs; 841 842 /// This list holds the registers assigned to the values. 843 /// Each legal or promoted value requires one register, and each 844 /// expanded value requires multiple registers. 845 SmallVector<unsigned, 4> Regs; 846 847 /// This list holds the number of registers for each value. 848 SmallVector<unsigned, 4> RegCount; 849 850 /// Records if this value needs to be treated in an ABI dependant manner, 851 /// different to normal type legalization. 852 Optional<CallingConv::ID> CallConv; 853 854 RegsForValue() = default; 855 RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, EVT valuevt, 856 Optional<CallingConv::ID> CC = None); 857 RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 858 const DataLayout &DL, unsigned Reg, Type *Ty, 859 Optional<CallingConv::ID> CC); 860 861 bool isABIMangled() const { 862 return CallConv.hasValue(); 863 } 864 865 /// Add the specified values to this one. 866 void append(const RegsForValue &RHS) { 867 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 868 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 869 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 870 RegCount.push_back(RHS.Regs.size()); 871 } 872 873 /// Emit a series of CopyFromReg nodes that copies from this value and returns 874 /// the result as a ValueVTs value. This uses Chain/Flag as the input and 875 /// updates them for the output Chain/Flag. If the Flag pointer is NULL, no 876 /// flag is used. 877 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 878 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 879 const Value *V = nullptr) const; 880 881 /// Emit a series of CopyToReg nodes that copies the specified value into the 882 /// registers specified by this object. This uses Chain/Flag as the input and 883 /// updates them for the output Chain/Flag. If the Flag pointer is nullptr, no 884 /// flag is used. If V is not nullptr, then it is used in printing better 885 /// diagnostic messages on error. 886 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, 887 SDValue &Chain, SDValue *Flag, const Value *V = nullptr, 888 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const; 889 890 /// Add this value to the specified inlineasm node operand list. This adds the 891 /// code marker, matching input operand index (if applicable), and includes 892 /// the number of values added into it. 893 void AddInlineAsmOperands(unsigned Code, bool HasMatching, 894 unsigned MatchingIdx, const SDLoc &dl, 895 SelectionDAG &DAG, std::vector<SDValue> &Ops) const; 896 897 /// Check if the total RegCount is greater than one. 898 bool occupiesMultipleRegs() const { 899 return std::accumulate(RegCount.begin(), RegCount.end(), 0) > 1; 900 } 901 902 /// Return a list of registers and their sizes. 903 SmallVector<std::pair<unsigned, unsigned>, 4> getRegsAndSizes() const; 904 }; 905 906 } // end namespace llvm 907 908 #endif // LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 909