SelectionDAGISel.cpp 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950
  1. //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
  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 the SelectionDAGISel class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "isel"
  14. #include "llvm/CodeGen/SelectionDAGISel.h"
  15. #include "ScheduleDAGSDNodes.h"
  16. #include "SelectionDAGBuilder.h"
  17. #include "llvm/ADT/PostOrderIterator.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BranchProbabilityInfo.h"
  21. #include "llvm/Analysis/TargetTransformInfo.h"
  22. #include "llvm/CodeGen/FastISel.h"
  23. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  24. #include "llvm/CodeGen/GCMetadata.h"
  25. #include "llvm/CodeGen/GCStrategy.h"
  26. #include "llvm/CodeGen/MachineFrameInfo.h"
  27. #include "llvm/CodeGen/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineInstrBuilder.h"
  29. #include "llvm/CodeGen/MachineModuleInfo.h"
  30. #include "llvm/CodeGen/MachineRegisterInfo.h"
  31. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  32. #include "llvm/CodeGen/SchedulerRegistry.h"
  33. #include "llvm/CodeGen/SelectionDAG.h"
  34. #include "llvm/DebugInfo.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/InlineAsm.h"
  38. #include "llvm/IR/Instructions.h"
  39. #include "llvm/IR/IntrinsicInst.h"
  40. #include "llvm/IR/Intrinsics.h"
  41. #include "llvm/IR/LLVMContext.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/Support/Compiler.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/ErrorHandling.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Target/TargetInstrInfo.h"
  49. #include "llvm/Target/TargetIntrinsicInfo.h"
  50. #include "llvm/Target/TargetLibraryInfo.h"
  51. #include "llvm/Target/TargetLowering.h"
  52. #include "llvm/Target/TargetMachine.h"
  53. #include "llvm/Target/TargetOptions.h"
  54. #include "llvm/Target/TargetRegisterInfo.h"
  55. #include "llvm/Target/TargetSubtargetInfo.h"
  56. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  57. #include <algorithm>
  58. using namespace llvm;
  59. STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
  60. STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
  61. STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
  62. STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
  63. STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
  64. STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
  65. STATISTIC(NumFastIselFailLowerArguments,
  66. "Number of entry blocks where fast isel failed to lower arguments");
  67. #ifndef NDEBUG
  68. static cl::opt<bool>
  69. EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
  70. cl::desc("Enable extra verbose messages in the \"fast\" "
  71. "instruction selector"));
  72. // Terminators
  73. STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
  74. STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
  75. STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
  76. STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
  77. STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
  78. STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
  79. STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
  80. // Standard binary operators...
  81. STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
  82. STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
  83. STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
  84. STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
  85. STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
  86. STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
  87. STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
  88. STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
  89. STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
  90. STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
  91. STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
  92. STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
  93. // Logical operators...
  94. STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
  95. STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
  96. STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
  97. // Memory instructions...
  98. STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
  99. STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
  100. STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
  101. STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
  102. STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
  103. STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
  104. STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
  105. // Convert instructions...
  106. STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
  107. STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
  108. STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
  109. STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
  110. STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
  111. STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
  112. STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
  113. STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
  114. STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
  115. STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
  116. STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
  117. STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
  118. // Other instructions...
  119. STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
  120. STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
  121. STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
  122. STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
  123. STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
  124. STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
  125. STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
  126. STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
  127. STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
  128. STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
  129. STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
  130. STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
  131. STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
  132. STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
  133. STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
  134. #endif
  135. static cl::opt<bool>
  136. EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
  137. cl::desc("Enable verbose messages in the \"fast\" "
  138. "instruction selector"));
  139. static cl::opt<bool>
  140. EnableFastISelAbort("fast-isel-abort", cl::Hidden,
  141. cl::desc("Enable abort calls when \"fast\" instruction selection "
  142. "fails to lower an instruction"));
  143. static cl::opt<bool>
  144. EnableFastISelAbortArgs("fast-isel-abort-args", cl::Hidden,
  145. cl::desc("Enable abort calls when \"fast\" instruction selection "
  146. "fails to lower a formal argument"));
  147. static cl::opt<bool>
  148. UseMBPI("use-mbpi",
  149. cl::desc("use Machine Branch Probability Info"),
  150. cl::init(true), cl::Hidden);
  151. #ifndef NDEBUG
  152. static cl::opt<bool>
  153. ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
  154. cl::desc("Pop up a window to show dags before the first "
  155. "dag combine pass"));
  156. static cl::opt<bool>
  157. ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
  158. cl::desc("Pop up a window to show dags before legalize types"));
  159. static cl::opt<bool>
  160. ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
  161. cl::desc("Pop up a window to show dags before legalize"));
  162. static cl::opt<bool>
  163. ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
  164. cl::desc("Pop up a window to show dags before the second "
  165. "dag combine pass"));
  166. static cl::opt<bool>
  167. ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
  168. cl::desc("Pop up a window to show dags before the post legalize types"
  169. " dag combine pass"));
  170. static cl::opt<bool>
  171. ViewISelDAGs("view-isel-dags", cl::Hidden,
  172. cl::desc("Pop up a window to show isel dags as they are selected"));
  173. static cl::opt<bool>
  174. ViewSchedDAGs("view-sched-dags", cl::Hidden,
  175. cl::desc("Pop up a window to show sched dags as they are processed"));
  176. static cl::opt<bool>
  177. ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
  178. cl::desc("Pop up a window to show SUnit dags after they are processed"));
  179. #else
  180. static const bool ViewDAGCombine1 = false,
  181. ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
  182. ViewDAGCombine2 = false,
  183. ViewDAGCombineLT = false,
  184. ViewISelDAGs = false, ViewSchedDAGs = false,
  185. ViewSUnitDAGs = false;
  186. #endif
  187. //===---------------------------------------------------------------------===//
  188. ///
  189. /// RegisterScheduler class - Track the registration of instruction schedulers.
  190. ///
  191. //===---------------------------------------------------------------------===//
  192. MachinePassRegistry RegisterScheduler::Registry;
  193. //===---------------------------------------------------------------------===//
  194. ///
  195. /// ISHeuristic command line option for instruction schedulers.
  196. ///
  197. //===---------------------------------------------------------------------===//
  198. static cl::opt<RegisterScheduler::FunctionPassCtor, false,
  199. RegisterPassParser<RegisterScheduler> >
  200. ISHeuristic("pre-RA-sched",
  201. cl::init(&createDefaultScheduler),
  202. cl::desc("Instruction schedulers available (before register"
  203. " allocation):"));
  204. static RegisterScheduler
  205. defaultListDAGScheduler("default", "Best scheduler for the target",
  206. createDefaultScheduler);
  207. namespace llvm {
  208. //===--------------------------------------------------------------------===//
  209. /// createDefaultScheduler - This creates an instruction scheduler appropriate
  210. /// for the target.
  211. ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
  212. CodeGenOpt::Level OptLevel) {
  213. const TargetLowering &TLI = IS->getTargetLowering();
  214. const TargetSubtargetInfo &ST = IS->TM.getSubtarget<TargetSubtargetInfo>();
  215. if (OptLevel == CodeGenOpt::None || ST.enableMachineScheduler() ||
  216. TLI.getSchedulingPreference() == Sched::Source)
  217. return createSourceListDAGScheduler(IS, OptLevel);
  218. if (TLI.getSchedulingPreference() == Sched::RegPressure)
  219. return createBURRListDAGScheduler(IS, OptLevel);
  220. if (TLI.getSchedulingPreference() == Sched::Hybrid)
  221. return createHybridListDAGScheduler(IS, OptLevel);
  222. if (TLI.getSchedulingPreference() == Sched::VLIW)
  223. return createVLIWDAGScheduler(IS, OptLevel);
  224. assert(TLI.getSchedulingPreference() == Sched::ILP &&
  225. "Unknown sched type!");
  226. return createILPListDAGScheduler(IS, OptLevel);
  227. }
  228. }
  229. // EmitInstrWithCustomInserter - This method should be implemented by targets
  230. // that mark instructions with the 'usesCustomInserter' flag. These
  231. // instructions are special in various ways, which require special support to
  232. // insert. The specified MachineInstr is created but not inserted into any
  233. // basic blocks, and this method is called to expand it into a sequence of
  234. // instructions, potentially also creating new basic blocks and control flow.
  235. // When new basic blocks are inserted and the edges from MBB to its successors
  236. // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
  237. // DenseMap.
  238. MachineBasicBlock *
  239. TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
  240. MachineBasicBlock *MBB) const {
  241. #ifndef NDEBUG
  242. dbgs() << "If a target marks an instruction with "
  243. "'usesCustomInserter', it must implement "
  244. "TargetLowering::EmitInstrWithCustomInserter!";
  245. #endif
  246. llvm_unreachable(0);
  247. }
  248. void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
  249. SDNode *Node) const {
  250. assert(!MI->hasPostISelHook() &&
  251. "If a target marks an instruction with 'hasPostISelHook', "
  252. "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
  253. }
  254. //===----------------------------------------------------------------------===//
  255. // SelectionDAGISel code
  256. //===----------------------------------------------------------------------===//
  257. SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm,
  258. CodeGenOpt::Level OL) :
  259. MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
  260. FuncInfo(new FunctionLoweringInfo(TLI)),
  261. CurDAG(new SelectionDAG(tm, OL)),
  262. SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
  263. GFI(),
  264. OptLevel(OL),
  265. DAGSize(0) {
  266. initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
  267. initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
  268. initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
  269. initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
  270. }
  271. SelectionDAGISel::~SelectionDAGISel() {
  272. delete SDB;
  273. delete CurDAG;
  274. delete FuncInfo;
  275. }
  276. void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
  277. AU.addRequired<AliasAnalysis>();
  278. AU.addPreserved<AliasAnalysis>();
  279. AU.addRequired<GCModuleInfo>();
  280. AU.addPreserved<GCModuleInfo>();
  281. AU.addRequired<TargetLibraryInfo>();
  282. if (UseMBPI && OptLevel != CodeGenOpt::None)
  283. AU.addRequired<BranchProbabilityInfo>();
  284. MachineFunctionPass::getAnalysisUsage(AU);
  285. }
  286. /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
  287. /// may trap on it. In this case we have to split the edge so that the path
  288. /// through the predecessor block that doesn't go to the phi block doesn't
  289. /// execute the possibly trapping instruction.
  290. ///
  291. /// This is required for correctness, so it must be done at -O0.
  292. ///
  293. static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
  294. // Loop for blocks with phi nodes.
  295. for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
  296. PHINode *PN = dyn_cast<PHINode>(BB->begin());
  297. if (PN == 0) continue;
  298. ReprocessBlock:
  299. // For each block with a PHI node, check to see if any of the input values
  300. // are potentially trapping constant expressions. Constant expressions are
  301. // the only potentially trapping value that can occur as the argument to a
  302. // PHI.
  303. for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
  304. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  305. ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
  306. if (CE == 0 || !CE->canTrap()) continue;
  307. // The only case we have to worry about is when the edge is critical.
  308. // Since this block has a PHI Node, we assume it has multiple input
  309. // edges: check to see if the pred has multiple successors.
  310. BasicBlock *Pred = PN->getIncomingBlock(i);
  311. if (Pred->getTerminator()->getNumSuccessors() == 1)
  312. continue;
  313. // Okay, we have to split this edge.
  314. SplitCriticalEdge(Pred->getTerminator(),
  315. GetSuccessorNumber(Pred, BB), SDISel, true);
  316. goto ReprocessBlock;
  317. }
  318. }
  319. }
  320. bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
  321. // Do some sanity-checking on the command-line options.
  322. assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
  323. "-fast-isel-verbose requires -fast-isel");
  324. assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
  325. "-fast-isel-abort requires -fast-isel");
  326. const Function &Fn = *mf.getFunction();
  327. const TargetInstrInfo &TII = *TM.getInstrInfo();
  328. const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
  329. MF = &mf;
  330. RegInfo = &MF->getRegInfo();
  331. AA = &getAnalysis<AliasAnalysis>();
  332. LibInfo = &getAnalysis<TargetLibraryInfo>();
  333. TTI = getAnalysisIfAvailable<TargetTransformInfo>();
  334. GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
  335. TargetSubtargetInfo &ST =
  336. const_cast<TargetSubtargetInfo&>(TM.getSubtarget<TargetSubtargetInfo>());
  337. ST.resetSubtargetFeatures(MF);
  338. TM.resetTargetOptions(MF);
  339. DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
  340. SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
  341. CurDAG->init(*MF, TTI);
  342. FuncInfo->set(Fn, *MF);
  343. if (UseMBPI && OptLevel != CodeGenOpt::None)
  344. FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
  345. else
  346. FuncInfo->BPI = 0;
  347. SDB->init(GFI, *AA, LibInfo);
  348. MF->setHasMSInlineAsm(false);
  349. SelectAllBasicBlocks(Fn);
  350. // If the first basic block in the function has live ins that need to be
  351. // copied into vregs, emit the copies into the top of the block before
  352. // emitting the code for the block.
  353. MachineBasicBlock *EntryMBB = MF->begin();
  354. RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
  355. DenseMap<unsigned, unsigned> LiveInMap;
  356. if (!FuncInfo->ArgDbgValues.empty())
  357. for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
  358. E = RegInfo->livein_end(); LI != E; ++LI)
  359. if (LI->second)
  360. LiveInMap.insert(std::make_pair(LI->first, LI->second));
  361. // Insert DBG_VALUE instructions for function arguments to the entry block.
  362. for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
  363. MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
  364. unsigned Reg = MI->getOperand(0).getReg();
  365. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  366. EntryMBB->insert(EntryMBB->begin(), MI);
  367. else {
  368. MachineInstr *Def = RegInfo->getVRegDef(Reg);
  369. MachineBasicBlock::iterator InsertPos = Def;
  370. // FIXME: VR def may not be in entry block.
  371. Def->getParent()->insert(llvm::next(InsertPos), MI);
  372. }
  373. // If Reg is live-in then update debug info to track its copy in a vreg.
  374. DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
  375. if (LDI != LiveInMap.end()) {
  376. MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
  377. MachineBasicBlock::iterator InsertPos = Def;
  378. const MDNode *Variable =
  379. MI->getOperand(MI->getNumOperands()-1).getMetadata();
  380. unsigned Offset = MI->getOperand(1).getImm();
  381. // Def is never a terminator here, so it is ok to increment InsertPos.
  382. BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
  383. TII.get(TargetOpcode::DBG_VALUE))
  384. .addReg(LDI->second, RegState::Debug)
  385. .addImm(Offset).addMetadata(Variable);
  386. // If this vreg is directly copied into an exported register then
  387. // that COPY instructions also need DBG_VALUE, if it is the only
  388. // user of LDI->second.
  389. MachineInstr *CopyUseMI = NULL;
  390. for (MachineRegisterInfo::use_iterator
  391. UI = RegInfo->use_begin(LDI->second);
  392. MachineInstr *UseMI = UI.skipInstruction();) {
  393. if (UseMI->isDebugValue()) continue;
  394. if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
  395. CopyUseMI = UseMI; continue;
  396. }
  397. // Otherwise this is another use or second copy use.
  398. CopyUseMI = NULL; break;
  399. }
  400. if (CopyUseMI) {
  401. MachineInstr *NewMI =
  402. BuildMI(*MF, CopyUseMI->getDebugLoc(),
  403. TII.get(TargetOpcode::DBG_VALUE))
  404. .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
  405. .addImm(Offset).addMetadata(Variable);
  406. MachineBasicBlock::iterator Pos = CopyUseMI;
  407. EntryMBB->insertAfter(Pos, NewMI);
  408. }
  409. }
  410. }
  411. // Determine if there are any calls in this machine function.
  412. MachineFrameInfo *MFI = MF->getFrameInfo();
  413. for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
  414. ++I) {
  415. if (MFI->hasCalls() && MF->hasMSInlineAsm())
  416. break;
  417. const MachineBasicBlock *MBB = I;
  418. for (MachineBasicBlock::const_iterator II = MBB->begin(), IE = MBB->end();
  419. II != IE; ++II) {
  420. const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
  421. if ((MCID.isCall() && !MCID.isReturn()) ||
  422. II->isStackAligningInlineAsm()) {
  423. MFI->setHasCalls(true);
  424. }
  425. if (II->isMSInlineAsm()) {
  426. MF->setHasMSInlineAsm(true);
  427. }
  428. }
  429. }
  430. // Determine if there is a call to setjmp in the machine function.
  431. MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
  432. // Replace forward-declared registers with the registers containing
  433. // the desired value.
  434. MachineRegisterInfo &MRI = MF->getRegInfo();
  435. for (DenseMap<unsigned, unsigned>::iterator
  436. I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
  437. I != E; ++I) {
  438. unsigned From = I->first;
  439. unsigned To = I->second;
  440. // If To is also scheduled to be replaced, find what its ultimate
  441. // replacement is.
  442. for (;;) {
  443. DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
  444. if (J == E) break;
  445. To = J->second;
  446. }
  447. // Replace it.
  448. MRI.replaceRegWith(From, To);
  449. }
  450. // Freeze the set of reserved registers now that MachineFrameInfo has been
  451. // set up. All the information required by getReservedRegs() should be
  452. // available now.
  453. MRI.freezeReservedRegs(*MF);
  454. // Release function-specific state. SDB and CurDAG are already cleared
  455. // at this point.
  456. FuncInfo->clear();
  457. return true;
  458. }
  459. void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
  460. BasicBlock::const_iterator End,
  461. bool &HadTailCall) {
  462. // Lower all of the non-terminator instructions. If a call is emitted
  463. // as a tail call, cease emitting nodes for this block. Terminators
  464. // are handled below.
  465. for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
  466. SDB->visit(*I);
  467. // Make sure the root of the DAG is up-to-date.
  468. CurDAG->setRoot(SDB->getControlRoot());
  469. HadTailCall = SDB->HasTailCall;
  470. SDB->clear();
  471. // Final step, emit the lowered DAG as machine code.
  472. CodeGenAndEmitDAG();
  473. }
  474. void SelectionDAGISel::ComputeLiveOutVRegInfo() {
  475. SmallPtrSet<SDNode*, 128> VisitedNodes;
  476. SmallVector<SDNode*, 128> Worklist;
  477. Worklist.push_back(CurDAG->getRoot().getNode());
  478. APInt KnownZero;
  479. APInt KnownOne;
  480. do {
  481. SDNode *N = Worklist.pop_back_val();
  482. // If we've already seen this node, ignore it.
  483. if (!VisitedNodes.insert(N))
  484. continue;
  485. // Otherwise, add all chain operands to the worklist.
  486. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  487. if (N->getOperand(i).getValueType() == MVT::Other)
  488. Worklist.push_back(N->getOperand(i).getNode());
  489. // If this is a CopyToReg with a vreg dest, process it.
  490. if (N->getOpcode() != ISD::CopyToReg)
  491. continue;
  492. unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
  493. if (!TargetRegisterInfo::isVirtualRegister(DestReg))
  494. continue;
  495. // Ignore non-scalar or non-integer values.
  496. SDValue Src = N->getOperand(2);
  497. EVT SrcVT = Src.getValueType();
  498. if (!SrcVT.isInteger() || SrcVT.isVector())
  499. continue;
  500. unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
  501. CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
  502. FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
  503. } while (!Worklist.empty());
  504. }
  505. void SelectionDAGISel::CodeGenAndEmitDAG() {
  506. std::string GroupName;
  507. if (TimePassesIsEnabled)
  508. GroupName = "Instruction Selection and Scheduling";
  509. std::string BlockName;
  510. int BlockNumber = -1;
  511. (void)BlockNumber;
  512. #ifdef NDEBUG
  513. if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
  514. ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
  515. ViewSUnitDAGs)
  516. #endif
  517. {
  518. BlockNumber = FuncInfo->MBB->getNumber();
  519. BlockName = MF->getName().str() + ":" +
  520. FuncInfo->MBB->getBasicBlock()->getName().str();
  521. }
  522. DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
  523. << " '" << BlockName << "'\n"; CurDAG->dump());
  524. if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
  525. // Run the DAG combiner in pre-legalize mode.
  526. {
  527. NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
  528. CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
  529. }
  530. DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
  531. << " '" << BlockName << "'\n"; CurDAG->dump());
  532. // Second step, hack on the DAG until it only uses operations and types that
  533. // the target supports.
  534. if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
  535. BlockName);
  536. bool Changed;
  537. {
  538. NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
  539. Changed = CurDAG->LegalizeTypes();
  540. }
  541. DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
  542. << " '" << BlockName << "'\n"; CurDAG->dump());
  543. if (Changed) {
  544. if (ViewDAGCombineLT)
  545. CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
  546. // Run the DAG combiner in post-type-legalize mode.
  547. {
  548. NamedRegionTimer T("DAG Combining after legalize types", GroupName,
  549. TimePassesIsEnabled);
  550. CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
  551. }
  552. DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
  553. << " '" << BlockName << "'\n"; CurDAG->dump());
  554. }
  555. {
  556. NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
  557. Changed = CurDAG->LegalizeVectors();
  558. }
  559. if (Changed) {
  560. {
  561. NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
  562. CurDAG->LegalizeTypes();
  563. }
  564. if (ViewDAGCombineLT)
  565. CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
  566. // Run the DAG combiner in post-type-legalize mode.
  567. {
  568. NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
  569. TimePassesIsEnabled);
  570. CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
  571. }
  572. DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
  573. << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
  574. }
  575. if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
  576. {
  577. NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
  578. CurDAG->Legalize();
  579. }
  580. DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
  581. << " '" << BlockName << "'\n"; CurDAG->dump());
  582. if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
  583. // Run the DAG combiner in post-legalize mode.
  584. {
  585. NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
  586. CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
  587. }
  588. DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
  589. << " '" << BlockName << "'\n"; CurDAG->dump());
  590. if (OptLevel != CodeGenOpt::None)
  591. ComputeLiveOutVRegInfo();
  592. if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
  593. // Third, instruction select all of the operations to machine code, adding the
  594. // code to the MachineBasicBlock.
  595. {
  596. NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
  597. DoInstructionSelection();
  598. }
  599. DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
  600. << " '" << BlockName << "'\n"; CurDAG->dump());
  601. if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
  602. // Schedule machine code.
  603. ScheduleDAGSDNodes *Scheduler = CreateScheduler();
  604. {
  605. NamedRegionTimer T("Instruction Scheduling", GroupName,
  606. TimePassesIsEnabled);
  607. Scheduler->Run(CurDAG, FuncInfo->MBB);
  608. }
  609. if (ViewSUnitDAGs) Scheduler->viewGraph();
  610. // Emit machine code to BB. This can change 'BB' to the last block being
  611. // inserted into.
  612. MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
  613. {
  614. NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
  615. // FuncInfo->InsertPt is passed by reference and set to the end of the
  616. // scheduled instructions.
  617. LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
  618. }
  619. // If the block was split, make sure we update any references that are used to
  620. // update PHI nodes later on.
  621. if (FirstMBB != LastMBB)
  622. SDB->UpdateSplitBlock(FirstMBB, LastMBB);
  623. // Free the scheduler state.
  624. {
  625. NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
  626. TimePassesIsEnabled);
  627. delete Scheduler;
  628. }
  629. // Free the SelectionDAG state, now that we're finished with it.
  630. CurDAG->clear();
  631. }
  632. namespace {
  633. /// ISelUpdater - helper class to handle updates of the instruction selection
  634. /// graph.
  635. class ISelUpdater : public SelectionDAG::DAGUpdateListener {
  636. SelectionDAG::allnodes_iterator &ISelPosition;
  637. public:
  638. ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
  639. : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
  640. /// NodeDeleted - Handle nodes deleted from the graph. If the node being
  641. /// deleted is the current ISelPosition node, update ISelPosition.
  642. ///
  643. virtual void NodeDeleted(SDNode *N, SDNode *E) {
  644. if (ISelPosition == SelectionDAG::allnodes_iterator(N))
  645. ++ISelPosition;
  646. }
  647. };
  648. } // end anonymous namespace
  649. void SelectionDAGISel::DoInstructionSelection() {
  650. DEBUG(dbgs() << "===== Instruction selection begins: BB#"
  651. << FuncInfo->MBB->getNumber()
  652. << " '" << FuncInfo->MBB->getName() << "'\n");
  653. PreprocessISelDAG();
  654. // Select target instructions for the DAG.
  655. {
  656. // Number all nodes with a topological order and set DAGSize.
  657. DAGSize = CurDAG->AssignTopologicalOrder();
  658. // Create a dummy node (which is not added to allnodes), that adds
  659. // a reference to the root node, preventing it from being deleted,
  660. // and tracking any changes of the root.
  661. HandleSDNode Dummy(CurDAG->getRoot());
  662. SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
  663. ++ISelPosition;
  664. // Make sure that ISelPosition gets properly updated when nodes are deleted
  665. // in calls made from this function.
  666. ISelUpdater ISU(*CurDAG, ISelPosition);
  667. // The AllNodes list is now topological-sorted. Visit the
  668. // nodes by starting at the end of the list (the root of the
  669. // graph) and preceding back toward the beginning (the entry
  670. // node).
  671. while (ISelPosition != CurDAG->allnodes_begin()) {
  672. SDNode *Node = --ISelPosition;
  673. // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
  674. // but there are currently some corner cases that it misses. Also, this
  675. // makes it theoretically possible to disable the DAGCombiner.
  676. if (Node->use_empty())
  677. continue;
  678. SDNode *ResNode = Select(Node);
  679. // FIXME: This is pretty gross. 'Select' should be changed to not return
  680. // anything at all and this code should be nuked with a tactical strike.
  681. // If node should not be replaced, continue with the next one.
  682. if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
  683. continue;
  684. // Replace node.
  685. if (ResNode) {
  686. // Propagate ordering
  687. CurDAG->AssignOrdering(ResNode, CurDAG->GetOrdering(Node));
  688. ReplaceUses(Node, ResNode);
  689. }
  690. // If after the replacement this node is not used any more,
  691. // remove this dead node.
  692. if (Node->use_empty()) // Don't delete EntryToken, etc.
  693. CurDAG->RemoveDeadNode(Node);
  694. }
  695. CurDAG->setRoot(Dummy.getValue());
  696. }
  697. DEBUG(dbgs() << "===== Instruction selection ends:\n");
  698. PostprocessISelDAG();
  699. }
  700. /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
  701. /// do other setup for EH landing-pad blocks.
  702. void SelectionDAGISel::PrepareEHLandingPad() {
  703. MachineBasicBlock *MBB = FuncInfo->MBB;
  704. // Add a label to mark the beginning of the landing pad. Deletion of the
  705. // landing pad can thus be detected via the MachineModuleInfo.
  706. MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
  707. // Assign the call site to the landing pad's begin label.
  708. MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
  709. const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
  710. BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
  711. .addSym(Label);
  712. // Mark exception register as live in.
  713. unsigned Reg = TLI.getExceptionPointerRegister();
  714. if (Reg) MBB->addLiveIn(Reg);
  715. // Mark exception selector register as live in.
  716. Reg = TLI.getExceptionSelectorRegister();
  717. if (Reg) MBB->addLiveIn(Reg);
  718. }
  719. /// isFoldedOrDeadInstruction - Return true if the specified instruction is
  720. /// side-effect free and is either dead or folded into a generated instruction.
  721. /// Return false if it needs to be emitted.
  722. static bool isFoldedOrDeadInstruction(const Instruction *I,
  723. FunctionLoweringInfo *FuncInfo) {
  724. return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
  725. !isa<TerminatorInst>(I) && // Terminators aren't folded.
  726. !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
  727. !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
  728. !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
  729. }
  730. #ifndef NDEBUG
  731. // Collect per Instruction statistics for fast-isel misses. Only those
  732. // instructions that cause the bail are accounted for. It does not account for
  733. // instructions higher in the block. Thus, summing the per instructions stats
  734. // will not add up to what is reported by NumFastIselFailures.
  735. static void collectFailStats(const Instruction *I) {
  736. switch (I->getOpcode()) {
  737. default: assert (0 && "<Invalid operator> ");
  738. // Terminators
  739. case Instruction::Ret: NumFastIselFailRet++; return;
  740. case Instruction::Br: NumFastIselFailBr++; return;
  741. case Instruction::Switch: NumFastIselFailSwitch++; return;
  742. case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
  743. case Instruction::Invoke: NumFastIselFailInvoke++; return;
  744. case Instruction::Resume: NumFastIselFailResume++; return;
  745. case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
  746. // Standard binary operators...
  747. case Instruction::Add: NumFastIselFailAdd++; return;
  748. case Instruction::FAdd: NumFastIselFailFAdd++; return;
  749. case Instruction::Sub: NumFastIselFailSub++; return;
  750. case Instruction::FSub: NumFastIselFailFSub++; return;
  751. case Instruction::Mul: NumFastIselFailMul++; return;
  752. case Instruction::FMul: NumFastIselFailFMul++; return;
  753. case Instruction::UDiv: NumFastIselFailUDiv++; return;
  754. case Instruction::SDiv: NumFastIselFailSDiv++; return;
  755. case Instruction::FDiv: NumFastIselFailFDiv++; return;
  756. case Instruction::URem: NumFastIselFailURem++; return;
  757. case Instruction::SRem: NumFastIselFailSRem++; return;
  758. case Instruction::FRem: NumFastIselFailFRem++; return;
  759. // Logical operators...
  760. case Instruction::And: NumFastIselFailAnd++; return;
  761. case Instruction::Or: NumFastIselFailOr++; return;
  762. case Instruction::Xor: NumFastIselFailXor++; return;
  763. // Memory instructions...
  764. case Instruction::Alloca: NumFastIselFailAlloca++; return;
  765. case Instruction::Load: NumFastIselFailLoad++; return;
  766. case Instruction::Store: NumFastIselFailStore++; return;
  767. case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
  768. case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
  769. case Instruction::Fence: NumFastIselFailFence++; return;
  770. case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
  771. // Convert instructions...
  772. case Instruction::Trunc: NumFastIselFailTrunc++; return;
  773. case Instruction::ZExt: NumFastIselFailZExt++; return;
  774. case Instruction::SExt: NumFastIselFailSExt++; return;
  775. case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
  776. case Instruction::FPExt: NumFastIselFailFPExt++; return;
  777. case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
  778. case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
  779. case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
  780. case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
  781. case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
  782. case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
  783. case Instruction::BitCast: NumFastIselFailBitCast++; return;
  784. // Other instructions...
  785. case Instruction::ICmp: NumFastIselFailICmp++; return;
  786. case Instruction::FCmp: NumFastIselFailFCmp++; return;
  787. case Instruction::PHI: NumFastIselFailPHI++; return;
  788. case Instruction::Select: NumFastIselFailSelect++; return;
  789. case Instruction::Call: NumFastIselFailCall++; return;
  790. case Instruction::Shl: NumFastIselFailShl++; return;
  791. case Instruction::LShr: NumFastIselFailLShr++; return;
  792. case Instruction::AShr: NumFastIselFailAShr++; return;
  793. case Instruction::VAArg: NumFastIselFailVAArg++; return;
  794. case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
  795. case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
  796. case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
  797. case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
  798. case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
  799. case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
  800. }
  801. }
  802. #endif
  803. void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
  804. // Initialize the Fast-ISel state, if needed.
  805. FastISel *FastIS = 0;
  806. if (TM.Options.EnableFastISel)
  807. FastIS = TLI.createFastISel(*FuncInfo, LibInfo);
  808. // Iterate over all basic blocks in the function.
  809. ReversePostOrderTraversal<const Function*> RPOT(&Fn);
  810. for (ReversePostOrderTraversal<const Function*>::rpo_iterator
  811. I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
  812. const BasicBlock *LLVMBB = *I;
  813. if (OptLevel != CodeGenOpt::None) {
  814. bool AllPredsVisited = true;
  815. for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
  816. PI != PE; ++PI) {
  817. if (!FuncInfo->VisitedBBs.count(*PI)) {
  818. AllPredsVisited = false;
  819. break;
  820. }
  821. }
  822. if (AllPredsVisited) {
  823. for (BasicBlock::const_iterator I = LLVMBB->begin();
  824. const PHINode *PN = dyn_cast<PHINode>(I); ++I)
  825. FuncInfo->ComputePHILiveOutRegInfo(PN);
  826. } else {
  827. for (BasicBlock::const_iterator I = LLVMBB->begin();
  828. const PHINode *PN = dyn_cast<PHINode>(I); ++I)
  829. FuncInfo->InvalidatePHILiveOutRegInfo(PN);
  830. }
  831. FuncInfo->VisitedBBs.insert(LLVMBB);
  832. }
  833. BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
  834. BasicBlock::const_iterator const End = LLVMBB->end();
  835. BasicBlock::const_iterator BI = End;
  836. FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
  837. FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
  838. // Setup an EH landing-pad block.
  839. if (FuncInfo->MBB->isLandingPad())
  840. PrepareEHLandingPad();
  841. // Before doing SelectionDAG ISel, see if FastISel has been requested.
  842. if (FastIS) {
  843. FastIS->startNewBlock();
  844. // Emit code for any incoming arguments. This must happen before
  845. // beginning FastISel on the entry block.
  846. if (LLVMBB == &Fn.getEntryBlock()) {
  847. ++NumEntryBlocks;
  848. // Lower any arguments needed in this block if this is the entry block.
  849. if (!FastIS->LowerArguments()) {
  850. // Fast isel failed to lower these arguments
  851. ++NumFastIselFailLowerArguments;
  852. if (EnableFastISelAbortArgs)
  853. llvm_unreachable("FastISel didn't lower all arguments");
  854. // Use SelectionDAG argument lowering
  855. LowerArguments(Fn);
  856. CurDAG->setRoot(SDB->getControlRoot());
  857. SDB->clear();
  858. CodeGenAndEmitDAG();
  859. }
  860. // If we inserted any instructions at the beginning, make a note of
  861. // where they are, so we can be sure to emit subsequent instructions
  862. // after them.
  863. if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
  864. FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
  865. else
  866. FastIS->setLastLocalValue(0);
  867. }
  868. unsigned NumFastIselRemaining = std::distance(Begin, End);
  869. // Do FastISel on as many instructions as possible.
  870. for (; BI != Begin; --BI) {
  871. const Instruction *Inst = llvm::prior(BI);
  872. // If we no longer require this instruction, skip it.
  873. if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
  874. --NumFastIselRemaining;
  875. continue;
  876. }
  877. // Bottom-up: reset the insert pos at the top, after any local-value
  878. // instructions.
  879. FastIS->recomputeInsertPt();
  880. // Try to select the instruction with FastISel.
  881. if (FastIS->SelectInstruction(Inst)) {
  882. --NumFastIselRemaining;
  883. ++NumFastIselSuccess;
  884. // If fast isel succeeded, skip over all the folded instructions, and
  885. // then see if there is a load right before the selected instructions.
  886. // Try to fold the load if so.
  887. const Instruction *BeforeInst = Inst;
  888. while (BeforeInst != Begin) {
  889. BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
  890. if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
  891. break;
  892. }
  893. if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
  894. BeforeInst->hasOneUse() &&
  895. FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
  896. // If we succeeded, don't re-select the load.
  897. BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
  898. --NumFastIselRemaining;
  899. ++NumFastIselSuccess;
  900. }
  901. continue;
  902. }
  903. #ifndef NDEBUG
  904. if (EnableFastISelVerbose2)
  905. collectFailStats(Inst);
  906. #endif
  907. // Then handle certain instructions as single-LLVM-Instruction blocks.
  908. if (isa<CallInst>(Inst)) {
  909. if (EnableFastISelVerbose || EnableFastISelAbort) {
  910. dbgs() << "FastISel missed call: ";
  911. Inst->dump();
  912. }
  913. if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
  914. unsigned &R = FuncInfo->ValueMap[Inst];
  915. if (!R)
  916. R = FuncInfo->CreateRegs(Inst->getType());
  917. }
  918. bool HadTailCall = false;
  919. MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
  920. SelectBasicBlock(Inst, BI, HadTailCall);
  921. // If the call was emitted as a tail call, we're done with the block.
  922. // We also need to delete any previously emitted instructions.
  923. if (HadTailCall) {
  924. FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
  925. --BI;
  926. break;
  927. }
  928. // Recompute NumFastIselRemaining as Selection DAG instruction
  929. // selection may have handled the call, input args, etc.
  930. unsigned RemainingNow = std::distance(Begin, BI);
  931. NumFastIselFailures += NumFastIselRemaining - RemainingNow;
  932. NumFastIselRemaining = RemainingNow;
  933. continue;
  934. }
  935. if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
  936. // Don't abort, and use a different message for terminator misses.
  937. NumFastIselFailures += NumFastIselRemaining;
  938. if (EnableFastISelVerbose || EnableFastISelAbort) {
  939. dbgs() << "FastISel missed terminator: ";
  940. Inst->dump();
  941. }
  942. } else {
  943. NumFastIselFailures += NumFastIselRemaining;
  944. if (EnableFastISelVerbose || EnableFastISelAbort) {
  945. dbgs() << "FastISel miss: ";
  946. Inst->dump();
  947. }
  948. if (EnableFastISelAbort)
  949. // The "fast" selector couldn't handle something and bailed.
  950. // For the purpose of debugging, just abort.
  951. llvm_unreachable("FastISel didn't select the entire block");
  952. }
  953. break;
  954. }
  955. FastIS->recomputeInsertPt();
  956. } else {
  957. // Lower any arguments needed in this block if this is the entry block.
  958. if (LLVMBB == &Fn.getEntryBlock()) {
  959. ++NumEntryBlocks;
  960. LowerArguments(Fn);
  961. }
  962. }
  963. if (Begin != BI)
  964. ++NumDAGBlocks;
  965. else
  966. ++NumFastIselBlocks;
  967. if (Begin != BI) {
  968. // Run SelectionDAG instruction selection on the remainder of the block
  969. // not handled by FastISel. If FastISel is not run, this is the entire
  970. // block.
  971. bool HadTailCall;
  972. SelectBasicBlock(Begin, BI, HadTailCall);
  973. }
  974. FinishBasicBlock();
  975. FuncInfo->PHINodesToUpdate.clear();
  976. }
  977. delete FastIS;
  978. SDB->clearDanglingDebugInfo();
  979. }
  980. void
  981. SelectionDAGISel::FinishBasicBlock() {
  982. DEBUG(dbgs() << "Total amount of phi nodes to update: "
  983. << FuncInfo->PHINodesToUpdate.size() << "\n";
  984. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
  985. dbgs() << "Node " << i << " : ("
  986. << FuncInfo->PHINodesToUpdate[i].first
  987. << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
  988. // Next, now that we know what the last MBB the LLVM BB expanded is, update
  989. // PHI nodes in successors.
  990. if (SDB->SwitchCases.empty() &&
  991. SDB->JTCases.empty() &&
  992. SDB->BitTestCases.empty()) {
  993. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
  994. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
  995. assert(PHI->isPHI() &&
  996. "This is not a machine PHI node that we are updating!");
  997. if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
  998. continue;
  999. PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
  1000. }
  1001. return;
  1002. }
  1003. for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
  1004. // Lower header first, if it wasn't already lowered
  1005. if (!SDB->BitTestCases[i].Emitted) {
  1006. // Set the current basic block to the mbb we wish to insert the code into
  1007. FuncInfo->MBB = SDB->BitTestCases[i].Parent;
  1008. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1009. // Emit the code
  1010. SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
  1011. CurDAG->setRoot(SDB->getRoot());
  1012. SDB->clear();
  1013. CodeGenAndEmitDAG();
  1014. }
  1015. uint32_t UnhandledWeight = 0;
  1016. for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
  1017. UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
  1018. for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
  1019. UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
  1020. // Set the current basic block to the mbb we wish to insert the code into
  1021. FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
  1022. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1023. // Emit the code
  1024. if (j+1 != ej)
  1025. SDB->visitBitTestCase(SDB->BitTestCases[i],
  1026. SDB->BitTestCases[i].Cases[j+1].ThisBB,
  1027. UnhandledWeight,
  1028. SDB->BitTestCases[i].Reg,
  1029. SDB->BitTestCases[i].Cases[j],
  1030. FuncInfo->MBB);
  1031. else
  1032. SDB->visitBitTestCase(SDB->BitTestCases[i],
  1033. SDB->BitTestCases[i].Default,
  1034. UnhandledWeight,
  1035. SDB->BitTestCases[i].Reg,
  1036. SDB->BitTestCases[i].Cases[j],
  1037. FuncInfo->MBB);
  1038. CurDAG->setRoot(SDB->getRoot());
  1039. SDB->clear();
  1040. CodeGenAndEmitDAG();
  1041. }
  1042. // Update PHI Nodes
  1043. for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
  1044. pi != pe; ++pi) {
  1045. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
  1046. MachineBasicBlock *PHIBB = PHI->getParent();
  1047. assert(PHI->isPHI() &&
  1048. "This is not a machine PHI node that we are updating!");
  1049. // This is "default" BB. We have two jumps to it. From "header" BB and
  1050. // from last "case" BB.
  1051. if (PHIBB == SDB->BitTestCases[i].Default)
  1052. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
  1053. .addMBB(SDB->BitTestCases[i].Parent)
  1054. .addReg(FuncInfo->PHINodesToUpdate[pi].second)
  1055. .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
  1056. // One of "cases" BB.
  1057. for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
  1058. j != ej; ++j) {
  1059. MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
  1060. if (cBB->isSuccessor(PHIBB))
  1061. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
  1062. }
  1063. }
  1064. }
  1065. SDB->BitTestCases.clear();
  1066. // If the JumpTable record is filled in, then we need to emit a jump table.
  1067. // Updating the PHI nodes is tricky in this case, since we need to determine
  1068. // whether the PHI is a successor of the range check MBB or the jump table MBB
  1069. for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
  1070. // Lower header first, if it wasn't already lowered
  1071. if (!SDB->JTCases[i].first.Emitted) {
  1072. // Set the current basic block to the mbb we wish to insert the code into
  1073. FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
  1074. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1075. // Emit the code
  1076. SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
  1077. FuncInfo->MBB);
  1078. CurDAG->setRoot(SDB->getRoot());
  1079. SDB->clear();
  1080. CodeGenAndEmitDAG();
  1081. }
  1082. // Set the current basic block to the mbb we wish to insert the code into
  1083. FuncInfo->MBB = SDB->JTCases[i].second.MBB;
  1084. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1085. // Emit the code
  1086. SDB->visitJumpTable(SDB->JTCases[i].second);
  1087. CurDAG->setRoot(SDB->getRoot());
  1088. SDB->clear();
  1089. CodeGenAndEmitDAG();
  1090. // Update PHI Nodes
  1091. for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
  1092. pi != pe; ++pi) {
  1093. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
  1094. MachineBasicBlock *PHIBB = PHI->getParent();
  1095. assert(PHI->isPHI() &&
  1096. "This is not a machine PHI node that we are updating!");
  1097. // "default" BB. We can go there only from header BB.
  1098. if (PHIBB == SDB->JTCases[i].second.Default)
  1099. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
  1100. .addMBB(SDB->JTCases[i].first.HeaderBB);
  1101. // JT BB. Just iterate over successors here
  1102. if (FuncInfo->MBB->isSuccessor(PHIBB))
  1103. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
  1104. }
  1105. }
  1106. SDB->JTCases.clear();
  1107. // If the switch block involved a branch to one of the actual successors, we
  1108. // need to update PHI nodes in that block.
  1109. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
  1110. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
  1111. assert(PHI->isPHI() &&
  1112. "This is not a machine PHI node that we are updating!");
  1113. if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
  1114. PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
  1115. }
  1116. // If we generated any switch lowering information, build and codegen any
  1117. // additional DAGs necessary.
  1118. for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
  1119. // Set the current basic block to the mbb we wish to insert the code into
  1120. FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
  1121. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1122. // Determine the unique successors.
  1123. SmallVector<MachineBasicBlock *, 2> Succs;
  1124. Succs.push_back(SDB->SwitchCases[i].TrueBB);
  1125. if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
  1126. Succs.push_back(SDB->SwitchCases[i].FalseBB);
  1127. // Emit the code. Note that this could result in FuncInfo->MBB being split.
  1128. SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
  1129. CurDAG->setRoot(SDB->getRoot());
  1130. SDB->clear();
  1131. CodeGenAndEmitDAG();
  1132. // Remember the last block, now that any splitting is done, for use in
  1133. // populating PHI nodes in successors.
  1134. MachineBasicBlock *ThisBB = FuncInfo->MBB;
  1135. // Handle any PHI nodes in successors of this chunk, as if we were coming
  1136. // from the original BB before switch expansion. Note that PHI nodes can
  1137. // occur multiple times in PHINodesToUpdate. We have to be very careful to
  1138. // handle them the right number of times.
  1139. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1140. FuncInfo->MBB = Succs[i];
  1141. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1142. // FuncInfo->MBB may have been removed from the CFG if a branch was
  1143. // constant folded.
  1144. if (ThisBB->isSuccessor(FuncInfo->MBB)) {
  1145. for (MachineBasicBlock::iterator
  1146. MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
  1147. MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
  1148. MachineInstrBuilder PHI(*MF, MBBI);
  1149. // This value for this PHI node is recorded in PHINodesToUpdate.
  1150. for (unsigned pn = 0; ; ++pn) {
  1151. assert(pn != FuncInfo->PHINodesToUpdate.size() &&
  1152. "Didn't find PHI entry!");
  1153. if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
  1154. PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. SDB->SwitchCases.clear();
  1163. }
  1164. /// Create the scheduler. If a specific scheduler was specified
  1165. /// via the SchedulerRegistry, use it, otherwise select the
  1166. /// one preferred by the target.
  1167. ///
  1168. ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
  1169. RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
  1170. if (!Ctor) {
  1171. Ctor = ISHeuristic;
  1172. RegisterScheduler::setDefault(Ctor);
  1173. }
  1174. return Ctor(this, OptLevel);
  1175. }
  1176. //===----------------------------------------------------------------------===//
  1177. // Helper functions used by the generated instruction selector.
  1178. //===----------------------------------------------------------------------===//
  1179. // Calls to these methods are generated by tblgen.
  1180. /// CheckAndMask - The isel is trying to match something like (and X, 255). If
  1181. /// the dag combiner simplified the 255, we still want to match. RHS is the
  1182. /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
  1183. /// specified in the .td file (e.g. 255).
  1184. bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
  1185. int64_t DesiredMaskS) const {
  1186. const APInt &ActualMask = RHS->getAPIntValue();
  1187. const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
  1188. // If the actual mask exactly matches, success!
  1189. if (ActualMask == DesiredMask)
  1190. return true;
  1191. // If the actual AND mask is allowing unallowed bits, this doesn't match.
  1192. if (ActualMask.intersects(~DesiredMask))
  1193. return false;
  1194. // Otherwise, the DAG Combiner may have proven that the value coming in is
  1195. // either already zero or is not demanded. Check for known zero input bits.
  1196. APInt NeededMask = DesiredMask & ~ActualMask;
  1197. if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
  1198. return true;
  1199. // TODO: check to see if missing bits are just not demanded.
  1200. // Otherwise, this pattern doesn't match.
  1201. return false;
  1202. }
  1203. /// CheckOrMask - The isel is trying to match something like (or X, 255). If
  1204. /// the dag combiner simplified the 255, we still want to match. RHS is the
  1205. /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
  1206. /// specified in the .td file (e.g. 255).
  1207. bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
  1208. int64_t DesiredMaskS) const {
  1209. const APInt &ActualMask = RHS->getAPIntValue();
  1210. const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
  1211. // If the actual mask exactly matches, success!
  1212. if (ActualMask == DesiredMask)
  1213. return true;
  1214. // If the actual AND mask is allowing unallowed bits, this doesn't match.
  1215. if (ActualMask.intersects(~DesiredMask))
  1216. return false;
  1217. // Otherwise, the DAG Combiner may have proven that the value coming in is
  1218. // either already zero or is not demanded. Check for known zero input bits.
  1219. APInt NeededMask = DesiredMask & ~ActualMask;
  1220. APInt KnownZero, KnownOne;
  1221. CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
  1222. // If all the missing bits in the or are already known to be set, match!
  1223. if ((NeededMask & KnownOne) == NeededMask)
  1224. return true;
  1225. // TODO: check to see if missing bits are just not demanded.
  1226. // Otherwise, this pattern doesn't match.
  1227. return false;
  1228. }
  1229. /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
  1230. /// by tblgen. Others should not call it.
  1231. void SelectionDAGISel::
  1232. SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
  1233. std::vector<SDValue> InOps;
  1234. std::swap(InOps, Ops);
  1235. Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
  1236. Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
  1237. Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
  1238. Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
  1239. unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
  1240. if (InOps[e-1].getValueType() == MVT::Glue)
  1241. --e; // Don't process a glue operand if it is here.
  1242. while (i != e) {
  1243. unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
  1244. if (!InlineAsm::isMemKind(Flags)) {
  1245. // Just skip over this operand, copying the operands verbatim.
  1246. Ops.insert(Ops.end(), InOps.begin()+i,
  1247. InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
  1248. i += InlineAsm::getNumOperandRegisters(Flags) + 1;
  1249. } else {
  1250. assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
  1251. "Memory operand with multiple values?");
  1252. // Otherwise, this is a memory operand. Ask the target to select it.
  1253. std::vector<SDValue> SelOps;
  1254. if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
  1255. report_fatal_error("Could not match memory address. Inline asm"
  1256. " failure!");
  1257. // Add this to the output node.
  1258. unsigned NewFlags =
  1259. InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
  1260. Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
  1261. Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
  1262. i += 2;
  1263. }
  1264. }
  1265. // Add the glue input back if present.
  1266. if (e != InOps.size())
  1267. Ops.push_back(InOps.back());
  1268. }
  1269. /// findGlueUse - Return use of MVT::Glue value produced by the specified
  1270. /// SDNode.
  1271. ///
  1272. static SDNode *findGlueUse(SDNode *N) {
  1273. unsigned FlagResNo = N->getNumValues()-1;
  1274. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  1275. SDUse &Use = I.getUse();
  1276. if (Use.getResNo() == FlagResNo)
  1277. return Use.getUser();
  1278. }
  1279. return NULL;
  1280. }
  1281. /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
  1282. /// This function recursively traverses up the operand chain, ignoring
  1283. /// certain nodes.
  1284. static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
  1285. SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
  1286. bool IgnoreChains) {
  1287. // The NodeID's are given uniques ID's where a node ID is guaranteed to be
  1288. // greater than all of its (recursive) operands. If we scan to a point where
  1289. // 'use' is smaller than the node we're scanning for, then we know we will
  1290. // never find it.
  1291. //
  1292. // The Use may be -1 (unassigned) if it is a newly allocated node. This can
  1293. // happen because we scan down to newly selected nodes in the case of glue
  1294. // uses.
  1295. if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
  1296. return false;
  1297. // Don't revisit nodes if we already scanned it and didn't fail, we know we
  1298. // won't fail if we scan it again.
  1299. if (!Visited.insert(Use))
  1300. return false;
  1301. for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
  1302. // Ignore chain uses, they are validated by HandleMergeInputChains.
  1303. if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
  1304. continue;
  1305. SDNode *N = Use->getOperand(i).getNode();
  1306. if (N == Def) {
  1307. if (Use == ImmedUse || Use == Root)
  1308. continue; // We are not looking for immediate use.
  1309. assert(N != Root);
  1310. return true;
  1311. }
  1312. // Traverse up the operand chain.
  1313. if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
  1314. return true;
  1315. }
  1316. return false;
  1317. }
  1318. /// IsProfitableToFold - Returns true if it's profitable to fold the specific
  1319. /// operand node N of U during instruction selection that starts at Root.
  1320. bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
  1321. SDNode *Root) const {
  1322. if (OptLevel == CodeGenOpt::None) return false;
  1323. return N.hasOneUse();
  1324. }
  1325. /// IsLegalToFold - Returns true if the specific operand node N of
  1326. /// U can be folded during instruction selection that starts at Root.
  1327. bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
  1328. CodeGenOpt::Level OptLevel,
  1329. bool IgnoreChains) {
  1330. if (OptLevel == CodeGenOpt::None) return false;
  1331. // If Root use can somehow reach N through a path that that doesn't contain
  1332. // U then folding N would create a cycle. e.g. In the following
  1333. // diagram, Root can reach N through X. If N is folded into into Root, then
  1334. // X is both a predecessor and a successor of U.
  1335. //
  1336. // [N*] //
  1337. // ^ ^ //
  1338. // / \ //
  1339. // [U*] [X]? //
  1340. // ^ ^ //
  1341. // \ / //
  1342. // \ / //
  1343. // [Root*] //
  1344. //
  1345. // * indicates nodes to be folded together.
  1346. //
  1347. // If Root produces glue, then it gets (even more) interesting. Since it
  1348. // will be "glued" together with its glue use in the scheduler, we need to
  1349. // check if it might reach N.
  1350. //
  1351. // [N*] //
  1352. // ^ ^ //
  1353. // / \ //
  1354. // [U*] [X]? //
  1355. // ^ ^ //
  1356. // \ \ //
  1357. // \ | //
  1358. // [Root*] | //
  1359. // ^ | //
  1360. // f | //
  1361. // | / //
  1362. // [Y] / //
  1363. // ^ / //
  1364. // f / //
  1365. // | / //
  1366. // [GU] //
  1367. //
  1368. // If GU (glue use) indirectly reaches N (the load), and Root folds N
  1369. // (call it Fold), then X is a predecessor of GU and a successor of
  1370. // Fold. But since Fold and GU are glued together, this will create
  1371. // a cycle in the scheduling graph.
  1372. // If the node has glue, walk down the graph to the "lowest" node in the
  1373. // glueged set.
  1374. EVT VT = Root->getValueType(Root->getNumValues()-1);
  1375. while (VT == MVT::Glue) {
  1376. SDNode *GU = findGlueUse(Root);
  1377. if (GU == NULL)
  1378. break;
  1379. Root = GU;
  1380. VT = Root->getValueType(Root->getNumValues()-1);
  1381. // If our query node has a glue result with a use, we've walked up it. If
  1382. // the user (which has already been selected) has a chain or indirectly uses
  1383. // the chain, our WalkChainUsers predicate will not consider it. Because of
  1384. // this, we cannot ignore chains in this predicate.
  1385. IgnoreChains = false;
  1386. }
  1387. SmallPtrSet<SDNode*, 16> Visited;
  1388. return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
  1389. }
  1390. SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
  1391. std::vector<SDValue> Ops(N->op_begin(), N->op_end());
  1392. SelectInlineAsmMemoryOperands(Ops);
  1393. EVT VTs[] = { MVT::Other, MVT::Glue };
  1394. SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N),
  1395. VTs, &Ops[0], Ops.size());
  1396. New->setNodeId(-1);
  1397. return New.getNode();
  1398. }
  1399. SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
  1400. return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
  1401. }
  1402. /// GetVBR - decode a vbr encoding whose top bit is set.
  1403. LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
  1404. GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
  1405. assert(Val >= 128 && "Not a VBR");
  1406. Val &= 127; // Remove first vbr bit.
  1407. unsigned Shift = 7;
  1408. uint64_t NextBits;
  1409. do {
  1410. NextBits = MatcherTable[Idx++];
  1411. Val |= (NextBits&127) << Shift;
  1412. Shift += 7;
  1413. } while (NextBits & 128);
  1414. return Val;
  1415. }
  1416. /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
  1417. /// interior glue and chain results to use the new glue and chain results.
  1418. void SelectionDAGISel::
  1419. UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
  1420. const SmallVectorImpl<SDNode*> &ChainNodesMatched,
  1421. SDValue InputGlue,
  1422. const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
  1423. bool isMorphNodeTo) {
  1424. SmallVector<SDNode*, 4> NowDeadNodes;
  1425. // Now that all the normal results are replaced, we replace the chain and
  1426. // glue results if present.
  1427. if (!ChainNodesMatched.empty()) {
  1428. assert(InputChain.getNode() != 0 &&
  1429. "Matched input chains but didn't produce a chain");
  1430. // Loop over all of the nodes we matched that produced a chain result.
  1431. // Replace all the chain results with the final chain we ended up with.
  1432. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
  1433. SDNode *ChainNode = ChainNodesMatched[i];
  1434. // If this node was already deleted, don't look at it.
  1435. if (ChainNode->getOpcode() == ISD::DELETED_NODE)
  1436. continue;
  1437. // Don't replace the results of the root node if we're doing a
  1438. // MorphNodeTo.
  1439. if (ChainNode == NodeToMatch && isMorphNodeTo)
  1440. continue;
  1441. SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
  1442. if (ChainVal.getValueType() == MVT::Glue)
  1443. ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
  1444. assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
  1445. CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
  1446. // If the node became dead and we haven't already seen it, delete it.
  1447. if (ChainNode->use_empty() &&
  1448. !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
  1449. NowDeadNodes.push_back(ChainNode);
  1450. }
  1451. }
  1452. // If the result produces glue, update any glue results in the matched
  1453. // pattern with the glue result.
  1454. if (InputGlue.getNode() != 0) {
  1455. // Handle any interior nodes explicitly marked.
  1456. for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
  1457. SDNode *FRN = GlueResultNodesMatched[i];
  1458. // If this node was already deleted, don't look at it.
  1459. if (FRN->getOpcode() == ISD::DELETED_NODE)
  1460. continue;
  1461. assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
  1462. "Doesn't have a glue result");
  1463. CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
  1464. InputGlue);
  1465. // If the node became dead and we haven't already seen it, delete it.
  1466. if (FRN->use_empty() &&
  1467. !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
  1468. NowDeadNodes.push_back(FRN);
  1469. }
  1470. }
  1471. if (!NowDeadNodes.empty())
  1472. CurDAG->RemoveDeadNodes(NowDeadNodes);
  1473. DEBUG(dbgs() << "ISEL: Match complete!\n");
  1474. }
  1475. enum ChainResult {
  1476. CR_Simple,
  1477. CR_InducesCycle,
  1478. CR_LeadsToInteriorNode
  1479. };
  1480. /// WalkChainUsers - Walk down the users of the specified chained node that is
  1481. /// part of the pattern we're matching, looking at all of the users we find.
  1482. /// This determines whether something is an interior node, whether we have a
  1483. /// non-pattern node in between two pattern nodes (which prevent folding because
  1484. /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
  1485. /// between pattern nodes (in which case the TF becomes part of the pattern).
  1486. ///
  1487. /// The walk we do here is guaranteed to be small because we quickly get down to
  1488. /// already selected nodes "below" us.
  1489. static ChainResult
  1490. WalkChainUsers(const SDNode *ChainedNode,
  1491. SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
  1492. SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
  1493. ChainResult Result = CR_Simple;
  1494. for (SDNode::use_iterator UI = ChainedNode->use_begin(),
  1495. E = ChainedNode->use_end(); UI != E; ++UI) {
  1496. // Make sure the use is of the chain, not some other value we produce.
  1497. if (UI.getUse().getValueType() != MVT::Other) continue;
  1498. SDNode *User = *UI;
  1499. // If we see an already-selected machine node, then we've gone beyond the
  1500. // pattern that we're selecting down into the already selected chunk of the
  1501. // DAG.
  1502. if (User->isMachineOpcode() ||
  1503. User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
  1504. continue;
  1505. unsigned UserOpcode = User->getOpcode();
  1506. if (UserOpcode == ISD::CopyToReg ||
  1507. UserOpcode == ISD::CopyFromReg ||
  1508. UserOpcode == ISD::INLINEASM ||
  1509. UserOpcode == ISD::EH_LABEL ||
  1510. UserOpcode == ISD::LIFETIME_START ||
  1511. UserOpcode == ISD::LIFETIME_END) {
  1512. // If their node ID got reset to -1 then they've already been selected.
  1513. // Treat them like a MachineOpcode.
  1514. if (User->getNodeId() == -1)
  1515. continue;
  1516. }
  1517. // If we have a TokenFactor, we handle it specially.
  1518. if (User->getOpcode() != ISD::TokenFactor) {
  1519. // If the node isn't a token factor and isn't part of our pattern, then it
  1520. // must be a random chained node in between two nodes we're selecting.
  1521. // This happens when we have something like:
  1522. // x = load ptr
  1523. // call
  1524. // y = x+4
  1525. // store y -> ptr
  1526. // Because we structurally match the load/store as a read/modify/write,
  1527. // but the call is chained between them. We cannot fold in this case
  1528. // because it would induce a cycle in the graph.
  1529. if (!std::count(ChainedNodesInPattern.begin(),
  1530. ChainedNodesInPattern.end(), User))
  1531. return CR_InducesCycle;
  1532. // Otherwise we found a node that is part of our pattern. For example in:
  1533. // x = load ptr
  1534. // y = x+4
  1535. // store y -> ptr
  1536. // This would happen when we're scanning down from the load and see the
  1537. // store as a user. Record that there is a use of ChainedNode that is
  1538. // part of the pattern and keep scanning uses.
  1539. Result = CR_LeadsToInteriorNode;
  1540. InteriorChainedNodes.push_back(User);
  1541. continue;
  1542. }
  1543. // If we found a TokenFactor, there are two cases to consider: first if the
  1544. // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
  1545. // uses of the TF are in our pattern) we just want to ignore it. Second,
  1546. // the TokenFactor can be sandwiched in between two chained nodes, like so:
  1547. // [Load chain]
  1548. // ^
  1549. // |
  1550. // [Load]
  1551. // ^ ^
  1552. // | \ DAG's like cheese
  1553. // / \ do you?
  1554. // / |
  1555. // [TokenFactor] [Op]
  1556. // ^ ^
  1557. // | |
  1558. // \ /
  1559. // \ /
  1560. // [Store]
  1561. //
  1562. // In this case, the TokenFactor becomes part of our match and we rewrite it
  1563. // as a new TokenFactor.
  1564. //
  1565. // To distinguish these two cases, do a recursive walk down the uses.
  1566. switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
  1567. case CR_Simple:
  1568. // If the uses of the TokenFactor are just already-selected nodes, ignore
  1569. // it, it is "below" our pattern.
  1570. continue;
  1571. case CR_InducesCycle:
  1572. // If the uses of the TokenFactor lead to nodes that are not part of our
  1573. // pattern that are not selected, folding would turn this into a cycle,
  1574. // bail out now.
  1575. return CR_InducesCycle;
  1576. case CR_LeadsToInteriorNode:
  1577. break; // Otherwise, keep processing.
  1578. }
  1579. // Okay, we know we're in the interesting interior case. The TokenFactor
  1580. // is now going to be considered part of the pattern so that we rewrite its
  1581. // uses (it may have uses that are not part of the pattern) with the
  1582. // ultimate chain result of the generated code. We will also add its chain
  1583. // inputs as inputs to the ultimate TokenFactor we create.
  1584. Result = CR_LeadsToInteriorNode;
  1585. ChainedNodesInPattern.push_back(User);
  1586. InteriorChainedNodes.push_back(User);
  1587. continue;
  1588. }
  1589. return Result;
  1590. }
  1591. /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
  1592. /// operation for when the pattern matched at least one node with a chains. The
  1593. /// input vector contains a list of all of the chained nodes that we match. We
  1594. /// must determine if this is a valid thing to cover (i.e. matching it won't
  1595. /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
  1596. /// be used as the input node chain for the generated nodes.
  1597. static SDValue
  1598. HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
  1599. SelectionDAG *CurDAG) {
  1600. // Walk all of the chained nodes we've matched, recursively scanning down the
  1601. // users of the chain result. This adds any TokenFactor nodes that are caught
  1602. // in between chained nodes to the chained and interior nodes list.
  1603. SmallVector<SDNode*, 3> InteriorChainedNodes;
  1604. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
  1605. if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
  1606. InteriorChainedNodes) == CR_InducesCycle)
  1607. return SDValue(); // Would induce a cycle.
  1608. }
  1609. // Okay, we have walked all the matched nodes and collected TokenFactor nodes
  1610. // that we are interested in. Form our input TokenFactor node.
  1611. SmallVector<SDValue, 3> InputChains;
  1612. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
  1613. // Add the input chain of this node to the InputChains list (which will be
  1614. // the operands of the generated TokenFactor) if it's not an interior node.
  1615. SDNode *N = ChainNodesMatched[i];
  1616. if (N->getOpcode() != ISD::TokenFactor) {
  1617. if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
  1618. continue;
  1619. // Otherwise, add the input chain.
  1620. SDValue InChain = ChainNodesMatched[i]->getOperand(0);
  1621. assert(InChain.getValueType() == MVT::Other && "Not a chain");
  1622. InputChains.push_back(InChain);
  1623. continue;
  1624. }
  1625. // If we have a token factor, we want to add all inputs of the token factor
  1626. // that are not part of the pattern we're matching.
  1627. for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
  1628. if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
  1629. N->getOperand(op).getNode()))
  1630. InputChains.push_back(N->getOperand(op));
  1631. }
  1632. }
  1633. SDValue Res;
  1634. if (InputChains.size() == 1)
  1635. return InputChains[0];
  1636. return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
  1637. MVT::Other, &InputChains[0], InputChains.size());
  1638. }
  1639. /// MorphNode - Handle morphing a node in place for the selector.
  1640. SDNode *SelectionDAGISel::
  1641. MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
  1642. const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
  1643. // It is possible we're using MorphNodeTo to replace a node with no
  1644. // normal results with one that has a normal result (or we could be
  1645. // adding a chain) and the input could have glue and chains as well.
  1646. // In this case we need to shift the operands down.
  1647. // FIXME: This is a horrible hack and broken in obscure cases, no worse
  1648. // than the old isel though.
  1649. int OldGlueResultNo = -1, OldChainResultNo = -1;
  1650. unsigned NTMNumResults = Node->getNumValues();
  1651. if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
  1652. OldGlueResultNo = NTMNumResults-1;
  1653. if (NTMNumResults != 1 &&
  1654. Node->getValueType(NTMNumResults-2) == MVT::Other)
  1655. OldChainResultNo = NTMNumResults-2;
  1656. } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
  1657. OldChainResultNo = NTMNumResults-1;
  1658. // Call the underlying SelectionDAG routine to do the transmogrification. Note
  1659. // that this deletes operands of the old node that become dead.
  1660. SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
  1661. // MorphNodeTo can operate in two ways: if an existing node with the
  1662. // specified operands exists, it can just return it. Otherwise, it
  1663. // updates the node in place to have the requested operands.
  1664. if (Res == Node) {
  1665. // If we updated the node in place, reset the node ID. To the isel,
  1666. // this should be just like a newly allocated machine node.
  1667. Res->setNodeId(-1);
  1668. }
  1669. unsigned ResNumResults = Res->getNumValues();
  1670. // Move the glue if needed.
  1671. if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
  1672. (unsigned)OldGlueResultNo != ResNumResults-1)
  1673. CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
  1674. SDValue(Res, ResNumResults-1));
  1675. if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
  1676. --ResNumResults;
  1677. // Move the chain reference if needed.
  1678. if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
  1679. (unsigned)OldChainResultNo != ResNumResults-1)
  1680. CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
  1681. SDValue(Res, ResNumResults-1));
  1682. // Otherwise, no replacement happened because the node already exists. Replace
  1683. // Uses of the old node with the new one.
  1684. if (Res != Node)
  1685. CurDAG->ReplaceAllUsesWith(Node, Res);
  1686. return Res;
  1687. }
  1688. /// CheckSame - Implements OP_CheckSame.
  1689. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1690. CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1691. SDValue N,
  1692. const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
  1693. // Accept if it is exactly the same as a previously recorded node.
  1694. unsigned RecNo = MatcherTable[MatcherIndex++];
  1695. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  1696. return N == RecordedNodes[RecNo].first;
  1697. }
  1698. /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
  1699. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1700. CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1701. const SelectionDAGISel &SDISel) {
  1702. return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
  1703. }
  1704. /// CheckNodePredicate - Implements OP_CheckNodePredicate.
  1705. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1706. CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1707. const SelectionDAGISel &SDISel, SDNode *N) {
  1708. return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
  1709. }
  1710. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1711. CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1712. SDNode *N) {
  1713. uint16_t Opc = MatcherTable[MatcherIndex++];
  1714. Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  1715. return N->getOpcode() == Opc;
  1716. }
  1717. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1718. CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1719. SDValue N, const TargetLowering &TLI) {
  1720. MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  1721. if (N.getValueType() == VT) return true;
  1722. // Handle the case when VT is iPTR.
  1723. return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
  1724. }
  1725. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1726. CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1727. SDValue N, const TargetLowering &TLI,
  1728. unsigned ChildNo) {
  1729. if (ChildNo >= N.getNumOperands())
  1730. return false; // Match fails if out of range child #.
  1731. return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
  1732. }
  1733. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1734. CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1735. SDValue N) {
  1736. return cast<CondCodeSDNode>(N)->get() ==
  1737. (ISD::CondCode)MatcherTable[MatcherIndex++];
  1738. }
  1739. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1740. CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1741. SDValue N, const TargetLowering &TLI) {
  1742. MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  1743. if (cast<VTSDNode>(N)->getVT() == VT)
  1744. return true;
  1745. // Handle the case when VT is iPTR.
  1746. return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
  1747. }
  1748. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1749. CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1750. SDValue N) {
  1751. int64_t Val = MatcherTable[MatcherIndex++];
  1752. if (Val & 128)
  1753. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  1754. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
  1755. return C != 0 && C->getSExtValue() == Val;
  1756. }
  1757. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1758. CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1759. SDValue N, const SelectionDAGISel &SDISel) {
  1760. int64_t Val = MatcherTable[MatcherIndex++];
  1761. if (Val & 128)
  1762. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  1763. if (N->getOpcode() != ISD::AND) return false;
  1764. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1765. return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
  1766. }
  1767. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  1768. CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  1769. SDValue N, const SelectionDAGISel &SDISel) {
  1770. int64_t Val = MatcherTable[MatcherIndex++];
  1771. if (Val & 128)
  1772. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  1773. if (N->getOpcode() != ISD::OR) return false;
  1774. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1775. return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
  1776. }
  1777. /// IsPredicateKnownToFail - If we know how and can do so without pushing a
  1778. /// scope, evaluate the current node. If the current predicate is known to
  1779. /// fail, set Result=true and return anything. If the current predicate is
  1780. /// known to pass, set Result=false and return the MatcherIndex to continue
  1781. /// with. If the current predicate is unknown, set Result=false and return the
  1782. /// MatcherIndex to continue with.
  1783. static unsigned IsPredicateKnownToFail(const unsigned char *Table,
  1784. unsigned Index, SDValue N,
  1785. bool &Result,
  1786. const SelectionDAGISel &SDISel,
  1787. SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
  1788. switch (Table[Index++]) {
  1789. default:
  1790. Result = false;
  1791. return Index-1; // Could not evaluate this predicate.
  1792. case SelectionDAGISel::OPC_CheckSame:
  1793. Result = !::CheckSame(Table, Index, N, RecordedNodes);
  1794. return Index;
  1795. case SelectionDAGISel::OPC_CheckPatternPredicate:
  1796. Result = !::CheckPatternPredicate(Table, Index, SDISel);
  1797. return Index;
  1798. case SelectionDAGISel::OPC_CheckPredicate:
  1799. Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
  1800. return Index;
  1801. case SelectionDAGISel::OPC_CheckOpcode:
  1802. Result = !::CheckOpcode(Table, Index, N.getNode());
  1803. return Index;
  1804. case SelectionDAGISel::OPC_CheckType:
  1805. Result = !::CheckType(Table, Index, N, SDISel.TLI);
  1806. return Index;
  1807. case SelectionDAGISel::OPC_CheckChild0Type:
  1808. case SelectionDAGISel::OPC_CheckChild1Type:
  1809. case SelectionDAGISel::OPC_CheckChild2Type:
  1810. case SelectionDAGISel::OPC_CheckChild3Type:
  1811. case SelectionDAGISel::OPC_CheckChild4Type:
  1812. case SelectionDAGISel::OPC_CheckChild5Type:
  1813. case SelectionDAGISel::OPC_CheckChild6Type:
  1814. case SelectionDAGISel::OPC_CheckChild7Type:
  1815. Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
  1816. Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
  1817. return Index;
  1818. case SelectionDAGISel::OPC_CheckCondCode:
  1819. Result = !::CheckCondCode(Table, Index, N);
  1820. return Index;
  1821. case SelectionDAGISel::OPC_CheckValueType:
  1822. Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
  1823. return Index;
  1824. case SelectionDAGISel::OPC_CheckInteger:
  1825. Result = !::CheckInteger(Table, Index, N);
  1826. return Index;
  1827. case SelectionDAGISel::OPC_CheckAndImm:
  1828. Result = !::CheckAndImm(Table, Index, N, SDISel);
  1829. return Index;
  1830. case SelectionDAGISel::OPC_CheckOrImm:
  1831. Result = !::CheckOrImm(Table, Index, N, SDISel);
  1832. return Index;
  1833. }
  1834. }
  1835. namespace {
  1836. struct MatchScope {
  1837. /// FailIndex - If this match fails, this is the index to continue with.
  1838. unsigned FailIndex;
  1839. /// NodeStack - The node stack when the scope was formed.
  1840. SmallVector<SDValue, 4> NodeStack;
  1841. /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
  1842. unsigned NumRecordedNodes;
  1843. /// NumMatchedMemRefs - The number of matched memref entries.
  1844. unsigned NumMatchedMemRefs;
  1845. /// InputChain/InputGlue - The current chain/glue
  1846. SDValue InputChain, InputGlue;
  1847. /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
  1848. bool HasChainNodesMatched, HasGlueResultNodesMatched;
  1849. };
  1850. }
  1851. SDNode *SelectionDAGISel::
  1852. SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
  1853. unsigned TableSize) {
  1854. // FIXME: Should these even be selected? Handle these cases in the caller?
  1855. switch (NodeToMatch->getOpcode()) {
  1856. default:
  1857. break;
  1858. case ISD::EntryToken: // These nodes remain the same.
  1859. case ISD::BasicBlock:
  1860. case ISD::Register:
  1861. case ISD::RegisterMask:
  1862. //case ISD::VALUETYPE:
  1863. //case ISD::CONDCODE:
  1864. case ISD::HANDLENODE:
  1865. case ISD::MDNODE_SDNODE:
  1866. case ISD::TargetConstant:
  1867. case ISD::TargetConstantFP:
  1868. case ISD::TargetConstantPool:
  1869. case ISD::TargetFrameIndex:
  1870. case ISD::TargetExternalSymbol:
  1871. case ISD::TargetBlockAddress:
  1872. case ISD::TargetJumpTable:
  1873. case ISD::TargetGlobalTLSAddress:
  1874. case ISD::TargetGlobalAddress:
  1875. case ISD::TokenFactor:
  1876. case ISD::CopyFromReg:
  1877. case ISD::CopyToReg:
  1878. case ISD::EH_LABEL:
  1879. case ISD::LIFETIME_START:
  1880. case ISD::LIFETIME_END:
  1881. NodeToMatch->setNodeId(-1); // Mark selected.
  1882. return 0;
  1883. case ISD::AssertSext:
  1884. case ISD::AssertZext:
  1885. CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
  1886. NodeToMatch->getOperand(0));
  1887. return 0;
  1888. case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
  1889. case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
  1890. }
  1891. assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
  1892. // Set up the node stack with NodeToMatch as the only node on the stack.
  1893. SmallVector<SDValue, 8> NodeStack;
  1894. SDValue N = SDValue(NodeToMatch, 0);
  1895. NodeStack.push_back(N);
  1896. // MatchScopes - Scopes used when matching, if a match failure happens, this
  1897. // indicates where to continue checking.
  1898. SmallVector<MatchScope, 8> MatchScopes;
  1899. // RecordedNodes - This is the set of nodes that have been recorded by the
  1900. // state machine. The second value is the parent of the node, or null if the
  1901. // root is recorded.
  1902. SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
  1903. // MatchedMemRefs - This is the set of MemRef's we've seen in the input
  1904. // pattern.
  1905. SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
  1906. // These are the current input chain and glue for use when generating nodes.
  1907. // Various Emit operations change these. For example, emitting a copytoreg
  1908. // uses and updates these.
  1909. SDValue InputChain, InputGlue;
  1910. // ChainNodesMatched - If a pattern matches nodes that have input/output
  1911. // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
  1912. // which ones they are. The result is captured into this list so that we can
  1913. // update the chain results when the pattern is complete.
  1914. SmallVector<SDNode*, 3> ChainNodesMatched;
  1915. SmallVector<SDNode*, 3> GlueResultNodesMatched;
  1916. DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
  1917. NodeToMatch->dump(CurDAG);
  1918. dbgs() << '\n');
  1919. // Determine where to start the interpreter. Normally we start at opcode #0,
  1920. // but if the state machine starts with an OPC_SwitchOpcode, then we
  1921. // accelerate the first lookup (which is guaranteed to be hot) with the
  1922. // OpcodeOffset table.
  1923. unsigned MatcherIndex = 0;
  1924. if (!OpcodeOffset.empty()) {
  1925. // Already computed the OpcodeOffset table, just index into it.
  1926. if (N.getOpcode() < OpcodeOffset.size())
  1927. MatcherIndex = OpcodeOffset[N.getOpcode()];
  1928. DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
  1929. } else if (MatcherTable[0] == OPC_SwitchOpcode) {
  1930. // Otherwise, the table isn't computed, but the state machine does start
  1931. // with an OPC_SwitchOpcode instruction. Populate the table now, since this
  1932. // is the first time we're selecting an instruction.
  1933. unsigned Idx = 1;
  1934. while (1) {
  1935. // Get the size of this case.
  1936. unsigned CaseSize = MatcherTable[Idx++];
  1937. if (CaseSize & 128)
  1938. CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
  1939. if (CaseSize == 0) break;
  1940. // Get the opcode, add the index to the table.
  1941. uint16_t Opc = MatcherTable[Idx++];
  1942. Opc |= (unsigned short)MatcherTable[Idx++] << 8;
  1943. if (Opc >= OpcodeOffset.size())
  1944. OpcodeOffset.resize((Opc+1)*2);
  1945. OpcodeOffset[Opc] = Idx;
  1946. Idx += CaseSize;
  1947. }
  1948. // Okay, do the lookup for the first opcode.
  1949. if (N.getOpcode() < OpcodeOffset.size())
  1950. MatcherIndex = OpcodeOffset[N.getOpcode()];
  1951. }
  1952. while (1) {
  1953. assert(MatcherIndex < TableSize && "Invalid index");
  1954. #ifndef NDEBUG
  1955. unsigned CurrentOpcodeIndex = MatcherIndex;
  1956. #endif
  1957. BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
  1958. switch (Opcode) {
  1959. case OPC_Scope: {
  1960. // Okay, the semantics of this operation are that we should push a scope
  1961. // then evaluate the first child. However, pushing a scope only to have
  1962. // the first check fail (which then pops it) is inefficient. If we can
  1963. // determine immediately that the first check (or first several) will
  1964. // immediately fail, don't even bother pushing a scope for them.
  1965. unsigned FailIndex;
  1966. while (1) {
  1967. unsigned NumToSkip = MatcherTable[MatcherIndex++];
  1968. if (NumToSkip & 128)
  1969. NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
  1970. // Found the end of the scope with no match.
  1971. if (NumToSkip == 0) {
  1972. FailIndex = 0;
  1973. break;
  1974. }
  1975. FailIndex = MatcherIndex+NumToSkip;
  1976. unsigned MatcherIndexOfPredicate = MatcherIndex;
  1977. (void)MatcherIndexOfPredicate; // silence warning.
  1978. // If we can't evaluate this predicate without pushing a scope (e.g. if
  1979. // it is a 'MoveParent') or if the predicate succeeds on this node, we
  1980. // push the scope and evaluate the full predicate chain.
  1981. bool Result;
  1982. MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
  1983. Result, *this, RecordedNodes);
  1984. if (!Result)
  1985. break;
  1986. DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
  1987. << "index " << MatcherIndexOfPredicate
  1988. << ", continuing at " << FailIndex << "\n");
  1989. ++NumDAGIselRetries;
  1990. // Otherwise, we know that this case of the Scope is guaranteed to fail,
  1991. // move to the next case.
  1992. MatcherIndex = FailIndex;
  1993. }
  1994. // If the whole scope failed to match, bail.
  1995. if (FailIndex == 0) break;
  1996. // Push a MatchScope which indicates where to go if the first child fails
  1997. // to match.
  1998. MatchScope NewEntry;
  1999. NewEntry.FailIndex = FailIndex;
  2000. NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
  2001. NewEntry.NumRecordedNodes = RecordedNodes.size();
  2002. NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
  2003. NewEntry.InputChain = InputChain;
  2004. NewEntry.InputGlue = InputGlue;
  2005. NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
  2006. NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
  2007. MatchScopes.push_back(NewEntry);
  2008. continue;
  2009. }
  2010. case OPC_RecordNode: {
  2011. // Remember this node, it may end up being an operand in the pattern.
  2012. SDNode *Parent = 0;
  2013. if (NodeStack.size() > 1)
  2014. Parent = NodeStack[NodeStack.size()-2].getNode();
  2015. RecordedNodes.push_back(std::make_pair(N, Parent));
  2016. continue;
  2017. }
  2018. case OPC_RecordChild0: case OPC_RecordChild1:
  2019. case OPC_RecordChild2: case OPC_RecordChild3:
  2020. case OPC_RecordChild4: case OPC_RecordChild5:
  2021. case OPC_RecordChild6: case OPC_RecordChild7: {
  2022. unsigned ChildNo = Opcode-OPC_RecordChild0;
  2023. if (ChildNo >= N.getNumOperands())
  2024. break; // Match fails if out of range child #.
  2025. RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
  2026. N.getNode()));
  2027. continue;
  2028. }
  2029. case OPC_RecordMemRef:
  2030. MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
  2031. continue;
  2032. case OPC_CaptureGlueInput:
  2033. // If the current node has an input glue, capture it in InputGlue.
  2034. if (N->getNumOperands() != 0 &&
  2035. N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
  2036. InputGlue = N->getOperand(N->getNumOperands()-1);
  2037. continue;
  2038. case OPC_MoveChild: {
  2039. unsigned ChildNo = MatcherTable[MatcherIndex++];
  2040. if (ChildNo >= N.getNumOperands())
  2041. break; // Match fails if out of range child #.
  2042. N = N.getOperand(ChildNo);
  2043. NodeStack.push_back(N);
  2044. continue;
  2045. }
  2046. case OPC_MoveParent:
  2047. // Pop the current node off the NodeStack.
  2048. NodeStack.pop_back();
  2049. assert(!NodeStack.empty() && "Node stack imbalance!");
  2050. N = NodeStack.back();
  2051. continue;
  2052. case OPC_CheckSame:
  2053. if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
  2054. continue;
  2055. case OPC_CheckPatternPredicate:
  2056. if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
  2057. continue;
  2058. case OPC_CheckPredicate:
  2059. if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
  2060. N.getNode()))
  2061. break;
  2062. continue;
  2063. case OPC_CheckComplexPat: {
  2064. unsigned CPNum = MatcherTable[MatcherIndex++];
  2065. unsigned RecNo = MatcherTable[MatcherIndex++];
  2066. assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
  2067. if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
  2068. RecordedNodes[RecNo].first, CPNum,
  2069. RecordedNodes))
  2070. break;
  2071. continue;
  2072. }
  2073. case OPC_CheckOpcode:
  2074. if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
  2075. continue;
  2076. case OPC_CheckType:
  2077. if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
  2078. continue;
  2079. case OPC_SwitchOpcode: {
  2080. unsigned CurNodeOpcode = N.getOpcode();
  2081. unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
  2082. unsigned CaseSize;
  2083. while (1) {
  2084. // Get the size of this case.
  2085. CaseSize = MatcherTable[MatcherIndex++];
  2086. if (CaseSize & 128)
  2087. CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
  2088. if (CaseSize == 0) break;
  2089. uint16_t Opc = MatcherTable[MatcherIndex++];
  2090. Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  2091. // If the opcode matches, then we will execute this case.
  2092. if (CurNodeOpcode == Opc)
  2093. break;
  2094. // Otherwise, skip over this case.
  2095. MatcherIndex += CaseSize;
  2096. }
  2097. // If no cases matched, bail out.
  2098. if (CaseSize == 0) break;
  2099. // Otherwise, execute the case we found.
  2100. DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
  2101. << " to " << MatcherIndex << "\n");
  2102. continue;
  2103. }
  2104. case OPC_SwitchType: {
  2105. MVT CurNodeVT = N.getValueType().getSimpleVT();
  2106. unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
  2107. unsigned CaseSize;
  2108. while (1) {
  2109. // Get the size of this case.
  2110. CaseSize = MatcherTable[MatcherIndex++];
  2111. if (CaseSize & 128)
  2112. CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
  2113. if (CaseSize == 0) break;
  2114. MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2115. if (CaseVT == MVT::iPTR)
  2116. CaseVT = TLI.getPointerTy();
  2117. // If the VT matches, then we will execute this case.
  2118. if (CurNodeVT == CaseVT)
  2119. break;
  2120. // Otherwise, skip over this case.
  2121. MatcherIndex += CaseSize;
  2122. }
  2123. // If no cases matched, bail out.
  2124. if (CaseSize == 0) break;
  2125. // Otherwise, execute the case we found.
  2126. DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
  2127. << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
  2128. continue;
  2129. }
  2130. case OPC_CheckChild0Type: case OPC_CheckChild1Type:
  2131. case OPC_CheckChild2Type: case OPC_CheckChild3Type:
  2132. case OPC_CheckChild4Type: case OPC_CheckChild5Type:
  2133. case OPC_CheckChild6Type: case OPC_CheckChild7Type:
  2134. if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
  2135. Opcode-OPC_CheckChild0Type))
  2136. break;
  2137. continue;
  2138. case OPC_CheckCondCode:
  2139. if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
  2140. continue;
  2141. case OPC_CheckValueType:
  2142. if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
  2143. continue;
  2144. case OPC_CheckInteger:
  2145. if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
  2146. continue;
  2147. case OPC_CheckAndImm:
  2148. if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
  2149. continue;
  2150. case OPC_CheckOrImm:
  2151. if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
  2152. continue;
  2153. case OPC_CheckFoldableChainNode: {
  2154. assert(NodeStack.size() != 1 && "No parent node");
  2155. // Verify that all intermediate nodes between the root and this one have
  2156. // a single use.
  2157. bool HasMultipleUses = false;
  2158. for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
  2159. if (!NodeStack[i].hasOneUse()) {
  2160. HasMultipleUses = true;
  2161. break;
  2162. }
  2163. if (HasMultipleUses) break;
  2164. // Check to see that the target thinks this is profitable to fold and that
  2165. // we can fold it without inducing cycles in the graph.
  2166. if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
  2167. NodeToMatch) ||
  2168. !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
  2169. NodeToMatch, OptLevel,
  2170. true/*We validate our own chains*/))
  2171. break;
  2172. continue;
  2173. }
  2174. case OPC_EmitInteger: {
  2175. MVT::SimpleValueType VT =
  2176. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2177. int64_t Val = MatcherTable[MatcherIndex++];
  2178. if (Val & 128)
  2179. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  2180. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2181. CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
  2182. continue;
  2183. }
  2184. case OPC_EmitRegister: {
  2185. MVT::SimpleValueType VT =
  2186. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2187. unsigned RegNo = MatcherTable[MatcherIndex++];
  2188. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2189. CurDAG->getRegister(RegNo, VT), (SDNode*)0));
  2190. continue;
  2191. }
  2192. case OPC_EmitRegister2: {
  2193. // For targets w/ more than 256 register names, the register enum
  2194. // values are stored in two bytes in the matcher table (just like
  2195. // opcodes).
  2196. MVT::SimpleValueType VT =
  2197. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2198. unsigned RegNo = MatcherTable[MatcherIndex++];
  2199. RegNo |= MatcherTable[MatcherIndex++] << 8;
  2200. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2201. CurDAG->getRegister(RegNo, VT), (SDNode*)0));
  2202. continue;
  2203. }
  2204. case OPC_EmitConvertToTarget: {
  2205. // Convert from IMM/FPIMM to target version.
  2206. unsigned RecNo = MatcherTable[MatcherIndex++];
  2207. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2208. SDValue Imm = RecordedNodes[RecNo].first;
  2209. if (Imm->getOpcode() == ISD::Constant) {
  2210. const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
  2211. Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
  2212. } else if (Imm->getOpcode() == ISD::ConstantFP) {
  2213. const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
  2214. Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
  2215. }
  2216. RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
  2217. continue;
  2218. }
  2219. case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
  2220. case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
  2221. // These are space-optimized forms of OPC_EmitMergeInputChains.
  2222. assert(InputChain.getNode() == 0 &&
  2223. "EmitMergeInputChains should be the first chain producing node");
  2224. assert(ChainNodesMatched.empty() &&
  2225. "Should only have one EmitMergeInputChains per match");
  2226. // Read all of the chained nodes.
  2227. unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
  2228. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2229. ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
  2230. // FIXME: What if other value results of the node have uses not matched
  2231. // by this pattern?
  2232. if (ChainNodesMatched.back() != NodeToMatch &&
  2233. !RecordedNodes[RecNo].first.hasOneUse()) {
  2234. ChainNodesMatched.clear();
  2235. break;
  2236. }
  2237. // Merge the input chains if they are not intra-pattern references.
  2238. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
  2239. if (InputChain.getNode() == 0)
  2240. break; // Failed to merge.
  2241. continue;
  2242. }
  2243. case OPC_EmitMergeInputChains: {
  2244. assert(InputChain.getNode() == 0 &&
  2245. "EmitMergeInputChains should be the first chain producing node");
  2246. // This node gets a list of nodes we matched in the input that have
  2247. // chains. We want to token factor all of the input chains to these nodes
  2248. // together. However, if any of the input chains is actually one of the
  2249. // nodes matched in this pattern, then we have an intra-match reference.
  2250. // Ignore these because the newly token factored chain should not refer to
  2251. // the old nodes.
  2252. unsigned NumChains = MatcherTable[MatcherIndex++];
  2253. assert(NumChains != 0 && "Can't TF zero chains");
  2254. assert(ChainNodesMatched.empty() &&
  2255. "Should only have one EmitMergeInputChains per match");
  2256. // Read all of the chained nodes.
  2257. for (unsigned i = 0; i != NumChains; ++i) {
  2258. unsigned RecNo = MatcherTable[MatcherIndex++];
  2259. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2260. ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
  2261. // FIXME: What if other value results of the node have uses not matched
  2262. // by this pattern?
  2263. if (ChainNodesMatched.back() != NodeToMatch &&
  2264. !RecordedNodes[RecNo].first.hasOneUse()) {
  2265. ChainNodesMatched.clear();
  2266. break;
  2267. }
  2268. }
  2269. // If the inner loop broke out, the match fails.
  2270. if (ChainNodesMatched.empty())
  2271. break;
  2272. // Merge the input chains if they are not intra-pattern references.
  2273. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
  2274. if (InputChain.getNode() == 0)
  2275. break; // Failed to merge.
  2276. continue;
  2277. }
  2278. case OPC_EmitCopyToReg: {
  2279. unsigned RecNo = MatcherTable[MatcherIndex++];
  2280. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2281. unsigned DestPhysReg = MatcherTable[MatcherIndex++];
  2282. if (InputChain.getNode() == 0)
  2283. InputChain = CurDAG->getEntryNode();
  2284. InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
  2285. DestPhysReg, RecordedNodes[RecNo].first,
  2286. InputGlue);
  2287. InputGlue = InputChain.getValue(1);
  2288. continue;
  2289. }
  2290. case OPC_EmitNodeXForm: {
  2291. unsigned XFormNo = MatcherTable[MatcherIndex++];
  2292. unsigned RecNo = MatcherTable[MatcherIndex++];
  2293. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2294. SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
  2295. RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
  2296. continue;
  2297. }
  2298. case OPC_EmitNode:
  2299. case OPC_MorphNodeTo: {
  2300. uint16_t TargetOpc = MatcherTable[MatcherIndex++];
  2301. TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  2302. unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
  2303. // Get the result VT list.
  2304. unsigned NumVTs = MatcherTable[MatcherIndex++];
  2305. SmallVector<EVT, 4> VTs;
  2306. for (unsigned i = 0; i != NumVTs; ++i) {
  2307. MVT::SimpleValueType VT =
  2308. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2309. if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
  2310. VTs.push_back(VT);
  2311. }
  2312. if (EmitNodeInfo & OPFL_Chain)
  2313. VTs.push_back(MVT::Other);
  2314. if (EmitNodeInfo & OPFL_GlueOutput)
  2315. VTs.push_back(MVT::Glue);
  2316. // This is hot code, so optimize the two most common cases of 1 and 2
  2317. // results.
  2318. SDVTList VTList;
  2319. if (VTs.size() == 1)
  2320. VTList = CurDAG->getVTList(VTs[0]);
  2321. else if (VTs.size() == 2)
  2322. VTList = CurDAG->getVTList(VTs[0], VTs[1]);
  2323. else
  2324. VTList = CurDAG->getVTList(VTs.data(), VTs.size());
  2325. // Get the operand list.
  2326. unsigned NumOps = MatcherTable[MatcherIndex++];
  2327. SmallVector<SDValue, 8> Ops;
  2328. for (unsigned i = 0; i != NumOps; ++i) {
  2329. unsigned RecNo = MatcherTable[MatcherIndex++];
  2330. if (RecNo & 128)
  2331. RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
  2332. assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
  2333. Ops.push_back(RecordedNodes[RecNo].first);
  2334. }
  2335. // If there are variadic operands to add, handle them now.
  2336. if (EmitNodeInfo & OPFL_VariadicInfo) {
  2337. // Determine the start index to copy from.
  2338. unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
  2339. FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
  2340. assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
  2341. "Invalid variadic node");
  2342. // Copy all of the variadic operands, not including a potential glue
  2343. // input.
  2344. for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
  2345. i != e; ++i) {
  2346. SDValue V = NodeToMatch->getOperand(i);
  2347. if (V.getValueType() == MVT::Glue) break;
  2348. Ops.push_back(V);
  2349. }
  2350. }
  2351. // If this has chain/glue inputs, add them.
  2352. if (EmitNodeInfo & OPFL_Chain)
  2353. Ops.push_back(InputChain);
  2354. if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
  2355. Ops.push_back(InputGlue);
  2356. // Create the node.
  2357. SDNode *Res = 0;
  2358. if (Opcode != OPC_MorphNodeTo) {
  2359. // If this is a normal EmitNode command, just create the new node and
  2360. // add the results to the RecordedNodes list.
  2361. Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
  2362. VTList, Ops);
  2363. // Add all the non-glue/non-chain results to the RecordedNodes list.
  2364. for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
  2365. if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
  2366. RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
  2367. (SDNode*) 0));
  2368. }
  2369. } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
  2370. Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
  2371. EmitNodeInfo);
  2372. } else {
  2373. // NodeToMatch was eliminated by CSE when the target changed the DAG.
  2374. // We will visit the equivalent node later.
  2375. DEBUG(dbgs() << "Node was eliminated by CSE\n");
  2376. return 0;
  2377. }
  2378. // If the node had chain/glue results, update our notion of the current
  2379. // chain and glue.
  2380. if (EmitNodeInfo & OPFL_GlueOutput) {
  2381. InputGlue = SDValue(Res, VTs.size()-1);
  2382. if (EmitNodeInfo & OPFL_Chain)
  2383. InputChain = SDValue(Res, VTs.size()-2);
  2384. } else if (EmitNodeInfo & OPFL_Chain)
  2385. InputChain = SDValue(Res, VTs.size()-1);
  2386. // If the OPFL_MemRefs glue is set on this node, slap all of the
  2387. // accumulated memrefs onto it.
  2388. //
  2389. // FIXME: This is vastly incorrect for patterns with multiple outputs
  2390. // instructions that access memory and for ComplexPatterns that match
  2391. // loads.
  2392. if (EmitNodeInfo & OPFL_MemRefs) {
  2393. // Only attach load or store memory operands if the generated
  2394. // instruction may load or store.
  2395. const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
  2396. bool mayLoad = MCID.mayLoad();
  2397. bool mayStore = MCID.mayStore();
  2398. unsigned NumMemRefs = 0;
  2399. for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
  2400. MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
  2401. if ((*I)->isLoad()) {
  2402. if (mayLoad)
  2403. ++NumMemRefs;
  2404. } else if ((*I)->isStore()) {
  2405. if (mayStore)
  2406. ++NumMemRefs;
  2407. } else {
  2408. ++NumMemRefs;
  2409. }
  2410. }
  2411. MachineSDNode::mmo_iterator MemRefs =
  2412. MF->allocateMemRefsArray(NumMemRefs);
  2413. MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
  2414. for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
  2415. MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
  2416. if ((*I)->isLoad()) {
  2417. if (mayLoad)
  2418. *MemRefsPos++ = *I;
  2419. } else if ((*I)->isStore()) {
  2420. if (mayStore)
  2421. *MemRefsPos++ = *I;
  2422. } else {
  2423. *MemRefsPos++ = *I;
  2424. }
  2425. }
  2426. cast<MachineSDNode>(Res)
  2427. ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
  2428. }
  2429. DEBUG(dbgs() << " "
  2430. << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
  2431. << " node: "; Res->dump(CurDAG); dbgs() << "\n");
  2432. // If this was a MorphNodeTo then we're completely done!
  2433. if (Opcode == OPC_MorphNodeTo) {
  2434. // Update chain and glue uses.
  2435. UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
  2436. InputGlue, GlueResultNodesMatched, true);
  2437. return Res;
  2438. }
  2439. continue;
  2440. }
  2441. case OPC_MarkGlueResults: {
  2442. unsigned NumNodes = MatcherTable[MatcherIndex++];
  2443. // Read and remember all the glue-result nodes.
  2444. for (unsigned i = 0; i != NumNodes; ++i) {
  2445. unsigned RecNo = MatcherTable[MatcherIndex++];
  2446. if (RecNo & 128)
  2447. RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
  2448. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2449. GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
  2450. }
  2451. continue;
  2452. }
  2453. case OPC_CompleteMatch: {
  2454. // The match has been completed, and any new nodes (if any) have been
  2455. // created. Patch up references to the matched dag to use the newly
  2456. // created nodes.
  2457. unsigned NumResults = MatcherTable[MatcherIndex++];
  2458. for (unsigned i = 0; i != NumResults; ++i) {
  2459. unsigned ResSlot = MatcherTable[MatcherIndex++];
  2460. if (ResSlot & 128)
  2461. ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
  2462. assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
  2463. SDValue Res = RecordedNodes[ResSlot].first;
  2464. assert(i < NodeToMatch->getNumValues() &&
  2465. NodeToMatch->getValueType(i) != MVT::Other &&
  2466. NodeToMatch->getValueType(i) != MVT::Glue &&
  2467. "Invalid number of results to complete!");
  2468. assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
  2469. NodeToMatch->getValueType(i) == MVT::iPTR ||
  2470. Res.getValueType() == MVT::iPTR ||
  2471. NodeToMatch->getValueType(i).getSizeInBits() ==
  2472. Res.getValueType().getSizeInBits()) &&
  2473. "invalid replacement");
  2474. CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
  2475. }
  2476. // If the root node defines glue, add it to the glue nodes to update list.
  2477. if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
  2478. GlueResultNodesMatched.push_back(NodeToMatch);
  2479. // Update chain and glue uses.
  2480. UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
  2481. InputGlue, GlueResultNodesMatched, false);
  2482. assert(NodeToMatch->use_empty() &&
  2483. "Didn't replace all uses of the node?");
  2484. // FIXME: We just return here, which interacts correctly with SelectRoot
  2485. // above. We should fix this to not return an SDNode* anymore.
  2486. return 0;
  2487. }
  2488. }
  2489. // If the code reached this point, then the match failed. See if there is
  2490. // another child to try in the current 'Scope', otherwise pop it until we
  2491. // find a case to check.
  2492. DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
  2493. ++NumDAGIselRetries;
  2494. while (1) {
  2495. if (MatchScopes.empty()) {
  2496. CannotYetSelect(NodeToMatch);
  2497. return 0;
  2498. }
  2499. // Restore the interpreter state back to the point where the scope was
  2500. // formed.
  2501. MatchScope &LastScope = MatchScopes.back();
  2502. RecordedNodes.resize(LastScope.NumRecordedNodes);
  2503. NodeStack.clear();
  2504. NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
  2505. N = NodeStack.back();
  2506. if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
  2507. MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
  2508. MatcherIndex = LastScope.FailIndex;
  2509. DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
  2510. InputChain = LastScope.InputChain;
  2511. InputGlue = LastScope.InputGlue;
  2512. if (!LastScope.HasChainNodesMatched)
  2513. ChainNodesMatched.clear();
  2514. if (!LastScope.HasGlueResultNodesMatched)
  2515. GlueResultNodesMatched.clear();
  2516. // Check to see what the offset is at the new MatcherIndex. If it is zero
  2517. // we have reached the end of this scope, otherwise we have another child
  2518. // in the current scope to try.
  2519. unsigned NumToSkip = MatcherTable[MatcherIndex++];
  2520. if (NumToSkip & 128)
  2521. NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
  2522. // If we have another child in this scope to match, update FailIndex and
  2523. // try it.
  2524. if (NumToSkip != 0) {
  2525. LastScope.FailIndex = MatcherIndex+NumToSkip;
  2526. break;
  2527. }
  2528. // End of this scope, pop it and try the next child in the containing
  2529. // scope.
  2530. MatchScopes.pop_back();
  2531. }
  2532. }
  2533. }
  2534. void SelectionDAGISel::CannotYetSelect(SDNode *N) {
  2535. std::string msg;
  2536. raw_string_ostream Msg(msg);
  2537. Msg << "Cannot select: ";
  2538. if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
  2539. N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
  2540. N->getOpcode() != ISD::INTRINSIC_VOID) {
  2541. N->printrFull(Msg, CurDAG);
  2542. Msg << "\nIn function: " << MF->getName();
  2543. } else {
  2544. bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
  2545. unsigned iid =
  2546. cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
  2547. if (iid < Intrinsic::num_intrinsics)
  2548. Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
  2549. else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
  2550. Msg << "target intrinsic %" << TII->getName(iid);
  2551. else
  2552. Msg << "unknown intrinsic #" << iid;
  2553. }
  2554. report_fatal_error(Msg.str());
  2555. }
  2556. char SelectionDAGISel::ID = 0;