InstructionCombining.cpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109
  1. //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
  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. // InstructionCombining - Combine instructions to form fewer, simple
  11. // instructions. This pass does not modify the CFG. This pass is where
  12. // algebraic simplification happens.
  13. //
  14. // This pass combines things like:
  15. // %Y = add i32 %X, 1
  16. // %Z = add i32 %Y, 1
  17. // into:
  18. // %Z = add i32 %X, 2
  19. //
  20. // This is a simple worklist driven algorithm.
  21. //
  22. // This pass guarantees that the following canonicalizations are performed on
  23. // the program:
  24. // 1. If a binary operator has a constant operand, it is moved to the RHS
  25. // 2. Bitwise operators with constant operands are always grouped so that
  26. // shifts are performed first, then or's, then and's, then xor's.
  27. // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
  28. // 4. All cmp instructions on boolean values are replaced with logical ops
  29. // 5. add X, X is represented as (X*2) => (X << 1)
  30. // 6. Multiplies with a power-of-two constant argument are transformed into
  31. // shifts.
  32. // ... etc.
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "llvm/Transforms/InstCombine/InstCombine.h"
  36. #include "InstCombineInternal.h"
  37. #include "llvm-c/Initialization.h"
  38. #include "llvm/ADT/SmallPtrSet.h"
  39. #include "llvm/ADT/Statistic.h"
  40. #include "llvm/ADT/StringSwitch.h"
  41. #include "llvm/Analysis/AssumptionCache.h"
  42. #include "llvm/Analysis/CFG.h"
  43. #include "llvm/Analysis/ConstantFolding.h"
  44. #include "llvm/Analysis/InstructionSimplify.h"
  45. #include "llvm/Analysis/LibCallSemantics.h"
  46. #include "llvm/Analysis/LoopInfo.h"
  47. #include "llvm/Analysis/MemoryBuiltins.h"
  48. #include "llvm/Analysis/TargetLibraryInfo.h"
  49. #include "llvm/Analysis/ValueTracking.h"
  50. #include "llvm/IR/CFG.h"
  51. #include "llvm/IR/DataLayout.h"
  52. #include "llvm/IR/Dominators.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/IntrinsicInst.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/ValueHandle.h"
  57. #include "llvm/Support/CommandLine.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Transforms/Scalar.h"
  61. #include "llvm/Transforms/Utils/Local.h"
  62. #include <algorithm>
  63. #include <climits>
  64. using namespace llvm;
  65. using namespace llvm::PatternMatch;
  66. #define DEBUG_TYPE "instcombine"
  67. STATISTIC(NumCombined , "Number of insts combined");
  68. STATISTIC(NumConstProp, "Number of constant folds");
  69. STATISTIC(NumDeadInst , "Number of dead inst eliminated");
  70. STATISTIC(NumSunkInst , "Number of instructions sunk");
  71. STATISTIC(NumExpand, "Number of expansions");
  72. STATISTIC(NumFactor , "Number of factorizations");
  73. STATISTIC(NumReassoc , "Number of reassociations");
  74. Value *InstCombiner::EmitGEPOffset(User *GEP) {
  75. return llvm::EmitGEPOffset(Builder, DL, GEP);
  76. }
  77. /// ShouldChangeType - Return true if it is desirable to convert a computation
  78. /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
  79. /// type for example, or from a smaller to a larger illegal type.
  80. bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
  81. assert(From->isIntegerTy() && To->isIntegerTy());
  82. unsigned FromWidth = From->getPrimitiveSizeInBits();
  83. unsigned ToWidth = To->getPrimitiveSizeInBits();
  84. bool FromLegal = DL.isLegalInteger(FromWidth);
  85. bool ToLegal = DL.isLegalInteger(ToWidth);
  86. // If this is a legal integer from type, and the result would be an illegal
  87. // type, don't do the transformation.
  88. if (FromLegal && !ToLegal)
  89. return false;
  90. // Otherwise, if both are illegal, do not increase the size of the result. We
  91. // do allow things like i160 -> i64, but not i64 -> i160.
  92. if (!FromLegal && !ToLegal && ToWidth > FromWidth)
  93. return false;
  94. return true;
  95. }
  96. // Return true, if No Signed Wrap should be maintained for I.
  97. // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
  98. // where both B and C should be ConstantInts, results in a constant that does
  99. // not overflow. This function only handles the Add and Sub opcodes. For
  100. // all other opcodes, the function conservatively returns false.
  101. static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
  102. OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
  103. if (!OBO || !OBO->hasNoSignedWrap()) {
  104. return false;
  105. }
  106. // We reason about Add and Sub Only.
  107. Instruction::BinaryOps Opcode = I.getOpcode();
  108. if (Opcode != Instruction::Add &&
  109. Opcode != Instruction::Sub) {
  110. return false;
  111. }
  112. ConstantInt *CB = dyn_cast<ConstantInt>(B);
  113. ConstantInt *CC = dyn_cast<ConstantInt>(C);
  114. if (!CB || !CC) {
  115. return false;
  116. }
  117. const APInt &BVal = CB->getValue();
  118. const APInt &CVal = CC->getValue();
  119. bool Overflow = false;
  120. if (Opcode == Instruction::Add) {
  121. BVal.sadd_ov(CVal, Overflow);
  122. } else {
  123. BVal.ssub_ov(CVal, Overflow);
  124. }
  125. return !Overflow;
  126. }
  127. /// Conservatively clears subclassOptionalData after a reassociation or
  128. /// commutation. We preserve fast-math flags when applicable as they can be
  129. /// preserved.
  130. static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
  131. FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
  132. if (!FPMO) {
  133. I.clearSubclassOptionalData();
  134. return;
  135. }
  136. FastMathFlags FMF = I.getFastMathFlags();
  137. I.clearSubclassOptionalData();
  138. I.setFastMathFlags(FMF);
  139. }
  140. /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
  141. /// operators which are associative or commutative:
  142. //
  143. // Commutative operators:
  144. //
  145. // 1. Order operands such that they are listed from right (least complex) to
  146. // left (most complex). This puts constants before unary operators before
  147. // binary operators.
  148. //
  149. // Associative operators:
  150. //
  151. // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
  152. // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
  153. //
  154. // Associative and commutative operators:
  155. //
  156. // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
  157. // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
  158. // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
  159. // if C1 and C2 are constants.
  160. //
  161. bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
  162. Instruction::BinaryOps Opcode = I.getOpcode();
  163. bool Changed = false;
  164. do {
  165. // Order operands such that they are listed from right (least complex) to
  166. // left (most complex). This puts constants before unary operators before
  167. // binary operators.
  168. if (I.isCommutative() && getComplexity(I.getOperand(0)) <
  169. getComplexity(I.getOperand(1)))
  170. Changed = !I.swapOperands();
  171. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
  172. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
  173. if (I.isAssociative()) {
  174. // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
  175. if (Op0 && Op0->getOpcode() == Opcode) {
  176. Value *A = Op0->getOperand(0);
  177. Value *B = Op0->getOperand(1);
  178. Value *C = I.getOperand(1);
  179. // Does "B op C" simplify?
  180. if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
  181. // It simplifies to V. Form "A op V".
  182. I.setOperand(0, A);
  183. I.setOperand(1, V);
  184. // Conservatively clear the optional flags, since they may not be
  185. // preserved by the reassociation.
  186. if (MaintainNoSignedWrap(I, B, C) &&
  187. (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
  188. // Note: this is only valid because SimplifyBinOp doesn't look at
  189. // the operands to Op0.
  190. I.clearSubclassOptionalData();
  191. I.setHasNoSignedWrap(true);
  192. } else {
  193. ClearSubclassDataAfterReassociation(I);
  194. }
  195. Changed = true;
  196. ++NumReassoc;
  197. continue;
  198. }
  199. }
  200. // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
  201. if (Op1 && Op1->getOpcode() == Opcode) {
  202. Value *A = I.getOperand(0);
  203. Value *B = Op1->getOperand(0);
  204. Value *C = Op1->getOperand(1);
  205. // Does "A op B" simplify?
  206. if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
  207. // It simplifies to V. Form "V op C".
  208. I.setOperand(0, V);
  209. I.setOperand(1, C);
  210. // Conservatively clear the optional flags, since they may not be
  211. // preserved by the reassociation.
  212. ClearSubclassDataAfterReassociation(I);
  213. Changed = true;
  214. ++NumReassoc;
  215. continue;
  216. }
  217. }
  218. }
  219. if (I.isAssociative() && I.isCommutative()) {
  220. // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
  221. if (Op0 && Op0->getOpcode() == Opcode) {
  222. Value *A = Op0->getOperand(0);
  223. Value *B = Op0->getOperand(1);
  224. Value *C = I.getOperand(1);
  225. // Does "C op A" simplify?
  226. if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
  227. // It simplifies to V. Form "V op B".
  228. I.setOperand(0, V);
  229. I.setOperand(1, B);
  230. // Conservatively clear the optional flags, since they may not be
  231. // preserved by the reassociation.
  232. ClearSubclassDataAfterReassociation(I);
  233. Changed = true;
  234. ++NumReassoc;
  235. continue;
  236. }
  237. }
  238. // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
  239. if (Op1 && Op1->getOpcode() == Opcode) {
  240. Value *A = I.getOperand(0);
  241. Value *B = Op1->getOperand(0);
  242. Value *C = Op1->getOperand(1);
  243. // Does "C op A" simplify?
  244. if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
  245. // It simplifies to V. Form "B op V".
  246. I.setOperand(0, B);
  247. I.setOperand(1, V);
  248. // Conservatively clear the optional flags, since they may not be
  249. // preserved by the reassociation.
  250. ClearSubclassDataAfterReassociation(I);
  251. Changed = true;
  252. ++NumReassoc;
  253. continue;
  254. }
  255. }
  256. // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
  257. // if C1 and C2 are constants.
  258. if (Op0 && Op1 &&
  259. Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
  260. isa<Constant>(Op0->getOperand(1)) &&
  261. isa<Constant>(Op1->getOperand(1)) &&
  262. Op0->hasOneUse() && Op1->hasOneUse()) {
  263. Value *A = Op0->getOperand(0);
  264. Constant *C1 = cast<Constant>(Op0->getOperand(1));
  265. Value *B = Op1->getOperand(0);
  266. Constant *C2 = cast<Constant>(Op1->getOperand(1));
  267. Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
  268. BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
  269. if (isa<FPMathOperator>(New)) {
  270. FastMathFlags Flags = I.getFastMathFlags();
  271. Flags &= Op0->getFastMathFlags();
  272. Flags &= Op1->getFastMathFlags();
  273. New->setFastMathFlags(Flags);
  274. }
  275. InsertNewInstWith(New, I);
  276. New->takeName(Op1);
  277. I.setOperand(0, New);
  278. I.setOperand(1, Folded);
  279. // Conservatively clear the optional flags, since they may not be
  280. // preserved by the reassociation.
  281. ClearSubclassDataAfterReassociation(I);
  282. Changed = true;
  283. continue;
  284. }
  285. }
  286. // No further simplifications.
  287. return Changed;
  288. } while (1);
  289. }
  290. /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
  291. /// "(X LOp Y) ROp (X LOp Z)".
  292. static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
  293. Instruction::BinaryOps ROp) {
  294. switch (LOp) {
  295. default:
  296. return false;
  297. case Instruction::And:
  298. // And distributes over Or and Xor.
  299. switch (ROp) {
  300. default:
  301. return false;
  302. case Instruction::Or:
  303. case Instruction::Xor:
  304. return true;
  305. }
  306. case Instruction::Mul:
  307. // Multiplication distributes over addition and subtraction.
  308. switch (ROp) {
  309. default:
  310. return false;
  311. case Instruction::Add:
  312. case Instruction::Sub:
  313. return true;
  314. }
  315. case Instruction::Or:
  316. // Or distributes over And.
  317. switch (ROp) {
  318. default:
  319. return false;
  320. case Instruction::And:
  321. return true;
  322. }
  323. }
  324. }
  325. /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
  326. /// "(X ROp Z) LOp (Y ROp Z)".
  327. static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
  328. Instruction::BinaryOps ROp) {
  329. if (Instruction::isCommutative(ROp))
  330. return LeftDistributesOverRight(ROp, LOp);
  331. switch (LOp) {
  332. default:
  333. return false;
  334. // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
  335. // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
  336. // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
  337. case Instruction::And:
  338. case Instruction::Or:
  339. case Instruction::Xor:
  340. switch (ROp) {
  341. default:
  342. return false;
  343. case Instruction::Shl:
  344. case Instruction::LShr:
  345. case Instruction::AShr:
  346. return true;
  347. }
  348. }
  349. // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
  350. // but this requires knowing that the addition does not overflow and other
  351. // such subtleties.
  352. return false;
  353. }
  354. /// This function returns identity value for given opcode, which can be used to
  355. /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
  356. static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
  357. if (isa<Constant>(V))
  358. return nullptr;
  359. if (OpCode == Instruction::Mul)
  360. return ConstantInt::get(V->getType(), 1);
  361. // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
  362. return nullptr;
  363. }
  364. /// This function factors binary ops which can be combined using distributive
  365. /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
  366. /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
  367. /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
  368. /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
  369. /// RHS to 4.
  370. static Instruction::BinaryOps
  371. getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
  372. BinaryOperator *Op, Value *&LHS, Value *&RHS) {
  373. if (!Op)
  374. return Instruction::BinaryOpsEnd;
  375. LHS = Op->getOperand(0);
  376. RHS = Op->getOperand(1);
  377. switch (TopLevelOpcode) {
  378. default:
  379. return Op->getOpcode();
  380. case Instruction::Add:
  381. case Instruction::Sub:
  382. if (Op->getOpcode() == Instruction::Shl) {
  383. if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
  384. // The multiplier is really 1 << CST.
  385. RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
  386. return Instruction::Mul;
  387. }
  388. }
  389. return Op->getOpcode();
  390. }
  391. // TODO: We can add other conversions e.g. shr => div etc.
  392. }
  393. /// This tries to simplify binary operations by factorizing out common terms
  394. /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
  395. static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
  396. const DataLayout &DL, BinaryOperator &I,
  397. Instruction::BinaryOps InnerOpcode, Value *A,
  398. Value *B, Value *C, Value *D) {
  399. // If any of A, B, C, D are null, we can not factor I, return early.
  400. // Checking A and C should be enough.
  401. if (!A || !C || !B || !D)
  402. return nullptr;
  403. Value *V = nullptr;
  404. Value *SimplifiedInst = nullptr;
  405. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  406. Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
  407. // Does "X op' Y" always equal "Y op' X"?
  408. bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
  409. // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
  410. if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
  411. // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
  412. // commutative case, "(A op' B) op (C op' A)"?
  413. if (A == C || (InnerCommutative && A == D)) {
  414. if (A != C)
  415. std::swap(C, D);
  416. // Consider forming "A op' (B op D)".
  417. // If "B op D" simplifies then it can be formed with no cost.
  418. V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
  419. // If "B op D" doesn't simplify then only go on if both of the existing
  420. // operations "A op' B" and "C op' D" will be zapped as no longer used.
  421. if (!V && LHS->hasOneUse() && RHS->hasOneUse())
  422. V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
  423. if (V) {
  424. SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
  425. }
  426. }
  427. // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
  428. if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
  429. // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
  430. // commutative case, "(A op' B) op (B op' D)"?
  431. if (B == D || (InnerCommutative && B == C)) {
  432. if (B != D)
  433. std::swap(C, D);
  434. // Consider forming "(A op C) op' B".
  435. // If "A op C" simplifies then it can be formed with no cost.
  436. V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
  437. // If "A op C" doesn't simplify then only go on if both of the existing
  438. // operations "A op' B" and "C op' D" will be zapped as no longer used.
  439. if (!V && LHS->hasOneUse() && RHS->hasOneUse())
  440. V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
  441. if (V) {
  442. SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
  443. }
  444. }
  445. if (SimplifiedInst) {
  446. ++NumFactor;
  447. SimplifiedInst->takeName(&I);
  448. // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
  449. // TODO: Check for NUW.
  450. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
  451. if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
  452. bool HasNSW = false;
  453. if (isa<OverflowingBinaryOperator>(&I))
  454. HasNSW = I.hasNoSignedWrap();
  455. if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
  456. if (isa<OverflowingBinaryOperator>(Op0))
  457. HasNSW &= Op0->hasNoSignedWrap();
  458. if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
  459. if (isa<OverflowingBinaryOperator>(Op1))
  460. HasNSW &= Op1->hasNoSignedWrap();
  461. // We can propogate 'nsw' if we know that
  462. // %Y = mul nsw i16 %X, C
  463. // %Z = add nsw i16 %Y, %X
  464. // =>
  465. // %Z = mul nsw i16 %X, C+1
  466. //
  467. // iff C+1 isn't INT_MIN
  468. const APInt *CInt;
  469. if (TopLevelOpcode == Instruction::Add &&
  470. InnerOpcode == Instruction::Mul)
  471. if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
  472. BO->setHasNoSignedWrap(HasNSW);
  473. }
  474. }
  475. }
  476. return SimplifiedInst;
  477. }
  478. /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
  479. /// which some other binary operation distributes over either by factorizing
  480. /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
  481. /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
  482. /// a win). Returns the simplified value, or null if it didn't simplify.
  483. Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
  484. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  485. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
  486. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
  487. // Factorization.
  488. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
  489. auto TopLevelOpcode = I.getOpcode();
  490. auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
  491. auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
  492. // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
  493. // a common term.
  494. if (LHSOpcode == RHSOpcode) {
  495. if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
  496. return V;
  497. }
  498. // The instruction has the form "(A op' B) op (C)". Try to factorize common
  499. // term.
  500. if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
  501. getIdentityValue(LHSOpcode, RHS)))
  502. return V;
  503. // The instruction has the form "(B) op (C op' D)". Try to factorize common
  504. // term.
  505. if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
  506. getIdentityValue(RHSOpcode, LHS), C, D))
  507. return V;
  508. // Expansion.
  509. if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
  510. // The instruction has the form "(A op' B) op C". See if expanding it out
  511. // to "(A op C) op' (B op C)" results in simplifications.
  512. Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
  513. Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
  514. // Do "A op C" and "B op C" both simplify?
  515. if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
  516. if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
  517. // They do! Return "L op' R".
  518. ++NumExpand;
  519. // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
  520. if ((L == A && R == B) ||
  521. (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
  522. return Op0;
  523. // Otherwise return "L op' R" if it simplifies.
  524. if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
  525. return V;
  526. // Otherwise, create a new instruction.
  527. C = Builder->CreateBinOp(InnerOpcode, L, R);
  528. C->takeName(&I);
  529. return C;
  530. }
  531. }
  532. if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
  533. // The instruction has the form "A op (B op' C)". See if expanding it out
  534. // to "(A op B) op' (A op C)" results in simplifications.
  535. Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
  536. Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
  537. // Do "A op B" and "A op C" both simplify?
  538. if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
  539. if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
  540. // They do! Return "L op' R".
  541. ++NumExpand;
  542. // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
  543. if ((L == B && R == C) ||
  544. (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
  545. return Op1;
  546. // Otherwise return "L op' R" if it simplifies.
  547. if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
  548. return V;
  549. // Otherwise, create a new instruction.
  550. A = Builder->CreateBinOp(InnerOpcode, L, R);
  551. A->takeName(&I);
  552. return A;
  553. }
  554. }
  555. return nullptr;
  556. }
  557. // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
  558. // if the LHS is a constant zero (which is the 'negate' form).
  559. //
  560. Value *InstCombiner::dyn_castNegVal(Value *V) const {
  561. if (BinaryOperator::isNeg(V))
  562. return BinaryOperator::getNegArgument(V);
  563. // Constants can be considered to be negated values if they can be folded.
  564. if (ConstantInt *C = dyn_cast<ConstantInt>(V))
  565. return ConstantExpr::getNeg(C);
  566. if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
  567. if (C->getType()->getElementType()->isIntegerTy())
  568. return ConstantExpr::getNeg(C);
  569. return nullptr;
  570. }
  571. // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
  572. // instruction if the LHS is a constant negative zero (which is the 'negate'
  573. // form).
  574. //
  575. Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
  576. if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
  577. return BinaryOperator::getFNegArgument(V);
  578. // Constants can be considered to be negated values if they can be folded.
  579. if (ConstantFP *C = dyn_cast<ConstantFP>(V))
  580. return ConstantExpr::getFNeg(C);
  581. if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
  582. if (C->getType()->getElementType()->isFloatingPointTy())
  583. return ConstantExpr::getFNeg(C);
  584. return nullptr;
  585. }
  586. static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
  587. InstCombiner *IC) {
  588. if (CastInst *CI = dyn_cast<CastInst>(&I)) {
  589. return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
  590. }
  591. // Figure out if the constant is the left or the right argument.
  592. bool ConstIsRHS = isa<Constant>(I.getOperand(1));
  593. Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
  594. if (Constant *SOC = dyn_cast<Constant>(SO)) {
  595. if (ConstIsRHS)
  596. return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
  597. return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
  598. }
  599. Value *Op0 = SO, *Op1 = ConstOperand;
  600. if (!ConstIsRHS)
  601. std::swap(Op0, Op1);
  602. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
  603. Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
  604. SO->getName()+".op");
  605. Instruction *FPInst = dyn_cast<Instruction>(RI);
  606. if (FPInst && isa<FPMathOperator>(FPInst))
  607. FPInst->copyFastMathFlags(BO);
  608. return RI;
  609. }
  610. if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
  611. return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
  612. SO->getName()+".cmp");
  613. if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
  614. return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
  615. SO->getName()+".cmp");
  616. llvm_unreachable("Unknown binary instruction type!");
  617. }
  618. // FoldOpIntoSelect - Given an instruction with a select as one operand and a
  619. // constant as the other operand, try to fold the binary operator into the
  620. // select arguments. This also works for Cast instructions, which obviously do
  621. // not have a second operand.
  622. Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
  623. // Don't modify shared select instructions
  624. if (!SI->hasOneUse()) return nullptr;
  625. Value *TV = SI->getOperand(1);
  626. Value *FV = SI->getOperand(2);
  627. if (isa<Constant>(TV) || isa<Constant>(FV)) {
  628. // Bool selects with constant operands can be folded to logical ops.
  629. if (SI->getType()->isIntegerTy(1)) return nullptr;
  630. // If it's a bitcast involving vectors, make sure it has the same number of
  631. // elements on both sides.
  632. if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
  633. VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
  634. VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
  635. // Verify that either both or neither are vectors.
  636. if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
  637. // If vectors, verify that they have the same number of elements.
  638. if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
  639. return nullptr;
  640. }
  641. // Test if a CmpInst instruction is used exclusively by a select as
  642. // part of a minimum or maximum operation. If so, refrain from doing
  643. // any other folding. This helps out other analyses which understand
  644. // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
  645. // and CodeGen. And in this case, at least one of the comparison
  646. // operands has at least one user besides the compare (the select),
  647. // which would often largely negate the benefit of folding anyway.
  648. if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
  649. if (CI->hasOneUse()) {
  650. Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
  651. if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
  652. (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
  653. return nullptr;
  654. }
  655. }
  656. Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
  657. Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
  658. return SelectInst::Create(SI->getCondition(),
  659. SelectTrueVal, SelectFalseVal);
  660. }
  661. return nullptr;
  662. }
  663. // HLSL change begins
  664. static bool HasUndefValue(PHINode *PHI) {
  665. for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++)
  666. if (isa<UndefValue>(PHI->getIncomingValue(i)))
  667. return true;
  668. return false;
  669. }
  670. // HLSL change ends
  671. /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
  672. /// has a PHI node as operand #0, see if we can fold the instruction into the
  673. /// PHI (which is only possible if all operands to the PHI are constants).
  674. ///
  675. Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
  676. PHINode *PN = cast<PHINode>(I.getOperand(0));
  677. unsigned NumPHIValues = PN->getNumIncomingValues();
  678. if (NumPHIValues == 0)
  679. return nullptr;
  680. // HLSL Change begins
  681. // Don't fold a binary op into PHI having undef value(s).
  682. if (HasUndefValue(PN))
  683. return nullptr;
  684. // HLSL Change ends
  685. // We normally only transform phis with a single use. However, if a PHI has
  686. // multiple uses and they are all the same operation, we can fold *all* of the
  687. // uses into the PHI.
  688. if (!PN->hasOneUse()) {
  689. // Walk the use list for the instruction, comparing them to I.
  690. for (User *U : PN->users()) {
  691. Instruction *UI = cast<Instruction>(U);
  692. if (UI != &I && !I.isIdenticalTo(UI))
  693. return nullptr;
  694. }
  695. // Otherwise, we can replace *all* users with the new PHI we form.
  696. }
  697. // Check to see if all of the operands of the PHI are simple constants
  698. // (constantint/constantfp/undef). If there is one non-constant value,
  699. // remember the BB it is in. If there is more than one or if *it* is a PHI,
  700. // bail out. We don't do arbitrary constant expressions here because moving
  701. // their computation can be expensive without a cost model.
  702. BasicBlock *NonConstBB = nullptr;
  703. for (unsigned i = 0; i != NumPHIValues; ++i) {
  704. Value *InVal = PN->getIncomingValue(i);
  705. if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
  706. continue;
  707. if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
  708. if (NonConstBB) return nullptr; // More than one non-const value.
  709. NonConstBB = PN->getIncomingBlock(i);
  710. // If the InVal is an invoke at the end of the pred block, then we can't
  711. // insert a computation after it without breaking the edge.
  712. if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
  713. if (II->getParent() == NonConstBB)
  714. return nullptr;
  715. // If the incoming non-constant value is in I's block, we will remove one
  716. // instruction, but insert another equivalent one, leading to infinite
  717. // instcombine.
  718. if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
  719. return nullptr;
  720. }
  721. // If there is exactly one non-constant value, we can insert a copy of the
  722. // operation in that block. However, if this is a critical edge, we would be
  723. // inserting the computation on some other paths (e.g. inside a loop). Only
  724. // do this if the pred block is unconditionally branching into the phi block.
  725. if (NonConstBB != nullptr) {
  726. BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
  727. if (!BI || !BI->isUnconditional()) return nullptr;
  728. }
  729. // Okay, we can do the transformation: create the new PHI node.
  730. PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
  731. InsertNewInstBefore(NewPN, *PN);
  732. NewPN->takeName(PN);
  733. // If we are going to have to insert a new computation, do so right before the
  734. // predecessors terminator.
  735. if (NonConstBB)
  736. Builder->SetInsertPoint(NonConstBB->getTerminator());
  737. // Next, add all of the operands to the PHI.
  738. if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
  739. // We only currently try to fold the condition of a select when it is a phi,
  740. // not the true/false values.
  741. Value *TrueV = SI->getTrueValue();
  742. Value *FalseV = SI->getFalseValue();
  743. BasicBlock *PhiTransBB = PN->getParent();
  744. for (unsigned i = 0; i != NumPHIValues; ++i) {
  745. BasicBlock *ThisBB = PN->getIncomingBlock(i);
  746. Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
  747. Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
  748. Value *InV = nullptr;
  749. // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
  750. // even if currently isNullValue gives false.
  751. Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
  752. if (InC && !isa<ConstantExpr>(InC))
  753. InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
  754. else
  755. InV = Builder->CreateSelect(PN->getIncomingValue(i),
  756. TrueVInPred, FalseVInPred, "phitmp");
  757. NewPN->addIncoming(InV, ThisBB);
  758. }
  759. } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
  760. Constant *C = cast<Constant>(I.getOperand(1));
  761. for (unsigned i = 0; i != NumPHIValues; ++i) {
  762. Value *InV = nullptr;
  763. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  764. InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
  765. else if (isa<ICmpInst>(CI))
  766. InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
  767. C, "phitmp");
  768. else
  769. InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
  770. C, "phitmp");
  771. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  772. }
  773. } else if (I.getNumOperands() == 2) {
  774. Constant *C = cast<Constant>(I.getOperand(1));
  775. for (unsigned i = 0; i != NumPHIValues; ++i) {
  776. Value *InV = nullptr;
  777. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  778. InV = ConstantExpr::get(I.getOpcode(), InC, C);
  779. else
  780. InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
  781. PN->getIncomingValue(i), C, "phitmp");
  782. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  783. }
  784. } else {
  785. CastInst *CI = cast<CastInst>(&I);
  786. Type *RetTy = CI->getType();
  787. for (unsigned i = 0; i != NumPHIValues; ++i) {
  788. Value *InV;
  789. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  790. InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
  791. else
  792. InV = Builder->CreateCast(CI->getOpcode(),
  793. PN->getIncomingValue(i), I.getType(), "phitmp");
  794. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  795. }
  796. }
  797. for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
  798. Instruction *User = cast<Instruction>(*UI++);
  799. if (User == &I) continue;
  800. ReplaceInstUsesWith(*User, NewPN);
  801. EraseInstFromFunction(*User);
  802. }
  803. return ReplaceInstUsesWith(I, NewPN);
  804. }
  805. /// FindElementAtOffset - Given a pointer type and a constant offset, determine
  806. /// whether or not there is a sequence of GEP indices into the pointed type that
  807. /// will land us at the specified offset. If so, fill them into NewIndices and
  808. /// return the resultant element type, otherwise return null.
  809. Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
  810. SmallVectorImpl<Value *> &NewIndices) {
  811. Type *Ty = PtrTy->getElementType();
  812. if (!Ty->isSized())
  813. return nullptr;
  814. // Start with the index over the outer type. Note that the type size
  815. // might be zero (even if the offset isn't zero) if the indexed type
  816. // is something like [0 x {int, int}]
  817. Type *IntPtrTy = DL.getIntPtrType(PtrTy);
  818. int64_t FirstIdx = 0;
  819. if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
  820. FirstIdx = Offset/TySize;
  821. Offset -= FirstIdx*TySize;
  822. // Handle hosts where % returns negative instead of values [0..TySize).
  823. if (Offset < 0) {
  824. --FirstIdx;
  825. Offset += TySize;
  826. assert(Offset >= 0);
  827. }
  828. assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
  829. }
  830. NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
  831. // Index into the types. If we fail, set OrigBase to null.
  832. while (Offset) {
  833. // Indexing into tail padding between struct/array elements.
  834. if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
  835. return nullptr;
  836. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  837. const StructLayout *SL = DL.getStructLayout(STy);
  838. assert(Offset < (int64_t)SL->getSizeInBytes() &&
  839. "Offset must stay within the indexed type");
  840. unsigned Elt = SL->getElementContainingOffset(Offset);
  841. NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
  842. Elt));
  843. Offset -= SL->getElementOffset(Elt);
  844. Ty = STy->getElementType(Elt);
  845. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  846. uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
  847. assert(EltSize && "Cannot index into a zero-sized array");
  848. NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
  849. Offset %= EltSize;
  850. Ty = AT->getElementType();
  851. } else {
  852. // Otherwise, we can't index into the middle of this atomic type, bail.
  853. return nullptr;
  854. }
  855. }
  856. return Ty;
  857. }
  858. static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
  859. // If this GEP has only 0 indices, it is the same pointer as
  860. // Src. If Src is not a trivial GEP too, don't combine
  861. // the indices.
  862. if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
  863. !Src.hasOneUse())
  864. return false;
  865. return true;
  866. }
  867. /// Descale - Return a value X such that Val = X * Scale, or null if none. If
  868. /// the multiplication is known not to overflow then NoSignedWrap is set.
  869. Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
  870. assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
  871. assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
  872. Scale.getBitWidth() && "Scale not compatible with value!");
  873. // If Val is zero or Scale is one then Val = Val * Scale.
  874. if (match(Val, m_Zero()) || Scale == 1) {
  875. NoSignedWrap = true;
  876. return Val;
  877. }
  878. // If Scale is zero then it does not divide Val.
  879. if (Scale.isMinValue())
  880. return nullptr;
  881. // Look through chains of multiplications, searching for a constant that is
  882. // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
  883. // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
  884. // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
  885. // down from Val:
  886. //
  887. // Val = M1 * X || Analysis starts here and works down
  888. // M1 = M2 * Y || Doesn't descend into terms with more
  889. // M2 = Z * 4 \/ than one use
  890. //
  891. // Then to modify a term at the bottom:
  892. //
  893. // Val = M1 * X
  894. // M1 = Z * Y || Replaced M2 with Z
  895. //
  896. // Then to work back up correcting nsw flags.
  897. // Op - the term we are currently analyzing. Starts at Val then drills down.
  898. // Replaced with its descaled value before exiting from the drill down loop.
  899. Value *Op = Val;
  900. // Parent - initially null, but after drilling down notes where Op came from.
  901. // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
  902. // 0'th operand of Val.
  903. std::pair<Instruction*, unsigned> Parent;
  904. // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
  905. // levels that doesn't overflow.
  906. bool RequireNoSignedWrap = false;
  907. // logScale - log base 2 of the scale. Negative if not a power of 2.
  908. int32_t logScale = Scale.exactLogBase2();
  909. for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
  910. if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  911. // If Op is a constant divisible by Scale then descale to the quotient.
  912. APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
  913. APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
  914. if (!Remainder.isMinValue())
  915. // Not divisible by Scale.
  916. return nullptr;
  917. // Replace with the quotient in the parent.
  918. Op = ConstantInt::get(CI->getType(), Quotient);
  919. NoSignedWrap = true;
  920. break;
  921. }
  922. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
  923. if (BO->getOpcode() == Instruction::Mul) {
  924. // Multiplication.
  925. NoSignedWrap = BO->hasNoSignedWrap();
  926. if (RequireNoSignedWrap && !NoSignedWrap)
  927. return nullptr;
  928. // There are three cases for multiplication: multiplication by exactly
  929. // the scale, multiplication by a constant different to the scale, and
  930. // multiplication by something else.
  931. Value *LHS = BO->getOperand(0);
  932. Value *RHS = BO->getOperand(1);
  933. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  934. // Multiplication by a constant.
  935. if (CI->getValue() == Scale) {
  936. // Multiplication by exactly the scale, replace the multiplication
  937. // by its left-hand side in the parent.
  938. Op = LHS;
  939. break;
  940. }
  941. // Otherwise drill down into the constant.
  942. if (!Op->hasOneUse())
  943. return nullptr;
  944. Parent = std::make_pair(BO, 1);
  945. continue;
  946. }
  947. // Multiplication by something else. Drill down into the left-hand side
  948. // since that's where the reassociate pass puts the good stuff.
  949. if (!Op->hasOneUse())
  950. return nullptr;
  951. Parent = std::make_pair(BO, 0);
  952. continue;
  953. }
  954. if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
  955. isa<ConstantInt>(BO->getOperand(1))) {
  956. // Multiplication by a power of 2.
  957. NoSignedWrap = BO->hasNoSignedWrap();
  958. if (RequireNoSignedWrap && !NoSignedWrap)
  959. return nullptr;
  960. Value *LHS = BO->getOperand(0);
  961. int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
  962. getLimitedValue(Scale.getBitWidth());
  963. // Op = LHS << Amt.
  964. if (Amt == logScale) {
  965. // Multiplication by exactly the scale, replace the multiplication
  966. // by its left-hand side in the parent.
  967. Op = LHS;
  968. break;
  969. }
  970. if (Amt < logScale || !Op->hasOneUse())
  971. return nullptr;
  972. // Multiplication by more than the scale. Reduce the multiplying amount
  973. // by the scale in the parent.
  974. Parent = std::make_pair(BO, 1);
  975. Op = ConstantInt::get(BO->getType(), Amt - logScale);
  976. break;
  977. }
  978. }
  979. if (!Op->hasOneUse())
  980. return nullptr;
  981. if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
  982. if (Cast->getOpcode() == Instruction::SExt) {
  983. // Op is sign-extended from a smaller type, descale in the smaller type.
  984. unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
  985. APInt SmallScale = Scale.trunc(SmallSize);
  986. // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
  987. // descale Op as (sext Y) * Scale. In order to have
  988. // sext (Y * SmallScale) = (sext Y) * Scale
  989. // some conditions need to hold however: SmallScale must sign-extend to
  990. // Scale and the multiplication Y * SmallScale should not overflow.
  991. if (SmallScale.sext(Scale.getBitWidth()) != Scale)
  992. // SmallScale does not sign-extend to Scale.
  993. return nullptr;
  994. assert(SmallScale.exactLogBase2() == logScale);
  995. // Require that Y * SmallScale must not overflow.
  996. RequireNoSignedWrap = true;
  997. // Drill down through the cast.
  998. Parent = std::make_pair(Cast, 0);
  999. Scale = SmallScale;
  1000. continue;
  1001. }
  1002. if (Cast->getOpcode() == Instruction::Trunc) {
  1003. // Op is truncated from a larger type, descale in the larger type.
  1004. // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
  1005. // trunc (Y * sext Scale) = (trunc Y) * Scale
  1006. // always holds. However (trunc Y) * Scale may overflow even if
  1007. // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
  1008. // from this point up in the expression (see later).
  1009. if (RequireNoSignedWrap)
  1010. return nullptr;
  1011. // Drill down through the cast.
  1012. unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
  1013. Parent = std::make_pair(Cast, 0);
  1014. Scale = Scale.sext(LargeSize);
  1015. if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
  1016. logScale = -1;
  1017. assert(Scale.exactLogBase2() == logScale);
  1018. continue;
  1019. }
  1020. }
  1021. // Unsupported expression, bail out.
  1022. return nullptr;
  1023. }
  1024. // If Op is zero then Val = Op * Scale.
  1025. if (match(Op, m_Zero())) {
  1026. NoSignedWrap = true;
  1027. return Op;
  1028. }
  1029. // We know that we can successfully descale, so from here on we can safely
  1030. // modify the IR. Op holds the descaled version of the deepest term in the
  1031. // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
  1032. // not to overflow.
  1033. if (!Parent.first)
  1034. // The expression only had one term.
  1035. return Op;
  1036. // Rewrite the parent using the descaled version of its operand.
  1037. assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
  1038. assert(Op != Parent.first->getOperand(Parent.second) &&
  1039. "Descaling was a no-op?");
  1040. Parent.first->setOperand(Parent.second, Op);
  1041. Worklist.Add(Parent.first);
  1042. // Now work back up the expression correcting nsw flags. The logic is based
  1043. // on the following observation: if X * Y is known not to overflow as a signed
  1044. // multiplication, and Y is replaced by a value Z with smaller absolute value,
  1045. // then X * Z will not overflow as a signed multiplication either. As we work
  1046. // our way up, having NoSignedWrap 'true' means that the descaled value at the
  1047. // current level has strictly smaller absolute value than the original.
  1048. Instruction *Ancestor = Parent.first;
  1049. do {
  1050. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
  1051. // If the multiplication wasn't nsw then we can't say anything about the
  1052. // value of the descaled multiplication, and we have to clear nsw flags
  1053. // from this point on up.
  1054. bool OpNoSignedWrap = BO->hasNoSignedWrap();
  1055. NoSignedWrap &= OpNoSignedWrap;
  1056. if (NoSignedWrap != OpNoSignedWrap) {
  1057. BO->setHasNoSignedWrap(NoSignedWrap);
  1058. Worklist.Add(Ancestor);
  1059. }
  1060. } else if (Ancestor->getOpcode() == Instruction::Trunc) {
  1061. // The fact that the descaled input to the trunc has smaller absolute
  1062. // value than the original input doesn't tell us anything useful about
  1063. // the absolute values of the truncations.
  1064. NoSignedWrap = false;
  1065. }
  1066. assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
  1067. "Failed to keep proper track of nsw flags while drilling down?");
  1068. if (Ancestor == Val)
  1069. // Got to the top, all done!
  1070. return Val;
  1071. // Move up one level in the expression.
  1072. assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
  1073. Ancestor = Ancestor->user_back();
  1074. } while (1);
  1075. }
  1076. /// \brief Creates node of binary operation with the same attributes as the
  1077. /// specified one but with other operands.
  1078. static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
  1079. InstCombiner::BuilderTy *B) {
  1080. Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
  1081. if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
  1082. if (isa<OverflowingBinaryOperator>(NewBO)) {
  1083. NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
  1084. NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
  1085. }
  1086. if (isa<PossiblyExactOperator>(NewBO))
  1087. NewBO->setIsExact(Inst.isExact());
  1088. }
  1089. return BORes;
  1090. }
  1091. /// \brief Makes transformation of binary operation specific for vector types.
  1092. /// \param Inst Binary operator to transform.
  1093. /// \return Pointer to node that must replace the original binary operator, or
  1094. /// null pointer if no transformation was made.
  1095. Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
  1096. if (!Inst.getType()->isVectorTy()) return nullptr;
  1097. // It may not be safe to reorder shuffles and things like div, urem, etc.
  1098. // because we may trap when executing those ops on unknown vector elements.
  1099. // See PR20059.
  1100. if (!isSafeToSpeculativelyExecute(&Inst))
  1101. return nullptr;
  1102. unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
  1103. Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
  1104. assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
  1105. assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
  1106. // If both arguments of binary operation are shuffles, which use the same
  1107. // mask and shuffle within a single vector, it is worthwhile to move the
  1108. // shuffle after binary operation:
  1109. // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
  1110. if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
  1111. ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
  1112. ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
  1113. if (isa<UndefValue>(LShuf->getOperand(1)) &&
  1114. isa<UndefValue>(RShuf->getOperand(1)) &&
  1115. LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
  1116. LShuf->getMask() == RShuf->getMask()) {
  1117. Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
  1118. RShuf->getOperand(0), Builder);
  1119. Value *Res = Builder->CreateShuffleVector(NewBO,
  1120. UndefValue::get(NewBO->getType()), LShuf->getMask());
  1121. return Res;
  1122. }
  1123. }
  1124. // If one argument is a shuffle within one vector, the other is a constant,
  1125. // try moving the shuffle after the binary operation.
  1126. ShuffleVectorInst *Shuffle = nullptr;
  1127. Constant *C1 = nullptr;
  1128. if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
  1129. if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
  1130. if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
  1131. if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
  1132. if (Shuffle && C1 &&
  1133. (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
  1134. isa<UndefValue>(Shuffle->getOperand(1)) &&
  1135. Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
  1136. SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
  1137. // Find constant C2 that has property:
  1138. // shuffle(C2, ShMask) = C1
  1139. // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
  1140. // reorder is not possible.
  1141. SmallVector<Constant*, 16> C2M(VWidth,
  1142. UndefValue::get(C1->getType()->getScalarType()));
  1143. bool MayChange = true;
  1144. for (unsigned I = 0; I < VWidth; ++I) {
  1145. if (ShMask[I] >= 0) {
  1146. assert(ShMask[I] < (int)VWidth);
  1147. if (!isa<UndefValue>(C2M[ShMask[I]])) {
  1148. MayChange = false;
  1149. break;
  1150. }
  1151. C2M[ShMask[I]] = C1->getAggregateElement(I);
  1152. }
  1153. }
  1154. if (MayChange) {
  1155. Constant *C2 = ConstantVector::get(C2M);
  1156. Value *NewLHS, *NewRHS;
  1157. if (isa<Constant>(LHS)) {
  1158. NewLHS = C2;
  1159. NewRHS = Shuffle->getOperand(0);
  1160. } else {
  1161. NewLHS = Shuffle->getOperand(0);
  1162. NewRHS = C2;
  1163. }
  1164. Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
  1165. Value *Res = Builder->CreateShuffleVector(NewBO,
  1166. UndefValue::get(Inst.getType()), Shuffle->getMask());
  1167. return Res;
  1168. }
  1169. }
  1170. return nullptr;
  1171. }
  1172. Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
  1173. SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
  1174. if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
  1175. return ReplaceInstUsesWith(GEP, V);
  1176. Value *PtrOp = GEP.getOperand(0);
  1177. // Eliminate unneeded casts for indices, and replace indices which displace
  1178. // by multiples of a zero size type with zero.
  1179. bool MadeChange = false;
  1180. Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
  1181. gep_type_iterator GTI = gep_type_begin(GEP);
  1182. for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
  1183. ++I, ++GTI) {
  1184. // Skip indices into struct types.
  1185. SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
  1186. if (!SeqTy)
  1187. continue;
  1188. // If the element type has zero size then any index over it is equivalent
  1189. // to an index of zero, so replace it with zero if it is not zero already.
  1190. if (SeqTy->getElementType()->isSized() &&
  1191. DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
  1192. if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
  1193. *I = Constant::getNullValue(IntPtrTy);
  1194. MadeChange = true;
  1195. }
  1196. Type *IndexTy = (*I)->getType();
  1197. if (IndexTy != IntPtrTy) {
  1198. // If we are using a wider index than needed for this platform, shrink
  1199. // it to what we need. If narrower, sign-extend it to what we need.
  1200. // This explicit cast can make subsequent optimizations more obvious.
  1201. *I = Builder->CreateIntCast(*I, IntPtrTy, true);
  1202. MadeChange = true;
  1203. }
  1204. }
  1205. if (MadeChange)
  1206. return &GEP;
  1207. // Check to see if the inputs to the PHI node are getelementptr instructions.
  1208. if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
  1209. GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
  1210. if (!Op1)
  1211. return nullptr;
  1212. // Don't fold a GEP into itself through a PHI node. This can only happen
  1213. // through the back-edge of a loop. Folding a GEP into itself means that
  1214. // the value of the previous iteration needs to be stored in the meantime,
  1215. // thus requiring an additional register variable to be live, but not
  1216. // actually achieving anything (the GEP still needs to be executed once per
  1217. // loop iteration).
  1218. if (Op1 == &GEP)
  1219. return nullptr;
  1220. signed DI = -1;
  1221. for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
  1222. GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
  1223. if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
  1224. return nullptr;
  1225. // As for Op1 above, don't try to fold a GEP into itself.
  1226. if (Op2 == &GEP)
  1227. return nullptr;
  1228. // Keep track of the type as we walk the GEP.
  1229. Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
  1230. for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
  1231. if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
  1232. return nullptr;
  1233. if (Op1->getOperand(J) != Op2->getOperand(J)) {
  1234. if (DI == -1) {
  1235. // We have not seen any differences yet in the GEPs feeding the
  1236. // PHI yet, so we record this one if it is allowed to be a
  1237. // variable.
  1238. // The first two arguments can vary for any GEP, the rest have to be
  1239. // static for struct slots
  1240. if (J > 1 && CurTy->isStructTy())
  1241. return nullptr;
  1242. DI = J;
  1243. } else {
  1244. // The GEP is different by more than one input. While this could be
  1245. // extended to support GEPs that vary by more than one variable it
  1246. // doesn't make sense since it greatly increases the complexity and
  1247. // would result in an R+R+R addressing mode which no backend
  1248. // directly supports and would need to be broken into several
  1249. // simpler instructions anyway.
  1250. return nullptr;
  1251. }
  1252. }
  1253. // Sink down a layer of the type for the next iteration.
  1254. if (J > 0) {
  1255. if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
  1256. CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
  1257. } else {
  1258. CurTy = nullptr;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
  1264. if (DI == -1) {
  1265. // All the GEPs feeding the PHI are identical. Clone one down into our
  1266. // BB so that it can be merged with the current GEP.
  1267. GEP.getParent()->getInstList().insert(
  1268. GEP.getParent()->getFirstInsertionPt(), NewGEP);
  1269. } else {
  1270. // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
  1271. // into the current block so it can be merged, and create a new PHI to
  1272. // set that index.
  1273. Instruction *InsertPt = Builder->GetInsertPoint();
  1274. Builder->SetInsertPoint(PN);
  1275. PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
  1276. PN->getNumOperands());
  1277. Builder->SetInsertPoint(InsertPt);
  1278. for (auto &I : PN->operands())
  1279. NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
  1280. PN->getIncomingBlock(I));
  1281. NewGEP->setOperand(DI, NewPN);
  1282. GEP.getParent()->getInstList().insert(
  1283. GEP.getParent()->getFirstInsertionPt(), NewGEP);
  1284. NewGEP->setOperand(DI, NewPN);
  1285. }
  1286. GEP.setOperand(0, NewGEP);
  1287. PtrOp = NewGEP;
  1288. }
  1289. // Combine Indices - If the source pointer to this getelementptr instruction
  1290. // is a getelementptr instruction, combine the indices of the two
  1291. // getelementptr instructions into a single instruction.
  1292. //
  1293. if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
  1294. if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
  1295. return nullptr;
  1296. // Note that if our source is a gep chain itself then we wait for that
  1297. // chain to be resolved before we perform this transformation. This
  1298. // avoids us creating a TON of code in some cases.
  1299. if (GEPOperator *SrcGEP =
  1300. dyn_cast<GEPOperator>(Src->getOperand(0)))
  1301. if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
  1302. return nullptr; // Wait until our source is folded to completion.
  1303. SmallVector<Value*, 8> Indices;
  1304. // Find out whether the last index in the source GEP is a sequential idx.
  1305. bool EndsWithSequential = false;
  1306. for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
  1307. I != E; ++I)
  1308. EndsWithSequential = !(*I)->isStructTy();
  1309. // Can we combine the two pointer arithmetics offsets?
  1310. if (EndsWithSequential) {
  1311. // Replace: gep (gep %P, long B), long A, ...
  1312. // With: T = long A+B; gep %P, T, ...
  1313. //
  1314. Value *Sum;
  1315. Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
  1316. Value *GO1 = GEP.getOperand(1);
  1317. if (SO1 == Constant::getNullValue(SO1->getType())) {
  1318. Sum = GO1;
  1319. } else if (GO1 == Constant::getNullValue(GO1->getType())) {
  1320. Sum = SO1;
  1321. } else {
  1322. // If they aren't the same type, then the input hasn't been processed
  1323. // by the loop above yet (which canonicalizes sequential index types to
  1324. // intptr_t). Just avoid transforming this until the input has been
  1325. // normalized.
  1326. if (SO1->getType() != GO1->getType())
  1327. return nullptr;
  1328. // Only do the combine when GO1 and SO1 are both constants. Only in
  1329. // this case, we are sure the cost after the merge is never more than
  1330. // that before the merge.
  1331. if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
  1332. return nullptr;
  1333. Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
  1334. }
  1335. // Update the GEP in place if possible.
  1336. if (Src->getNumOperands() == 2) {
  1337. GEP.setOperand(0, Src->getOperand(0));
  1338. GEP.setOperand(1, Sum);
  1339. return &GEP;
  1340. }
  1341. Indices.append(Src->op_begin()+1, Src->op_end()-1);
  1342. Indices.push_back(Sum);
  1343. Indices.append(GEP.op_begin()+2, GEP.op_end());
  1344. } else if (isa<Constant>(*GEP.idx_begin()) &&
  1345. cast<Constant>(*GEP.idx_begin())->isNullValue() &&
  1346. Src->getNumOperands() != 1) {
  1347. // Otherwise we can do the fold if the first index of the GEP is a zero
  1348. Indices.append(Src->op_begin()+1, Src->op_end());
  1349. Indices.append(GEP.idx_begin()+1, GEP.idx_end());
  1350. }
  1351. if (!Indices.empty())
  1352. return GEP.isInBounds() && Src->isInBounds()
  1353. ? GetElementPtrInst::CreateInBounds(
  1354. Src->getSourceElementType(), Src->getOperand(0), Indices,
  1355. GEP.getName())
  1356. : GetElementPtrInst::Create(Src->getSourceElementType(),
  1357. Src->getOperand(0), Indices,
  1358. GEP.getName());
  1359. }
  1360. if (GEP.getNumIndices() == 1) {
  1361. unsigned AS = GEP.getPointerAddressSpace();
  1362. if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
  1363. DL.getPointerSizeInBits(AS)) {
  1364. Type *PtrTy = GEP.getPointerOperandType();
  1365. Type *Ty = PtrTy->getPointerElementType();
  1366. uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
  1367. bool Matched = false;
  1368. uint64_t C;
  1369. Value *V = nullptr;
  1370. if (TyAllocSize == 1) {
  1371. V = GEP.getOperand(1);
  1372. Matched = true;
  1373. } else if (match(GEP.getOperand(1),
  1374. m_AShr(m_Value(V), m_ConstantInt(C)))) {
  1375. if (TyAllocSize == 1ULL << C)
  1376. Matched = true;
  1377. } else if (match(GEP.getOperand(1),
  1378. m_SDiv(m_Value(V), m_ConstantInt(C)))) {
  1379. if (TyAllocSize == C)
  1380. Matched = true;
  1381. }
  1382. if (Matched) {
  1383. // Canonicalize (gep i8* X, -(ptrtoint Y))
  1384. // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
  1385. // The GEP pattern is emitted by the SCEV expander for certain kinds of
  1386. // pointer arithmetic.
  1387. if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
  1388. Operator *Index = cast<Operator>(V);
  1389. Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
  1390. Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
  1391. return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
  1392. }
  1393. // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
  1394. // to (bitcast Y)
  1395. Value *Y;
  1396. if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
  1397. m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
  1398. return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
  1399. GEP.getType());
  1400. }
  1401. }
  1402. }
  1403. }
  1404. // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
  1405. Value *StrippedPtr = PtrOp->stripPointerCasts();
  1406. PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
  1407. // We do not handle pointer-vector geps here.
  1408. if (!StrippedPtrTy)
  1409. return nullptr;
  1410. if (StrippedPtr != PtrOp) {
  1411. bool HasZeroPointerIndex = false;
  1412. if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
  1413. HasZeroPointerIndex = C->isZero();
  1414. // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
  1415. // into : GEP [10 x i8]* X, i32 0, ...
  1416. //
  1417. // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
  1418. // into : GEP i8* X, ...
  1419. //
  1420. // This occurs when the program declares an array extern like "int X[];"
  1421. if (HasZeroPointerIndex) {
  1422. PointerType *CPTy = cast<PointerType>(PtrOp->getType());
  1423. if (ArrayType *CATy =
  1424. dyn_cast<ArrayType>(CPTy->getElementType())) {
  1425. // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
  1426. if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
  1427. // -> GEP i8* X, ...
  1428. SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
  1429. GetElementPtrInst *Res = GetElementPtrInst::Create(
  1430. StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
  1431. Res->setIsInBounds(GEP.isInBounds());
  1432. if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
  1433. return Res;
  1434. // Insert Res, and create an addrspacecast.
  1435. // e.g.,
  1436. // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
  1437. // ->
  1438. // %0 = GEP i8 addrspace(1)* X, ...
  1439. // addrspacecast i8 addrspace(1)* %0 to i8*
  1440. return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
  1441. }
  1442. if (ArrayType *XATy =
  1443. dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
  1444. // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
  1445. if (CATy->getElementType() == XATy->getElementType()) {
  1446. // -> GEP [10 x i8]* X, i32 0, ...
  1447. // At this point, we know that the cast source type is a pointer
  1448. // to an array of the same type as the destination pointer
  1449. // array. Because the array type is never stepped over (there
  1450. // is a leading zero) we can fold the cast into this GEP.
  1451. if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
  1452. GEP.setOperand(0, StrippedPtr);
  1453. GEP.setSourceElementType(XATy);
  1454. return &GEP;
  1455. }
  1456. // Cannot replace the base pointer directly because StrippedPtr's
  1457. // address space is different. Instead, create a new GEP followed by
  1458. // an addrspacecast.
  1459. // e.g.,
  1460. // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
  1461. // i32 0, ...
  1462. // ->
  1463. // %0 = GEP [10 x i8] addrspace(1)* X, ...
  1464. // addrspacecast i8 addrspace(1)* %0 to i8*
  1465. SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
  1466. Value *NewGEP = GEP.isInBounds()
  1467. ? Builder->CreateInBoundsGEP(
  1468. nullptr, StrippedPtr, Idx, GEP.getName())
  1469. : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
  1470. GEP.getName());
  1471. return new AddrSpaceCastInst(NewGEP, GEP.getType());
  1472. }
  1473. }
  1474. }
  1475. } else if (GEP.getNumOperands() == 2) {
  1476. // Transform things like:
  1477. // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
  1478. // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
  1479. Type *SrcElTy = StrippedPtrTy->getElementType();
  1480. Type *ResElTy = PtrOp->getType()->getPointerElementType();
  1481. if (SrcElTy->isArrayTy() &&
  1482. DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
  1483. DL.getTypeAllocSize(ResElTy)) {
  1484. Type *IdxType = DL.getIntPtrType(GEP.getType());
  1485. Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
  1486. Value *NewGEP =
  1487. GEP.isInBounds()
  1488. ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
  1489. GEP.getName())
  1490. : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
  1491. // V and GEP are both pointer types --> BitCast
  1492. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1493. GEP.getType());
  1494. }
  1495. // Transform things like:
  1496. // %V = mul i64 %N, 4
  1497. // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
  1498. // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
  1499. if (ResElTy->isSized() && SrcElTy->isSized()) {
  1500. // Check that changing the type amounts to dividing the index by a scale
  1501. // factor.
  1502. uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
  1503. uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
  1504. if (ResSize && SrcSize % ResSize == 0) {
  1505. Value *Idx = GEP.getOperand(1);
  1506. unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
  1507. uint64_t Scale = SrcSize / ResSize;
  1508. // Earlier transforms ensure that the index has type IntPtrType, which
  1509. // considerably simplifies the logic by eliminating implicit casts.
  1510. assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
  1511. "Index not cast to pointer width?");
  1512. bool NSW;
  1513. if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
  1514. // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
  1515. // If the multiplication NewIdx * Scale may overflow then the new
  1516. // GEP may not be "inbounds".
  1517. Value *NewGEP =
  1518. GEP.isInBounds() && NSW
  1519. ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
  1520. GEP.getName())
  1521. : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
  1522. GEP.getName());
  1523. // The NewGEP must be pointer typed, so must the old one -> BitCast
  1524. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1525. GEP.getType());
  1526. }
  1527. }
  1528. }
  1529. // Similarly, transform things like:
  1530. // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
  1531. // (where tmp = 8*tmp2) into:
  1532. // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
  1533. if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
  1534. // Check that changing to the array element type amounts to dividing the
  1535. // index by a scale factor.
  1536. uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
  1537. uint64_t ArrayEltSize =
  1538. DL.getTypeAllocSize(SrcElTy->getArrayElementType());
  1539. if (ResSize && ArrayEltSize % ResSize == 0) {
  1540. Value *Idx = GEP.getOperand(1);
  1541. unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
  1542. uint64_t Scale = ArrayEltSize / ResSize;
  1543. // Earlier transforms ensure that the index has type IntPtrType, which
  1544. // considerably simplifies the logic by eliminating implicit casts.
  1545. assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
  1546. "Index not cast to pointer width?");
  1547. bool NSW;
  1548. if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
  1549. // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
  1550. // If the multiplication NewIdx * Scale may overflow then the new
  1551. // GEP may not be "inbounds".
  1552. Value *Off[2] = {
  1553. Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
  1554. NewIdx};
  1555. Value *NewGEP = GEP.isInBounds() && NSW
  1556. ? Builder->CreateInBoundsGEP(
  1557. SrcElTy, StrippedPtr, Off, GEP.getName())
  1558. : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
  1559. GEP.getName());
  1560. // The NewGEP must be pointer typed, so must the old one -> BitCast
  1561. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1562. GEP.getType());
  1563. }
  1564. }
  1565. }
  1566. }
  1567. }
  1568. // addrspacecast between types is canonicalized as a bitcast, then an
  1569. // addrspacecast. To take advantage of the below bitcast + struct GEP, look
  1570. // through the addrspacecast.
  1571. if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
  1572. // X = bitcast A addrspace(1)* to B addrspace(1)*
  1573. // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
  1574. // Z = gep Y, <...constant indices...>
  1575. // Into an addrspacecasted GEP of the struct.
  1576. if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
  1577. PtrOp = BC;
  1578. }
  1579. /// See if we can simplify:
  1580. /// X = bitcast A* to B*
  1581. /// Y = gep X, <...constant indices...>
  1582. /// into a gep of the original struct. This is important for SROA and alias
  1583. /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
  1584. if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
  1585. Value *Operand = BCI->getOperand(0);
  1586. PointerType *OpType = cast<PointerType>(Operand->getType());
  1587. unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
  1588. APInt Offset(OffsetBits, 0);
  1589. if (!isa<BitCastInst>(Operand) &&
  1590. GEP.accumulateConstantOffset(DL, Offset)) {
  1591. // If this GEP instruction doesn't move the pointer, just replace the GEP
  1592. // with a bitcast of the real input to the dest type.
  1593. if (!Offset) {
  1594. // If the bitcast is of an allocation, and the allocation will be
  1595. // converted to match the type of the cast, don't touch this.
  1596. if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
  1597. // See if the bitcast simplifies, if so, don't nuke this GEP yet.
  1598. if (Instruction *I = visitBitCast(*BCI)) {
  1599. if (I != BCI) {
  1600. I->takeName(BCI);
  1601. BCI->getParent()->getInstList().insert(BCI, I);
  1602. ReplaceInstUsesWith(*BCI, I);
  1603. }
  1604. return &GEP;
  1605. }
  1606. }
  1607. if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
  1608. return new AddrSpaceCastInst(Operand, GEP.getType());
  1609. return new BitCastInst(Operand, GEP.getType());
  1610. }
  1611. // Otherwise, if the offset is non-zero, we need to find out if there is a
  1612. // field at Offset in 'A's type. If so, we can pull the cast through the
  1613. // GEP.
  1614. SmallVector<Value*, 8> NewIndices;
  1615. if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
  1616. Value *NGEP =
  1617. GEP.isInBounds()
  1618. ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
  1619. : Builder->CreateGEP(nullptr, Operand, NewIndices);
  1620. if (NGEP->getType() == GEP.getType())
  1621. return ReplaceInstUsesWith(GEP, NGEP);
  1622. NGEP->takeName(&GEP);
  1623. if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
  1624. return new AddrSpaceCastInst(NGEP, GEP.getType());
  1625. return new BitCastInst(NGEP, GEP.getType());
  1626. }
  1627. }
  1628. }
  1629. return nullptr;
  1630. }
  1631. static bool
  1632. isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
  1633. const TargetLibraryInfo *TLI) {
  1634. SmallVector<Instruction*, 4> Worklist;
  1635. Worklist.push_back(AI);
  1636. do {
  1637. Instruction *PI = Worklist.pop_back_val();
  1638. for (User *U : PI->users()) {
  1639. Instruction *I = cast<Instruction>(U);
  1640. switch (I->getOpcode()) {
  1641. default:
  1642. // Give up the moment we see something we can't handle.
  1643. return false;
  1644. case Instruction::BitCast:
  1645. case Instruction::GetElementPtr:
  1646. Users.emplace_back(I);
  1647. Worklist.push_back(I);
  1648. continue;
  1649. case Instruction::ICmp: {
  1650. ICmpInst *ICI = cast<ICmpInst>(I);
  1651. // We can fold eq/ne comparisons with null to false/true, respectively.
  1652. if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
  1653. return false;
  1654. Users.emplace_back(I);
  1655. continue;
  1656. }
  1657. case Instruction::Call:
  1658. // Ignore no-op and store intrinsics.
  1659. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1660. switch (II->getIntrinsicID()) {
  1661. default:
  1662. return false;
  1663. case Intrinsic::memmove:
  1664. case Intrinsic::memcpy:
  1665. case Intrinsic::memset: {
  1666. MemIntrinsic *MI = cast<MemIntrinsic>(II);
  1667. if (MI->isVolatile() || MI->getRawDest() != PI)
  1668. return false;
  1669. }
  1670. // fall through
  1671. case Intrinsic::dbg_declare:
  1672. case Intrinsic::dbg_value:
  1673. case Intrinsic::invariant_start:
  1674. case Intrinsic::invariant_end:
  1675. case Intrinsic::lifetime_start:
  1676. case Intrinsic::lifetime_end:
  1677. case Intrinsic::objectsize:
  1678. Users.emplace_back(I);
  1679. continue;
  1680. }
  1681. }
  1682. if (isFreeCall(I, TLI)) {
  1683. Users.emplace_back(I);
  1684. continue;
  1685. }
  1686. return false;
  1687. case Instruction::Store: {
  1688. StoreInst *SI = cast<StoreInst>(I);
  1689. if (SI->isVolatile() || SI->getPointerOperand() != PI)
  1690. return false;
  1691. Users.emplace_back(I);
  1692. continue;
  1693. }
  1694. }
  1695. llvm_unreachable("missing a return?");
  1696. }
  1697. } while (!Worklist.empty());
  1698. return true;
  1699. }
  1700. Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
  1701. // If we have a malloc call which is only used in any amount of comparisons
  1702. // to null and free calls, delete the calls and replace the comparisons with
  1703. // true or false as appropriate.
  1704. SmallVector<WeakVH, 64> Users;
  1705. if (isAllocSiteRemovable(&MI, Users, TLI)) {
  1706. for (unsigned i = 0, e = Users.size(); i != e; ++i) {
  1707. Instruction *I = cast_or_null<Instruction>(&*Users[i]);
  1708. if (!I) continue;
  1709. if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
  1710. ReplaceInstUsesWith(*C,
  1711. ConstantInt::get(Type::getInt1Ty(C->getContext()),
  1712. C->isFalseWhenEqual()));
  1713. } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
  1714. ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
  1715. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1716. if (II->getIntrinsicID() == Intrinsic::objectsize) {
  1717. ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
  1718. uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
  1719. ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
  1720. }
  1721. }
  1722. EraseInstFromFunction(*I);
  1723. }
  1724. if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
  1725. // Replace invoke with a NOP intrinsic to maintain the original CFG
  1726. Module *M = II->getParent()->getParent()->getParent();
  1727. Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
  1728. InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
  1729. None, "", II->getParent());
  1730. }
  1731. return EraseInstFromFunction(MI);
  1732. }
  1733. return nullptr;
  1734. }
  1735. /// \brief Move the call to free before a NULL test.
  1736. ///
  1737. /// Check if this free is accessed after its argument has been test
  1738. /// against NULL (property 0).
  1739. /// If yes, it is legal to move this call in its predecessor block.
  1740. ///
  1741. /// The move is performed only if the block containing the call to free
  1742. /// will be removed, i.e.:
  1743. /// 1. it has only one predecessor P, and P has two successors
  1744. /// 2. it contains the call and an unconditional branch
  1745. /// 3. its successor is the same as its predecessor's successor
  1746. ///
  1747. /// The profitability is out-of concern here and this function should
  1748. /// be called only if the caller knows this transformation would be
  1749. /// profitable (e.g., for code size).
  1750. static Instruction *
  1751. tryToMoveFreeBeforeNullTest(CallInst &FI) {
  1752. Value *Op = FI.getArgOperand(0);
  1753. BasicBlock *FreeInstrBB = FI.getParent();
  1754. BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
  1755. // Validate part of constraint #1: Only one predecessor
  1756. // FIXME: We can extend the number of predecessor, but in that case, we
  1757. // would duplicate the call to free in each predecessor and it may
  1758. // not be profitable even for code size.
  1759. if (!PredBB)
  1760. return nullptr;
  1761. // Validate constraint #2: Does this block contains only the call to
  1762. // free and an unconditional branch?
  1763. // FIXME: We could check if we can speculate everything in the
  1764. // predecessor block
  1765. if (FreeInstrBB->size() != 2)
  1766. return nullptr;
  1767. BasicBlock *SuccBB;
  1768. if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
  1769. return nullptr;
  1770. // Validate the rest of constraint #1 by matching on the pred branch.
  1771. TerminatorInst *TI = PredBB->getTerminator();
  1772. BasicBlock *TrueBB, *FalseBB;
  1773. ICmpInst::Predicate Pred;
  1774. if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
  1775. return nullptr;
  1776. if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
  1777. return nullptr;
  1778. // Validate constraint #3: Ensure the null case just falls through.
  1779. if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
  1780. return nullptr;
  1781. assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
  1782. "Broken CFG: missing edge from predecessor to successor");
  1783. FI.moveBefore(TI);
  1784. return &FI;
  1785. }
  1786. Instruction *InstCombiner::visitFree(CallInst &FI) {
  1787. Value *Op = FI.getArgOperand(0);
  1788. // free undef -> unreachable.
  1789. if (isa<UndefValue>(Op)) {
  1790. // Insert a new store to null because we cannot modify the CFG here.
  1791. Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
  1792. UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
  1793. return EraseInstFromFunction(FI);
  1794. }
  1795. // If we have 'free null' delete the instruction. This can happen in stl code
  1796. // when lots of inlining happens.
  1797. if (isa<ConstantPointerNull>(Op))
  1798. return EraseInstFromFunction(FI);
  1799. // If we optimize for code size, try to move the call to free before the null
  1800. // test so that simplify cfg can remove the empty block and dead code
  1801. // elimination the branch. I.e., helps to turn something like:
  1802. // if (foo) free(foo);
  1803. // into
  1804. // free(foo);
  1805. if (MinimizeSize)
  1806. if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
  1807. return I;
  1808. return nullptr;
  1809. }
  1810. Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
  1811. if (RI.getNumOperands() == 0) // ret void
  1812. return nullptr;
  1813. Value *ResultOp = RI.getOperand(0);
  1814. Type *VTy = ResultOp->getType();
  1815. if (!VTy->isIntegerTy())
  1816. return nullptr;
  1817. // There might be assume intrinsics dominating this return that completely
  1818. // determine the value. If so, constant fold it.
  1819. unsigned BitWidth = VTy->getPrimitiveSizeInBits();
  1820. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  1821. computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
  1822. if ((KnownZero|KnownOne).isAllOnesValue())
  1823. RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
  1824. return nullptr;
  1825. }
  1826. Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
  1827. // Change br (not X), label True, label False to: br X, label False, True
  1828. Value *X = nullptr;
  1829. BasicBlock *TrueDest;
  1830. BasicBlock *FalseDest;
  1831. if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
  1832. !isa<Constant>(X)) {
  1833. // Swap Destinations and condition...
  1834. BI.setCondition(X);
  1835. BI.swapSuccessors();
  1836. return &BI;
  1837. }
  1838. // If the condition is irrelevant, remove the use so that other
  1839. // transforms on the condition become more effective.
  1840. if (BI.isConditional() &&
  1841. BI.getSuccessor(0) == BI.getSuccessor(1) &&
  1842. !isa<UndefValue>(BI.getCondition())) {
  1843. BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
  1844. return &BI;
  1845. }
  1846. // Canonicalize fcmp_one -> fcmp_oeq
  1847. FCmpInst::Predicate FPred; Value *Y;
  1848. if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
  1849. TrueDest, FalseDest)) &&
  1850. BI.getCondition()->hasOneUse())
  1851. if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
  1852. FPred == FCmpInst::FCMP_OGE) {
  1853. FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
  1854. Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
  1855. // Swap Destinations and condition.
  1856. BI.swapSuccessors();
  1857. Worklist.Add(Cond);
  1858. return &BI;
  1859. }
  1860. // Canonicalize icmp_ne -> icmp_eq
  1861. ICmpInst::Predicate IPred;
  1862. if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
  1863. TrueDest, FalseDest)) &&
  1864. BI.getCondition()->hasOneUse())
  1865. if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
  1866. IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
  1867. IPred == ICmpInst::ICMP_SGE) {
  1868. ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
  1869. Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
  1870. // Swap Destinations and condition.
  1871. BI.swapSuccessors();
  1872. Worklist.Add(Cond);
  1873. return &BI;
  1874. }
  1875. return nullptr;
  1876. }
  1877. Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
  1878. Value *Cond = SI.getCondition();
  1879. unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
  1880. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  1881. computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
  1882. unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
  1883. unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
  1884. // Compute the number of leading bits we can ignore.
  1885. for (auto &C : SI.cases()) {
  1886. LeadingKnownZeros = std::min(
  1887. LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
  1888. LeadingKnownOnes = std::min(
  1889. LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
  1890. }
  1891. unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
  1892. // Truncate the condition operand if the new type is equal to or larger than
  1893. // the largest legal integer type. We need to be conservative here since
  1894. // x86 generates redundant zero-extension instructions if the operand is
  1895. // truncated to i8 or i16.
  1896. bool TruncCond = false;
  1897. if (NewWidth > 0 && BitWidth > NewWidth &&
  1898. NewWidth >= DL.getLargestLegalIntTypeSize()) {
  1899. TruncCond = true;
  1900. IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
  1901. Builder->SetInsertPoint(&SI);
  1902. Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
  1903. SI.setCondition(NewCond);
  1904. for (auto &C : SI.cases())
  1905. static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
  1906. SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
  1907. }
  1908. if (Instruction *I = dyn_cast<Instruction>(Cond)) {
  1909. if (I->getOpcode() == Instruction::Add)
  1910. if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
  1911. // change 'switch (X+4) case 1:' into 'switch (X) case -3'
  1912. // Skip the first item since that's the default case.
  1913. for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
  1914. i != e; ++i) {
  1915. ConstantInt* CaseVal = i.getCaseValue();
  1916. Constant *LHS = CaseVal;
  1917. if (TruncCond)
  1918. LHS = LeadingKnownZeros
  1919. ? ConstantExpr::getZExt(CaseVal, Cond->getType())
  1920. : ConstantExpr::getSExt(CaseVal, Cond->getType());
  1921. Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
  1922. assert(isa<ConstantInt>(NewCaseVal) &&
  1923. "Result of expression should be constant");
  1924. i.setValue(cast<ConstantInt>(NewCaseVal));
  1925. }
  1926. SI.setCondition(I->getOperand(0));
  1927. Worklist.Add(I);
  1928. return &SI;
  1929. }
  1930. }
  1931. return TruncCond ? &SI : nullptr;
  1932. }
  1933. Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
  1934. Value *Agg = EV.getAggregateOperand();
  1935. if (!EV.hasIndices())
  1936. return ReplaceInstUsesWith(EV, Agg);
  1937. if (Value *V =
  1938. SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
  1939. return ReplaceInstUsesWith(EV, V);
  1940. if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
  1941. // We're extracting from an insertvalue instruction, compare the indices
  1942. const unsigned *exti, *exte, *insi, *inse;
  1943. for (exti = EV.idx_begin(), insi = IV->idx_begin(),
  1944. exte = EV.idx_end(), inse = IV->idx_end();
  1945. exti != exte && insi != inse;
  1946. ++exti, ++insi) {
  1947. if (*insi != *exti)
  1948. // The insert and extract both reference distinctly different elements.
  1949. // This means the extract is not influenced by the insert, and we can
  1950. // replace the aggregate operand of the extract with the aggregate
  1951. // operand of the insert. i.e., replace
  1952. // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
  1953. // %E = extractvalue { i32, { i32 } } %I, 0
  1954. // with
  1955. // %E = extractvalue { i32, { i32 } } %A, 0
  1956. return ExtractValueInst::Create(IV->getAggregateOperand(),
  1957. EV.getIndices());
  1958. }
  1959. if (exti == exte && insi == inse)
  1960. // Both iterators are at the end: Index lists are identical. Replace
  1961. // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
  1962. // %C = extractvalue { i32, { i32 } } %B, 1, 0
  1963. // with "i32 42"
  1964. return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
  1965. if (exti == exte) {
  1966. // The extract list is a prefix of the insert list. i.e. replace
  1967. // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
  1968. // %E = extractvalue { i32, { i32 } } %I, 1
  1969. // with
  1970. // %X = extractvalue { i32, { i32 } } %A, 1
  1971. // %E = insertvalue { i32 } %X, i32 42, 0
  1972. // by switching the order of the insert and extract (though the
  1973. // insertvalue should be left in, since it may have other uses).
  1974. Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
  1975. EV.getIndices());
  1976. return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
  1977. makeArrayRef(insi, inse));
  1978. }
  1979. if (insi == inse)
  1980. // The insert list is a prefix of the extract list
  1981. // We can simply remove the common indices from the extract and make it
  1982. // operate on the inserted value instead of the insertvalue result.
  1983. // i.e., replace
  1984. // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
  1985. // %E = extractvalue { i32, { i32 } } %I, 1, 0
  1986. // with
  1987. // %E extractvalue { i32 } { i32 42 }, 0
  1988. return ExtractValueInst::Create(IV->getInsertedValueOperand(),
  1989. makeArrayRef(exti, exte));
  1990. }
  1991. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
  1992. // We're extracting from an intrinsic, see if we're the only user, which
  1993. // allows us to simplify multiple result intrinsics to simpler things that
  1994. // just get one value.
  1995. if (II->hasOneUse()) {
  1996. // Check if we're grabbing the overflow bit or the result of a 'with
  1997. // overflow' intrinsic. If it's the latter we can remove the intrinsic
  1998. // and replace it with a traditional binary instruction.
  1999. switch (II->getIntrinsicID()) {
  2000. case Intrinsic::uadd_with_overflow:
  2001. case Intrinsic::sadd_with_overflow:
  2002. if (*EV.idx_begin() == 0) { // Normal result.
  2003. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  2004. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  2005. EraseInstFromFunction(*II);
  2006. return BinaryOperator::CreateAdd(LHS, RHS);
  2007. }
  2008. // If the normal result of the add is dead, and the RHS is a constant,
  2009. // we can transform this into a range comparison.
  2010. // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
  2011. if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
  2012. if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
  2013. return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
  2014. ConstantExpr::getNot(CI));
  2015. break;
  2016. case Intrinsic::usub_with_overflow:
  2017. case Intrinsic::ssub_with_overflow:
  2018. if (*EV.idx_begin() == 0) { // Normal result.
  2019. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  2020. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  2021. EraseInstFromFunction(*II);
  2022. return BinaryOperator::CreateSub(LHS, RHS);
  2023. }
  2024. break;
  2025. case Intrinsic::umul_with_overflow:
  2026. case Intrinsic::smul_with_overflow:
  2027. if (*EV.idx_begin() == 0) { // Normal result.
  2028. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  2029. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  2030. EraseInstFromFunction(*II);
  2031. return BinaryOperator::CreateMul(LHS, RHS);
  2032. }
  2033. break;
  2034. default:
  2035. break;
  2036. }
  2037. }
  2038. }
  2039. if (LoadInst *L = dyn_cast<LoadInst>(Agg))
  2040. // If the (non-volatile) load only has one use, we can rewrite this to a
  2041. // load from a GEP. This reduces the size of the load.
  2042. // FIXME: If a load is used only by extractvalue instructions then this
  2043. // could be done regardless of having multiple uses.
  2044. if (L->isSimple() && L->hasOneUse()) {
  2045. // extractvalue has integer indices, getelementptr has Value*s. Convert.
  2046. SmallVector<Value*, 4> Indices;
  2047. // Prefix an i32 0 since we need the first element.
  2048. Indices.push_back(Builder->getInt32(0));
  2049. for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
  2050. I != E; ++I)
  2051. Indices.push_back(Builder->getInt32(*I));
  2052. // We need to insert these at the location of the old load, not at that of
  2053. // the extractvalue.
  2054. Builder->SetInsertPoint(L->getParent(), L);
  2055. Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
  2056. L->getPointerOperand(), Indices);
  2057. // Returning the load directly will cause the main loop to insert it in
  2058. // the wrong spot, so use ReplaceInstUsesWith().
  2059. return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
  2060. }
  2061. // We could simplify extracts from other values. Note that nested extracts may
  2062. // already be simplified implicitly by the above: extract (extract (insert) )
  2063. // will be translated into extract ( insert ( extract ) ) first and then just
  2064. // the value inserted, if appropriate. Similarly for extracts from single-use
  2065. // loads: extract (extract (load)) will be translated to extract (load (gep))
  2066. // and if again single-use then via load (gep (gep)) to load (gep).
  2067. // However, double extracts from e.g. function arguments or return values
  2068. // aren't handled yet.
  2069. return nullptr;
  2070. }
  2071. /// isCatchAll - Return 'true' if the given typeinfo will match anything.
  2072. static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
  2073. switch (Personality) {
  2074. case EHPersonality::GNU_C:
  2075. // The GCC C EH personality only exists to support cleanups, so it's not
  2076. // clear what the semantics of catch clauses are.
  2077. return false;
  2078. case EHPersonality::Unknown:
  2079. return false;
  2080. case EHPersonality::GNU_Ada:
  2081. // While __gnat_all_others_value will match any Ada exception, it doesn't
  2082. // match foreign exceptions (or didn't, before gcc-4.7).
  2083. return false;
  2084. case EHPersonality::GNU_CXX:
  2085. case EHPersonality::GNU_ObjC:
  2086. case EHPersonality::MSVC_X86SEH:
  2087. case EHPersonality::MSVC_Win64SEH:
  2088. case EHPersonality::MSVC_CXX:
  2089. return TypeInfo->isNullValue();
  2090. }
  2091. llvm_unreachable("invalid enum");
  2092. }
  2093. static bool shorter_filter(const Value *LHS, const Value *RHS) {
  2094. return
  2095. cast<ArrayType>(LHS->getType())->getNumElements()
  2096. <
  2097. cast<ArrayType>(RHS->getType())->getNumElements();
  2098. }
  2099. Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
  2100. // The logic here should be correct for any real-world personality function.
  2101. // However if that turns out not to be true, the offending logic can always
  2102. // be conditioned on the personality function, like the catch-all logic is.
  2103. EHPersonality Personality =
  2104. classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
  2105. // Simplify the list of clauses, eg by removing repeated catch clauses
  2106. // (these are often created by inlining).
  2107. bool MakeNewInstruction = false; // If true, recreate using the following:
  2108. SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
  2109. bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
  2110. SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
  2111. for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
  2112. bool isLastClause = i + 1 == e;
  2113. if (LI.isCatch(i)) {
  2114. // A catch clause.
  2115. Constant *CatchClause = LI.getClause(i);
  2116. Constant *TypeInfo = CatchClause->stripPointerCasts();
  2117. // If we already saw this clause, there is no point in having a second
  2118. // copy of it.
  2119. if (AlreadyCaught.insert(TypeInfo).second) {
  2120. // This catch clause was not already seen.
  2121. NewClauses.push_back(CatchClause);
  2122. } else {
  2123. // Repeated catch clause - drop the redundant copy.
  2124. MakeNewInstruction = true;
  2125. }
  2126. // If this is a catch-all then there is no point in keeping any following
  2127. // clauses or marking the landingpad as having a cleanup.
  2128. if (isCatchAll(Personality, TypeInfo)) {
  2129. if (!isLastClause)
  2130. MakeNewInstruction = true;
  2131. CleanupFlag = false;
  2132. break;
  2133. }
  2134. } else {
  2135. // A filter clause. If any of the filter elements were already caught
  2136. // then they can be dropped from the filter. It is tempting to try to
  2137. // exploit the filter further by saying that any typeinfo that does not
  2138. // occur in the filter can't be caught later (and thus can be dropped).
  2139. // However this would be wrong, since typeinfos can match without being
  2140. // equal (for example if one represents a C++ class, and the other some
  2141. // class derived from it).
  2142. assert(LI.isFilter(i) && "Unsupported landingpad clause!");
  2143. Constant *FilterClause = LI.getClause(i);
  2144. ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
  2145. unsigned NumTypeInfos = FilterType->getNumElements();
  2146. // An empty filter catches everything, so there is no point in keeping any
  2147. // following clauses or marking the landingpad as having a cleanup. By
  2148. // dealing with this case here the following code is made a bit simpler.
  2149. if (!NumTypeInfos) {
  2150. NewClauses.push_back(FilterClause);
  2151. if (!isLastClause)
  2152. MakeNewInstruction = true;
  2153. CleanupFlag = false;
  2154. break;
  2155. }
  2156. bool MakeNewFilter = false; // If true, make a new filter.
  2157. SmallVector<Constant *, 16> NewFilterElts; // New elements.
  2158. if (isa<ConstantAggregateZero>(FilterClause)) {
  2159. // Not an empty filter - it contains at least one null typeinfo.
  2160. assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
  2161. Constant *TypeInfo =
  2162. Constant::getNullValue(FilterType->getElementType());
  2163. // If this typeinfo is a catch-all then the filter can never match.
  2164. if (isCatchAll(Personality, TypeInfo)) {
  2165. // Throw the filter away.
  2166. MakeNewInstruction = true;
  2167. continue;
  2168. }
  2169. // There is no point in having multiple copies of this typeinfo, so
  2170. // discard all but the first copy if there is more than one.
  2171. NewFilterElts.push_back(TypeInfo);
  2172. if (NumTypeInfos > 1)
  2173. MakeNewFilter = true;
  2174. } else {
  2175. ConstantArray *Filter = cast<ConstantArray>(FilterClause);
  2176. SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
  2177. NewFilterElts.reserve(NumTypeInfos);
  2178. // Remove any filter elements that were already caught or that already
  2179. // occurred in the filter. While there, see if any of the elements are
  2180. // catch-alls. If so, the filter can be discarded.
  2181. bool SawCatchAll = false;
  2182. for (unsigned j = 0; j != NumTypeInfos; ++j) {
  2183. Constant *Elt = Filter->getOperand(j);
  2184. Constant *TypeInfo = Elt->stripPointerCasts();
  2185. if (isCatchAll(Personality, TypeInfo)) {
  2186. // This element is a catch-all. Bail out, noting this fact.
  2187. SawCatchAll = true;
  2188. break;
  2189. }
  2190. if (AlreadyCaught.count(TypeInfo))
  2191. // Already caught by an earlier clause, so having it in the filter
  2192. // is pointless.
  2193. continue;
  2194. // There is no point in having multiple copies of the same typeinfo in
  2195. // a filter, so only add it if we didn't already.
  2196. if (SeenInFilter.insert(TypeInfo).second)
  2197. NewFilterElts.push_back(cast<Constant>(Elt));
  2198. }
  2199. // A filter containing a catch-all cannot match anything by definition.
  2200. if (SawCatchAll) {
  2201. // Throw the filter away.
  2202. MakeNewInstruction = true;
  2203. continue;
  2204. }
  2205. // If we dropped something from the filter, make a new one.
  2206. if (NewFilterElts.size() < NumTypeInfos)
  2207. MakeNewFilter = true;
  2208. }
  2209. if (MakeNewFilter) {
  2210. FilterType = ArrayType::get(FilterType->getElementType(),
  2211. NewFilterElts.size());
  2212. FilterClause = ConstantArray::get(FilterType, NewFilterElts);
  2213. MakeNewInstruction = true;
  2214. }
  2215. NewClauses.push_back(FilterClause);
  2216. // If the new filter is empty then it will catch everything so there is
  2217. // no point in keeping any following clauses or marking the landingpad
  2218. // as having a cleanup. The case of the original filter being empty was
  2219. // already handled above.
  2220. if (MakeNewFilter && !NewFilterElts.size()) {
  2221. assert(MakeNewInstruction && "New filter but not a new instruction!");
  2222. CleanupFlag = false;
  2223. break;
  2224. }
  2225. }
  2226. }
  2227. // If several filters occur in a row then reorder them so that the shortest
  2228. // filters come first (those with the smallest number of elements). This is
  2229. // advantageous because shorter filters are more likely to match, speeding up
  2230. // unwinding, but mostly because it increases the effectiveness of the other
  2231. // filter optimizations below.
  2232. for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
  2233. unsigned j;
  2234. // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
  2235. for (j = i; j != e; ++j)
  2236. if (!isa<ArrayType>(NewClauses[j]->getType()))
  2237. break;
  2238. // Check whether the filters are already sorted by length. We need to know
  2239. // if sorting them is actually going to do anything so that we only make a
  2240. // new landingpad instruction if it does.
  2241. for (unsigned k = i; k + 1 < j; ++k)
  2242. if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
  2243. // Not sorted, so sort the filters now. Doing an unstable sort would be
  2244. // correct too but reordering filters pointlessly might confuse users.
  2245. std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
  2246. shorter_filter);
  2247. MakeNewInstruction = true;
  2248. break;
  2249. }
  2250. // Look for the next batch of filters.
  2251. i = j + 1;
  2252. }
  2253. // If typeinfos matched if and only if equal, then the elements of a filter L
  2254. // that occurs later than a filter F could be replaced by the intersection of
  2255. // the elements of F and L. In reality two typeinfos can match without being
  2256. // equal (for example if one represents a C++ class, and the other some class
  2257. // derived from it) so it would be wrong to perform this transform in general.
  2258. // However the transform is correct and useful if F is a subset of L. In that
  2259. // case L can be replaced by F, and thus removed altogether since repeating a
  2260. // filter is pointless. So here we look at all pairs of filters F and L where
  2261. // L follows F in the list of clauses, and remove L if every element of F is
  2262. // an element of L. This can occur when inlining C++ functions with exception
  2263. // specifications.
  2264. for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
  2265. // Examine each filter in turn.
  2266. Value *Filter = NewClauses[i];
  2267. ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
  2268. if (!FTy)
  2269. // Not a filter - skip it.
  2270. continue;
  2271. unsigned FElts = FTy->getNumElements();
  2272. // Examine each filter following this one. Doing this backwards means that
  2273. // we don't have to worry about filters disappearing under us when removed.
  2274. for (unsigned j = NewClauses.size() - 1; j != i; --j) {
  2275. Value *LFilter = NewClauses[j];
  2276. ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
  2277. if (!LTy)
  2278. // Not a filter - skip it.
  2279. continue;
  2280. // If Filter is a subset of LFilter, i.e. every element of Filter is also
  2281. // an element of LFilter, then discard LFilter.
  2282. SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
  2283. // If Filter is empty then it is a subset of LFilter.
  2284. if (!FElts) {
  2285. // Discard LFilter.
  2286. NewClauses.erase(J);
  2287. MakeNewInstruction = true;
  2288. // Move on to the next filter.
  2289. continue;
  2290. }
  2291. unsigned LElts = LTy->getNumElements();
  2292. // If Filter is longer than LFilter then it cannot be a subset of it.
  2293. if (FElts > LElts)
  2294. // Move on to the next filter.
  2295. continue;
  2296. // At this point we know that LFilter has at least one element.
  2297. if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
  2298. // Filter is a subset of LFilter iff Filter contains only zeros (as we
  2299. // already know that Filter is not longer than LFilter).
  2300. if (isa<ConstantAggregateZero>(Filter)) {
  2301. assert(FElts <= LElts && "Should have handled this case earlier!");
  2302. // Discard LFilter.
  2303. NewClauses.erase(J);
  2304. MakeNewInstruction = true;
  2305. }
  2306. // Move on to the next filter.
  2307. continue;
  2308. }
  2309. ConstantArray *LArray = cast<ConstantArray>(LFilter);
  2310. if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
  2311. // Since Filter is non-empty and contains only zeros, it is a subset of
  2312. // LFilter iff LFilter contains a zero.
  2313. assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
  2314. for (unsigned l = 0; l != LElts; ++l)
  2315. if (LArray->getOperand(l)->isNullValue()) {
  2316. // LFilter contains a zero - discard it.
  2317. NewClauses.erase(J);
  2318. MakeNewInstruction = true;
  2319. break;
  2320. }
  2321. // Move on to the next filter.
  2322. continue;
  2323. }
  2324. // At this point we know that both filters are ConstantArrays. Loop over
  2325. // operands to see whether every element of Filter is also an element of
  2326. // LFilter. Since filters tend to be short this is probably faster than
  2327. // using a method that scales nicely.
  2328. ConstantArray *FArray = cast<ConstantArray>(Filter);
  2329. bool AllFound = true;
  2330. for (unsigned f = 0; f != FElts; ++f) {
  2331. Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
  2332. AllFound = false;
  2333. for (unsigned l = 0; l != LElts; ++l) {
  2334. Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
  2335. if (LTypeInfo == FTypeInfo) {
  2336. AllFound = true;
  2337. break;
  2338. }
  2339. }
  2340. if (!AllFound)
  2341. break;
  2342. }
  2343. if (AllFound) {
  2344. // Discard LFilter.
  2345. NewClauses.erase(J);
  2346. MakeNewInstruction = true;
  2347. }
  2348. // Move on to the next filter.
  2349. }
  2350. }
  2351. // If we changed any of the clauses, replace the old landingpad instruction
  2352. // with a new one.
  2353. if (MakeNewInstruction) {
  2354. LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
  2355. NewClauses.size());
  2356. for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
  2357. NLI->addClause(NewClauses[i]);
  2358. // A landing pad with no clauses must have the cleanup flag set. It is
  2359. // theoretically possible, though highly unlikely, that we eliminated all
  2360. // clauses. If so, force the cleanup flag to true.
  2361. if (NewClauses.empty())
  2362. CleanupFlag = true;
  2363. NLI->setCleanup(CleanupFlag);
  2364. return NLI;
  2365. }
  2366. // Even if none of the clauses changed, we may nonetheless have understood
  2367. // that the cleanup flag is pointless. Clear it if so.
  2368. if (LI.isCleanup() != CleanupFlag) {
  2369. assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
  2370. LI.setCleanup(CleanupFlag);
  2371. return &LI;
  2372. }
  2373. return nullptr;
  2374. }
  2375. /// TryToSinkInstruction - Try to move the specified instruction from its
  2376. /// current block into the beginning of DestBlock, which can only happen if it's
  2377. /// safe to move the instruction past all of the instructions between it and the
  2378. /// end of its block.
  2379. static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
  2380. assert(I->hasOneUse() && "Invariants didn't hold!");
  2381. // Cannot move control-flow-involving, volatile loads, vaarg, etc.
  2382. if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
  2383. isa<TerminatorInst>(I))
  2384. return false;
  2385. // Do not sink alloca instructions out of the entry block.
  2386. if (isa<AllocaInst>(I) && I->getParent() ==
  2387. &DestBlock->getParent()->getEntryBlock())
  2388. return false;
  2389. // We can only sink load instructions if there is nothing between the load and
  2390. // the end of block that could change the value.
  2391. if (I->mayReadFromMemory()) {
  2392. for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
  2393. Scan != E; ++Scan)
  2394. if (Scan->mayWriteToMemory())
  2395. return false;
  2396. }
  2397. BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
  2398. I->moveBefore(InsertPos);
  2399. ++NumSunkInst;
  2400. return true;
  2401. }
  2402. bool InstCombiner::run() {
  2403. while (!Worklist.isEmpty()) {
  2404. Instruction *I = Worklist.RemoveOne();
  2405. if (I == nullptr) continue; // skip null values.
  2406. // Check to see if we can DCE the instruction.
  2407. if (isInstructionTriviallyDead(I, TLI)) {
  2408. DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
  2409. EraseInstFromFunction(*I);
  2410. ++NumDeadInst;
  2411. MadeIRChange = true;
  2412. continue;
  2413. }
  2414. // Instruction isn't dead, see if we can constant propagate it.
  2415. if (!I->use_empty() &&
  2416. (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
  2417. if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
  2418. DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
  2419. // Add operands to the worklist.
  2420. ReplaceInstUsesWith(*I, C);
  2421. ++NumConstProp;
  2422. EraseInstFromFunction(*I);
  2423. MadeIRChange = true;
  2424. continue;
  2425. }
  2426. }
  2427. // See if we can trivially sink this instruction to a successor basic block.
  2428. if (I->hasOneUse()) {
  2429. BasicBlock *BB = I->getParent();
  2430. Instruction *UserInst = cast<Instruction>(*I->user_begin());
  2431. BasicBlock *UserParent;
  2432. // Get the block the use occurs in.
  2433. if (PHINode *PN = dyn_cast<PHINode>(UserInst))
  2434. UserParent = PN->getIncomingBlock(*I->use_begin());
  2435. else
  2436. UserParent = UserInst->getParent();
  2437. if (UserParent != BB) {
  2438. bool UserIsSuccessor = false;
  2439. // See if the user is one of our successors.
  2440. for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
  2441. if (*SI == UserParent) {
  2442. UserIsSuccessor = true;
  2443. break;
  2444. }
  2445. // If the user is one of our immediate successors, and if that successor
  2446. // only has us as a predecessors (we'd have to split the critical edge
  2447. // otherwise), we can keep going.
  2448. if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
  2449. // Okay, the CFG is simple enough, try to sink this instruction.
  2450. if (TryToSinkInstruction(I, UserParent)) {
  2451. MadeIRChange = true;
  2452. // We'll add uses of the sunk instruction below, but since sinking
  2453. // can expose opportunities for it's *operands* add them to the
  2454. // worklist
  2455. for (Use &U : I->operands())
  2456. if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
  2457. Worklist.Add(OpI);
  2458. }
  2459. }
  2460. }
  2461. }
  2462. // Now that we have an instruction, try combining it to simplify it.
  2463. Builder->SetInsertPoint(I->getParent(), I);
  2464. Builder->SetCurrentDebugLocation(I->getDebugLoc());
  2465. #ifndef NDEBUG
  2466. std::string OrigI;
  2467. #endif
  2468. DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
  2469. DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
  2470. if (Instruction *Result = visit(*I)) {
  2471. ++NumCombined;
  2472. // Should we replace the old instruction with a new one?
  2473. if (Result != I) {
  2474. DEBUG(dbgs() << "IC: Old = " << *I << '\n'
  2475. << " New = " << *Result << '\n');
  2476. if (I->getDebugLoc())
  2477. Result->setDebugLoc(I->getDebugLoc());
  2478. // Everything uses the new instruction now.
  2479. I->replaceAllUsesWith(Result);
  2480. // Move the name to the new instruction first.
  2481. Result->takeName(I);
  2482. // Push the new instruction and any users onto the worklist.
  2483. Worklist.Add(Result);
  2484. Worklist.AddUsersToWorkList(*Result);
  2485. // Insert the new instruction into the basic block...
  2486. BasicBlock *InstParent = I->getParent();
  2487. BasicBlock::iterator InsertPos = I;
  2488. // If we replace a PHI with something that isn't a PHI, fix up the
  2489. // insertion point.
  2490. if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
  2491. InsertPos = InstParent->getFirstInsertionPt();
  2492. InstParent->getInstList().insert(InsertPos, Result);
  2493. EraseInstFromFunction(*I);
  2494. } else {
  2495. #ifndef NDEBUG
  2496. DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
  2497. << " New = " << *I << '\n');
  2498. #endif
  2499. // If the instruction was modified, it's possible that it is now dead.
  2500. // if so, remove it.
  2501. if (isInstructionTriviallyDead(I, TLI)) {
  2502. EraseInstFromFunction(*I);
  2503. } else {
  2504. Worklist.Add(I);
  2505. Worklist.AddUsersToWorkList(*I);
  2506. }
  2507. }
  2508. MadeIRChange = true;
  2509. }
  2510. }
  2511. Worklist.Zap();
  2512. return MadeIRChange;
  2513. }
  2514. /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
  2515. /// all reachable code to the worklist.
  2516. ///
  2517. /// This has a couple of tricks to make the code faster and more powerful. In
  2518. /// particular, we constant fold and DCE instructions as we go, to avoid adding
  2519. /// them to the worklist (this significantly speeds up instcombine on code where
  2520. /// many instructions are dead or constant). Additionally, if we find a branch
  2521. /// whose condition is a known constant, we only visit the reachable successors.
  2522. ///
  2523. static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
  2524. SmallPtrSetImpl<BasicBlock *> &Visited,
  2525. InstCombineWorklist &ICWorklist,
  2526. const TargetLibraryInfo *TLI) {
  2527. bool MadeIRChange = false;
  2528. SmallVector<BasicBlock*, 256> Worklist;
  2529. Worklist.push_back(BB);
  2530. SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
  2531. DenseMap<ConstantExpr*, Constant*> FoldedConstants;
  2532. do {
  2533. BB = Worklist.pop_back_val();
  2534. // We have now visited this block! If we've already been here, ignore it.
  2535. if (!Visited.insert(BB).second)
  2536. continue;
  2537. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  2538. Instruction *Inst = BBI++;
  2539. // DCE instruction if trivially dead.
  2540. if (isInstructionTriviallyDead(Inst, TLI)) {
  2541. ++NumDeadInst;
  2542. DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
  2543. Inst->eraseFromParent();
  2544. continue;
  2545. }
  2546. // ConstantProp instruction if trivially constant.
  2547. if (!Inst->use_empty() &&
  2548. (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
  2549. if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
  2550. DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
  2551. << *Inst << '\n');
  2552. Inst->replaceAllUsesWith(C);
  2553. ++NumConstProp;
  2554. Inst->eraseFromParent();
  2555. continue;
  2556. }
  2557. // See if we can constant fold its operands.
  2558. for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
  2559. ++i) {
  2560. ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
  2561. if (CE == nullptr)
  2562. continue;
  2563. Constant *&FoldRes = FoldedConstants[CE];
  2564. if (!FoldRes)
  2565. FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
  2566. if (!FoldRes)
  2567. FoldRes = CE;
  2568. if (FoldRes != CE) {
  2569. *i = FoldRes;
  2570. MadeIRChange = true;
  2571. }
  2572. }
  2573. InstrsForInstCombineWorklist.push_back(Inst);
  2574. }
  2575. // Recursively visit successors. If this is a branch or switch on a
  2576. // constant, only visit the reachable successor.
  2577. TerminatorInst *TI = BB->getTerminator();
  2578. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2579. if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
  2580. bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
  2581. BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
  2582. Worklist.push_back(ReachableBB);
  2583. continue;
  2584. }
  2585. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2586. if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
  2587. // See if this is an explicit destination.
  2588. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2589. i != e; ++i)
  2590. if (i.getCaseValue() == Cond) {
  2591. BasicBlock *ReachableBB = i.getCaseSuccessor();
  2592. Worklist.push_back(ReachableBB);
  2593. continue;
  2594. }
  2595. // Otherwise it is the default destination.
  2596. Worklist.push_back(SI->getDefaultDest());
  2597. continue;
  2598. }
  2599. }
  2600. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  2601. Worklist.push_back(TI->getSuccessor(i));
  2602. } while (!Worklist.empty());
  2603. // Once we've found all of the instructions to add to instcombine's worklist,
  2604. // add them in reverse order. This way instcombine will visit from the top
  2605. // of the function down. This jives well with the way that it adds all uses
  2606. // of instructions to the worklist after doing a transformation, thus avoiding
  2607. // some N^2 behavior in pathological cases.
  2608. ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
  2609. InstrsForInstCombineWorklist.size());
  2610. return MadeIRChange;
  2611. }
  2612. /// \brief Populate the IC worklist from a function, and prune any dead basic
  2613. /// blocks discovered in the process.
  2614. ///
  2615. /// This also does basic constant propagation and other forward fixing to make
  2616. /// the combiner itself run much faster.
  2617. static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
  2618. TargetLibraryInfo *TLI,
  2619. InstCombineWorklist &ICWorklist) {
  2620. bool MadeIRChange = false;
  2621. // Do a depth-first traversal of the function, populate the worklist with
  2622. // the reachable instructions. Ignore blocks that are not reachable. Keep
  2623. // track of which blocks we visit.
  2624. SmallPtrSet<BasicBlock *, 64> Visited;
  2625. MadeIRChange |=
  2626. AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
  2627. // Do a quick scan over the function. If we find any blocks that are
  2628. // unreachable, remove any instructions inside of them. This prevents
  2629. // the instcombine code from having to deal with some bad special cases.
  2630. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  2631. if (Visited.count(BB))
  2632. continue;
  2633. // Delete the instructions backwards, as it has a reduced likelihood of
  2634. // having to update as many def-use and use-def chains.
  2635. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  2636. while (EndInst != BB->begin()) {
  2637. // Delete the next to last instruction.
  2638. BasicBlock::iterator I = EndInst;
  2639. Instruction *Inst = --I;
  2640. if (!Inst->use_empty())
  2641. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  2642. if (isa<LandingPadInst>(Inst)) {
  2643. EndInst = Inst;
  2644. continue;
  2645. }
  2646. if (!isa<DbgInfoIntrinsic>(Inst)) {
  2647. ++NumDeadInst;
  2648. MadeIRChange = true;
  2649. }
  2650. Inst->eraseFromParent();
  2651. }
  2652. }
  2653. return MadeIRChange;
  2654. }
  2655. static bool
  2656. combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
  2657. AliasAnalysis *AA, AssumptionCache &AC,
  2658. TargetLibraryInfo &TLI, DominatorTree &DT,
  2659. LoopInfo *LI = nullptr) {
  2660. // Minimizing size?
  2661. bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
  2662. auto &DL = F.getParent()->getDataLayout();
  2663. /// Builder - This is an IRBuilder that automatically inserts new
  2664. /// instructions into the worklist when they are created.
  2665. IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
  2666. F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
  2667. // Lower dbg.declare intrinsics otherwise their value may be clobbered
  2668. // by instcombiner.
  2669. bool DbgDeclaresChanged = LowerDbgDeclare(F);
  2670. // Iterate while there is work to do.
  2671. int Iteration = 0;
  2672. for (;;) {
  2673. ++Iteration;
  2674. DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
  2675. << F.getName() << "\n");
  2676. bool Changed = false;
  2677. if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
  2678. Changed = true;
  2679. InstCombiner IC(Worklist, &Builder, MinimizeSize,
  2680. AA, &AC, &TLI, &DT, DL, LI);
  2681. if (IC.run())
  2682. Changed = true;
  2683. if (!Changed)
  2684. break;
  2685. }
  2686. return DbgDeclaresChanged || Iteration > 1;
  2687. }
  2688. PreservedAnalyses InstCombinePass::run(Function &F,
  2689. AnalysisManager<Function> *AM) {
  2690. auto &AC = AM->getResult<AssumptionAnalysis>(F);
  2691. auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
  2692. auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
  2693. auto *LI = AM->getCachedResult<LoopAnalysis>(F);
  2694. // FIXME: The AliasAnalysis is not yet supported in the new pass manager
  2695. if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
  2696. // No changes, all analyses are preserved.
  2697. return PreservedAnalyses::all();
  2698. // Mark all the analyses that instcombine updates as preserved.
  2699. // FIXME: Need a way to preserve CFG analyses here!
  2700. PreservedAnalyses PA;
  2701. PA.preserve<DominatorTreeAnalysis>();
  2702. return PA;
  2703. }
  2704. namespace {
  2705. /// \brief The legacy pass manager's instcombine pass.
  2706. ///
  2707. /// This is a basic whole-function wrapper around the instcombine utility. It
  2708. /// will try to combine all instructions in the function.
  2709. class InstructionCombiningPass : public FunctionPass {
  2710. InstCombineWorklist Worklist;
  2711. public:
  2712. static char ID; // Pass identification, replacement for typeid
  2713. InstructionCombiningPass() : FunctionPass(ID) {
  2714. initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
  2715. }
  2716. void getAnalysisUsage(AnalysisUsage &AU) const override;
  2717. bool runOnFunction(Function &F) override;
  2718. };
  2719. }
  2720. void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
  2721. AU.setPreservesCFG();
  2722. AU.addRequired<AliasAnalysis>();
  2723. AU.addRequired<AssumptionCacheTracker>();
  2724. AU.addRequired<TargetLibraryInfoWrapperPass>();
  2725. AU.addRequired<DominatorTreeWrapperPass>();
  2726. AU.addPreserved<DominatorTreeWrapperPass>();
  2727. }
  2728. bool InstructionCombiningPass::runOnFunction(Function &F) {
  2729. if (skipOptnoneFunction(F))
  2730. return false;
  2731. // Required analyses.
  2732. auto AA = &getAnalysis<AliasAnalysis>();
  2733. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2734. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2735. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2736. // Optional analyses.
  2737. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  2738. auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  2739. return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
  2740. }
  2741. char InstructionCombiningPass::ID = 0;
  2742. INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
  2743. "Combine redundant instructions", false, false)
  2744. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  2745. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2746. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2747. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  2748. INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
  2749. "Combine redundant instructions", false, false)
  2750. // Initialization Routines
  2751. void llvm::initializeInstCombine(PassRegistry &Registry) {
  2752. initializeInstructionCombiningPassPass(Registry);
  2753. }
  2754. void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
  2755. initializeInstructionCombiningPassPass(*unwrap(R));
  2756. }
  2757. FunctionPass *llvm::createInstructionCombiningPass() {
  2758. return new InstructionCombiningPass();
  2759. }