FastISel.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  1. //===- FastISel.cpp - Implementation of the FastISel class ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the implementation of the FastISel class.
  10. //
  11. // "Fast" instruction selection is designed to emit very poor code quickly.
  12. // Also, it is not designed to be able to do much lowering, so most illegal
  13. // types (e.g. i64 on 32-bit targets) and operations are not supported. It is
  14. // also not intended to be able to do much optimization, except in a few cases
  15. // where doing optimizations reduces overall compile time. For example, folding
  16. // constants into immediate fields is often done, because it's cheap and it
  17. // reduces the number of instructions later phases have to examine.
  18. //
  19. // "Fast" instruction selection is able to fail gracefully and transfer
  20. // control to the SelectionDAG selector for operations that it doesn't
  21. // support. In many cases, this allows us to avoid duplicating a lot of
  22. // the complicated lowering logic that SelectionDAG currently has.
  23. //
  24. // The intended use for "fast" instruction selection is "-O0" mode
  25. // compilation, where the quality of the generated code is irrelevant when
  26. // weighed against the speed at which the code can be generated. Also,
  27. // at -O0, the LLVM optimizers are not running, and this makes the
  28. // compile time of codegen a much higher portion of the overall compile
  29. // time. Despite its limitations, "fast" instruction selection is able to
  30. // handle enough code on its own to provide noticeable overall speedups
  31. // in -O0 compiles.
  32. //
  33. // Basic operations are supported in a target-independent way, by reading
  34. // the same instruction descriptions that the SelectionDAG selector reads,
  35. // and identifying simple arithmetic operations that can be directly selected
  36. // from simple operators. More complicated operations currently require
  37. // target-specific code.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #include "llvm/CodeGen/FastISel.h"
  41. #include "llvm/ADT/APFloat.h"
  42. #include "llvm/ADT/APSInt.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/Optional.h"
  45. #include "llvm/ADT/SmallPtrSet.h"
  46. #include "llvm/ADT/SmallString.h"
  47. #include "llvm/ADT/SmallVector.h"
  48. #include "llvm/ADT/Statistic.h"
  49. #include "llvm/Analysis/BranchProbabilityInfo.h"
  50. #include "llvm/Analysis/TargetLibraryInfo.h"
  51. #include "llvm/CodeGen/Analysis.h"
  52. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  53. #include "llvm/CodeGen/ISDOpcodes.h"
  54. #include "llvm/CodeGen/MachineBasicBlock.h"
  55. #include "llvm/CodeGen/MachineFrameInfo.h"
  56. #include "llvm/CodeGen/MachineInstr.h"
  57. #include "llvm/CodeGen/MachineInstrBuilder.h"
  58. #include "llvm/CodeGen/MachineMemOperand.h"
  59. #include "llvm/CodeGen/MachineModuleInfo.h"
  60. #include "llvm/CodeGen/MachineOperand.h"
  61. #include "llvm/CodeGen/MachineRegisterInfo.h"
  62. #include "llvm/CodeGen/StackMaps.h"
  63. #include "llvm/CodeGen/TargetInstrInfo.h"
  64. #include "llvm/CodeGen/TargetLowering.h"
  65. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  66. #include "llvm/CodeGen/ValueTypes.h"
  67. #include "llvm/IR/Argument.h"
  68. #include "llvm/IR/Attributes.h"
  69. #include "llvm/IR/BasicBlock.h"
  70. #include "llvm/IR/CallSite.h"
  71. #include "llvm/IR/CallingConv.h"
  72. #include "llvm/IR/Constant.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfo.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/GlobalValue.h"
  81. #include "llvm/IR/InlineAsm.h"
  82. #include "llvm/IR/InstrTypes.h"
  83. #include "llvm/IR/Instruction.h"
  84. #include "llvm/IR/Instructions.h"
  85. #include "llvm/IR/IntrinsicInst.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Mangler.h"
  88. #include "llvm/IR/Metadata.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/User.h"
  93. #include "llvm/IR/Value.h"
  94. #include "llvm/MC/MCContext.h"
  95. #include "llvm/MC/MCInstrDesc.h"
  96. #include "llvm/MC/MCRegisterInfo.h"
  97. #include "llvm/Support/Casting.h"
  98. #include "llvm/Support/Debug.h"
  99. #include "llvm/Support/ErrorHandling.h"
  100. #include "llvm/Support/MachineValueType.h"
  101. #include "llvm/Support/MathExtras.h"
  102. #include "llvm/Support/raw_ostream.h"
  103. #include "llvm/Target/TargetMachine.h"
  104. #include "llvm/Target/TargetOptions.h"
  105. #include <algorithm>
  106. #include <cassert>
  107. #include <cstdint>
  108. #include <iterator>
  109. #include <utility>
  110. using namespace llvm;
  111. using namespace PatternMatch;
  112. #define DEBUG_TYPE "isel"
  113. // FIXME: Remove this after the feature has proven reliable.
  114. static cl::opt<bool> SinkLocalValues("fast-isel-sink-local-values",
  115. cl::init(true), cl::Hidden,
  116. cl::desc("Sink local values in FastISel"));
  117. STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
  118. "target-independent selector");
  119. STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
  120. "target-specific selector");
  121. STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
  122. /// Set the current block to which generated machine instructions will be
  123. /// appended.
  124. void FastISel::startNewBlock() {
  125. assert(LocalValueMap.empty() &&
  126. "local values should be cleared after finishing a BB");
  127. // Instructions are appended to FuncInfo.MBB. If the basic block already
  128. // contains labels or copies, use the last instruction as the last local
  129. // value.
  130. EmitStartPt = nullptr;
  131. if (!FuncInfo.MBB->empty())
  132. EmitStartPt = &FuncInfo.MBB->back();
  133. LastLocalValue = EmitStartPt;
  134. }
  135. /// Flush the local CSE map and sink anything we can.
  136. void FastISel::finishBasicBlock() { flushLocalValueMap(); }
  137. bool FastISel::lowerArguments() {
  138. if (!FuncInfo.CanLowerReturn)
  139. // Fallback to SDISel argument lowering code to deal with sret pointer
  140. // parameter.
  141. return false;
  142. if (!fastLowerArguments())
  143. return false;
  144. // Enter arguments into ValueMap for uses in non-entry BBs.
  145. for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
  146. E = FuncInfo.Fn->arg_end();
  147. I != E; ++I) {
  148. DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
  149. assert(VI != LocalValueMap.end() && "Missed an argument?");
  150. FuncInfo.ValueMap[&*I] = VI->second;
  151. }
  152. return true;
  153. }
  154. /// Return the defined register if this instruction defines exactly one
  155. /// virtual register and uses no other virtual registers. Otherwise return 0.
  156. static unsigned findSinkableLocalRegDef(MachineInstr &MI) {
  157. unsigned RegDef = 0;
  158. for (const MachineOperand &MO : MI.operands()) {
  159. if (!MO.isReg())
  160. continue;
  161. if (MO.isDef()) {
  162. if (RegDef)
  163. return 0;
  164. RegDef = MO.getReg();
  165. } else if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  166. // This is another use of a vreg. Don't try to sink it.
  167. return 0;
  168. }
  169. }
  170. return RegDef;
  171. }
  172. void FastISel::flushLocalValueMap() {
  173. // Try to sink local values down to their first use so that we can give them a
  174. // better debug location. This has the side effect of shrinking local value
  175. // live ranges, which helps out fast regalloc.
  176. if (SinkLocalValues && LastLocalValue != EmitStartPt) {
  177. // Sink local value materialization instructions between EmitStartPt and
  178. // LastLocalValue. Visit them bottom-up, starting from LastLocalValue, to
  179. // avoid inserting into the range that we're iterating over.
  180. MachineBasicBlock::reverse_iterator RE =
  181. EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt)
  182. : FuncInfo.MBB->rend();
  183. MachineBasicBlock::reverse_iterator RI(LastLocalValue);
  184. InstOrderMap OrderMap;
  185. for (; RI != RE;) {
  186. MachineInstr &LocalMI = *RI;
  187. ++RI;
  188. bool Store = true;
  189. if (!LocalMI.isSafeToMove(nullptr, Store))
  190. continue;
  191. unsigned DefReg = findSinkableLocalRegDef(LocalMI);
  192. if (DefReg == 0)
  193. continue;
  194. sinkLocalValueMaterialization(LocalMI, DefReg, OrderMap);
  195. }
  196. }
  197. LocalValueMap.clear();
  198. LastLocalValue = EmitStartPt;
  199. recomputeInsertPt();
  200. SavedInsertPt = FuncInfo.InsertPt;
  201. LastFlushPoint = FuncInfo.InsertPt;
  202. }
  203. static bool isRegUsedByPhiNodes(unsigned DefReg,
  204. FunctionLoweringInfo &FuncInfo) {
  205. for (auto &P : FuncInfo.PHINodesToUpdate)
  206. if (P.second == DefReg)
  207. return true;
  208. return false;
  209. }
  210. /// Build a map of instruction orders. Return the first terminator and its
  211. /// order. Consider EH_LABEL instructions to be terminators as well, since local
  212. /// values for phis after invokes must be materialized before the call.
  213. void FastISel::InstOrderMap::initialize(
  214. MachineBasicBlock *MBB, MachineBasicBlock::iterator LastFlushPoint) {
  215. unsigned Order = 0;
  216. for (MachineInstr &I : *MBB) {
  217. if (!FirstTerminator &&
  218. (I.isTerminator() || (I.isEHLabel() && &I != &MBB->front()))) {
  219. FirstTerminator = &I;
  220. FirstTerminatorOrder = Order;
  221. }
  222. Orders[&I] = Order++;
  223. // We don't need to order instructions past the last flush point.
  224. if (I.getIterator() == LastFlushPoint)
  225. break;
  226. }
  227. }
  228. void FastISel::sinkLocalValueMaterialization(MachineInstr &LocalMI,
  229. unsigned DefReg,
  230. InstOrderMap &OrderMap) {
  231. // If this register is used by a register fixup, MRI will not contain all
  232. // the uses until after register fixups, so don't attempt to sink or DCE
  233. // this instruction. Register fixups typically come from no-op cast
  234. // instructions, which replace the cast instruction vreg with the local
  235. // value vreg.
  236. if (FuncInfo.RegsWithFixups.count(DefReg))
  237. return;
  238. // We can DCE this instruction if there are no uses and it wasn't a
  239. // materialized for a successor PHI node.
  240. bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo);
  241. if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) {
  242. if (EmitStartPt == &LocalMI)
  243. EmitStartPt = EmitStartPt->getPrevNode();
  244. LLVM_DEBUG(dbgs() << "removing dead local value materialization "
  245. << LocalMI);
  246. OrderMap.Orders.erase(&LocalMI);
  247. LocalMI.eraseFromParent();
  248. return;
  249. }
  250. // Number the instructions if we haven't yet so we can efficiently find the
  251. // earliest use.
  252. if (OrderMap.Orders.empty())
  253. OrderMap.initialize(FuncInfo.MBB, LastFlushPoint);
  254. // Find the first user in the BB.
  255. MachineInstr *FirstUser = nullptr;
  256. unsigned FirstOrder = std::numeric_limits<unsigned>::max();
  257. for (MachineInstr &UseInst : MRI.use_nodbg_instructions(DefReg)) {
  258. auto I = OrderMap.Orders.find(&UseInst);
  259. assert(I != OrderMap.Orders.end() &&
  260. "local value used by instruction outside local region");
  261. unsigned UseOrder = I->second;
  262. if (UseOrder < FirstOrder) {
  263. FirstOrder = UseOrder;
  264. FirstUser = &UseInst;
  265. }
  266. }
  267. // The insertion point will be the first terminator or the first user,
  268. // whichever came first. If there was no terminator, this must be a
  269. // fallthrough block and the insertion point is the end of the block.
  270. MachineBasicBlock::instr_iterator SinkPos;
  271. if (UsedByPHI && OrderMap.FirstTerminatorOrder < FirstOrder) {
  272. FirstOrder = OrderMap.FirstTerminatorOrder;
  273. SinkPos = OrderMap.FirstTerminator->getIterator();
  274. } else if (FirstUser) {
  275. SinkPos = FirstUser->getIterator();
  276. } else {
  277. assert(UsedByPHI && "must be users if not used by a phi");
  278. SinkPos = FuncInfo.MBB->instr_end();
  279. }
  280. // Collect all DBG_VALUEs before the new insertion position so that we can
  281. // sink them.
  282. SmallVector<MachineInstr *, 1> DbgValues;
  283. for (MachineInstr &DbgVal : MRI.use_instructions(DefReg)) {
  284. if (!DbgVal.isDebugValue())
  285. continue;
  286. unsigned UseOrder = OrderMap.Orders[&DbgVal];
  287. if (UseOrder < FirstOrder)
  288. DbgValues.push_back(&DbgVal);
  289. }
  290. // Sink LocalMI before SinkPos and assign it the same DebugLoc.
  291. LLVM_DEBUG(dbgs() << "sinking local value to first use " << LocalMI);
  292. FuncInfo.MBB->remove(&LocalMI);
  293. FuncInfo.MBB->insert(SinkPos, &LocalMI);
  294. if (SinkPos != FuncInfo.MBB->end())
  295. LocalMI.setDebugLoc(SinkPos->getDebugLoc());
  296. // Sink any debug values that we've collected.
  297. for (MachineInstr *DI : DbgValues) {
  298. FuncInfo.MBB->remove(DI);
  299. FuncInfo.MBB->insert(SinkPos, DI);
  300. }
  301. }
  302. bool FastISel::hasTrivialKill(const Value *V) {
  303. // Don't consider constants or arguments to have trivial kills.
  304. const Instruction *I = dyn_cast<Instruction>(V);
  305. if (!I)
  306. return false;
  307. // No-op casts are trivially coalesced by fast-isel.
  308. if (const auto *Cast = dyn_cast<CastInst>(I))
  309. if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0)))
  310. return false;
  311. // Even the value might have only one use in the LLVM IR, it is possible that
  312. // FastISel might fold the use into another instruction and now there is more
  313. // than one use at the Machine Instruction level.
  314. unsigned Reg = lookUpRegForValue(V);
  315. if (Reg && !MRI.use_empty(Reg))
  316. return false;
  317. // GEPs with all zero indices are trivially coalesced by fast-isel.
  318. if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
  319. if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
  320. return false;
  321. // Only instructions with a single use in the same basic block are considered
  322. // to have trivial kills.
  323. return I->hasOneUse() &&
  324. !(I->getOpcode() == Instruction::BitCast ||
  325. I->getOpcode() == Instruction::PtrToInt ||
  326. I->getOpcode() == Instruction::IntToPtr) &&
  327. cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
  328. }
  329. unsigned FastISel::getRegForValue(const Value *V) {
  330. EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
  331. // Don't handle non-simple values in FastISel.
  332. if (!RealVT.isSimple())
  333. return 0;
  334. // Ignore illegal types. We must do this before looking up the value
  335. // in ValueMap because Arguments are given virtual registers regardless
  336. // of whether FastISel can handle them.
  337. MVT VT = RealVT.getSimpleVT();
  338. if (!TLI.isTypeLegal(VT)) {
  339. // Handle integer promotions, though, because they're common and easy.
  340. if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
  341. VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
  342. else
  343. return 0;
  344. }
  345. // Look up the value to see if we already have a register for it.
  346. unsigned Reg = lookUpRegForValue(V);
  347. if (Reg)
  348. return Reg;
  349. // In bottom-up mode, just create the virtual register which will be used
  350. // to hold the value. It will be materialized later.
  351. if (isa<Instruction>(V) &&
  352. (!isa<AllocaInst>(V) ||
  353. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
  354. return FuncInfo.InitializeRegForValue(V);
  355. SavePoint SaveInsertPt = enterLocalValueArea();
  356. // Materialize the value in a register. Emit any instructions in the
  357. // local value area.
  358. Reg = materializeRegForValue(V, VT);
  359. leaveLocalValueArea(SaveInsertPt);
  360. return Reg;
  361. }
  362. unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
  363. unsigned Reg = 0;
  364. if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  365. if (CI->getValue().getActiveBits() <= 64)
  366. Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
  367. } else if (isa<AllocaInst>(V))
  368. Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
  369. else if (isa<ConstantPointerNull>(V))
  370. // Translate this as an integer zero so that it can be
  371. // local-CSE'd with actual integer zeros.
  372. Reg = getRegForValue(
  373. Constant::getNullValue(DL.getIntPtrType(V->getContext())));
  374. else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  375. if (CF->isNullValue())
  376. Reg = fastMaterializeFloatZero(CF);
  377. else
  378. // Try to emit the constant directly.
  379. Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
  380. if (!Reg) {
  381. // Try to emit the constant by using an integer constant with a cast.
  382. const APFloat &Flt = CF->getValueAPF();
  383. EVT IntVT = TLI.getPointerTy(DL);
  384. uint32_t IntBitWidth = IntVT.getSizeInBits();
  385. APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
  386. bool isExact;
  387. (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
  388. if (isExact) {
  389. unsigned IntegerReg =
  390. getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
  391. if (IntegerReg != 0)
  392. Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
  393. /*Kill=*/false);
  394. }
  395. }
  396. } else if (const auto *Op = dyn_cast<Operator>(V)) {
  397. if (!selectOperator(Op, Op->getOpcode()))
  398. if (!isa<Instruction>(Op) ||
  399. !fastSelectInstruction(cast<Instruction>(Op)))
  400. return 0;
  401. Reg = lookUpRegForValue(Op);
  402. } else if (isa<UndefValue>(V)) {
  403. Reg = createResultReg(TLI.getRegClassFor(VT));
  404. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  405. TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
  406. }
  407. return Reg;
  408. }
  409. /// Helper for getRegForValue. This function is called when the value isn't
  410. /// already available in a register and must be materialized with new
  411. /// instructions.
  412. unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
  413. unsigned Reg = 0;
  414. // Give the target-specific code a try first.
  415. if (isa<Constant>(V))
  416. Reg = fastMaterializeConstant(cast<Constant>(V));
  417. // If target-specific code couldn't or didn't want to handle the value, then
  418. // give target-independent code a try.
  419. if (!Reg)
  420. Reg = materializeConstant(V, VT);
  421. // Don't cache constant materializations in the general ValueMap.
  422. // To do so would require tracking what uses they dominate.
  423. if (Reg) {
  424. LocalValueMap[V] = Reg;
  425. LastLocalValue = MRI.getVRegDef(Reg);
  426. }
  427. return Reg;
  428. }
  429. unsigned FastISel::lookUpRegForValue(const Value *V) {
  430. // Look up the value to see if we already have a register for it. We
  431. // cache values defined by Instructions across blocks, and other values
  432. // only locally. This is because Instructions already have the SSA
  433. // def-dominates-use requirement enforced.
  434. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
  435. if (I != FuncInfo.ValueMap.end())
  436. return I->second;
  437. return LocalValueMap[V];
  438. }
  439. void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
  440. if (!isa<Instruction>(I)) {
  441. LocalValueMap[I] = Reg;
  442. return;
  443. }
  444. unsigned &AssignedReg = FuncInfo.ValueMap[I];
  445. if (AssignedReg == 0)
  446. // Use the new register.
  447. AssignedReg = Reg;
  448. else if (Reg != AssignedReg) {
  449. // Arrange for uses of AssignedReg to be replaced by uses of Reg.
  450. for (unsigned i = 0; i < NumRegs; i++) {
  451. FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
  452. FuncInfo.RegsWithFixups.insert(Reg + i);
  453. }
  454. AssignedReg = Reg;
  455. }
  456. }
  457. std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
  458. unsigned IdxN = getRegForValue(Idx);
  459. if (IdxN == 0)
  460. // Unhandled operand. Halt "fast" selection and bail.
  461. return std::pair<unsigned, bool>(0, false);
  462. bool IdxNIsKill = hasTrivialKill(Idx);
  463. // If the index is smaller or larger than intptr_t, truncate or extend it.
  464. MVT PtrVT = TLI.getPointerTy(DL);
  465. EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
  466. if (IdxVT.bitsLT(PtrVT)) {
  467. IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
  468. IdxNIsKill);
  469. IdxNIsKill = true;
  470. } else if (IdxVT.bitsGT(PtrVT)) {
  471. IdxN =
  472. fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
  473. IdxNIsKill = true;
  474. }
  475. return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
  476. }
  477. void FastISel::recomputeInsertPt() {
  478. if (getLastLocalValue()) {
  479. FuncInfo.InsertPt = getLastLocalValue();
  480. FuncInfo.MBB = FuncInfo.InsertPt->getParent();
  481. ++FuncInfo.InsertPt;
  482. } else
  483. FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
  484. // Now skip past any EH_LABELs, which must remain at the beginning.
  485. while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
  486. FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
  487. ++FuncInfo.InsertPt;
  488. }
  489. void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
  490. MachineBasicBlock::iterator E) {
  491. assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
  492. "Invalid iterator!");
  493. while (I != E) {
  494. if (LastFlushPoint == I)
  495. LastFlushPoint = E;
  496. if (SavedInsertPt == I)
  497. SavedInsertPt = E;
  498. if (EmitStartPt == I)
  499. EmitStartPt = E.isValid() ? &*E : nullptr;
  500. if (LastLocalValue == I)
  501. LastLocalValue = E.isValid() ? &*E : nullptr;
  502. MachineInstr *Dead = &*I;
  503. ++I;
  504. Dead->eraseFromParent();
  505. ++NumFastIselDead;
  506. }
  507. recomputeInsertPt();
  508. }
  509. FastISel::SavePoint FastISel::enterLocalValueArea() {
  510. MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
  511. DebugLoc OldDL = DbgLoc;
  512. recomputeInsertPt();
  513. DbgLoc = DebugLoc();
  514. SavePoint SP = {OldInsertPt, OldDL};
  515. return SP;
  516. }
  517. void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
  518. if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
  519. LastLocalValue = &*std::prev(FuncInfo.InsertPt);
  520. // Restore the previous insert position.
  521. FuncInfo.InsertPt = OldInsertPt.InsertPt;
  522. DbgLoc = OldInsertPt.DL;
  523. }
  524. bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
  525. EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
  526. if (VT == MVT::Other || !VT.isSimple())
  527. // Unhandled type. Halt "fast" selection and bail.
  528. return false;
  529. // We only handle legal types. For example, on x86-32 the instruction
  530. // selector contains all of the 64-bit instructions from x86-64,
  531. // under the assumption that i64 won't be used if the target doesn't
  532. // support it.
  533. if (!TLI.isTypeLegal(VT)) {
  534. // MVT::i1 is special. Allow AND, OR, or XOR because they
  535. // don't require additional zeroing, which makes them easy.
  536. if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
  537. ISDOpcode == ISD::XOR))
  538. VT = TLI.getTypeToTransformTo(I->getContext(), VT);
  539. else
  540. return false;
  541. }
  542. // Check if the first operand is a constant, and handle it as "ri". At -O0,
  543. // we don't have anything that canonicalizes operand order.
  544. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
  545. if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
  546. unsigned Op1 = getRegForValue(I->getOperand(1));
  547. if (!Op1)
  548. return false;
  549. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  550. unsigned ResultReg =
  551. fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
  552. CI->getZExtValue(), VT.getSimpleVT());
  553. if (!ResultReg)
  554. return false;
  555. // We successfully emitted code for the given LLVM Instruction.
  556. updateValueMap(I, ResultReg);
  557. return true;
  558. }
  559. unsigned Op0 = getRegForValue(I->getOperand(0));
  560. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  561. return false;
  562. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  563. // Check if the second operand is a constant and handle it appropriately.
  564. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  565. uint64_t Imm = CI->getSExtValue();
  566. // Transform "sdiv exact X, 8" -> "sra X, 3".
  567. if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
  568. cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
  569. Imm = Log2_64(Imm);
  570. ISDOpcode = ISD::SRA;
  571. }
  572. // Transform "urem x, pow2" -> "and x, pow2-1".
  573. if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
  574. isPowerOf2_64(Imm)) {
  575. --Imm;
  576. ISDOpcode = ISD::AND;
  577. }
  578. unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
  579. Op0IsKill, Imm, VT.getSimpleVT());
  580. if (!ResultReg)
  581. return false;
  582. // We successfully emitted code for the given LLVM Instruction.
  583. updateValueMap(I, ResultReg);
  584. return true;
  585. }
  586. unsigned Op1 = getRegForValue(I->getOperand(1));
  587. if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
  588. return false;
  589. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  590. // Now we have both operands in registers. Emit the instruction.
  591. unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
  592. ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
  593. if (!ResultReg)
  594. // Target-specific code wasn't able to find a machine opcode for
  595. // the given ISD opcode and type. Halt "fast" selection and bail.
  596. return false;
  597. // We successfully emitted code for the given LLVM Instruction.
  598. updateValueMap(I, ResultReg);
  599. return true;
  600. }
  601. bool FastISel::selectGetElementPtr(const User *I) {
  602. unsigned N = getRegForValue(I->getOperand(0));
  603. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  604. return false;
  605. bool NIsKill = hasTrivialKill(I->getOperand(0));
  606. // Keep a running tab of the total offset to coalesce multiple N = N + Offset
  607. // into a single N = N + TotalOffset.
  608. uint64_t TotalOffs = 0;
  609. // FIXME: What's a good SWAG number for MaxOffs?
  610. uint64_t MaxOffs = 2048;
  611. MVT VT = TLI.getPointerTy(DL);
  612. for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
  613. GTI != E; ++GTI) {
  614. const Value *Idx = GTI.getOperand();
  615. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  616. uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
  617. if (Field) {
  618. // N = N + Offset
  619. TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
  620. if (TotalOffs >= MaxOffs) {
  621. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  622. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  623. return false;
  624. NIsKill = true;
  625. TotalOffs = 0;
  626. }
  627. }
  628. } else {
  629. Type *Ty = GTI.getIndexedType();
  630. // If this is a constant subscript, handle it quickly.
  631. if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
  632. if (CI->isZero())
  633. continue;
  634. // N = N + Offset
  635. uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
  636. TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
  637. if (TotalOffs >= MaxOffs) {
  638. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  639. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  640. return false;
  641. NIsKill = true;
  642. TotalOffs = 0;
  643. }
  644. continue;
  645. }
  646. if (TotalOffs) {
  647. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  648. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  649. return false;
  650. NIsKill = true;
  651. TotalOffs = 0;
  652. }
  653. // N = N + Idx * ElementSize;
  654. uint64_t ElementSize = DL.getTypeAllocSize(Ty);
  655. std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
  656. unsigned IdxN = Pair.first;
  657. bool IdxNIsKill = Pair.second;
  658. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  659. return false;
  660. if (ElementSize != 1) {
  661. IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
  662. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  663. return false;
  664. IdxNIsKill = true;
  665. }
  666. N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
  667. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  668. return false;
  669. }
  670. }
  671. if (TotalOffs) {
  672. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  673. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  674. return false;
  675. }
  676. // We successfully emitted code for the given LLVM Instruction.
  677. updateValueMap(I, N);
  678. return true;
  679. }
  680. bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
  681. const CallInst *CI, unsigned StartIdx) {
  682. for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
  683. Value *Val = CI->getArgOperand(i);
  684. // Check for constants and encode them with a StackMaps::ConstantOp prefix.
  685. if (const auto *C = dyn_cast<ConstantInt>(Val)) {
  686. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  687. Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
  688. } else if (isa<ConstantPointerNull>(Val)) {
  689. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  690. Ops.push_back(MachineOperand::CreateImm(0));
  691. } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
  692. // Values coming from a stack location also require a special encoding,
  693. // but that is added later on by the target specific frame index
  694. // elimination implementation.
  695. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  696. if (SI != FuncInfo.StaticAllocaMap.end())
  697. Ops.push_back(MachineOperand::CreateFI(SI->second));
  698. else
  699. return false;
  700. } else {
  701. unsigned Reg = getRegForValue(Val);
  702. if (!Reg)
  703. return false;
  704. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  705. }
  706. }
  707. return true;
  708. }
  709. bool FastISel::selectStackmap(const CallInst *I) {
  710. // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
  711. // [live variables...])
  712. assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
  713. "Stackmap cannot return a value.");
  714. // The stackmap intrinsic only records the live variables (the arguments
  715. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  716. // intrinsic, this won't be lowered to a function call. This means we don't
  717. // have to worry about calling conventions and target-specific lowering code.
  718. // Instead we perform the call lowering right here.
  719. //
  720. // CALLSEQ_START(0, 0...)
  721. // STACKMAP(id, nbytes, ...)
  722. // CALLSEQ_END(0, 0)
  723. //
  724. SmallVector<MachineOperand, 32> Ops;
  725. // Add the <id> and <numBytes> constants.
  726. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  727. "Expected a constant integer.");
  728. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  729. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  730. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  731. "Expected a constant integer.");
  732. const auto *NumBytes =
  733. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  734. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  735. // Push live variables for the stack map (skipping the first two arguments
  736. // <id> and <numBytes>).
  737. if (!addStackMapLiveVars(Ops, I, 2))
  738. return false;
  739. // We are not adding any register mask info here, because the stackmap doesn't
  740. // clobber anything.
  741. // Add scratch registers as implicit def and early clobber.
  742. CallingConv::ID CC = I->getCallingConv();
  743. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  744. for (unsigned i = 0; ScratchRegs[i]; ++i)
  745. Ops.push_back(MachineOperand::CreateReg(
  746. ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
  747. /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
  748. // Issue CALLSEQ_START
  749. unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
  750. auto Builder =
  751. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
  752. const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
  753. for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
  754. Builder.addImm(0);
  755. // Issue STACKMAP.
  756. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  757. TII.get(TargetOpcode::STACKMAP));
  758. for (auto const &MO : Ops)
  759. MIB.add(MO);
  760. // Issue CALLSEQ_END
  761. unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
  762. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
  763. .addImm(0)
  764. .addImm(0);
  765. // Inform the Frame Information that we have a stackmap in this function.
  766. FuncInfo.MF->getFrameInfo().setHasStackMap();
  767. return true;
  768. }
  769. /// Lower an argument list according to the target calling convention.
  770. ///
  771. /// This is a helper for lowering intrinsics that follow a target calling
  772. /// convention or require stack pointer adjustment. Only a subset of the
  773. /// intrinsic's operands need to participate in the calling convention.
  774. bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
  775. unsigned NumArgs, const Value *Callee,
  776. bool ForceRetVoidTy, CallLoweringInfo &CLI) {
  777. ArgListTy Args;
  778. Args.reserve(NumArgs);
  779. // Populate the argument list.
  780. ImmutableCallSite CS(CI);
  781. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
  782. Value *V = CI->getOperand(ArgI);
  783. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  784. ArgListEntry Entry;
  785. Entry.Val = V;
  786. Entry.Ty = V->getType();
  787. Entry.setAttributes(&CS, ArgI);
  788. Args.push_back(Entry);
  789. }
  790. Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
  791. : CI->getType();
  792. CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
  793. return lowerCallTo(CLI);
  794. }
  795. FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
  796. const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
  797. StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
  798. SmallString<32> MangledName;
  799. Mangler::getNameWithPrefix(MangledName, Target, DL);
  800. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  801. return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
  802. }
  803. bool FastISel::selectPatchpoint(const CallInst *I) {
  804. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  805. // i32 <numBytes>,
  806. // i8* <target>,
  807. // i32 <numArgs>,
  808. // [Args...],
  809. // [live variables...])
  810. CallingConv::ID CC = I->getCallingConv();
  811. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  812. bool HasDef = !I->getType()->isVoidTy();
  813. Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
  814. // Get the real number of arguments participating in the call <numArgs>
  815. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
  816. "Expected a constant integer.");
  817. const auto *NumArgsVal =
  818. cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
  819. unsigned NumArgs = NumArgsVal->getZExtValue();
  820. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  821. // This includes all meta-operands up to but not including CC.
  822. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  823. assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
  824. "Not enough arguments provided to the patchpoint intrinsic");
  825. // For AnyRegCC the arguments are lowered later on manually.
  826. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  827. CallLoweringInfo CLI;
  828. CLI.setIsPatchPoint();
  829. if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
  830. return false;
  831. assert(CLI.Call && "No call instruction specified.");
  832. SmallVector<MachineOperand, 32> Ops;
  833. // Add an explicit result reg if we use the anyreg calling convention.
  834. if (IsAnyRegCC && HasDef) {
  835. assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
  836. CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
  837. CLI.NumResultRegs = 1;
  838. Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true));
  839. }
  840. // Add the <id> and <numBytes> constants.
  841. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  842. "Expected a constant integer.");
  843. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  844. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  845. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  846. "Expected a constant integer.");
  847. const auto *NumBytes =
  848. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  849. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  850. // Add the call target.
  851. if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
  852. uint64_t CalleeConstAddr =
  853. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  854. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  855. } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
  856. if (C->getOpcode() == Instruction::IntToPtr) {
  857. uint64_t CalleeConstAddr =
  858. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  859. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  860. } else
  861. llvm_unreachable("Unsupported ConstantExpr.");
  862. } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
  863. Ops.push_back(MachineOperand::CreateGA(GV, 0));
  864. } else if (isa<ConstantPointerNull>(Callee))
  865. Ops.push_back(MachineOperand::CreateImm(0));
  866. else
  867. llvm_unreachable("Unsupported callee address.");
  868. // Adjust <numArgs> to account for any arguments that have been passed on
  869. // the stack instead.
  870. unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
  871. Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
  872. // Add the calling convention
  873. Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
  874. // Add the arguments we omitted previously. The register allocator should
  875. // place these in any free register.
  876. if (IsAnyRegCC) {
  877. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
  878. unsigned Reg = getRegForValue(I->getArgOperand(i));
  879. if (!Reg)
  880. return false;
  881. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  882. }
  883. }
  884. // Push the arguments from the call instruction.
  885. for (auto Reg : CLI.OutRegs)
  886. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  887. // Push live variables for the stack map.
  888. if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
  889. return false;
  890. // Push the register mask info.
  891. Ops.push_back(MachineOperand::CreateRegMask(
  892. TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
  893. // Add scratch registers as implicit def and early clobber.
  894. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  895. for (unsigned i = 0; ScratchRegs[i]; ++i)
  896. Ops.push_back(MachineOperand::CreateReg(
  897. ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
  898. /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
  899. // Add implicit defs (return values).
  900. for (auto Reg : CLI.InRegs)
  901. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true,
  902. /*isImp=*/true));
  903. // Insert the patchpoint instruction before the call generated by the target.
  904. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
  905. TII.get(TargetOpcode::PATCHPOINT));
  906. for (auto &MO : Ops)
  907. MIB.add(MO);
  908. MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  909. // Delete the original call instruction.
  910. CLI.Call->eraseFromParent();
  911. // Inform the Frame Information that we have a patchpoint in this function.
  912. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  913. if (CLI.NumResultRegs)
  914. updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
  915. return true;
  916. }
  917. bool FastISel::selectXRayCustomEvent(const CallInst *I) {
  918. const auto &Triple = TM.getTargetTriple();
  919. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  920. return true; // don't do anything to this instruction.
  921. SmallVector<MachineOperand, 8> Ops;
  922. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
  923. /*isDef=*/false));
  924. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
  925. /*isDef=*/false));
  926. MachineInstrBuilder MIB =
  927. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  928. TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
  929. for (auto &MO : Ops)
  930. MIB.add(MO);
  931. // Insert the Patchable Event Call instruction, that gets lowered properly.
  932. return true;
  933. }
  934. bool FastISel::selectXRayTypedEvent(const CallInst *I) {
  935. const auto &Triple = TM.getTargetTriple();
  936. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  937. return true; // don't do anything to this instruction.
  938. SmallVector<MachineOperand, 8> Ops;
  939. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
  940. /*isDef=*/false));
  941. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
  942. /*isDef=*/false));
  943. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)),
  944. /*isDef=*/false));
  945. MachineInstrBuilder MIB =
  946. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  947. TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL));
  948. for (auto &MO : Ops)
  949. MIB.add(MO);
  950. // Insert the Patchable Typed Event Call instruction, that gets lowered properly.
  951. return true;
  952. }
  953. /// Returns an AttributeList representing the attributes applied to the return
  954. /// value of the given call.
  955. static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
  956. SmallVector<Attribute::AttrKind, 2> Attrs;
  957. if (CLI.RetSExt)
  958. Attrs.push_back(Attribute::SExt);
  959. if (CLI.RetZExt)
  960. Attrs.push_back(Attribute::ZExt);
  961. if (CLI.IsInReg)
  962. Attrs.push_back(Attribute::InReg);
  963. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  964. Attrs);
  965. }
  966. bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
  967. unsigned NumArgs) {
  968. MCContext &Ctx = MF->getContext();
  969. SmallString<32> MangledName;
  970. Mangler::getNameWithPrefix(MangledName, SymName, DL);
  971. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  972. return lowerCallTo(CI, Sym, NumArgs);
  973. }
  974. bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
  975. unsigned NumArgs) {
  976. ImmutableCallSite CS(CI);
  977. FunctionType *FTy = CS.getFunctionType();
  978. Type *RetTy = CS.getType();
  979. ArgListTy Args;
  980. Args.reserve(NumArgs);
  981. // Populate the argument list.
  982. // Attributes for args start at offset 1, after the return attribute.
  983. for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
  984. Value *V = CI->getOperand(ArgI);
  985. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  986. ArgListEntry Entry;
  987. Entry.Val = V;
  988. Entry.Ty = V->getType();
  989. Entry.setAttributes(&CS, ArgI);
  990. Args.push_back(Entry);
  991. }
  992. TLI.markLibCallAttributes(MF, CS.getCallingConv(), Args);
  993. CallLoweringInfo CLI;
  994. CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs);
  995. return lowerCallTo(CLI);
  996. }
  997. bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
  998. // Handle the incoming return values from the call.
  999. CLI.clearIns();
  1000. SmallVector<EVT, 4> RetTys;
  1001. ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
  1002. SmallVector<ISD::OutputArg, 4> Outs;
  1003. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
  1004. bool CanLowerReturn = TLI.CanLowerReturn(
  1005. CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  1006. // FIXME: sret demotion isn't supported yet - bail out.
  1007. if (!CanLowerReturn)
  1008. return false;
  1009. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  1010. EVT VT = RetTys[I];
  1011. MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
  1012. unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
  1013. for (unsigned i = 0; i != NumRegs; ++i) {
  1014. ISD::InputArg MyFlags;
  1015. MyFlags.VT = RegisterVT;
  1016. MyFlags.ArgVT = VT;
  1017. MyFlags.Used = CLI.IsReturnValueUsed;
  1018. if (CLI.RetSExt)
  1019. MyFlags.Flags.setSExt();
  1020. if (CLI.RetZExt)
  1021. MyFlags.Flags.setZExt();
  1022. if (CLI.IsInReg)
  1023. MyFlags.Flags.setInReg();
  1024. CLI.Ins.push_back(MyFlags);
  1025. }
  1026. }
  1027. // Handle all of the outgoing arguments.
  1028. CLI.clearOuts();
  1029. for (auto &Arg : CLI.getArgs()) {
  1030. Type *FinalType = Arg.Ty;
  1031. if (Arg.IsByVal)
  1032. FinalType = cast<PointerType>(Arg.Ty)->getElementType();
  1033. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1034. FinalType, CLI.CallConv, CLI.IsVarArg);
  1035. ISD::ArgFlagsTy Flags;
  1036. if (Arg.IsZExt)
  1037. Flags.setZExt();
  1038. if (Arg.IsSExt)
  1039. Flags.setSExt();
  1040. if (Arg.IsInReg)
  1041. Flags.setInReg();
  1042. if (Arg.IsSRet)
  1043. Flags.setSRet();
  1044. if (Arg.IsSwiftSelf)
  1045. Flags.setSwiftSelf();
  1046. if (Arg.IsSwiftError)
  1047. Flags.setSwiftError();
  1048. if (Arg.IsByVal)
  1049. Flags.setByVal();
  1050. if (Arg.IsInAlloca) {
  1051. Flags.setInAlloca();
  1052. // Set the byval flag for CCAssignFn callbacks that don't know about
  1053. // inalloca. This way we can know how many bytes we should've allocated
  1054. // and how many bytes a callee cleanup function will pop. If we port
  1055. // inalloca to more targets, we'll have to add custom inalloca handling in
  1056. // the various CC lowering callbacks.
  1057. Flags.setByVal();
  1058. }
  1059. if (Arg.IsByVal || Arg.IsInAlloca) {
  1060. PointerType *Ty = cast<PointerType>(Arg.Ty);
  1061. Type *ElementTy = Ty->getElementType();
  1062. unsigned FrameSize =
  1063. DL.getTypeAllocSize(Arg.ByValType ? Arg.ByValType : ElementTy);
  1064. // For ByVal, alignment should come from FE. BE will guess if this info
  1065. // is not there, but there are cases it cannot get right.
  1066. unsigned FrameAlign = Arg.Alignment;
  1067. if (!FrameAlign)
  1068. FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL);
  1069. Flags.setByValSize(FrameSize);
  1070. Flags.setByValAlign(FrameAlign);
  1071. }
  1072. if (Arg.IsNest)
  1073. Flags.setNest();
  1074. if (NeedsRegBlock)
  1075. Flags.setInConsecutiveRegs();
  1076. unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
  1077. Flags.setOrigAlign(OriginalAlignment);
  1078. CLI.OutVals.push_back(Arg.Val);
  1079. CLI.OutFlags.push_back(Flags);
  1080. }
  1081. if (!fastLowerCall(CLI))
  1082. return false;
  1083. // Set all unused physreg defs as dead.
  1084. assert(CLI.Call && "No call instruction specified.");
  1085. CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  1086. if (CLI.NumResultRegs && CLI.CS)
  1087. updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
  1088. // Set labels for heapallocsite call.
  1089. if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
  1090. MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
  1091. MF->addCodeViewHeapAllocSite(CLI.Call, MD);
  1092. }
  1093. return true;
  1094. }
  1095. bool FastISel::lowerCall(const CallInst *CI) {
  1096. ImmutableCallSite CS(CI);
  1097. FunctionType *FuncTy = CS.getFunctionType();
  1098. Type *RetTy = CS.getType();
  1099. ArgListTy Args;
  1100. ArgListEntry Entry;
  1101. Args.reserve(CS.arg_size());
  1102. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  1103. i != e; ++i) {
  1104. Value *V = *i;
  1105. // Skip empty types
  1106. if (V->getType()->isEmptyTy())
  1107. continue;
  1108. Entry.Val = V;
  1109. Entry.Ty = V->getType();
  1110. // Skip the first return-type Attribute to get to params.
  1111. Entry.setAttributes(&CS, i - CS.arg_begin());
  1112. Args.push_back(Entry);
  1113. }
  1114. // Check if target-independent constraints permit a tail call here.
  1115. // Target-dependent constraints are checked within fastLowerCall.
  1116. bool IsTailCall = CI->isTailCall();
  1117. if (IsTailCall && !isInTailCallPosition(CS, TM))
  1118. IsTailCall = false;
  1119. CallLoweringInfo CLI;
  1120. CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
  1121. .setTailCall(IsTailCall);
  1122. return lowerCallTo(CLI);
  1123. }
  1124. bool FastISel::selectCall(const User *I) {
  1125. const CallInst *Call = cast<CallInst>(I);
  1126. // Handle simple inline asms.
  1127. if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
  1128. // If the inline asm has side effects, then make sure that no local value
  1129. // lives across by flushing the local value map.
  1130. if (IA->hasSideEffects())
  1131. flushLocalValueMap();
  1132. // Don't attempt to handle constraints.
  1133. if (!IA->getConstraintString().empty())
  1134. return false;
  1135. unsigned ExtraInfo = 0;
  1136. if (IA->hasSideEffects())
  1137. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  1138. if (IA->isAlignStack())
  1139. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  1140. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1141. TII.get(TargetOpcode::INLINEASM))
  1142. .addExternalSymbol(IA->getAsmString().c_str())
  1143. .addImm(ExtraInfo);
  1144. return true;
  1145. }
  1146. // Handle intrinsic function calls.
  1147. if (const auto *II = dyn_cast<IntrinsicInst>(Call))
  1148. return selectIntrinsicCall(II);
  1149. // Usually, it does not make sense to initialize a value,
  1150. // make an unrelated function call and use the value, because
  1151. // it tends to be spilled on the stack. So, we move the pointer
  1152. // to the last local value to the beginning of the block, so that
  1153. // all the values which have already been materialized,
  1154. // appear after the call. It also makes sense to skip intrinsics
  1155. // since they tend to be inlined.
  1156. flushLocalValueMap();
  1157. return lowerCall(Call);
  1158. }
  1159. bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
  1160. switch (II->getIntrinsicID()) {
  1161. default:
  1162. break;
  1163. // At -O0 we don't care about the lifetime intrinsics.
  1164. case Intrinsic::lifetime_start:
  1165. case Intrinsic::lifetime_end:
  1166. // The donothing intrinsic does, well, nothing.
  1167. case Intrinsic::donothing:
  1168. // Neither does the sideeffect intrinsic.
  1169. case Intrinsic::sideeffect:
  1170. // Neither does the assume intrinsic; it's also OK not to codegen its operand.
  1171. case Intrinsic::assume:
  1172. return true;
  1173. case Intrinsic::dbg_declare: {
  1174. const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
  1175. assert(DI->getVariable() && "Missing variable");
  1176. if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
  1177. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1178. return true;
  1179. }
  1180. const Value *Address = DI->getAddress();
  1181. if (!Address || isa<UndefValue>(Address)) {
  1182. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1183. return true;
  1184. }
  1185. // Byval arguments with frame indices were already handled after argument
  1186. // lowering and before isel.
  1187. const auto *Arg =
  1188. dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
  1189. if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
  1190. return true;
  1191. Optional<MachineOperand> Op;
  1192. if (unsigned Reg = lookUpRegForValue(Address))
  1193. Op = MachineOperand::CreateReg(Reg, false);
  1194. // If we have a VLA that has a "use" in a metadata node that's then used
  1195. // here but it has no other uses, then we have a problem. E.g.,
  1196. //
  1197. // int foo (const int *x) {
  1198. // char a[*x];
  1199. // return 0;
  1200. // }
  1201. //
  1202. // If we assign 'a' a vreg and fast isel later on has to use the selection
  1203. // DAG isel, it will want to copy the value to the vreg. However, there are
  1204. // no uses, which goes counter to what selection DAG isel expects.
  1205. if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
  1206. (!isa<AllocaInst>(Address) ||
  1207. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
  1208. Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
  1209. false);
  1210. if (Op) {
  1211. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1212. "Expected inlined-at fields to agree");
  1213. // A dbg.declare describes the address of a source variable, so lower it
  1214. // into an indirect DBG_VALUE.
  1215. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1216. TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
  1217. *Op, DI->getVariable(), DI->getExpression());
  1218. } else {
  1219. // We can't yet handle anything else here because it would require
  1220. // generating code, thus altering codegen because of debug info.
  1221. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1222. }
  1223. return true;
  1224. }
  1225. case Intrinsic::dbg_value: {
  1226. // This form of DBG_VALUE is target-independent.
  1227. const DbgValueInst *DI = cast<DbgValueInst>(II);
  1228. const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
  1229. const Value *V = DI->getValue();
  1230. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1231. "Expected inlined-at fields to agree");
  1232. if (!V) {
  1233. // Currently the optimizer can produce this; insert an undef to
  1234. // help debugging. Probably the optimizer should not do this.
  1235. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
  1236. DI->getVariable(), DI->getExpression());
  1237. } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  1238. if (CI->getBitWidth() > 64)
  1239. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1240. .addCImm(CI)
  1241. .addImm(0U)
  1242. .addMetadata(DI->getVariable())
  1243. .addMetadata(DI->getExpression());
  1244. else
  1245. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1246. .addImm(CI->getZExtValue())
  1247. .addImm(0U)
  1248. .addMetadata(DI->getVariable())
  1249. .addMetadata(DI->getExpression());
  1250. } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  1251. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1252. .addFPImm(CF)
  1253. .addImm(0U)
  1254. .addMetadata(DI->getVariable())
  1255. .addMetadata(DI->getExpression());
  1256. } else if (unsigned Reg = lookUpRegForValue(V)) {
  1257. // FIXME: This does not handle register-indirect values at offset 0.
  1258. bool IsIndirect = false;
  1259. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
  1260. DI->getVariable(), DI->getExpression());
  1261. } else {
  1262. // We can't yet handle anything else here because it would require
  1263. // generating code, thus altering codegen because of debug info.
  1264. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1265. }
  1266. return true;
  1267. }
  1268. case Intrinsic::dbg_label: {
  1269. const DbgLabelInst *DI = cast<DbgLabelInst>(II);
  1270. assert(DI->getLabel() && "Missing label");
  1271. if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
  1272. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1273. return true;
  1274. }
  1275. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1276. TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel());
  1277. return true;
  1278. }
  1279. case Intrinsic::objectsize: {
  1280. ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
  1281. unsigned long long Res = CI->isZero() ? -1ULL : 0;
  1282. Constant *ResCI = ConstantInt::get(II->getType(), Res);
  1283. unsigned ResultReg = getRegForValue(ResCI);
  1284. if (!ResultReg)
  1285. return false;
  1286. updateValueMap(II, ResultReg);
  1287. return true;
  1288. }
  1289. case Intrinsic::is_constant: {
  1290. Constant *ResCI = ConstantInt::get(II->getType(), 0);
  1291. unsigned ResultReg = getRegForValue(ResCI);
  1292. if (!ResultReg)
  1293. return false;
  1294. updateValueMap(II, ResultReg);
  1295. return true;
  1296. }
  1297. case Intrinsic::launder_invariant_group:
  1298. case Intrinsic::strip_invariant_group:
  1299. case Intrinsic::expect: {
  1300. unsigned ResultReg = getRegForValue(II->getArgOperand(0));
  1301. if (!ResultReg)
  1302. return false;
  1303. updateValueMap(II, ResultReg);
  1304. return true;
  1305. }
  1306. case Intrinsic::experimental_stackmap:
  1307. return selectStackmap(II);
  1308. case Intrinsic::experimental_patchpoint_void:
  1309. case Intrinsic::experimental_patchpoint_i64:
  1310. return selectPatchpoint(II);
  1311. case Intrinsic::xray_customevent:
  1312. return selectXRayCustomEvent(II);
  1313. case Intrinsic::xray_typedevent:
  1314. return selectXRayTypedEvent(II);
  1315. }
  1316. return fastLowerIntrinsicCall(II);
  1317. }
  1318. bool FastISel::selectCast(const User *I, unsigned Opcode) {
  1319. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1320. EVT DstVT = TLI.getValueType(DL, I->getType());
  1321. if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
  1322. !DstVT.isSimple())
  1323. // Unhandled type. Halt "fast" selection and bail.
  1324. return false;
  1325. // Check if the destination type is legal.
  1326. if (!TLI.isTypeLegal(DstVT))
  1327. return false;
  1328. // Check if the source operand is legal.
  1329. if (!TLI.isTypeLegal(SrcVT))
  1330. return false;
  1331. unsigned InputReg = getRegForValue(I->getOperand(0));
  1332. if (!InputReg)
  1333. // Unhandled operand. Halt "fast" selection and bail.
  1334. return false;
  1335. bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
  1336. unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
  1337. Opcode, InputReg, InputRegIsKill);
  1338. if (!ResultReg)
  1339. return false;
  1340. updateValueMap(I, ResultReg);
  1341. return true;
  1342. }
  1343. bool FastISel::selectBitCast(const User *I) {
  1344. // If the bitcast doesn't change the type, just use the operand value.
  1345. if (I->getType() == I->getOperand(0)->getType()) {
  1346. unsigned Reg = getRegForValue(I->getOperand(0));
  1347. if (!Reg)
  1348. return false;
  1349. updateValueMap(I, Reg);
  1350. return true;
  1351. }
  1352. // Bitcasts of other values become reg-reg copies or BITCAST operators.
  1353. EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1354. EVT DstEVT = TLI.getValueType(DL, I->getType());
  1355. if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
  1356. !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
  1357. // Unhandled type. Halt "fast" selection and bail.
  1358. return false;
  1359. MVT SrcVT = SrcEVT.getSimpleVT();
  1360. MVT DstVT = DstEVT.getSimpleVT();
  1361. unsigned Op0 = getRegForValue(I->getOperand(0));
  1362. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  1363. return false;
  1364. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  1365. // First, try to perform the bitcast by inserting a reg-reg copy.
  1366. unsigned ResultReg = 0;
  1367. if (SrcVT == DstVT) {
  1368. const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
  1369. const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
  1370. // Don't attempt a cross-class copy. It will likely fail.
  1371. if (SrcClass == DstClass) {
  1372. ResultReg = createResultReg(DstClass);
  1373. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1374. TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
  1375. }
  1376. }
  1377. // If the reg-reg copy failed, select a BITCAST opcode.
  1378. if (!ResultReg)
  1379. ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
  1380. if (!ResultReg)
  1381. return false;
  1382. updateValueMap(I, ResultReg);
  1383. return true;
  1384. }
  1385. // Remove local value instructions starting from the instruction after
  1386. // SavedLastLocalValue to the current function insert point.
  1387. void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
  1388. {
  1389. MachineInstr *CurLastLocalValue = getLastLocalValue();
  1390. if (CurLastLocalValue != SavedLastLocalValue) {
  1391. // Find the first local value instruction to be deleted.
  1392. // This is the instruction after SavedLastLocalValue if it is non-NULL.
  1393. // Otherwise it's the first instruction in the block.
  1394. MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
  1395. if (SavedLastLocalValue)
  1396. ++FirstDeadInst;
  1397. else
  1398. FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
  1399. setLastLocalValue(SavedLastLocalValue);
  1400. removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
  1401. }
  1402. }
  1403. bool FastISel::selectInstruction(const Instruction *I) {
  1404. MachineInstr *SavedLastLocalValue = getLastLocalValue();
  1405. // Just before the terminator instruction, insert instructions to
  1406. // feed PHI nodes in successor blocks.
  1407. if (I->isTerminator()) {
  1408. if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
  1409. // PHI node handling may have generated local value instructions,
  1410. // even though it failed to handle all PHI nodes.
  1411. // We remove these instructions because SelectionDAGISel will generate
  1412. // them again.
  1413. removeDeadLocalValueCode(SavedLastLocalValue);
  1414. return false;
  1415. }
  1416. }
  1417. // FastISel does not handle any operand bundles except OB_funclet.
  1418. if (ImmutableCallSite CS = ImmutableCallSite(I))
  1419. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i)
  1420. if (CS.getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
  1421. return false;
  1422. DbgLoc = I->getDebugLoc();
  1423. SavedInsertPt = FuncInfo.InsertPt;
  1424. if (const auto *Call = dyn_cast<CallInst>(I)) {
  1425. const Function *F = Call->getCalledFunction();
  1426. LibFunc Func;
  1427. // As a special case, don't handle calls to builtin library functions that
  1428. // may be translated directly to target instructions.
  1429. if (F && !F->hasLocalLinkage() && F->hasName() &&
  1430. LibInfo->getLibFunc(F->getName(), Func) &&
  1431. LibInfo->hasOptimizedCodeGen(Func))
  1432. return false;
  1433. // Don't handle Intrinsic::trap if a trap function is specified.
  1434. if (F && F->getIntrinsicID() == Intrinsic::trap &&
  1435. Call->hasFnAttr("trap-func-name"))
  1436. return false;
  1437. }
  1438. // First, try doing target-independent selection.
  1439. if (!SkipTargetIndependentISel) {
  1440. if (selectOperator(I, I->getOpcode())) {
  1441. ++NumFastIselSuccessIndependent;
  1442. DbgLoc = DebugLoc();
  1443. return true;
  1444. }
  1445. // Remove dead code.
  1446. recomputeInsertPt();
  1447. if (SavedInsertPt != FuncInfo.InsertPt)
  1448. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1449. SavedInsertPt = FuncInfo.InsertPt;
  1450. }
  1451. // Next, try calling the target to attempt to handle the instruction.
  1452. if (fastSelectInstruction(I)) {
  1453. ++NumFastIselSuccessTarget;
  1454. DbgLoc = DebugLoc();
  1455. return true;
  1456. }
  1457. // Remove dead code.
  1458. recomputeInsertPt();
  1459. if (SavedInsertPt != FuncInfo.InsertPt)
  1460. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1461. DbgLoc = DebugLoc();
  1462. // Undo phi node updates, because they will be added again by SelectionDAG.
  1463. if (I->isTerminator()) {
  1464. // PHI node handling may have generated local value instructions.
  1465. // We remove them because SelectionDAGISel will generate them again.
  1466. removeDeadLocalValueCode(SavedLastLocalValue);
  1467. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1468. }
  1469. return false;
  1470. }
  1471. /// Emit an unconditional branch to the given block, unless it is the immediate
  1472. /// (fall-through) successor, and update the CFG.
  1473. void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
  1474. const DebugLoc &DbgLoc) {
  1475. if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
  1476. FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
  1477. // For more accurate line information if this is the only instruction
  1478. // in the block then emit it, otherwise we have the unconditional
  1479. // fall-through case, which needs no instructions.
  1480. } else {
  1481. // The unconditional branch case.
  1482. TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
  1483. SmallVector<MachineOperand, 0>(), DbgLoc);
  1484. }
  1485. if (FuncInfo.BPI) {
  1486. auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
  1487. FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
  1488. FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
  1489. } else
  1490. FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
  1491. }
  1492. void FastISel::finishCondBranch(const BasicBlock *BranchBB,
  1493. MachineBasicBlock *TrueMBB,
  1494. MachineBasicBlock *FalseMBB) {
  1495. // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
  1496. // happen in degenerate IR and MachineIR forbids to have a block twice in the
  1497. // successor/predecessor lists.
  1498. if (TrueMBB != FalseMBB) {
  1499. if (FuncInfo.BPI) {
  1500. auto BranchProbability =
  1501. FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
  1502. FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
  1503. } else
  1504. FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
  1505. }
  1506. fastEmitBranch(FalseMBB, DbgLoc);
  1507. }
  1508. /// Emit an FNeg operation.
  1509. bool FastISel::selectFNeg(const User *I, const Value *In) {
  1510. unsigned OpReg = getRegForValue(In);
  1511. if (!OpReg)
  1512. return false;
  1513. bool OpRegIsKill = hasTrivialKill(In);
  1514. // If the target has ISD::FNEG, use it.
  1515. EVT VT = TLI.getValueType(DL, I->getType());
  1516. unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
  1517. OpReg, OpRegIsKill);
  1518. if (ResultReg) {
  1519. updateValueMap(I, ResultReg);
  1520. return true;
  1521. }
  1522. // Bitcast the value to integer, twiddle the sign bit with xor,
  1523. // and then bitcast it back to floating-point.
  1524. if (VT.getSizeInBits() > 64)
  1525. return false;
  1526. EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
  1527. if (!TLI.isTypeLegal(IntVT))
  1528. return false;
  1529. unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
  1530. ISD::BITCAST, OpReg, OpRegIsKill);
  1531. if (!IntReg)
  1532. return false;
  1533. unsigned IntResultReg = fastEmit_ri_(
  1534. IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
  1535. UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
  1536. if (!IntResultReg)
  1537. return false;
  1538. ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
  1539. IntResultReg, /*IsKill=*/true);
  1540. if (!ResultReg)
  1541. return false;
  1542. updateValueMap(I, ResultReg);
  1543. return true;
  1544. }
  1545. bool FastISel::selectExtractValue(const User *U) {
  1546. const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
  1547. if (!EVI)
  1548. return false;
  1549. // Make sure we only try to handle extracts with a legal result. But also
  1550. // allow i1 because it's easy.
  1551. EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
  1552. if (!RealVT.isSimple())
  1553. return false;
  1554. MVT VT = RealVT.getSimpleVT();
  1555. if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
  1556. return false;
  1557. const Value *Op0 = EVI->getOperand(0);
  1558. Type *AggTy = Op0->getType();
  1559. // Get the base result register.
  1560. unsigned ResultReg;
  1561. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
  1562. if (I != FuncInfo.ValueMap.end())
  1563. ResultReg = I->second;
  1564. else if (isa<Instruction>(Op0))
  1565. ResultReg = FuncInfo.InitializeRegForValue(Op0);
  1566. else
  1567. return false; // fast-isel can't handle aggregate constants at the moment
  1568. // Get the actual result register, which is an offset from the base register.
  1569. unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
  1570. SmallVector<EVT, 4> AggValueVTs;
  1571. ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
  1572. for (unsigned i = 0; i < VTIndex; i++)
  1573. ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
  1574. updateValueMap(EVI, ResultReg);
  1575. return true;
  1576. }
  1577. bool FastISel::selectOperator(const User *I, unsigned Opcode) {
  1578. switch (Opcode) {
  1579. case Instruction::Add:
  1580. return selectBinaryOp(I, ISD::ADD);
  1581. case Instruction::FAdd:
  1582. return selectBinaryOp(I, ISD::FADD);
  1583. case Instruction::Sub:
  1584. return selectBinaryOp(I, ISD::SUB);
  1585. case Instruction::FSub: {
  1586. // FNeg is currently represented in LLVM IR as a special case of FSub.
  1587. Value *X;
  1588. if (match(I, m_FNeg(m_Value(X))))
  1589. return selectFNeg(I, X);
  1590. return selectBinaryOp(I, ISD::FSUB);
  1591. }
  1592. case Instruction::Mul:
  1593. return selectBinaryOp(I, ISD::MUL);
  1594. case Instruction::FMul:
  1595. return selectBinaryOp(I, ISD::FMUL);
  1596. case Instruction::SDiv:
  1597. return selectBinaryOp(I, ISD::SDIV);
  1598. case Instruction::UDiv:
  1599. return selectBinaryOp(I, ISD::UDIV);
  1600. case Instruction::FDiv:
  1601. return selectBinaryOp(I, ISD::FDIV);
  1602. case Instruction::SRem:
  1603. return selectBinaryOp(I, ISD::SREM);
  1604. case Instruction::URem:
  1605. return selectBinaryOp(I, ISD::UREM);
  1606. case Instruction::FRem:
  1607. return selectBinaryOp(I, ISD::FREM);
  1608. case Instruction::Shl:
  1609. return selectBinaryOp(I, ISD::SHL);
  1610. case Instruction::LShr:
  1611. return selectBinaryOp(I, ISD::SRL);
  1612. case Instruction::AShr:
  1613. return selectBinaryOp(I, ISD::SRA);
  1614. case Instruction::And:
  1615. return selectBinaryOp(I, ISD::AND);
  1616. case Instruction::Or:
  1617. return selectBinaryOp(I, ISD::OR);
  1618. case Instruction::Xor:
  1619. return selectBinaryOp(I, ISD::XOR);
  1620. case Instruction::FNeg:
  1621. return selectFNeg(I, I->getOperand(0));
  1622. case Instruction::GetElementPtr:
  1623. return selectGetElementPtr(I);
  1624. case Instruction::Br: {
  1625. const BranchInst *BI = cast<BranchInst>(I);
  1626. if (BI->isUnconditional()) {
  1627. const BasicBlock *LLVMSucc = BI->getSuccessor(0);
  1628. MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
  1629. fastEmitBranch(MSucc, BI->getDebugLoc());
  1630. return true;
  1631. }
  1632. // Conditional branches are not handed yet.
  1633. // Halt "fast" selection and bail.
  1634. return false;
  1635. }
  1636. case Instruction::Unreachable:
  1637. if (TM.Options.TrapUnreachable)
  1638. return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
  1639. else
  1640. return true;
  1641. case Instruction::Alloca:
  1642. // FunctionLowering has the static-sized case covered.
  1643. if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
  1644. return true;
  1645. // Dynamic-sized alloca is not handled yet.
  1646. return false;
  1647. case Instruction::Call:
  1648. // On AIX, call lowering uses the DAG-ISEL path currently so that the
  1649. // callee of the direct function call instruction will be mapped to the
  1650. // symbol for the function's entry point, which is distinct from the
  1651. // function descriptor symbol. The latter is the symbol whose XCOFF symbol
  1652. // name is the C-linkage name of the source level function.
  1653. if (TM.getTargetTriple().isOSAIX())
  1654. return false;
  1655. return selectCall(I);
  1656. case Instruction::BitCast:
  1657. return selectBitCast(I);
  1658. case Instruction::FPToSI:
  1659. return selectCast(I, ISD::FP_TO_SINT);
  1660. case Instruction::ZExt:
  1661. return selectCast(I, ISD::ZERO_EXTEND);
  1662. case Instruction::SExt:
  1663. return selectCast(I, ISD::SIGN_EXTEND);
  1664. case Instruction::Trunc:
  1665. return selectCast(I, ISD::TRUNCATE);
  1666. case Instruction::SIToFP:
  1667. return selectCast(I, ISD::SINT_TO_FP);
  1668. case Instruction::IntToPtr: // Deliberate fall-through.
  1669. case Instruction::PtrToInt: {
  1670. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1671. EVT DstVT = TLI.getValueType(DL, I->getType());
  1672. if (DstVT.bitsGT(SrcVT))
  1673. return selectCast(I, ISD::ZERO_EXTEND);
  1674. if (DstVT.bitsLT(SrcVT))
  1675. return selectCast(I, ISD::TRUNCATE);
  1676. unsigned Reg = getRegForValue(I->getOperand(0));
  1677. if (!Reg)
  1678. return false;
  1679. updateValueMap(I, Reg);
  1680. return true;
  1681. }
  1682. case Instruction::ExtractValue:
  1683. return selectExtractValue(I);
  1684. case Instruction::PHI:
  1685. llvm_unreachable("FastISel shouldn't visit PHI nodes!");
  1686. default:
  1687. // Unhandled instruction. Halt "fast" selection and bail.
  1688. return false;
  1689. }
  1690. }
  1691. FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
  1692. const TargetLibraryInfo *LibInfo,
  1693. bool SkipTargetIndependentISel)
  1694. : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
  1695. MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
  1696. TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
  1697. TII(*MF->getSubtarget().getInstrInfo()),
  1698. TLI(*MF->getSubtarget().getTargetLowering()),
  1699. TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
  1700. SkipTargetIndependentISel(SkipTargetIndependentISel) {}
  1701. FastISel::~FastISel() = default;
  1702. bool FastISel::fastLowerArguments() { return false; }
  1703. bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
  1704. bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
  1705. return false;
  1706. }
  1707. unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
  1708. unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
  1709. bool /*Op0IsKill*/) {
  1710. return 0;
  1711. }
  1712. unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
  1713. bool /*Op0IsKill*/, unsigned /*Op1*/,
  1714. bool /*Op1IsKill*/) {
  1715. return 0;
  1716. }
  1717. unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
  1718. return 0;
  1719. }
  1720. unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
  1721. const ConstantFP * /*FPImm*/) {
  1722. return 0;
  1723. }
  1724. unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
  1725. bool /*Op0IsKill*/, uint64_t /*Imm*/) {
  1726. return 0;
  1727. }
  1728. /// This method is a wrapper of fastEmit_ri. It first tries to emit an
  1729. /// instruction with an immediate operand using fastEmit_ri.
  1730. /// If that fails, it materializes the immediate into a register and try
  1731. /// fastEmit_rr instead.
  1732. unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
  1733. bool Op0IsKill, uint64_t Imm, MVT ImmType) {
  1734. // If this is a multiply by a power of two, emit this as a shift left.
  1735. if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
  1736. Opcode = ISD::SHL;
  1737. Imm = Log2_64(Imm);
  1738. } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
  1739. // div x, 8 -> srl x, 3
  1740. Opcode = ISD::SRL;
  1741. Imm = Log2_64(Imm);
  1742. }
  1743. // Horrible hack (to be removed), check to make sure shift amounts are
  1744. // in-range.
  1745. if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
  1746. Imm >= VT.getSizeInBits())
  1747. return 0;
  1748. // First check if immediate type is legal. If not, we can't use the ri form.
  1749. unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
  1750. if (ResultReg)
  1751. return ResultReg;
  1752. unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
  1753. bool IsImmKill = true;
  1754. if (!MaterialReg) {
  1755. // This is a bit ugly/slow, but failing here means falling out of
  1756. // fast-isel, which would be very slow.
  1757. IntegerType *ITy =
  1758. IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
  1759. MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
  1760. if (!MaterialReg)
  1761. return 0;
  1762. // FIXME: If the materialized register here has no uses yet then this
  1763. // will be the first use and we should be able to mark it as killed.
  1764. // However, the local value area for materialising constant expressions
  1765. // grows down, not up, which means that any constant expressions we generate
  1766. // later which also use 'Imm' could be after this instruction and therefore
  1767. // after this kill.
  1768. IsImmKill = false;
  1769. }
  1770. return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
  1771. }
  1772. unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
  1773. return MRI.createVirtualRegister(RC);
  1774. }
  1775. unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
  1776. unsigned OpNum) {
  1777. if (TargetRegisterInfo::isVirtualRegister(Op)) {
  1778. const TargetRegisterClass *RegClass =
  1779. TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
  1780. if (!MRI.constrainRegClass(Op, RegClass)) {
  1781. // If it's not legal to COPY between the register classes, something
  1782. // has gone very wrong before we got here.
  1783. unsigned NewOp = createResultReg(RegClass);
  1784. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1785. TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
  1786. return NewOp;
  1787. }
  1788. }
  1789. return Op;
  1790. }
  1791. unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
  1792. const TargetRegisterClass *RC) {
  1793. unsigned ResultReg = createResultReg(RC);
  1794. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1795. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
  1796. return ResultReg;
  1797. }
  1798. unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
  1799. const TargetRegisterClass *RC, unsigned Op0,
  1800. bool Op0IsKill) {
  1801. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1802. unsigned ResultReg = createResultReg(RC);
  1803. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1804. if (II.getNumDefs() >= 1)
  1805. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1806. .addReg(Op0, getKillRegState(Op0IsKill));
  1807. else {
  1808. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1809. .addReg(Op0, getKillRegState(Op0IsKill));
  1810. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1811. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1812. }
  1813. return ResultReg;
  1814. }
  1815. unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
  1816. const TargetRegisterClass *RC, unsigned Op0,
  1817. bool Op0IsKill, unsigned Op1,
  1818. bool Op1IsKill) {
  1819. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1820. unsigned ResultReg = createResultReg(RC);
  1821. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1822. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1823. if (II.getNumDefs() >= 1)
  1824. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1825. .addReg(Op0, getKillRegState(Op0IsKill))
  1826. .addReg(Op1, getKillRegState(Op1IsKill));
  1827. else {
  1828. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1829. .addReg(Op0, getKillRegState(Op0IsKill))
  1830. .addReg(Op1, getKillRegState(Op1IsKill));
  1831. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1832. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1833. }
  1834. return ResultReg;
  1835. }
  1836. unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
  1837. const TargetRegisterClass *RC, unsigned Op0,
  1838. bool Op0IsKill, unsigned Op1,
  1839. bool Op1IsKill, unsigned Op2,
  1840. bool Op2IsKill) {
  1841. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1842. unsigned ResultReg = createResultReg(RC);
  1843. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1844. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1845. Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
  1846. if (II.getNumDefs() >= 1)
  1847. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1848. .addReg(Op0, getKillRegState(Op0IsKill))
  1849. .addReg(Op1, getKillRegState(Op1IsKill))
  1850. .addReg(Op2, getKillRegState(Op2IsKill));
  1851. else {
  1852. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1853. .addReg(Op0, getKillRegState(Op0IsKill))
  1854. .addReg(Op1, getKillRegState(Op1IsKill))
  1855. .addReg(Op2, getKillRegState(Op2IsKill));
  1856. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1857. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1858. }
  1859. return ResultReg;
  1860. }
  1861. unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
  1862. const TargetRegisterClass *RC, unsigned Op0,
  1863. bool Op0IsKill, uint64_t Imm) {
  1864. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1865. unsigned ResultReg = createResultReg(RC);
  1866. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1867. if (II.getNumDefs() >= 1)
  1868. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1869. .addReg(Op0, getKillRegState(Op0IsKill))
  1870. .addImm(Imm);
  1871. else {
  1872. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1873. .addReg(Op0, getKillRegState(Op0IsKill))
  1874. .addImm(Imm);
  1875. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1876. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1877. }
  1878. return ResultReg;
  1879. }
  1880. unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
  1881. const TargetRegisterClass *RC, unsigned Op0,
  1882. bool Op0IsKill, uint64_t Imm1,
  1883. uint64_t Imm2) {
  1884. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1885. unsigned ResultReg = createResultReg(RC);
  1886. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1887. if (II.getNumDefs() >= 1)
  1888. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1889. .addReg(Op0, getKillRegState(Op0IsKill))
  1890. .addImm(Imm1)
  1891. .addImm(Imm2);
  1892. else {
  1893. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1894. .addReg(Op0, getKillRegState(Op0IsKill))
  1895. .addImm(Imm1)
  1896. .addImm(Imm2);
  1897. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1898. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1899. }
  1900. return ResultReg;
  1901. }
  1902. unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
  1903. const TargetRegisterClass *RC,
  1904. const ConstantFP *FPImm) {
  1905. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1906. unsigned ResultReg = createResultReg(RC);
  1907. if (II.getNumDefs() >= 1)
  1908. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1909. .addFPImm(FPImm);
  1910. else {
  1911. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1912. .addFPImm(FPImm);
  1913. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1914. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1915. }
  1916. return ResultReg;
  1917. }
  1918. unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
  1919. const TargetRegisterClass *RC, unsigned Op0,
  1920. bool Op0IsKill, unsigned Op1,
  1921. bool Op1IsKill, uint64_t Imm) {
  1922. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1923. unsigned ResultReg = createResultReg(RC);
  1924. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1925. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1926. if (II.getNumDefs() >= 1)
  1927. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1928. .addReg(Op0, getKillRegState(Op0IsKill))
  1929. .addReg(Op1, getKillRegState(Op1IsKill))
  1930. .addImm(Imm);
  1931. else {
  1932. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1933. .addReg(Op0, getKillRegState(Op0IsKill))
  1934. .addReg(Op1, getKillRegState(Op1IsKill))
  1935. .addImm(Imm);
  1936. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1937. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1938. }
  1939. return ResultReg;
  1940. }
  1941. unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
  1942. const TargetRegisterClass *RC, uint64_t Imm) {
  1943. unsigned ResultReg = createResultReg(RC);
  1944. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1945. if (II.getNumDefs() >= 1)
  1946. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1947. .addImm(Imm);
  1948. else {
  1949. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
  1950. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1951. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1952. }
  1953. return ResultReg;
  1954. }
  1955. unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
  1956. bool Op0IsKill, uint32_t Idx) {
  1957. unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
  1958. assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
  1959. "Cannot yet extract from physregs");
  1960. const TargetRegisterClass *RC = MRI.getRegClass(Op0);
  1961. MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
  1962. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
  1963. ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
  1964. return ResultReg;
  1965. }
  1966. /// Emit MachineInstrs to compute the value of Op with all but the least
  1967. /// significant bit set to zero.
  1968. unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
  1969. return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
  1970. }
  1971. /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
  1972. /// Emit code to ensure constants are copied into registers when needed.
  1973. /// Remember the virtual registers that need to be added to the Machine PHI
  1974. /// nodes as input. We cannot just directly add them, because expansion
  1975. /// might result in multiple MBB's for one BB. As such, the start of the
  1976. /// BB might correspond to a different MBB than the end.
  1977. bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  1978. const Instruction *TI = LLVMBB->getTerminator();
  1979. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  1980. FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
  1981. // Check successor nodes' PHI nodes that expect a constant to be available
  1982. // from this block.
  1983. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  1984. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  1985. if (!isa<PHINode>(SuccBB->begin()))
  1986. continue;
  1987. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  1988. // If this terminator has multiple identical successors (common for
  1989. // switches), only handle each succ once.
  1990. if (!SuccsHandled.insert(SuccMBB).second)
  1991. continue;
  1992. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  1993. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  1994. // nodes and Machine PHI nodes, but the incoming operands have not been
  1995. // emitted yet.
  1996. for (const PHINode &PN : SuccBB->phis()) {
  1997. // Ignore dead phi's.
  1998. if (PN.use_empty())
  1999. continue;
  2000. // Only handle legal types. Two interesting things to note here. First,
  2001. // by bailing out early, we may leave behind some dead instructions,
  2002. // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
  2003. // own moves. Second, this check is necessary because FastISel doesn't
  2004. // use CreateRegs to create registers, so it always creates
  2005. // exactly one register for each non-void instruction.
  2006. EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
  2007. if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
  2008. // Handle integer promotions, though, because they're common and easy.
  2009. if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
  2010. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  2011. return false;
  2012. }
  2013. }
  2014. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  2015. // Set the DebugLoc for the copy. Prefer the location of the operand
  2016. // if there is one; use the location of the PHI otherwise.
  2017. DbgLoc = PN.getDebugLoc();
  2018. if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
  2019. DbgLoc = Inst->getDebugLoc();
  2020. unsigned Reg = getRegForValue(PHIOp);
  2021. if (!Reg) {
  2022. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  2023. return false;
  2024. }
  2025. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
  2026. DbgLoc = DebugLoc();
  2027. }
  2028. }
  2029. return true;
  2030. }
  2031. bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
  2032. assert(LI->hasOneUse() &&
  2033. "tryToFoldLoad expected a LoadInst with a single use");
  2034. // We know that the load has a single use, but don't know what it is. If it
  2035. // isn't one of the folded instructions, then we can't succeed here. Handle
  2036. // this by scanning the single-use users of the load until we get to FoldInst.
  2037. unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
  2038. const Instruction *TheUser = LI->user_back();
  2039. while (TheUser != FoldInst && // Scan up until we find FoldInst.
  2040. // Stay in the right block.
  2041. TheUser->getParent() == FoldInst->getParent() &&
  2042. --MaxUsers) { // Don't scan too far.
  2043. // If there are multiple or no uses of this instruction, then bail out.
  2044. if (!TheUser->hasOneUse())
  2045. return false;
  2046. TheUser = TheUser->user_back();
  2047. }
  2048. // If we didn't find the fold instruction, then we failed to collapse the
  2049. // sequence.
  2050. if (TheUser != FoldInst)
  2051. return false;
  2052. // Don't try to fold volatile loads. Target has to deal with alignment
  2053. // constraints.
  2054. if (LI->isVolatile())
  2055. return false;
  2056. // Figure out which vreg this is going into. If there is no assigned vreg yet
  2057. // then there actually was no reference to it. Perhaps the load is referenced
  2058. // by a dead instruction.
  2059. unsigned LoadReg = getRegForValue(LI);
  2060. if (!LoadReg)
  2061. return false;
  2062. // We can't fold if this vreg has no uses or more than one use. Multiple uses
  2063. // may mean that the instruction got lowered to multiple MIs, or the use of
  2064. // the loaded value ended up being multiple operands of the result.
  2065. if (!MRI.hasOneUse(LoadReg))
  2066. return false;
  2067. MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
  2068. MachineInstr *User = RI->getParent();
  2069. // Set the insertion point properly. Folding the load can cause generation of
  2070. // other random instructions (like sign extends) for addressing modes; make
  2071. // sure they get inserted in a logical place before the new instruction.
  2072. FuncInfo.InsertPt = User;
  2073. FuncInfo.MBB = User->getParent();
  2074. // Ask the target to try folding the load.
  2075. return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
  2076. }
  2077. bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
  2078. // Must be an add.
  2079. if (!isa<AddOperator>(Add))
  2080. return false;
  2081. // Type size needs to match.
  2082. if (DL.getTypeSizeInBits(GEP->getType()) !=
  2083. DL.getTypeSizeInBits(Add->getType()))
  2084. return false;
  2085. // Must be in the same basic block.
  2086. if (isa<Instruction>(Add) &&
  2087. FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
  2088. return false;
  2089. // Must have a constant operand.
  2090. return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
  2091. }
  2092. MachineMemOperand *
  2093. FastISel::createMachineMemOperandFor(const Instruction *I) const {
  2094. const Value *Ptr;
  2095. Type *ValTy;
  2096. unsigned Alignment;
  2097. MachineMemOperand::Flags Flags;
  2098. bool IsVolatile;
  2099. if (const auto *LI = dyn_cast<LoadInst>(I)) {
  2100. Alignment = LI->getAlignment();
  2101. IsVolatile = LI->isVolatile();
  2102. Flags = MachineMemOperand::MOLoad;
  2103. Ptr = LI->getPointerOperand();
  2104. ValTy = LI->getType();
  2105. } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
  2106. Alignment = SI->getAlignment();
  2107. IsVolatile = SI->isVolatile();
  2108. Flags = MachineMemOperand::MOStore;
  2109. Ptr = SI->getPointerOperand();
  2110. ValTy = SI->getValueOperand()->getType();
  2111. } else
  2112. return nullptr;
  2113. bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  2114. bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  2115. bool IsDereferenceable =
  2116. I->getMetadata(LLVMContext::MD_dereferenceable) != nullptr;
  2117. const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
  2118. AAMDNodes AAInfo;
  2119. I->getAAMetadata(AAInfo);
  2120. if (Alignment == 0) // Ensure that codegen never sees alignment 0.
  2121. Alignment = DL.getABITypeAlignment(ValTy);
  2122. unsigned Size = DL.getTypeStoreSize(ValTy);
  2123. if (IsVolatile)
  2124. Flags |= MachineMemOperand::MOVolatile;
  2125. if (IsNonTemporal)
  2126. Flags |= MachineMemOperand::MONonTemporal;
  2127. if (IsDereferenceable)
  2128. Flags |= MachineMemOperand::MODereferenceable;
  2129. if (IsInvariant)
  2130. Flags |= MachineMemOperand::MOInvariant;
  2131. return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
  2132. Alignment, AAInfo, Ranges);
  2133. }
  2134. CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
  2135. // If both operands are the same, then try to optimize or fold the cmp.
  2136. CmpInst::Predicate Predicate = CI->getPredicate();
  2137. if (CI->getOperand(0) != CI->getOperand(1))
  2138. return Predicate;
  2139. switch (Predicate) {
  2140. default: llvm_unreachable("Invalid predicate!");
  2141. case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
  2142. case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
  2143. case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
  2144. case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
  2145. case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
  2146. case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
  2147. case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
  2148. case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
  2149. case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
  2150. case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
  2151. case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
  2152. case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  2153. case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
  2154. case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  2155. case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
  2156. case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
  2157. case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
  2158. case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
  2159. case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
  2160. case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  2161. case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
  2162. case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  2163. case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
  2164. case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
  2165. case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
  2166. case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
  2167. }
  2168. return Predicate;
  2169. }