IRTranslator.cpp 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521
  1. //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements the IRTranslator class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
  12. #include "llvm/ADT/PostOrderIterator.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/BranchProbabilityInfo.h"
  18. #include "llvm/Analysis/Loads.h"
  19. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/CodeGen/Analysis.h"
  22. #include "llvm/CodeGen/GlobalISel/CallLowering.h"
  23. #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
  24. #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
  25. #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
  26. #include "llvm/CodeGen/LowLevelType.h"
  27. #include "llvm/CodeGen/MachineBasicBlock.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineMemOperand.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/RuntimeLibcalls.h"
  36. #include "llvm/CodeGen/StackProtector.h"
  37. #include "llvm/CodeGen/SwitchLoweringUtils.h"
  38. #include "llvm/CodeGen/TargetFrameLowering.h"
  39. #include "llvm/CodeGen/TargetInstrInfo.h"
  40. #include "llvm/CodeGen/TargetLowering.h"
  41. #include "llvm/CodeGen/TargetPassConfig.h"
  42. #include "llvm/CodeGen/TargetRegisterInfo.h"
  43. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  44. #include "llvm/IR/BasicBlock.h"
  45. #include "llvm/IR/CFG.h"
  46. #include "llvm/IR/Constant.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/DebugInfo.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/DiagnosticInfo.h"
  52. #include "llvm/IR/Function.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/InlineAsm.h"
  55. #include "llvm/IR/InstrTypes.h"
  56. #include "llvm/IR/Instructions.h"
  57. #include "llvm/IR/IntrinsicInst.h"
  58. #include "llvm/IR/Intrinsics.h"
  59. #include "llvm/IR/LLVMContext.h"
  60. #include "llvm/IR/Metadata.h"
  61. #include "llvm/IR/PatternMatch.h"
  62. #include "llvm/IR/Type.h"
  63. #include "llvm/IR/User.h"
  64. #include "llvm/IR/Value.h"
  65. #include "llvm/InitializePasses.h"
  66. #include "llvm/MC/MCContext.h"
  67. #include "llvm/Pass.h"
  68. #include "llvm/Support/Casting.h"
  69. #include "llvm/Support/CodeGen.h"
  70. #include "llvm/Support/Debug.h"
  71. #include "llvm/Support/ErrorHandling.h"
  72. #include "llvm/Support/LowLevelTypeImpl.h"
  73. #include "llvm/Support/MathExtras.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include "llvm/Target/TargetIntrinsicInfo.h"
  76. #include "llvm/Target/TargetMachine.h"
  77. #include "llvm/Transforms/Utils/MemoryOpRemark.h"
  78. #include <algorithm>
  79. #include <cassert>
  80. #include <cstddef>
  81. #include <cstdint>
  82. #include <iterator>
  83. #include <string>
  84. #include <utility>
  85. #include <vector>
  86. #define DEBUG_TYPE "irtranslator"
  87. using namespace llvm;
  88. static cl::opt<bool>
  89. EnableCSEInIRTranslator("enable-cse-in-irtranslator",
  90. cl::desc("Should enable CSE in irtranslator"),
  91. cl::Optional, cl::init(false));
  92. char IRTranslator::ID = 0;
  93. INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
  94. false, false)
  95. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  96. INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
  97. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  98. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  99. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  100. INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
  101. false, false)
  102. static void reportTranslationError(MachineFunction &MF,
  103. const TargetPassConfig &TPC,
  104. OptimizationRemarkEmitter &ORE,
  105. OptimizationRemarkMissed &R) {
  106. MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
  107. // Print the function name explicitly if we don't have a debug location (which
  108. // makes the diagnostic less useful) or if we're going to emit a raw error.
  109. if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
  110. R << (" (in function: " + MF.getName() + ")").str();
  111. if (TPC.isGlobalISelAbortEnabled())
  112. report_fatal_error(Twine(R.getMsg()));
  113. else
  114. ORE.emit(R);
  115. }
  116. IRTranslator::IRTranslator(CodeGenOpt::Level optlevel)
  117. : MachineFunctionPass(ID), OptLevel(optlevel) {}
  118. #ifndef NDEBUG
  119. namespace {
  120. /// Verify that every instruction created has the same DILocation as the
  121. /// instruction being translated.
  122. class DILocationVerifier : public GISelChangeObserver {
  123. const Instruction *CurrInst = nullptr;
  124. public:
  125. DILocationVerifier() = default;
  126. ~DILocationVerifier() = default;
  127. const Instruction *getCurrentInst() const { return CurrInst; }
  128. void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
  129. void erasingInstr(MachineInstr &MI) override {}
  130. void changingInstr(MachineInstr &MI) override {}
  131. void changedInstr(MachineInstr &MI) override {}
  132. void createdInstr(MachineInstr &MI) override {
  133. assert(getCurrentInst() && "Inserted instruction without a current MI");
  134. // Only print the check message if we're actually checking it.
  135. #ifndef NDEBUG
  136. LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
  137. << " was copied to " << MI);
  138. #endif
  139. // We allow insts in the entry block to have a debug loc line of 0 because
  140. // they could have originated from constants, and we don't want a jumpy
  141. // debug experience.
  142. assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
  143. MI.getDebugLoc().getLine() == 0) &&
  144. "Line info was not transferred to all instructions");
  145. }
  146. };
  147. } // namespace
  148. #endif // ifndef NDEBUG
  149. void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
  150. AU.addRequired<StackProtector>();
  151. AU.addRequired<TargetPassConfig>();
  152. AU.addRequired<GISelCSEAnalysisWrapperPass>();
  153. if (OptLevel != CodeGenOpt::None)
  154. AU.addRequired<BranchProbabilityInfoWrapperPass>();
  155. AU.addRequired<TargetLibraryInfoWrapperPass>();
  156. AU.addPreserved<TargetLibraryInfoWrapperPass>();
  157. getSelectionDAGFallbackAnalysisUsage(AU);
  158. MachineFunctionPass::getAnalysisUsage(AU);
  159. }
  160. IRTranslator::ValueToVRegInfo::VRegListT &
  161. IRTranslator::allocateVRegs(const Value &Val) {
  162. auto VRegsIt = VMap.findVRegs(Val);
  163. if (VRegsIt != VMap.vregs_end())
  164. return *VRegsIt->second;
  165. auto *Regs = VMap.getVRegs(Val);
  166. auto *Offsets = VMap.getOffsets(Val);
  167. SmallVector<LLT, 4> SplitTys;
  168. computeValueLLTs(*DL, *Val.getType(), SplitTys,
  169. Offsets->empty() ? Offsets : nullptr);
  170. for (unsigned i = 0; i < SplitTys.size(); ++i)
  171. Regs->push_back(0);
  172. return *Regs;
  173. }
  174. ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
  175. auto VRegsIt = VMap.findVRegs(Val);
  176. if (VRegsIt != VMap.vregs_end())
  177. return *VRegsIt->second;
  178. if (Val.getType()->isVoidTy())
  179. return *VMap.getVRegs(Val);
  180. // Create entry for this type.
  181. auto *VRegs = VMap.getVRegs(Val);
  182. auto *Offsets = VMap.getOffsets(Val);
  183. assert(Val.getType()->isSized() &&
  184. "Don't know how to create an empty vreg");
  185. SmallVector<LLT, 4> SplitTys;
  186. computeValueLLTs(*DL, *Val.getType(), SplitTys,
  187. Offsets->empty() ? Offsets : nullptr);
  188. if (!isa<Constant>(Val)) {
  189. for (auto Ty : SplitTys)
  190. VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
  191. return *VRegs;
  192. }
  193. if (Val.getType()->isAggregateType()) {
  194. // UndefValue, ConstantAggregateZero
  195. auto &C = cast<Constant>(Val);
  196. unsigned Idx = 0;
  197. while (auto Elt = C.getAggregateElement(Idx++)) {
  198. auto EltRegs = getOrCreateVRegs(*Elt);
  199. llvm::copy(EltRegs, std::back_inserter(*VRegs));
  200. }
  201. } else {
  202. assert(SplitTys.size() == 1 && "unexpectedly split LLT");
  203. VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
  204. bool Success = translate(cast<Constant>(Val), VRegs->front());
  205. if (!Success) {
  206. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  207. MF->getFunction().getSubprogram(),
  208. &MF->getFunction().getEntryBlock());
  209. R << "unable to translate constant: " << ore::NV("Type", Val.getType());
  210. reportTranslationError(*MF, *TPC, *ORE, R);
  211. return *VRegs;
  212. }
  213. }
  214. return *VRegs;
  215. }
  216. int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
  217. auto MapEntry = FrameIndices.find(&AI);
  218. if (MapEntry != FrameIndices.end())
  219. return MapEntry->second;
  220. uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
  221. uint64_t Size =
  222. ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
  223. // Always allocate at least one byte.
  224. Size = std::max<uint64_t>(Size, 1u);
  225. int &FI = FrameIndices[&AI];
  226. FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
  227. return FI;
  228. }
  229. Align IRTranslator::getMemOpAlign(const Instruction &I) {
  230. if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
  231. return SI->getAlign();
  232. if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
  233. return LI->getAlign();
  234. if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
  235. return AI->getAlign();
  236. if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
  237. return AI->getAlign();
  238. OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
  239. R << "unable to translate memop: " << ore::NV("Opcode", &I);
  240. reportTranslationError(*MF, *TPC, *ORE, R);
  241. return Align(1);
  242. }
  243. MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
  244. MachineBasicBlock *&MBB = BBToMBB[&BB];
  245. assert(MBB && "BasicBlock was not encountered before");
  246. return *MBB;
  247. }
  248. void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
  249. assert(NewPred && "new predecessor must be a real MachineBasicBlock");
  250. MachinePreds[Edge].push_back(NewPred);
  251. }
  252. bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
  253. MachineIRBuilder &MIRBuilder) {
  254. // Get or create a virtual register for each value.
  255. // Unless the value is a Constant => loadimm cst?
  256. // or inline constant each time?
  257. // Creation of a virtual register needs to have a size.
  258. Register Op0 = getOrCreateVReg(*U.getOperand(0));
  259. Register Op1 = getOrCreateVReg(*U.getOperand(1));
  260. Register Res = getOrCreateVReg(U);
  261. uint16_t Flags = 0;
  262. if (isa<Instruction>(U)) {
  263. const Instruction &I = cast<Instruction>(U);
  264. Flags = MachineInstr::copyFlagsFromInstruction(I);
  265. }
  266. MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
  267. return true;
  268. }
  269. bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U,
  270. MachineIRBuilder &MIRBuilder) {
  271. Register Op0 = getOrCreateVReg(*U.getOperand(0));
  272. Register Res = getOrCreateVReg(U);
  273. uint16_t Flags = 0;
  274. if (isa<Instruction>(U)) {
  275. const Instruction &I = cast<Instruction>(U);
  276. Flags = MachineInstr::copyFlagsFromInstruction(I);
  277. }
  278. MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
  279. return true;
  280. }
  281. bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
  282. return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
  283. }
  284. bool IRTranslator::translateCompare(const User &U,
  285. MachineIRBuilder &MIRBuilder) {
  286. auto *CI = dyn_cast<CmpInst>(&U);
  287. Register Op0 = getOrCreateVReg(*U.getOperand(0));
  288. Register Op1 = getOrCreateVReg(*U.getOperand(1));
  289. Register Res = getOrCreateVReg(U);
  290. CmpInst::Predicate Pred =
  291. CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
  292. cast<ConstantExpr>(U).getPredicate());
  293. if (CmpInst::isIntPredicate(Pred))
  294. MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
  295. else if (Pred == CmpInst::FCMP_FALSE)
  296. MIRBuilder.buildCopy(
  297. Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
  298. else if (Pred == CmpInst::FCMP_TRUE)
  299. MIRBuilder.buildCopy(
  300. Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
  301. else {
  302. uint16_t Flags = 0;
  303. if (CI)
  304. Flags = MachineInstr::copyFlagsFromInstruction(*CI);
  305. MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags);
  306. }
  307. return true;
  308. }
  309. bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
  310. const ReturnInst &RI = cast<ReturnInst>(U);
  311. const Value *Ret = RI.getReturnValue();
  312. if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
  313. Ret = nullptr;
  314. ArrayRef<Register> VRegs;
  315. if (Ret)
  316. VRegs = getOrCreateVRegs(*Ret);
  317. Register SwiftErrorVReg = 0;
  318. if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
  319. SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
  320. &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
  321. }
  322. // The target may mess up with the insertion point, but
  323. // this is not important as a return is the last instruction
  324. // of the block anyway.
  325. return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
  326. }
  327. void IRTranslator::emitBranchForMergedCondition(
  328. const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
  329. MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
  330. BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
  331. // If the leaf of the tree is a comparison, merge the condition into
  332. // the caseblock.
  333. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  334. CmpInst::Predicate Condition;
  335. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  336. Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  337. } else {
  338. const FCmpInst *FC = cast<FCmpInst>(Cond);
  339. Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  340. }
  341. SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
  342. BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
  343. CurBuilder->getDebugLoc(), TProb, FProb);
  344. SL->SwitchCases.push_back(CB);
  345. return;
  346. }
  347. // Create a CaseBlock record representing this branch.
  348. CmpInst::Predicate Pred = InvertCond ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
  349. SwitchCG::CaseBlock CB(
  350. Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
  351. nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
  352. SL->SwitchCases.push_back(CB);
  353. }
  354. static bool isValInBlock(const Value *V, const BasicBlock *BB) {
  355. if (const Instruction *I = dyn_cast<Instruction>(V))
  356. return I->getParent() == BB;
  357. return true;
  358. }
  359. void IRTranslator::findMergedConditions(
  360. const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
  361. MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
  362. Instruction::BinaryOps Opc, BranchProbability TProb,
  363. BranchProbability FProb, bool InvertCond) {
  364. using namespace PatternMatch;
  365. assert((Opc == Instruction::And || Opc == Instruction::Or) &&
  366. "Expected Opc to be AND/OR");
  367. // Skip over not part of the tree and remember to invert op and operands at
  368. // next level.
  369. Value *NotCond;
  370. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  371. isValInBlock(NotCond, CurBB->getBasicBlock())) {
  372. findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  373. !InvertCond);
  374. return;
  375. }
  376. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  377. const Value *BOpOp0, *BOpOp1;
  378. // Compute the effective opcode for Cond, taking into account whether it needs
  379. // to be inverted, e.g.
  380. // and (not (or A, B)), C
  381. // gets lowered as
  382. // and (and (not A, not B), C)
  383. Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
  384. if (BOp) {
  385. BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
  386. ? Instruction::And
  387. : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
  388. ? Instruction::Or
  389. : (Instruction::BinaryOps)0);
  390. if (InvertCond) {
  391. if (BOpc == Instruction::And)
  392. BOpc = Instruction::Or;
  393. else if (BOpc == Instruction::Or)
  394. BOpc = Instruction::And;
  395. }
  396. }
  397. // If this node is not part of the or/and tree, emit it as a branch.
  398. // Note that all nodes in the tree should have same opcode.
  399. bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
  400. if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
  401. !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
  402. !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
  403. emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
  404. InvertCond);
  405. return;
  406. }
  407. // Create TmpBB after CurBB.
  408. MachineFunction::iterator BBI(CurBB);
  409. MachineBasicBlock *TmpBB =
  410. MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
  411. CurBB->getParent()->insert(++BBI, TmpBB);
  412. if (Opc == Instruction::Or) {
  413. // Codegen X | Y as:
  414. // BB1:
  415. // jmp_if_X TBB
  416. // jmp TmpBB
  417. // TmpBB:
  418. // jmp_if_Y TBB
  419. // jmp FBB
  420. //
  421. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  422. // The requirement is that
  423. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  424. // = TrueProb for original BB.
  425. // Assuming the original probabilities are A and B, one choice is to set
  426. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  427. // A/(1+B) and 2B/(1+B). This choice assumes that
  428. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  429. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  430. // TmpBB, but the math is more complicated.
  431. auto NewTrueProb = TProb / 2;
  432. auto NewFalseProb = TProb / 2 + FProb;
  433. // Emit the LHS condition.
  434. findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
  435. NewFalseProb, InvertCond);
  436. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  437. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  438. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  439. // Emit the RHS condition into TmpBB.
  440. findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  441. Probs[1], InvertCond);
  442. } else {
  443. assert(Opc == Instruction::And && "Unknown merge op!");
  444. // Codegen X & Y as:
  445. // BB1:
  446. // jmp_if_X TmpBB
  447. // jmp FBB
  448. // TmpBB:
  449. // jmp_if_Y TBB
  450. // jmp FBB
  451. //
  452. // This requires creation of TmpBB after CurBB.
  453. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  454. // The requirement is that
  455. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  456. // = FalseProb for original BB.
  457. // Assuming the original probabilities are A and B, one choice is to set
  458. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  459. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  460. // TrueProb for BB1 * FalseProb for TmpBB.
  461. auto NewTrueProb = TProb + FProb / 2;
  462. auto NewFalseProb = FProb / 2;
  463. // Emit the LHS condition.
  464. findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
  465. NewFalseProb, InvertCond);
  466. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  467. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  468. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  469. // Emit the RHS condition into TmpBB.
  470. findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  471. Probs[1], InvertCond);
  472. }
  473. }
  474. bool IRTranslator::shouldEmitAsBranches(
  475. const std::vector<SwitchCG::CaseBlock> &Cases) {
  476. // For multiple cases, it's better to emit as branches.
  477. if (Cases.size() != 2)
  478. return true;
  479. // If this is two comparisons of the same values or'd or and'd together, they
  480. // will get folded into a single comparison, so don't emit two blocks.
  481. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  482. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  483. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  484. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  485. return false;
  486. }
  487. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  488. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  489. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  490. Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
  491. isa<Constant>(Cases[0].CmpRHS) &&
  492. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  493. if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
  494. Cases[0].TrueBB == Cases[1].ThisBB)
  495. return false;
  496. if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
  497. Cases[0].FalseBB == Cases[1].ThisBB)
  498. return false;
  499. }
  500. return true;
  501. }
  502. bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
  503. const BranchInst &BrInst = cast<BranchInst>(U);
  504. auto &CurMBB = MIRBuilder.getMBB();
  505. auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
  506. if (BrInst.isUnconditional()) {
  507. // If the unconditional target is the layout successor, fallthrough.
  508. if (OptLevel == CodeGenOpt::None || !CurMBB.isLayoutSuccessor(Succ0MBB))
  509. MIRBuilder.buildBr(*Succ0MBB);
  510. // Link successors.
  511. for (const BasicBlock *Succ : successors(&BrInst))
  512. CurMBB.addSuccessor(&getMBB(*Succ));
  513. return true;
  514. }
  515. // If this condition is one of the special cases we handle, do special stuff
  516. // now.
  517. const Value *CondVal = BrInst.getCondition();
  518. MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
  519. const auto &TLI = *MF->getSubtarget().getTargetLowering();
  520. // If this is a series of conditions that are or'd or and'd together, emit
  521. // this as a sequence of branches instead of setcc's with and/or operations.
  522. // As long as jumps are not expensive (exceptions for multi-use logic ops,
  523. // unpredictable branches, and vector extracts because those jumps are likely
  524. // expensive for any target), this should improve performance.
  525. // For example, instead of something like:
  526. // cmp A, B
  527. // C = seteq
  528. // cmp D, E
  529. // F = setle
  530. // or C, F
  531. // jnz foo
  532. // Emit:
  533. // cmp A, B
  534. // je foo
  535. // cmp D, E
  536. // jle foo
  537. using namespace PatternMatch;
  538. const Instruction *CondI = dyn_cast<Instruction>(CondVal);
  539. if (!TLI.isJumpExpensive() && CondI && CondI->hasOneUse() &&
  540. !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
  541. Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
  542. Value *Vec;
  543. const Value *BOp0, *BOp1;
  544. if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
  545. Opcode = Instruction::And;
  546. else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
  547. Opcode = Instruction::Or;
  548. if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
  549. match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
  550. findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
  551. getEdgeProbability(&CurMBB, Succ0MBB),
  552. getEdgeProbability(&CurMBB, Succ1MBB),
  553. /*InvertCond=*/false);
  554. assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
  555. // Allow some cases to be rejected.
  556. if (shouldEmitAsBranches(SL->SwitchCases)) {
  557. // Emit the branch for this block.
  558. emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
  559. SL->SwitchCases.erase(SL->SwitchCases.begin());
  560. return true;
  561. }
  562. // Okay, we decided not to do this, remove any inserted MBB's and clear
  563. // SwitchCases.
  564. for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
  565. MF->erase(SL->SwitchCases[I].ThisBB);
  566. SL->SwitchCases.clear();
  567. }
  568. }
  569. // Create a CaseBlock record representing this branch.
  570. SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
  571. ConstantInt::getTrue(MF->getFunction().getContext()),
  572. nullptr, Succ0MBB, Succ1MBB, &CurMBB,
  573. CurBuilder->getDebugLoc());
  574. // Use emitSwitchCase to actually insert the fast branch sequence for this
  575. // cond branch.
  576. emitSwitchCase(CB, &CurMBB, *CurBuilder);
  577. return true;
  578. }
  579. void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
  580. MachineBasicBlock *Dst,
  581. BranchProbability Prob) {
  582. if (!FuncInfo.BPI) {
  583. Src->addSuccessorWithoutProb(Dst);
  584. return;
  585. }
  586. if (Prob.isUnknown())
  587. Prob = getEdgeProbability(Src, Dst);
  588. Src->addSuccessor(Dst, Prob);
  589. }
  590. BranchProbability
  591. IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
  592. const MachineBasicBlock *Dst) const {
  593. const BasicBlock *SrcBB = Src->getBasicBlock();
  594. const BasicBlock *DstBB = Dst->getBasicBlock();
  595. if (!FuncInfo.BPI) {
  596. // If BPI is not available, set the default probability as 1 / N, where N is
  597. // the number of successors.
  598. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  599. return BranchProbability(1, SuccSize);
  600. }
  601. return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
  602. }
  603. bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
  604. using namespace SwitchCG;
  605. // Extract cases from the switch.
  606. const SwitchInst &SI = cast<SwitchInst>(U);
  607. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  608. CaseClusterVector Clusters;
  609. Clusters.reserve(SI.getNumCases());
  610. for (auto &I : SI.cases()) {
  611. MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
  612. assert(Succ && "Could not find successor mbb in mapping");
  613. const ConstantInt *CaseVal = I.getCaseValue();
  614. BranchProbability Prob =
  615. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  616. : BranchProbability(1, SI.getNumCases() + 1);
  617. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  618. }
  619. MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
  620. // Cluster adjacent cases with the same destination. We do this at all
  621. // optimization levels because it's cheap to do and will make codegen faster
  622. // if there are many clusters.
  623. sortAndRangeify(Clusters);
  624. MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
  625. // If there is only the default destination, jump there directly.
  626. if (Clusters.empty()) {
  627. SwitchMBB->addSuccessor(DefaultMBB);
  628. if (DefaultMBB != SwitchMBB->getNextNode())
  629. MIB.buildBr(*DefaultMBB);
  630. return true;
  631. }
  632. SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr);
  633. SL->findBitTestClusters(Clusters, &SI);
  634. LLVM_DEBUG({
  635. dbgs() << "Case clusters: ";
  636. for (const CaseCluster &C : Clusters) {
  637. if (C.Kind == CC_JumpTable)
  638. dbgs() << "JT:";
  639. if (C.Kind == CC_BitTests)
  640. dbgs() << "BT:";
  641. C.Low->getValue().print(dbgs(), true);
  642. if (C.Low != C.High) {
  643. dbgs() << '-';
  644. C.High->getValue().print(dbgs(), true);
  645. }
  646. dbgs() << ' ';
  647. }
  648. dbgs() << '\n';
  649. });
  650. assert(!Clusters.empty());
  651. SwitchWorkList WorkList;
  652. CaseClusterIt First = Clusters.begin();
  653. CaseClusterIt Last = Clusters.end() - 1;
  654. auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
  655. WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  656. // FIXME: At the moment we don't do any splitting optimizations here like
  657. // SelectionDAG does, so this worklist only has one entry.
  658. while (!WorkList.empty()) {
  659. SwitchWorkListItem W = WorkList.pop_back_val();
  660. if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
  661. return false;
  662. }
  663. return true;
  664. }
  665. void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
  666. MachineBasicBlock *MBB) {
  667. // Emit the code for the jump table
  668. assert(JT.Reg != -1U && "Should lower JT Header first!");
  669. MachineIRBuilder MIB(*MBB->getParent());
  670. MIB.setMBB(*MBB);
  671. MIB.setDebugLoc(CurBuilder->getDebugLoc());
  672. Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
  673. const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
  674. auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
  675. MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
  676. }
  677. bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
  678. SwitchCG::JumpTableHeader &JTH,
  679. MachineBasicBlock *HeaderBB) {
  680. MachineIRBuilder MIB(*HeaderBB->getParent());
  681. MIB.setMBB(*HeaderBB);
  682. MIB.setDebugLoc(CurBuilder->getDebugLoc());
  683. const Value &SValue = *JTH.SValue;
  684. // Subtract the lowest switch case value from the value being switched on.
  685. const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
  686. Register SwitchOpReg = getOrCreateVReg(SValue);
  687. auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
  688. auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
  689. // This value may be smaller or larger than the target's pointer type, and
  690. // therefore require extension or truncating.
  691. Type *PtrIRTy = SValue.getType()->getPointerTo();
  692. const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
  693. Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
  694. JT.Reg = Sub.getReg(0);
  695. if (JTH.FallthroughUnreachable) {
  696. if (JT.MBB != HeaderBB->getNextNode())
  697. MIB.buildBr(*JT.MBB);
  698. return true;
  699. }
  700. // Emit the range check for the jump table, and branch to the default block
  701. // for the switch statement if the value being switched on exceeds the
  702. // largest case in the switch.
  703. auto Cst = getOrCreateVReg(
  704. *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
  705. Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
  706. auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
  707. auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
  708. // Avoid emitting unnecessary branches to the next block.
  709. if (JT.MBB != HeaderBB->getNextNode())
  710. BrCond = MIB.buildBr(*JT.MBB);
  711. return true;
  712. }
  713. void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
  714. MachineBasicBlock *SwitchBB,
  715. MachineIRBuilder &MIB) {
  716. Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
  717. Register Cond;
  718. DebugLoc OldDbgLoc = MIB.getDebugLoc();
  719. MIB.setDebugLoc(CB.DbgLoc);
  720. MIB.setMBB(*CB.ThisBB);
  721. if (CB.PredInfo.NoCmp) {
  722. // Branch or fall through to TrueBB.
  723. addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
  724. addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
  725. CB.ThisBB);
  726. CB.ThisBB->normalizeSuccProbs();
  727. if (CB.TrueBB != CB.ThisBB->getNextNode())
  728. MIB.buildBr(*CB.TrueBB);
  729. MIB.setDebugLoc(OldDbgLoc);
  730. return;
  731. }
  732. const LLT i1Ty = LLT::scalar(1);
  733. // Build the compare.
  734. if (!CB.CmpMHS) {
  735. const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
  736. // For conditional branch lowering, we might try to do something silly like
  737. // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
  738. // just re-use the existing condition vreg.
  739. if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI &&
  740. CI->getZExtValue() == 1 && CB.PredInfo.Pred == CmpInst::ICMP_EQ) {
  741. Cond = CondLHS;
  742. } else {
  743. Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
  744. if (CmpInst::isFPPredicate(CB.PredInfo.Pred))
  745. Cond =
  746. MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
  747. else
  748. Cond =
  749. MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
  750. }
  751. } else {
  752. assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
  753. "Can only handle SLE ranges");
  754. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  755. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  756. Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
  757. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  758. Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
  759. Cond =
  760. MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
  761. } else {
  762. const LLT CmpTy = MRI->getType(CmpOpReg);
  763. auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
  764. auto Diff = MIB.buildConstant(CmpTy, High - Low);
  765. Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
  766. }
  767. }
  768. // Update successor info
  769. addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
  770. addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
  771. CB.ThisBB);
  772. // TrueBB and FalseBB are always different unless the incoming IR is
  773. // degenerate. This only happens when running llc on weird IR.
  774. if (CB.TrueBB != CB.FalseBB)
  775. addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
  776. CB.ThisBB->normalizeSuccProbs();
  777. addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
  778. CB.ThisBB);
  779. MIB.buildBrCond(Cond, *CB.TrueBB);
  780. MIB.buildBr(*CB.FalseBB);
  781. MIB.setDebugLoc(OldDbgLoc);
  782. }
  783. bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
  784. MachineBasicBlock *SwitchMBB,
  785. MachineBasicBlock *CurMBB,
  786. MachineBasicBlock *DefaultMBB,
  787. MachineIRBuilder &MIB,
  788. MachineFunction::iterator BBI,
  789. BranchProbability UnhandledProbs,
  790. SwitchCG::CaseClusterIt I,
  791. MachineBasicBlock *Fallthrough,
  792. bool FallthroughUnreachable) {
  793. using namespace SwitchCG;
  794. MachineFunction *CurMF = SwitchMBB->getParent();
  795. // FIXME: Optimize away range check based on pivot comparisons.
  796. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  797. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  798. BranchProbability DefaultProb = W.DefaultProb;
  799. // The jump block hasn't been inserted yet; insert it here.
  800. MachineBasicBlock *JumpMBB = JT->MBB;
  801. CurMF->insert(BBI, JumpMBB);
  802. // Since the jump table block is separate from the switch block, we need
  803. // to keep track of it as a machine predecessor to the default block,
  804. // otherwise we lose the phi edges.
  805. addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
  806. CurMBB);
  807. addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
  808. JumpMBB);
  809. auto JumpProb = I->Prob;
  810. auto FallthroughProb = UnhandledProbs;
  811. // If the default statement is a target of the jump table, we evenly
  812. // distribute the default probability to successors of CurMBB. Also
  813. // update the probability on the edge from JumpMBB to Fallthrough.
  814. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  815. SE = JumpMBB->succ_end();
  816. SI != SE; ++SI) {
  817. if (*SI == DefaultMBB) {
  818. JumpProb += DefaultProb / 2;
  819. FallthroughProb -= DefaultProb / 2;
  820. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  821. JumpMBB->normalizeSuccProbs();
  822. } else {
  823. // Also record edges from the jump table block to it's successors.
  824. addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
  825. JumpMBB);
  826. }
  827. }
  828. if (FallthroughUnreachable)
  829. JTH->FallthroughUnreachable = true;
  830. if (!JTH->FallthroughUnreachable)
  831. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  832. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  833. CurMBB->normalizeSuccProbs();
  834. // The jump table header will be inserted in our current block, do the
  835. // range check, and fall through to our fallthrough block.
  836. JTH->HeaderBB = CurMBB;
  837. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  838. // If we're in the right place, emit the jump table header right now.
  839. if (CurMBB == SwitchMBB) {
  840. if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
  841. return false;
  842. JTH->Emitted = true;
  843. }
  844. return true;
  845. }
  846. bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
  847. Value *Cond,
  848. MachineBasicBlock *Fallthrough,
  849. bool FallthroughUnreachable,
  850. BranchProbability UnhandledProbs,
  851. MachineBasicBlock *CurMBB,
  852. MachineIRBuilder &MIB,
  853. MachineBasicBlock *SwitchMBB) {
  854. using namespace SwitchCG;
  855. const Value *RHS, *LHS, *MHS;
  856. CmpInst::Predicate Pred;
  857. if (I->Low == I->High) {
  858. // Check Cond == I->Low.
  859. Pred = CmpInst::ICMP_EQ;
  860. LHS = Cond;
  861. RHS = I->Low;
  862. MHS = nullptr;
  863. } else {
  864. // Check I->Low <= Cond <= I->High.
  865. Pred = CmpInst::ICMP_SLE;
  866. LHS = I->Low;
  867. MHS = Cond;
  868. RHS = I->High;
  869. }
  870. // If Fallthrough is unreachable, fold away the comparison.
  871. // The false probability is the sum of all unhandled cases.
  872. CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
  873. CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
  874. emitSwitchCase(CB, SwitchMBB, MIB);
  875. return true;
  876. }
  877. void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B,
  878. MachineBasicBlock *SwitchBB) {
  879. MachineIRBuilder &MIB = *CurBuilder;
  880. MIB.setMBB(*SwitchBB);
  881. // Subtract the minimum value.
  882. Register SwitchOpReg = getOrCreateVReg(*B.SValue);
  883. LLT SwitchOpTy = MRI->getType(SwitchOpReg);
  884. Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
  885. auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
  886. Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
  887. const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
  888. LLT MaskTy = SwitchOpTy;
  889. if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
  890. !isPowerOf2_32(MaskTy.getSizeInBits()))
  891. MaskTy = LLT::scalar(PtrTy.getSizeInBits());
  892. else {
  893. // Ensure that the type will fit the mask value.
  894. for (unsigned I = 0, E = B.Cases.size(); I != E; ++I) {
  895. if (!isUIntN(SwitchOpTy.getSizeInBits(), B.Cases[I].Mask)) {
  896. // Switch table case range are encoded into series of masks.
  897. // Just use pointer type, it's guaranteed to fit.
  898. MaskTy = LLT::scalar(PtrTy.getSizeInBits());
  899. break;
  900. }
  901. }
  902. }
  903. Register SubReg = RangeSub.getReg(0);
  904. if (SwitchOpTy != MaskTy)
  905. SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
  906. B.RegVT = getMVTForLLT(MaskTy);
  907. B.Reg = SubReg;
  908. MachineBasicBlock *MBB = B.Cases[0].ThisBB;
  909. if (!B.FallthroughUnreachable)
  910. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  911. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  912. SwitchBB->normalizeSuccProbs();
  913. if (!B.FallthroughUnreachable) {
  914. // Conditional branch to the default block.
  915. auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
  916. auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1),
  917. RangeSub, RangeCst);
  918. MIB.buildBrCond(RangeCmp, *B.Default);
  919. }
  920. // Avoid emitting unnecessary branches to the next block.
  921. if (MBB != SwitchBB->getNextNode())
  922. MIB.buildBr(*MBB);
  923. }
  924. void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB,
  925. MachineBasicBlock *NextMBB,
  926. BranchProbability BranchProbToNext,
  927. Register Reg, SwitchCG::BitTestCase &B,
  928. MachineBasicBlock *SwitchBB) {
  929. MachineIRBuilder &MIB = *CurBuilder;
  930. MIB.setMBB(*SwitchBB);
  931. LLT SwitchTy = getLLTForMVT(BB.RegVT);
  932. Register Cmp;
  933. unsigned PopCount = countPopulation(B.Mask);
  934. if (PopCount == 1) {
  935. // Testing for a single bit; just compare the shift count with what it
  936. // would need to be to shift a 1 bit in that position.
  937. auto MaskTrailingZeros =
  938. MIB.buildConstant(SwitchTy, countTrailingZeros(B.Mask));
  939. Cmp =
  940. MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros)
  941. .getReg(0);
  942. } else if (PopCount == BB.Range) {
  943. // There is only one zero bit in the range, test for it directly.
  944. auto MaskTrailingOnes =
  945. MIB.buildConstant(SwitchTy, countTrailingOnes(B.Mask));
  946. Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes)
  947. .getReg(0);
  948. } else {
  949. // Make desired shift.
  950. auto CstOne = MIB.buildConstant(SwitchTy, 1);
  951. auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
  952. // Emit bit tests and jumps.
  953. auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
  954. auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
  955. auto CstZero = MIB.buildConstant(SwitchTy, 0);
  956. Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero)
  957. .getReg(0);
  958. }
  959. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  960. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  961. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  962. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  963. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  964. // one as they are relative probabilities (and thus work more like weights),
  965. // and hence we need to normalize them to let the sum of them become one.
  966. SwitchBB->normalizeSuccProbs();
  967. // Record the fact that the IR edge from the header to the bit test target
  968. // will go through our new block. Neeeded for PHIs to have nodes added.
  969. addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
  970. SwitchBB);
  971. MIB.buildBrCond(Cmp, *B.TargetBB);
  972. // Avoid emitting unnecessary branches to the next block.
  973. if (NextMBB != SwitchBB->getNextNode())
  974. MIB.buildBr(*NextMBB);
  975. }
  976. bool IRTranslator::lowerBitTestWorkItem(
  977. SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
  978. MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
  979. MachineIRBuilder &MIB, MachineFunction::iterator BBI,
  980. BranchProbability DefaultProb, BranchProbability UnhandledProbs,
  981. SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough,
  982. bool FallthroughUnreachable) {
  983. using namespace SwitchCG;
  984. MachineFunction *CurMF = SwitchMBB->getParent();
  985. // FIXME: Optimize away range check based on pivot comparisons.
  986. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  987. // The bit test blocks haven't been inserted yet; insert them here.
  988. for (BitTestCase &BTC : BTB->Cases)
  989. CurMF->insert(BBI, BTC.ThisBB);
  990. // Fill in fields of the BitTestBlock.
  991. BTB->Parent = CurMBB;
  992. BTB->Default = Fallthrough;
  993. BTB->DefaultProb = UnhandledProbs;
  994. // If the cases in bit test don't form a contiguous range, we evenly
  995. // distribute the probability on the edge to Fallthrough to two
  996. // successors of CurMBB.
  997. if (!BTB->ContiguousRange) {
  998. BTB->Prob += DefaultProb / 2;
  999. BTB->DefaultProb -= DefaultProb / 2;
  1000. }
  1001. if (FallthroughUnreachable)
  1002. BTB->FallthroughUnreachable = true;
  1003. // If we're in the right place, emit the bit test header right now.
  1004. if (CurMBB == SwitchMBB) {
  1005. emitBitTestHeader(*BTB, SwitchMBB);
  1006. BTB->Emitted = true;
  1007. }
  1008. return true;
  1009. }
  1010. bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
  1011. Value *Cond,
  1012. MachineBasicBlock *SwitchMBB,
  1013. MachineBasicBlock *DefaultMBB,
  1014. MachineIRBuilder &MIB) {
  1015. using namespace SwitchCG;
  1016. MachineFunction *CurMF = FuncInfo.MF;
  1017. MachineBasicBlock *NextMBB = nullptr;
  1018. MachineFunction::iterator BBI(W.MBB);
  1019. if (++BBI != FuncInfo.MF->end())
  1020. NextMBB = &*BBI;
  1021. if (EnableOpts) {
  1022. // Here, we order cases by probability so the most likely case will be
  1023. // checked first. However, two clusters can have the same probability in
  1024. // which case their relative ordering is non-deterministic. So we use Low
  1025. // as a tie-breaker as clusters are guaranteed to never overlap.
  1026. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  1027. [](const CaseCluster &a, const CaseCluster &b) {
  1028. return a.Prob != b.Prob
  1029. ? a.Prob > b.Prob
  1030. : a.Low->getValue().slt(b.Low->getValue());
  1031. });
  1032. // Rearrange the case blocks so that the last one falls through if possible
  1033. // without changing the order of probabilities.
  1034. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
  1035. --I;
  1036. if (I->Prob > W.LastCluster->Prob)
  1037. break;
  1038. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  1039. std::swap(*I, *W.LastCluster);
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. // Compute total probability.
  1045. BranchProbability DefaultProb = W.DefaultProb;
  1046. BranchProbability UnhandledProbs = DefaultProb;
  1047. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  1048. UnhandledProbs += I->Prob;
  1049. MachineBasicBlock *CurMBB = W.MBB;
  1050. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  1051. bool FallthroughUnreachable = false;
  1052. MachineBasicBlock *Fallthrough;
  1053. if (I == W.LastCluster) {
  1054. // For the last cluster, fall through to the default destination.
  1055. Fallthrough = DefaultMBB;
  1056. FallthroughUnreachable = isa<UnreachableInst>(
  1057. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  1058. } else {
  1059. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  1060. CurMF->insert(BBI, Fallthrough);
  1061. }
  1062. UnhandledProbs -= I->Prob;
  1063. switch (I->Kind) {
  1064. case CC_BitTests: {
  1065. if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
  1066. DefaultProb, UnhandledProbs, I, Fallthrough,
  1067. FallthroughUnreachable)) {
  1068. LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
  1069. return false;
  1070. }
  1071. break;
  1072. }
  1073. case CC_JumpTable: {
  1074. if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
  1075. UnhandledProbs, I, Fallthrough,
  1076. FallthroughUnreachable)) {
  1077. LLVM_DEBUG(dbgs() << "Failed to lower jump table");
  1078. return false;
  1079. }
  1080. break;
  1081. }
  1082. case CC_Range: {
  1083. if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
  1084. FallthroughUnreachable, UnhandledProbs,
  1085. CurMBB, MIB, SwitchMBB)) {
  1086. LLVM_DEBUG(dbgs() << "Failed to lower switch range");
  1087. return false;
  1088. }
  1089. break;
  1090. }
  1091. }
  1092. CurMBB = Fallthrough;
  1093. }
  1094. return true;
  1095. }
  1096. bool IRTranslator::translateIndirectBr(const User &U,
  1097. MachineIRBuilder &MIRBuilder) {
  1098. const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
  1099. const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
  1100. MIRBuilder.buildBrIndirect(Tgt);
  1101. // Link successors.
  1102. SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
  1103. MachineBasicBlock &CurBB = MIRBuilder.getMBB();
  1104. for (const BasicBlock *Succ : successors(&BrInst)) {
  1105. // It's legal for indirectbr instructions to have duplicate blocks in the
  1106. // destination list. We don't allow this in MIR. Skip anything that's
  1107. // already a successor.
  1108. if (!AddedSuccessors.insert(Succ).second)
  1109. continue;
  1110. CurBB.addSuccessor(&getMBB(*Succ));
  1111. }
  1112. return true;
  1113. }
  1114. static bool isSwiftError(const Value *V) {
  1115. if (auto Arg = dyn_cast<Argument>(V))
  1116. return Arg->hasSwiftErrorAttr();
  1117. if (auto AI = dyn_cast<AllocaInst>(V))
  1118. return AI->isSwiftError();
  1119. return false;
  1120. }
  1121. bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
  1122. const LoadInst &LI = cast<LoadInst>(U);
  1123. if (DL->getTypeStoreSize(LI.getType()) == 0)
  1124. return true;
  1125. ArrayRef<Register> Regs = getOrCreateVRegs(LI);
  1126. ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
  1127. Register Base = getOrCreateVReg(*LI.getPointerOperand());
  1128. Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
  1129. LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
  1130. if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
  1131. assert(Regs.size() == 1 && "swifterror should be single pointer");
  1132. Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
  1133. LI.getPointerOperand());
  1134. MIRBuilder.buildCopy(Regs[0], VReg);
  1135. return true;
  1136. }
  1137. auto &TLI = *MF->getSubtarget().getTargetLowering();
  1138. MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL);
  1139. const MDNode *Ranges =
  1140. Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
  1141. for (unsigned i = 0; i < Regs.size(); ++i) {
  1142. Register Addr;
  1143. MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
  1144. MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
  1145. Align BaseAlign = getMemOpAlign(LI);
  1146. auto MMO = MF->getMachineMemOperand(
  1147. Ptr, Flags, MRI->getType(Regs[i]),
  1148. commonAlignment(BaseAlign, Offsets[i] / 8), LI.getAAMetadata(), Ranges,
  1149. LI.getSyncScopeID(), LI.getOrdering());
  1150. MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
  1151. }
  1152. return true;
  1153. }
  1154. bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
  1155. const StoreInst &SI = cast<StoreInst>(U);
  1156. if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
  1157. return true;
  1158. ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
  1159. ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
  1160. Register Base = getOrCreateVReg(*SI.getPointerOperand());
  1161. Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
  1162. LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
  1163. if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
  1164. assert(Vals.size() == 1 && "swifterror should be single pointer");
  1165. Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
  1166. SI.getPointerOperand());
  1167. MIRBuilder.buildCopy(VReg, Vals[0]);
  1168. return true;
  1169. }
  1170. auto &TLI = *MF->getSubtarget().getTargetLowering();
  1171. MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL);
  1172. for (unsigned i = 0; i < Vals.size(); ++i) {
  1173. Register Addr;
  1174. MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
  1175. MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
  1176. Align BaseAlign = getMemOpAlign(SI);
  1177. auto MMO = MF->getMachineMemOperand(
  1178. Ptr, Flags, MRI->getType(Vals[i]),
  1179. commonAlignment(BaseAlign, Offsets[i] / 8), SI.getAAMetadata(), nullptr,
  1180. SI.getSyncScopeID(), SI.getOrdering());
  1181. MIRBuilder.buildStore(Vals[i], Addr, *MMO);
  1182. }
  1183. return true;
  1184. }
  1185. static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
  1186. const Value *Src = U.getOperand(0);
  1187. Type *Int32Ty = Type::getInt32Ty(U.getContext());
  1188. // getIndexedOffsetInType is designed for GEPs, so the first index is the
  1189. // usual array element rather than looking into the actual aggregate.
  1190. SmallVector<Value *, 1> Indices;
  1191. Indices.push_back(ConstantInt::get(Int32Ty, 0));
  1192. if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
  1193. for (auto Idx : EVI->indices())
  1194. Indices.push_back(ConstantInt::get(Int32Ty, Idx));
  1195. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
  1196. for (auto Idx : IVI->indices())
  1197. Indices.push_back(ConstantInt::get(Int32Ty, Idx));
  1198. } else {
  1199. for (unsigned i = 1; i < U.getNumOperands(); ++i)
  1200. Indices.push_back(U.getOperand(i));
  1201. }
  1202. return 8 * static_cast<uint64_t>(
  1203. DL.getIndexedOffsetInType(Src->getType(), Indices));
  1204. }
  1205. bool IRTranslator::translateExtractValue(const User &U,
  1206. MachineIRBuilder &MIRBuilder) {
  1207. const Value *Src = U.getOperand(0);
  1208. uint64_t Offset = getOffsetFromIndices(U, *DL);
  1209. ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
  1210. ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
  1211. unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
  1212. auto &DstRegs = allocateVRegs(U);
  1213. for (unsigned i = 0; i < DstRegs.size(); ++i)
  1214. DstRegs[i] = SrcRegs[Idx++];
  1215. return true;
  1216. }
  1217. bool IRTranslator::translateInsertValue(const User &U,
  1218. MachineIRBuilder &MIRBuilder) {
  1219. const Value *Src = U.getOperand(0);
  1220. uint64_t Offset = getOffsetFromIndices(U, *DL);
  1221. auto &DstRegs = allocateVRegs(U);
  1222. ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
  1223. ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
  1224. ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
  1225. auto InsertedIt = InsertedRegs.begin();
  1226. for (unsigned i = 0; i < DstRegs.size(); ++i) {
  1227. if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
  1228. DstRegs[i] = *InsertedIt++;
  1229. else
  1230. DstRegs[i] = SrcRegs[i];
  1231. }
  1232. return true;
  1233. }
  1234. bool IRTranslator::translateSelect(const User &U,
  1235. MachineIRBuilder &MIRBuilder) {
  1236. Register Tst = getOrCreateVReg(*U.getOperand(0));
  1237. ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
  1238. ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
  1239. ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
  1240. uint16_t Flags = 0;
  1241. if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
  1242. Flags = MachineInstr::copyFlagsFromInstruction(*SI);
  1243. for (unsigned i = 0; i < ResRegs.size(); ++i) {
  1244. MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
  1245. }
  1246. return true;
  1247. }
  1248. bool IRTranslator::translateCopy(const User &U, const Value &V,
  1249. MachineIRBuilder &MIRBuilder) {
  1250. Register Src = getOrCreateVReg(V);
  1251. auto &Regs = *VMap.getVRegs(U);
  1252. if (Regs.empty()) {
  1253. Regs.push_back(Src);
  1254. VMap.getOffsets(U)->push_back(0);
  1255. } else {
  1256. // If we already assigned a vreg for this instruction, we can't change that.
  1257. // Emit a copy to satisfy the users we already emitted.
  1258. MIRBuilder.buildCopy(Regs[0], Src);
  1259. }
  1260. return true;
  1261. }
  1262. bool IRTranslator::translateBitCast(const User &U,
  1263. MachineIRBuilder &MIRBuilder) {
  1264. // If we're bitcasting to the source type, we can reuse the source vreg.
  1265. if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
  1266. getLLTForType(*U.getType(), *DL))
  1267. return translateCopy(U, *U.getOperand(0), MIRBuilder);
  1268. return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
  1269. }
  1270. bool IRTranslator::translateCast(unsigned Opcode, const User &U,
  1271. MachineIRBuilder &MIRBuilder) {
  1272. Register Op = getOrCreateVReg(*U.getOperand(0));
  1273. Register Res = getOrCreateVReg(U);
  1274. MIRBuilder.buildInstr(Opcode, {Res}, {Op});
  1275. return true;
  1276. }
  1277. bool IRTranslator::translateGetElementPtr(const User &U,
  1278. MachineIRBuilder &MIRBuilder) {
  1279. Value &Op0 = *U.getOperand(0);
  1280. Register BaseReg = getOrCreateVReg(Op0);
  1281. Type *PtrIRTy = Op0.getType();
  1282. LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
  1283. Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
  1284. LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
  1285. // Normalize Vector GEP - all scalar operands should be converted to the
  1286. // splat vector.
  1287. unsigned VectorWidth = 0;
  1288. // True if we should use a splat vector; using VectorWidth alone is not
  1289. // sufficient.
  1290. bool WantSplatVector = false;
  1291. if (auto *VT = dyn_cast<VectorType>(U.getType())) {
  1292. VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
  1293. // We don't produce 1 x N vectors; those are treated as scalars.
  1294. WantSplatVector = VectorWidth > 1;
  1295. }
  1296. // We might need to splat the base pointer into a vector if the offsets
  1297. // are vectors.
  1298. if (WantSplatVector && !PtrTy.isVector()) {
  1299. BaseReg =
  1300. MIRBuilder
  1301. .buildSplatVector(LLT::fixed_vector(VectorWidth, PtrTy), BaseReg)
  1302. .getReg(0);
  1303. PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
  1304. PtrTy = getLLTForType(*PtrIRTy, *DL);
  1305. OffsetIRTy = DL->getIntPtrType(PtrIRTy);
  1306. OffsetTy = getLLTForType(*OffsetIRTy, *DL);
  1307. }
  1308. int64_t Offset = 0;
  1309. for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
  1310. GTI != E; ++GTI) {
  1311. const Value *Idx = GTI.getOperand();
  1312. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  1313. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  1314. Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
  1315. continue;
  1316. } else {
  1317. uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
  1318. // If this is a scalar constant or a splat vector of constants,
  1319. // handle it quickly.
  1320. if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
  1321. Offset += ElementSize * CI->getSExtValue();
  1322. continue;
  1323. }
  1324. if (Offset != 0) {
  1325. auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
  1326. BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
  1327. .getReg(0);
  1328. Offset = 0;
  1329. }
  1330. Register IdxReg = getOrCreateVReg(*Idx);
  1331. LLT IdxTy = MRI->getType(IdxReg);
  1332. if (IdxTy != OffsetTy) {
  1333. if (!IdxTy.isVector() && WantSplatVector) {
  1334. IdxReg = MIRBuilder.buildSplatVector(
  1335. OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0);
  1336. }
  1337. IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
  1338. }
  1339. // N = N + Idx * ElementSize;
  1340. // Avoid doing it for ElementSize of 1.
  1341. Register GepOffsetReg;
  1342. if (ElementSize != 1) {
  1343. auto ElementSizeMIB = MIRBuilder.buildConstant(
  1344. getLLTForType(*OffsetIRTy, *DL), ElementSize);
  1345. GepOffsetReg =
  1346. MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0);
  1347. } else
  1348. GepOffsetReg = IdxReg;
  1349. BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
  1350. }
  1351. }
  1352. if (Offset != 0) {
  1353. auto OffsetMIB =
  1354. MIRBuilder.buildConstant(OffsetTy, Offset);
  1355. MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
  1356. return true;
  1357. }
  1358. MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
  1359. return true;
  1360. }
  1361. bool IRTranslator::translateMemFunc(const CallInst &CI,
  1362. MachineIRBuilder &MIRBuilder,
  1363. unsigned Opcode) {
  1364. // If the source is undef, then just emit a nop.
  1365. if (isa<UndefValue>(CI.getArgOperand(1)))
  1366. return true;
  1367. SmallVector<Register, 3> SrcRegs;
  1368. unsigned MinPtrSize = UINT_MAX;
  1369. for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
  1370. Register SrcReg = getOrCreateVReg(**AI);
  1371. LLT SrcTy = MRI->getType(SrcReg);
  1372. if (SrcTy.isPointer())
  1373. MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
  1374. SrcRegs.push_back(SrcReg);
  1375. }
  1376. LLT SizeTy = LLT::scalar(MinPtrSize);
  1377. // The size operand should be the minimum of the pointer sizes.
  1378. Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
  1379. if (MRI->getType(SizeOpReg) != SizeTy)
  1380. SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
  1381. auto ICall = MIRBuilder.buildInstr(Opcode);
  1382. for (Register SrcReg : SrcRegs)
  1383. ICall.addUse(SrcReg);
  1384. Align DstAlign;
  1385. Align SrcAlign;
  1386. unsigned IsVol =
  1387. cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1))->getZExtValue();
  1388. if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
  1389. DstAlign = MCI->getDestAlign().valueOrOne();
  1390. SrcAlign = MCI->getSourceAlign().valueOrOne();
  1391. } else if (auto *MCI = dyn_cast<MemCpyInlineInst>(&CI)) {
  1392. DstAlign = MCI->getDestAlign().valueOrOne();
  1393. SrcAlign = MCI->getSourceAlign().valueOrOne();
  1394. } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
  1395. DstAlign = MMI->getDestAlign().valueOrOne();
  1396. SrcAlign = MMI->getSourceAlign().valueOrOne();
  1397. } else {
  1398. auto *MSI = cast<MemSetInst>(&CI);
  1399. DstAlign = MSI->getDestAlign().valueOrOne();
  1400. }
  1401. if (Opcode != TargetOpcode::G_MEMCPY_INLINE) {
  1402. // We need to propagate the tail call flag from the IR inst as an argument.
  1403. // Otherwise, we have to pessimize and assume later that we cannot tail call
  1404. // any memory intrinsics.
  1405. ICall.addImm(CI.isTailCall() ? 1 : 0);
  1406. }
  1407. // Create mem operands to store the alignment and volatile info.
  1408. auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  1409. ICall.addMemOperand(MF->getMachineMemOperand(
  1410. MachinePointerInfo(CI.getArgOperand(0)),
  1411. MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
  1412. if (Opcode != TargetOpcode::G_MEMSET)
  1413. ICall.addMemOperand(MF->getMachineMemOperand(
  1414. MachinePointerInfo(CI.getArgOperand(1)),
  1415. MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
  1416. return true;
  1417. }
  1418. void IRTranslator::getStackGuard(Register DstReg,
  1419. MachineIRBuilder &MIRBuilder) {
  1420. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  1421. MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
  1422. auto MIB =
  1423. MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
  1424. auto &TLI = *MF->getSubtarget().getTargetLowering();
  1425. Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
  1426. if (!Global)
  1427. return;
  1428. unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
  1429. LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
  1430. MachinePointerInfo MPInfo(Global);
  1431. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1432. MachineMemOperand::MODereferenceable;
  1433. MachineMemOperand *MemRef = MF->getMachineMemOperand(
  1434. MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
  1435. MIB.setMemRefs({MemRef});
  1436. }
  1437. bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
  1438. MachineIRBuilder &MIRBuilder) {
  1439. ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
  1440. MIRBuilder.buildInstr(
  1441. Op, {ResRegs[0], ResRegs[1]},
  1442. {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
  1443. return true;
  1444. }
  1445. bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
  1446. MachineIRBuilder &MIRBuilder) {
  1447. Register Dst = getOrCreateVReg(CI);
  1448. Register Src0 = getOrCreateVReg(*CI.getOperand(0));
  1449. Register Src1 = getOrCreateVReg(*CI.getOperand(1));
  1450. uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
  1451. MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
  1452. return true;
  1453. }
  1454. unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
  1455. switch (ID) {
  1456. default:
  1457. break;
  1458. case Intrinsic::bswap:
  1459. return TargetOpcode::G_BSWAP;
  1460. case Intrinsic::bitreverse:
  1461. return TargetOpcode::G_BITREVERSE;
  1462. case Intrinsic::fshl:
  1463. return TargetOpcode::G_FSHL;
  1464. case Intrinsic::fshr:
  1465. return TargetOpcode::G_FSHR;
  1466. case Intrinsic::ceil:
  1467. return TargetOpcode::G_FCEIL;
  1468. case Intrinsic::cos:
  1469. return TargetOpcode::G_FCOS;
  1470. case Intrinsic::ctpop:
  1471. return TargetOpcode::G_CTPOP;
  1472. case Intrinsic::exp:
  1473. return TargetOpcode::G_FEXP;
  1474. case Intrinsic::exp2:
  1475. return TargetOpcode::G_FEXP2;
  1476. case Intrinsic::fabs:
  1477. return TargetOpcode::G_FABS;
  1478. case Intrinsic::copysign:
  1479. return TargetOpcode::G_FCOPYSIGN;
  1480. case Intrinsic::minnum:
  1481. return TargetOpcode::G_FMINNUM;
  1482. case Intrinsic::maxnum:
  1483. return TargetOpcode::G_FMAXNUM;
  1484. case Intrinsic::minimum:
  1485. return TargetOpcode::G_FMINIMUM;
  1486. case Intrinsic::maximum:
  1487. return TargetOpcode::G_FMAXIMUM;
  1488. case Intrinsic::canonicalize:
  1489. return TargetOpcode::G_FCANONICALIZE;
  1490. case Intrinsic::floor:
  1491. return TargetOpcode::G_FFLOOR;
  1492. case Intrinsic::fma:
  1493. return TargetOpcode::G_FMA;
  1494. case Intrinsic::log:
  1495. return TargetOpcode::G_FLOG;
  1496. case Intrinsic::log2:
  1497. return TargetOpcode::G_FLOG2;
  1498. case Intrinsic::log10:
  1499. return TargetOpcode::G_FLOG10;
  1500. case Intrinsic::nearbyint:
  1501. return TargetOpcode::G_FNEARBYINT;
  1502. case Intrinsic::pow:
  1503. return TargetOpcode::G_FPOW;
  1504. case Intrinsic::powi:
  1505. return TargetOpcode::G_FPOWI;
  1506. case Intrinsic::rint:
  1507. return TargetOpcode::G_FRINT;
  1508. case Intrinsic::round:
  1509. return TargetOpcode::G_INTRINSIC_ROUND;
  1510. case Intrinsic::roundeven:
  1511. return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
  1512. case Intrinsic::sin:
  1513. return TargetOpcode::G_FSIN;
  1514. case Intrinsic::sqrt:
  1515. return TargetOpcode::G_FSQRT;
  1516. case Intrinsic::trunc:
  1517. return TargetOpcode::G_INTRINSIC_TRUNC;
  1518. case Intrinsic::readcyclecounter:
  1519. return TargetOpcode::G_READCYCLECOUNTER;
  1520. case Intrinsic::ptrmask:
  1521. return TargetOpcode::G_PTRMASK;
  1522. case Intrinsic::lrint:
  1523. return TargetOpcode::G_INTRINSIC_LRINT;
  1524. // FADD/FMUL require checking the FMF, so are handled elsewhere.
  1525. case Intrinsic::vector_reduce_fmin:
  1526. return TargetOpcode::G_VECREDUCE_FMIN;
  1527. case Intrinsic::vector_reduce_fmax:
  1528. return TargetOpcode::G_VECREDUCE_FMAX;
  1529. case Intrinsic::vector_reduce_add:
  1530. return TargetOpcode::G_VECREDUCE_ADD;
  1531. case Intrinsic::vector_reduce_mul:
  1532. return TargetOpcode::G_VECREDUCE_MUL;
  1533. case Intrinsic::vector_reduce_and:
  1534. return TargetOpcode::G_VECREDUCE_AND;
  1535. case Intrinsic::vector_reduce_or:
  1536. return TargetOpcode::G_VECREDUCE_OR;
  1537. case Intrinsic::vector_reduce_xor:
  1538. return TargetOpcode::G_VECREDUCE_XOR;
  1539. case Intrinsic::vector_reduce_smax:
  1540. return TargetOpcode::G_VECREDUCE_SMAX;
  1541. case Intrinsic::vector_reduce_smin:
  1542. return TargetOpcode::G_VECREDUCE_SMIN;
  1543. case Intrinsic::vector_reduce_umax:
  1544. return TargetOpcode::G_VECREDUCE_UMAX;
  1545. case Intrinsic::vector_reduce_umin:
  1546. return TargetOpcode::G_VECREDUCE_UMIN;
  1547. case Intrinsic::lround:
  1548. return TargetOpcode::G_LROUND;
  1549. case Intrinsic::llround:
  1550. return TargetOpcode::G_LLROUND;
  1551. }
  1552. return Intrinsic::not_intrinsic;
  1553. }
  1554. bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
  1555. Intrinsic::ID ID,
  1556. MachineIRBuilder &MIRBuilder) {
  1557. unsigned Op = getSimpleIntrinsicOpcode(ID);
  1558. // Is this a simple intrinsic?
  1559. if (Op == Intrinsic::not_intrinsic)
  1560. return false;
  1561. // Yes. Let's translate it.
  1562. SmallVector<llvm::SrcOp, 4> VRegs;
  1563. for (auto &Arg : CI.args())
  1564. VRegs.push_back(getOrCreateVReg(*Arg));
  1565. MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
  1566. MachineInstr::copyFlagsFromInstruction(CI));
  1567. return true;
  1568. }
  1569. // TODO: Include ConstainedOps.def when all strict instructions are defined.
  1570. static unsigned getConstrainedOpcode(Intrinsic::ID ID) {
  1571. switch (ID) {
  1572. case Intrinsic::experimental_constrained_fadd:
  1573. return TargetOpcode::G_STRICT_FADD;
  1574. case Intrinsic::experimental_constrained_fsub:
  1575. return TargetOpcode::G_STRICT_FSUB;
  1576. case Intrinsic::experimental_constrained_fmul:
  1577. return TargetOpcode::G_STRICT_FMUL;
  1578. case Intrinsic::experimental_constrained_fdiv:
  1579. return TargetOpcode::G_STRICT_FDIV;
  1580. case Intrinsic::experimental_constrained_frem:
  1581. return TargetOpcode::G_STRICT_FREM;
  1582. case Intrinsic::experimental_constrained_fma:
  1583. return TargetOpcode::G_STRICT_FMA;
  1584. case Intrinsic::experimental_constrained_sqrt:
  1585. return TargetOpcode::G_STRICT_FSQRT;
  1586. default:
  1587. return 0;
  1588. }
  1589. }
  1590. bool IRTranslator::translateConstrainedFPIntrinsic(
  1591. const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
  1592. fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
  1593. unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
  1594. if (!Opcode)
  1595. return false;
  1596. unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI);
  1597. if (EB == fp::ExceptionBehavior::ebIgnore)
  1598. Flags |= MachineInstr::NoFPExcept;
  1599. SmallVector<llvm::SrcOp, 4> VRegs;
  1600. VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0)));
  1601. if (!FPI.isUnaryOp())
  1602. VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1)));
  1603. if (FPI.isTernaryOp())
  1604. VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2)));
  1605. MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
  1606. return true;
  1607. }
  1608. bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
  1609. MachineIRBuilder &MIRBuilder) {
  1610. if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
  1611. if (ORE->enabled()) {
  1612. const Function &F = *MI->getParent()->getParent();
  1613. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  1614. if (MemoryOpRemark::canHandle(MI, TLI)) {
  1615. MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, TLI);
  1616. R.visit(MI);
  1617. }
  1618. }
  1619. }
  1620. // If this is a simple intrinsic (that is, we just need to add a def of
  1621. // a vreg, and uses for each arg operand, then translate it.
  1622. if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
  1623. return true;
  1624. switch (ID) {
  1625. default:
  1626. break;
  1627. case Intrinsic::lifetime_start:
  1628. case Intrinsic::lifetime_end: {
  1629. // No stack colouring in O0, discard region information.
  1630. if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
  1631. return true;
  1632. unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
  1633. : TargetOpcode::LIFETIME_END;
  1634. // Get the underlying objects for the location passed on the lifetime
  1635. // marker.
  1636. SmallVector<const Value *, 4> Allocas;
  1637. getUnderlyingObjects(CI.getArgOperand(1), Allocas);
  1638. // Iterate over each underlying object, creating lifetime markers for each
  1639. // static alloca. Quit if we find a non-static alloca.
  1640. for (const Value *V : Allocas) {
  1641. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  1642. if (!AI)
  1643. continue;
  1644. if (!AI->isStaticAlloca())
  1645. return true;
  1646. MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
  1647. }
  1648. return true;
  1649. }
  1650. case Intrinsic::dbg_declare: {
  1651. const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
  1652. assert(DI.getVariable() && "Missing variable");
  1653. const Value *Address = DI.getAddress();
  1654. if (!Address || isa<UndefValue>(Address)) {
  1655. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  1656. return true;
  1657. }
  1658. assert(DI.getVariable()->isValidLocationForIntrinsic(
  1659. MIRBuilder.getDebugLoc()) &&
  1660. "Expected inlined-at fields to agree");
  1661. auto AI = dyn_cast<AllocaInst>(Address);
  1662. if (AI && AI->isStaticAlloca()) {
  1663. // Static allocas are tracked at the MF level, no need for DBG_VALUE
  1664. // instructions (in fact, they get ignored if they *do* exist).
  1665. MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
  1666. getOrCreateFrameIndex(*AI), DI.getDebugLoc());
  1667. } else {
  1668. // A dbg.declare describes the address of a source variable, so lower it
  1669. // into an indirect DBG_VALUE.
  1670. MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
  1671. DI.getVariable(), DI.getExpression());
  1672. }
  1673. return true;
  1674. }
  1675. case Intrinsic::dbg_label: {
  1676. const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
  1677. assert(DI.getLabel() && "Missing label");
  1678. assert(DI.getLabel()->isValidLocationForIntrinsic(
  1679. MIRBuilder.getDebugLoc()) &&
  1680. "Expected inlined-at fields to agree");
  1681. MIRBuilder.buildDbgLabel(DI.getLabel());
  1682. return true;
  1683. }
  1684. case Intrinsic::vaend:
  1685. // No target I know of cares about va_end. Certainly no in-tree target
  1686. // does. Simplest intrinsic ever!
  1687. return true;
  1688. case Intrinsic::vastart: {
  1689. auto &TLI = *MF->getSubtarget().getTargetLowering();
  1690. Value *Ptr = CI.getArgOperand(0);
  1691. unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
  1692. // FIXME: Get alignment
  1693. MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
  1694. .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
  1695. MachineMemOperand::MOStore,
  1696. ListSize, Align(1)));
  1697. return true;
  1698. }
  1699. case Intrinsic::dbg_value: {
  1700. // This form of DBG_VALUE is target-independent.
  1701. const DbgValueInst &DI = cast<DbgValueInst>(CI);
  1702. const Value *V = DI.getValue();
  1703. assert(DI.getVariable()->isValidLocationForIntrinsic(
  1704. MIRBuilder.getDebugLoc()) &&
  1705. "Expected inlined-at fields to agree");
  1706. if (!V || DI.hasArgList()) {
  1707. // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
  1708. // terminate any prior location.
  1709. MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
  1710. } else if (const auto *CI = dyn_cast<Constant>(V)) {
  1711. MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
  1712. } else {
  1713. for (Register Reg : getOrCreateVRegs(*V)) {
  1714. // FIXME: This does not handle register-indirect values at offset 0. The
  1715. // direct/indirect thing shouldn't really be handled by something as
  1716. // implicit as reg+noreg vs reg+imm in the first place, but it seems
  1717. // pretty baked in right now.
  1718. MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
  1719. }
  1720. }
  1721. return true;
  1722. }
  1723. case Intrinsic::uadd_with_overflow:
  1724. return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
  1725. case Intrinsic::sadd_with_overflow:
  1726. return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
  1727. case Intrinsic::usub_with_overflow:
  1728. return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
  1729. case Intrinsic::ssub_with_overflow:
  1730. return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
  1731. case Intrinsic::umul_with_overflow:
  1732. return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
  1733. case Intrinsic::smul_with_overflow:
  1734. return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
  1735. case Intrinsic::uadd_sat:
  1736. return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
  1737. case Intrinsic::sadd_sat:
  1738. return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
  1739. case Intrinsic::usub_sat:
  1740. return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
  1741. case Intrinsic::ssub_sat:
  1742. return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
  1743. case Intrinsic::ushl_sat:
  1744. return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
  1745. case Intrinsic::sshl_sat:
  1746. return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
  1747. case Intrinsic::umin:
  1748. return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
  1749. case Intrinsic::umax:
  1750. return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
  1751. case Intrinsic::smin:
  1752. return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
  1753. case Intrinsic::smax:
  1754. return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
  1755. case Intrinsic::abs:
  1756. // TODO: Preserve "int min is poison" arg in GMIR?
  1757. return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
  1758. case Intrinsic::smul_fix:
  1759. return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
  1760. case Intrinsic::umul_fix:
  1761. return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
  1762. case Intrinsic::smul_fix_sat:
  1763. return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
  1764. case Intrinsic::umul_fix_sat:
  1765. return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
  1766. case Intrinsic::sdiv_fix:
  1767. return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
  1768. case Intrinsic::udiv_fix:
  1769. return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
  1770. case Intrinsic::sdiv_fix_sat:
  1771. return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
  1772. case Intrinsic::udiv_fix_sat:
  1773. return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
  1774. case Intrinsic::fmuladd: {
  1775. const TargetMachine &TM = MF->getTarget();
  1776. const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
  1777. Register Dst = getOrCreateVReg(CI);
  1778. Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
  1779. Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
  1780. Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
  1781. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  1782. TLI.isFMAFasterThanFMulAndFAdd(*MF,
  1783. TLI.getValueType(*DL, CI.getType()))) {
  1784. // TODO: Revisit this to see if we should move this part of the
  1785. // lowering to the combiner.
  1786. MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
  1787. MachineInstr::copyFlagsFromInstruction(CI));
  1788. } else {
  1789. LLT Ty = getLLTForType(*CI.getType(), *DL);
  1790. auto FMul = MIRBuilder.buildFMul(
  1791. Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
  1792. MIRBuilder.buildFAdd(Dst, FMul, Op2,
  1793. MachineInstr::copyFlagsFromInstruction(CI));
  1794. }
  1795. return true;
  1796. }
  1797. case Intrinsic::convert_from_fp16:
  1798. // FIXME: This intrinsic should probably be removed from the IR.
  1799. MIRBuilder.buildFPExt(getOrCreateVReg(CI),
  1800. getOrCreateVReg(*CI.getArgOperand(0)),
  1801. MachineInstr::copyFlagsFromInstruction(CI));
  1802. return true;
  1803. case Intrinsic::convert_to_fp16:
  1804. // FIXME: This intrinsic should probably be removed from the IR.
  1805. MIRBuilder.buildFPTrunc(getOrCreateVReg(CI),
  1806. getOrCreateVReg(*CI.getArgOperand(0)),
  1807. MachineInstr::copyFlagsFromInstruction(CI));
  1808. return true;
  1809. case Intrinsic::memcpy_inline:
  1810. return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
  1811. case Intrinsic::memcpy:
  1812. return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
  1813. case Intrinsic::memmove:
  1814. return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
  1815. case Intrinsic::memset:
  1816. return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
  1817. case Intrinsic::eh_typeid_for: {
  1818. GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
  1819. Register Reg = getOrCreateVReg(CI);
  1820. unsigned TypeID = MF->getTypeIDFor(GV);
  1821. MIRBuilder.buildConstant(Reg, TypeID);
  1822. return true;
  1823. }
  1824. case Intrinsic::objectsize:
  1825. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  1826. case Intrinsic::is_constant:
  1827. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  1828. case Intrinsic::stackguard:
  1829. getStackGuard(getOrCreateVReg(CI), MIRBuilder);
  1830. return true;
  1831. case Intrinsic::stackprotector: {
  1832. LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
  1833. Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
  1834. getStackGuard(GuardVal, MIRBuilder);
  1835. AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
  1836. int FI = getOrCreateFrameIndex(*Slot);
  1837. MF->getFrameInfo().setStackProtectorIndex(FI);
  1838. MIRBuilder.buildStore(
  1839. GuardVal, getOrCreateVReg(*Slot),
  1840. *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
  1841. MachineMemOperand::MOStore |
  1842. MachineMemOperand::MOVolatile,
  1843. PtrTy, Align(8)));
  1844. return true;
  1845. }
  1846. case Intrinsic::stacksave: {
  1847. // Save the stack pointer to the location provided by the intrinsic.
  1848. Register Reg = getOrCreateVReg(CI);
  1849. Register StackPtr = MF->getSubtarget()
  1850. .getTargetLowering()
  1851. ->getStackPointerRegisterToSaveRestore();
  1852. // If the target doesn't specify a stack pointer, then fall back.
  1853. if (!StackPtr)
  1854. return false;
  1855. MIRBuilder.buildCopy(Reg, StackPtr);
  1856. return true;
  1857. }
  1858. case Intrinsic::stackrestore: {
  1859. // Restore the stack pointer from the location provided by the intrinsic.
  1860. Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
  1861. Register StackPtr = MF->getSubtarget()
  1862. .getTargetLowering()
  1863. ->getStackPointerRegisterToSaveRestore();
  1864. // If the target doesn't specify a stack pointer, then fall back.
  1865. if (!StackPtr)
  1866. return false;
  1867. MIRBuilder.buildCopy(StackPtr, Reg);
  1868. return true;
  1869. }
  1870. case Intrinsic::cttz:
  1871. case Intrinsic::ctlz: {
  1872. ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
  1873. bool isTrailing = ID == Intrinsic::cttz;
  1874. unsigned Opcode = isTrailing
  1875. ? Cst->isZero() ? TargetOpcode::G_CTTZ
  1876. : TargetOpcode::G_CTTZ_ZERO_UNDEF
  1877. : Cst->isZero() ? TargetOpcode::G_CTLZ
  1878. : TargetOpcode::G_CTLZ_ZERO_UNDEF;
  1879. MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
  1880. {getOrCreateVReg(*CI.getArgOperand(0))});
  1881. return true;
  1882. }
  1883. case Intrinsic::invariant_start: {
  1884. LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
  1885. Register Undef = MRI->createGenericVirtualRegister(PtrTy);
  1886. MIRBuilder.buildUndef(Undef);
  1887. return true;
  1888. }
  1889. case Intrinsic::invariant_end:
  1890. return true;
  1891. case Intrinsic::expect:
  1892. case Intrinsic::annotation:
  1893. case Intrinsic::ptr_annotation:
  1894. case Intrinsic::launder_invariant_group:
  1895. case Intrinsic::strip_invariant_group: {
  1896. // Drop the intrinsic, but forward the value.
  1897. MIRBuilder.buildCopy(getOrCreateVReg(CI),
  1898. getOrCreateVReg(*CI.getArgOperand(0)));
  1899. return true;
  1900. }
  1901. case Intrinsic::assume:
  1902. case Intrinsic::experimental_noalias_scope_decl:
  1903. case Intrinsic::var_annotation:
  1904. case Intrinsic::sideeffect:
  1905. // Discard annotate attributes, assumptions, and artificial side-effects.
  1906. return true;
  1907. case Intrinsic::read_volatile_register:
  1908. case Intrinsic::read_register: {
  1909. Value *Arg = CI.getArgOperand(0);
  1910. MIRBuilder
  1911. .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
  1912. .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
  1913. return true;
  1914. }
  1915. case Intrinsic::write_register: {
  1916. Value *Arg = CI.getArgOperand(0);
  1917. MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
  1918. .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
  1919. .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
  1920. return true;
  1921. }
  1922. case Intrinsic::localescape: {
  1923. MachineBasicBlock &EntryMBB = MF->front();
  1924. StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
  1925. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  1926. // is the same on all targets.
  1927. for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) {
  1928. Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
  1929. if (isa<ConstantPointerNull>(Arg))
  1930. continue; // Skip null pointers. They represent a hole in index space.
  1931. int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
  1932. MCSymbol *FrameAllocSym =
  1933. MF->getMMI().getContext().getOrCreateFrameAllocSymbol(EscapedName,
  1934. Idx);
  1935. // This should be inserted at the start of the entry block.
  1936. auto LocalEscape =
  1937. MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
  1938. .addSym(FrameAllocSym)
  1939. .addFrameIndex(FI);
  1940. EntryMBB.insert(EntryMBB.begin(), LocalEscape);
  1941. }
  1942. return true;
  1943. }
  1944. case Intrinsic::vector_reduce_fadd:
  1945. case Intrinsic::vector_reduce_fmul: {
  1946. // Need to check for the reassoc flag to decide whether we want a
  1947. // sequential reduction opcode or not.
  1948. Register Dst = getOrCreateVReg(CI);
  1949. Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
  1950. Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
  1951. unsigned Opc = 0;
  1952. if (!CI.hasAllowReassoc()) {
  1953. // The sequential ordering case.
  1954. Opc = ID == Intrinsic::vector_reduce_fadd
  1955. ? TargetOpcode::G_VECREDUCE_SEQ_FADD
  1956. : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
  1957. MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
  1958. MachineInstr::copyFlagsFromInstruction(CI));
  1959. return true;
  1960. }
  1961. // We split the operation into a separate G_FADD/G_FMUL + the reduce,
  1962. // since the associativity doesn't matter.
  1963. unsigned ScalarOpc;
  1964. if (ID == Intrinsic::vector_reduce_fadd) {
  1965. Opc = TargetOpcode::G_VECREDUCE_FADD;
  1966. ScalarOpc = TargetOpcode::G_FADD;
  1967. } else {
  1968. Opc = TargetOpcode::G_VECREDUCE_FMUL;
  1969. ScalarOpc = TargetOpcode::G_FMUL;
  1970. }
  1971. LLT DstTy = MRI->getType(Dst);
  1972. auto Rdx = MIRBuilder.buildInstr(
  1973. Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
  1974. MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
  1975. MachineInstr::copyFlagsFromInstruction(CI));
  1976. return true;
  1977. }
  1978. case Intrinsic::trap:
  1979. case Intrinsic::debugtrap:
  1980. case Intrinsic::ubsantrap: {
  1981. StringRef TrapFuncName =
  1982. CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
  1983. if (TrapFuncName.empty())
  1984. break; // Use the default handling.
  1985. CallLowering::CallLoweringInfo Info;
  1986. if (ID == Intrinsic::ubsantrap) {
  1987. Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
  1988. CI.getArgOperand(0)->getType(), 0});
  1989. }
  1990. Info.Callee = MachineOperand::CreateES(TrapFuncName.data());
  1991. Info.CB = &CI;
  1992. Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
  1993. return CLI->lowerCall(MIRBuilder, Info);
  1994. }
  1995. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  1996. case Intrinsic::INTRINSIC:
  1997. #include "llvm/IR/ConstrainedOps.def"
  1998. return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
  1999. MIRBuilder);
  2000. }
  2001. return false;
  2002. }
  2003. bool IRTranslator::translateInlineAsm(const CallBase &CB,
  2004. MachineIRBuilder &MIRBuilder) {
  2005. const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
  2006. if (!ALI) {
  2007. LLVM_DEBUG(
  2008. dbgs() << "Inline asm lowering is not supported for this target yet\n");
  2009. return false;
  2010. }
  2011. return ALI->lowerInlineAsm(
  2012. MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
  2013. }
  2014. bool IRTranslator::translateCallBase(const CallBase &CB,
  2015. MachineIRBuilder &MIRBuilder) {
  2016. ArrayRef<Register> Res = getOrCreateVRegs(CB);
  2017. SmallVector<ArrayRef<Register>, 8> Args;
  2018. Register SwiftInVReg = 0;
  2019. Register SwiftErrorVReg = 0;
  2020. for (auto &Arg : CB.args()) {
  2021. if (CLI->supportSwiftError() && isSwiftError(Arg)) {
  2022. assert(SwiftInVReg == 0 && "Expected only one swift error argument");
  2023. LLT Ty = getLLTForType(*Arg->getType(), *DL);
  2024. SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
  2025. MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
  2026. &CB, &MIRBuilder.getMBB(), Arg));
  2027. Args.emplace_back(makeArrayRef(SwiftInVReg));
  2028. SwiftErrorVReg =
  2029. SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
  2030. continue;
  2031. }
  2032. Args.push_back(getOrCreateVRegs(*Arg));
  2033. }
  2034. if (auto *CI = dyn_cast<CallInst>(&CB)) {
  2035. if (ORE->enabled()) {
  2036. const Function &F = *CI->getParent()->getParent();
  2037. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  2038. if (MemoryOpRemark::canHandle(CI, TLI)) {
  2039. MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, TLI);
  2040. R.visit(CI);
  2041. }
  2042. }
  2043. }
  2044. // We don't set HasCalls on MFI here yet because call lowering may decide to
  2045. // optimize into tail calls. Instead, we defer that to selection where a final
  2046. // scan is done to check if any instructions are calls.
  2047. bool Success =
  2048. CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg,
  2049. [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
  2050. // Check if we just inserted a tail call.
  2051. if (Success) {
  2052. assert(!HasTailCall && "Can't tail call return twice from block?");
  2053. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  2054. HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
  2055. }
  2056. return Success;
  2057. }
  2058. bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
  2059. const CallInst &CI = cast<CallInst>(U);
  2060. auto TII = MF->getTarget().getIntrinsicInfo();
  2061. const Function *F = CI.getCalledFunction();
  2062. // FIXME: support Windows dllimport function calls.
  2063. if (F && (F->hasDLLImportStorageClass() ||
  2064. (MF->getTarget().getTargetTriple().isOSWindows() &&
  2065. F->hasExternalWeakLinkage())))
  2066. return false;
  2067. // FIXME: support control flow guard targets.
  2068. if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
  2069. return false;
  2070. if (CI.isInlineAsm())
  2071. return translateInlineAsm(CI, MIRBuilder);
  2072. diagnoseDontCall(CI);
  2073. Intrinsic::ID ID = Intrinsic::not_intrinsic;
  2074. if (F && F->isIntrinsic()) {
  2075. ID = F->getIntrinsicID();
  2076. if (TII && ID == Intrinsic::not_intrinsic)
  2077. ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
  2078. }
  2079. if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
  2080. return translateCallBase(CI, MIRBuilder);
  2081. assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
  2082. if (translateKnownIntrinsic(CI, ID, MIRBuilder))
  2083. return true;
  2084. ArrayRef<Register> ResultRegs;
  2085. if (!CI.getType()->isVoidTy())
  2086. ResultRegs = getOrCreateVRegs(CI);
  2087. // Ignore the callsite attributes. Backend code is most likely not expecting
  2088. // an intrinsic to sometimes have side effects and sometimes not.
  2089. MachineInstrBuilder MIB =
  2090. MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
  2091. if (isa<FPMathOperator>(CI))
  2092. MIB->copyIRFlags(CI);
  2093. for (auto &Arg : enumerate(CI.args())) {
  2094. // If this is required to be an immediate, don't materialize it in a
  2095. // register.
  2096. if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
  2097. if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
  2098. // imm arguments are more convenient than cimm (and realistically
  2099. // probably sufficient), so use them.
  2100. assert(CI->getBitWidth() <= 64 &&
  2101. "large intrinsic immediates not handled");
  2102. MIB.addImm(CI->getSExtValue());
  2103. } else {
  2104. MIB.addFPImm(cast<ConstantFP>(Arg.value()));
  2105. }
  2106. } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
  2107. auto *MD = MDVal->getMetadata();
  2108. auto *MDN = dyn_cast<MDNode>(MD);
  2109. if (!MDN) {
  2110. if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
  2111. MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
  2112. else // This was probably an MDString.
  2113. return false;
  2114. }
  2115. MIB.addMetadata(MDN);
  2116. } else {
  2117. ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
  2118. if (VRegs.size() > 1)
  2119. return false;
  2120. MIB.addUse(VRegs[0]);
  2121. }
  2122. }
  2123. // Add a MachineMemOperand if it is a target mem intrinsic.
  2124. const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
  2125. TargetLowering::IntrinsicInfo Info;
  2126. // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
  2127. if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
  2128. Align Alignment = Info.align.getValueOr(
  2129. DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext())));
  2130. LLT MemTy = Info.memVT.isSimple()
  2131. ? getLLTForMVT(Info.memVT.getSimpleVT())
  2132. : LLT::scalar(Info.memVT.getStoreSizeInBits());
  2133. MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
  2134. Info.flags, MemTy, Alignment));
  2135. }
  2136. return true;
  2137. }
  2138. bool IRTranslator::findUnwindDestinations(
  2139. const BasicBlock *EHPadBB,
  2140. BranchProbability Prob,
  2141. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  2142. &UnwindDests) {
  2143. EHPersonality Personality = classifyEHPersonality(
  2144. EHPadBB->getParent()->getFunction().getPersonalityFn());
  2145. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  2146. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  2147. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  2148. bool IsSEH = isAsynchronousEHPersonality(Personality);
  2149. if (IsWasmCXX) {
  2150. // Ignore this for now.
  2151. return false;
  2152. }
  2153. while (EHPadBB) {
  2154. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  2155. BasicBlock *NewEHPadBB = nullptr;
  2156. if (isa<LandingPadInst>(Pad)) {
  2157. // Stop on landingpads. They are not funclets.
  2158. UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
  2159. break;
  2160. }
  2161. if (isa<CleanupPadInst>(Pad)) {
  2162. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  2163. // personalities.
  2164. UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
  2165. UnwindDests.back().first->setIsEHScopeEntry();
  2166. UnwindDests.back().first->setIsEHFuncletEntry();
  2167. break;
  2168. }
  2169. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  2170. // Add the catchpad handlers to the possible destinations.
  2171. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  2172. UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
  2173. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  2174. if (IsMSVCCXX || IsCoreCLR)
  2175. UnwindDests.back().first->setIsEHFuncletEntry();
  2176. if (!IsSEH)
  2177. UnwindDests.back().first->setIsEHScopeEntry();
  2178. }
  2179. NewEHPadBB = CatchSwitch->getUnwindDest();
  2180. } else {
  2181. continue;
  2182. }
  2183. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2184. if (BPI && NewEHPadBB)
  2185. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  2186. EHPadBB = NewEHPadBB;
  2187. }
  2188. return true;
  2189. }
  2190. bool IRTranslator::translateInvoke(const User &U,
  2191. MachineIRBuilder &MIRBuilder) {
  2192. const InvokeInst &I = cast<InvokeInst>(U);
  2193. MCContext &Context = MF->getContext();
  2194. const BasicBlock *ReturnBB = I.getSuccessor(0);
  2195. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2196. const Function *Fn = I.getCalledFunction();
  2197. // FIXME: support invoking patchpoint and statepoint intrinsics.
  2198. if (Fn && Fn->isIntrinsic())
  2199. return false;
  2200. // FIXME: support whatever these are.
  2201. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  2202. return false;
  2203. // FIXME: support control flow guard targets.
  2204. if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
  2205. return false;
  2206. // FIXME: support Windows exception handling.
  2207. if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHI()))
  2208. return false;
  2209. bool LowerInlineAsm = I.isInlineAsm();
  2210. bool NeedEHLabel = true;
  2211. // If it can't throw then use a fast-path without emitting EH labels.
  2212. if (LowerInlineAsm)
  2213. NeedEHLabel = (cast<InlineAsm>(I.getCalledOperand()))->canThrow();
  2214. // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
  2215. // the region covered by the try.
  2216. MCSymbol *BeginSymbol = nullptr;
  2217. if (NeedEHLabel) {
  2218. BeginSymbol = Context.createTempSymbol();
  2219. MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
  2220. }
  2221. if (LowerInlineAsm) {
  2222. if (!translateInlineAsm(I, MIRBuilder))
  2223. return false;
  2224. } else if (!translateCallBase(I, MIRBuilder))
  2225. return false;
  2226. MCSymbol *EndSymbol = nullptr;
  2227. if (NeedEHLabel) {
  2228. EndSymbol = Context.createTempSymbol();
  2229. MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
  2230. }
  2231. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2232. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2233. MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
  2234. BranchProbability EHPadBBProb =
  2235. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2236. : BranchProbability::getZero();
  2237. if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
  2238. return false;
  2239. MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
  2240. &ReturnMBB = getMBB(*ReturnBB);
  2241. // Update successor info.
  2242. addSuccessorWithProb(InvokeMBB, &ReturnMBB);
  2243. for (auto &UnwindDest : UnwindDests) {
  2244. UnwindDest.first->setIsEHPad();
  2245. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2246. }
  2247. InvokeMBB->normalizeSuccProbs();
  2248. if (NeedEHLabel) {
  2249. assert(BeginSymbol && "Expected a begin symbol!");
  2250. assert(EndSymbol && "Expected an end symbol!");
  2251. MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
  2252. }
  2253. MIRBuilder.buildBr(ReturnMBB);
  2254. return true;
  2255. }
  2256. bool IRTranslator::translateCallBr(const User &U,
  2257. MachineIRBuilder &MIRBuilder) {
  2258. // FIXME: Implement this.
  2259. return false;
  2260. }
  2261. bool IRTranslator::translateLandingPad(const User &U,
  2262. MachineIRBuilder &MIRBuilder) {
  2263. const LandingPadInst &LP = cast<LandingPadInst>(U);
  2264. MachineBasicBlock &MBB = MIRBuilder.getMBB();
  2265. MBB.setIsEHPad();
  2266. // If there aren't registers to copy the values into (e.g., during SjLj
  2267. // exceptions), then don't bother.
  2268. auto &TLI = *MF->getSubtarget().getTargetLowering();
  2269. const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
  2270. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2271. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2272. return true;
  2273. // If landingpad's return type is token type, we don't create DAG nodes
  2274. // for its exception pointer and selector value. The extraction of exception
  2275. // pointer or selector value from token type landingpads is not currently
  2276. // supported.
  2277. if (LP.getType()->isTokenTy())
  2278. return true;
  2279. // Add a label to mark the beginning of the landing pad. Deletion of the
  2280. // landing pad can thus be detected via the MachineModuleInfo.
  2281. MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
  2282. .addSym(MF->addLandingPad(&MBB));
  2283. // If the unwinder does not preserve all registers, ensure that the
  2284. // function marks the clobbered registers as used.
  2285. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
  2286. if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
  2287. MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
  2288. LLT Ty = getLLTForType(*LP.getType(), *DL);
  2289. Register Undef = MRI->createGenericVirtualRegister(Ty);
  2290. MIRBuilder.buildUndef(Undef);
  2291. SmallVector<LLT, 2> Tys;
  2292. for (Type *Ty : cast<StructType>(LP.getType())->elements())
  2293. Tys.push_back(getLLTForType(*Ty, *DL));
  2294. assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
  2295. // Mark exception register as live in.
  2296. Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
  2297. if (!ExceptionReg)
  2298. return false;
  2299. MBB.addLiveIn(ExceptionReg);
  2300. ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
  2301. MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
  2302. Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
  2303. if (!SelectorReg)
  2304. return false;
  2305. MBB.addLiveIn(SelectorReg);
  2306. Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
  2307. MIRBuilder.buildCopy(PtrVReg, SelectorReg);
  2308. MIRBuilder.buildCast(ResRegs[1], PtrVReg);
  2309. return true;
  2310. }
  2311. bool IRTranslator::translateAlloca(const User &U,
  2312. MachineIRBuilder &MIRBuilder) {
  2313. auto &AI = cast<AllocaInst>(U);
  2314. if (AI.isSwiftError())
  2315. return true;
  2316. if (AI.isStaticAlloca()) {
  2317. Register Res = getOrCreateVReg(AI);
  2318. int FI = getOrCreateFrameIndex(AI);
  2319. MIRBuilder.buildFrameIndex(Res, FI);
  2320. return true;
  2321. }
  2322. // FIXME: support stack probing for Windows.
  2323. if (MF->getTarget().getTargetTriple().isOSWindows())
  2324. return false;
  2325. // Now we're in the harder dynamic case.
  2326. Register NumElts = getOrCreateVReg(*AI.getArraySize());
  2327. Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
  2328. LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
  2329. if (MRI->getType(NumElts) != IntPtrTy) {
  2330. Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
  2331. MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
  2332. NumElts = ExtElts;
  2333. }
  2334. Type *Ty = AI.getAllocatedType();
  2335. Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
  2336. Register TySize =
  2337. getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
  2338. MIRBuilder.buildMul(AllocSize, NumElts, TySize);
  2339. // Round the size of the allocation up to the stack alignment size
  2340. // by add SA-1 to the size. This doesn't overflow because we're computing
  2341. // an address inside an alloca.
  2342. Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
  2343. auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
  2344. auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
  2345. MachineInstr::NoUWrap);
  2346. auto AlignCst =
  2347. MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
  2348. auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
  2349. Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty));
  2350. if (Alignment <= StackAlign)
  2351. Alignment = Align(1);
  2352. MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
  2353. MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
  2354. assert(MF->getFrameInfo().hasVarSizedObjects());
  2355. return true;
  2356. }
  2357. bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
  2358. // FIXME: We may need more info about the type. Because of how LLT works,
  2359. // we're completely discarding the i64/double distinction here (amongst
  2360. // others). Fortunately the ABIs I know of where that matters don't use va_arg
  2361. // anyway but that's not guaranteed.
  2362. MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
  2363. {getOrCreateVReg(*U.getOperand(0)),
  2364. DL->getABITypeAlign(U.getType()).value()});
  2365. return true;
  2366. }
  2367. bool IRTranslator::translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder) {
  2368. if (!MF->getTarget().Options.TrapUnreachable)
  2369. return true;
  2370. auto &UI = cast<UnreachableInst>(U);
  2371. // We may be able to ignore unreachable behind a noreturn call.
  2372. if (MF->getTarget().Options.NoTrapAfterNoreturn) {
  2373. const BasicBlock &BB = *UI.getParent();
  2374. if (&UI != &BB.front()) {
  2375. BasicBlock::const_iterator PredI =
  2376. std::prev(BasicBlock::const_iterator(UI));
  2377. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2378. if (Call->doesNotReturn())
  2379. return true;
  2380. }
  2381. }
  2382. }
  2383. MIRBuilder.buildIntrinsic(Intrinsic::trap, ArrayRef<Register>(), true);
  2384. return true;
  2385. }
  2386. bool IRTranslator::translateInsertElement(const User &U,
  2387. MachineIRBuilder &MIRBuilder) {
  2388. // If it is a <1 x Ty> vector, use the scalar as it is
  2389. // not a legal vector type in LLT.
  2390. if (cast<FixedVectorType>(U.getType())->getNumElements() == 1)
  2391. return translateCopy(U, *U.getOperand(1), MIRBuilder);
  2392. Register Res = getOrCreateVReg(U);
  2393. Register Val = getOrCreateVReg(*U.getOperand(0));
  2394. Register Elt = getOrCreateVReg(*U.getOperand(1));
  2395. Register Idx = getOrCreateVReg(*U.getOperand(2));
  2396. MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
  2397. return true;
  2398. }
  2399. bool IRTranslator::translateExtractElement(const User &U,
  2400. MachineIRBuilder &MIRBuilder) {
  2401. // If it is a <1 x Ty> vector, use the scalar as it is
  2402. // not a legal vector type in LLT.
  2403. if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1)
  2404. return translateCopy(U, *U.getOperand(0), MIRBuilder);
  2405. Register Res = getOrCreateVReg(U);
  2406. Register Val = getOrCreateVReg(*U.getOperand(0));
  2407. const auto &TLI = *MF->getSubtarget().getTargetLowering();
  2408. unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
  2409. Register Idx;
  2410. if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
  2411. if (CI->getBitWidth() != PreferredVecIdxWidth) {
  2412. APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
  2413. auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
  2414. Idx = getOrCreateVReg(*NewIdxCI);
  2415. }
  2416. }
  2417. if (!Idx)
  2418. Idx = getOrCreateVReg(*U.getOperand(1));
  2419. if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
  2420. const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
  2421. Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0);
  2422. }
  2423. MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
  2424. return true;
  2425. }
  2426. bool IRTranslator::translateShuffleVector(const User &U,
  2427. MachineIRBuilder &MIRBuilder) {
  2428. ArrayRef<int> Mask;
  2429. if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
  2430. Mask = SVI->getShuffleMask();
  2431. else
  2432. Mask = cast<ConstantExpr>(U).getShuffleMask();
  2433. ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
  2434. MIRBuilder
  2435. .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
  2436. {getOrCreateVReg(*U.getOperand(0)),
  2437. getOrCreateVReg(*U.getOperand(1))})
  2438. .addShuffleMask(MaskAlloc);
  2439. return true;
  2440. }
  2441. bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
  2442. const PHINode &PI = cast<PHINode>(U);
  2443. SmallVector<MachineInstr *, 4> Insts;
  2444. for (auto Reg : getOrCreateVRegs(PI)) {
  2445. auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
  2446. Insts.push_back(MIB.getInstr());
  2447. }
  2448. PendingPHIs.emplace_back(&PI, std::move(Insts));
  2449. return true;
  2450. }
  2451. bool IRTranslator::translateAtomicCmpXchg(const User &U,
  2452. MachineIRBuilder &MIRBuilder) {
  2453. const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
  2454. auto &TLI = *MF->getSubtarget().getTargetLowering();
  2455. auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
  2456. auto Res = getOrCreateVRegs(I);
  2457. Register OldValRes = Res[0];
  2458. Register SuccessRes = Res[1];
  2459. Register Addr = getOrCreateVReg(*I.getPointerOperand());
  2460. Register Cmp = getOrCreateVReg(*I.getCompareOperand());
  2461. Register NewVal = getOrCreateVReg(*I.getNewValOperand());
  2462. MIRBuilder.buildAtomicCmpXchgWithSuccess(
  2463. OldValRes, SuccessRes, Addr, Cmp, NewVal,
  2464. *MF->getMachineMemOperand(
  2465. MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
  2466. getMemOpAlign(I), I.getAAMetadata(), nullptr, I.getSyncScopeID(),
  2467. I.getSuccessOrdering(), I.getFailureOrdering()));
  2468. return true;
  2469. }
  2470. bool IRTranslator::translateAtomicRMW(const User &U,
  2471. MachineIRBuilder &MIRBuilder) {
  2472. const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
  2473. auto &TLI = *MF->getSubtarget().getTargetLowering();
  2474. auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
  2475. Register Res = getOrCreateVReg(I);
  2476. Register Addr = getOrCreateVReg(*I.getPointerOperand());
  2477. Register Val = getOrCreateVReg(*I.getValOperand());
  2478. unsigned Opcode = 0;
  2479. switch (I.getOperation()) {
  2480. default:
  2481. return false;
  2482. case AtomicRMWInst::Xchg:
  2483. Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
  2484. break;
  2485. case AtomicRMWInst::Add:
  2486. Opcode = TargetOpcode::G_ATOMICRMW_ADD;
  2487. break;
  2488. case AtomicRMWInst::Sub:
  2489. Opcode = TargetOpcode::G_ATOMICRMW_SUB;
  2490. break;
  2491. case AtomicRMWInst::And:
  2492. Opcode = TargetOpcode::G_ATOMICRMW_AND;
  2493. break;
  2494. case AtomicRMWInst::Nand:
  2495. Opcode = TargetOpcode::G_ATOMICRMW_NAND;
  2496. break;
  2497. case AtomicRMWInst::Or:
  2498. Opcode = TargetOpcode::G_ATOMICRMW_OR;
  2499. break;
  2500. case AtomicRMWInst::Xor:
  2501. Opcode = TargetOpcode::G_ATOMICRMW_XOR;
  2502. break;
  2503. case AtomicRMWInst::Max:
  2504. Opcode = TargetOpcode::G_ATOMICRMW_MAX;
  2505. break;
  2506. case AtomicRMWInst::Min:
  2507. Opcode = TargetOpcode::G_ATOMICRMW_MIN;
  2508. break;
  2509. case AtomicRMWInst::UMax:
  2510. Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
  2511. break;
  2512. case AtomicRMWInst::UMin:
  2513. Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
  2514. break;
  2515. case AtomicRMWInst::FAdd:
  2516. Opcode = TargetOpcode::G_ATOMICRMW_FADD;
  2517. break;
  2518. case AtomicRMWInst::FSub:
  2519. Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
  2520. break;
  2521. }
  2522. MIRBuilder.buildAtomicRMW(
  2523. Opcode, Res, Addr, Val,
  2524. *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  2525. Flags, MRI->getType(Val), getMemOpAlign(I),
  2526. I.getAAMetadata(), nullptr, I.getSyncScopeID(),
  2527. I.getOrdering()));
  2528. return true;
  2529. }
  2530. bool IRTranslator::translateFence(const User &U,
  2531. MachineIRBuilder &MIRBuilder) {
  2532. const FenceInst &Fence = cast<FenceInst>(U);
  2533. MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
  2534. Fence.getSyncScopeID());
  2535. return true;
  2536. }
  2537. bool IRTranslator::translateFreeze(const User &U,
  2538. MachineIRBuilder &MIRBuilder) {
  2539. const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
  2540. const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
  2541. assert(DstRegs.size() == SrcRegs.size() &&
  2542. "Freeze with different source and destination type?");
  2543. for (unsigned I = 0; I < DstRegs.size(); ++I) {
  2544. MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
  2545. }
  2546. return true;
  2547. }
  2548. void IRTranslator::finishPendingPhis() {
  2549. #ifndef NDEBUG
  2550. DILocationVerifier Verifier;
  2551. GISelObserverWrapper WrapperObserver(&Verifier);
  2552. RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
  2553. #endif // ifndef NDEBUG
  2554. for (auto &Phi : PendingPHIs) {
  2555. const PHINode *PI = Phi.first;
  2556. ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
  2557. MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
  2558. EntryBuilder->setDebugLoc(PI->getDebugLoc());
  2559. #ifndef NDEBUG
  2560. Verifier.setCurrentInst(PI);
  2561. #endif // ifndef NDEBUG
  2562. SmallSet<const MachineBasicBlock *, 16> SeenPreds;
  2563. for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
  2564. auto IRPred = PI->getIncomingBlock(i);
  2565. ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
  2566. for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
  2567. if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
  2568. continue;
  2569. SeenPreds.insert(Pred);
  2570. for (unsigned j = 0; j < ValRegs.size(); ++j) {
  2571. MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
  2572. MIB.addUse(ValRegs[j]);
  2573. MIB.addMBB(Pred);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. }
  2579. bool IRTranslator::valueIsSplit(const Value &V,
  2580. SmallVectorImpl<uint64_t> *Offsets) {
  2581. SmallVector<LLT, 4> SplitTys;
  2582. if (Offsets && !Offsets->empty())
  2583. Offsets->clear();
  2584. computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
  2585. return SplitTys.size() > 1;
  2586. }
  2587. bool IRTranslator::translate(const Instruction &Inst) {
  2588. CurBuilder->setDebugLoc(Inst.getDebugLoc());
  2589. auto &TLI = *MF->getSubtarget().getTargetLowering();
  2590. if (TLI.fallBackToDAGISel(Inst))
  2591. return false;
  2592. switch (Inst.getOpcode()) {
  2593. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  2594. case Instruction::OPCODE: \
  2595. return translate##OPCODE(Inst, *CurBuilder.get());
  2596. #include "llvm/IR/Instruction.def"
  2597. default:
  2598. return false;
  2599. }
  2600. }
  2601. bool IRTranslator::translate(const Constant &C, Register Reg) {
  2602. // We only emit constants into the entry block from here. To prevent jumpy
  2603. // debug behaviour set the line to 0.
  2604. if (auto CurrInstDL = CurBuilder->getDL())
  2605. EntryBuilder->setDebugLoc(DILocation::get(C.getContext(), 0, 0,
  2606. CurrInstDL.getScope(),
  2607. CurrInstDL.getInlinedAt()));
  2608. if (auto CI = dyn_cast<ConstantInt>(&C))
  2609. EntryBuilder->buildConstant(Reg, *CI);
  2610. else if (auto CF = dyn_cast<ConstantFP>(&C))
  2611. EntryBuilder->buildFConstant(Reg, *CF);
  2612. else if (isa<UndefValue>(C))
  2613. EntryBuilder->buildUndef(Reg);
  2614. else if (isa<ConstantPointerNull>(C))
  2615. EntryBuilder->buildConstant(Reg, 0);
  2616. else if (auto GV = dyn_cast<GlobalValue>(&C))
  2617. EntryBuilder->buildGlobalValue(Reg, GV);
  2618. else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
  2619. if (!isa<FixedVectorType>(CAZ->getType()))
  2620. return false;
  2621. // Return the scalar if it is a <1 x Ty> vector.
  2622. unsigned NumElts = CAZ->getElementCount().getFixedValue();
  2623. if (NumElts == 1)
  2624. return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get());
  2625. SmallVector<Register, 4> Ops;
  2626. for (unsigned I = 0; I < NumElts; ++I) {
  2627. Constant &Elt = *CAZ->getElementValue(I);
  2628. Ops.push_back(getOrCreateVReg(Elt));
  2629. }
  2630. EntryBuilder->buildBuildVector(Reg, Ops);
  2631. } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
  2632. // Return the scalar if it is a <1 x Ty> vector.
  2633. if (CV->getNumElements() == 1)
  2634. return translateCopy(C, *CV->getElementAsConstant(0),
  2635. *EntryBuilder.get());
  2636. SmallVector<Register, 4> Ops;
  2637. for (unsigned i = 0; i < CV->getNumElements(); ++i) {
  2638. Constant &Elt = *CV->getElementAsConstant(i);
  2639. Ops.push_back(getOrCreateVReg(Elt));
  2640. }
  2641. EntryBuilder->buildBuildVector(Reg, Ops);
  2642. } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
  2643. switch(CE->getOpcode()) {
  2644. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  2645. case Instruction::OPCODE: \
  2646. return translate##OPCODE(*CE, *EntryBuilder.get());
  2647. #include "llvm/IR/Instruction.def"
  2648. default:
  2649. return false;
  2650. }
  2651. } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
  2652. if (CV->getNumOperands() == 1)
  2653. return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get());
  2654. SmallVector<Register, 4> Ops;
  2655. for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
  2656. Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
  2657. }
  2658. EntryBuilder->buildBuildVector(Reg, Ops);
  2659. } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
  2660. EntryBuilder->buildBlockAddress(Reg, BA);
  2661. } else
  2662. return false;
  2663. return true;
  2664. }
  2665. bool IRTranslator::finalizeBasicBlock(const BasicBlock &BB,
  2666. MachineBasicBlock &MBB) {
  2667. for (auto &BTB : SL->BitTestCases) {
  2668. // Emit header first, if it wasn't already emitted.
  2669. if (!BTB.Emitted)
  2670. emitBitTestHeader(BTB, BTB.Parent);
  2671. BranchProbability UnhandledProb = BTB.Prob;
  2672. for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
  2673. UnhandledProb -= BTB.Cases[j].ExtraProb;
  2674. // Set the current basic block to the mbb we wish to insert the code into
  2675. MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
  2676. // If all cases cover a contiguous range, it is not necessary to jump to
  2677. // the default block after the last bit test fails. This is because the
  2678. // range check during bit test header creation has guaranteed that every
  2679. // case here doesn't go outside the range. In this case, there is no need
  2680. // to perform the last bit test, as it will always be true. Instead, make
  2681. // the second-to-last bit-test fall through to the target of the last bit
  2682. // test, and delete the last bit test.
  2683. MachineBasicBlock *NextMBB;
  2684. if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
  2685. // Second-to-last bit-test with contiguous range: fall through to the
  2686. // target of the final bit test.
  2687. NextMBB = BTB.Cases[j + 1].TargetBB;
  2688. } else if (j + 1 == ej) {
  2689. // For the last bit test, fall through to Default.
  2690. NextMBB = BTB.Default;
  2691. } else {
  2692. // Otherwise, fall through to the next bit test.
  2693. NextMBB = BTB.Cases[j + 1].ThisBB;
  2694. }
  2695. emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
  2696. if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
  2697. // We need to record the replacement phi edge here that normally
  2698. // happens in emitBitTestCase before we delete the case, otherwise the
  2699. // phi edge will be lost.
  2700. addMachineCFGPred({BTB.Parent->getBasicBlock(),
  2701. BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
  2702. MBB);
  2703. // Since we're not going to use the final bit test, remove it.
  2704. BTB.Cases.pop_back();
  2705. break;
  2706. }
  2707. }
  2708. // This is "default" BB. We have two jumps to it. From "header" BB and from
  2709. // last "case" BB, unless the latter was skipped.
  2710. CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
  2711. BTB.Default->getBasicBlock()};
  2712. addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
  2713. if (!BTB.ContiguousRange) {
  2714. addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
  2715. }
  2716. }
  2717. SL->BitTestCases.clear();
  2718. for (auto &JTCase : SL->JTCases) {
  2719. // Emit header first, if it wasn't already emitted.
  2720. if (!JTCase.first.Emitted)
  2721. emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
  2722. emitJumpTable(JTCase.second, JTCase.second.MBB);
  2723. }
  2724. SL->JTCases.clear();
  2725. for (auto &SwCase : SL->SwitchCases)
  2726. emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
  2727. SL->SwitchCases.clear();
  2728. // Check if we need to generate stack-protector guard checks.
  2729. StackProtector &SP = getAnalysis<StackProtector>();
  2730. if (SP.shouldEmitSDCheck(BB)) {
  2731. const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
  2732. bool FunctionBasedInstrumentation =
  2733. TLI.getSSPStackGuardCheck(*MF->getFunction().getParent());
  2734. SPDescriptor.initialize(&BB, &MBB, FunctionBasedInstrumentation);
  2735. }
  2736. // Handle stack protector.
  2737. if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
  2738. LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n");
  2739. return false;
  2740. } else if (SPDescriptor.shouldEmitStackProtector()) {
  2741. MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB();
  2742. MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB();
  2743. // Find the split point to split the parent mbb. At the same time copy all
  2744. // physical registers used in the tail of parent mbb into virtual registers
  2745. // before the split point and back into physical registers after the split
  2746. // point. This prevents us needing to deal with Live-ins and many other
  2747. // register allocation issues caused by us splitting the parent mbb. The
  2748. // register allocator will clean up said virtual copies later on.
  2749. MachineBasicBlock::iterator SplitPoint = findSplitPointForStackProtector(
  2750. ParentMBB, *MF->getSubtarget().getInstrInfo());
  2751. // Splice the terminator of ParentMBB into SuccessMBB.
  2752. SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
  2753. ParentMBB->end());
  2754. // Add compare/jump on neq/jump to the parent BB.
  2755. if (!emitSPDescriptorParent(SPDescriptor, ParentMBB))
  2756. return false;
  2757. // CodeGen Failure MBB if we have not codegened it yet.
  2758. MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB();
  2759. if (FailureMBB->empty()) {
  2760. if (!emitSPDescriptorFailure(SPDescriptor, FailureMBB))
  2761. return false;
  2762. }
  2763. // Clear the Per-BB State.
  2764. SPDescriptor.resetPerBBState();
  2765. }
  2766. return true;
  2767. }
  2768. bool IRTranslator::emitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2769. MachineBasicBlock *ParentBB) {
  2770. CurBuilder->setInsertPt(*ParentBB, ParentBB->end());
  2771. // First create the loads to the guard/stack slot for the comparison.
  2772. const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
  2773. Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
  2774. const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
  2775. LLT PtrMemTy = getLLTForMVT(TLI.getPointerMemTy(*DL));
  2776. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2777. int FI = MFI.getStackProtectorIndex();
  2778. Register Guard;
  2779. Register StackSlotPtr = CurBuilder->buildFrameIndex(PtrTy, FI).getReg(0);
  2780. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2781. Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
  2782. // Generate code to load the content of the guard slot.
  2783. Register GuardVal =
  2784. CurBuilder
  2785. ->buildLoad(PtrMemTy, StackSlotPtr,
  2786. MachinePointerInfo::getFixedStack(*MF, FI), Align,
  2787. MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile)
  2788. .getReg(0);
  2789. if (TLI.useStackGuardXorFP()) {
  2790. LLVM_DEBUG(dbgs() << "Stack protector xor'ing with FP not yet implemented");
  2791. return false;
  2792. }
  2793. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2794. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2795. // This path is currently untestable on GlobalISel, since the only platform
  2796. // that needs this seems to be Windows, and we fall back on that currently.
  2797. // The code still lives here in case that changes.
  2798. // Silence warning about unused variable until the code below that uses
  2799. // 'GuardCheckFn' is enabled.
  2800. (void)GuardCheckFn;
  2801. return false;
  2802. #if 0
  2803. // The target provides a guard check function to validate the guard value.
  2804. // Generate a call to that function with the content of the guard slot as
  2805. // argument.
  2806. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2807. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2808. ISD::ArgFlagsTy Flags;
  2809. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2810. Flags.setInReg();
  2811. CallLowering::ArgInfo GuardArgInfo(
  2812. {GuardVal, FnTy->getParamType(0), {Flags}});
  2813. CallLowering::CallLoweringInfo Info;
  2814. Info.OrigArgs.push_back(GuardArgInfo);
  2815. Info.CallConv = GuardCheckFn->getCallingConv();
  2816. Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0);
  2817. Info.OrigRet = {Register(), FnTy->getReturnType()};
  2818. if (!CLI->lowerCall(MIRBuilder, Info)) {
  2819. LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n");
  2820. return false;
  2821. }
  2822. return true;
  2823. #endif
  2824. }
  2825. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2826. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2827. if (TLI.useLoadStackGuardNode()) {
  2828. Guard =
  2829. MRI->createGenericVirtualRegister(LLT::scalar(PtrTy.getSizeInBits()));
  2830. getStackGuard(Guard, *CurBuilder);
  2831. } else {
  2832. // TODO: test using android subtarget when we support @llvm.thread.pointer.
  2833. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2834. Register GuardPtr = getOrCreateVReg(*IRGuard);
  2835. Guard = CurBuilder
  2836. ->buildLoad(PtrMemTy, GuardPtr,
  2837. MachinePointerInfo::getFixedStack(*MF, FI), Align,
  2838. MachineMemOperand::MOLoad |
  2839. MachineMemOperand::MOVolatile)
  2840. .getReg(0);
  2841. }
  2842. // Perform the comparison.
  2843. auto Cmp =
  2844. CurBuilder->buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Guard, GuardVal);
  2845. // If the guard/stackslot do not equal, branch to failure MBB.
  2846. CurBuilder->buildBrCond(Cmp, *SPD.getFailureMBB());
  2847. // Otherwise branch to success MBB.
  2848. CurBuilder->buildBr(*SPD.getSuccessMBB());
  2849. return true;
  2850. }
  2851. bool IRTranslator::emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
  2852. MachineBasicBlock *FailureBB) {
  2853. CurBuilder->setInsertPt(*FailureBB, FailureBB->end());
  2854. const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
  2855. const RTLIB::Libcall Libcall = RTLIB::STACKPROTECTOR_CHECK_FAIL;
  2856. const char *Name = TLI.getLibcallName(Libcall);
  2857. CallLowering::CallLoweringInfo Info;
  2858. Info.CallConv = TLI.getLibcallCallingConv(Libcall);
  2859. Info.Callee = MachineOperand::CreateES(Name);
  2860. Info.OrigRet = {Register(), Type::getVoidTy(MF->getFunction().getContext()),
  2861. 0};
  2862. if (!CLI->lowerCall(*CurBuilder, Info)) {
  2863. LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n");
  2864. return false;
  2865. }
  2866. // On PS4, the "return address" must still be within the calling function,
  2867. // even if it's at the very end, so emit an explicit TRAP here.
  2868. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2869. // WebAssembly needs an unreachable instruction after a non-returning call,
  2870. // because the function return type can be different from __stack_chk_fail's
  2871. // return type (void).
  2872. const TargetMachine &TM = MF->getTarget();
  2873. if (TM.getTargetTriple().isPS4CPU() || TM.getTargetTriple().isWasm()) {
  2874. LLVM_DEBUG(dbgs() << "Unhandled trap emission for stack protector fail\n");
  2875. return false;
  2876. }
  2877. return true;
  2878. }
  2879. void IRTranslator::finalizeFunction() {
  2880. // Release the memory used by the different maps we
  2881. // needed during the translation.
  2882. PendingPHIs.clear();
  2883. VMap.reset();
  2884. FrameIndices.clear();
  2885. MachinePreds.clear();
  2886. // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
  2887. // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
  2888. // destroying it twice (in ~IRTranslator() and ~LLVMContext())
  2889. EntryBuilder.reset();
  2890. CurBuilder.reset();
  2891. FuncInfo.clear();
  2892. SPDescriptor.resetPerFunctionState();
  2893. }
  2894. /// Returns true if a BasicBlock \p BB within a variadic function contains a
  2895. /// variadic musttail call.
  2896. static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
  2897. if (!IsVarArg)
  2898. return false;
  2899. // Walk the block backwards, because tail calls usually only appear at the end
  2900. // of a block.
  2901. return llvm::any_of(llvm::reverse(BB), [](const Instruction &I) {
  2902. const auto *CI = dyn_cast<CallInst>(&I);
  2903. return CI && CI->isMustTailCall();
  2904. });
  2905. }
  2906. bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
  2907. MF = &CurMF;
  2908. const Function &F = MF->getFunction();
  2909. GISelCSEAnalysisWrapper &Wrapper =
  2910. getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
  2911. // Set the CSEConfig and run the analysis.
  2912. GISelCSEInfo *CSEInfo = nullptr;
  2913. TPC = &getAnalysis<TargetPassConfig>();
  2914. bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
  2915. ? EnableCSEInIRTranslator
  2916. : TPC->isGISelCSEEnabled();
  2917. if (EnableCSE) {
  2918. EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
  2919. CSEInfo = &Wrapper.get(TPC->getCSEConfig());
  2920. EntryBuilder->setCSEInfo(CSEInfo);
  2921. CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
  2922. CurBuilder->setCSEInfo(CSEInfo);
  2923. } else {
  2924. EntryBuilder = std::make_unique<MachineIRBuilder>();
  2925. CurBuilder = std::make_unique<MachineIRBuilder>();
  2926. }
  2927. CLI = MF->getSubtarget().getCallLowering();
  2928. CurBuilder->setMF(*MF);
  2929. EntryBuilder->setMF(*MF);
  2930. MRI = &MF->getRegInfo();
  2931. DL = &F.getParent()->getDataLayout();
  2932. ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
  2933. const TargetMachine &TM = MF->getTarget();
  2934. TM.resetTargetOptions(F);
  2935. EnableOpts = OptLevel != CodeGenOpt::None && !skipFunction(F);
  2936. FuncInfo.MF = MF;
  2937. if (EnableOpts)
  2938. FuncInfo.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
  2939. else
  2940. FuncInfo.BPI = nullptr;
  2941. FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
  2942. const auto &TLI = *MF->getSubtarget().getTargetLowering();
  2943. SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
  2944. SL->init(TLI, TM, *DL);
  2945. assert(PendingPHIs.empty() && "stale PHIs");
  2946. // Targets which want to use big endian can enable it using
  2947. // enableBigEndian()
  2948. if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
  2949. // Currently we don't properly handle big endian code.
  2950. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  2951. F.getSubprogram(), &F.getEntryBlock());
  2952. R << "unable to translate in big endian mode";
  2953. reportTranslationError(*MF, *TPC, *ORE, R);
  2954. }
  2955. // Release the per-function state when we return, whether we succeeded or not.
  2956. auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
  2957. // Setup a separate basic-block for the arguments and constants
  2958. MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
  2959. MF->push_back(EntryBB);
  2960. EntryBuilder->setMBB(*EntryBB);
  2961. DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
  2962. SwiftError.setFunction(CurMF);
  2963. SwiftError.createEntriesInEntryBlock(DbgLoc);
  2964. bool IsVarArg = F.isVarArg();
  2965. bool HasMustTailInVarArgFn = false;
  2966. // Create all blocks, in IR order, to preserve the layout.
  2967. for (const BasicBlock &BB: F) {
  2968. auto *&MBB = BBToMBB[&BB];
  2969. MBB = MF->CreateMachineBasicBlock(&BB);
  2970. MF->push_back(MBB);
  2971. if (BB.hasAddressTaken())
  2972. MBB->setHasAddressTaken();
  2973. if (!HasMustTailInVarArgFn)
  2974. HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
  2975. }
  2976. MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
  2977. // Make our arguments/constants entry block fallthrough to the IR entry block.
  2978. EntryBB->addSuccessor(&getMBB(F.front()));
  2979. if (CLI->fallBackToDAGISel(*MF)) {
  2980. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  2981. F.getSubprogram(), &F.getEntryBlock());
  2982. R << "unable to lower function: " << ore::NV("Prototype", F.getType());
  2983. reportTranslationError(*MF, *TPC, *ORE, R);
  2984. return false;
  2985. }
  2986. // Lower the actual args into this basic block.
  2987. SmallVector<ArrayRef<Register>, 8> VRegArgs;
  2988. for (const Argument &Arg: F.args()) {
  2989. if (DL->getTypeStoreSize(Arg.getType()).isZero())
  2990. continue; // Don't handle zero sized types.
  2991. ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
  2992. VRegArgs.push_back(VRegs);
  2993. if (Arg.hasSwiftErrorAttr()) {
  2994. assert(VRegs.size() == 1 && "Too many vregs for Swift error");
  2995. SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
  2996. }
  2997. }
  2998. if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs, FuncInfo)) {
  2999. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  3000. F.getSubprogram(), &F.getEntryBlock());
  3001. R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
  3002. reportTranslationError(*MF, *TPC, *ORE, R);
  3003. return false;
  3004. }
  3005. // Need to visit defs before uses when translating instructions.
  3006. GISelObserverWrapper WrapperObserver;
  3007. if (EnableCSE && CSEInfo)
  3008. WrapperObserver.addObserver(CSEInfo);
  3009. {
  3010. ReversePostOrderTraversal<const Function *> RPOT(&F);
  3011. #ifndef NDEBUG
  3012. DILocationVerifier Verifier;
  3013. WrapperObserver.addObserver(&Verifier);
  3014. #endif // ifndef NDEBUG
  3015. RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
  3016. RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver);
  3017. for (const BasicBlock *BB : RPOT) {
  3018. MachineBasicBlock &MBB = getMBB(*BB);
  3019. // Set the insertion point of all the following translations to
  3020. // the end of this basic block.
  3021. CurBuilder->setMBB(MBB);
  3022. HasTailCall = false;
  3023. for (const Instruction &Inst : *BB) {
  3024. // If we translated a tail call in the last step, then we know
  3025. // everything after the call is either a return, or something that is
  3026. // handled by the call itself. (E.g. a lifetime marker or assume
  3027. // intrinsic.) In this case, we should stop translating the block and
  3028. // move on.
  3029. if (HasTailCall)
  3030. break;
  3031. #ifndef NDEBUG
  3032. Verifier.setCurrentInst(&Inst);
  3033. #endif // ifndef NDEBUG
  3034. if (translate(Inst))
  3035. continue;
  3036. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  3037. Inst.getDebugLoc(), BB);
  3038. R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
  3039. if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
  3040. std::string InstStrStorage;
  3041. raw_string_ostream InstStr(InstStrStorage);
  3042. InstStr << Inst;
  3043. R << ": '" << InstStr.str() << "'";
  3044. }
  3045. reportTranslationError(*MF, *TPC, *ORE, R);
  3046. return false;
  3047. }
  3048. if (!finalizeBasicBlock(*BB, MBB)) {
  3049. OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
  3050. BB->getTerminator()->getDebugLoc(), BB);
  3051. R << "unable to translate basic block";
  3052. reportTranslationError(*MF, *TPC, *ORE, R);
  3053. return false;
  3054. }
  3055. }
  3056. #ifndef NDEBUG
  3057. WrapperObserver.removeObserver(&Verifier);
  3058. #endif
  3059. }
  3060. finishPendingPhis();
  3061. SwiftError.propagateVRegs();
  3062. // Merge the argument lowering and constants block with its single
  3063. // successor, the LLVM-IR entry block. We want the basic block to
  3064. // be maximal.
  3065. assert(EntryBB->succ_size() == 1 &&
  3066. "Custom BB used for lowering should have only one successor");
  3067. // Get the successor of the current entry block.
  3068. MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
  3069. assert(NewEntryBB.pred_size() == 1 &&
  3070. "LLVM-IR entry block has a predecessor!?");
  3071. // Move all the instruction from the current entry block to the
  3072. // new entry block.
  3073. NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
  3074. EntryBB->end());
  3075. // Update the live-in information for the new entry block.
  3076. for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
  3077. NewEntryBB.addLiveIn(LiveIn);
  3078. NewEntryBB.sortUniqueLiveIns();
  3079. // Get rid of the now empty basic block.
  3080. EntryBB->removeSuccessor(&NewEntryBB);
  3081. MF->remove(EntryBB);
  3082. MF->deleteMachineBasicBlock(EntryBB);
  3083. assert(&MF->front() == &NewEntryBB &&
  3084. "New entry wasn't next in the list of basic block!");
  3085. // Initialize stack protector information.
  3086. StackProtector &SP = getAnalysis<StackProtector>();
  3087. SP.copyToMachineFrameInfo(MF->getFrameInfo());
  3088. return false;
  3089. }