1 //===-- SelectionDAGBuilder.h - Selection-DAG building --------*- C++ -*---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 15 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 16 17 #include "StatepointLowering.h" 18 #include "llvm/ADT/APInt.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/CodeGen/SelectionDAGNodes.h" 22 #include "llvm/IR/CallSite.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include "llvm/Target/TargetLowering.h" 26 #include <vector> 27 28 namespace llvm { 29 30 class AddrSpaceCastInst; 31 class AliasAnalysis; 32 class AllocaInst; 33 class BasicBlock; 34 class BitCastInst; 35 class BranchInst; 36 class CallInst; 37 class DbgValueInst; 38 class ExtractElementInst; 39 class ExtractValueInst; 40 class FCmpInst; 41 class FPExtInst; 42 class FPToSIInst; 43 class FPToUIInst; 44 class FPTruncInst; 45 class Function; 46 class FunctionLoweringInfo; 47 class GetElementPtrInst; 48 class GCFunctionInfo; 49 class ICmpInst; 50 class IntToPtrInst; 51 class IndirectBrInst; 52 class InvokeInst; 53 class InsertElementInst; 54 class InsertValueInst; 55 class Instruction; 56 class LoadInst; 57 class MachineBasicBlock; 58 class MachineInstr; 59 class MachineRegisterInfo; 60 class MDNode; 61 class MVT; 62 class PHINode; 63 class PtrToIntInst; 64 class ReturnInst; 65 class SDDbgValue; 66 class SExtInst; 67 class SelectInst; 68 class ShuffleVectorInst; 69 class SIToFPInst; 70 class StoreInst; 71 class SwitchInst; 72 class DataLayout; 73 class TargetLibraryInfo; 74 class TargetLowering; 75 class TruncInst; 76 class UIToFPInst; 77 class UnreachableInst; 78 class VAArgInst; 79 class ZExtInst; 80 81 //===----------------------------------------------------------------------===// 82 /// SelectionDAGBuilder - This is the common target-independent lowering 83 /// implementation that is parameterized by a TargetLowering object. 84 /// 85 class SelectionDAGBuilder { 86 /// CurInst - The current instruction being visited 87 const Instruction *CurInst; 88 89 DenseMap<const Value*, SDValue> NodeMap; 90 91 /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used 92 /// to preserve debug information for incoming arguments. 93 DenseMap<const Value*, SDValue> UnusedArgNodeMap; 94 95 /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap. 96 class DanglingDebugInfo { 97 const DbgValueInst* DI; 98 DebugLoc dl; 99 unsigned SDNodeOrder; 100 public: DanglingDebugInfo()101 DanglingDebugInfo() : DI(nullptr), dl(DebugLoc()), SDNodeOrder(0) { } DanglingDebugInfo(const DbgValueInst * di,DebugLoc DL,unsigned SDNO)102 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) : 103 DI(di), dl(DL), SDNodeOrder(SDNO) { } getDI()104 const DbgValueInst* getDI() { return DI; } getdl()105 DebugLoc getdl() { return dl; } getSDNodeOrder()106 unsigned getSDNodeOrder() { return SDNodeOrder; } 107 }; 108 109 /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not 110 /// yet seen the referent. We defer handling these until we do see it. 111 DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap; 112 113 public: 114 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 115 /// them up and then emit token factor nodes when possible. This allows us to 116 /// get simple disambiguation between loads without worrying about alias 117 /// analysis. 118 SmallVector<SDValue, 8> PendingLoads; 119 120 /// State used while lowering a statepoint sequence (gc_statepoint, 121 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details. 122 StatepointLoweringState StatepointLowering; 123 private: 124 125 /// PendingExports - CopyToReg nodes that copy values to virtual registers 126 /// for export to other blocks need to be emitted before any terminator 127 /// instruction, but they have no other ordering requirements. We bunch them 128 /// up and the emit a single tokenfactor for them just before terminator 129 /// instructions. 130 SmallVector<SDValue, 8> PendingExports; 131 132 /// SDNodeOrder - A unique monotonically increasing number used to order the 133 /// SDNodes we create. 134 unsigned SDNodeOrder; 135 136 /// Case - A struct to record the Value for a switch case, and the 137 /// case's target basic block. 138 struct Case { 139 const Constant *Low; 140 const Constant *High; 141 MachineBasicBlock* BB; 142 uint32_t ExtraWeight; 143 CaseCase144 Case() : Low(nullptr), High(nullptr), BB(nullptr), ExtraWeight(0) { } CaseCase145 Case(const Constant *low, const Constant *high, MachineBasicBlock *bb, 146 uint32_t extraweight) : Low(low), High(high), BB(bb), 147 ExtraWeight(extraweight) { } 148 sizeCase149 APInt size() const { 150 const APInt &rHigh = cast<ConstantInt>(High)->getValue(); 151 const APInt &rLow = cast<ConstantInt>(Low)->getValue(); 152 return (rHigh - rLow + 1ULL); 153 } 154 }; 155 156 struct CaseBits { 157 uint64_t Mask; 158 MachineBasicBlock* BB; 159 unsigned Bits; 160 uint32_t ExtraWeight; 161 CaseBitsCaseBits162 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits, 163 uint32_t Weight): 164 Mask(mask), BB(bb), Bits(bits), ExtraWeight(Weight) { } 165 }; 166 167 typedef std::vector<Case> CaseVector; 168 typedef std::vector<CaseBits> CaseBitsVector; 169 typedef CaseVector::iterator CaseItr; 170 typedef std::pair<CaseItr, CaseItr> CaseRange; 171 172 /// CaseRec - A struct with ctor used in lowering switches to a binary tree 173 /// of conditional branches. 174 struct CaseRec { CaseRecCaseRec175 CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge, 176 CaseRange r) : 177 CaseBB(bb), LT(lt), GE(ge), Range(r) {} 178 179 /// CaseBB - The MBB in which to emit the compare and branch 180 MachineBasicBlock *CaseBB; 181 /// LT, GE - If nonzero, we know the current case value must be less-than or 182 /// greater-than-or-equal-to these Constants. 183 const Constant *LT; 184 const Constant *GE; 185 /// Range - A pair of iterators representing the range of case values to be 186 /// processed at this point in the binary search tree. 187 CaseRange Range; 188 }; 189 190 typedef std::vector<CaseRec> CaseRecVector; 191 192 /// The comparison function for sorting the switch case values in the vector. 193 /// WARNING: Case ranges should be disjoint! 194 struct CaseCmp { operatorCaseCmp195 bool operator()(const Case &C1, const Case &C2) { 196 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High)); 197 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low); 198 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High); 199 return CI1->getValue().slt(CI2->getValue()); 200 } 201 }; 202 203 struct CaseBitsCmp { operatorCaseBitsCmp204 bool operator()(const CaseBits &C1, const CaseBits &C2) { 205 return C1.Bits > C2.Bits; 206 } 207 }; 208 209 void Clusterify(CaseVector &Cases, const SwitchInst &SI); 210 211 /// CaseBlock - This structure is used to communicate between 212 /// SelectionDAGBuilder and SDISel for the code generation of additional basic 213 /// blocks needed by multi-case switch statements. 214 struct CaseBlock { 215 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs, 216 const Value *cmpmiddle, 217 MachineBasicBlock *truebb, MachineBasicBlock *falsebb, 218 MachineBasicBlock *me, 219 uint32_t trueweight = 0, uint32_t falseweight = 0) CCCaseBlock220 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs), 221 TrueBB(truebb), FalseBB(falsebb), ThisBB(me), 222 TrueWeight(trueweight), FalseWeight(falseweight) { } 223 224 // CC - the condition code to use for the case block's setcc node 225 ISD::CondCode CC; 226 227 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit. 228 // Emit by default LHS op RHS. MHS is used for range comparisons: 229 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS). 230 const Value *CmpLHS, *CmpMHS, *CmpRHS; 231 232 // TrueBB/FalseBB - the block to branch to if the setcc is true/false. 233 MachineBasicBlock *TrueBB, *FalseBB; 234 235 // ThisBB - the block into which to emit the code for the setcc and branches 236 MachineBasicBlock *ThisBB; 237 238 // TrueWeight/FalseWeight - branch weights. 239 uint32_t TrueWeight, FalseWeight; 240 }; 241 242 struct JumpTable { JumpTableJumpTable243 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M, 244 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {} 245 246 /// Reg - the virtual register containing the index of the jump table entry 247 //. to jump to. 248 unsigned Reg; 249 /// JTI - the JumpTableIndex for this jump table in the function. 250 unsigned JTI; 251 /// MBB - the MBB into which to emit the code for the indirect jump. 252 MachineBasicBlock *MBB; 253 /// Default - the MBB of the default bb, which is a successor of the range 254 /// check MBB. This is when updating PHI nodes in successors. 255 MachineBasicBlock *Default; 256 }; 257 struct JumpTableHeader { 258 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H, 259 bool E = false): FirstJumpTableHeader260 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {} 261 APInt First; 262 APInt Last; 263 const Value *SValue; 264 MachineBasicBlock *HeaderBB; 265 bool Emitted; 266 }; 267 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock; 268 269 struct BitTestCase { BitTestCaseBitTestCase270 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr, 271 uint32_t Weight): 272 Mask(M), ThisBB(T), TargetBB(Tr), ExtraWeight(Weight) { } 273 uint64_t Mask; 274 MachineBasicBlock *ThisBB; 275 MachineBasicBlock *TargetBB; 276 uint32_t ExtraWeight; 277 }; 278 279 typedef SmallVector<BitTestCase, 3> BitTestInfo; 280 281 struct BitTestBlock { BitTestBlockBitTestBlock282 BitTestBlock(APInt F, APInt R, const Value* SV, 283 unsigned Rg, MVT RgVT, bool E, 284 MachineBasicBlock* P, MachineBasicBlock* D, 285 BitTestInfo C): 286 First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E), 287 Parent(P), Default(D), Cases(std::move(C)) { } 288 APInt First; 289 APInt Range; 290 const Value *SValue; 291 unsigned Reg; 292 MVT RegVT; 293 bool Emitted; 294 MachineBasicBlock *Parent; 295 MachineBasicBlock *Default; 296 BitTestInfo Cases; 297 }; 298 299 /// A class which encapsulates all of the information needed to generate a 300 /// stack protector check and signals to isel via its state being initialized 301 /// that a stack protector needs to be generated. 302 /// 303 /// *NOTE* The following is a high level documentation of SelectionDAG Stack 304 /// Protector Generation. The reason that it is placed here is for a lack of 305 /// other good places to stick it. 306 /// 307 /// High Level Overview of SelectionDAG Stack Protector Generation: 308 /// 309 /// Previously, generation of stack protectors was done exclusively in the 310 /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated 311 /// splitting basic blocks at the IR level to create the success/failure basic 312 /// blocks in the tail of the basic block in question. As a result of this, 313 /// calls that would have qualified for the sibling call optimization were no 314 /// longer eligible for optimization since said calls were no longer right in 315 /// the "tail position" (i.e. the immediate predecessor of a ReturnInst 316 /// instruction). 317 /// 318 /// Then it was noticed that since the sibling call optimization causes the 319 /// callee to reuse the caller's stack, if we could delay the generation of 320 /// the stack protector check until later in CodeGen after the sibling call 321 /// decision was made, we get both the tail call optimization and the stack 322 /// protector check! 323 /// 324 /// A few goals in solving this problem were: 325 /// 326 /// 1. Preserve the architecture independence of stack protector generation. 327 /// 328 /// 2. Preserve the normal IR level stack protector check for platforms like 329 /// OpenBSD for which we support platform-specific stack protector 330 /// generation. 331 /// 332 /// The main problem that guided the present solution is that one can not 333 /// solve this problem in an architecture independent manner at the IR level 334 /// only. This is because: 335 /// 336 /// 1. The decision on whether or not to perform a sibling call on certain 337 /// platforms (for instance i386) requires lower level information 338 /// related to available registers that can not be known at the IR level. 339 /// 340 /// 2. Even if the previous point were not true, the decision on whether to 341 /// perform a tail call is done in LowerCallTo in SelectionDAG which 342 /// occurs after the Stack Protector Pass. As a result, one would need to 343 /// put the relevant callinst into the stack protector check success 344 /// basic block (where the return inst is placed) and then move it back 345 /// later at SelectionDAG/MI time before the stack protector check if the 346 /// tail call optimization failed. The MI level option was nixed 347 /// immediately since it would require platform-specific pattern 348 /// matching. The SelectionDAG level option was nixed because 349 /// SelectionDAG only processes one IR level basic block at a time 350 /// implying one could not create a DAG Combine to move the callinst. 351 /// 352 /// To get around this problem a few things were realized: 353 /// 354 /// 1. While one can not handle multiple IR level basic blocks at the 355 /// SelectionDAG Level, one can generate multiple machine basic blocks 356 /// for one IR level basic block. This is how we handle bit tests and 357 /// switches. 358 /// 359 /// 2. At the MI level, tail calls are represented via a special return 360 /// MIInst called "tcreturn". Thus if we know the basic block in which we 361 /// wish to insert the stack protector check, we get the correct behavior 362 /// by always inserting the stack protector check right before the return 363 /// statement. This is a "magical transformation" since no matter where 364 /// the stack protector check intrinsic is, we always insert the stack 365 /// protector check code at the end of the BB. 366 /// 367 /// Given the aforementioned constraints, the following solution was devised: 368 /// 369 /// 1. On platforms that do not support SelectionDAG stack protector check 370 /// generation, allow for the normal IR level stack protector check 371 /// generation to continue. 372 /// 373 /// 2. On platforms that do support SelectionDAG stack protector check 374 /// generation: 375 /// 376 /// a. Use the IR level stack protector pass to decide if a stack 377 /// protector is required/which BB we insert the stack protector check 378 /// in by reusing the logic already therein. If we wish to generate a 379 /// stack protector check in a basic block, we place a special IR 380 /// intrinsic called llvm.stackprotectorcheck right before the BB's 381 /// returninst or if there is a callinst that could potentially be 382 /// sibling call optimized, before the call inst. 383 /// 384 /// b. Then when a BB with said intrinsic is processed, we codegen the BB 385 /// normally via SelectBasicBlock. In said process, when we visit the 386 /// stack protector check, we do not actually emit anything into the 387 /// BB. Instead, we just initialize the stack protector descriptor 388 /// class (which involves stashing information/creating the success 389 /// mbbb and the failure mbb if we have not created one for this 390 /// function yet) and export the guard variable that we are going to 391 /// compare. 392 /// 393 /// c. After we finish selecting the basic block, in FinishBasicBlock if 394 /// the StackProtectorDescriptor attached to the SelectionDAGBuilder is 395 /// initialized, we first find a splice point in the parent basic block 396 /// before the terminator and then splice the terminator of said basic 397 /// block into the success basic block. Then we code-gen a new tail for 398 /// the parent basic block consisting of the two loads, the comparison, 399 /// and finally two branches to the success/failure basic blocks. We 400 /// conclude by code-gening the failure basic block if we have not 401 /// code-gened it already (all stack protector checks we generate in 402 /// the same function, use the same failure basic block). 403 class StackProtectorDescriptor { 404 public: StackProtectorDescriptor()405 StackProtectorDescriptor() : ParentMBB(nullptr), SuccessMBB(nullptr), 406 FailureMBB(nullptr), Guard(nullptr), 407 GuardReg(0) { } ~StackProtectorDescriptor()408 ~StackProtectorDescriptor() { } 409 410 /// Returns true if all fields of the stack protector descriptor are 411 /// initialized implying that we should/are ready to emit a stack protector. shouldEmitStackProtector()412 bool shouldEmitStackProtector() const { 413 return ParentMBB && SuccessMBB && FailureMBB && Guard; 414 } 415 416 /// Initialize the stack protector descriptor structure for a new basic 417 /// block. initialize(const BasicBlock * BB,MachineBasicBlock * MBB,const CallInst & StackProtCheckCall)418 void initialize(const BasicBlock *BB, 419 MachineBasicBlock *MBB, 420 const CallInst &StackProtCheckCall) { 421 // Make sure we are not initialized yet. 422 assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is " 423 "already initialized!"); 424 ParentMBB = MBB; 425 SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true); 426 FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB); 427 if (!Guard) 428 Guard = StackProtCheckCall.getArgOperand(0); 429 } 430 431 /// Reset state that changes when we handle different basic blocks. 432 /// 433 /// This currently includes: 434 /// 435 /// 1. The specific basic block we are generating a 436 /// stack protector for (ParentMBB). 437 /// 438 /// 2. The successor machine basic block that will contain the tail of 439 /// parent mbb after we create the stack protector check (SuccessMBB). This 440 /// BB is visited only on stack protector check success. resetPerBBState()441 void resetPerBBState() { 442 ParentMBB = nullptr; 443 SuccessMBB = nullptr; 444 } 445 446 /// Reset state that only changes when we switch functions. 447 /// 448 /// This currently includes: 449 /// 450 /// 1. FailureMBB since we reuse the failure code path for all stack 451 /// protector checks created in an individual function. 452 /// 453 /// 2.The guard variable since the guard variable we are checking against is 454 /// always the same. resetPerFunctionState()455 void resetPerFunctionState() { 456 FailureMBB = nullptr; 457 Guard = nullptr; 458 } 459 getParentMBB()460 MachineBasicBlock *getParentMBB() { return ParentMBB; } getSuccessMBB()461 MachineBasicBlock *getSuccessMBB() { return SuccessMBB; } getFailureMBB()462 MachineBasicBlock *getFailureMBB() { return FailureMBB; } getGuard()463 const Value *getGuard() { return Guard; } 464 getGuardReg()465 unsigned getGuardReg() const { return GuardReg; } setGuardReg(unsigned R)466 void setGuardReg(unsigned R) { GuardReg = R; } 467 468 private: 469 /// The basic block for which we are generating the stack protector. 470 /// 471 /// As a result of stack protector generation, we will splice the 472 /// terminators of this basic block into the successor mbb SuccessMBB and 473 /// replace it with a compare/branch to the successor mbbs 474 /// SuccessMBB/FailureMBB depending on whether or not the stack protector 475 /// was violated. 476 MachineBasicBlock *ParentMBB; 477 478 /// A basic block visited on stack protector check success that contains the 479 /// terminators of ParentMBB. 480 MachineBasicBlock *SuccessMBB; 481 482 /// This basic block visited on stack protector check failure that will 483 /// contain a call to __stack_chk_fail(). 484 MachineBasicBlock *FailureMBB; 485 486 /// The guard variable which we will compare against the stored value in the 487 /// stack protector stack slot. 488 const Value *Guard; 489 490 /// The virtual register holding the stack guard value. 491 unsigned GuardReg; 492 493 /// Add a successor machine basic block to ParentMBB. If the successor mbb 494 /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic 495 /// block will be created. Assign a large weight if IsLikely is true. 496 MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB, 497 MachineBasicBlock *ParentMBB, 498 bool IsLikely, 499 MachineBasicBlock *SuccMBB = nullptr); 500 }; 501 502 private: 503 const TargetMachine &TM; 504 public: 505 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling 506 /// nodes without a corresponding SDNode. 507 static const unsigned LowestSDNodeOrder = 1; 508 509 SelectionDAG &DAG; 510 const DataLayout *DL; 511 AliasAnalysis *AA; 512 const TargetLibraryInfo *LibInfo; 513 514 /// SwitchCases - Vector of CaseBlock structures used to communicate 515 /// SwitchInst code generation information. 516 std::vector<CaseBlock> SwitchCases; 517 /// JTCases - Vector of JumpTable structures used to communicate 518 /// SwitchInst code generation information. 519 std::vector<JumpTableBlock> JTCases; 520 /// BitTestCases - Vector of BitTestBlock structures used to communicate 521 /// SwitchInst code generation information. 522 std::vector<BitTestBlock> BitTestCases; 523 /// A StackProtectorDescriptor structure used to communicate stack protector 524 /// information in between SelectBasicBlock and FinishBasicBlock. 525 StackProtectorDescriptor SPDescriptor; 526 527 // Emit PHI-node-operand constants only once even if used by multiple 528 // PHI nodes. 529 DenseMap<const Constant *, unsigned> ConstantsOut; 530 531 /// FuncInfo - Information about the function as a whole. 532 /// 533 FunctionLoweringInfo &FuncInfo; 534 535 /// OptLevel - What optimization level we're generating code for. 536 /// 537 CodeGenOpt::Level OptLevel; 538 539 /// GFI - Garbage collection metadata for the function. 540 GCFunctionInfo *GFI; 541 542 /// LPadToCallSiteMap - Map a landing pad to the call site indexes. 543 DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap; 544 545 /// HasTailCall - This is set to true if a call in the current 546 /// block has been translated as a tail call. In this case, 547 /// no subsequent DAG nodes should be created. 548 /// 549 bool HasTailCall; 550 551 LLVMContext *Context; 552 SelectionDAGBuilder(SelectionDAG & dag,FunctionLoweringInfo & funcinfo,CodeGenOpt::Level ol)553 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, 554 CodeGenOpt::Level ol) 555 : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), 556 DAG(dag), FuncInfo(funcinfo), OptLevel(ol), 557 HasTailCall(false) { 558 } 559 560 void init(GCFunctionInfo *gfi, AliasAnalysis &aa, 561 const TargetLibraryInfo *li); 562 563 /// clear - Clear out the current SelectionDAG and the associated 564 /// state and prepare this SelectionDAGBuilder object to be used 565 /// for a new block. This doesn't clear out information about 566 /// additional blocks that are needed to complete switch lowering 567 /// or PHI node updating; that information is cleared out as it is 568 /// consumed. 569 void clear(); 570 571 /// clearDanglingDebugInfo - Clear the dangling debug information 572 /// map. This function is separated from the clear so that debug 573 /// information that is dangling in a basic block can be properly 574 /// resolved in a different basic block. This allows the 575 /// SelectionDAG to resolve dangling debug information attached 576 /// to PHI nodes. 577 void clearDanglingDebugInfo(); 578 579 /// getRoot - Return the current virtual root of the Selection DAG, 580 /// flushing any PendingLoad items. This must be done before emitting 581 /// a store or any other node that may need to be ordered after any 582 /// prior load instructions. 583 /// 584 SDValue getRoot(); 585 586 /// getControlRoot - Similar to getRoot, but instead of flushing all the 587 /// PendingLoad items, flush all the PendingExports items. It is necessary 588 /// to do this before emitting a terminator instruction. 589 /// 590 SDValue getControlRoot(); 591 getCurSDLoc()592 SDLoc getCurSDLoc() const { 593 return SDLoc(CurInst, SDNodeOrder); 594 } 595 getCurDebugLoc()596 DebugLoc getCurDebugLoc() const { 597 return CurInst ? CurInst->getDebugLoc() : DebugLoc(); 598 } 599 getSDNodeOrder()600 unsigned getSDNodeOrder() const { return SDNodeOrder; } 601 602 void CopyValueToVirtualRegister(const Value *V, unsigned Reg); 603 604 void visit(const Instruction &I); 605 606 void visit(unsigned Opcode, const User &I); 607 608 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 609 // generate the debug data structures now that we've seen its definition. 610 void resolveDanglingDebugInfo(const Value *V, SDValue Val); 611 SDValue getValue(const Value *V); 612 SDValue getNonRegisterValue(const Value *V); 613 SDValue getValueImpl(const Value *V); 614 setValue(const Value * V,SDValue NewN)615 void setValue(const Value *V, SDValue NewN) { 616 SDValue &N = NodeMap[V]; 617 assert(!N.getNode() && "Already set a value for this node!"); 618 N = NewN; 619 } 620 removeValue(const Value * V)621 void removeValue(const Value *V) { 622 // This is to support hack in lowerCallFromStatepoint 623 // Should be removed when hack is resolved 624 if (NodeMap.count(V)) 625 NodeMap.erase(V); 626 } 627 setUnusedArgValue(const Value * V,SDValue NewN)628 void setUnusedArgValue(const Value *V, SDValue NewN) { 629 SDValue &N = UnusedArgNodeMap[V]; 630 assert(!N.getNode() && "Already set a value for this node!"); 631 N = NewN; 632 } 633 634 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, 635 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 636 MachineBasicBlock *SwitchBB, unsigned Opc, 637 uint32_t TW, uint32_t FW); 638 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, 639 MachineBasicBlock *FBB, 640 MachineBasicBlock *CurBB, 641 MachineBasicBlock *SwitchBB, 642 uint32_t TW, uint32_t FW); 643 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases); 644 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB); 645 void CopyToExportRegsIfNeeded(const Value *V); 646 void ExportFromCurrentBlock(const Value *V); 647 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall, 648 MachineBasicBlock *LandingPad = nullptr); 649 650 std::pair<SDValue, SDValue> lowerCallOperands( 651 ImmutableCallSite CS, 652 unsigned ArgIdx, 653 unsigned NumArgs, 654 SDValue Callee, 655 bool UseVoidTy = false, 656 MachineBasicBlock *LandingPad = nullptr, 657 bool IsPatchPoint = false); 658 659 /// UpdateSplitBlock - When an MBB was split during scheduling, update the 660 /// references that need to refer to the last resulting block. 661 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last); 662 663 private: 664 std::pair<SDValue, SDValue> lowerInvokable( 665 TargetLowering::CallLoweringInfo &CLI, 666 MachineBasicBlock *LandingPad); 667 668 // Terminator instructions. 669 void visitRet(const ReturnInst &I); 670 void visitBr(const BranchInst &I); 671 void visitSwitch(const SwitchInst &I); 672 void visitIndirectBr(const IndirectBrInst &I); 673 void visitUnreachable(const UnreachableInst &I); 674 675 // Helpers for visitSwitch 676 bool handleSmallSwitchRange(CaseRec& CR, 677 CaseRecVector& WorkList, 678 const Value* SV, 679 MachineBasicBlock* Default, 680 MachineBasicBlock *SwitchBB); 681 bool handleJTSwitchCase(CaseRec& CR, 682 CaseRecVector& WorkList, 683 const Value* SV, 684 MachineBasicBlock* Default, 685 MachineBasicBlock *SwitchBB); 686 bool handleBTSplitSwitchCase(CaseRec& CR, 687 CaseRecVector& WorkList, 688 const Value* SV, 689 MachineBasicBlock *SwitchBB); 690 bool handleBitTestsSwitchCase(CaseRec& CR, 691 CaseRecVector& WorkList, 692 const Value* SV, 693 MachineBasicBlock* Default, 694 MachineBasicBlock *SwitchBB); 695 696 uint32_t getEdgeWeight(const MachineBasicBlock *Src, 697 const MachineBasicBlock *Dst) const; 698 void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, 699 uint32_t Weight = 0); 700 public: 701 void visitSwitchCase(CaseBlock &CB, 702 MachineBasicBlock *SwitchBB); 703 void visitSPDescriptorParent(StackProtectorDescriptor &SPD, 704 MachineBasicBlock *ParentBB); 705 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD); 706 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB); 707 void visitBitTestCase(BitTestBlock &BB, 708 MachineBasicBlock* NextMBB, 709 uint32_t BranchWeightToNext, 710 unsigned Reg, 711 BitTestCase &B, 712 MachineBasicBlock *SwitchBB); 713 void visitJumpTable(JumpTable &JT); 714 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH, 715 MachineBasicBlock *SwitchBB); 716 717 private: 718 // These all get lowered before this pass. 719 void visitInvoke(const InvokeInst &I); 720 void visitResume(const ResumeInst &I); 721 722 void visitBinary(const User &I, unsigned OpCode); 723 void visitShift(const User &I, unsigned Opcode); visitAdd(const User & I)724 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); } visitFAdd(const User & I)725 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); } visitSub(const User & I)726 void visitSub(const User &I) { visitBinary(I, ISD::SUB); } 727 void visitFSub(const User &I); visitMul(const User & I)728 void visitMul(const User &I) { visitBinary(I, ISD::MUL); } visitFMul(const User & I)729 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); } visitURem(const User & I)730 void visitURem(const User &I) { visitBinary(I, ISD::UREM); } visitSRem(const User & I)731 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); } visitFRem(const User & I)732 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); } visitUDiv(const User & I)733 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); } 734 void visitSDiv(const User &I); visitFDiv(const User & I)735 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); } visitAnd(const User & I)736 void visitAnd (const User &I) { visitBinary(I, ISD::AND); } visitOr(const User & I)737 void visitOr (const User &I) { visitBinary(I, ISD::OR); } visitXor(const User & I)738 void visitXor (const User &I) { visitBinary(I, ISD::XOR); } visitShl(const User & I)739 void visitShl (const User &I) { visitShift(I, ISD::SHL); } visitLShr(const User & I)740 void visitLShr(const User &I) { visitShift(I, ISD::SRL); } visitAShr(const User & I)741 void visitAShr(const User &I) { visitShift(I, ISD::SRA); } 742 void visitICmp(const User &I); 743 void visitFCmp(const User &I); 744 // Visit the conversion instructions 745 void visitTrunc(const User &I); 746 void visitZExt(const User &I); 747 void visitSExt(const User &I); 748 void visitFPTrunc(const User &I); 749 void visitFPExt(const User &I); 750 void visitFPToUI(const User &I); 751 void visitFPToSI(const User &I); 752 void visitUIToFP(const User &I); 753 void visitSIToFP(const User &I); 754 void visitPtrToInt(const User &I); 755 void visitIntToPtr(const User &I); 756 void visitBitCast(const User &I); 757 void visitAddrSpaceCast(const User &I); 758 759 void visitExtractElement(const User &I); 760 void visitInsertElement(const User &I); 761 void visitShuffleVector(const User &I); 762 763 void visitExtractValue(const ExtractValueInst &I); 764 void visitInsertValue(const InsertValueInst &I); 765 void visitLandingPad(const LandingPadInst &I); 766 767 void visitGetElementPtr(const User &I); 768 void visitSelect(const User &I); 769 770 void visitAlloca(const AllocaInst &I); 771 void visitLoad(const LoadInst &I); 772 void visitStore(const StoreInst &I); 773 void visitMaskedLoad(const CallInst &I); 774 void visitMaskedStore(const CallInst &I); 775 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I); 776 void visitAtomicRMW(const AtomicRMWInst &I); 777 void visitFence(const FenceInst &I); 778 void visitPHI(const PHINode &I); 779 void visitCall(const CallInst &I); 780 bool visitMemCmpCall(const CallInst &I); 781 bool visitMemChrCall(const CallInst &I); 782 bool visitStrCpyCall(const CallInst &I, bool isStpcpy); 783 bool visitStrCmpCall(const CallInst &I); 784 bool visitStrLenCall(const CallInst &I); 785 bool visitStrNLenCall(const CallInst &I); 786 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode); 787 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode); 788 void visitAtomicLoad(const LoadInst &I); 789 void visitAtomicStore(const StoreInst &I); 790 791 void visitInlineAsm(ImmutableCallSite CS); 792 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic); 793 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic); 794 795 void visitVAStart(const CallInst &I); 796 void visitVAArg(const VAArgInst &I); 797 void visitVAEnd(const CallInst &I); 798 void visitVACopy(const CallInst &I); 799 void visitStackmap(const CallInst &I); 800 void visitPatchpoint(ImmutableCallSite CS, 801 MachineBasicBlock *LandingPad = nullptr); 802 803 // These three are implemented in StatepointLowering.cpp 804 void visitStatepoint(const CallInst &I); 805 void visitGCRelocate(const CallInst &I); 806 void visitGCResult(const CallInst &I); 807 visitUserOp1(const Instruction & I)808 void visitUserOp1(const Instruction &I) { 809 llvm_unreachable("UserOp1 should not exist at instruction selection time!"); 810 } visitUserOp2(const Instruction & I)811 void visitUserOp2(const Instruction &I) { 812 llvm_unreachable("UserOp2 should not exist at instruction selection time!"); 813 } 814 815 void processIntegerCallValue(const Instruction &I, 816 SDValue Value, bool IsSigned); 817 818 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB); 819 820 /// EmitFuncArgumentDbgValue - If V is an function argument then create 821 /// corresponding DBG_VALUE machine instruction for it now. At the end of 822 /// instruction selection, they will be inserted to the entry BB. 823 bool EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable, MDNode *Expr, 824 int64_t Offset, bool IsIndirect, 825 const SDValue &N); 826 }; 827 828 } // end namespace llvm 829 830 #endif 831