ARMConstantIslandPass.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  1. //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains a pass that splits the constant pool up into 'islands'
  10. // which are scattered through-out the function. This is required due to the
  11. // limited pc-relative displacements that ARM has.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ARM.h"
  15. #include "ARMBaseInstrInfo.h"
  16. #include "ARMBasicBlockInfo.h"
  17. #include "ARMMachineFunctionInfo.h"
  18. #include "ARMSubtarget.h"
  19. #include "MCTargetDesc/ARMBaseInfo.h"
  20. #include "MVETailPredUtils.h"
  21. #include "Thumb2InstrInfo.h"
  22. #include "Utils/ARMBaseInfo.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include "llvm/CodeGen/LivePhysRegs.h"
  30. #include "llvm/CodeGen/MachineBasicBlock.h"
  31. #include "llvm/CodeGen/MachineConstantPool.h"
  32. #include "llvm/CodeGen/MachineDominators.h"
  33. #include "llvm/CodeGen/MachineFunction.h"
  34. #include "llvm/CodeGen/MachineFunctionPass.h"
  35. #include "llvm/CodeGen/MachineInstr.h"
  36. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  37. #include "llvm/CodeGen/MachineOperand.h"
  38. #include "llvm/CodeGen/MachineRegisterInfo.h"
  39. #include "llvm/Config/llvm-config.h"
  40. #include "llvm/IR/DataLayout.h"
  41. #include "llvm/IR/DebugLoc.h"
  42. #include "llvm/MC/MCInstrDesc.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/CommandLine.h"
  45. #include "llvm/Support/Compiler.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/ErrorHandling.h"
  48. #include "llvm/Support/Format.h"
  49. #include "llvm/Support/MathExtras.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include <algorithm>
  52. #include <cassert>
  53. #include <cstdint>
  54. #include <iterator>
  55. #include <utility>
  56. #include <vector>
  57. using namespace llvm;
  58. #define DEBUG_TYPE "arm-cp-islands"
  59. #define ARM_CP_ISLANDS_OPT_NAME \
  60. "ARM constant island placement and branch shortening pass"
  61. STATISTIC(NumCPEs, "Number of constpool entries");
  62. STATISTIC(NumSplit, "Number of uncond branches inserted");
  63. STATISTIC(NumCBrFixed, "Number of cond branches fixed");
  64. STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
  65. STATISTIC(NumTBs, "Number of table branches generated");
  66. STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
  67. STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
  68. STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
  69. STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
  70. STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
  71. STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");
  72. static cl::opt<bool>
  73. AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
  74. cl::desc("Adjust basic block layout to better use TB[BH]"));
  75. static cl::opt<unsigned>
  76. CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
  77. cl::desc("The max number of iteration for converge"));
  78. static cl::opt<bool> SynthesizeThumb1TBB(
  79. "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
  80. cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
  81. "equivalent to the TBB/TBH instructions"));
  82. namespace {
  83. /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
  84. /// requires constant pool entries to be scattered among the instructions
  85. /// inside a function. To do this, it completely ignores the normal LLVM
  86. /// constant pool; instead, it places constants wherever it feels like with
  87. /// special instructions.
  88. ///
  89. /// The terminology used in this pass includes:
  90. /// Islands - Clumps of constants placed in the function.
  91. /// Water - Potential places where an island could be formed.
  92. /// CPE - A constant pool entry that has been placed somewhere, which
  93. /// tracks a list of users.
  94. class ARMConstantIslands : public MachineFunctionPass {
  95. std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
  96. /// WaterList - A sorted list of basic blocks where islands could be placed
  97. /// (i.e. blocks that don't fall through to the following block, due
  98. /// to a return, unreachable, or unconditional branch).
  99. std::vector<MachineBasicBlock*> WaterList;
  100. /// NewWaterList - The subset of WaterList that was created since the
  101. /// previous iteration by inserting unconditional branches.
  102. SmallSet<MachineBasicBlock*, 4> NewWaterList;
  103. using water_iterator = std::vector<MachineBasicBlock *>::iterator;
  104. /// CPUser - One user of a constant pool, keeping the machine instruction
  105. /// pointer, the constant pool being referenced, and the max displacement
  106. /// allowed from the instruction to the CP. The HighWaterMark records the
  107. /// highest basic block where a new CPEntry can be placed. To ensure this
  108. /// pass terminates, the CP entries are initially placed at the end of the
  109. /// function and then move monotonically to lower addresses. The
  110. /// exception to this rule is when the current CP entry for a particular
  111. /// CPUser is out of range, but there is another CP entry for the same
  112. /// constant value in range. We want to use the existing in-range CP
  113. /// entry, but if it later moves out of range, the search for new water
  114. /// should resume where it left off. The HighWaterMark is used to record
  115. /// that point.
  116. struct CPUser {
  117. MachineInstr *MI;
  118. MachineInstr *CPEMI;
  119. MachineBasicBlock *HighWaterMark;
  120. unsigned MaxDisp;
  121. bool NegOk;
  122. bool IsSoImm;
  123. bool KnownAlignment = false;
  124. CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
  125. bool neg, bool soimm)
  126. : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
  127. HighWaterMark = CPEMI->getParent();
  128. }
  129. /// getMaxDisp - Returns the maximum displacement supported by MI.
  130. /// Correct for unknown alignment.
  131. /// Conservatively subtract 2 bytes to handle weird alignment effects.
  132. unsigned getMaxDisp() const {
  133. return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
  134. }
  135. };
  136. /// CPUsers - Keep track of all of the machine instructions that use various
  137. /// constant pools and their max displacement.
  138. std::vector<CPUser> CPUsers;
  139. /// CPEntry - One per constant pool entry, keeping the machine instruction
  140. /// pointer, the constpool index, and the number of CPUser's which
  141. /// reference this entry.
  142. struct CPEntry {
  143. MachineInstr *CPEMI;
  144. unsigned CPI;
  145. unsigned RefCount;
  146. CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
  147. : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
  148. };
  149. /// CPEntries - Keep track of all of the constant pool entry machine
  150. /// instructions. For each original constpool index (i.e. those that existed
  151. /// upon entry to this pass), it keeps a vector of entries. Original
  152. /// elements are cloned as we go along; the clones are put in the vector of
  153. /// the original element, but have distinct CPIs.
  154. ///
  155. /// The first half of CPEntries contains generic constants, the second half
  156. /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
  157. /// which vector it will be in here.
  158. std::vector<std::vector<CPEntry>> CPEntries;
  159. /// Maps a JT index to the offset in CPEntries containing copies of that
  160. /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
  161. DenseMap<int, int> JumpTableEntryIndices;
  162. /// Maps a JT index to the LEA that actually uses the index to calculate its
  163. /// base address.
  164. DenseMap<int, int> JumpTableUserIndices;
  165. // Maps a MachineBasicBlock to the number of jump tables entries.
  166. DenseMap<const MachineBasicBlock *, int> BlockJumpTableRefCount;
  167. /// ImmBranch - One per immediate branch, keeping the machine instruction
  168. /// pointer, conditional or unconditional, the max displacement,
  169. /// and (if isCond is true) the corresponding unconditional branch
  170. /// opcode.
  171. struct ImmBranch {
  172. MachineInstr *MI;
  173. unsigned MaxDisp : 31;
  174. bool isCond : 1;
  175. unsigned UncondBr;
  176. ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
  177. : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
  178. };
  179. /// ImmBranches - Keep track of all the immediate branch instructions.
  180. std::vector<ImmBranch> ImmBranches;
  181. /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
  182. SmallVector<MachineInstr*, 4> PushPopMIs;
  183. /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
  184. SmallVector<MachineInstr*, 4> T2JumpTables;
  185. MachineFunction *MF;
  186. MachineConstantPool *MCP;
  187. const ARMBaseInstrInfo *TII;
  188. const ARMSubtarget *STI;
  189. ARMFunctionInfo *AFI;
  190. MachineDominatorTree *DT = nullptr;
  191. bool isThumb;
  192. bool isThumb1;
  193. bool isThumb2;
  194. bool isPositionIndependentOrROPI;
  195. public:
  196. static char ID;
  197. ARMConstantIslands() : MachineFunctionPass(ID) {}
  198. bool runOnMachineFunction(MachineFunction &MF) override;
  199. void getAnalysisUsage(AnalysisUsage &AU) const override {
  200. AU.addRequired<MachineDominatorTree>();
  201. MachineFunctionPass::getAnalysisUsage(AU);
  202. }
  203. MachineFunctionProperties getRequiredProperties() const override {
  204. return MachineFunctionProperties().set(
  205. MachineFunctionProperties::Property::NoVRegs);
  206. }
  207. StringRef getPassName() const override {
  208. return ARM_CP_ISLANDS_OPT_NAME;
  209. }
  210. private:
  211. void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
  212. void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
  213. bool BBHasFallthrough(MachineBasicBlock *MBB);
  214. CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
  215. Align getCPEAlign(const MachineInstr *CPEMI);
  216. void scanFunctionJumpTables();
  217. void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
  218. MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
  219. void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
  220. bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
  221. unsigned getCombinedIndex(const MachineInstr *CPEMI);
  222. int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
  223. bool findAvailableWater(CPUser&U, unsigned UserOffset,
  224. water_iterator &WaterIter, bool CloserWater);
  225. void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
  226. MachineBasicBlock *&NewMBB);
  227. bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
  228. void removeDeadCPEMI(MachineInstr *CPEMI);
  229. bool removeUnusedCPEntries();
  230. bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
  231. MachineInstr *CPEMI, unsigned Disp, bool NegOk,
  232. bool DoDump = false);
  233. bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
  234. CPUser &U, unsigned &Growth);
  235. bool fixupImmediateBr(ImmBranch &Br);
  236. bool fixupConditionalBr(ImmBranch &Br);
  237. bool fixupUnconditionalBr(ImmBranch &Br);
  238. bool optimizeThumb2Instructions();
  239. bool optimizeThumb2Branches();
  240. bool reorderThumb2JumpTables();
  241. bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
  242. unsigned &DeadSize, bool &CanDeleteLEA,
  243. bool &BaseRegKill);
  244. bool optimizeThumb2JumpTables();
  245. void fixupBTI(unsigned JTI, MachineBasicBlock &OldBB,
  246. MachineBasicBlock &NewBB);
  247. MachineBasicBlock *adjustJTTargetBlockForward(unsigned JTI,
  248. MachineBasicBlock *BB,
  249. MachineBasicBlock *JTBB);
  250. unsigned getUserOffset(CPUser&) const;
  251. void dumpBBs();
  252. void verify();
  253. bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
  254. unsigned Disp, bool NegativeOK, bool IsSoImm = false);
  255. bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
  256. const CPUser &U) {
  257. return isOffsetInRange(UserOffset, TrialOffset,
  258. U.getMaxDisp(), U.NegOk, U.IsSoImm);
  259. }
  260. };
  261. } // end anonymous namespace
  262. char ARMConstantIslands::ID = 0;
  263. /// verify - check BBOffsets, BBSizes, alignment of islands
  264. void ARMConstantIslands::verify() {
  265. #ifndef NDEBUG
  266. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  267. assert(is_sorted(*MF, [&BBInfo](const MachineBasicBlock &LHS,
  268. const MachineBasicBlock &RHS) {
  269. return BBInfo[LHS.getNumber()].postOffset() <
  270. BBInfo[RHS.getNumber()].postOffset();
  271. }));
  272. LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
  273. for (CPUser &U : CPUsers) {
  274. unsigned UserOffset = getUserOffset(U);
  275. // Verify offset using the real max displacement without the safety
  276. // adjustment.
  277. if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
  278. /* DoDump = */ true)) {
  279. LLVM_DEBUG(dbgs() << "OK\n");
  280. continue;
  281. }
  282. LLVM_DEBUG(dbgs() << "Out of range.\n");
  283. dumpBBs();
  284. LLVM_DEBUG(MF->dump());
  285. llvm_unreachable("Constant pool entry out of range!");
  286. }
  287. #endif
  288. }
  289. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  290. /// print block size and offset information - debugging
  291. LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
  292. LLVM_DEBUG({
  293. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  294. for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
  295. const BasicBlockInfo &BBI = BBInfo[J];
  296. dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
  297. << " kb=" << unsigned(BBI.KnownBits)
  298. << " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign)
  299. << format(" size=%#x\n", BBInfo[J].Size);
  300. }
  301. });
  302. }
  303. #endif
  304. // Align blocks where the previous block does not fall through. This may add
  305. // extra NOP's but they will not be executed. It uses the PrefLoopAlignment as a
  306. // measure of how much to align, and only runs at CodeGenOpt::Aggressive.
  307. static bool AlignBlocks(MachineFunction *MF, const ARMSubtarget *STI) {
  308. if (MF->getTarget().getOptLevel() != CodeGenOpt::Aggressive ||
  309. MF->getFunction().hasOptSize())
  310. return false;
  311. auto *TLI = STI->getTargetLowering();
  312. const Align Alignment = TLI->getPrefLoopAlignment();
  313. if (Alignment < 4)
  314. return false;
  315. bool Changed = false;
  316. bool PrevCanFallthough = true;
  317. for (auto &MBB : *MF) {
  318. if (!PrevCanFallthough) {
  319. Changed = true;
  320. MBB.setAlignment(Alignment);
  321. }
  322. PrevCanFallthough = MBB.canFallThrough();
  323. // For LOB's, the ARMLowOverheadLoops pass may remove the unconditional
  324. // branch later in the pipeline.
  325. if (STI->hasLOB()) {
  326. for (const auto &MI : reverse(MBB.terminators())) {
  327. if (MI.getOpcode() == ARM::t2B &&
  328. MI.getOperand(0).getMBB() == MBB.getNextNode())
  329. continue;
  330. if (isLoopStart(MI) || MI.getOpcode() == ARM::t2LoopEnd ||
  331. MI.getOpcode() == ARM::t2LoopEndDec) {
  332. PrevCanFallthough = true;
  333. break;
  334. }
  335. // Any other terminator - nothing to do
  336. break;
  337. }
  338. }
  339. }
  340. return Changed;
  341. }
  342. bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
  343. MF = &mf;
  344. MCP = mf.getConstantPool();
  345. BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf));
  346. LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
  347. << MCP->getConstants().size() << " CP entries, aligned to "
  348. << MCP->getConstantPoolAlign().value() << " bytes *****\n");
  349. STI = &MF->getSubtarget<ARMSubtarget>();
  350. TII = STI->getInstrInfo();
  351. isPositionIndependentOrROPI =
  352. STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
  353. AFI = MF->getInfo<ARMFunctionInfo>();
  354. DT = &getAnalysis<MachineDominatorTree>();
  355. isThumb = AFI->isThumbFunction();
  356. isThumb1 = AFI->isThumb1OnlyFunction();
  357. isThumb2 = AFI->isThumb2Function();
  358. bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
  359. // TBB generation code in this constant island pass has not been adapted to
  360. // deal with speculation barriers.
  361. if (STI->hardenSlsRetBr())
  362. GenerateTBB = false;
  363. // Renumber all of the machine basic blocks in the function, guaranteeing that
  364. // the numbers agree with the position of the block in the function.
  365. MF->RenumberBlocks();
  366. // Try to reorder and otherwise adjust the block layout to make good use
  367. // of the TB[BH] instructions.
  368. bool MadeChange = false;
  369. if (GenerateTBB && AdjustJumpTableBlocks) {
  370. scanFunctionJumpTables();
  371. MadeChange |= reorderThumb2JumpTables();
  372. // Data is out of date, so clear it. It'll be re-computed later.
  373. T2JumpTables.clear();
  374. // Blocks may have shifted around. Keep the numbering up to date.
  375. MF->RenumberBlocks();
  376. }
  377. // Align any non-fallthrough blocks
  378. MadeChange |= AlignBlocks(MF, STI);
  379. // Perform the initial placement of the constant pool entries. To start with,
  380. // we put them all at the end of the function.
  381. std::vector<MachineInstr*> CPEMIs;
  382. if (!MCP->isEmpty())
  383. doInitialConstPlacement(CPEMIs);
  384. if (MF->getJumpTableInfo())
  385. doInitialJumpTablePlacement(CPEMIs);
  386. /// The next UID to take is the first unused one.
  387. AFI->initPICLabelUId(CPEMIs.size());
  388. // Do the initial scan of the function, building up information about the
  389. // sizes of each block, the location of all the water, and finding all of the
  390. // constant pool users.
  391. initializeFunctionInfo(CPEMIs);
  392. CPEMIs.clear();
  393. LLVM_DEBUG(dumpBBs());
  394. // Functions with jump tables need an alignment of 4 because they use the ADR
  395. // instruction, which aligns the PC to 4 bytes before adding an offset.
  396. if (!T2JumpTables.empty())
  397. MF->ensureAlignment(Align(4));
  398. /// Remove dead constant pool entries.
  399. MadeChange |= removeUnusedCPEntries();
  400. // Iteratively place constant pool entries and fix up branches until there
  401. // is no change.
  402. unsigned NoCPIters = 0, NoBRIters = 0;
  403. while (true) {
  404. LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
  405. bool CPChange = false;
  406. for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
  407. // For most inputs, it converges in no more than 5 iterations.
  408. // If it doesn't end in 10, the input may have huge BB or many CPEs.
  409. // In this case, we will try different heuristics.
  410. CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
  411. if (CPChange && ++NoCPIters > CPMaxIteration)
  412. report_fatal_error("Constant Island pass failed to converge!");
  413. LLVM_DEBUG(dumpBBs());
  414. // Clear NewWaterList now. If we split a block for branches, it should
  415. // appear as "new water" for the next iteration of constant pool placement.
  416. NewWaterList.clear();
  417. LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
  418. bool BRChange = false;
  419. for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
  420. BRChange |= fixupImmediateBr(ImmBranches[i]);
  421. if (BRChange && ++NoBRIters > 30)
  422. report_fatal_error("Branch Fix Up pass failed to converge!");
  423. LLVM_DEBUG(dumpBBs());
  424. if (!CPChange && !BRChange)
  425. break;
  426. MadeChange = true;
  427. }
  428. // Shrink 32-bit Thumb2 load and store instructions.
  429. if (isThumb2 && !STI->prefers32BitThumb())
  430. MadeChange |= optimizeThumb2Instructions();
  431. // Shrink 32-bit branch instructions.
  432. if (isThumb && STI->hasV8MBaselineOps())
  433. MadeChange |= optimizeThumb2Branches();
  434. // Optimize jump tables using TBB / TBH.
  435. if (GenerateTBB && !STI->genExecuteOnly())
  436. MadeChange |= optimizeThumb2JumpTables();
  437. // After a while, this might be made debug-only, but it is not expensive.
  438. verify();
  439. // Save the mapping between original and cloned constpool entries.
  440. for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
  441. for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
  442. const CPEntry & CPE = CPEntries[i][j];
  443. if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
  444. AFI->recordCPEClone(i, CPE.CPI);
  445. }
  446. }
  447. LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
  448. BBUtils->clear();
  449. WaterList.clear();
  450. CPUsers.clear();
  451. CPEntries.clear();
  452. JumpTableEntryIndices.clear();
  453. JumpTableUserIndices.clear();
  454. BlockJumpTableRefCount.clear();
  455. ImmBranches.clear();
  456. PushPopMIs.clear();
  457. T2JumpTables.clear();
  458. return MadeChange;
  459. }
  460. /// Perform the initial placement of the regular constant pool entries.
  461. /// To start with, we put them all at the end of the function.
  462. void
  463. ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
  464. // Create the basic block to hold the CPE's.
  465. MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
  466. MF->push_back(BB);
  467. // MachineConstantPool measures alignment in bytes.
  468. const Align MaxAlign = MCP->getConstantPoolAlign();
  469. const unsigned MaxLogAlign = Log2(MaxAlign);
  470. // Mark the basic block as required by the const-pool.
  471. BB->setAlignment(MaxAlign);
  472. // The function needs to be as aligned as the basic blocks. The linker may
  473. // move functions around based on their alignment.
  474. // Special case: halfword literals still need word alignment on the function.
  475. Align FuncAlign = MaxAlign;
  476. if (MaxAlign == 2)
  477. FuncAlign = Align(4);
  478. MF->ensureAlignment(FuncAlign);
  479. // Order the entries in BB by descending alignment. That ensures correct
  480. // alignment of all entries as long as BB is sufficiently aligned. Keep
  481. // track of the insertion point for each alignment. We are going to bucket
  482. // sort the entries as they are created.
  483. SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
  484. BB->end());
  485. // Add all of the constants from the constant pool to the end block, use an
  486. // identity mapping of CPI's to CPE's.
  487. const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
  488. const DataLayout &TD = MF->getDataLayout();
  489. for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
  490. unsigned Size = CPs[i].getSizeInBytes(TD);
  491. Align Alignment = CPs[i].getAlign();
  492. // Verify that all constant pool entries are a multiple of their alignment.
  493. // If not, we would have to pad them out so that instructions stay aligned.
  494. assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
  495. // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
  496. unsigned LogAlign = Log2(Alignment);
  497. MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
  498. MachineInstr *CPEMI =
  499. BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
  500. .addImm(i).addConstantPoolIndex(i).addImm(Size);
  501. CPEMIs.push_back(CPEMI);
  502. // Ensure that future entries with higher alignment get inserted before
  503. // CPEMI. This is bucket sort with iterators.
  504. for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
  505. if (InsPoint[a] == InsAt)
  506. InsPoint[a] = CPEMI;
  507. // Add a new CPEntry, but no corresponding CPUser yet.
  508. CPEntries.emplace_back(1, CPEntry(CPEMI, i));
  509. ++NumCPEs;
  510. LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
  511. << Size << ", align = " << Alignment.value() << '\n');
  512. }
  513. LLVM_DEBUG(BB->dump());
  514. }
  515. /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
  516. /// instructions can be made more efficient if the jump table immediately
  517. /// follows the instruction, it's best to place them immediately next to their
  518. /// jumps to begin with. In almost all cases they'll never be moved from that
  519. /// position.
  520. void ARMConstantIslands::doInitialJumpTablePlacement(
  521. std::vector<MachineInstr *> &CPEMIs) {
  522. unsigned i = CPEntries.size();
  523. auto MJTI = MF->getJumpTableInfo();
  524. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  525. MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
  526. for (MachineBasicBlock &MBB : *MF) {
  527. auto MI = MBB.getLastNonDebugInstr();
  528. // Look past potential SpeculationBarriers at end of BB.
  529. while (MI != MBB.end() &&
  530. (isSpeculationBarrierEndBBOpcode(MI->getOpcode()) ||
  531. MI->isDebugInstr()))
  532. --MI;
  533. if (MI == MBB.end())
  534. continue;
  535. unsigned JTOpcode;
  536. switch (MI->getOpcode()) {
  537. default:
  538. continue;
  539. case ARM::BR_JTadd:
  540. case ARM::BR_JTr:
  541. case ARM::tBR_JTr:
  542. case ARM::BR_JTm_i12:
  543. case ARM::BR_JTm_rs:
  544. JTOpcode = ARM::JUMPTABLE_ADDRS;
  545. break;
  546. case ARM::t2BR_JT:
  547. JTOpcode = ARM::JUMPTABLE_INSTS;
  548. break;
  549. case ARM::tTBB_JT:
  550. case ARM::t2TBB_JT:
  551. JTOpcode = ARM::JUMPTABLE_TBB;
  552. break;
  553. case ARM::tTBH_JT:
  554. case ARM::t2TBH_JT:
  555. JTOpcode = ARM::JUMPTABLE_TBH;
  556. break;
  557. }
  558. unsigned NumOps = MI->getDesc().getNumOperands();
  559. MachineOperand JTOp =
  560. MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
  561. unsigned JTI = JTOp.getIndex();
  562. unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
  563. MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
  564. MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
  565. MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
  566. DebugLoc(), TII->get(JTOpcode))
  567. .addImm(i++)
  568. .addJumpTableIndex(JTI)
  569. .addImm(Size);
  570. CPEMIs.push_back(CPEMI);
  571. CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
  572. JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
  573. if (!LastCorrectlyNumberedBB)
  574. LastCorrectlyNumberedBB = &MBB;
  575. }
  576. // If we did anything then we need to renumber the subsequent blocks.
  577. if (LastCorrectlyNumberedBB)
  578. MF->RenumberBlocks(LastCorrectlyNumberedBB);
  579. }
  580. /// BBHasFallthrough - Return true if the specified basic block can fallthrough
  581. /// into the block immediately after it.
  582. bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
  583. // Get the next machine basic block in the function.
  584. MachineFunction::iterator MBBI = MBB->getIterator();
  585. // Can't fall off end of function.
  586. if (std::next(MBBI) == MBB->getParent()->end())
  587. return false;
  588. MachineBasicBlock *NextBB = &*std::next(MBBI);
  589. if (!MBB->isSuccessor(NextBB))
  590. return false;
  591. // Try to analyze the end of the block. A potential fallthrough may already
  592. // have an unconditional branch for whatever reason.
  593. MachineBasicBlock *TBB, *FBB;
  594. SmallVector<MachineOperand, 4> Cond;
  595. bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
  596. return TooDifficult || FBB == nullptr;
  597. }
  598. /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
  599. /// look up the corresponding CPEntry.
  600. ARMConstantIslands::CPEntry *
  601. ARMConstantIslands::findConstPoolEntry(unsigned CPI,
  602. const MachineInstr *CPEMI) {
  603. std::vector<CPEntry> &CPEs = CPEntries[CPI];
  604. // Number of entries per constpool index should be small, just do a
  605. // linear search.
  606. for (CPEntry &CPE : CPEs)
  607. if (CPE.CPEMI == CPEMI)
  608. return &CPE;
  609. return nullptr;
  610. }
  611. /// getCPEAlign - Returns the required alignment of the constant pool entry
  612. /// represented by CPEMI.
  613. Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) {
  614. switch (CPEMI->getOpcode()) {
  615. case ARM::CONSTPOOL_ENTRY:
  616. break;
  617. case ARM::JUMPTABLE_TBB:
  618. return isThumb1 ? Align(4) : Align(1);
  619. case ARM::JUMPTABLE_TBH:
  620. return isThumb1 ? Align(4) : Align(2);
  621. case ARM::JUMPTABLE_INSTS:
  622. return Align(2);
  623. case ARM::JUMPTABLE_ADDRS:
  624. return Align(4);
  625. default:
  626. llvm_unreachable("unknown constpool entry kind");
  627. }
  628. unsigned CPI = getCombinedIndex(CPEMI);
  629. assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
  630. return MCP->getConstants()[CPI].getAlign();
  631. }
  632. // Exception landing pads, blocks that has their adress taken, and function
  633. // entry blocks will always be (potential) indirect jump targets, regardless of
  634. // whether they are referenced by or not by jump tables.
  635. static bool isAlwaysIndirectTarget(const MachineBasicBlock &MBB) {
  636. return MBB.isEHPad() || MBB.hasAddressTaken() ||
  637. &MBB == &MBB.getParent()->front();
  638. }
  639. /// scanFunctionJumpTables - Do a scan of the function, building up
  640. /// information about the sizes of each block and the locations of all
  641. /// the jump tables.
  642. void ARMConstantIslands::scanFunctionJumpTables() {
  643. for (MachineBasicBlock &MBB : *MF) {
  644. for (MachineInstr &I : MBB)
  645. if (I.isBranch() &&
  646. (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
  647. T2JumpTables.push_back(&I);
  648. }
  649. if (!MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement())
  650. return;
  651. if (const MachineJumpTableInfo *JTI = MF->getJumpTableInfo())
  652. for (const MachineJumpTableEntry &JTE : JTI->getJumpTables())
  653. for (const MachineBasicBlock *MBB : JTE.MBBs) {
  654. if (isAlwaysIndirectTarget(*MBB))
  655. // Set the reference count essentially to infinity, it will never
  656. // reach zero and the BTI Instruction will never be removed.
  657. BlockJumpTableRefCount[MBB] = std::numeric_limits<int>::max();
  658. else
  659. ++BlockJumpTableRefCount[MBB];
  660. }
  661. }
  662. /// initializeFunctionInfo - Do the initial scan of the function, building up
  663. /// information about the sizes of each block, the location of all the water,
  664. /// and finding all of the constant pool users.
  665. void ARMConstantIslands::
  666. initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
  667. BBUtils->computeAllBlockSizes();
  668. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  669. // The known bits of the entry block offset are determined by the function
  670. // alignment.
  671. BBInfo.front().KnownBits = Log2(MF->getAlignment());
  672. // Compute block offsets and known bits.
  673. BBUtils->adjustBBOffsetsAfter(&MF->front());
  674. // Now go back through the instructions and build up our data structures.
  675. for (MachineBasicBlock &MBB : *MF) {
  676. // If this block doesn't fall through into the next MBB, then this is
  677. // 'water' that a constant pool island could be placed.
  678. if (!BBHasFallthrough(&MBB))
  679. WaterList.push_back(&MBB);
  680. for (MachineInstr &I : MBB) {
  681. if (I.isDebugInstr())
  682. continue;
  683. unsigned Opc = I.getOpcode();
  684. if (I.isBranch()) {
  685. bool isCond = false;
  686. unsigned Bits = 0;
  687. unsigned Scale = 1;
  688. int UOpc = Opc;
  689. switch (Opc) {
  690. default:
  691. continue; // Ignore other JT branches
  692. case ARM::t2BR_JT:
  693. case ARM::tBR_JTr:
  694. T2JumpTables.push_back(&I);
  695. continue; // Does not get an entry in ImmBranches
  696. case ARM::Bcc:
  697. isCond = true;
  698. UOpc = ARM::B;
  699. [[fallthrough]];
  700. case ARM::B:
  701. Bits = 24;
  702. Scale = 4;
  703. break;
  704. case ARM::tBcc:
  705. isCond = true;
  706. UOpc = ARM::tB;
  707. Bits = 8;
  708. Scale = 2;
  709. break;
  710. case ARM::tB:
  711. Bits = 11;
  712. Scale = 2;
  713. break;
  714. case ARM::t2Bcc:
  715. isCond = true;
  716. UOpc = ARM::t2B;
  717. Bits = 20;
  718. Scale = 2;
  719. break;
  720. case ARM::t2B:
  721. Bits = 24;
  722. Scale = 2;
  723. break;
  724. }
  725. // Record this immediate branch.
  726. unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
  727. ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
  728. }
  729. if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
  730. PushPopMIs.push_back(&I);
  731. if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
  732. Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
  733. Opc == ARM::JUMPTABLE_TBH)
  734. continue;
  735. // Scan the instructions for constant pool operands.
  736. for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
  737. if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
  738. // We found one. The addressing mode tells us the max displacement
  739. // from the PC that this instruction permits.
  740. // Basic size info comes from the TSFlags field.
  741. unsigned Bits = 0;
  742. unsigned Scale = 1;
  743. bool NegOk = false;
  744. bool IsSoImm = false;
  745. switch (Opc) {
  746. default:
  747. llvm_unreachable("Unknown addressing mode for CP reference!");
  748. // Taking the address of a CP entry.
  749. case ARM::LEApcrel:
  750. case ARM::LEApcrelJT: {
  751. // This takes a SoImm, which is 8 bit immediate rotated. We'll
  752. // pretend the maximum offset is 255 * 4. Since each instruction
  753. // 4 byte wide, this is always correct. We'll check for other
  754. // displacements that fits in a SoImm as well.
  755. Bits = 8;
  756. NegOk = true;
  757. IsSoImm = true;
  758. unsigned CPI = I.getOperand(op).getIndex();
  759. assert(CPI < CPEMIs.size());
  760. MachineInstr *CPEMI = CPEMIs[CPI];
  761. const Align CPEAlign = getCPEAlign(CPEMI);
  762. const unsigned LogCPEAlign = Log2(CPEAlign);
  763. if (LogCPEAlign >= 2)
  764. Scale = 4;
  765. else
  766. // For constants with less than 4-byte alignment,
  767. // we'll pretend the maximum offset is 255 * 1.
  768. Scale = 1;
  769. }
  770. break;
  771. case ARM::t2LEApcrel:
  772. case ARM::t2LEApcrelJT:
  773. Bits = 12;
  774. NegOk = true;
  775. break;
  776. case ARM::tLEApcrel:
  777. case ARM::tLEApcrelJT:
  778. Bits = 8;
  779. Scale = 4;
  780. break;
  781. case ARM::LDRBi12:
  782. case ARM::LDRi12:
  783. case ARM::LDRcp:
  784. case ARM::t2LDRpci:
  785. case ARM::t2LDRHpci:
  786. case ARM::t2LDRSHpci:
  787. case ARM::t2LDRBpci:
  788. case ARM::t2LDRSBpci:
  789. Bits = 12; // +-offset_12
  790. NegOk = true;
  791. break;
  792. case ARM::tLDRpci:
  793. Bits = 8;
  794. Scale = 4; // +(offset_8*4)
  795. break;
  796. case ARM::VLDRD:
  797. case ARM::VLDRS:
  798. Bits = 8;
  799. Scale = 4; // +-(offset_8*4)
  800. NegOk = true;
  801. break;
  802. case ARM::VLDRH:
  803. Bits = 8;
  804. Scale = 2; // +-(offset_8*2)
  805. NegOk = true;
  806. break;
  807. }
  808. // Remember that this is a user of a CP entry.
  809. unsigned CPI = I.getOperand(op).getIndex();
  810. if (I.getOperand(op).isJTI()) {
  811. JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
  812. CPI = JumpTableEntryIndices[CPI];
  813. }
  814. MachineInstr *CPEMI = CPEMIs[CPI];
  815. unsigned MaxOffs = ((1 << Bits)-1) * Scale;
  816. CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
  817. // Increment corresponding CPEntry reference count.
  818. CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
  819. assert(CPE && "Cannot find a corresponding CPEntry!");
  820. CPE->RefCount++;
  821. // Instructions can only use one CP entry, don't bother scanning the
  822. // rest of the operands.
  823. break;
  824. }
  825. }
  826. }
  827. }
  828. /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
  829. /// ID.
  830. static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
  831. const MachineBasicBlock *RHS) {
  832. return LHS->getNumber() < RHS->getNumber();
  833. }
  834. /// updateForInsertedWaterBlock - When a block is newly inserted into the
  835. /// machine function, it upsets all of the block numbers. Renumber the blocks
  836. /// and update the arrays that parallel this numbering.
  837. void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
  838. // Renumber the MBB's to keep them consecutive.
  839. NewBB->getParent()->RenumberBlocks(NewBB);
  840. // Insert an entry into BBInfo to align it properly with the (newly
  841. // renumbered) block numbers.
  842. BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
  843. // Next, update WaterList. Specifically, we need to add NewMBB as having
  844. // available water after it.
  845. water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
  846. WaterList.insert(IP, NewBB);
  847. }
  848. /// Split the basic block containing MI into two blocks, which are joined by
  849. /// an unconditional branch. Update data structures and renumber blocks to
  850. /// account for this change and returns the newly created block.
  851. MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
  852. MachineBasicBlock *OrigBB = MI->getParent();
  853. // Collect liveness information at MI.
  854. LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());
  855. LRs.addLiveOuts(*OrigBB);
  856. auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();
  857. for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))
  858. LRs.stepBackward(LiveMI);
  859. // Create a new MBB for the code after the OrigBB.
  860. MachineBasicBlock *NewBB =
  861. MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
  862. MachineFunction::iterator MBBI = ++OrigBB->getIterator();
  863. MF->insert(MBBI, NewBB);
  864. // Splice the instructions starting with MI over to NewBB.
  865. NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
  866. // Add an unconditional branch from OrigBB to NewBB.
  867. // Note the new unconditional branch is not being recorded.
  868. // There doesn't seem to be meaningful DebugInfo available; this doesn't
  869. // correspond to anything in the source.
  870. unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
  871. if (!isThumb)
  872. BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
  873. else
  874. BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
  875. .addMBB(NewBB)
  876. .add(predOps(ARMCC::AL));
  877. ++NumSplit;
  878. // Update the CFG. All succs of OrigBB are now succs of NewBB.
  879. NewBB->transferSuccessors(OrigBB);
  880. // OrigBB branches to NewBB.
  881. OrigBB->addSuccessor(NewBB);
  882. // Update live-in information in the new block.
  883. MachineRegisterInfo &MRI = MF->getRegInfo();
  884. for (MCPhysReg L : LRs)
  885. if (!MRI.isReserved(L))
  886. NewBB->addLiveIn(L);
  887. // Update internal data structures to account for the newly inserted MBB.
  888. // This is almost the same as updateForInsertedWaterBlock, except that
  889. // the Water goes after OrigBB, not NewBB.
  890. MF->RenumberBlocks(NewBB);
  891. // Insert an entry into BBInfo to align it properly with the (newly
  892. // renumbered) block numbers.
  893. BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
  894. // Next, update WaterList. Specifically, we need to add OrigMBB as having
  895. // available water after it (but not if it's already there, which happens
  896. // when splitting before a conditional branch that is followed by an
  897. // unconditional branch - in that case we want to insert NewBB).
  898. water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
  899. MachineBasicBlock* WaterBB = *IP;
  900. if (WaterBB == OrigBB)
  901. WaterList.insert(std::next(IP), NewBB);
  902. else
  903. WaterList.insert(IP, OrigBB);
  904. NewWaterList.insert(OrigBB);
  905. // Figure out how large the OrigBB is. As the first half of the original
  906. // block, it cannot contain a tablejump. The size includes
  907. // the new jump we added. (It should be possible to do this without
  908. // recounting everything, but it's very confusing, and this is rarely
  909. // executed.)
  910. BBUtils->computeBlockSize(OrigBB);
  911. // Figure out how large the NewMBB is. As the second half of the original
  912. // block, it may contain a tablejump.
  913. BBUtils->computeBlockSize(NewBB);
  914. // All BBOffsets following these blocks must be modified.
  915. BBUtils->adjustBBOffsetsAfter(OrigBB);
  916. return NewBB;
  917. }
  918. /// getUserOffset - Compute the offset of U.MI as seen by the hardware
  919. /// displacement computation. Update U.KnownAlignment to match its current
  920. /// basic block location.
  921. unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
  922. unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
  923. SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
  924. const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
  925. unsigned KnownBits = BBI.internalKnownBits();
  926. // The value read from PC is offset from the actual instruction address.
  927. UserOffset += (isThumb ? 4 : 8);
  928. // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
  929. // Make sure U.getMaxDisp() returns a constrained range.
  930. U.KnownAlignment = (KnownBits >= 2);
  931. // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
  932. // purposes of the displacement computation; compensate for that here.
  933. // For unknown alignments, getMaxDisp() constrains the range instead.
  934. if (isThumb && U.KnownAlignment)
  935. UserOffset &= ~3u;
  936. return UserOffset;
  937. }
  938. /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
  939. /// reference) is within MaxDisp of TrialOffset (a proposed location of a
  940. /// constant pool entry).
  941. /// UserOffset is computed by getUserOffset above to include PC adjustments. If
  942. /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
  943. /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
  944. bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
  945. unsigned TrialOffset, unsigned MaxDisp,
  946. bool NegativeOK, bool IsSoImm) {
  947. if (UserOffset <= TrialOffset) {
  948. // User before the Trial.
  949. if (TrialOffset - UserOffset <= MaxDisp)
  950. return true;
  951. // FIXME: Make use full range of soimm values.
  952. } else if (NegativeOK) {
  953. if (UserOffset - TrialOffset <= MaxDisp)
  954. return true;
  955. // FIXME: Make use full range of soimm values.
  956. }
  957. return false;
  958. }
  959. /// isWaterInRange - Returns true if a CPE placed after the specified
  960. /// Water (a basic block) will be in range for the specific MI.
  961. ///
  962. /// Compute how much the function will grow by inserting a CPE after Water.
  963. bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
  964. MachineBasicBlock* Water, CPUser &U,
  965. unsigned &Growth) {
  966. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  967. const Align CPEAlign = getCPEAlign(U.CPEMI);
  968. const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign);
  969. unsigned NextBlockOffset;
  970. Align NextBlockAlignment;
  971. MachineFunction::const_iterator NextBlock = Water->getIterator();
  972. if (++NextBlock == MF->end()) {
  973. NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
  974. } else {
  975. NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
  976. NextBlockAlignment = NextBlock->getAlignment();
  977. }
  978. unsigned Size = U.CPEMI->getOperand(2).getImm();
  979. unsigned CPEEnd = CPEOffset + Size;
  980. // The CPE may be able to hide in the alignment padding before the next
  981. // block. It may also cause more padding to be required if it is more aligned
  982. // that the next block.
  983. if (CPEEnd > NextBlockOffset) {
  984. Growth = CPEEnd - NextBlockOffset;
  985. // Compute the padding that would go at the end of the CPE to align the next
  986. // block.
  987. Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
  988. // If the CPE is to be inserted before the instruction, that will raise
  989. // the offset of the instruction. Also account for unknown alignment padding
  990. // in blocks between CPE and the user.
  991. if (CPEOffset < UserOffset)
  992. UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign));
  993. } else
  994. // CPE fits in existing padding.
  995. Growth = 0;
  996. return isOffsetInRange(UserOffset, CPEOffset, U);
  997. }
  998. /// isCPEntryInRange - Returns true if the distance between specific MI and
  999. /// specific ConstPool entry instruction can fit in MI's displacement field.
  1000. bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
  1001. MachineInstr *CPEMI, unsigned MaxDisp,
  1002. bool NegOk, bool DoDump) {
  1003. unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
  1004. if (DoDump) {
  1005. LLVM_DEBUG({
  1006. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1007. unsigned Block = MI->getParent()->getNumber();
  1008. const BasicBlockInfo &BBI = BBInfo[Block];
  1009. dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
  1010. << " max delta=" << MaxDisp
  1011. << format(" insn address=%#x", UserOffset) << " in "
  1012. << printMBBReference(*MI->getParent()) << ": "
  1013. << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
  1014. << format("CPE address=%#x offset=%+d: ", CPEOffset,
  1015. int(CPEOffset - UserOffset));
  1016. });
  1017. }
  1018. return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
  1019. }
  1020. #ifndef NDEBUG
  1021. /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
  1022. /// unconditionally branches to its only successor.
  1023. static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
  1024. if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
  1025. return false;
  1026. MachineBasicBlock *Succ = *MBB->succ_begin();
  1027. MachineBasicBlock *Pred = *MBB->pred_begin();
  1028. MachineInstr *PredMI = &Pred->back();
  1029. if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
  1030. || PredMI->getOpcode() == ARM::t2B)
  1031. return PredMI->getOperand(0).getMBB() == Succ;
  1032. return false;
  1033. }
  1034. #endif // NDEBUG
  1035. /// decrementCPEReferenceCount - find the constant pool entry with index CPI
  1036. /// and instruction CPEMI, and decrement its refcount. If the refcount
  1037. /// becomes 0 remove the entry and instruction. Returns true if we removed
  1038. /// the entry, false if we didn't.
  1039. bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
  1040. MachineInstr *CPEMI) {
  1041. // Find the old entry. Eliminate it if it is no longer used.
  1042. CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
  1043. assert(CPE && "Unexpected!");
  1044. if (--CPE->RefCount == 0) {
  1045. removeDeadCPEMI(CPEMI);
  1046. CPE->CPEMI = nullptr;
  1047. --NumCPEs;
  1048. return true;
  1049. }
  1050. return false;
  1051. }
  1052. unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
  1053. if (CPEMI->getOperand(1).isCPI())
  1054. return CPEMI->getOperand(1).getIndex();
  1055. return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
  1056. }
  1057. /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
  1058. /// if not, see if an in-range clone of the CPE is in range, and if so,
  1059. /// change the data structures so the user references the clone. Returns:
  1060. /// 0 = no existing entry found
  1061. /// 1 = entry found, and there were no code insertions or deletions
  1062. /// 2 = entry found, and there were code insertions or deletions
  1063. int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
  1064. MachineInstr *UserMI = U.MI;
  1065. MachineInstr *CPEMI = U.CPEMI;
  1066. // Check to see if the CPE is already in-range.
  1067. if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
  1068. true)) {
  1069. LLVM_DEBUG(dbgs() << "In range\n");
  1070. return 1;
  1071. }
  1072. // No. Look for previously created clones of the CPE that are in range.
  1073. unsigned CPI = getCombinedIndex(CPEMI);
  1074. std::vector<CPEntry> &CPEs = CPEntries[CPI];
  1075. for (CPEntry &CPE : CPEs) {
  1076. // We already tried this one
  1077. if (CPE.CPEMI == CPEMI)
  1078. continue;
  1079. // Removing CPEs can leave empty entries, skip
  1080. if (CPE.CPEMI == nullptr)
  1081. continue;
  1082. if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getMaxDisp(),
  1083. U.NegOk)) {
  1084. LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
  1085. << "\n");
  1086. // Point the CPUser node to the replacement
  1087. U.CPEMI = CPE.CPEMI;
  1088. // Change the CPI in the instruction operand to refer to the clone.
  1089. for (MachineOperand &MO : UserMI->operands())
  1090. if (MO.isCPI()) {
  1091. MO.setIndex(CPE.CPI);
  1092. break;
  1093. }
  1094. // Adjust the refcount of the clone...
  1095. CPE.RefCount++;
  1096. // ...and the original. If we didn't remove the old entry, none of the
  1097. // addresses changed, so we don't need another pass.
  1098. return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
  1099. }
  1100. }
  1101. return 0;
  1102. }
  1103. /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
  1104. /// the specific unconditional branch instruction.
  1105. static inline unsigned getUnconditionalBrDisp(int Opc) {
  1106. switch (Opc) {
  1107. case ARM::tB:
  1108. return ((1<<10)-1)*2;
  1109. case ARM::t2B:
  1110. return ((1<<23)-1)*2;
  1111. default:
  1112. break;
  1113. }
  1114. return ((1<<23)-1)*4;
  1115. }
  1116. /// findAvailableWater - Look for an existing entry in the WaterList in which
  1117. /// we can place the CPE referenced from U so it's within range of U's MI.
  1118. /// Returns true if found, false if not. If it returns true, WaterIter
  1119. /// is set to the WaterList entry. For Thumb, prefer water that will not
  1120. /// introduce padding to water that will. To ensure that this pass
  1121. /// terminates, the CPE location for a particular CPUser is only allowed to
  1122. /// move to a lower address, so search backward from the end of the list and
  1123. /// prefer the first water that is in range.
  1124. bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
  1125. water_iterator &WaterIter,
  1126. bool CloserWater) {
  1127. if (WaterList.empty())
  1128. return false;
  1129. unsigned BestGrowth = ~0u;
  1130. // The nearest water without splitting the UserBB is right after it.
  1131. // If the distance is still large (we have a big BB), then we need to split it
  1132. // if we don't converge after certain iterations. This helps the following
  1133. // situation to converge:
  1134. // BB0:
  1135. // Big BB
  1136. // BB1:
  1137. // Constant Pool
  1138. // When a CP access is out of range, BB0 may be used as water. However,
  1139. // inserting islands between BB0 and BB1 makes other accesses out of range.
  1140. MachineBasicBlock *UserBB = U.MI->getParent();
  1141. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1142. const Align CPEAlign = getCPEAlign(U.CPEMI);
  1143. unsigned MinNoSplitDisp = BBInfo[UserBB->getNumber()].postOffset(CPEAlign);
  1144. if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
  1145. return false;
  1146. for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
  1147. --IP) {
  1148. MachineBasicBlock* WaterBB = *IP;
  1149. // Check if water is in range and is either at a lower address than the
  1150. // current "high water mark" or a new water block that was created since
  1151. // the previous iteration by inserting an unconditional branch. In the
  1152. // latter case, we want to allow resetting the high water mark back to
  1153. // this new water since we haven't seen it before. Inserting branches
  1154. // should be relatively uncommon and when it does happen, we want to be
  1155. // sure to take advantage of it for all the CPEs near that block, so that
  1156. // we don't insert more branches than necessary.
  1157. // When CloserWater is true, we try to find the lowest address after (or
  1158. // equal to) user MI's BB no matter of padding growth.
  1159. unsigned Growth;
  1160. if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
  1161. (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
  1162. NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
  1163. Growth < BestGrowth) {
  1164. // This is the least amount of required padding seen so far.
  1165. BestGrowth = Growth;
  1166. WaterIter = IP;
  1167. LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
  1168. << " Growth=" << Growth << '\n');
  1169. if (CloserWater && WaterBB == U.MI->getParent())
  1170. return true;
  1171. // Keep looking unless it is perfect and we're not looking for the lowest
  1172. // possible address.
  1173. if (!CloserWater && BestGrowth == 0)
  1174. return true;
  1175. }
  1176. if (IP == B)
  1177. break;
  1178. }
  1179. return BestGrowth != ~0u;
  1180. }
  1181. /// createNewWater - No existing WaterList entry will work for
  1182. /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
  1183. /// block is used if in range, and the conditional branch munged so control
  1184. /// flow is correct. Otherwise the block is split to create a hole with an
  1185. /// unconditional branch around it. In either case NewMBB is set to a
  1186. /// block following which the new island can be inserted (the WaterList
  1187. /// is not adjusted).
  1188. void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
  1189. unsigned UserOffset,
  1190. MachineBasicBlock *&NewMBB) {
  1191. CPUser &U = CPUsers[CPUserIndex];
  1192. MachineInstr *UserMI = U.MI;
  1193. MachineInstr *CPEMI = U.CPEMI;
  1194. const Align CPEAlign = getCPEAlign(CPEMI);
  1195. MachineBasicBlock *UserMBB = UserMI->getParent();
  1196. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1197. const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
  1198. // If the block does not end in an unconditional branch already, and if the
  1199. // end of the block is within range, make new water there. (The addition
  1200. // below is for the unconditional branch we will be adding: 4 bytes on ARM +
  1201. // Thumb2, 2 on Thumb1.
  1202. if (BBHasFallthrough(UserMBB)) {
  1203. // Size of branch to insert.
  1204. unsigned Delta = isThumb1 ? 2 : 4;
  1205. // Compute the offset where the CPE will begin.
  1206. unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta;
  1207. if (isOffsetInRange(UserOffset, CPEOffset, U)) {
  1208. LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
  1209. << format(", expected CPE offset %#x\n", CPEOffset));
  1210. NewMBB = &*++UserMBB->getIterator();
  1211. // Add an unconditional branch from UserMBB to fallthrough block. Record
  1212. // it for branch lengthening; this new branch will not get out of range,
  1213. // but if the preceding conditional branch is out of range, the targets
  1214. // will be exchanged, and the altered branch may be out of range, so the
  1215. // machinery has to know about it.
  1216. int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
  1217. if (!isThumb)
  1218. BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
  1219. else
  1220. BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
  1221. .addMBB(NewMBB)
  1222. .add(predOps(ARMCC::AL));
  1223. unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
  1224. ImmBranches.push_back(ImmBranch(&UserMBB->back(),
  1225. MaxDisp, false, UncondBr));
  1226. BBUtils->computeBlockSize(UserMBB);
  1227. BBUtils->adjustBBOffsetsAfter(UserMBB);
  1228. return;
  1229. }
  1230. }
  1231. // What a big block. Find a place within the block to split it. This is a
  1232. // little tricky on Thumb1 since instructions are 2 bytes and constant pool
  1233. // entries are 4 bytes: if instruction I references island CPE, and
  1234. // instruction I+1 references CPE', it will not work well to put CPE as far
  1235. // forward as possible, since then CPE' cannot immediately follow it (that
  1236. // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
  1237. // need to create a new island. So, we make a first guess, then walk through
  1238. // the instructions between the one currently being looked at and the
  1239. // possible insertion point, and make sure any other instructions that
  1240. // reference CPEs will be able to use the same island area; if not, we back
  1241. // up the insertion point.
  1242. // Try to split the block so it's fully aligned. Compute the latest split
  1243. // point where we can add a 4-byte branch instruction, and then align to
  1244. // Align which is the largest possible alignment in the function.
  1245. const Align Align = MF->getAlignment();
  1246. assert(Align >= CPEAlign && "Over-aligned constant pool entry");
  1247. unsigned KnownBits = UserBBI.internalKnownBits();
  1248. unsigned UPad = UnknownPadding(Align, KnownBits);
  1249. unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
  1250. LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
  1251. BaseInsertOffset));
  1252. // The 4 in the following is for the unconditional branch we'll be inserting
  1253. // (allows for long branch on Thumb1). Alignment of the island is handled
  1254. // inside isOffsetInRange.
  1255. BaseInsertOffset -= 4;
  1256. LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
  1257. << " la=" << Log2(Align) << " kb=" << KnownBits
  1258. << " up=" << UPad << '\n');
  1259. // This could point off the end of the block if we've already got constant
  1260. // pool entries following this block; only the last one is in the water list.
  1261. // Back past any possible branches (allow for a conditional and a maximally
  1262. // long unconditional).
  1263. if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
  1264. // Ensure BaseInsertOffset is larger than the offset of the instruction
  1265. // following UserMI so that the loop which searches for the split point
  1266. // iterates at least once.
  1267. BaseInsertOffset =
  1268. std::max(UserBBI.postOffset() - UPad - 8,
  1269. UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
  1270. // If the CP is referenced(ie, UserOffset) is in first four instructions
  1271. // after IT, this recalculated BaseInsertOffset could be in the middle of
  1272. // an IT block. If it is, change the BaseInsertOffset to just after the
  1273. // IT block. This still make the CP Entry is in range becuase of the
  1274. // following reasons.
  1275. // 1. The initial BaseseInsertOffset calculated is (UserOffset +
  1276. // U.getMaxDisp() - UPad).
  1277. // 2. An IT block is only at most 4 instructions plus the "it" itself (18
  1278. // bytes).
  1279. // 3. All the relevant instructions support much larger Maximum
  1280. // displacement.
  1281. MachineBasicBlock::iterator I = UserMI;
  1282. ++I;
  1283. Register PredReg;
  1284. for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
  1285. I->getOpcode() != ARM::t2IT &&
  1286. getITInstrPredicate(*I, PredReg) != ARMCC::AL;
  1287. Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {
  1288. BaseInsertOffset =
  1289. std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);
  1290. assert(I != UserMBB->end() && "Fell off end of block");
  1291. }
  1292. LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
  1293. }
  1294. unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
  1295. CPEMI->getOperand(2).getImm();
  1296. MachineBasicBlock::iterator MI = UserMI;
  1297. ++MI;
  1298. unsigned CPUIndex = CPUserIndex+1;
  1299. unsigned NumCPUsers = CPUsers.size();
  1300. MachineInstr *LastIT = nullptr;
  1301. for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
  1302. Offset < BaseInsertOffset;
  1303. Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
  1304. assert(MI != UserMBB->end() && "Fell off end of block");
  1305. if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
  1306. CPUser &U = CPUsers[CPUIndex];
  1307. if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
  1308. // Shift intertion point by one unit of alignment so it is within reach.
  1309. BaseInsertOffset -= Align.value();
  1310. EndInsertOffset -= Align.value();
  1311. }
  1312. // This is overly conservative, as we don't account for CPEMIs being
  1313. // reused within the block, but it doesn't matter much. Also assume CPEs
  1314. // are added in order with alignment padding. We may eventually be able
  1315. // to pack the aligned CPEs better.
  1316. EndInsertOffset += U.CPEMI->getOperand(2).getImm();
  1317. CPUIndex++;
  1318. }
  1319. // Remember the last IT instruction.
  1320. if (MI->getOpcode() == ARM::t2IT)
  1321. LastIT = &*MI;
  1322. }
  1323. --MI;
  1324. // Avoid splitting an IT block.
  1325. if (LastIT) {
  1326. Register PredReg;
  1327. ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
  1328. if (CC != ARMCC::AL)
  1329. MI = LastIT;
  1330. }
  1331. // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
  1332. // On Windows, this instruction pair is covered by one single
  1333. // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
  1334. // constant island is injected inbetween them, the relocation will clobber
  1335. // the instruction and fail to update the MOVT instruction.
  1336. // (These instructions are bundled up until right before the ConstantIslands
  1337. // pass.)
  1338. if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
  1339. (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
  1340. ARMII::MO_HI16) {
  1341. --MI;
  1342. assert(MI->getOpcode() == ARM::t2MOVi16 &&
  1343. (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
  1344. ARMII::MO_LO16);
  1345. }
  1346. // We really must not split an IT block.
  1347. #ifndef NDEBUG
  1348. Register PredReg;
  1349. assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);
  1350. #endif
  1351. NewMBB = splitBlockBeforeInstr(&*MI);
  1352. }
  1353. /// handleConstantPoolUser - Analyze the specified user, checking to see if it
  1354. /// is out-of-range. If so, pick up the constant pool value and move it some
  1355. /// place in-range. Return true if we changed any addresses (thus must run
  1356. /// another pass of branch lengthening), false otherwise.
  1357. bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
  1358. bool CloserWater) {
  1359. CPUser &U = CPUsers[CPUserIndex];
  1360. MachineInstr *UserMI = U.MI;
  1361. MachineInstr *CPEMI = U.CPEMI;
  1362. unsigned CPI = getCombinedIndex(CPEMI);
  1363. unsigned Size = CPEMI->getOperand(2).getImm();
  1364. // Compute this only once, it's expensive.
  1365. unsigned UserOffset = getUserOffset(U);
  1366. // See if the current entry is within range, or there is a clone of it
  1367. // in range.
  1368. int result = findInRangeCPEntry(U, UserOffset);
  1369. if (result==1) return false;
  1370. else if (result==2) return true;
  1371. // No existing clone of this CPE is within range.
  1372. // We will be generating a new clone. Get a UID for it.
  1373. unsigned ID = AFI->createPICLabelUId();
  1374. // Look for water where we can place this CPE.
  1375. MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
  1376. MachineBasicBlock *NewMBB;
  1377. water_iterator IP;
  1378. if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
  1379. LLVM_DEBUG(dbgs() << "Found water in range\n");
  1380. MachineBasicBlock *WaterBB = *IP;
  1381. // If the original WaterList entry was "new water" on this iteration,
  1382. // propagate that to the new island. This is just keeping NewWaterList
  1383. // updated to match the WaterList, which will be updated below.
  1384. if (NewWaterList.erase(WaterBB))
  1385. NewWaterList.insert(NewIsland);
  1386. // The new CPE goes before the following block (NewMBB).
  1387. NewMBB = &*++WaterBB->getIterator();
  1388. } else {
  1389. // No water found.
  1390. LLVM_DEBUG(dbgs() << "No water found\n");
  1391. createNewWater(CPUserIndex, UserOffset, NewMBB);
  1392. // splitBlockBeforeInstr adds to WaterList, which is important when it is
  1393. // called while handling branches so that the water will be seen on the
  1394. // next iteration for constant pools, but in this context, we don't want
  1395. // it. Check for this so it will be removed from the WaterList.
  1396. // Also remove any entry from NewWaterList.
  1397. MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
  1398. IP = find(WaterList, WaterBB);
  1399. if (IP != WaterList.end())
  1400. NewWaterList.erase(WaterBB);
  1401. // We are adding new water. Update NewWaterList.
  1402. NewWaterList.insert(NewIsland);
  1403. }
  1404. // Always align the new block because CP entries can be smaller than 4
  1405. // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
  1406. // be an already aligned constant pool block.
  1407. const Align Alignment = isThumb ? Align(2) : Align(4);
  1408. if (NewMBB->getAlignment() < Alignment)
  1409. NewMBB->setAlignment(Alignment);
  1410. // Remove the original WaterList entry; we want subsequent insertions in
  1411. // this vicinity to go after the one we're about to insert. This
  1412. // considerably reduces the number of times we have to move the same CPE
  1413. // more than once and is also important to ensure the algorithm terminates.
  1414. if (IP != WaterList.end())
  1415. WaterList.erase(IP);
  1416. // Okay, we know we can put an island before NewMBB now, do it!
  1417. MF->insert(NewMBB->getIterator(), NewIsland);
  1418. // Update internal data structures to account for the newly inserted MBB.
  1419. updateForInsertedWaterBlock(NewIsland);
  1420. // Now that we have an island to add the CPE to, clone the original CPE and
  1421. // add it to the island.
  1422. U.HighWaterMark = NewIsland;
  1423. U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
  1424. .addImm(ID)
  1425. .add(CPEMI->getOperand(1))
  1426. .addImm(Size);
  1427. CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
  1428. ++NumCPEs;
  1429. // Decrement the old entry, and remove it if refcount becomes 0.
  1430. decrementCPEReferenceCount(CPI, CPEMI);
  1431. // Mark the basic block as aligned as required by the const-pool entry.
  1432. NewIsland->setAlignment(getCPEAlign(U.CPEMI));
  1433. // Increase the size of the island block to account for the new entry.
  1434. BBUtils->adjustBBSize(NewIsland, Size);
  1435. BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
  1436. // Finally, change the CPI in the instruction operand to be ID.
  1437. for (MachineOperand &MO : UserMI->operands())
  1438. if (MO.isCPI()) {
  1439. MO.setIndex(ID);
  1440. break;
  1441. }
  1442. LLVM_DEBUG(
  1443. dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
  1444. << format(" offset=%#x\n",
  1445. BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
  1446. return true;
  1447. }
  1448. /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
  1449. /// sizes and offsets of impacted basic blocks.
  1450. void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
  1451. MachineBasicBlock *CPEBB = CPEMI->getParent();
  1452. unsigned Size = CPEMI->getOperand(2).getImm();
  1453. CPEMI->eraseFromParent();
  1454. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1455. BBUtils->adjustBBSize(CPEBB, -Size);
  1456. // All succeeding offsets have the current size value added in, fix this.
  1457. if (CPEBB->empty()) {
  1458. BBInfo[CPEBB->getNumber()].Size = 0;
  1459. // This block no longer needs to be aligned.
  1460. CPEBB->setAlignment(Align(1));
  1461. } else {
  1462. // Entries are sorted by descending alignment, so realign from the front.
  1463. CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin()));
  1464. }
  1465. BBUtils->adjustBBOffsetsAfter(CPEBB);
  1466. // An island has only one predecessor BB and one successor BB. Check if
  1467. // this BB's predecessor jumps directly to this BB's successor. This
  1468. // shouldn't happen currently.
  1469. assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
  1470. // FIXME: remove the empty blocks after all the work is done?
  1471. }
  1472. /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
  1473. /// are zero.
  1474. bool ARMConstantIslands::removeUnusedCPEntries() {
  1475. unsigned MadeChange = false;
  1476. for (std::vector<CPEntry> &CPEs : CPEntries) {
  1477. for (CPEntry &CPE : CPEs) {
  1478. if (CPE.RefCount == 0 && CPE.CPEMI) {
  1479. removeDeadCPEMI(CPE.CPEMI);
  1480. CPE.CPEMI = nullptr;
  1481. MadeChange = true;
  1482. }
  1483. }
  1484. }
  1485. return MadeChange;
  1486. }
  1487. /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
  1488. /// away to fit in its displacement field.
  1489. bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
  1490. MachineInstr *MI = Br.MI;
  1491. MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
  1492. // Check to see if the DestBB is already in-range.
  1493. if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
  1494. return false;
  1495. if (!Br.isCond)
  1496. return fixupUnconditionalBr(Br);
  1497. return fixupConditionalBr(Br);
  1498. }
  1499. /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
  1500. /// too far away to fit in its displacement field. If the LR register has been
  1501. /// spilled in the epilogue, then we can use BL to implement a far jump.
  1502. /// Otherwise, add an intermediate branch instruction to a branch.
  1503. bool
  1504. ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
  1505. MachineInstr *MI = Br.MI;
  1506. MachineBasicBlock *MBB = MI->getParent();
  1507. if (!isThumb1)
  1508. llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
  1509. if (!AFI->isLRSpilled())
  1510. report_fatal_error("underestimated function size");
  1511. // Use BL to implement far jump.
  1512. Br.MaxDisp = (1 << 21) * 2;
  1513. MI->setDesc(TII->get(ARM::tBfar));
  1514. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1515. BBInfo[MBB->getNumber()].Size += 2;
  1516. BBUtils->adjustBBOffsetsAfter(MBB);
  1517. ++NumUBrFixed;
  1518. LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
  1519. return true;
  1520. }
  1521. /// fixupConditionalBr - Fix up a conditional branch whose destination is too
  1522. /// far away to fit in its displacement field. It is converted to an inverse
  1523. /// conditional branch + an unconditional branch to the destination.
  1524. bool
  1525. ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
  1526. MachineInstr *MI = Br.MI;
  1527. MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
  1528. // Add an unconditional branch to the destination and invert the branch
  1529. // condition to jump over it:
  1530. // blt L1
  1531. // =>
  1532. // bge L2
  1533. // b L1
  1534. // L2:
  1535. ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
  1536. CC = ARMCC::getOppositeCondition(CC);
  1537. Register CCReg = MI->getOperand(2).getReg();
  1538. // If the branch is at the end of its MBB and that has a fall-through block,
  1539. // direct the updated conditional branch to the fall-through block. Otherwise,
  1540. // split the MBB before the next instruction.
  1541. MachineBasicBlock *MBB = MI->getParent();
  1542. MachineInstr *BMI = &MBB->back();
  1543. bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
  1544. ++NumCBrFixed;
  1545. if (BMI != MI) {
  1546. if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
  1547. BMI->getOpcode() == Br.UncondBr) {
  1548. // Last MI in the BB is an unconditional branch. Can we simply invert the
  1549. // condition and swap destinations:
  1550. // beq L1
  1551. // b L2
  1552. // =>
  1553. // bne L2
  1554. // b L1
  1555. MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
  1556. if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
  1557. LLVM_DEBUG(
  1558. dbgs() << " Invert Bcc condition and swap its destination with "
  1559. << *BMI);
  1560. BMI->getOperand(0).setMBB(DestBB);
  1561. MI->getOperand(0).setMBB(NewDest);
  1562. MI->getOperand(1).setImm(CC);
  1563. return true;
  1564. }
  1565. }
  1566. }
  1567. if (NeedSplit) {
  1568. splitBlockBeforeInstr(MI);
  1569. // No need for the branch to the next block. We're adding an unconditional
  1570. // branch to the destination.
  1571. int delta = TII->getInstSizeInBytes(MBB->back());
  1572. BBUtils->adjustBBSize(MBB, -delta);
  1573. MBB->back().eraseFromParent();
  1574. // The conditional successor will be swapped between the BBs after this, so
  1575. // update CFG.
  1576. MBB->addSuccessor(DestBB);
  1577. std::next(MBB->getIterator())->removeSuccessor(DestBB);
  1578. // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
  1579. }
  1580. MachineBasicBlock *NextBB = &*++MBB->getIterator();
  1581. LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
  1582. << " also invert condition and change dest. to "
  1583. << printMBBReference(*NextBB) << "\n");
  1584. // Insert a new conditional branch and a new unconditional branch.
  1585. // Also update the ImmBranch as well as adding a new entry for the new branch.
  1586. BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
  1587. .addMBB(NextBB).addImm(CC).addReg(CCReg);
  1588. Br.MI = &MBB->back();
  1589. BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
  1590. if (isThumb)
  1591. BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
  1592. .addMBB(DestBB)
  1593. .add(predOps(ARMCC::AL));
  1594. else
  1595. BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
  1596. BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
  1597. unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
  1598. ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
  1599. // Remove the old conditional branch. It may or may not still be in MBB.
  1600. BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
  1601. MI->eraseFromParent();
  1602. BBUtils->adjustBBOffsetsAfter(MBB);
  1603. return true;
  1604. }
  1605. bool ARMConstantIslands::optimizeThumb2Instructions() {
  1606. bool MadeChange = false;
  1607. // Shrink ADR and LDR from constantpool.
  1608. for (CPUser &U : CPUsers) {
  1609. unsigned Opcode = U.MI->getOpcode();
  1610. unsigned NewOpc = 0;
  1611. unsigned Scale = 1;
  1612. unsigned Bits = 0;
  1613. switch (Opcode) {
  1614. default: break;
  1615. case ARM::t2LEApcrel:
  1616. if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
  1617. NewOpc = ARM::tLEApcrel;
  1618. Bits = 8;
  1619. Scale = 4;
  1620. }
  1621. break;
  1622. case ARM::t2LDRpci:
  1623. if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
  1624. NewOpc = ARM::tLDRpci;
  1625. Bits = 8;
  1626. Scale = 4;
  1627. }
  1628. break;
  1629. }
  1630. if (!NewOpc)
  1631. continue;
  1632. unsigned UserOffset = getUserOffset(U);
  1633. unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
  1634. // Be conservative with inline asm.
  1635. if (!U.KnownAlignment)
  1636. MaxOffs -= 2;
  1637. // FIXME: Check if offset is multiple of scale if scale is not 4.
  1638. if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
  1639. LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
  1640. U.MI->setDesc(TII->get(NewOpc));
  1641. MachineBasicBlock *MBB = U.MI->getParent();
  1642. BBUtils->adjustBBSize(MBB, -2);
  1643. BBUtils->adjustBBOffsetsAfter(MBB);
  1644. ++NumT2CPShrunk;
  1645. MadeChange = true;
  1646. }
  1647. }
  1648. return MadeChange;
  1649. }
  1650. bool ARMConstantIslands::optimizeThumb2Branches() {
  1651. auto TryShrinkBranch = [this](ImmBranch &Br) {
  1652. unsigned Opcode = Br.MI->getOpcode();
  1653. unsigned NewOpc = 0;
  1654. unsigned Scale = 1;
  1655. unsigned Bits = 0;
  1656. switch (Opcode) {
  1657. default: break;
  1658. case ARM::t2B:
  1659. NewOpc = ARM::tB;
  1660. Bits = 11;
  1661. Scale = 2;
  1662. break;
  1663. case ARM::t2Bcc:
  1664. NewOpc = ARM::tBcc;
  1665. Bits = 8;
  1666. Scale = 2;
  1667. break;
  1668. }
  1669. if (NewOpc) {
  1670. unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
  1671. MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
  1672. if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
  1673. LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
  1674. Br.MI->setDesc(TII->get(NewOpc));
  1675. MachineBasicBlock *MBB = Br.MI->getParent();
  1676. BBUtils->adjustBBSize(MBB, -2);
  1677. BBUtils->adjustBBOffsetsAfter(MBB);
  1678. ++NumT2BrShrunk;
  1679. return true;
  1680. }
  1681. }
  1682. return false;
  1683. };
  1684. struct ImmCompare {
  1685. MachineInstr* MI = nullptr;
  1686. unsigned NewOpc = 0;
  1687. };
  1688. auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,
  1689. MachineBasicBlock *DestBB) {
  1690. ImmCmp.MI = nullptr;
  1691. ImmCmp.NewOpc = 0;
  1692. // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
  1693. // so this transformation is not safe.
  1694. if (!Br.MI->killsRegister(ARM::CPSR))
  1695. return false;
  1696. Register PredReg;
  1697. unsigned NewOpc = 0;
  1698. ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
  1699. if (Pred == ARMCC::EQ)
  1700. NewOpc = ARM::tCBZ;
  1701. else if (Pred == ARMCC::NE)
  1702. NewOpc = ARM::tCBNZ;
  1703. else
  1704. return false;
  1705. // Check if the distance is within 126. Subtract starting offset by 2
  1706. // because the cmp will be eliminated.
  1707. unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
  1708. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1709. unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
  1710. if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
  1711. return false;
  1712. // Search backwards to find a tCMPi8
  1713. auto *TRI = STI->getRegisterInfo();
  1714. MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
  1715. if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
  1716. return false;
  1717. ImmCmp.MI = CmpMI;
  1718. ImmCmp.NewOpc = NewOpc;
  1719. return true;
  1720. };
  1721. auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {
  1722. if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() ||
  1723. STI->hasMinSize())
  1724. return false;
  1725. MachineBasicBlock *MBB = Br.MI->getParent();
  1726. MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
  1727. if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||
  1728. !BBUtils->isBBInRange(Br.MI, DestBB, 4094))
  1729. return false;
  1730. if (!DT->dominates(DestBB, MBB))
  1731. return false;
  1732. // We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite
  1733. // target of Br. So now we need to reverse the condition.
  1734. Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;
  1735. MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),
  1736. TII->get(ARM::t2LE));
  1737. // Swapped a t2Bcc for a t2LE, so no need to update the size of the block.
  1738. MIB.add(Br.MI->getOperand(0));
  1739. Br.MI->eraseFromParent();
  1740. Br.MI = MIB;
  1741. ++NumLEInserted;
  1742. return true;
  1743. };
  1744. bool MadeChange = false;
  1745. // The order in which branches appear in ImmBranches is approximately their
  1746. // order within the function body. By visiting later branches first, we reduce
  1747. // the distance between earlier forward branches and their targets, making it
  1748. // more likely that the cbn?z optimization, which can only apply to forward
  1749. // branches, will succeed.
  1750. for (ImmBranch &Br : reverse(ImmBranches)) {
  1751. MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
  1752. MachineBasicBlock *MBB = Br.MI->getParent();
  1753. MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?
  1754. MBB->getFallThrough() :
  1755. MBB->back().getOperand(0).getMBB();
  1756. ImmCompare Cmp;
  1757. if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {
  1758. DestBB = ExitBB;
  1759. MadeChange = true;
  1760. } else {
  1761. FindCmpForCBZ(Br, Cmp, DestBB);
  1762. MadeChange |= TryShrinkBranch(Br);
  1763. }
  1764. unsigned Opcode = Br.MI->getOpcode();
  1765. if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)
  1766. continue;
  1767. Register Reg = Cmp.MI->getOperand(0).getReg();
  1768. // Check for Kill flags on Reg. If they are present remove them and set kill
  1769. // on the new CBZ.
  1770. auto *TRI = STI->getRegisterInfo();
  1771. MachineBasicBlock::iterator KillMI = Br.MI;
  1772. bool RegKilled = false;
  1773. do {
  1774. --KillMI;
  1775. if (KillMI->killsRegister(Reg, TRI)) {
  1776. KillMI->clearRegisterKills(Reg, TRI);
  1777. RegKilled = true;
  1778. break;
  1779. }
  1780. } while (KillMI != Cmp.MI);
  1781. // Create the new CBZ/CBNZ
  1782. LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);
  1783. MachineInstr *NewBR =
  1784. BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))
  1785. .addReg(Reg, getKillRegState(RegKilled) |
  1786. getRegState(Cmp.MI->getOperand(0)))
  1787. .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
  1788. Cmp.MI->eraseFromParent();
  1789. if (Br.MI->getOpcode() == ARM::tBcc) {
  1790. Br.MI->eraseFromParent();
  1791. Br.MI = NewBR;
  1792. BBUtils->adjustBBSize(MBB, -2);
  1793. } else if (MBB->back().getOpcode() != ARM::t2LE) {
  1794. // An LE has been generated, but it's not the terminator - that is an
  1795. // unconditional branch. However, the logic has now been reversed with the
  1796. // CBN?Z being the conditional branch and the LE being the unconditional
  1797. // branch. So this means we can remove the redundant unconditional branch
  1798. // at the end of the block.
  1799. MachineInstr *LastMI = &MBB->back();
  1800. BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize());
  1801. LastMI->eraseFromParent();
  1802. }
  1803. BBUtils->adjustBBOffsetsAfter(MBB);
  1804. ++NumCBZ;
  1805. MadeChange = true;
  1806. }
  1807. return MadeChange;
  1808. }
  1809. static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
  1810. unsigned BaseReg) {
  1811. if (I.getOpcode() != ARM::t2ADDrs)
  1812. return false;
  1813. if (I.getOperand(0).getReg() != EntryReg)
  1814. return false;
  1815. if (I.getOperand(1).getReg() != BaseReg)
  1816. return false;
  1817. // FIXME: what about CC and IdxReg?
  1818. return true;
  1819. }
  1820. /// While trying to form a TBB/TBH instruction, we may (if the table
  1821. /// doesn't immediately follow the BR_JT) need access to the start of the
  1822. /// jump-table. We know one instruction that produces such a register; this
  1823. /// function works out whether that definition can be preserved to the BR_JT,
  1824. /// possibly by removing an intervening addition (which is usually needed to
  1825. /// calculate the actual entry to jump to).
  1826. bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
  1827. MachineInstr *LEAMI,
  1828. unsigned &DeadSize,
  1829. bool &CanDeleteLEA,
  1830. bool &BaseRegKill) {
  1831. if (JumpMI->getParent() != LEAMI->getParent())
  1832. return false;
  1833. // Now we hope that we have at least these instructions in the basic block:
  1834. // BaseReg = t2LEA ...
  1835. // [...]
  1836. // EntryReg = t2ADDrs BaseReg, ...
  1837. // [...]
  1838. // t2BR_JT EntryReg
  1839. //
  1840. // We have to be very conservative about what we recognise here though. The
  1841. // main perturbing factors to watch out for are:
  1842. // + Spills at any point in the chain: not direct problems but we would
  1843. // expect a blocking Def of the spilled register so in practice what we
  1844. // can do is limited.
  1845. // + EntryReg == BaseReg: this is the one situation we should allow a Def
  1846. // of BaseReg, but only if the t2ADDrs can be removed.
  1847. // + Some instruction other than t2ADDrs computing the entry. Not seen in
  1848. // the wild, but we should be careful.
  1849. Register EntryReg = JumpMI->getOperand(0).getReg();
  1850. Register BaseReg = LEAMI->getOperand(0).getReg();
  1851. CanDeleteLEA = true;
  1852. BaseRegKill = false;
  1853. MachineInstr *RemovableAdd = nullptr;
  1854. MachineBasicBlock::iterator I(LEAMI);
  1855. for (++I; &*I != JumpMI; ++I) {
  1856. if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
  1857. RemovableAdd = &*I;
  1858. break;
  1859. }
  1860. for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
  1861. const MachineOperand &MO = I->getOperand(K);
  1862. if (!MO.isReg() || !MO.getReg())
  1863. continue;
  1864. if (MO.isDef() && MO.getReg() == BaseReg)
  1865. return false;
  1866. if (MO.isUse() && MO.getReg() == BaseReg) {
  1867. BaseRegKill = BaseRegKill || MO.isKill();
  1868. CanDeleteLEA = false;
  1869. }
  1870. }
  1871. }
  1872. if (!RemovableAdd)
  1873. return true;
  1874. // Check the add really is removable, and that nothing else in the block
  1875. // clobbers BaseReg.
  1876. for (++I; &*I != JumpMI; ++I) {
  1877. for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
  1878. const MachineOperand &MO = I->getOperand(K);
  1879. if (!MO.isReg() || !MO.getReg())
  1880. continue;
  1881. if (MO.isDef() && MO.getReg() == BaseReg)
  1882. return false;
  1883. if (MO.isUse() && MO.getReg() == EntryReg)
  1884. RemovableAdd = nullptr;
  1885. }
  1886. }
  1887. if (RemovableAdd) {
  1888. RemovableAdd->eraseFromParent();
  1889. DeadSize += isThumb2 ? 4 : 2;
  1890. } else if (BaseReg == EntryReg) {
  1891. // The add wasn't removable, but clobbered the base for the TBB. So we can't
  1892. // preserve it.
  1893. return false;
  1894. }
  1895. // We reached the end of the block without seeing another definition of
  1896. // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
  1897. // used in the TBB/TBH if necessary.
  1898. return true;
  1899. }
  1900. /// Returns whether CPEMI is the first instruction in the block
  1901. /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
  1902. /// we can switch the first register to PC and usually remove the address
  1903. /// calculation that preceded it.
  1904. static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
  1905. MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
  1906. MachineFunction *MF = MBB->getParent();
  1907. ++MBB;
  1908. return MBB != MF->end() && !MBB->empty() && &*MBB->begin() == CPEMI;
  1909. }
  1910. static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
  1911. MachineInstr *JumpMI,
  1912. unsigned &DeadSize) {
  1913. // Remove a dead add between the LEA and JT, which used to compute EntryReg,
  1914. // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
  1915. // and is not clobbered / used.
  1916. MachineInstr *RemovableAdd = nullptr;
  1917. Register EntryReg = JumpMI->getOperand(0).getReg();
  1918. // Find the last ADD to set EntryReg
  1919. MachineBasicBlock::iterator I(LEAMI);
  1920. for (++I; &*I != JumpMI; ++I) {
  1921. if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
  1922. RemovableAdd = &*I;
  1923. }
  1924. if (!RemovableAdd)
  1925. return;
  1926. // Ensure EntryReg is not clobbered or used.
  1927. MachineBasicBlock::iterator J(RemovableAdd);
  1928. for (++J; &*J != JumpMI; ++J) {
  1929. for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
  1930. const MachineOperand &MO = J->getOperand(K);
  1931. if (!MO.isReg() || !MO.getReg())
  1932. continue;
  1933. if (MO.isDef() && MO.getReg() == EntryReg)
  1934. return;
  1935. if (MO.isUse() && MO.getReg() == EntryReg)
  1936. return;
  1937. }
  1938. }
  1939. LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
  1940. RemovableAdd->eraseFromParent();
  1941. DeadSize += 4;
  1942. }
  1943. /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
  1944. /// jumptables when it's possible.
  1945. bool ARMConstantIslands::optimizeThumb2JumpTables() {
  1946. bool MadeChange = false;
  1947. // FIXME: After the tables are shrunk, can we get rid some of the
  1948. // constantpool tables?
  1949. MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
  1950. if (!MJTI) return false;
  1951. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  1952. for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
  1953. MachineInstr *MI = T2JumpTables[i];
  1954. const MCInstrDesc &MCID = MI->getDesc();
  1955. unsigned NumOps = MCID.getNumOperands();
  1956. unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
  1957. MachineOperand JTOP = MI->getOperand(JTOpIdx);
  1958. unsigned JTI = JTOP.getIndex();
  1959. assert(JTI < JT.size());
  1960. bool ByteOk = true;
  1961. bool HalfWordOk = true;
  1962. unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
  1963. const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
  1964. BBInfoVector &BBInfo = BBUtils->getBBInfo();
  1965. for (MachineBasicBlock *MBB : JTBBs) {
  1966. unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
  1967. // Negative offset is not ok. FIXME: We should change BB layout to make
  1968. // sure all the branches are forward.
  1969. if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
  1970. ByteOk = false;
  1971. unsigned TBHLimit = ((1<<16)-1)*2;
  1972. if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
  1973. HalfWordOk = false;
  1974. if (!ByteOk && !HalfWordOk)
  1975. break;
  1976. }
  1977. if (!ByteOk && !HalfWordOk)
  1978. continue;
  1979. CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
  1980. MachineBasicBlock *MBB = MI->getParent();
  1981. if (!MI->getOperand(0).isKill()) // FIXME: needed now?
  1982. continue;
  1983. unsigned DeadSize = 0;
  1984. bool CanDeleteLEA = false;
  1985. bool BaseRegKill = false;
  1986. unsigned IdxReg = ~0U;
  1987. bool IdxRegKill = true;
  1988. if (isThumb2) {
  1989. IdxReg = MI->getOperand(1).getReg();
  1990. IdxRegKill = MI->getOperand(1).isKill();
  1991. bool PreservedBaseReg =
  1992. preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
  1993. if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
  1994. continue;
  1995. } else {
  1996. // We're in thumb-1 mode, so we must have something like:
  1997. // %idx = tLSLri %idx, 2
  1998. // %base = tLEApcrelJT
  1999. // %t = tLDRr %base, %idx
  2000. Register BaseReg = User.MI->getOperand(0).getReg();
  2001. if (User.MI->getIterator() == User.MI->getParent()->begin())
  2002. continue;
  2003. MachineInstr *Shift = User.MI->getPrevNode();
  2004. if (Shift->getOpcode() != ARM::tLSLri ||
  2005. Shift->getOperand(3).getImm() != 2 ||
  2006. !Shift->getOperand(2).isKill())
  2007. continue;
  2008. IdxReg = Shift->getOperand(2).getReg();
  2009. Register ShiftedIdxReg = Shift->getOperand(0).getReg();
  2010. // It's important that IdxReg is live until the actual TBB/TBH. Most of
  2011. // the range is checked later, but the LEA might still clobber it and not
  2012. // actually get removed.
  2013. if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
  2014. continue;
  2015. MachineInstr *Load = User.MI->getNextNode();
  2016. if (Load->getOpcode() != ARM::tLDRr)
  2017. continue;
  2018. if (Load->getOperand(1).getReg() != BaseReg ||
  2019. Load->getOperand(2).getReg() != ShiftedIdxReg ||
  2020. !Load->getOperand(2).isKill())
  2021. continue;
  2022. // If we're in PIC mode, there should be another ADD following.
  2023. auto *TRI = STI->getRegisterInfo();
  2024. // %base cannot be redefined after the load as it will appear before
  2025. // TBB/TBH like:
  2026. // %base =
  2027. // %base =
  2028. // tBB %base, %idx
  2029. if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
  2030. continue;
  2031. if (isPositionIndependentOrROPI) {
  2032. MachineInstr *Add = Load->getNextNode();
  2033. if (Add->getOpcode() != ARM::tADDrr ||
  2034. Add->getOperand(2).getReg() != BaseReg ||
  2035. Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
  2036. !Add->getOperand(3).isKill())
  2037. continue;
  2038. if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
  2039. continue;
  2040. if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
  2041. // IdxReg gets redefined in the middle of the sequence.
  2042. continue;
  2043. Add->eraseFromParent();
  2044. DeadSize += 2;
  2045. } else {
  2046. if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
  2047. continue;
  2048. if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
  2049. // IdxReg gets redefined in the middle of the sequence.
  2050. continue;
  2051. }
  2052. // Now safe to delete the load and lsl. The LEA will be removed later.
  2053. CanDeleteLEA = true;
  2054. Shift->eraseFromParent();
  2055. Load->eraseFromParent();
  2056. DeadSize += 4;
  2057. }
  2058. LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
  2059. MachineInstr *CPEMI = User.CPEMI;
  2060. unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
  2061. if (!isThumb2)
  2062. Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
  2063. MachineBasicBlock::iterator MI_JT = MI;
  2064. MachineInstr *NewJTMI =
  2065. BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
  2066. .addReg(User.MI->getOperand(0).getReg(),
  2067. getKillRegState(BaseRegKill))
  2068. .addReg(IdxReg, getKillRegState(IdxRegKill))
  2069. .addJumpTableIndex(JTI, JTOP.getTargetFlags())
  2070. .addImm(CPEMI->getOperand(0).getImm());
  2071. LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
  2072. unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
  2073. CPEMI->setDesc(TII->get(JTOpc));
  2074. if (jumpTableFollowsTB(MI, User.CPEMI)) {
  2075. NewJTMI->getOperand(0).setReg(ARM::PC);
  2076. NewJTMI->getOperand(0).setIsKill(false);
  2077. if (CanDeleteLEA) {
  2078. if (isThumb2)
  2079. RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
  2080. User.MI->eraseFromParent();
  2081. DeadSize += isThumb2 ? 4 : 2;
  2082. // The LEA was eliminated, the TBB instruction becomes the only new user
  2083. // of the jump table.
  2084. User.MI = NewJTMI;
  2085. User.MaxDisp = 4;
  2086. User.NegOk = false;
  2087. User.IsSoImm = false;
  2088. User.KnownAlignment = false;
  2089. } else {
  2090. // The LEA couldn't be eliminated, so we must add another CPUser to
  2091. // record the TBB or TBH use.
  2092. int CPEntryIdx = JumpTableEntryIndices[JTI];
  2093. auto &CPEs = CPEntries[CPEntryIdx];
  2094. auto Entry =
  2095. find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
  2096. ++Entry->RefCount;
  2097. CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
  2098. }
  2099. }
  2100. unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
  2101. unsigned OrigSize = TII->getInstSizeInBytes(*MI);
  2102. MI->eraseFromParent();
  2103. int Delta = OrigSize - NewSize + DeadSize;
  2104. BBInfo[MBB->getNumber()].Size -= Delta;
  2105. BBUtils->adjustBBOffsetsAfter(MBB);
  2106. ++NumTBs;
  2107. MadeChange = true;
  2108. }
  2109. return MadeChange;
  2110. }
  2111. /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
  2112. /// jump tables always branch forwards, since that's what tbb and tbh need.
  2113. bool ARMConstantIslands::reorderThumb2JumpTables() {
  2114. bool MadeChange = false;
  2115. MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
  2116. if (!MJTI) return false;
  2117. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  2118. for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
  2119. MachineInstr *MI = T2JumpTables[i];
  2120. const MCInstrDesc &MCID = MI->getDesc();
  2121. unsigned NumOps = MCID.getNumOperands();
  2122. unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
  2123. MachineOperand JTOP = MI->getOperand(JTOpIdx);
  2124. unsigned JTI = JTOP.getIndex();
  2125. assert(JTI < JT.size());
  2126. // We prefer if target blocks for the jump table come after the jump
  2127. // instruction so we can use TB[BH]. Loop through the target blocks
  2128. // and try to adjust them such that that's true.
  2129. int JTNumber = MI->getParent()->getNumber();
  2130. const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
  2131. for (MachineBasicBlock *MBB : JTBBs) {
  2132. int DTNumber = MBB->getNumber();
  2133. if (DTNumber < JTNumber) {
  2134. // The destination precedes the switch. Try to move the block forward
  2135. // so we have a positive offset.
  2136. MachineBasicBlock *NewBB =
  2137. adjustJTTargetBlockForward(JTI, MBB, MI->getParent());
  2138. if (NewBB)
  2139. MJTI->ReplaceMBBInJumpTable(JTI, MBB, NewBB);
  2140. MadeChange = true;
  2141. }
  2142. }
  2143. }
  2144. return MadeChange;
  2145. }
  2146. void ARMConstantIslands::fixupBTI(unsigned JTI, MachineBasicBlock &OldBB,
  2147. MachineBasicBlock &NewBB) {
  2148. assert(isThumb2 && "BTI in Thumb1?");
  2149. // Insert a BTI instruction into NewBB
  2150. BuildMI(NewBB, NewBB.begin(), DebugLoc(), TII->get(ARM::t2BTI));
  2151. // Update jump table reference counts.
  2152. const MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
  2153. const MachineJumpTableEntry &JTE = MJTI.getJumpTables()[JTI];
  2154. for (const MachineBasicBlock *MBB : JTE.MBBs) {
  2155. if (MBB != &OldBB)
  2156. continue;
  2157. --BlockJumpTableRefCount[MBB];
  2158. ++BlockJumpTableRefCount[&NewBB];
  2159. }
  2160. // If the old basic block reference count dropped to zero, remove
  2161. // the BTI instruction at its beginning.
  2162. if (BlockJumpTableRefCount[&OldBB] > 0)
  2163. return;
  2164. // Skip meta instructions
  2165. auto BTIPos = llvm::find_if_not(OldBB.instrs(), [](const MachineInstr &MI) {
  2166. return MI.isMetaInstruction();
  2167. });
  2168. assert(BTIPos->getOpcode() == ARM::t2BTI &&
  2169. "BasicBlock is mentioned in a jump table but does start with BTI");
  2170. if (BTIPos->getOpcode() == ARM::t2BTI)
  2171. BTIPos->eraseFromParent();
  2172. }
  2173. MachineBasicBlock *ARMConstantIslands::adjustJTTargetBlockForward(
  2174. unsigned JTI, MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
  2175. // If the destination block is terminated by an unconditional branch,
  2176. // try to move it; otherwise, create a new block following the jump
  2177. // table that branches back to the actual target. This is a very simple
  2178. // heuristic. FIXME: We can definitely improve it.
  2179. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  2180. SmallVector<MachineOperand, 4> Cond;
  2181. SmallVector<MachineOperand, 4> CondPrior;
  2182. MachineFunction::iterator BBi = BB->getIterator();
  2183. MachineFunction::iterator OldPrior = std::prev(BBi);
  2184. MachineFunction::iterator OldNext = std::next(BBi);
  2185. // If the block terminator isn't analyzable, don't try to move the block
  2186. bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
  2187. // If the block ends in an unconditional branch, move it. The prior block
  2188. // has to have an analyzable terminator for us to move this one. Be paranoid
  2189. // and make sure we're not trying to move the entry block of the function.
  2190. if (!B && Cond.empty() && BB != &MF->front() &&
  2191. !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
  2192. BB->moveAfter(JTBB);
  2193. OldPrior->updateTerminator(BB);
  2194. BB->updateTerminator(OldNext != MF->end() ? &*OldNext : nullptr);
  2195. // Update numbering to account for the block being moved.
  2196. MF->RenumberBlocks();
  2197. ++NumJTMoved;
  2198. return nullptr;
  2199. }
  2200. // Create a new MBB for the code after the jump BB.
  2201. MachineBasicBlock *NewBB =
  2202. MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
  2203. MachineFunction::iterator MBBI = ++JTBB->getIterator();
  2204. MF->insert(MBBI, NewBB);
  2205. // Copy live-in information to new block.
  2206. for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())
  2207. NewBB->addLiveIn(RegMaskPair);
  2208. // Add an unconditional branch from NewBB to BB.
  2209. // There doesn't seem to be meaningful DebugInfo available; this doesn't
  2210. // correspond directly to anything in the source.
  2211. if (isThumb2)
  2212. BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
  2213. .addMBB(BB)
  2214. .add(predOps(ARMCC::AL));
  2215. else
  2216. BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
  2217. .addMBB(BB)
  2218. .add(predOps(ARMCC::AL));
  2219. // Update internal data structures to account for the newly inserted MBB.
  2220. MF->RenumberBlocks(NewBB);
  2221. // Update the CFG.
  2222. NewBB->addSuccessor(BB);
  2223. JTBB->replaceSuccessor(BB, NewBB);
  2224. if (MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement())
  2225. fixupBTI(JTI, *BB, *NewBB);
  2226. ++NumJTInserted;
  2227. return NewBB;
  2228. }
  2229. /// createARMConstantIslandPass - returns an instance of the constpool
  2230. /// island pass.
  2231. FunctionPass *llvm::createARMConstantIslandPass() {
  2232. return new ARMConstantIslands();
  2233. }
  2234. INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
  2235. false, false)