2
0

SelectionDAGBuilder.h 38 KB

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