ARMConstantIslandPass.cpp 93 KB

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