CodeGenPrepare.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/IR/CallSite.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Dominators.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/GetElementPtrTypeIterator.h"
  27. #include "llvm/IR/IRBuilder.h"
  28. #include "llvm/IR/InlineAsm.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/IntrinsicInst.h"
  31. #include "llvm/IR/PatternMatch.h"
  32. #include "llvm/IR/ValueHandle.h"
  33. #include "llvm/IR/ValueMap.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Target/TargetLibraryInfo.h"
  39. #include "llvm/Target/TargetLowering.h"
  40. #include "llvm/Target/TargetSubtargetInfo.h"
  41. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  42. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  43. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  44. #include "llvm/Transforms/Utils/Local.h"
  45. using namespace llvm;
  46. using namespace llvm::PatternMatch;
  47. #define DEBUG_TYPE "codegenprepare"
  48. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  49. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  50. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  51. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  52. "sunken Cmps");
  53. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  54. "of sunken Casts");
  55. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  56. "computations were sunk");
  57. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  58. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  59. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  60. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  61. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  62. STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
  63. static cl::opt<bool> DisableBranchOpts(
  64. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  65. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  66. static cl::opt<bool> DisableSelectToBranch(
  67. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  68. cl::desc("Disable select to branch conversion."));
  69. static cl::opt<bool> AddrSinkUsingGEPs(
  70. "addr-sink-using-gep", cl::Hidden, cl::init(false),
  71. cl::desc("Address sinking in CGP using GEPs."));
  72. static cl::opt<bool> EnableAndCmpSinking(
  73. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  74. cl::desc("Enable sinkinig and/cmp into branches."));
  75. namespace {
  76. typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
  77. typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
  78. class CodeGenPrepare : public FunctionPass {
  79. /// TLI - Keep a pointer of a TargetLowering to consult for determining
  80. /// transformation profitability.
  81. const TargetMachine *TM;
  82. const TargetLowering *TLI;
  83. const TargetLibraryInfo *TLInfo;
  84. DominatorTree *DT;
  85. /// CurInstIterator - As we scan instructions optimizing them, this is the
  86. /// next instruction to optimize. Xforms that can invalidate this should
  87. /// update it.
  88. BasicBlock::iterator CurInstIterator;
  89. /// Keeps track of non-local addresses that have been sunk into a block.
  90. /// This allows us to avoid inserting duplicate code for blocks with
  91. /// multiple load/stores of the same address.
  92. ValueMap<Value*, Value*> SunkAddrs;
  93. /// Keeps track of all truncates inserted for the current function.
  94. SetOfInstrs InsertedTruncsSet;
  95. /// Keeps track of the type of the related instruction before their
  96. /// promotion for the current function.
  97. InstrToOrigTy PromotedInsts;
  98. /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
  99. /// be updated.
  100. bool ModifiedDT;
  101. /// OptSize - True if optimizing for size.
  102. bool OptSize;
  103. public:
  104. static char ID; // Pass identification, replacement for typeid
  105. explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
  106. : FunctionPass(ID), TM(TM), TLI(nullptr) {
  107. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  108. }
  109. bool runOnFunction(Function &F) override;
  110. const char *getPassName() const override { return "CodeGen Prepare"; }
  111. void getAnalysisUsage(AnalysisUsage &AU) const override {
  112. AU.addPreserved<DominatorTreeWrapperPass>();
  113. AU.addRequired<TargetLibraryInfo>();
  114. }
  115. private:
  116. bool EliminateFallThrough(Function &F);
  117. bool EliminateMostlyEmptyBlocks(Function &F);
  118. bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  119. void EliminateMostlyEmptyBlock(BasicBlock *BB);
  120. bool OptimizeBlock(BasicBlock &BB);
  121. bool OptimizeInst(Instruction *I);
  122. bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
  123. bool OptimizeInlineAsmInst(CallInst *CS);
  124. bool OptimizeCallInst(CallInst *CI);
  125. bool MoveExtToFormExtLoad(Instruction *I);
  126. bool OptimizeExtUses(Instruction *I);
  127. bool OptimizeSelectInst(SelectInst *SI);
  128. bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
  129. bool DupRetToEnableTailCallOpts(BasicBlock *BB);
  130. bool PlaceDbgValues(Function &F);
  131. bool sinkAndCmp(Function &F);
  132. };
  133. }
  134. char CodeGenPrepare::ID = 0;
  135. INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
  136. "Optimize for code generation", false, false)
  137. FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
  138. return new CodeGenPrepare(TM);
  139. }
  140. bool CodeGenPrepare::runOnFunction(Function &F) {
  141. if (skipOptnoneFunction(F))
  142. return false;
  143. bool EverMadeChange = false;
  144. // Clear per function information.
  145. InsertedTruncsSet.clear();
  146. PromotedInsts.clear();
  147. ModifiedDT = false;
  148. if (TM)
  149. TLI = TM->getSubtargetImpl()->getTargetLowering();
  150. TLInfo = &getAnalysis<TargetLibraryInfo>();
  151. DominatorTreeWrapperPass *DTWP =
  152. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  153. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  154. OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  155. Attribute::OptimizeForSize);
  156. /// This optimization identifies DIV instructions that can be
  157. /// profitably bypassed and carried out with a shorter, faster divide.
  158. if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
  159. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  160. TLI->getBypassSlowDivWidths();
  161. for (Function::iterator I = F.begin(); I != F.end(); I++)
  162. EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
  163. }
  164. // Eliminate blocks that contain only PHI nodes and an
  165. // unconditional branch.
  166. EverMadeChange |= EliminateMostlyEmptyBlocks(F);
  167. // llvm.dbg.value is far away from the value then iSel may not be able
  168. // handle it properly. iSel will drop llvm.dbg.value if it can not
  169. // find a node corresponding to the value.
  170. EverMadeChange |= PlaceDbgValues(F);
  171. // If there is a mask, compare against zero, and branch that can be combined
  172. // into a single target instruction, push the mask and compare into branch
  173. // users. Do this before OptimizeBlock -> OptimizeInst ->
  174. // OptimizeCmpExpression, which perturbs the pattern being searched for.
  175. if (!DisableBranchOpts)
  176. EverMadeChange |= sinkAndCmp(F);
  177. bool MadeChange = true;
  178. while (MadeChange) {
  179. MadeChange = false;
  180. for (Function::iterator I = F.begin(); I != F.end(); ) {
  181. BasicBlock *BB = I++;
  182. MadeChange |= OptimizeBlock(*BB);
  183. }
  184. EverMadeChange |= MadeChange;
  185. }
  186. SunkAddrs.clear();
  187. if (!DisableBranchOpts) {
  188. MadeChange = false;
  189. SmallPtrSet<BasicBlock*, 8> WorkList;
  190. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  191. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  192. MadeChange |= ConstantFoldTerminator(BB, true);
  193. if (!MadeChange) continue;
  194. for (SmallVectorImpl<BasicBlock*>::iterator
  195. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  196. if (pred_begin(*II) == pred_end(*II))
  197. WorkList.insert(*II);
  198. }
  199. // Delete the dead blocks and any of their dead successors.
  200. MadeChange |= !WorkList.empty();
  201. while (!WorkList.empty()) {
  202. BasicBlock *BB = *WorkList.begin();
  203. WorkList.erase(BB);
  204. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  205. DeleteDeadBlock(BB);
  206. for (SmallVectorImpl<BasicBlock*>::iterator
  207. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  208. if (pred_begin(*II) == pred_end(*II))
  209. WorkList.insert(*II);
  210. }
  211. // Merge pairs of basic blocks with unconditional branches, connected by
  212. // a single edge.
  213. if (EverMadeChange || MadeChange)
  214. MadeChange |= EliminateFallThrough(F);
  215. if (MadeChange)
  216. ModifiedDT = true;
  217. EverMadeChange |= MadeChange;
  218. }
  219. if (ModifiedDT && DT)
  220. DT->recalculate(F);
  221. return EverMadeChange;
  222. }
  223. /// EliminateFallThrough - Merge basic blocks which are connected
  224. /// by a single edge, where one of the basic blocks has a single successor
  225. /// pointing to the other basic block, which has a single predecessor.
  226. bool CodeGenPrepare::EliminateFallThrough(Function &F) {
  227. bool Changed = false;
  228. // Scan all of the blocks in the function, except for the entry block.
  229. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  230. BasicBlock *BB = I++;
  231. // If the destination block has a single pred, then this is a trivial
  232. // edge, just collapse it.
  233. BasicBlock *SinglePred = BB->getSinglePredecessor();
  234. // Don't merge if BB's address is taken.
  235. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  236. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  237. if (Term && !Term->isConditional()) {
  238. Changed = true;
  239. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  240. // Remember if SinglePred was the entry block of the function.
  241. // If so, we will need to move BB back to the entry position.
  242. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  243. MergeBasicBlockIntoOnlyPred(BB, this);
  244. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  245. BB->moveBefore(&BB->getParent()->getEntryBlock());
  246. // We have erased a block. Update the iterator.
  247. I = BB;
  248. }
  249. }
  250. return Changed;
  251. }
  252. /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
  253. /// debug info directives, and an unconditional branch. Passes before isel
  254. /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
  255. /// isel. Start by eliminating these blocks so we can split them the way we
  256. /// want them.
  257. bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
  258. bool MadeChange = false;
  259. // Note that this intentionally skips the entry block.
  260. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  261. BasicBlock *BB = I++;
  262. // If this block doesn't end with an uncond branch, ignore it.
  263. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  264. if (!BI || !BI->isUnconditional())
  265. continue;
  266. // If the instruction before the branch (skipping debug info) isn't a phi
  267. // node, then other stuff is happening here.
  268. BasicBlock::iterator BBI = BI;
  269. if (BBI != BB->begin()) {
  270. --BBI;
  271. while (isa<DbgInfoIntrinsic>(BBI)) {
  272. if (BBI == BB->begin())
  273. break;
  274. --BBI;
  275. }
  276. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  277. continue;
  278. }
  279. // Do not break infinite loops.
  280. BasicBlock *DestBB = BI->getSuccessor(0);
  281. if (DestBB == BB)
  282. continue;
  283. if (!CanMergeBlocks(BB, DestBB))
  284. continue;
  285. EliminateMostlyEmptyBlock(BB);
  286. MadeChange = true;
  287. }
  288. return MadeChange;
  289. }
  290. /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
  291. /// single uncond branch between them, and BB contains no other non-phi
  292. /// instructions.
  293. bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
  294. const BasicBlock *DestBB) const {
  295. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  296. // the successor. If there are more complex condition (e.g. preheaders),
  297. // don't mess around with them.
  298. BasicBlock::const_iterator BBI = BB->begin();
  299. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  300. for (const User *U : PN->users()) {
  301. const Instruction *UI = cast<Instruction>(U);
  302. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  303. return false;
  304. // If User is inside DestBB block and it is a PHINode then check
  305. // incoming value. If incoming value is not from BB then this is
  306. // a complex condition (e.g. preheaders) we want to avoid here.
  307. if (UI->getParent() == DestBB) {
  308. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  309. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  310. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  311. if (Insn && Insn->getParent() == BB &&
  312. Insn->getParent() != UPN->getIncomingBlock(I))
  313. return false;
  314. }
  315. }
  316. }
  317. }
  318. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  319. // and DestBB may have conflicting incoming values for the block. If so, we
  320. // can't merge the block.
  321. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  322. if (!DestBBPN) return true; // no conflict.
  323. // Collect the preds of BB.
  324. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  325. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  326. // It is faster to get preds from a PHI than with pred_iterator.
  327. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  328. BBPreds.insert(BBPN->getIncomingBlock(i));
  329. } else {
  330. BBPreds.insert(pred_begin(BB), pred_end(BB));
  331. }
  332. // Walk the preds of DestBB.
  333. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  334. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  335. if (BBPreds.count(Pred)) { // Common predecessor?
  336. BBI = DestBB->begin();
  337. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  338. const Value *V1 = PN->getIncomingValueForBlock(Pred);
  339. const Value *V2 = PN->getIncomingValueForBlock(BB);
  340. // If V2 is a phi node in BB, look up what the mapped value will be.
  341. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  342. if (V2PN->getParent() == BB)
  343. V2 = V2PN->getIncomingValueForBlock(Pred);
  344. // If there is a conflict, bail out.
  345. if (V1 != V2) return false;
  346. }
  347. }
  348. }
  349. return true;
  350. }
  351. /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
  352. /// an unconditional branch in it.
  353. void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
  354. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  355. BasicBlock *DestBB = BI->getSuccessor(0);
  356. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  357. // If the destination block has a single pred, then this is a trivial edge,
  358. // just collapse it.
  359. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  360. if (SinglePred != DestBB) {
  361. // Remember if SinglePred was the entry block of the function. If so, we
  362. // will need to move BB back to the entry position.
  363. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  364. MergeBasicBlockIntoOnlyPred(DestBB, this);
  365. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  366. BB->moveBefore(&BB->getParent()->getEntryBlock());
  367. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  368. return;
  369. }
  370. }
  371. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  372. // to handle the new incoming edges it is about to have.
  373. PHINode *PN;
  374. for (BasicBlock::iterator BBI = DestBB->begin();
  375. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  376. // Remove the incoming value for BB, and remember it.
  377. Value *InVal = PN->removeIncomingValue(BB, false);
  378. // Two options: either the InVal is a phi node defined in BB or it is some
  379. // value that dominates BB.
  380. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  381. if (InValPhi && InValPhi->getParent() == BB) {
  382. // Add all of the input values of the input PHI as inputs of this phi.
  383. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  384. PN->addIncoming(InValPhi->getIncomingValue(i),
  385. InValPhi->getIncomingBlock(i));
  386. } else {
  387. // Otherwise, add one instance of the dominating value for each edge that
  388. // we will be adding.
  389. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  390. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  391. PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
  392. } else {
  393. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  394. PN->addIncoming(InVal, *PI);
  395. }
  396. }
  397. }
  398. // The PHIs are now updated, change everything that refers to BB to use
  399. // DestBB and remove BB.
  400. BB->replaceAllUsesWith(DestBB);
  401. if (DT && !ModifiedDT) {
  402. BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
  403. BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
  404. BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
  405. DT->changeImmediateDominator(DestBB, NewIDom);
  406. DT->eraseNode(BB);
  407. }
  408. BB->eraseFromParent();
  409. ++NumBlocksElim;
  410. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  411. }
  412. /// SinkCast - Sink the specified cast instruction into its user blocks
  413. static bool SinkCast(CastInst *CI) {
  414. BasicBlock *DefBB = CI->getParent();
  415. /// InsertedCasts - Only insert a cast in each block once.
  416. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  417. bool MadeChange = false;
  418. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  419. UI != E; ) {
  420. Use &TheUse = UI.getUse();
  421. Instruction *User = cast<Instruction>(*UI);
  422. // Figure out which BB this cast is used in. For PHI's this is the
  423. // appropriate predecessor block.
  424. BasicBlock *UserBB = User->getParent();
  425. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  426. UserBB = PN->getIncomingBlock(TheUse);
  427. }
  428. // Preincrement use iterator so we don't invalidate it.
  429. ++UI;
  430. // If this user is in the same block as the cast, don't change the cast.
  431. if (UserBB == DefBB) continue;
  432. // If we have already inserted a cast into this block, use it.
  433. CastInst *&InsertedCast = InsertedCasts[UserBB];
  434. if (!InsertedCast) {
  435. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  436. InsertedCast =
  437. CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
  438. InsertPt);
  439. MadeChange = true;
  440. }
  441. // Replace a use of the cast with a use of the new cast.
  442. TheUse = InsertedCast;
  443. ++NumCastUses;
  444. }
  445. // If we removed all uses, nuke the cast.
  446. if (CI->use_empty()) {
  447. CI->eraseFromParent();
  448. MadeChange = true;
  449. }
  450. return MadeChange;
  451. }
  452. /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
  453. /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
  454. /// sink it into user blocks to reduce the number of virtual
  455. /// registers that must be created and coalesced.
  456. ///
  457. /// Return true if any changes are made.
  458. ///
  459. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
  460. // If this is a noop copy,
  461. EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
  462. EVT DstVT = TLI.getValueType(CI->getType());
  463. // This is an fp<->int conversion?
  464. if (SrcVT.isInteger() != DstVT.isInteger())
  465. return false;
  466. // If this is an extension, it will be a zero or sign extension, which
  467. // isn't a noop.
  468. if (SrcVT.bitsLT(DstVT)) return false;
  469. // If these values will be promoted, find out what they will be promoted
  470. // to. This helps us consider truncates on PPC as noop copies when they
  471. // are.
  472. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  473. TargetLowering::TypePromoteInteger)
  474. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  475. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  476. TargetLowering::TypePromoteInteger)
  477. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  478. // If, after promotion, these are the same types, this is a noop copy.
  479. if (SrcVT != DstVT)
  480. return false;
  481. return SinkCast(CI);
  482. }
  483. /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
  484. /// the number of virtual registers that must be created and coalesced. This is
  485. /// a clear win except on targets with multiple condition code registers
  486. /// (PowerPC), where it might lose; some adjustment may be wanted there.
  487. ///
  488. /// Return true if any changes are made.
  489. static bool OptimizeCmpExpression(CmpInst *CI) {
  490. BasicBlock *DefBB = CI->getParent();
  491. /// InsertedCmp - Only insert a cmp in each block once.
  492. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  493. bool MadeChange = false;
  494. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  495. UI != E; ) {
  496. Use &TheUse = UI.getUse();
  497. Instruction *User = cast<Instruction>(*UI);
  498. // Preincrement use iterator so we don't invalidate it.
  499. ++UI;
  500. // Don't bother for PHI nodes.
  501. if (isa<PHINode>(User))
  502. continue;
  503. // Figure out which BB this cmp is used in.
  504. BasicBlock *UserBB = User->getParent();
  505. // If this user is in the same block as the cmp, don't change the cmp.
  506. if (UserBB == DefBB) continue;
  507. // If we have already inserted a cmp into this block, use it.
  508. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  509. if (!InsertedCmp) {
  510. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  511. InsertedCmp =
  512. CmpInst::Create(CI->getOpcode(),
  513. CI->getPredicate(), CI->getOperand(0),
  514. CI->getOperand(1), "", InsertPt);
  515. MadeChange = true;
  516. }
  517. // Replace a use of the cmp with a use of the new cmp.
  518. TheUse = InsertedCmp;
  519. ++NumCmpUses;
  520. }
  521. // If we removed all uses, nuke the cmp.
  522. if (CI->use_empty())
  523. CI->eraseFromParent();
  524. return MadeChange;
  525. }
  526. /// isExtractBitsCandidateUse - Check if the candidates could
  527. /// be combined with shift instruction, which includes:
  528. /// 1. Truncate instruction
  529. /// 2. And instruction and the imm is a mask of the low bits:
  530. /// imm & (imm+1) == 0
  531. static bool isExtractBitsCandidateUse(Instruction *User) {
  532. if (!isa<TruncInst>(User)) {
  533. if (User->getOpcode() != Instruction::And ||
  534. !isa<ConstantInt>(User->getOperand(1)))
  535. return false;
  536. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  537. if ((Cimm & (Cimm + 1)).getBoolValue())
  538. return false;
  539. }
  540. return true;
  541. }
  542. /// SinkShiftAndTruncate - sink both shift and truncate instruction
  543. /// to the use of truncate's BB.
  544. static bool
  545. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  546. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  547. const TargetLowering &TLI) {
  548. BasicBlock *UserBB = User->getParent();
  549. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  550. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  551. bool MadeChange = false;
  552. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  553. TruncE = TruncI->user_end();
  554. TruncUI != TruncE;) {
  555. Use &TruncTheUse = TruncUI.getUse();
  556. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  557. // Preincrement use iterator so we don't invalidate it.
  558. ++TruncUI;
  559. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  560. if (!ISDOpcode)
  561. continue;
  562. // If the use is actually a legal node, there will not be an
  563. // implicit truncate.
  564. // FIXME: always querying the result type is just an
  565. // approximation; some nodes' legality is determined by the
  566. // operand or other means. There's no good way to find out though.
  567. if (TLI.isOperationLegalOrCustom(ISDOpcode,
  568. EVT::getEVT(TruncUser->getType(), true)))
  569. continue;
  570. // Don't bother for PHI nodes.
  571. if (isa<PHINode>(TruncUser))
  572. continue;
  573. BasicBlock *TruncUserBB = TruncUser->getParent();
  574. if (UserBB == TruncUserBB)
  575. continue;
  576. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  577. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  578. if (!InsertedShift && !InsertedTrunc) {
  579. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  580. // Sink the shift
  581. if (ShiftI->getOpcode() == Instruction::AShr)
  582. InsertedShift =
  583. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  584. else
  585. InsertedShift =
  586. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  587. // Sink the trunc
  588. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  589. TruncInsertPt++;
  590. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  591. TruncI->getType(), "", TruncInsertPt);
  592. MadeChange = true;
  593. TruncTheUse = InsertedTrunc;
  594. }
  595. }
  596. return MadeChange;
  597. }
  598. /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
  599. /// the uses could potentially be combined with this shift instruction and
  600. /// generate BitExtract instruction. It will only be applied if the architecture
  601. /// supports BitExtract instruction. Here is an example:
  602. /// BB1:
  603. /// %x.extract.shift = lshr i64 %arg1, 32
  604. /// BB2:
  605. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  606. /// ==>
  607. ///
  608. /// BB2:
  609. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  610. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  611. ///
  612. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  613. /// instruction.
  614. /// Return true if any changes are made.
  615. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  616. const TargetLowering &TLI) {
  617. BasicBlock *DefBB = ShiftI->getParent();
  618. /// Only insert instructions in each block once.
  619. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  620. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
  621. bool MadeChange = false;
  622. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  623. UI != E;) {
  624. Use &TheUse = UI.getUse();
  625. Instruction *User = cast<Instruction>(*UI);
  626. // Preincrement use iterator so we don't invalidate it.
  627. ++UI;
  628. // Don't bother for PHI nodes.
  629. if (isa<PHINode>(User))
  630. continue;
  631. if (!isExtractBitsCandidateUse(User))
  632. continue;
  633. BasicBlock *UserBB = User->getParent();
  634. if (UserBB == DefBB) {
  635. // If the shift and truncate instruction are in the same BB. The use of
  636. // the truncate(TruncUse) may still introduce another truncate if not
  637. // legal. In this case, we would like to sink both shift and truncate
  638. // instruction to the BB of TruncUse.
  639. // for example:
  640. // BB1:
  641. // i64 shift.result = lshr i64 opnd, imm
  642. // trunc.result = trunc shift.result to i16
  643. //
  644. // BB2:
  645. // ----> We will have an implicit truncate here if the architecture does
  646. // not have i16 compare.
  647. // cmp i16 trunc.result, opnd2
  648. //
  649. if (isa<TruncInst>(User) && shiftIsLegal
  650. // If the type of the truncate is legal, no trucate will be
  651. // introduced in other basic blocks.
  652. && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
  653. MadeChange =
  654. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
  655. continue;
  656. }
  657. // If we have already inserted a shift into this block, use it.
  658. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  659. if (!InsertedShift) {
  660. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  661. if (ShiftI->getOpcode() == Instruction::AShr)
  662. InsertedShift =
  663. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  664. else
  665. InsertedShift =
  666. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  667. MadeChange = true;
  668. }
  669. // Replace a use of the shift with a use of the new shift.
  670. TheUse = InsertedShift;
  671. }
  672. // If we removed all uses, nuke the shift.
  673. if (ShiftI->use_empty())
  674. ShiftI->eraseFromParent();
  675. return MadeChange;
  676. }
  677. namespace {
  678. class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
  679. protected:
  680. void replaceCall(Value *With) override {
  681. CI->replaceAllUsesWith(With);
  682. CI->eraseFromParent();
  683. }
  684. bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
  685. if (ConstantInt *SizeCI =
  686. dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
  687. return SizeCI->isAllOnesValue();
  688. return false;
  689. }
  690. };
  691. } // end anonymous namespace
  692. bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
  693. BasicBlock *BB = CI->getParent();
  694. // Lower inline assembly if we can.
  695. // If we found an inline asm expession, and if the target knows how to
  696. // lower it to normal LLVM code, do so now.
  697. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  698. if (TLI->ExpandInlineAsm(CI)) {
  699. // Avoid invalidating the iterator.
  700. CurInstIterator = BB->begin();
  701. // Avoid processing instructions out of order, which could cause
  702. // reuse before a value is defined.
  703. SunkAddrs.clear();
  704. return true;
  705. }
  706. // Sink address computing for memory operands into the block.
  707. if (OptimizeInlineAsmInst(CI))
  708. return true;
  709. }
  710. // Lower all uses of llvm.objectsize.*
  711. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  712. if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
  713. bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
  714. Type *ReturnTy = CI->getType();
  715. Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
  716. // Substituting this can cause recursive simplifications, which can
  717. // invalidate our iterator. Use a WeakVH to hold onto it in case this
  718. // happens.
  719. WeakVH IterHandle(CurInstIterator);
  720. replaceAndRecursivelySimplify(CI, RetVal,
  721. TLI ? TLI->getDataLayout() : nullptr,
  722. TLInfo, ModifiedDT ? nullptr : DT);
  723. // If the iterator instruction was recursively deleted, start over at the
  724. // start of the block.
  725. if (IterHandle != CurInstIterator) {
  726. CurInstIterator = BB->begin();
  727. SunkAddrs.clear();
  728. }
  729. return true;
  730. }
  731. if (II && TLI) {
  732. SmallVector<Value*, 2> PtrOps;
  733. Type *AccessTy;
  734. if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
  735. while (!PtrOps.empty())
  736. if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
  737. return true;
  738. }
  739. // From here on out we're working with named functions.
  740. if (!CI->getCalledFunction()) return false;
  741. // We'll need DataLayout from here on out.
  742. const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
  743. if (!TD) return false;
  744. // Lower all default uses of _chk calls. This is very similar
  745. // to what InstCombineCalls does, but here we are only lowering calls
  746. // that have the default "don't know" as the objectsize. Anything else
  747. // should be left alone.
  748. CodeGenPrepareFortifiedLibCalls Simplifier;
  749. return Simplifier.fold(CI, TD, TLInfo);
  750. }
  751. /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
  752. /// instructions to the predecessor to enable tail call optimizations. The
  753. /// case it is currently looking for is:
  754. /// @code
  755. /// bb0:
  756. /// %tmp0 = tail call i32 @f0()
  757. /// br label %return
  758. /// bb1:
  759. /// %tmp1 = tail call i32 @f1()
  760. /// br label %return
  761. /// bb2:
  762. /// %tmp2 = tail call i32 @f2()
  763. /// br label %return
  764. /// return:
  765. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  766. /// ret i32 %retval
  767. /// @endcode
  768. ///
  769. /// =>
  770. ///
  771. /// @code
  772. /// bb0:
  773. /// %tmp0 = tail call i32 @f0()
  774. /// ret i32 %tmp0
  775. /// bb1:
  776. /// %tmp1 = tail call i32 @f1()
  777. /// ret i32 %tmp1
  778. /// bb2:
  779. /// %tmp2 = tail call i32 @f2()
  780. /// ret i32 %tmp2
  781. /// @endcode
  782. bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
  783. if (!TLI)
  784. return false;
  785. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  786. if (!RI)
  787. return false;
  788. PHINode *PN = nullptr;
  789. BitCastInst *BCI = nullptr;
  790. Value *V = RI->getReturnValue();
  791. if (V) {
  792. BCI = dyn_cast<BitCastInst>(V);
  793. if (BCI)
  794. V = BCI->getOperand(0);
  795. PN = dyn_cast<PHINode>(V);
  796. if (!PN)
  797. return false;
  798. }
  799. if (PN && PN->getParent() != BB)
  800. return false;
  801. // It's not safe to eliminate the sign / zero extension of the return value.
  802. // See llvm::isInTailCallPosition().
  803. const Function *F = BB->getParent();
  804. AttributeSet CallerAttrs = F->getAttributes();
  805. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
  806. CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
  807. return false;
  808. // Make sure there are no instructions between the PHI and return, or that the
  809. // return is the first instruction in the block.
  810. if (PN) {
  811. BasicBlock::iterator BI = BB->begin();
  812. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  813. if (&*BI == BCI)
  814. // Also skip over the bitcast.
  815. ++BI;
  816. if (&*BI != RI)
  817. return false;
  818. } else {
  819. BasicBlock::iterator BI = BB->begin();
  820. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  821. if (&*BI != RI)
  822. return false;
  823. }
  824. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  825. /// call.
  826. SmallVector<CallInst*, 4> TailCalls;
  827. if (PN) {
  828. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  829. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  830. // Make sure the phi value is indeed produced by the tail call.
  831. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  832. TLI->mayBeEmittedAsTailCall(CI))
  833. TailCalls.push_back(CI);
  834. }
  835. } else {
  836. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  837. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  838. if (!VisitedBBs.insert(*PI))
  839. continue;
  840. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  841. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  842. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  843. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  844. if (RI == RE)
  845. continue;
  846. CallInst *CI = dyn_cast<CallInst>(&*RI);
  847. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
  848. TailCalls.push_back(CI);
  849. }
  850. }
  851. bool Changed = false;
  852. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  853. CallInst *CI = TailCalls[i];
  854. CallSite CS(CI);
  855. // Conservatively require the attributes of the call to match those of the
  856. // return. Ignore noalias because it doesn't affect the call sequence.
  857. AttributeSet CalleeAttrs = CS.getAttributes();
  858. if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  859. removeAttribute(Attribute::NoAlias) !=
  860. AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  861. removeAttribute(Attribute::NoAlias))
  862. continue;
  863. // Make sure the call instruction is followed by an unconditional branch to
  864. // the return block.
  865. BasicBlock *CallBB = CI->getParent();
  866. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  867. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  868. continue;
  869. // Duplicate the return into CallBB.
  870. (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
  871. ModifiedDT = Changed = true;
  872. ++NumRetsDup;
  873. }
  874. // If we eliminated all predecessors of the block, delete the block now.
  875. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  876. BB->eraseFromParent();
  877. return Changed;
  878. }
  879. //===----------------------------------------------------------------------===//
  880. // Memory Optimization
  881. //===----------------------------------------------------------------------===//
  882. namespace {
  883. /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
  884. /// which holds actual Value*'s for register values.
  885. struct ExtAddrMode : public TargetLowering::AddrMode {
  886. Value *BaseReg;
  887. Value *ScaledReg;
  888. ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
  889. void print(raw_ostream &OS) const;
  890. void dump() const;
  891. bool operator==(const ExtAddrMode& O) const {
  892. return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
  893. (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
  894. (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
  895. }
  896. };
  897. #ifndef NDEBUG
  898. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  899. AM.print(OS);
  900. return OS;
  901. }
  902. #endif
  903. void ExtAddrMode::print(raw_ostream &OS) const {
  904. bool NeedPlus = false;
  905. OS << "[";
  906. if (BaseGV) {
  907. OS << (NeedPlus ? " + " : "")
  908. << "GV:";
  909. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  910. NeedPlus = true;
  911. }
  912. if (BaseOffs) {
  913. OS << (NeedPlus ? " + " : "")
  914. << BaseOffs;
  915. NeedPlus = true;
  916. }
  917. if (BaseReg) {
  918. OS << (NeedPlus ? " + " : "")
  919. << "Base:";
  920. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  921. NeedPlus = true;
  922. }
  923. if (Scale) {
  924. OS << (NeedPlus ? " + " : "")
  925. << Scale << "*";
  926. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  927. }
  928. OS << ']';
  929. }
  930. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  931. void ExtAddrMode::dump() const {
  932. print(dbgs());
  933. dbgs() << '\n';
  934. }
  935. #endif
  936. /// \brief This class provides transaction based operation on the IR.
  937. /// Every change made through this class is recorded in the internal state and
  938. /// can be undone (rollback) until commit is called.
  939. class TypePromotionTransaction {
  940. /// \brief This represents the common interface of the individual transaction.
  941. /// Each class implements the logic for doing one specific modification on
  942. /// the IR via the TypePromotionTransaction.
  943. class TypePromotionAction {
  944. protected:
  945. /// The Instruction modified.
  946. Instruction *Inst;
  947. public:
  948. /// \brief Constructor of the action.
  949. /// The constructor performs the related action on the IR.
  950. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  951. virtual ~TypePromotionAction() {}
  952. /// \brief Undo the modification done by this action.
  953. /// When this method is called, the IR must be in the same state as it was
  954. /// before this action was applied.
  955. /// \pre Undoing the action works if and only if the IR is in the exact same
  956. /// state as it was directly after this action was applied.
  957. virtual void undo() = 0;
  958. /// \brief Advocate every change made by this action.
  959. /// When the results on the IR of the action are to be kept, it is important
  960. /// to call this function, otherwise hidden information may be kept forever.
  961. virtual void commit() {
  962. // Nothing to be done, this action is not doing anything.
  963. }
  964. };
  965. /// \brief Utility to remember the position of an instruction.
  966. class InsertionHandler {
  967. /// Position of an instruction.
  968. /// Either an instruction:
  969. /// - Is the first in a basic block: BB is used.
  970. /// - Has a previous instructon: PrevInst is used.
  971. union {
  972. Instruction *PrevInst;
  973. BasicBlock *BB;
  974. } Point;
  975. /// Remember whether or not the instruction had a previous instruction.
  976. bool HasPrevInstruction;
  977. public:
  978. /// \brief Record the position of \p Inst.
  979. InsertionHandler(Instruction *Inst) {
  980. BasicBlock::iterator It = Inst;
  981. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  982. if (HasPrevInstruction)
  983. Point.PrevInst = --It;
  984. else
  985. Point.BB = Inst->getParent();
  986. }
  987. /// \brief Insert \p Inst at the recorded position.
  988. void insert(Instruction *Inst) {
  989. if (HasPrevInstruction) {
  990. if (Inst->getParent())
  991. Inst->removeFromParent();
  992. Inst->insertAfter(Point.PrevInst);
  993. } else {
  994. Instruction *Position = Point.BB->getFirstInsertionPt();
  995. if (Inst->getParent())
  996. Inst->moveBefore(Position);
  997. else
  998. Inst->insertBefore(Position);
  999. }
  1000. }
  1001. };
  1002. /// \brief Move an instruction before another.
  1003. class InstructionMoveBefore : public TypePromotionAction {
  1004. /// Original position of the instruction.
  1005. InsertionHandler Position;
  1006. public:
  1007. /// \brief Move \p Inst before \p Before.
  1008. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1009. : TypePromotionAction(Inst), Position(Inst) {
  1010. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1011. Inst->moveBefore(Before);
  1012. }
  1013. /// \brief Move the instruction back to its original position.
  1014. void undo() override {
  1015. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1016. Position.insert(Inst);
  1017. }
  1018. };
  1019. /// \brief Set the operand of an instruction with a new value.
  1020. class OperandSetter : public TypePromotionAction {
  1021. /// Original operand of the instruction.
  1022. Value *Origin;
  1023. /// Index of the modified instruction.
  1024. unsigned Idx;
  1025. public:
  1026. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1027. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1028. : TypePromotionAction(Inst), Idx(Idx) {
  1029. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1030. << "for:" << *Inst << "\n"
  1031. << "with:" << *NewVal << "\n");
  1032. Origin = Inst->getOperand(Idx);
  1033. Inst->setOperand(Idx, NewVal);
  1034. }
  1035. /// \brief Restore the original value of the instruction.
  1036. void undo() override {
  1037. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1038. << "for: " << *Inst << "\n"
  1039. << "with: " << *Origin << "\n");
  1040. Inst->setOperand(Idx, Origin);
  1041. }
  1042. };
  1043. /// \brief Hide the operands of an instruction.
  1044. /// Do as if this instruction was not using any of its operands.
  1045. class OperandsHider : public TypePromotionAction {
  1046. /// The list of original operands.
  1047. SmallVector<Value *, 4> OriginalValues;
  1048. public:
  1049. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1050. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1051. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1052. unsigned NumOpnds = Inst->getNumOperands();
  1053. OriginalValues.reserve(NumOpnds);
  1054. for (unsigned It = 0; It < NumOpnds; ++It) {
  1055. // Save the current operand.
  1056. Value *Val = Inst->getOperand(It);
  1057. OriginalValues.push_back(Val);
  1058. // Set a dummy one.
  1059. // We could use OperandSetter here, but that would implied an overhead
  1060. // that we are not willing to pay.
  1061. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1062. }
  1063. }
  1064. /// \brief Restore the original list of uses.
  1065. void undo() override {
  1066. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1067. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1068. Inst->setOperand(It, OriginalValues[It]);
  1069. }
  1070. };
  1071. /// \brief Build a truncate instruction.
  1072. class TruncBuilder : public TypePromotionAction {
  1073. public:
  1074. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1075. /// result.
  1076. /// trunc Opnd to Ty.
  1077. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  1078. IRBuilder<> Builder(Opnd);
  1079. Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
  1080. DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
  1081. }
  1082. /// \brief Get the built instruction.
  1083. Instruction *getBuiltInstruction() { return Inst; }
  1084. /// \brief Remove the built instruction.
  1085. void undo() override {
  1086. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
  1087. Inst->eraseFromParent();
  1088. }
  1089. };
  1090. /// \brief Build a sign extension instruction.
  1091. class SExtBuilder : public TypePromotionAction {
  1092. public:
  1093. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  1094. /// result.
  1095. /// sext Opnd to Ty.
  1096. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1097. : TypePromotionAction(Inst) {
  1098. IRBuilder<> Builder(InsertPt);
  1099. Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
  1100. DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
  1101. }
  1102. /// \brief Get the built instruction.
  1103. Instruction *getBuiltInstruction() { return Inst; }
  1104. /// \brief Remove the built instruction.
  1105. void undo() override {
  1106. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
  1107. Inst->eraseFromParent();
  1108. }
  1109. };
  1110. /// \brief Mutate an instruction to another type.
  1111. class TypeMutator : public TypePromotionAction {
  1112. /// Record the original type.
  1113. Type *OrigTy;
  1114. public:
  1115. /// \brief Mutate the type of \p Inst into \p NewTy.
  1116. TypeMutator(Instruction *Inst, Type *NewTy)
  1117. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  1118. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  1119. << "\n");
  1120. Inst->mutateType(NewTy);
  1121. }
  1122. /// \brief Mutate the instruction back to its original type.
  1123. void undo() override {
  1124. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  1125. << "\n");
  1126. Inst->mutateType(OrigTy);
  1127. }
  1128. };
  1129. /// \brief Replace the uses of an instruction by another instruction.
  1130. class UsesReplacer : public TypePromotionAction {
  1131. /// Helper structure to keep track of the replaced uses.
  1132. struct InstructionAndIdx {
  1133. /// The instruction using the instruction.
  1134. Instruction *Inst;
  1135. /// The index where this instruction is used for Inst.
  1136. unsigned Idx;
  1137. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  1138. : Inst(Inst), Idx(Idx) {}
  1139. };
  1140. /// Keep track of the original uses (pair Instruction, Index).
  1141. SmallVector<InstructionAndIdx, 4> OriginalUses;
  1142. typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
  1143. public:
  1144. /// \brief Replace all the use of \p Inst by \p New.
  1145. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  1146. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  1147. << "\n");
  1148. // Record the original uses.
  1149. for (Use &U : Inst->uses()) {
  1150. Instruction *UserI = cast<Instruction>(U.getUser());
  1151. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  1152. }
  1153. // Now, we can replace the uses.
  1154. Inst->replaceAllUsesWith(New);
  1155. }
  1156. /// \brief Reassign the original uses of Inst to Inst.
  1157. void undo() override {
  1158. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  1159. for (use_iterator UseIt = OriginalUses.begin(),
  1160. EndIt = OriginalUses.end();
  1161. UseIt != EndIt; ++UseIt) {
  1162. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  1163. }
  1164. }
  1165. };
  1166. /// \brief Remove an instruction from the IR.
  1167. class InstructionRemover : public TypePromotionAction {
  1168. /// Original position of the instruction.
  1169. InsertionHandler Inserter;
  1170. /// Helper structure to hide all the link to the instruction. In other
  1171. /// words, this helps to do as if the instruction was removed.
  1172. OperandsHider Hider;
  1173. /// Keep track of the uses replaced, if any.
  1174. UsesReplacer *Replacer;
  1175. public:
  1176. /// \brief Remove all reference of \p Inst and optinally replace all its
  1177. /// uses with New.
  1178. /// \pre If !Inst->use_empty(), then New != nullptr
  1179. InstructionRemover(Instruction *Inst, Value *New = nullptr)
  1180. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  1181. Replacer(nullptr) {
  1182. if (New)
  1183. Replacer = new UsesReplacer(Inst, New);
  1184. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  1185. Inst->removeFromParent();
  1186. }
  1187. ~InstructionRemover() { delete Replacer; }
  1188. /// \brief Really remove the instruction.
  1189. void commit() override { delete Inst; }
  1190. /// \brief Resurrect the instruction and reassign it to the proper uses if
  1191. /// new value was provided when build this action.
  1192. void undo() override {
  1193. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  1194. Inserter.insert(Inst);
  1195. if (Replacer)
  1196. Replacer->undo();
  1197. Hider.undo();
  1198. }
  1199. };
  1200. public:
  1201. /// Restoration point.
  1202. /// The restoration point is a pointer to an action instead of an iterator
  1203. /// because the iterator may be invalidated but not the pointer.
  1204. typedef const TypePromotionAction *ConstRestorationPt;
  1205. /// Advocate every changes made in that transaction.
  1206. void commit();
  1207. /// Undo all the changes made after the given point.
  1208. void rollback(ConstRestorationPt Point);
  1209. /// Get the current restoration point.
  1210. ConstRestorationPt getRestorationPoint() const;
  1211. /// \name API for IR modification with state keeping to support rollback.
  1212. /// @{
  1213. /// Same as Instruction::setOperand.
  1214. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  1215. /// Same as Instruction::eraseFromParent.
  1216. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  1217. /// Same as Value::replaceAllUsesWith.
  1218. void replaceAllUsesWith(Instruction *Inst, Value *New);
  1219. /// Same as Value::mutateType.
  1220. void mutateType(Instruction *Inst, Type *NewTy);
  1221. /// Same as IRBuilder::createTrunc.
  1222. Instruction *createTrunc(Instruction *Opnd, Type *Ty);
  1223. /// Same as IRBuilder::createSExt.
  1224. Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  1225. /// Same as Instruction::moveBefore.
  1226. void moveBefore(Instruction *Inst, Instruction *Before);
  1227. /// @}
  1228. private:
  1229. /// The ordered list of actions made so far.
  1230. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  1231. typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
  1232. };
  1233. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  1234. Value *NewVal) {
  1235. Actions.push_back(
  1236. make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
  1237. }
  1238. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  1239. Value *NewVal) {
  1240. Actions.push_back(
  1241. make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
  1242. }
  1243. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  1244. Value *New) {
  1245. Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  1246. }
  1247. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  1248. Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  1249. }
  1250. Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  1251. Type *Ty) {
  1252. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  1253. Instruction *I = Ptr->getBuiltInstruction();
  1254. Actions.push_back(std::move(Ptr));
  1255. return I;
  1256. }
  1257. Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
  1258. Value *Opnd, Type *Ty) {
  1259. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  1260. Instruction *I = Ptr->getBuiltInstruction();
  1261. Actions.push_back(std::move(Ptr));
  1262. return I;
  1263. }
  1264. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  1265. Instruction *Before) {
  1266. Actions.push_back(
  1267. make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
  1268. }
  1269. TypePromotionTransaction::ConstRestorationPt
  1270. TypePromotionTransaction::getRestorationPoint() const {
  1271. return !Actions.empty() ? Actions.back().get() : nullptr;
  1272. }
  1273. void TypePromotionTransaction::commit() {
  1274. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  1275. ++It)
  1276. (*It)->commit();
  1277. Actions.clear();
  1278. }
  1279. void TypePromotionTransaction::rollback(
  1280. TypePromotionTransaction::ConstRestorationPt Point) {
  1281. while (!Actions.empty() && Point != Actions.back().get()) {
  1282. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  1283. Curr->undo();
  1284. }
  1285. }
  1286. /// \brief A helper class for matching addressing modes.
  1287. ///
  1288. /// This encapsulates the logic for matching the target-legal addressing modes.
  1289. class AddressingModeMatcher {
  1290. SmallVectorImpl<Instruction*> &AddrModeInsts;
  1291. const TargetLowering &TLI;
  1292. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  1293. /// the memory instruction that we're computing this address for.
  1294. Type *AccessTy;
  1295. Instruction *MemoryInst;
  1296. /// AddrMode - This is the addressing mode that we're building up. This is
  1297. /// part of the return value of this addressing mode matching stuff.
  1298. ExtAddrMode &AddrMode;
  1299. /// The truncate instruction inserted by other CodeGenPrepare optimizations.
  1300. const SetOfInstrs &InsertedTruncs;
  1301. /// A map from the instructions to their type before promotion.
  1302. InstrToOrigTy &PromotedInsts;
  1303. /// The ongoing transaction where every action should be registered.
  1304. TypePromotionTransaction &TPT;
  1305. /// IgnoreProfitability - This is set to true when we should not do
  1306. /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
  1307. /// always returns true.
  1308. bool IgnoreProfitability;
  1309. AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
  1310. const TargetLowering &T, Type *AT,
  1311. Instruction *MI, ExtAddrMode &AM,
  1312. const SetOfInstrs &InsertedTruncs,
  1313. InstrToOrigTy &PromotedInsts,
  1314. TypePromotionTransaction &TPT)
  1315. : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
  1316. InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
  1317. IgnoreProfitability = false;
  1318. }
  1319. public:
  1320. /// Match - Find the maximal addressing mode that a load/store of V can fold,
  1321. /// give an access type of AccessTy. This returns a list of involved
  1322. /// instructions in AddrModeInsts.
  1323. /// \p InsertedTruncs The truncate instruction inserted by other
  1324. /// CodeGenPrepare
  1325. /// optimizations.
  1326. /// \p PromotedInsts maps the instructions to their type before promotion.
  1327. /// \p The ongoing transaction where every action should be registered.
  1328. static ExtAddrMode Match(Value *V, Type *AccessTy,
  1329. Instruction *MemoryInst,
  1330. SmallVectorImpl<Instruction*> &AddrModeInsts,
  1331. const TargetLowering &TLI,
  1332. const SetOfInstrs &InsertedTruncs,
  1333. InstrToOrigTy &PromotedInsts,
  1334. TypePromotionTransaction &TPT) {
  1335. ExtAddrMode Result;
  1336. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
  1337. MemoryInst, Result, InsertedTruncs,
  1338. PromotedInsts, TPT).MatchAddr(V, 0);
  1339. (void)Success; assert(Success && "Couldn't select *anything*?");
  1340. return Result;
  1341. }
  1342. private:
  1343. bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  1344. bool MatchAddr(Value *V, unsigned Depth);
  1345. bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  1346. bool *MovedAway = nullptr);
  1347. bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
  1348. ExtAddrMode &AMBefore,
  1349. ExtAddrMode &AMAfter);
  1350. bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  1351. bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
  1352. Value *PromotedOperand) const;
  1353. };
  1354. /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
  1355. /// Return true and update AddrMode if this addr mode is legal for the target,
  1356. /// false if not.
  1357. bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
  1358. unsigned Depth) {
  1359. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  1360. // mode. Just process that directly.
  1361. if (Scale == 1)
  1362. return MatchAddr(ScaleReg, Depth);
  1363. // If the scale is 0, it takes nothing to add this.
  1364. if (Scale == 0)
  1365. return true;
  1366. // If we already have a scale of this value, we can add to it, otherwise, we
  1367. // need an available scale field.
  1368. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  1369. return false;
  1370. ExtAddrMode TestAddrMode = AddrMode;
  1371. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  1372. // [A+B + A*7] -> [B+A*8].
  1373. TestAddrMode.Scale += Scale;
  1374. TestAddrMode.ScaledReg = ScaleReg;
  1375. // If the new address isn't legal, bail out.
  1376. if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
  1377. return false;
  1378. // It was legal, so commit it.
  1379. AddrMode = TestAddrMode;
  1380. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  1381. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  1382. // X*Scale + C*Scale to addr mode.
  1383. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  1384. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  1385. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  1386. TestAddrMode.ScaledReg = AddLHS;
  1387. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  1388. // If this addressing mode is legal, commit it and remember that we folded
  1389. // this instruction.
  1390. if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
  1391. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  1392. AddrMode = TestAddrMode;
  1393. return true;
  1394. }
  1395. }
  1396. // Otherwise, not (x+c)*scale, just return what we have.
  1397. return true;
  1398. }
  1399. /// MightBeFoldableInst - This is a little filter, which returns true if an
  1400. /// addressing computation involving I might be folded into a load/store
  1401. /// accessing it. This doesn't need to be perfect, but needs to accept at least
  1402. /// the set of instructions that MatchOperationAddr can.
  1403. static bool MightBeFoldableInst(Instruction *I) {
  1404. switch (I->getOpcode()) {
  1405. case Instruction::BitCast:
  1406. case Instruction::AddrSpaceCast:
  1407. // Don't touch identity bitcasts.
  1408. if (I->getType() == I->getOperand(0)->getType())
  1409. return false;
  1410. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  1411. case Instruction::PtrToInt:
  1412. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  1413. return true;
  1414. case Instruction::IntToPtr:
  1415. // We know the input is intptr_t, so this is foldable.
  1416. return true;
  1417. case Instruction::Add:
  1418. return true;
  1419. case Instruction::Mul:
  1420. case Instruction::Shl:
  1421. // Can only handle X*C and X << C.
  1422. return isa<ConstantInt>(I->getOperand(1));
  1423. case Instruction::GetElementPtr:
  1424. return true;
  1425. default:
  1426. return false;
  1427. }
  1428. }
  1429. /// \brief Hepler class to perform type promotion.
  1430. class TypePromotionHelper {
  1431. /// \brief Utility function to check whether or not a sign extension of
  1432. /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
  1433. /// using the operands of \p Inst or promoting \p Inst.
  1434. /// In other words, check if:
  1435. /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
  1436. /// #1 Promotion applies:
  1437. /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
  1438. /// #2 Operand reuses:
  1439. /// sext opnd1 to ConsideredSExtType.
  1440. /// \p PromotedInsts maps the instructions to their type before promotion.
  1441. static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
  1442. const InstrToOrigTy &PromotedInsts);
  1443. /// \brief Utility function to determine if \p OpIdx should be promoted when
  1444. /// promoting \p Inst.
  1445. static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
  1446. if (isa<SelectInst>(Inst) && OpIdx == 0)
  1447. return false;
  1448. return true;
  1449. }
  1450. /// \brief Utility function to promote the operand of \p SExt when this
  1451. /// operand is a promotable trunc or sext.
  1452. /// \p PromotedInsts maps the instructions to their type before promotion.
  1453. /// \p CreatedInsts[out] contains how many non-free instructions have been
  1454. /// created to promote the operand of SExt.
  1455. /// Should never be called directly.
  1456. /// \return The promoted value which is used instead of SExt.
  1457. static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
  1458. TypePromotionTransaction &TPT,
  1459. InstrToOrigTy &PromotedInsts,
  1460. unsigned &CreatedInsts);
  1461. /// \brief Utility function to promote the operand of \p SExt when this
  1462. /// operand is promotable and is not a supported trunc or sext.
  1463. /// \p PromotedInsts maps the instructions to their type before promotion.
  1464. /// \p CreatedInsts[out] contains how many non-free instructions have been
  1465. /// created to promote the operand of SExt.
  1466. /// Should never be called directly.
  1467. /// \return The promoted value which is used instead of SExt.
  1468. static Value *promoteOperandForOther(Instruction *SExt,
  1469. TypePromotionTransaction &TPT,
  1470. InstrToOrigTy &PromotedInsts,
  1471. unsigned &CreatedInsts);
  1472. public:
  1473. /// Type for the utility function that promotes the operand of SExt.
  1474. typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
  1475. InstrToOrigTy &PromotedInsts,
  1476. unsigned &CreatedInsts);
  1477. /// \brief Given a sign extend instruction \p SExt, return the approriate
  1478. /// action to promote the operand of \p SExt instead of using SExt.
  1479. /// \return NULL if no promotable action is possible with the current
  1480. /// sign extension.
  1481. /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
  1482. /// the others CodeGenPrepare optimizations. This information is important
  1483. /// because we do not want to promote these instructions as CodeGenPrepare
  1484. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  1485. /// \p PromotedInsts maps the instructions to their type before promotion.
  1486. static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
  1487. const TargetLowering &TLI,
  1488. const InstrToOrigTy &PromotedInsts);
  1489. };
  1490. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  1491. Type *ConsideredSExtType,
  1492. const InstrToOrigTy &PromotedInsts) {
  1493. // We can always get through sext.
  1494. if (isa<SExtInst>(Inst))
  1495. return true;
  1496. // We can get through binary operator, if it is legal. In other words, the
  1497. // binary operator must have a nuw or nsw flag.
  1498. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  1499. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  1500. (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
  1501. return true;
  1502. // Check if we can do the following simplification.
  1503. // sext(trunc(sext)) --> sext
  1504. if (!isa<TruncInst>(Inst))
  1505. return false;
  1506. Value *OpndVal = Inst->getOperand(0);
  1507. // Check if we can use this operand in the sext.
  1508. // If the type is larger than the result type of the sign extension,
  1509. // we cannot.
  1510. if (OpndVal->getType()->getIntegerBitWidth() >
  1511. ConsideredSExtType->getIntegerBitWidth())
  1512. return false;
  1513. // If the operand of the truncate is not an instruction, we will not have
  1514. // any information on the dropped bits.
  1515. // (Actually we could for constant but it is not worth the extra logic).
  1516. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  1517. if (!Opnd)
  1518. return false;
  1519. // Check if the source of the type is narrow enough.
  1520. // I.e., check that trunc just drops sign extended bits.
  1521. // #1 get the type of the operand.
  1522. const Type *OpndType;
  1523. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  1524. if (It != PromotedInsts.end())
  1525. OpndType = It->second;
  1526. else if (isa<SExtInst>(Opnd))
  1527. OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
  1528. else
  1529. return false;
  1530. // #2 check that the truncate just drop sign extended bits.
  1531. if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
  1532. return true;
  1533. return false;
  1534. }
  1535. TypePromotionHelper::Action TypePromotionHelper::getAction(
  1536. Instruction *SExt, const SetOfInstrs &InsertedTruncs,
  1537. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  1538. Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
  1539. Type *SExtTy = SExt->getType();
  1540. // If the operand of the sign extension is not an instruction, we cannot
  1541. // get through.
  1542. // If it, check we can get through.
  1543. if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
  1544. return nullptr;
  1545. // Do not promote if the operand has been added by codegenprepare.
  1546. // Otherwise, it means we are undoing an optimization that is likely to be
  1547. // redone, thus causing potential infinite loop.
  1548. if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
  1549. return nullptr;
  1550. // SExt or Trunc instructions.
  1551. // Return the related handler.
  1552. if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
  1553. return promoteOperandForTruncAndSExt;
  1554. // Regular instruction.
  1555. // Abort early if we will have to insert non-free instructions.
  1556. if (!SExtOpnd->hasOneUse() &&
  1557. !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
  1558. return nullptr;
  1559. return promoteOperandForOther;
  1560. }
  1561. Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
  1562. llvm::Instruction *SExt, TypePromotionTransaction &TPT,
  1563. InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
  1564. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  1565. // get through it and this method should not be called.
  1566. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  1567. // Replace sext(trunc(opnd)) or sext(sext(opnd))
  1568. // => sext(opnd).
  1569. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  1570. CreatedInsts = 0;
  1571. // Remove dead code.
  1572. if (SExtOpnd->use_empty())
  1573. TPT.eraseInstruction(SExtOpnd);
  1574. // Check if the sext is still needed.
  1575. if (SExt->getType() != SExt->getOperand(0)->getType())
  1576. return SExt;
  1577. // At this point we have: sext ty opnd to ty.
  1578. // Reassign the uses of SExt to the opnd and remove SExt.
  1579. Value *NextVal = SExt->getOperand(0);
  1580. TPT.eraseInstruction(SExt, NextVal);
  1581. return NextVal;
  1582. }
  1583. Value *
  1584. TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
  1585. TypePromotionTransaction &TPT,
  1586. InstrToOrigTy &PromotedInsts,
  1587. unsigned &CreatedInsts) {
  1588. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  1589. // get through it and this method should not be called.
  1590. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  1591. CreatedInsts = 0;
  1592. if (!SExtOpnd->hasOneUse()) {
  1593. // SExtOpnd will be promoted.
  1594. // All its uses, but SExt, will need to use a truncated value of the
  1595. // promoted version.
  1596. // Create the truncate now.
  1597. Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
  1598. Trunc->removeFromParent();
  1599. // Insert it just after the definition.
  1600. Trunc->insertAfter(SExtOpnd);
  1601. TPT.replaceAllUsesWith(SExtOpnd, Trunc);
  1602. // Restore the operand of SExt (which has been replace by the previous call
  1603. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  1604. TPT.setOperand(SExt, 0, SExtOpnd);
  1605. }
  1606. // Get through the Instruction:
  1607. // 1. Update its type.
  1608. // 2. Replace the uses of SExt by Inst.
  1609. // 3. Sign extend each operand that needs to be sign extended.
  1610. // Remember the original type of the instruction before promotion.
  1611. // This is useful to know that the high bits are sign extended bits.
  1612. PromotedInsts.insert(
  1613. std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
  1614. // Step #1.
  1615. TPT.mutateType(SExtOpnd, SExt->getType());
  1616. // Step #2.
  1617. TPT.replaceAllUsesWith(SExt, SExtOpnd);
  1618. // Step #3.
  1619. Instruction *SExtForOpnd = SExt;
  1620. DEBUG(dbgs() << "Propagate SExt to operands\n");
  1621. for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  1622. ++OpIdx) {
  1623. DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
  1624. if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
  1625. !shouldSExtOperand(SExtOpnd, OpIdx)) {
  1626. DEBUG(dbgs() << "No need to propagate\n");
  1627. continue;
  1628. }
  1629. // Check if we can statically sign extend the operand.
  1630. Value *Opnd = SExtOpnd->getOperand(OpIdx);
  1631. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  1632. DEBUG(dbgs() << "Statically sign extend\n");
  1633. TPT.setOperand(
  1634. SExtOpnd, OpIdx,
  1635. ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
  1636. continue;
  1637. }
  1638. // UndefValue are typed, so we have to statically sign extend them.
  1639. if (isa<UndefValue>(Opnd)) {
  1640. DEBUG(dbgs() << "Statically sign extend\n");
  1641. TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
  1642. continue;
  1643. }
  1644. // Otherwise we have to explicity sign extend the operand.
  1645. // Check if SExt was reused to sign extend an operand.
  1646. if (!SExtForOpnd) {
  1647. // If yes, create a new one.
  1648. DEBUG(dbgs() << "More operands to sext\n");
  1649. SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
  1650. ++CreatedInsts;
  1651. }
  1652. TPT.setOperand(SExtForOpnd, 0, Opnd);
  1653. // Move the sign extension before the insertion point.
  1654. TPT.moveBefore(SExtForOpnd, SExtOpnd);
  1655. TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
  1656. // If more sext are required, new instructions will have to be created.
  1657. SExtForOpnd = nullptr;
  1658. }
  1659. if (SExtForOpnd == SExt) {
  1660. DEBUG(dbgs() << "Sign extension is useless now\n");
  1661. TPT.eraseInstruction(SExt);
  1662. }
  1663. return SExtOpnd;
  1664. }
  1665. /// IsPromotionProfitable - Check whether or not promoting an instruction
  1666. /// to a wider type was profitable.
  1667. /// \p MatchedSize gives the number of instructions that have been matched
  1668. /// in the addressing mode after the promotion was applied.
  1669. /// \p SizeWithPromotion gives the number of created instructions for
  1670. /// the promotion plus the number of instructions that have been
  1671. /// matched in the addressing mode before the promotion.
  1672. /// \p PromotedOperand is the value that has been promoted.
  1673. /// \return True if the promotion is profitable, false otherwise.
  1674. bool
  1675. AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
  1676. unsigned SizeWithPromotion,
  1677. Value *PromotedOperand) const {
  1678. // We folded less instructions than what we created to promote the operand.
  1679. // This is not profitable.
  1680. if (MatchedSize < SizeWithPromotion)
  1681. return false;
  1682. if (MatchedSize > SizeWithPromotion)
  1683. return true;
  1684. // The promotion is neutral but it may help folding the sign extension in
  1685. // loads for instance.
  1686. // Check that we did not create an illegal instruction.
  1687. Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
  1688. if (!PromotedInst)
  1689. return false;
  1690. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  1691. // If the ISDOpcode is undefined, it was undefined before the promotion.
  1692. if (!ISDOpcode)
  1693. return true;
  1694. // Otherwise, check if the promoted instruction is legal or not.
  1695. return TLI.isOperationLegalOrCustom(ISDOpcode,
  1696. EVT::getEVT(PromotedInst->getType()));
  1697. }
  1698. /// MatchOperationAddr - Given an instruction or constant expr, see if we can
  1699. /// fold the operation into the addressing mode. If so, update the addressing
  1700. /// mode and return true, otherwise return false without modifying AddrMode.
  1701. /// If \p MovedAway is not NULL, it contains the information of whether or
  1702. /// not AddrInst has to be folded into the addressing mode on success.
  1703. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  1704. /// because it has been moved away.
  1705. /// Thus AddrInst must not be added in the matched instructions.
  1706. /// This state can happen when AddrInst is a sext, since it may be moved away.
  1707. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  1708. /// not be referenced anymore.
  1709. bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
  1710. unsigned Depth,
  1711. bool *MovedAway) {
  1712. // Avoid exponential behavior on extremely deep expression trees.
  1713. if (Depth >= 5) return false;
  1714. // By default, all matched instructions stay in place.
  1715. if (MovedAway)
  1716. *MovedAway = false;
  1717. switch (Opcode) {
  1718. case Instruction::PtrToInt:
  1719. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  1720. return MatchAddr(AddrInst->getOperand(0), Depth);
  1721. case Instruction::IntToPtr:
  1722. // This inttoptr is a no-op if the integer type is pointer sized.
  1723. if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
  1724. TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
  1725. return MatchAddr(AddrInst->getOperand(0), Depth);
  1726. return false;
  1727. case Instruction::BitCast:
  1728. case Instruction::AddrSpaceCast:
  1729. // BitCast is always a noop, and we can handle it as long as it is
  1730. // int->int or pointer->pointer (we don't want int<->fp or something).
  1731. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  1732. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  1733. // Don't touch identity bitcasts. These were probably put here by LSR,
  1734. // and we don't want to mess around with them. Assume it knows what it
  1735. // is doing.
  1736. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  1737. return MatchAddr(AddrInst->getOperand(0), Depth);
  1738. return false;
  1739. case Instruction::Add: {
  1740. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  1741. ExtAddrMode BackupAddrMode = AddrMode;
  1742. unsigned OldSize = AddrModeInsts.size();
  1743. // Start a transaction at this point.
  1744. // The LHS may match but not the RHS.
  1745. // Therefore, we need a higher level restoration point to undo partially
  1746. // matched operation.
  1747. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  1748. TPT.getRestorationPoint();
  1749. if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
  1750. MatchAddr(AddrInst->getOperand(0), Depth+1))
  1751. return true;
  1752. // Restore the old addr mode info.
  1753. AddrMode = BackupAddrMode;
  1754. AddrModeInsts.resize(OldSize);
  1755. TPT.rollback(LastKnownGood);
  1756. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  1757. if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
  1758. MatchAddr(AddrInst->getOperand(1), Depth+1))
  1759. return true;
  1760. // Otherwise we definitely can't merge the ADD in.
  1761. AddrMode = BackupAddrMode;
  1762. AddrModeInsts.resize(OldSize);
  1763. TPT.rollback(LastKnownGood);
  1764. break;
  1765. }
  1766. //case Instruction::Or:
  1767. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  1768. //break;
  1769. case Instruction::Mul:
  1770. case Instruction::Shl: {
  1771. // Can only handle X*C and X << C.
  1772. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  1773. if (!RHS)
  1774. return false;
  1775. int64_t Scale = RHS->getSExtValue();
  1776. if (Opcode == Instruction::Shl)
  1777. Scale = 1LL << Scale;
  1778. return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  1779. }
  1780. case Instruction::GetElementPtr: {
  1781. // Scan the GEP. We check it if it contains constant offsets and at most
  1782. // one variable offset.
  1783. int VariableOperand = -1;
  1784. unsigned VariableScale = 0;
  1785. int64_t ConstantOffset = 0;
  1786. const DataLayout *TD = TLI.getDataLayout();
  1787. gep_type_iterator GTI = gep_type_begin(AddrInst);
  1788. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  1789. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1790. const StructLayout *SL = TD->getStructLayout(STy);
  1791. unsigned Idx =
  1792. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  1793. ConstantOffset += SL->getElementOffset(Idx);
  1794. } else {
  1795. uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
  1796. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  1797. ConstantOffset += CI->getSExtValue()*TypeSize;
  1798. } else if (TypeSize) { // Scales of zero don't do anything.
  1799. // We only allow one variable index at the moment.
  1800. if (VariableOperand != -1)
  1801. return false;
  1802. // Remember the variable index.
  1803. VariableOperand = i;
  1804. VariableScale = TypeSize;
  1805. }
  1806. }
  1807. }
  1808. // A common case is for the GEP to only do a constant offset. In this case,
  1809. // just add it to the disp field and check validity.
  1810. if (VariableOperand == -1) {
  1811. AddrMode.BaseOffs += ConstantOffset;
  1812. if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
  1813. // Check to see if we can fold the base pointer in too.
  1814. if (MatchAddr(AddrInst->getOperand(0), Depth+1))
  1815. return true;
  1816. }
  1817. AddrMode.BaseOffs -= ConstantOffset;
  1818. return false;
  1819. }
  1820. // Save the valid addressing mode in case we can't match.
  1821. ExtAddrMode BackupAddrMode = AddrMode;
  1822. unsigned OldSize = AddrModeInsts.size();
  1823. // See if the scale and offset amount is valid for this target.
  1824. AddrMode.BaseOffs += ConstantOffset;
  1825. // Match the base operand of the GEP.
  1826. if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
  1827. // If it couldn't be matched, just stuff the value in a register.
  1828. if (AddrMode.HasBaseReg) {
  1829. AddrMode = BackupAddrMode;
  1830. AddrModeInsts.resize(OldSize);
  1831. return false;
  1832. }
  1833. AddrMode.HasBaseReg = true;
  1834. AddrMode.BaseReg = AddrInst->getOperand(0);
  1835. }
  1836. // Match the remaining variable portion of the GEP.
  1837. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  1838. Depth)) {
  1839. // If it couldn't be matched, try stuffing the base into a register
  1840. // instead of matching it, and retrying the match of the scale.
  1841. AddrMode = BackupAddrMode;
  1842. AddrModeInsts.resize(OldSize);
  1843. if (AddrMode.HasBaseReg)
  1844. return false;
  1845. AddrMode.HasBaseReg = true;
  1846. AddrMode.BaseReg = AddrInst->getOperand(0);
  1847. AddrMode.BaseOffs += ConstantOffset;
  1848. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
  1849. VariableScale, Depth)) {
  1850. // If even that didn't work, bail.
  1851. AddrMode = BackupAddrMode;
  1852. AddrModeInsts.resize(OldSize);
  1853. return false;
  1854. }
  1855. }
  1856. return true;
  1857. }
  1858. case Instruction::SExt: {
  1859. Instruction *SExt = dyn_cast<Instruction>(AddrInst);
  1860. if (!SExt)
  1861. return false;
  1862. // Try to move this sext out of the way of the addressing mode.
  1863. // Ask for a method for doing so.
  1864. TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
  1865. SExt, InsertedTruncs, TLI, PromotedInsts);
  1866. if (!TPH)
  1867. return false;
  1868. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  1869. TPT.getRestorationPoint();
  1870. unsigned CreatedInsts = 0;
  1871. Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
  1872. // SExt has been moved away.
  1873. // Thus either it will be rematched later in the recursive calls or it is
  1874. // gone. Anyway, we must not fold it into the addressing mode at this point.
  1875. // E.g.,
  1876. // op = add opnd, 1
  1877. // idx = sext op
  1878. // addr = gep base, idx
  1879. // is now:
  1880. // promotedOpnd = sext opnd <- no match here
  1881. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  1882. // addr = gep base, op <- match
  1883. if (MovedAway)
  1884. *MovedAway = true;
  1885. assert(PromotedOperand &&
  1886. "TypePromotionHelper should have filtered out those cases");
  1887. ExtAddrMode BackupAddrMode = AddrMode;
  1888. unsigned OldSize = AddrModeInsts.size();
  1889. if (!MatchAddr(PromotedOperand, Depth) ||
  1890. !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
  1891. PromotedOperand)) {
  1892. AddrMode = BackupAddrMode;
  1893. AddrModeInsts.resize(OldSize);
  1894. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  1895. TPT.rollback(LastKnownGood);
  1896. return false;
  1897. }
  1898. return true;
  1899. }
  1900. }
  1901. return false;
  1902. }
  1903. /// MatchAddr - If we can, try to add the value of 'Addr' into the current
  1904. /// addressing mode. If Addr can't be added to AddrMode this returns false and
  1905. /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
  1906. /// or intptr_t for the target.
  1907. ///
  1908. bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
  1909. // Start a transaction at this point that we will rollback if the matching
  1910. // fails.
  1911. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  1912. TPT.getRestorationPoint();
  1913. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  1914. // Fold in immediates if legal for the target.
  1915. AddrMode.BaseOffs += CI->getSExtValue();
  1916. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  1917. return true;
  1918. AddrMode.BaseOffs -= CI->getSExtValue();
  1919. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  1920. // If this is a global variable, try to fold it into the addressing mode.
  1921. if (!AddrMode.BaseGV) {
  1922. AddrMode.BaseGV = GV;
  1923. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  1924. return true;
  1925. AddrMode.BaseGV = nullptr;
  1926. }
  1927. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  1928. ExtAddrMode BackupAddrMode = AddrMode;
  1929. unsigned OldSize = AddrModeInsts.size();
  1930. // Check to see if it is possible to fold this operation.
  1931. bool MovedAway = false;
  1932. if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  1933. // This instruction may have been move away. If so, there is nothing
  1934. // to check here.
  1935. if (MovedAway)
  1936. return true;
  1937. // Okay, it's possible to fold this. Check to see if it is actually
  1938. // *profitable* to do so. We use a simple cost model to avoid increasing
  1939. // register pressure too much.
  1940. if (I->hasOneUse() ||
  1941. IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  1942. AddrModeInsts.push_back(I);
  1943. return true;
  1944. }
  1945. // It isn't profitable to do this, roll back.
  1946. //cerr << "NOT FOLDING: " << *I;
  1947. AddrMode = BackupAddrMode;
  1948. AddrModeInsts.resize(OldSize);
  1949. TPT.rollback(LastKnownGood);
  1950. }
  1951. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  1952. if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
  1953. return true;
  1954. TPT.rollback(LastKnownGood);
  1955. } else if (isa<ConstantPointerNull>(Addr)) {
  1956. // Null pointer gets folded without affecting the addressing mode.
  1957. return true;
  1958. }
  1959. // Worse case, the target should support [reg] addressing modes. :)
  1960. if (!AddrMode.HasBaseReg) {
  1961. AddrMode.HasBaseReg = true;
  1962. AddrMode.BaseReg = Addr;
  1963. // Still check for legality in case the target supports [imm] but not [i+r].
  1964. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  1965. return true;
  1966. AddrMode.HasBaseReg = false;
  1967. AddrMode.BaseReg = nullptr;
  1968. }
  1969. // If the base register is already taken, see if we can do [r+r].
  1970. if (AddrMode.Scale == 0) {
  1971. AddrMode.Scale = 1;
  1972. AddrMode.ScaledReg = Addr;
  1973. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  1974. return true;
  1975. AddrMode.Scale = 0;
  1976. AddrMode.ScaledReg = nullptr;
  1977. }
  1978. // Couldn't match.
  1979. TPT.rollback(LastKnownGood);
  1980. return false;
  1981. }
  1982. /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
  1983. /// inline asm call are due to memory operands. If so, return true, otherwise
  1984. /// return false.
  1985. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  1986. const TargetLowering &TLI) {
  1987. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
  1988. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  1989. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  1990. // Compute the constraint code and ConstraintType to use.
  1991. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  1992. // If this asm operand is our Value*, and if it isn't an indirect memory
  1993. // operand, we can't fold it!
  1994. if (OpInfo.CallOperandVal == OpVal &&
  1995. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  1996. !OpInfo.isIndirect))
  1997. return false;
  1998. }
  1999. return true;
  2000. }
  2001. /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
  2002. /// memory use. If we find an obviously non-foldable instruction, return true.
  2003. /// Add the ultimately found memory instructions to MemoryUses.
  2004. static bool FindAllMemoryUses(Instruction *I,
  2005. SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
  2006. SmallPtrSetImpl<Instruction*> &ConsideredInsts,
  2007. const TargetLowering &TLI) {
  2008. // If we already considered this instruction, we're done.
  2009. if (!ConsideredInsts.insert(I))
  2010. return false;
  2011. // If this is an obviously unfoldable instruction, bail out.
  2012. if (!MightBeFoldableInst(I))
  2013. return true;
  2014. // Loop over all the uses, recursively processing them.
  2015. for (Use &U : I->uses()) {
  2016. Instruction *UserI = cast<Instruction>(U.getUser());
  2017. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  2018. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  2019. continue;
  2020. }
  2021. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  2022. unsigned opNo = U.getOperandNo();
  2023. if (opNo == 0) return true; // Storing addr, not into addr.
  2024. MemoryUses.push_back(std::make_pair(SI, opNo));
  2025. continue;
  2026. }
  2027. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  2028. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  2029. if (!IA) return true;
  2030. // If this is a memory operand, we're cool, otherwise bail out.
  2031. if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
  2032. return true;
  2033. continue;
  2034. }
  2035. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
  2036. return true;
  2037. }
  2038. return false;
  2039. }
  2040. /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
  2041. /// the use site that we're folding it into. If so, there is no cost to
  2042. /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
  2043. /// that we know are live at the instruction already.
  2044. bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  2045. Value *KnownLive2) {
  2046. // If Val is either of the known-live values, we know it is live!
  2047. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  2048. return true;
  2049. // All values other than instructions and arguments (e.g. constants) are live.
  2050. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  2051. // If Val is a constant sized alloca in the entry block, it is live, this is
  2052. // true because it is just a reference to the stack/frame pointer, which is
  2053. // live for the whole function.
  2054. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  2055. if (AI->isStaticAlloca())
  2056. return true;
  2057. // Check to see if this value is already used in the memory instruction's
  2058. // block. If so, it's already live into the block at the very least, so we
  2059. // can reasonably fold it.
  2060. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  2061. }
  2062. /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
  2063. /// mode of the machine to fold the specified instruction into a load or store
  2064. /// that ultimately uses it. However, the specified instruction has multiple
  2065. /// uses. Given this, it may actually increase register pressure to fold it
  2066. /// into the load. For example, consider this code:
  2067. ///
  2068. /// X = ...
  2069. /// Y = X+1
  2070. /// use(Y) -> nonload/store
  2071. /// Z = Y+1
  2072. /// load Z
  2073. ///
  2074. /// In this case, Y has multiple uses, and can be folded into the load of Z
  2075. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  2076. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  2077. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  2078. /// number of computations either.
  2079. ///
  2080. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  2081. /// X was live across 'load Z' for other reasons, we actually *would* want to
  2082. /// fold the addressing mode in the Z case. This would make Y die earlier.
  2083. bool AddressingModeMatcher::
  2084. IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  2085. ExtAddrMode &AMAfter) {
  2086. if (IgnoreProfitability) return true;
  2087. // AMBefore is the addressing mode before this instruction was folded into it,
  2088. // and AMAfter is the addressing mode after the instruction was folded. Get
  2089. // the set of registers referenced by AMAfter and subtract out those
  2090. // referenced by AMBefore: this is the set of values which folding in this
  2091. // address extends the lifetime of.
  2092. //
  2093. // Note that there are only two potential values being referenced here,
  2094. // BaseReg and ScaleReg (global addresses are always available, as are any
  2095. // folded immediates).
  2096. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  2097. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  2098. // lifetime wasn't extended by adding this instruction.
  2099. if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2100. BaseReg = nullptr;
  2101. if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2102. ScaledReg = nullptr;
  2103. // If folding this instruction (and it's subexprs) didn't extend any live
  2104. // ranges, we're ok with it.
  2105. if (!BaseReg && !ScaledReg)
  2106. return true;
  2107. // If all uses of this instruction are ultimately load/store/inlineasm's,
  2108. // check to see if their addressing modes will include this instruction. If
  2109. // so, we can fold it into all uses, so it doesn't matter if it has multiple
  2110. // uses.
  2111. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  2112. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  2113. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
  2114. return false; // Has a non-memory, non-foldable use!
  2115. // Now that we know that all uses of this instruction are part of a chain of
  2116. // computation involving only operations that could theoretically be folded
  2117. // into a memory use, loop over each of these uses and see if they could
  2118. // *actually* fold the instruction.
  2119. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  2120. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  2121. Instruction *User = MemoryUses[i].first;
  2122. unsigned OpNo = MemoryUses[i].second;
  2123. // Get the access type of this use. If the use isn't a pointer, we don't
  2124. // know what it accesses.
  2125. Value *Address = User->getOperand(OpNo);
  2126. if (!Address->getType()->isPointerTy())
  2127. return false;
  2128. Type *AddressAccessTy = Address->getType()->getPointerElementType();
  2129. // Do a match against the root of this address, ignoring profitability. This
  2130. // will tell us if the addressing mode for the memory operation will
  2131. // *actually* cover the shared instruction.
  2132. ExtAddrMode Result;
  2133. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2134. TPT.getRestorationPoint();
  2135. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
  2136. MemoryInst, Result, InsertedTruncs,
  2137. PromotedInsts, TPT);
  2138. Matcher.IgnoreProfitability = true;
  2139. bool Success = Matcher.MatchAddr(Address, 0);
  2140. (void)Success; assert(Success && "Couldn't select *anything*?");
  2141. // The match was to check the profitability, the changes made are not
  2142. // part of the original matcher. Therefore, they should be dropped
  2143. // otherwise the original matcher will not present the right state.
  2144. TPT.rollback(LastKnownGood);
  2145. // If the match didn't cover I, then it won't be shared by it.
  2146. if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
  2147. I) == MatchedAddrModeInsts.end())
  2148. return false;
  2149. MatchedAddrModeInsts.clear();
  2150. }
  2151. return true;
  2152. }
  2153. } // end anonymous namespace
  2154. /// IsNonLocalValue - Return true if the specified values are defined in a
  2155. /// different basic block than BB.
  2156. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  2157. if (Instruction *I = dyn_cast<Instruction>(V))
  2158. return I->getParent() != BB;
  2159. return false;
  2160. }
  2161. /// OptimizeMemoryInst - Load and Store Instructions often have
  2162. /// addressing modes that can do significant amounts of computation. As such,
  2163. /// instruction selection will try to get the load or store to do as much
  2164. /// computation as possible for the program. The problem is that isel can only
  2165. /// see within a single block. As such, we sink as much legal addressing mode
  2166. /// stuff into the block as possible.
  2167. ///
  2168. /// This method is used to optimize both load/store and inline asms with memory
  2169. /// operands.
  2170. bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  2171. Type *AccessTy) {
  2172. Value *Repl = Addr;
  2173. // Try to collapse single-value PHI nodes. This is necessary to undo
  2174. // unprofitable PRE transformations.
  2175. SmallVector<Value*, 8> worklist;
  2176. SmallPtrSet<Value*, 16> Visited;
  2177. worklist.push_back(Addr);
  2178. // Use a worklist to iteratively look through PHI nodes, and ensure that
  2179. // the addressing mode obtained from the non-PHI roots of the graph
  2180. // are equivalent.
  2181. Value *Consensus = nullptr;
  2182. unsigned NumUsesConsensus = 0;
  2183. bool IsNumUsesConsensusValid = false;
  2184. SmallVector<Instruction*, 16> AddrModeInsts;
  2185. ExtAddrMode AddrMode;
  2186. TypePromotionTransaction TPT;
  2187. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2188. TPT.getRestorationPoint();
  2189. while (!worklist.empty()) {
  2190. Value *V = worklist.back();
  2191. worklist.pop_back();
  2192. // Break use-def graph loops.
  2193. if (!Visited.insert(V)) {
  2194. Consensus = nullptr;
  2195. break;
  2196. }
  2197. // For a PHI node, push all of its incoming values.
  2198. if (PHINode *P = dyn_cast<PHINode>(V)) {
  2199. for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
  2200. worklist.push_back(P->getIncomingValue(i));
  2201. continue;
  2202. }
  2203. // For non-PHIs, determine the addressing mode being computed.
  2204. SmallVector<Instruction*, 16> NewAddrModeInsts;
  2205. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  2206. V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
  2207. PromotedInsts, TPT);
  2208. // This check is broken into two cases with very similar code to avoid using
  2209. // getNumUses() as much as possible. Some values have a lot of uses, so
  2210. // calling getNumUses() unconditionally caused a significant compile-time
  2211. // regression.
  2212. if (!Consensus) {
  2213. Consensus = V;
  2214. AddrMode = NewAddrMode;
  2215. AddrModeInsts = NewAddrModeInsts;
  2216. continue;
  2217. } else if (NewAddrMode == AddrMode) {
  2218. if (!IsNumUsesConsensusValid) {
  2219. NumUsesConsensus = Consensus->getNumUses();
  2220. IsNumUsesConsensusValid = true;
  2221. }
  2222. // Ensure that the obtained addressing mode is equivalent to that obtained
  2223. // for all other roots of the PHI traversal. Also, when choosing one
  2224. // such root as representative, select the one with the most uses in order
  2225. // to keep the cost modeling heuristics in AddressingModeMatcher
  2226. // applicable.
  2227. unsigned NumUses = V->getNumUses();
  2228. if (NumUses > NumUsesConsensus) {
  2229. Consensus = V;
  2230. NumUsesConsensus = NumUses;
  2231. AddrModeInsts = NewAddrModeInsts;
  2232. }
  2233. continue;
  2234. }
  2235. Consensus = nullptr;
  2236. break;
  2237. }
  2238. // If the addressing mode couldn't be determined, or if multiple different
  2239. // ones were determined, bail out now.
  2240. if (!Consensus) {
  2241. TPT.rollback(LastKnownGood);
  2242. return false;
  2243. }
  2244. TPT.commit();
  2245. // Check to see if any of the instructions supersumed by this addr mode are
  2246. // non-local to I's BB.
  2247. bool AnyNonLocal = false;
  2248. for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
  2249. if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
  2250. AnyNonLocal = true;
  2251. break;
  2252. }
  2253. }
  2254. // If all the instructions matched are already in this BB, don't do anything.
  2255. if (!AnyNonLocal) {
  2256. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  2257. return false;
  2258. }
  2259. // Insert this computation right after this user. Since our caller is
  2260. // scanning from the top of the BB to the bottom, reuse of the expr are
  2261. // guaranteed to happen later.
  2262. IRBuilder<> Builder(MemoryInst);
  2263. // Now that we determined the addressing expression we want to use and know
  2264. // that we have to sink it into this block. Check to see if we have already
  2265. // done this for some other load/store instr in this block. If so, reuse the
  2266. // computation.
  2267. Value *&SunkAddr = SunkAddrs[Addr];
  2268. if (SunkAddr) {
  2269. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  2270. << *MemoryInst << "\n");
  2271. if (SunkAddr->getType() != Addr->getType())
  2272. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  2273. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  2274. TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
  2275. // By default, we use the GEP-based method when AA is used later. This
  2276. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  2277. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  2278. << *MemoryInst << "\n");
  2279. Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
  2280. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  2281. // First, find the pointer.
  2282. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  2283. ResultPtr = AddrMode.BaseReg;
  2284. AddrMode.BaseReg = nullptr;
  2285. }
  2286. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  2287. // We can't add more than one pointer together, nor can we scale a
  2288. // pointer (both of which seem meaningless).
  2289. if (ResultPtr || AddrMode.Scale != 1)
  2290. return false;
  2291. ResultPtr = AddrMode.ScaledReg;
  2292. AddrMode.Scale = 0;
  2293. }
  2294. if (AddrMode.BaseGV) {
  2295. if (ResultPtr)
  2296. return false;
  2297. ResultPtr = AddrMode.BaseGV;
  2298. }
  2299. // If the real base value actually came from an inttoptr, then the matcher
  2300. // will look through it and provide only the integer value. In that case,
  2301. // use it here.
  2302. if (!ResultPtr && AddrMode.BaseReg) {
  2303. ResultPtr =
  2304. Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
  2305. AddrMode.BaseReg = nullptr;
  2306. } else if (!ResultPtr && AddrMode.Scale == 1) {
  2307. ResultPtr =
  2308. Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
  2309. AddrMode.Scale = 0;
  2310. }
  2311. if (!ResultPtr &&
  2312. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  2313. SunkAddr = Constant::getNullValue(Addr->getType());
  2314. } else if (!ResultPtr) {
  2315. return false;
  2316. } else {
  2317. Type *I8PtrTy =
  2318. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  2319. // Start with the base register. Do this first so that subsequent address
  2320. // matching finds it last, which will prevent it from trying to match it
  2321. // as the scaled value in case it happens to be a mul. That would be
  2322. // problematic if we've sunk a different mul for the scale, because then
  2323. // we'd end up sinking both muls.
  2324. if (AddrMode.BaseReg) {
  2325. Value *V = AddrMode.BaseReg;
  2326. if (V->getType() != IntPtrTy)
  2327. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  2328. ResultIndex = V;
  2329. }
  2330. // Add the scale value.
  2331. if (AddrMode.Scale) {
  2332. Value *V = AddrMode.ScaledReg;
  2333. if (V->getType() == IntPtrTy) {
  2334. // done.
  2335. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  2336. cast<IntegerType>(V->getType())->getBitWidth()) {
  2337. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  2338. } else {
  2339. // It is only safe to sign extend the BaseReg if we know that the math
  2340. // required to create it did not overflow before we extend it. Since
  2341. // the original IR value was tossed in favor of a constant back when
  2342. // the AddrMode was created we need to bail out gracefully if widths
  2343. // do not match instead of extending it.
  2344. Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
  2345. if (I && (ResultIndex != AddrMode.BaseReg))
  2346. I->eraseFromParent();
  2347. return false;
  2348. }
  2349. if (AddrMode.Scale != 1)
  2350. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  2351. "sunkaddr");
  2352. if (ResultIndex)
  2353. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  2354. else
  2355. ResultIndex = V;
  2356. }
  2357. // Add in the Base Offset if present.
  2358. if (AddrMode.BaseOffs) {
  2359. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  2360. if (ResultIndex) {
  2361. // We need to add this separately from the scale above to help with
  2362. // SDAG consecutive load/store merging.
  2363. if (ResultPtr->getType() != I8PtrTy)
  2364. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  2365. ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
  2366. }
  2367. ResultIndex = V;
  2368. }
  2369. if (!ResultIndex) {
  2370. SunkAddr = ResultPtr;
  2371. } else {
  2372. if (ResultPtr->getType() != I8PtrTy)
  2373. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  2374. SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
  2375. }
  2376. if (SunkAddr->getType() != Addr->getType())
  2377. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  2378. }
  2379. } else {
  2380. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  2381. << *MemoryInst << "\n");
  2382. Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
  2383. Value *Result = nullptr;
  2384. // Start with the base register. Do this first so that subsequent address
  2385. // matching finds it last, which will prevent it from trying to match it
  2386. // as the scaled value in case it happens to be a mul. That would be
  2387. // problematic if we've sunk a different mul for the scale, because then
  2388. // we'd end up sinking both muls.
  2389. if (AddrMode.BaseReg) {
  2390. Value *V = AddrMode.BaseReg;
  2391. if (V->getType()->isPointerTy())
  2392. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  2393. if (V->getType() != IntPtrTy)
  2394. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  2395. Result = V;
  2396. }
  2397. // Add the scale value.
  2398. if (AddrMode.Scale) {
  2399. Value *V = AddrMode.ScaledReg;
  2400. if (V->getType() == IntPtrTy) {
  2401. // done.
  2402. } else if (V->getType()->isPointerTy()) {
  2403. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  2404. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  2405. cast<IntegerType>(V->getType())->getBitWidth()) {
  2406. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  2407. } else {
  2408. // It is only safe to sign extend the BaseReg if we know that the math
  2409. // required to create it did not overflow before we extend it. Since
  2410. // the original IR value was tossed in favor of a constant back when
  2411. // the AddrMode was created we need to bail out gracefully if widths
  2412. // do not match instead of extending it.
  2413. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  2414. if (I && (Result != AddrMode.BaseReg))
  2415. I->eraseFromParent();
  2416. return false;
  2417. }
  2418. if (AddrMode.Scale != 1)
  2419. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  2420. "sunkaddr");
  2421. if (Result)
  2422. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2423. else
  2424. Result = V;
  2425. }
  2426. // Add in the BaseGV if present.
  2427. if (AddrMode.BaseGV) {
  2428. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  2429. if (Result)
  2430. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2431. else
  2432. Result = V;
  2433. }
  2434. // Add in the Base Offset if present.
  2435. if (AddrMode.BaseOffs) {
  2436. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  2437. if (Result)
  2438. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2439. else
  2440. Result = V;
  2441. }
  2442. if (!Result)
  2443. SunkAddr = Constant::getNullValue(Addr->getType());
  2444. else
  2445. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  2446. }
  2447. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  2448. // If we have no uses, recursively delete the value and all dead instructions
  2449. // using it.
  2450. if (Repl->use_empty()) {
  2451. // This can cause recursive deletion, which can invalidate our iterator.
  2452. // Use a WeakVH to hold onto it in case this happens.
  2453. WeakVH IterHandle(CurInstIterator);
  2454. BasicBlock *BB = CurInstIterator->getParent();
  2455. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  2456. if (IterHandle != CurInstIterator) {
  2457. // If the iterator instruction was recursively deleted, start over at the
  2458. // start of the block.
  2459. CurInstIterator = BB->begin();
  2460. SunkAddrs.clear();
  2461. }
  2462. }
  2463. ++NumMemoryInsts;
  2464. return true;
  2465. }
  2466. /// OptimizeInlineAsmInst - If there are any memory operands, use
  2467. /// OptimizeMemoryInst to sink their address computing into the block when
  2468. /// possible / profitable.
  2469. bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
  2470. bool MadeChange = false;
  2471. TargetLowering::AsmOperandInfoVector
  2472. TargetConstraints = TLI->ParseConstraints(CS);
  2473. unsigned ArgNo = 0;
  2474. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  2475. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  2476. // Compute the constraint code and ConstraintType to use.
  2477. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  2478. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  2479. OpInfo.isIndirect) {
  2480. Value *OpVal = CS->getArgOperand(ArgNo++);
  2481. MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
  2482. } else if (OpInfo.Type == InlineAsm::isInput)
  2483. ArgNo++;
  2484. }
  2485. return MadeChange;
  2486. }
  2487. /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
  2488. /// basic block as the load, unless conditions are unfavorable. This allows
  2489. /// SelectionDAG to fold the extend into the load.
  2490. ///
  2491. bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
  2492. // Look for a load being extended.
  2493. LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
  2494. if (!LI) return false;
  2495. // If they're already in the same block, there's nothing to do.
  2496. if (LI->getParent() == I->getParent())
  2497. return false;
  2498. // If the load has other users and the truncate is not free, this probably
  2499. // isn't worthwhile.
  2500. if (!LI->hasOneUse() &&
  2501. TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
  2502. !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
  2503. !TLI->isTruncateFree(I->getType(), LI->getType()))
  2504. return false;
  2505. // Check whether the target supports casts folded into loads.
  2506. unsigned LType;
  2507. if (isa<ZExtInst>(I))
  2508. LType = ISD::ZEXTLOAD;
  2509. else {
  2510. assert(isa<SExtInst>(I) && "Unexpected ext type!");
  2511. LType = ISD::SEXTLOAD;
  2512. }
  2513. if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
  2514. return false;
  2515. // Move the extend into the same block as the load, so that SelectionDAG
  2516. // can fold it.
  2517. I->removeFromParent();
  2518. I->insertAfter(LI);
  2519. ++NumExtsMoved;
  2520. return true;
  2521. }
  2522. bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
  2523. BasicBlock *DefBB = I->getParent();
  2524. // If the result of a {s|z}ext and its source are both live out, rewrite all
  2525. // other uses of the source with result of extension.
  2526. Value *Src = I->getOperand(0);
  2527. if (Src->hasOneUse())
  2528. return false;
  2529. // Only do this xform if truncating is free.
  2530. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  2531. return false;
  2532. // Only safe to perform the optimization if the source is also defined in
  2533. // this block.
  2534. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  2535. return false;
  2536. bool DefIsLiveOut = false;
  2537. for (User *U : I->users()) {
  2538. Instruction *UI = cast<Instruction>(U);
  2539. // Figure out which BB this ext is used in.
  2540. BasicBlock *UserBB = UI->getParent();
  2541. if (UserBB == DefBB) continue;
  2542. DefIsLiveOut = true;
  2543. break;
  2544. }
  2545. if (!DefIsLiveOut)
  2546. return false;
  2547. // Make sure none of the uses are PHI nodes.
  2548. for (User *U : Src->users()) {
  2549. Instruction *UI = cast<Instruction>(U);
  2550. BasicBlock *UserBB = UI->getParent();
  2551. if (UserBB == DefBB) continue;
  2552. // Be conservative. We don't want this xform to end up introducing
  2553. // reloads just before load / store instructions.
  2554. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  2555. return false;
  2556. }
  2557. // InsertedTruncs - Only insert one trunc in each block once.
  2558. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  2559. bool MadeChange = false;
  2560. for (Use &U : Src->uses()) {
  2561. Instruction *User = cast<Instruction>(U.getUser());
  2562. // Figure out which BB this ext is used in.
  2563. BasicBlock *UserBB = User->getParent();
  2564. if (UserBB == DefBB) continue;
  2565. // Both src and def are live in this block. Rewrite the use.
  2566. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  2567. if (!InsertedTrunc) {
  2568. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  2569. InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
  2570. InsertedTruncsSet.insert(InsertedTrunc);
  2571. }
  2572. // Replace a use of the {s|z}ext source with a use of the result.
  2573. U = InsertedTrunc;
  2574. ++NumExtUses;
  2575. MadeChange = true;
  2576. }
  2577. return MadeChange;
  2578. }
  2579. /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
  2580. /// turned into an explicit branch.
  2581. static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
  2582. // FIXME: This should use the same heuristics as IfConversion to determine
  2583. // whether a select is better represented as a branch. This requires that
  2584. // branch probability metadata is preserved for the select, which is not the
  2585. // case currently.
  2586. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  2587. // If the branch is predicted right, an out of order CPU can avoid blocking on
  2588. // the compare. Emit cmovs on compares with a memory operand as branches to
  2589. // avoid stalls on the load from memory. If the compare has more than one use
  2590. // there's probably another cmov or setcc around so it's not worth emitting a
  2591. // branch.
  2592. if (!Cmp)
  2593. return false;
  2594. Value *CmpOp0 = Cmp->getOperand(0);
  2595. Value *CmpOp1 = Cmp->getOperand(1);
  2596. // We check that the memory operand has one use to avoid uses of the loaded
  2597. // value directly after the compare, making branches unprofitable.
  2598. return Cmp->hasOneUse() &&
  2599. ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
  2600. (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
  2601. }
  2602. /// If we have a SelectInst that will likely profit from branch prediction,
  2603. /// turn it into a branch.
  2604. bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
  2605. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  2606. // Can we convert the 'select' to CF ?
  2607. if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
  2608. return false;
  2609. TargetLowering::SelectSupportKind SelectKind;
  2610. if (VectorCond)
  2611. SelectKind = TargetLowering::VectorMaskSelect;
  2612. else if (SI->getType()->isVectorTy())
  2613. SelectKind = TargetLowering::ScalarCondVectorVal;
  2614. else
  2615. SelectKind = TargetLowering::ScalarValSelect;
  2616. // Do we have efficient codegen support for this kind of 'selects' ?
  2617. if (TLI->isSelectSupported(SelectKind)) {
  2618. // We have efficient codegen support for the select instruction.
  2619. // Check if it is profitable to keep this 'select'.
  2620. if (!TLI->isPredictableSelectExpensive() ||
  2621. !isFormingBranchFromSelectProfitable(SI))
  2622. return false;
  2623. }
  2624. ModifiedDT = true;
  2625. // First, we split the block containing the select into 2 blocks.
  2626. BasicBlock *StartBlock = SI->getParent();
  2627. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
  2628. BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  2629. // Create a new block serving as the landing pad for the branch.
  2630. BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
  2631. NextBlock->getParent(), NextBlock);
  2632. // Move the unconditional branch from the block with the select in it into our
  2633. // landing pad block.
  2634. StartBlock->getTerminator()->eraseFromParent();
  2635. BranchInst::Create(NextBlock, SmallBlock);
  2636. // Insert the real conditional branch based on the original condition.
  2637. BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
  2638. // The select itself is replaced with a PHI Node.
  2639. PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
  2640. PN->takeName(SI);
  2641. PN->addIncoming(SI->getTrueValue(), StartBlock);
  2642. PN->addIncoming(SI->getFalseValue(), SmallBlock);
  2643. SI->replaceAllUsesWith(PN);
  2644. SI->eraseFromParent();
  2645. // Instruct OptimizeBlock to skip to the next block.
  2646. CurInstIterator = StartBlock->end();
  2647. ++NumSelectsExpanded;
  2648. return true;
  2649. }
  2650. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  2651. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  2652. int SplatElem = -1;
  2653. for (unsigned i = 0; i < Mask.size(); ++i) {
  2654. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  2655. return false;
  2656. SplatElem = Mask[i];
  2657. }
  2658. return true;
  2659. }
  2660. /// Some targets have expensive vector shifts if the lanes aren't all the same
  2661. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  2662. /// it's often worth sinking a shufflevector splat down to its use so that
  2663. /// codegen can spot all lanes are identical.
  2664. bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  2665. BasicBlock *DefBB = SVI->getParent();
  2666. // Only do this xform if variable vector shifts are particularly expensive.
  2667. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  2668. return false;
  2669. // We only expect better codegen by sinking a shuffle if we can recognise a
  2670. // constant splat.
  2671. if (!isBroadcastShuffle(SVI))
  2672. return false;
  2673. // InsertedShuffles - Only insert a shuffle in each block once.
  2674. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  2675. bool MadeChange = false;
  2676. for (User *U : SVI->users()) {
  2677. Instruction *UI = cast<Instruction>(U);
  2678. // Figure out which BB this ext is used in.
  2679. BasicBlock *UserBB = UI->getParent();
  2680. if (UserBB == DefBB) continue;
  2681. // For now only apply this when the splat is used by a shift instruction.
  2682. if (!UI->isShift()) continue;
  2683. // Everything checks out, sink the shuffle if the user's block doesn't
  2684. // already have a copy.
  2685. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  2686. if (!InsertedShuffle) {
  2687. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  2688. InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
  2689. SVI->getOperand(1),
  2690. SVI->getOperand(2), "", InsertPt);
  2691. }
  2692. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  2693. MadeChange = true;
  2694. }
  2695. // If we removed all uses, nuke the shuffle.
  2696. if (SVI->use_empty()) {
  2697. SVI->eraseFromParent();
  2698. MadeChange = true;
  2699. }
  2700. return MadeChange;
  2701. }
  2702. bool CodeGenPrepare::OptimizeInst(Instruction *I) {
  2703. if (PHINode *P = dyn_cast<PHINode>(I)) {
  2704. // It is possible for very late stage optimizations (such as SimplifyCFG)
  2705. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  2706. // trivial PHI, go ahead and zap it here.
  2707. if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
  2708. TLInfo, DT)) {
  2709. P->replaceAllUsesWith(V);
  2710. P->eraseFromParent();
  2711. ++NumPHIsElim;
  2712. return true;
  2713. }
  2714. return false;
  2715. }
  2716. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  2717. // If the source of the cast is a constant, then this should have
  2718. // already been constant folded. The only reason NOT to constant fold
  2719. // it is if something (e.g. LSR) was careful to place the constant
  2720. // evaluation in a block other than then one that uses it (e.g. to hoist
  2721. // the address of globals out of a loop). If this is the case, we don't
  2722. // want to forward-subst the cast.
  2723. if (isa<Constant>(CI->getOperand(0)))
  2724. return false;
  2725. if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
  2726. return true;
  2727. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  2728. /// Sink a zext or sext into its user blocks if the target type doesn't
  2729. /// fit in one register
  2730. if (TLI && TLI->getTypeAction(CI->getContext(),
  2731. TLI->getValueType(CI->getType())) ==
  2732. TargetLowering::TypeExpandInteger) {
  2733. return SinkCast(CI);
  2734. } else {
  2735. bool MadeChange = MoveExtToFormExtLoad(I);
  2736. return MadeChange | OptimizeExtUses(I);
  2737. }
  2738. }
  2739. return false;
  2740. }
  2741. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  2742. if (!TLI || !TLI->hasMultipleConditionRegisters())
  2743. return OptimizeCmpExpression(CI);
  2744. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  2745. if (TLI)
  2746. return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
  2747. return false;
  2748. }
  2749. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  2750. if (TLI)
  2751. return OptimizeMemoryInst(I, SI->getOperand(1),
  2752. SI->getOperand(0)->getType());
  2753. return false;
  2754. }
  2755. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  2756. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  2757. BinOp->getOpcode() == Instruction::LShr)) {
  2758. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  2759. if (TLI && CI && TLI->hasExtractBitsInsn())
  2760. return OptimizeExtractBits(BinOp, CI, *TLI);
  2761. return false;
  2762. }
  2763. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  2764. if (GEPI->hasAllZeroIndices()) {
  2765. /// The GEP operand must be a pointer, so must its result -> BitCast
  2766. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  2767. GEPI->getName(), GEPI);
  2768. GEPI->replaceAllUsesWith(NC);
  2769. GEPI->eraseFromParent();
  2770. ++NumGEPsElim;
  2771. OptimizeInst(NC);
  2772. return true;
  2773. }
  2774. return false;
  2775. }
  2776. if (CallInst *CI = dyn_cast<CallInst>(I))
  2777. return OptimizeCallInst(CI);
  2778. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  2779. return OptimizeSelectInst(SI);
  2780. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  2781. return OptimizeShuffleVectorInst(SVI);
  2782. return false;
  2783. }
  2784. // In this pass we look for GEP and cast instructions that are used
  2785. // across basic blocks and rewrite them to improve basic-block-at-a-time
  2786. // selection.
  2787. bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
  2788. SunkAddrs.clear();
  2789. bool MadeChange = false;
  2790. CurInstIterator = BB.begin();
  2791. while (CurInstIterator != BB.end())
  2792. MadeChange |= OptimizeInst(CurInstIterator++);
  2793. MadeChange |= DupRetToEnableTailCallOpts(&BB);
  2794. return MadeChange;
  2795. }
  2796. // llvm.dbg.value is far away from the value then iSel may not be able
  2797. // handle it properly. iSel will drop llvm.dbg.value if it can not
  2798. // find a node corresponding to the value.
  2799. bool CodeGenPrepare::PlaceDbgValues(Function &F) {
  2800. bool MadeChange = false;
  2801. for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  2802. Instruction *PrevNonDbgInst = nullptr;
  2803. for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
  2804. Instruction *Insn = BI; ++BI;
  2805. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  2806. // Leave dbg.values that refer to an alloca alone. These
  2807. // instrinsics describe the address of a variable (= the alloca)
  2808. // being taken. They should not be moved next to the alloca
  2809. // (and to the beginning of the scope), but rather stay close to
  2810. // where said address is used.
  2811. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  2812. PrevNonDbgInst = Insn;
  2813. continue;
  2814. }
  2815. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  2816. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  2817. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  2818. DVI->removeFromParent();
  2819. if (isa<PHINode>(VI))
  2820. DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
  2821. else
  2822. DVI->insertAfter(VI);
  2823. MadeChange = true;
  2824. ++NumDbgValueMoved;
  2825. }
  2826. }
  2827. }
  2828. return MadeChange;
  2829. }
  2830. // If there is a sequence that branches based on comparing a single bit
  2831. // against zero that can be combined into a single instruction, and the
  2832. // target supports folding these into a single instruction, sink the
  2833. // mask and compare into the branch uses. Do this before OptimizeBlock ->
  2834. // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
  2835. // searched for.
  2836. bool CodeGenPrepare::sinkAndCmp(Function &F) {
  2837. if (!EnableAndCmpSinking)
  2838. return false;
  2839. if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
  2840. return false;
  2841. bool MadeChange = false;
  2842. for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
  2843. BasicBlock *BB = I++;
  2844. // Does this BB end with the following?
  2845. // %andVal = and %val, #single-bit-set
  2846. // %icmpVal = icmp %andResult, 0
  2847. // br i1 %cmpVal label %dest1, label %dest2"
  2848. BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
  2849. if (!Brcc || !Brcc->isConditional())
  2850. continue;
  2851. ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
  2852. if (!Cmp || Cmp->getParent() != BB)
  2853. continue;
  2854. ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
  2855. if (!Zero || !Zero->isZero())
  2856. continue;
  2857. Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
  2858. if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
  2859. continue;
  2860. ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
  2861. if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
  2862. continue;
  2863. DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
  2864. // Push the "and; icmp" for any users that are conditional branches.
  2865. // Since there can only be one branch use per BB, we don't need to keep
  2866. // track of which BBs we insert into.
  2867. for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
  2868. UI != E; ) {
  2869. Use &TheUse = *UI;
  2870. // Find brcc use.
  2871. BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
  2872. ++UI;
  2873. if (!BrccUser || !BrccUser->isConditional())
  2874. continue;
  2875. BasicBlock *UserBB = BrccUser->getParent();
  2876. if (UserBB == BB) continue;
  2877. DEBUG(dbgs() << "found Brcc use\n");
  2878. // Sink the "and; icmp" to use.
  2879. MadeChange = true;
  2880. BinaryOperator *NewAnd =
  2881. BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
  2882. BrccUser);
  2883. CmpInst *NewCmp =
  2884. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
  2885. "", BrccUser);
  2886. TheUse = NewCmp;
  2887. ++NumAndCmpsMoved;
  2888. DEBUG(BrccUser->getParent()->dump());
  2889. }
  2890. }
  2891. return MadeChange;
  2892. }