FastISel.cpp 81 KB

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