CodeGenPrepare.cpp 107 KB

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