InstCombineVectorOps.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110
  1. //===- InstCombineVectorOps.cpp -------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements instcombine for ExtractElement, InsertElement and
  10. // ShuffleVector.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallBitVector.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/VectorUtils.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/Constant.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/InstrTypes.h"
  28. #include "llvm/IR/Instruction.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/Operator.h"
  31. #include "llvm/IR/PatternMatch.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/User.h"
  34. #include "llvm/IR/Value.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  38. #include <cassert>
  39. #include <cstdint>
  40. #include <iterator>
  41. #include <utility>
  42. #define DEBUG_TYPE "instcombine"
  43. using namespace llvm;
  44. using namespace PatternMatch;
  45. STATISTIC(NumAggregateReconstructionsSimplified,
  46. "Number of aggregate reconstructions turned into reuse of the "
  47. "original aggregate");
  48. /// Return true if the value is cheaper to scalarize than it is to leave as a
  49. /// vector operation. If the extract index \p EI is a constant integer then
  50. /// some operations may be cheap to scalarize.
  51. ///
  52. /// FIXME: It's possible to create more instructions than previously existed.
  53. static bool cheapToScalarize(Value *V, Value *EI) {
  54. ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
  55. // If we can pick a scalar constant value out of a vector, that is free.
  56. if (auto *C = dyn_cast<Constant>(V))
  57. return CEI || C->getSplatValue();
  58. if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
  59. ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
  60. // Index needs to be lower than the minimum size of the vector, because
  61. // for scalable vector, the vector size is known at run time.
  62. return CEI->getValue().ult(EC.getKnownMinValue());
  63. }
  64. // An insertelement to the same constant index as our extract will simplify
  65. // to the scalar inserted element. An insertelement to a different constant
  66. // index is irrelevant to our extract.
  67. if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
  68. return CEI;
  69. if (match(V, m_OneUse(m_Load(m_Value()))))
  70. return true;
  71. if (match(V, m_OneUse(m_UnOp())))
  72. return true;
  73. Value *V0, *V1;
  74. if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
  75. if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
  76. return true;
  77. CmpInst::Predicate UnusedPred;
  78. if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
  79. if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
  80. return true;
  81. return false;
  82. }
  83. // If we have a PHI node with a vector type that is only used to feed
  84. // itself and be an operand of extractelement at a constant location,
  85. // try to replace the PHI of the vector type with a PHI of a scalar type.
  86. Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
  87. PHINode *PN) {
  88. SmallVector<Instruction *, 2> Extracts;
  89. // The users we want the PHI to have are:
  90. // 1) The EI ExtractElement (we already know this)
  91. // 2) Possibly more ExtractElements with the same index.
  92. // 3) Another operand, which will feed back into the PHI.
  93. Instruction *PHIUser = nullptr;
  94. for (auto *U : PN->users()) {
  95. if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
  96. if (EI.getIndexOperand() == EU->getIndexOperand())
  97. Extracts.push_back(EU);
  98. else
  99. return nullptr;
  100. } else if (!PHIUser) {
  101. PHIUser = cast<Instruction>(U);
  102. } else {
  103. return nullptr;
  104. }
  105. }
  106. if (!PHIUser)
  107. return nullptr;
  108. // Verify that this PHI user has one use, which is the PHI itself,
  109. // and that it is a binary operation which is cheap to scalarize.
  110. // otherwise return nullptr.
  111. if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
  112. !(isa<BinaryOperator>(PHIUser)) ||
  113. !cheapToScalarize(PHIUser, EI.getIndexOperand()))
  114. return nullptr;
  115. // Create a scalar PHI node that will replace the vector PHI node
  116. // just before the current PHI node.
  117. PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
  118. PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
  119. // Scalarize each PHI operand.
  120. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  121. Value *PHIInVal = PN->getIncomingValue(i);
  122. BasicBlock *inBB = PN->getIncomingBlock(i);
  123. Value *Elt = EI.getIndexOperand();
  124. // If the operand is the PHI induction variable:
  125. if (PHIInVal == PHIUser) {
  126. // Scalarize the binary operation. Its first operand is the
  127. // scalar PHI, and the second operand is extracted from the other
  128. // vector operand.
  129. BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
  130. unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
  131. Value *Op = InsertNewInstWith(
  132. ExtractElementInst::Create(B0->getOperand(opId), Elt,
  133. B0->getOperand(opId)->getName() + ".Elt"),
  134. *B0);
  135. Value *newPHIUser = InsertNewInstWith(
  136. BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
  137. scalarPHI, Op, B0), *B0);
  138. scalarPHI->addIncoming(newPHIUser, inBB);
  139. } else {
  140. // Scalarize PHI input:
  141. Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
  142. // Insert the new instruction into the predecessor basic block.
  143. Instruction *pos = dyn_cast<Instruction>(PHIInVal);
  144. BasicBlock::iterator InsertPos;
  145. if (pos && !isa<PHINode>(pos)) {
  146. InsertPos = ++pos->getIterator();
  147. } else {
  148. InsertPos = inBB->getFirstInsertionPt();
  149. }
  150. InsertNewInstWith(newEI, *InsertPos);
  151. scalarPHI->addIncoming(newEI, inBB);
  152. }
  153. }
  154. for (auto *E : Extracts)
  155. replaceInstUsesWith(*E, scalarPHI);
  156. return &EI;
  157. }
  158. Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
  159. Value *X;
  160. uint64_t ExtIndexC;
  161. if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
  162. !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
  163. return nullptr;
  164. ElementCount NumElts =
  165. cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
  166. Type *DestTy = Ext.getType();
  167. unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
  168. bool IsBigEndian = DL.isBigEndian();
  169. // If we are casting an integer to vector and extracting a portion, that is
  170. // a shift-right and truncate.
  171. if (X->getType()->isIntegerTy()) {
  172. assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
  173. "Expected fixed vector type for bitcast from scalar integer");
  174. // Big endian requires adjusting the extract index since MSB is at index 0.
  175. // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
  176. // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
  177. if (IsBigEndian)
  178. ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
  179. unsigned ShiftAmountC = ExtIndexC * DestWidth;
  180. if (!ShiftAmountC ||
  181. (isDesirableIntType(X->getType()->getPrimitiveSizeInBits()) &&
  182. Ext.getVectorOperand()->hasOneUse())) {
  183. if (ShiftAmountC)
  184. X = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
  185. if (DestTy->isFloatingPointTy()) {
  186. Type *DstIntTy = IntegerType::getIntNTy(X->getContext(), DestWidth);
  187. Value *Trunc = Builder.CreateTrunc(X, DstIntTy);
  188. return new BitCastInst(Trunc, DestTy);
  189. }
  190. return new TruncInst(X, DestTy);
  191. }
  192. }
  193. if (!X->getType()->isVectorTy())
  194. return nullptr;
  195. // If this extractelement is using a bitcast from a vector of the same number
  196. // of elements, see if we can find the source element from the source vector:
  197. // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
  198. auto *SrcTy = cast<VectorType>(X->getType());
  199. ElementCount NumSrcElts = SrcTy->getElementCount();
  200. if (NumSrcElts == NumElts)
  201. if (Value *Elt = findScalarElement(X, ExtIndexC))
  202. return new BitCastInst(Elt, DestTy);
  203. assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
  204. "Src and Dst must be the same sort of vector type");
  205. // If the source elements are wider than the destination, try to shift and
  206. // truncate a subset of scalar bits of an insert op.
  207. if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
  208. Value *Scalar;
  209. Value *Vec;
  210. uint64_t InsIndexC;
  211. if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
  212. m_ConstantInt(InsIndexC))))
  213. return nullptr;
  214. // The extract must be from the subset of vector elements that we inserted
  215. // into. Example: if we inserted element 1 of a <2 x i64> and we are
  216. // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
  217. // of elements 4-7 of the bitcasted vector.
  218. unsigned NarrowingRatio =
  219. NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
  220. if (ExtIndexC / NarrowingRatio != InsIndexC) {
  221. // Remove insertelement, if we don't use the inserted element.
  222. // extractelement (bitcast (insertelement (Vec, b)), a) ->
  223. // extractelement (bitcast (Vec), a)
  224. // FIXME: this should be removed to SimplifyDemandedVectorElts,
  225. // once scale vectors are supported.
  226. if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
  227. Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
  228. return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
  229. }
  230. return nullptr;
  231. }
  232. // We are extracting part of the original scalar. How that scalar is
  233. // inserted into the vector depends on the endian-ness. Example:
  234. // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
  235. // +--+--+--+--+--+--+--+--+
  236. // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
  237. // extelt <4 x i16> V', 3: | |S2|S3|
  238. // +--+--+--+--+--+--+--+--+
  239. // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
  240. // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
  241. // In this example, we must right-shift little-endian. Big-endian is just a
  242. // truncate.
  243. unsigned Chunk = ExtIndexC % NarrowingRatio;
  244. if (IsBigEndian)
  245. Chunk = NarrowingRatio - 1 - Chunk;
  246. // Bail out if this is an FP vector to FP vector sequence. That would take
  247. // more instructions than we started with unless there is no shift, and it
  248. // may not be handled as well in the backend.
  249. bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
  250. bool NeedDestBitcast = DestTy->isFloatingPointTy();
  251. if (NeedSrcBitcast && NeedDestBitcast)
  252. return nullptr;
  253. unsigned SrcWidth = SrcTy->getScalarSizeInBits();
  254. unsigned ShAmt = Chunk * DestWidth;
  255. // TODO: This limitation is more strict than necessary. We could sum the
  256. // number of new instructions and subtract the number eliminated to know if
  257. // we can proceed.
  258. if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
  259. if (NeedSrcBitcast || NeedDestBitcast)
  260. return nullptr;
  261. if (NeedSrcBitcast) {
  262. Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
  263. Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
  264. }
  265. if (ShAmt) {
  266. // Bail out if we could end with more instructions than we started with.
  267. if (!Ext.getVectorOperand()->hasOneUse())
  268. return nullptr;
  269. Scalar = Builder.CreateLShr(Scalar, ShAmt);
  270. }
  271. if (NeedDestBitcast) {
  272. Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
  273. return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
  274. }
  275. return new TruncInst(Scalar, DestTy);
  276. }
  277. return nullptr;
  278. }
  279. /// Find elements of V demanded by UserInstr.
  280. static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
  281. unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
  282. // Conservatively assume that all elements are needed.
  283. APInt UsedElts(APInt::getAllOnes(VWidth));
  284. switch (UserInstr->getOpcode()) {
  285. case Instruction::ExtractElement: {
  286. ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
  287. assert(EEI->getVectorOperand() == V);
  288. ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
  289. if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
  290. UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
  291. }
  292. break;
  293. }
  294. case Instruction::ShuffleVector: {
  295. ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
  296. unsigned MaskNumElts =
  297. cast<FixedVectorType>(UserInstr->getType())->getNumElements();
  298. UsedElts = APInt(VWidth, 0);
  299. for (unsigned i = 0; i < MaskNumElts; i++) {
  300. unsigned MaskVal = Shuffle->getMaskValue(i);
  301. if (MaskVal == -1u || MaskVal >= 2 * VWidth)
  302. continue;
  303. if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
  304. UsedElts.setBit(MaskVal);
  305. if (Shuffle->getOperand(1) == V &&
  306. ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
  307. UsedElts.setBit(MaskVal - VWidth);
  308. }
  309. break;
  310. }
  311. default:
  312. break;
  313. }
  314. return UsedElts;
  315. }
  316. /// Find union of elements of V demanded by all its users.
  317. /// If it is known by querying findDemandedEltsBySingleUser that
  318. /// no user demands an element of V, then the corresponding bit
  319. /// remains unset in the returned value.
  320. static APInt findDemandedEltsByAllUsers(Value *V) {
  321. unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
  322. APInt UnionUsedElts(VWidth, 0);
  323. for (const Use &U : V->uses()) {
  324. if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
  325. UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
  326. } else {
  327. UnionUsedElts = APInt::getAllOnes(VWidth);
  328. break;
  329. }
  330. if (UnionUsedElts.isAllOnes())
  331. break;
  332. }
  333. return UnionUsedElts;
  334. }
  335. /// Given a constant index for a extractelement or insertelement instruction,
  336. /// return it with the canonical type if it isn't already canonical. We
  337. /// arbitrarily pick 64 bit as our canonical type. The actual bitwidth doesn't
  338. /// matter, we just want a consistent type to simplify CSE.
  339. ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
  340. const unsigned IndexBW = IndexC->getType()->getBitWidth();
  341. if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
  342. return nullptr;
  343. return ConstantInt::get(IndexC->getContext(),
  344. IndexC->getValue().zextOrTrunc(64));
  345. }
  346. Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
  347. Value *SrcVec = EI.getVectorOperand();
  348. Value *Index = EI.getIndexOperand();
  349. if (Value *V = simplifyExtractElementInst(SrcVec, Index,
  350. SQ.getWithInstruction(&EI)))
  351. return replaceInstUsesWith(EI, V);
  352. // extractelt (select %x, %vec1, %vec2), %const ->
  353. // select %x, %vec1[%const], %vec2[%const]
  354. // TODO: Support constant folding of multiple select operands:
  355. // extractelt (select %x, %vec1, %vec2), (select %x, %c1, %c2)
  356. // If the extractelement will for instance try to do out of bounds accesses
  357. // because of the values of %c1 and/or %c2, the sequence could be optimized
  358. // early. This is currently not possible because constant folding will reach
  359. // an unreachable assertion if it doesn't find a constant operand.
  360. if (SelectInst *SI = dyn_cast<SelectInst>(EI.getVectorOperand()))
  361. if (SI->getCondition()->getType()->isIntegerTy() &&
  362. isa<Constant>(EI.getIndexOperand()))
  363. if (Instruction *R = FoldOpIntoSelect(EI, SI))
  364. return R;
  365. // If extracting a specified index from the vector, see if we can recursively
  366. // find a previously computed scalar that was inserted into the vector.
  367. auto *IndexC = dyn_cast<ConstantInt>(Index);
  368. if (IndexC) {
  369. // Canonicalize type of constant indices to i64 to simplify CSE
  370. if (auto *NewIdx = getPreferredVectorIndex(IndexC))
  371. return replaceOperand(EI, 1, NewIdx);
  372. ElementCount EC = EI.getVectorOperandType()->getElementCount();
  373. unsigned NumElts = EC.getKnownMinValue();
  374. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
  375. Intrinsic::ID IID = II->getIntrinsicID();
  376. // Index needs to be lower than the minimum size of the vector, because
  377. // for scalable vector, the vector size is known at run time.
  378. if (IID == Intrinsic::experimental_stepvector &&
  379. IndexC->getValue().ult(NumElts)) {
  380. Type *Ty = EI.getType();
  381. unsigned BitWidth = Ty->getIntegerBitWidth();
  382. Value *Idx;
  383. // Return index when its value does not exceed the allowed limit
  384. // for the element type of the vector, otherwise return undefined.
  385. if (IndexC->getValue().getActiveBits() <= BitWidth)
  386. Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
  387. else
  388. Idx = UndefValue::get(Ty);
  389. return replaceInstUsesWith(EI, Idx);
  390. }
  391. }
  392. // InstSimplify should handle cases where the index is invalid.
  393. // For fixed-length vector, it's invalid to extract out-of-range element.
  394. if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
  395. return nullptr;
  396. if (Instruction *I = foldBitcastExtElt(EI))
  397. return I;
  398. // If there's a vector PHI feeding a scalar use through this extractelement
  399. // instruction, try to scalarize the PHI.
  400. if (auto *Phi = dyn_cast<PHINode>(SrcVec))
  401. if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
  402. return ScalarPHI;
  403. }
  404. // TODO come up with a n-ary matcher that subsumes both unary and
  405. // binary matchers.
  406. UnaryOperator *UO;
  407. if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
  408. // extelt (unop X), Index --> unop (extelt X, Index)
  409. Value *X = UO->getOperand(0);
  410. Value *E = Builder.CreateExtractElement(X, Index);
  411. return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
  412. }
  413. BinaryOperator *BO;
  414. if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
  415. // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
  416. Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
  417. Value *E0 = Builder.CreateExtractElement(X, Index);
  418. Value *E1 = Builder.CreateExtractElement(Y, Index);
  419. return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
  420. }
  421. Value *X, *Y;
  422. CmpInst::Predicate Pred;
  423. if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
  424. cheapToScalarize(SrcVec, Index)) {
  425. // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
  426. Value *E0 = Builder.CreateExtractElement(X, Index);
  427. Value *E1 = Builder.CreateExtractElement(Y, Index);
  428. return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
  429. }
  430. if (auto *I = dyn_cast<Instruction>(SrcVec)) {
  431. if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  432. // instsimplify already handled the case where the indices are constants
  433. // and equal by value, if both are constants, they must not be the same
  434. // value, extract from the pre-inserted value instead.
  435. if (isa<Constant>(IE->getOperand(2)) && IndexC)
  436. return replaceOperand(EI, 0, IE->getOperand(0));
  437. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  438. auto *VecType = cast<VectorType>(GEP->getType());
  439. ElementCount EC = VecType->getElementCount();
  440. uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
  441. if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
  442. // Find out why we have a vector result - these are a few examples:
  443. // 1. We have a scalar pointer and a vector of indices, or
  444. // 2. We have a vector of pointers and a scalar index, or
  445. // 3. We have a vector of pointers and a vector of indices, etc.
  446. // Here we only consider combining when there is exactly one vector
  447. // operand, since the optimization is less obviously a win due to
  448. // needing more than one extractelements.
  449. unsigned VectorOps =
  450. llvm::count_if(GEP->operands(), [](const Value *V) {
  451. return isa<VectorType>(V->getType());
  452. });
  453. if (VectorOps == 1) {
  454. Value *NewPtr = GEP->getPointerOperand();
  455. if (isa<VectorType>(NewPtr->getType()))
  456. NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
  457. SmallVector<Value *> NewOps;
  458. for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
  459. Value *Op = GEP->getOperand(I);
  460. if (isa<VectorType>(Op->getType()))
  461. NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
  462. else
  463. NewOps.push_back(Op);
  464. }
  465. GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
  466. GEP->getSourceElementType(), NewPtr, NewOps);
  467. NewGEP->setIsInBounds(GEP->isInBounds());
  468. return NewGEP;
  469. }
  470. }
  471. } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
  472. // If this is extracting an element from a shufflevector, figure out where
  473. // it came from and extract from the appropriate input element instead.
  474. // Restrict the following transformation to fixed-length vector.
  475. if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
  476. int SrcIdx =
  477. SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
  478. Value *Src;
  479. unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
  480. ->getNumElements();
  481. if (SrcIdx < 0)
  482. return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
  483. if (SrcIdx < (int)LHSWidth)
  484. Src = SVI->getOperand(0);
  485. else {
  486. SrcIdx -= LHSWidth;
  487. Src = SVI->getOperand(1);
  488. }
  489. Type *Int32Ty = Type::getInt32Ty(EI.getContext());
  490. return ExtractElementInst::Create(
  491. Src, ConstantInt::get(Int32Ty, SrcIdx, false));
  492. }
  493. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  494. // Canonicalize extractelement(cast) -> cast(extractelement).
  495. // Bitcasts can change the number of vector elements, and they cost
  496. // nothing.
  497. if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
  498. Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
  499. return CastInst::Create(CI->getOpcode(), EE, EI.getType());
  500. }
  501. }
  502. }
  503. // Run demanded elements after other transforms as this can drop flags on
  504. // binops. If there's two paths to the same final result, we prefer the
  505. // one which doesn't force us to drop flags.
  506. if (IndexC) {
  507. ElementCount EC = EI.getVectorOperandType()->getElementCount();
  508. unsigned NumElts = EC.getKnownMinValue();
  509. // This instruction only demands the single element from the input vector.
  510. // Skip for scalable type, the number of elements is unknown at
  511. // compile-time.
  512. if (!EC.isScalable() && NumElts != 1) {
  513. // If the input vector has a single use, simplify it based on this use
  514. // property.
  515. if (SrcVec->hasOneUse()) {
  516. APInt UndefElts(NumElts, 0);
  517. APInt DemandedElts(NumElts, 0);
  518. DemandedElts.setBit(IndexC->getZExtValue());
  519. if (Value *V =
  520. SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
  521. return replaceOperand(EI, 0, V);
  522. } else {
  523. // If the input vector has multiple uses, simplify it based on a union
  524. // of all elements used.
  525. APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
  526. if (!DemandedElts.isAllOnes()) {
  527. APInt UndefElts(NumElts, 0);
  528. if (Value *V = SimplifyDemandedVectorElts(
  529. SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
  530. true /* AllowMultipleUsers */)) {
  531. if (V != SrcVec) {
  532. SrcVec->replaceAllUsesWith(V);
  533. return &EI;
  534. }
  535. }
  536. }
  537. }
  538. }
  539. }
  540. return nullptr;
  541. }
  542. /// If V is a shuffle of values that ONLY returns elements from either LHS or
  543. /// RHS, return the shuffle mask and true. Otherwise, return false.
  544. static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
  545. SmallVectorImpl<int> &Mask) {
  546. assert(LHS->getType() == RHS->getType() &&
  547. "Invalid CollectSingleShuffleElements");
  548. unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
  549. if (match(V, m_Undef())) {
  550. Mask.assign(NumElts, -1);
  551. return true;
  552. }
  553. if (V == LHS) {
  554. for (unsigned i = 0; i != NumElts; ++i)
  555. Mask.push_back(i);
  556. return true;
  557. }
  558. if (V == RHS) {
  559. for (unsigned i = 0; i != NumElts; ++i)
  560. Mask.push_back(i + NumElts);
  561. return true;
  562. }
  563. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  564. // If this is an insert of an extract from some other vector, include it.
  565. Value *VecOp = IEI->getOperand(0);
  566. Value *ScalarOp = IEI->getOperand(1);
  567. Value *IdxOp = IEI->getOperand(2);
  568. if (!isa<ConstantInt>(IdxOp))
  569. return false;
  570. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  571. if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
  572. // We can handle this if the vector we are inserting into is
  573. // transitively ok.
  574. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  575. // If so, update the mask to reflect the inserted undef.
  576. Mask[InsertedIdx] = -1;
  577. return true;
  578. }
  579. } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
  580. if (isa<ConstantInt>(EI->getOperand(1))) {
  581. unsigned ExtractedIdx =
  582. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  583. unsigned NumLHSElts =
  584. cast<FixedVectorType>(LHS->getType())->getNumElements();
  585. // This must be extracting from either LHS or RHS.
  586. if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
  587. // We can handle this if the vector we are inserting into is
  588. // transitively ok.
  589. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  590. // If so, update the mask to reflect the inserted value.
  591. if (EI->getOperand(0) == LHS) {
  592. Mask[InsertedIdx % NumElts] = ExtractedIdx;
  593. } else {
  594. assert(EI->getOperand(0) == RHS);
  595. Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
  596. }
  597. return true;
  598. }
  599. }
  600. }
  601. }
  602. }
  603. return false;
  604. }
  605. /// If we have insertion into a vector that is wider than the vector that we
  606. /// are extracting from, try to widen the source vector to allow a single
  607. /// shufflevector to replace one or more insert/extract pairs.
  608. static void replaceExtractElements(InsertElementInst *InsElt,
  609. ExtractElementInst *ExtElt,
  610. InstCombinerImpl &IC) {
  611. auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
  612. auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
  613. unsigned NumInsElts = InsVecType->getNumElements();
  614. unsigned NumExtElts = ExtVecType->getNumElements();
  615. // The inserted-to vector must be wider than the extracted-from vector.
  616. if (InsVecType->getElementType() != ExtVecType->getElementType() ||
  617. NumExtElts >= NumInsElts)
  618. return;
  619. // Create a shuffle mask to widen the extended-from vector using poison
  620. // values. The mask selects all of the values of the original vector followed
  621. // by as many poison values as needed to create a vector of the same length
  622. // as the inserted-to vector.
  623. SmallVector<int, 16> ExtendMask;
  624. for (unsigned i = 0; i < NumExtElts; ++i)
  625. ExtendMask.push_back(i);
  626. for (unsigned i = NumExtElts; i < NumInsElts; ++i)
  627. ExtendMask.push_back(-1);
  628. Value *ExtVecOp = ExtElt->getVectorOperand();
  629. auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
  630. BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
  631. ? ExtVecOpInst->getParent()
  632. : ExtElt->getParent();
  633. // TODO: This restriction matches the basic block check below when creating
  634. // new extractelement instructions. If that limitation is removed, this one
  635. // could also be removed. But for now, we just bail out to ensure that we
  636. // will replace the extractelement instruction that is feeding our
  637. // insertelement instruction. This allows the insertelement to then be
  638. // replaced by a shufflevector. If the insertelement is not replaced, we can
  639. // induce infinite looping because there's an optimization for extractelement
  640. // that will delete our widening shuffle. This would trigger another attempt
  641. // here to create that shuffle, and we spin forever.
  642. if (InsertionBlock != InsElt->getParent())
  643. return;
  644. // TODO: This restriction matches the check in visitInsertElementInst() and
  645. // prevents an infinite loop caused by not turning the extract/insert pair
  646. // into a shuffle. We really should not need either check, but we're lacking
  647. // folds for shufflevectors because we're afraid to generate shuffle masks
  648. // that the backend can't handle.
  649. if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
  650. return;
  651. auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
  652. // Insert the new shuffle after the vector operand of the extract is defined
  653. // (as long as it's not a PHI) or at the start of the basic block of the
  654. // extract, so any subsequent extracts in the same basic block can use it.
  655. // TODO: Insert before the earliest ExtractElementInst that is replaced.
  656. if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
  657. WideVec->insertAfter(ExtVecOpInst);
  658. else
  659. IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
  660. // Replace extracts from the original narrow vector with extracts from the new
  661. // wide vector.
  662. for (User *U : ExtVecOp->users()) {
  663. ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
  664. if (!OldExt || OldExt->getParent() != WideVec->getParent())
  665. continue;
  666. auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
  667. NewExt->insertAfter(OldExt);
  668. IC.replaceInstUsesWith(*OldExt, NewExt);
  669. }
  670. }
  671. /// We are building a shuffle to create V, which is a sequence of insertelement,
  672. /// extractelement pairs. If PermittedRHS is set, then we must either use it or
  673. /// not rely on the second vector source. Return a std::pair containing the
  674. /// left and right vectors of the proposed shuffle (or 0), and set the Mask
  675. /// parameter as required.
  676. ///
  677. /// Note: we intentionally don't try to fold earlier shuffles since they have
  678. /// often been chosen carefully to be efficiently implementable on the target.
  679. using ShuffleOps = std::pair<Value *, Value *>;
  680. static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
  681. Value *PermittedRHS,
  682. InstCombinerImpl &IC) {
  683. assert(V->getType()->isVectorTy() && "Invalid shuffle!");
  684. unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
  685. if (match(V, m_Undef())) {
  686. Mask.assign(NumElts, -1);
  687. return std::make_pair(
  688. PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
  689. }
  690. if (isa<ConstantAggregateZero>(V)) {
  691. Mask.assign(NumElts, 0);
  692. return std::make_pair(V, nullptr);
  693. }
  694. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  695. // If this is an insert of an extract from some other vector, include it.
  696. Value *VecOp = IEI->getOperand(0);
  697. Value *ScalarOp = IEI->getOperand(1);
  698. Value *IdxOp = IEI->getOperand(2);
  699. if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
  700. if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
  701. unsigned ExtractedIdx =
  702. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  703. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  704. // Either the extracted from or inserted into vector must be RHSVec,
  705. // otherwise we'd end up with a shuffle of three inputs.
  706. if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
  707. Value *RHS = EI->getOperand(0);
  708. ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
  709. assert(LR.second == nullptr || LR.second == RHS);
  710. if (LR.first->getType() != RHS->getType()) {
  711. // Although we are giving up for now, see if we can create extracts
  712. // that match the inserts for another round of combining.
  713. replaceExtractElements(IEI, EI, IC);
  714. // We tried our best, but we can't find anything compatible with RHS
  715. // further up the chain. Return a trivial shuffle.
  716. for (unsigned i = 0; i < NumElts; ++i)
  717. Mask[i] = i;
  718. return std::make_pair(V, nullptr);
  719. }
  720. unsigned NumLHSElts =
  721. cast<FixedVectorType>(RHS->getType())->getNumElements();
  722. Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
  723. return std::make_pair(LR.first, RHS);
  724. }
  725. if (VecOp == PermittedRHS) {
  726. // We've gone as far as we can: anything on the other side of the
  727. // extractelement will already have been converted into a shuffle.
  728. unsigned NumLHSElts =
  729. cast<FixedVectorType>(EI->getOperand(0)->getType())
  730. ->getNumElements();
  731. for (unsigned i = 0; i != NumElts; ++i)
  732. Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
  733. return std::make_pair(EI->getOperand(0), PermittedRHS);
  734. }
  735. // If this insertelement is a chain that comes from exactly these two
  736. // vectors, return the vector and the effective shuffle.
  737. if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
  738. collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
  739. Mask))
  740. return std::make_pair(EI->getOperand(0), PermittedRHS);
  741. }
  742. }
  743. }
  744. // Otherwise, we can't do anything fancy. Return an identity vector.
  745. for (unsigned i = 0; i != NumElts; ++i)
  746. Mask.push_back(i);
  747. return std::make_pair(V, nullptr);
  748. }
  749. /// Look for chain of insertvalue's that fully define an aggregate, and trace
  750. /// back the values inserted, see if they are all were extractvalue'd from
  751. /// the same source aggregate from the exact same element indexes.
  752. /// If they were, just reuse the source aggregate.
  753. /// This potentially deals with PHI indirections.
  754. Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
  755. InsertValueInst &OrigIVI) {
  756. Type *AggTy = OrigIVI.getType();
  757. unsigned NumAggElts;
  758. switch (AggTy->getTypeID()) {
  759. case Type::StructTyID:
  760. NumAggElts = AggTy->getStructNumElements();
  761. break;
  762. case Type::ArrayTyID:
  763. NumAggElts = AggTy->getArrayNumElements();
  764. break;
  765. default:
  766. llvm_unreachable("Unhandled aggregate type?");
  767. }
  768. // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
  769. // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
  770. // FIXME: any interesting patterns to be caught with larger limit?
  771. assert(NumAggElts > 0 && "Aggregate should have elements.");
  772. if (NumAggElts > 2)
  773. return nullptr;
  774. static constexpr auto NotFound = std::nullopt;
  775. static constexpr auto FoundMismatch = nullptr;
  776. // Try to find a value of each element of an aggregate.
  777. // FIXME: deal with more complex, not one-dimensional, aggregate types
  778. SmallVector<std::optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
  779. // Do we know values for each element of the aggregate?
  780. auto KnowAllElts = [&AggElts]() {
  781. return !llvm::is_contained(AggElts, NotFound);
  782. };
  783. int Depth = 0;
  784. // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
  785. // every element being overwritten twice, which should never happen.
  786. static const int DepthLimit = 2 * NumAggElts;
  787. // Recurse up the chain of `insertvalue` aggregate operands until either we've
  788. // reconstructed full initializer or can't visit any more `insertvalue`'s.
  789. for (InsertValueInst *CurrIVI = &OrigIVI;
  790. Depth < DepthLimit && CurrIVI && !KnowAllElts();
  791. CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
  792. ++Depth) {
  793. auto *InsertedValue =
  794. dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
  795. if (!InsertedValue)
  796. return nullptr; // Inserted value must be produced by an instruction.
  797. ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
  798. // Don't bother with more than single-level aggregates.
  799. if (Indices.size() != 1)
  800. return nullptr; // FIXME: deal with more complex aggregates?
  801. // Now, we may have already previously recorded the value for this element
  802. // of an aggregate. If we did, that means the CurrIVI will later be
  803. // overwritten with the already-recorded value. But if not, let's record it!
  804. std::optional<Instruction *> &Elt = AggElts[Indices.front()];
  805. Elt = Elt.value_or(InsertedValue);
  806. // FIXME: should we handle chain-terminating undef base operand?
  807. }
  808. // Was that sufficient to deduce the full initializer for the aggregate?
  809. if (!KnowAllElts())
  810. return nullptr; // Give up then.
  811. // We now want to find the source[s] of the aggregate elements we've found.
  812. // And with "source" we mean the original aggregate[s] from which
  813. // the inserted elements were extracted. This may require PHI translation.
  814. enum class AggregateDescription {
  815. /// When analyzing the value that was inserted into an aggregate, we did
  816. /// not manage to find defining `extractvalue` instruction to analyze.
  817. NotFound,
  818. /// When analyzing the value that was inserted into an aggregate, we did
  819. /// manage to find defining `extractvalue` instruction[s], and everything
  820. /// matched perfectly - aggregate type, element insertion/extraction index.
  821. Found,
  822. /// When analyzing the value that was inserted into an aggregate, we did
  823. /// manage to find defining `extractvalue` instruction, but there was
  824. /// a mismatch: either the source type from which the extraction was didn't
  825. /// match the aggregate type into which the insertion was,
  826. /// or the extraction/insertion channels mismatched,
  827. /// or different elements had different source aggregates.
  828. FoundMismatch
  829. };
  830. auto Describe = [](std::optional<Value *> SourceAggregate) {
  831. if (SourceAggregate == NotFound)
  832. return AggregateDescription::NotFound;
  833. if (*SourceAggregate == FoundMismatch)
  834. return AggregateDescription::FoundMismatch;
  835. return AggregateDescription::Found;
  836. };
  837. // Given the value \p Elt that was being inserted into element \p EltIdx of an
  838. // aggregate AggTy, see if \p Elt was originally defined by an
  839. // appropriate extractvalue (same element index, same aggregate type).
  840. // If found, return the source aggregate from which the extraction was.
  841. // If \p PredBB is provided, does PHI translation of an \p Elt first.
  842. auto FindSourceAggregate =
  843. [&](Instruction *Elt, unsigned EltIdx, std::optional<BasicBlock *> UseBB,
  844. std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
  845. // For now(?), only deal with, at most, a single level of PHI indirection.
  846. if (UseBB && PredBB)
  847. Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
  848. // FIXME: deal with multiple levels of PHI indirection?
  849. // Did we find an extraction?
  850. auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
  851. if (!EVI)
  852. return NotFound;
  853. Value *SourceAggregate = EVI->getAggregateOperand();
  854. // Is the extraction from the same type into which the insertion was?
  855. if (SourceAggregate->getType() != AggTy)
  856. return FoundMismatch;
  857. // And the element index doesn't change between extraction and insertion?
  858. if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
  859. return FoundMismatch;
  860. return SourceAggregate; // AggregateDescription::Found
  861. };
  862. // Given elements AggElts that were constructing an aggregate OrigIVI,
  863. // see if we can find appropriate source aggregate for each of the elements,
  864. // and see it's the same aggregate for each element. If so, return it.
  865. auto FindCommonSourceAggregate =
  866. [&](std::optional<BasicBlock *> UseBB,
  867. std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
  868. std::optional<Value *> SourceAggregate;
  869. for (auto I : enumerate(AggElts)) {
  870. assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
  871. "We don't store nullptr in SourceAggregate!");
  872. assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
  873. (I.index() != 0) &&
  874. "SourceAggregate should be valid after the first element,");
  875. // For this element, is there a plausible source aggregate?
  876. // FIXME: we could special-case undef element, IFF we know that in the
  877. // source aggregate said element isn't poison.
  878. std::optional<Value *> SourceAggregateForElement =
  879. FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
  880. // Okay, what have we found? Does that correlate with previous findings?
  881. // Regardless of whether or not we have previously found source
  882. // aggregate for previous elements (if any), if we didn't find one for
  883. // this element, passthrough whatever we have just found.
  884. if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
  885. return SourceAggregateForElement;
  886. // Okay, we have found source aggregate for this element.
  887. // Let's see what we already know from previous elements, if any.
  888. switch (Describe(SourceAggregate)) {
  889. case AggregateDescription::NotFound:
  890. // This is apparently the first element that we have examined.
  891. SourceAggregate = SourceAggregateForElement; // Record the aggregate!
  892. continue; // Great, now look at next element.
  893. case AggregateDescription::Found:
  894. // We have previously already successfully examined other elements.
  895. // Is this the same source aggregate we've found for other elements?
  896. if (*SourceAggregateForElement != *SourceAggregate)
  897. return FoundMismatch;
  898. continue; // Still the same aggregate, look at next element.
  899. case AggregateDescription::FoundMismatch:
  900. llvm_unreachable("Can't happen. We would have early-exited then.");
  901. };
  902. }
  903. assert(Describe(SourceAggregate) == AggregateDescription::Found &&
  904. "Must be a valid Value");
  905. return *SourceAggregate;
  906. };
  907. std::optional<Value *> SourceAggregate;
  908. // Can we find the source aggregate without looking at predecessors?
  909. SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/std::nullopt,
  910. /*PredBB=*/std::nullopt);
  911. if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
  912. if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
  913. return nullptr; // Conflicting source aggregates!
  914. ++NumAggregateReconstructionsSimplified;
  915. return replaceInstUsesWith(OrigIVI, *SourceAggregate);
  916. }
  917. // Okay, apparently we need to look at predecessors.
  918. // We should be smart about picking the "use" basic block, which will be the
  919. // merge point for aggregate, where we'll insert the final PHI that will be
  920. // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
  921. // We should look in which blocks each of the AggElts is being defined,
  922. // they all should be defined in the same basic block.
  923. BasicBlock *UseBB = nullptr;
  924. for (const std::optional<Instruction *> &I : AggElts) {
  925. BasicBlock *BB = (*I)->getParent();
  926. // If it's the first instruction we've encountered, record the basic block.
  927. if (!UseBB) {
  928. UseBB = BB;
  929. continue;
  930. }
  931. // Otherwise, this must be the same basic block we've seen previously.
  932. if (UseBB != BB)
  933. return nullptr;
  934. }
  935. // If *all* of the elements are basic-block-independent, meaning they are
  936. // either function arguments, or constant expressions, then if we didn't
  937. // handle them without predecessor-aware handling, we won't handle them now.
  938. if (!UseBB)
  939. return nullptr;
  940. // If we didn't manage to find source aggregate without looking at
  941. // predecessors, and there are no predecessors to look at, then we're done.
  942. if (pred_empty(UseBB))
  943. return nullptr;
  944. // Arbitrary predecessor count limit.
  945. static const int PredCountLimit = 64;
  946. // Cache the (non-uniqified!) list of predecessors in a vector,
  947. // checking the limit at the same time for efficiency.
  948. SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
  949. for (BasicBlock *Pred : predecessors(UseBB)) {
  950. // Don't bother if there are too many predecessors.
  951. if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
  952. return nullptr;
  953. Preds.emplace_back(Pred);
  954. }
  955. // For each predecessor, what is the source aggregate,
  956. // from which all the elements were originally extracted from?
  957. // Note that we want for the map to have stable iteration order!
  958. SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
  959. for (BasicBlock *Pred : Preds) {
  960. std::pair<decltype(SourceAggregates)::iterator, bool> IV =
  961. SourceAggregates.insert({Pred, nullptr});
  962. // Did we already evaluate this predecessor?
  963. if (!IV.second)
  964. continue;
  965. // Let's hope that when coming from predecessor Pred, all elements of the
  966. // aggregate produced by OrigIVI must have been originally extracted from
  967. // the same aggregate. Is that so? Can we find said original aggregate?
  968. SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
  969. if (Describe(SourceAggregate) != AggregateDescription::Found)
  970. return nullptr; // Give up.
  971. IV.first->second = *SourceAggregate;
  972. }
  973. // All good! Now we just need to thread the source aggregates here.
  974. // Note that we have to insert the new PHI here, ourselves, because we can't
  975. // rely on InstCombinerImpl::run() inserting it into the right basic block.
  976. // Note that the same block can be a predecessor more than once,
  977. // and we need to preserve that invariant for the PHI node.
  978. BuilderTy::InsertPointGuard Guard(Builder);
  979. Builder.SetInsertPoint(UseBB->getFirstNonPHI());
  980. auto *PHI =
  981. Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
  982. for (BasicBlock *Pred : Preds)
  983. PHI->addIncoming(SourceAggregates[Pred], Pred);
  984. ++NumAggregateReconstructionsSimplified;
  985. return replaceInstUsesWith(OrigIVI, PHI);
  986. }
  987. /// Try to find redundant insertvalue instructions, like the following ones:
  988. /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
  989. /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
  990. /// Here the second instruction inserts values at the same indices, as the
  991. /// first one, making the first one redundant.
  992. /// It should be transformed to:
  993. /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
  994. Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
  995. bool IsRedundant = false;
  996. ArrayRef<unsigned int> FirstIndices = I.getIndices();
  997. // If there is a chain of insertvalue instructions (each of them except the
  998. // last one has only one use and it's another insertvalue insn from this
  999. // chain), check if any of the 'children' uses the same indices as the first
  1000. // instruction. In this case, the first one is redundant.
  1001. Value *V = &I;
  1002. unsigned Depth = 0;
  1003. while (V->hasOneUse() && Depth < 10) {
  1004. User *U = V->user_back();
  1005. auto UserInsInst = dyn_cast<InsertValueInst>(U);
  1006. if (!UserInsInst || U->getOperand(0) != V)
  1007. break;
  1008. if (UserInsInst->getIndices() == FirstIndices) {
  1009. IsRedundant = true;
  1010. break;
  1011. }
  1012. V = UserInsInst;
  1013. Depth++;
  1014. }
  1015. if (IsRedundant)
  1016. return replaceInstUsesWith(I, I.getOperand(0));
  1017. if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
  1018. return NewI;
  1019. return nullptr;
  1020. }
  1021. static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
  1022. // Can not analyze scalable type, the number of elements is not a compile-time
  1023. // constant.
  1024. if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
  1025. return false;
  1026. int MaskSize = Shuf.getShuffleMask().size();
  1027. int VecSize =
  1028. cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
  1029. // A vector select does not change the size of the operands.
  1030. if (MaskSize != VecSize)
  1031. return false;
  1032. // Each mask element must be undefined or choose a vector element from one of
  1033. // the source operands without crossing vector lanes.
  1034. for (int i = 0; i != MaskSize; ++i) {
  1035. int Elt = Shuf.getMaskValue(i);
  1036. if (Elt != -1 && Elt != i && Elt != i + VecSize)
  1037. return false;
  1038. }
  1039. return true;
  1040. }
  1041. /// Turn a chain of inserts that splats a value into an insert + shuffle:
  1042. /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
  1043. /// shufflevector(insertelt(X, %k, 0), poison, zero)
  1044. static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
  1045. // We are interested in the last insert in a chain. So if this insert has a
  1046. // single user and that user is an insert, bail.
  1047. if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
  1048. return nullptr;
  1049. VectorType *VecTy = InsElt.getType();
  1050. // Can not handle scalable type, the number of elements is not a compile-time
  1051. // constant.
  1052. if (isa<ScalableVectorType>(VecTy))
  1053. return nullptr;
  1054. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  1055. // Do not try to do this for a one-element vector, since that's a nop,
  1056. // and will cause an inf-loop.
  1057. if (NumElements == 1)
  1058. return nullptr;
  1059. Value *SplatVal = InsElt.getOperand(1);
  1060. InsertElementInst *CurrIE = &InsElt;
  1061. SmallBitVector ElementPresent(NumElements, false);
  1062. InsertElementInst *FirstIE = nullptr;
  1063. // Walk the chain backwards, keeping track of which indices we inserted into,
  1064. // until we hit something that isn't an insert of the splatted value.
  1065. while (CurrIE) {
  1066. auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
  1067. if (!Idx || CurrIE->getOperand(1) != SplatVal)
  1068. return nullptr;
  1069. auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
  1070. // Check none of the intermediate steps have any additional uses, except
  1071. // for the root insertelement instruction, which can be re-used, if it
  1072. // inserts at position 0.
  1073. if (CurrIE != &InsElt &&
  1074. (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
  1075. return nullptr;
  1076. ElementPresent[Idx->getZExtValue()] = true;
  1077. FirstIE = CurrIE;
  1078. CurrIE = NextIE;
  1079. }
  1080. // If this is just a single insertelement (not a sequence), we are done.
  1081. if (FirstIE == &InsElt)
  1082. return nullptr;
  1083. // If we are not inserting into an undef vector, make sure we've seen an
  1084. // insert into every element.
  1085. // TODO: If the base vector is not undef, it might be better to create a splat
  1086. // and then a select-shuffle (blend) with the base vector.
  1087. if (!match(FirstIE->getOperand(0), m_Undef()))
  1088. if (!ElementPresent.all())
  1089. return nullptr;
  1090. // Create the insert + shuffle.
  1091. Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
  1092. PoisonValue *PoisonVec = PoisonValue::get(VecTy);
  1093. Constant *Zero = ConstantInt::get(Int32Ty, 0);
  1094. if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
  1095. FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
  1096. // Splat from element 0, but replace absent elements with undef in the mask.
  1097. SmallVector<int, 16> Mask(NumElements, 0);
  1098. for (unsigned i = 0; i != NumElements; ++i)
  1099. if (!ElementPresent[i])
  1100. Mask[i] = -1;
  1101. return new ShuffleVectorInst(FirstIE, Mask);
  1102. }
  1103. /// Try to fold an insert element into an existing splat shuffle by changing
  1104. /// the shuffle's mask to include the index of this insert element.
  1105. static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
  1106. // Check if the vector operand of this insert is a canonical splat shuffle.
  1107. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
  1108. if (!Shuf || !Shuf->isZeroEltSplat())
  1109. return nullptr;
  1110. // Bail out early if shuffle is scalable type. The number of elements in
  1111. // shuffle mask is unknown at compile-time.
  1112. if (isa<ScalableVectorType>(Shuf->getType()))
  1113. return nullptr;
  1114. // Check for a constant insertion index.
  1115. uint64_t IdxC;
  1116. if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
  1117. return nullptr;
  1118. // Check if the splat shuffle's input is the same as this insert's scalar op.
  1119. Value *X = InsElt.getOperand(1);
  1120. Value *Op0 = Shuf->getOperand(0);
  1121. if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
  1122. return nullptr;
  1123. // Replace the shuffle mask element at the index of this insert with a zero.
  1124. // For example:
  1125. // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
  1126. // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
  1127. unsigned NumMaskElts =
  1128. cast<FixedVectorType>(Shuf->getType())->getNumElements();
  1129. SmallVector<int, 16> NewMask(NumMaskElts);
  1130. for (unsigned i = 0; i != NumMaskElts; ++i)
  1131. NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
  1132. return new ShuffleVectorInst(Op0, NewMask);
  1133. }
  1134. /// Try to fold an extract+insert element into an existing identity shuffle by
  1135. /// changing the shuffle's mask to include the index of this insert element.
  1136. static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
  1137. // Check if the vector operand of this insert is an identity shuffle.
  1138. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
  1139. if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
  1140. !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
  1141. return nullptr;
  1142. // Bail out early if shuffle is scalable type. The number of elements in
  1143. // shuffle mask is unknown at compile-time.
  1144. if (isa<ScalableVectorType>(Shuf->getType()))
  1145. return nullptr;
  1146. // Check for a constant insertion index.
  1147. uint64_t IdxC;
  1148. if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
  1149. return nullptr;
  1150. // Check if this insert's scalar op is extracted from the identity shuffle's
  1151. // input vector.
  1152. Value *Scalar = InsElt.getOperand(1);
  1153. Value *X = Shuf->getOperand(0);
  1154. if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
  1155. return nullptr;
  1156. // Replace the shuffle mask element at the index of this extract+insert with
  1157. // that same index value.
  1158. // For example:
  1159. // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
  1160. unsigned NumMaskElts =
  1161. cast<FixedVectorType>(Shuf->getType())->getNumElements();
  1162. SmallVector<int, 16> NewMask(NumMaskElts);
  1163. ArrayRef<int> OldMask = Shuf->getShuffleMask();
  1164. for (unsigned i = 0; i != NumMaskElts; ++i) {
  1165. if (i != IdxC) {
  1166. // All mask elements besides the inserted element remain the same.
  1167. NewMask[i] = OldMask[i];
  1168. } else if (OldMask[i] == (int)IdxC) {
  1169. // If the mask element was already set, there's nothing to do
  1170. // (demanded elements analysis may unset it later).
  1171. return nullptr;
  1172. } else {
  1173. assert(OldMask[i] == UndefMaskElem &&
  1174. "Unexpected shuffle mask element for identity shuffle");
  1175. NewMask[i] = IdxC;
  1176. }
  1177. }
  1178. return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
  1179. }
  1180. /// If we have an insertelement instruction feeding into another insertelement
  1181. /// and the 2nd is inserting a constant into the vector, canonicalize that
  1182. /// constant insertion before the insertion of a variable:
  1183. ///
  1184. /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
  1185. /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
  1186. ///
  1187. /// This has the potential of eliminating the 2nd insertelement instruction
  1188. /// via constant folding of the scalar constant into a vector constant.
  1189. static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
  1190. InstCombiner::BuilderTy &Builder) {
  1191. auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
  1192. if (!InsElt1 || !InsElt1->hasOneUse())
  1193. return nullptr;
  1194. Value *X, *Y;
  1195. Constant *ScalarC;
  1196. ConstantInt *IdxC1, *IdxC2;
  1197. if (match(InsElt1->getOperand(0), m_Value(X)) &&
  1198. match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
  1199. match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
  1200. match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
  1201. match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
  1202. Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
  1203. return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
  1204. }
  1205. return nullptr;
  1206. }
  1207. /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
  1208. /// --> shufflevector X, CVec', Mask'
  1209. static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
  1210. auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
  1211. // Bail out if the parent has more than one use. In that case, we'd be
  1212. // replacing the insertelt with a shuffle, and that's not a clear win.
  1213. if (!Inst || !Inst->hasOneUse())
  1214. return nullptr;
  1215. if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
  1216. // The shuffle must have a constant vector operand. The insertelt must have
  1217. // a constant scalar being inserted at a constant position in the vector.
  1218. Constant *ShufConstVec, *InsEltScalar;
  1219. uint64_t InsEltIndex;
  1220. if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
  1221. !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
  1222. !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
  1223. return nullptr;
  1224. // Adding an element to an arbitrary shuffle could be expensive, but a
  1225. // shuffle that selects elements from vectors without crossing lanes is
  1226. // assumed cheap.
  1227. // If we're just adding a constant into that shuffle, it will still be
  1228. // cheap.
  1229. if (!isShuffleEquivalentToSelect(*Shuf))
  1230. return nullptr;
  1231. // From the above 'select' check, we know that the mask has the same number
  1232. // of elements as the vector input operands. We also know that each constant
  1233. // input element is used in its lane and can not be used more than once by
  1234. // the shuffle. Therefore, replace the constant in the shuffle's constant
  1235. // vector with the insertelt constant. Replace the constant in the shuffle's
  1236. // mask vector with the insertelt index plus the length of the vector
  1237. // (because the constant vector operand of a shuffle is always the 2nd
  1238. // operand).
  1239. ArrayRef<int> Mask = Shuf->getShuffleMask();
  1240. unsigned NumElts = Mask.size();
  1241. SmallVector<Constant *, 16> NewShufElts(NumElts);
  1242. SmallVector<int, 16> NewMaskElts(NumElts);
  1243. for (unsigned I = 0; I != NumElts; ++I) {
  1244. if (I == InsEltIndex) {
  1245. NewShufElts[I] = InsEltScalar;
  1246. NewMaskElts[I] = InsEltIndex + NumElts;
  1247. } else {
  1248. // Copy over the existing values.
  1249. NewShufElts[I] = ShufConstVec->getAggregateElement(I);
  1250. NewMaskElts[I] = Mask[I];
  1251. }
  1252. // Bail if we failed to find an element.
  1253. if (!NewShufElts[I])
  1254. return nullptr;
  1255. }
  1256. // Create new operands for a shuffle that includes the constant of the
  1257. // original insertelt. The old shuffle will be dead now.
  1258. return new ShuffleVectorInst(Shuf->getOperand(0),
  1259. ConstantVector::get(NewShufElts), NewMaskElts);
  1260. } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
  1261. // Transform sequences of insertelements ops with constant data/indexes into
  1262. // a single shuffle op.
  1263. // Can not handle scalable type, the number of elements needed to create
  1264. // shuffle mask is not a compile-time constant.
  1265. if (isa<ScalableVectorType>(InsElt.getType()))
  1266. return nullptr;
  1267. unsigned NumElts =
  1268. cast<FixedVectorType>(InsElt.getType())->getNumElements();
  1269. uint64_t InsertIdx[2];
  1270. Constant *Val[2];
  1271. if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
  1272. !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
  1273. !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
  1274. !match(IEI->getOperand(1), m_Constant(Val[1])))
  1275. return nullptr;
  1276. SmallVector<Constant *, 16> Values(NumElts);
  1277. SmallVector<int, 16> Mask(NumElts);
  1278. auto ValI = std::begin(Val);
  1279. // Generate new constant vector and mask.
  1280. // We have 2 values/masks from the insertelements instructions. Insert them
  1281. // into new value/mask vectors.
  1282. for (uint64_t I : InsertIdx) {
  1283. if (!Values[I]) {
  1284. Values[I] = *ValI;
  1285. Mask[I] = NumElts + I;
  1286. }
  1287. ++ValI;
  1288. }
  1289. // Remaining values are filled with 'undef' values.
  1290. for (unsigned I = 0; I < NumElts; ++I) {
  1291. if (!Values[I]) {
  1292. Values[I] = UndefValue::get(InsElt.getType()->getElementType());
  1293. Mask[I] = I;
  1294. }
  1295. }
  1296. // Create new operands for a shuffle that includes the constant of the
  1297. // original insertelt.
  1298. return new ShuffleVectorInst(IEI->getOperand(0),
  1299. ConstantVector::get(Values), Mask);
  1300. }
  1301. return nullptr;
  1302. }
  1303. /// If both the base vector and the inserted element are extended from the same
  1304. /// type, do the insert element in the narrow source type followed by extend.
  1305. /// TODO: This can be extended to include other cast opcodes, but particularly
  1306. /// if we create a wider insertelement, make sure codegen is not harmed.
  1307. static Instruction *narrowInsElt(InsertElementInst &InsElt,
  1308. InstCombiner::BuilderTy &Builder) {
  1309. // We are creating a vector extend. If the original vector extend has another
  1310. // use, that would mean we end up with 2 vector extends, so avoid that.
  1311. // TODO: We could ease the use-clause to "if at least one op has one use"
  1312. // (assuming that the source types match - see next TODO comment).
  1313. Value *Vec = InsElt.getOperand(0);
  1314. if (!Vec->hasOneUse())
  1315. return nullptr;
  1316. Value *Scalar = InsElt.getOperand(1);
  1317. Value *X, *Y;
  1318. CastInst::CastOps CastOpcode;
  1319. if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
  1320. CastOpcode = Instruction::FPExt;
  1321. else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
  1322. CastOpcode = Instruction::SExt;
  1323. else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
  1324. CastOpcode = Instruction::ZExt;
  1325. else
  1326. return nullptr;
  1327. // TODO: We can allow mismatched types by creating an intermediate cast.
  1328. if (X->getType()->getScalarType() != Y->getType())
  1329. return nullptr;
  1330. // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
  1331. Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
  1332. return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
  1333. }
  1334. /// If we are inserting 2 halves of a value into adjacent elements of a vector,
  1335. /// try to convert to a single insert with appropriate bitcasts.
  1336. static Instruction *foldTruncInsEltPair(InsertElementInst &InsElt,
  1337. bool IsBigEndian,
  1338. InstCombiner::BuilderTy &Builder) {
  1339. Value *VecOp = InsElt.getOperand(0);
  1340. Value *ScalarOp = InsElt.getOperand(1);
  1341. Value *IndexOp = InsElt.getOperand(2);
  1342. // Pattern depends on endian because we expect lower index is inserted first.
  1343. // Big endian:
  1344. // inselt (inselt BaseVec, (trunc (lshr X, BW/2), Index0), (trunc X), Index1
  1345. // Little endian:
  1346. // inselt (inselt BaseVec, (trunc X), Index0), (trunc (lshr X, BW/2)), Index1
  1347. // Note: It is not safe to do this transform with an arbitrary base vector
  1348. // because the bitcast of that vector to fewer/larger elements could
  1349. // allow poison to spill into an element that was not poison before.
  1350. // TODO: Detect smaller fractions of the scalar.
  1351. // TODO: One-use checks are conservative.
  1352. auto *VTy = dyn_cast<FixedVectorType>(InsElt.getType());
  1353. Value *Scalar0, *BaseVec;
  1354. uint64_t Index0, Index1;
  1355. if (!VTy || (VTy->getNumElements() & 1) ||
  1356. !match(IndexOp, m_ConstantInt(Index1)) ||
  1357. !match(VecOp, m_InsertElt(m_Value(BaseVec), m_Value(Scalar0),
  1358. m_ConstantInt(Index0))) ||
  1359. !match(BaseVec, m_Undef()))
  1360. return nullptr;
  1361. // The first insert must be to the index one less than this one, and
  1362. // the first insert must be to an even index.
  1363. if (Index0 + 1 != Index1 || Index0 & 1)
  1364. return nullptr;
  1365. // For big endian, the high half of the value should be inserted first.
  1366. // For little endian, the low half of the value should be inserted first.
  1367. Value *X;
  1368. uint64_t ShAmt;
  1369. if (IsBigEndian) {
  1370. if (!match(ScalarOp, m_Trunc(m_Value(X))) ||
  1371. !match(Scalar0, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
  1372. return nullptr;
  1373. } else {
  1374. if (!match(Scalar0, m_Trunc(m_Value(X))) ||
  1375. !match(ScalarOp, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
  1376. return nullptr;
  1377. }
  1378. Type *SrcTy = X->getType();
  1379. unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
  1380. unsigned VecEltWidth = VTy->getScalarSizeInBits();
  1381. if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
  1382. return nullptr;
  1383. // Bitcast the base vector to a vector type with the source element type.
  1384. Type *CastTy = FixedVectorType::get(SrcTy, VTy->getNumElements() / 2);
  1385. Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
  1386. // Scale the insert index for a vector with half as many elements.
  1387. // bitcast (inselt (bitcast BaseVec), X, NewIndex)
  1388. uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
  1389. Value *NewInsert = Builder.CreateInsertElement(CastBaseVec, X, NewIndex);
  1390. return new BitCastInst(NewInsert, VTy);
  1391. }
  1392. Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
  1393. Value *VecOp = IE.getOperand(0);
  1394. Value *ScalarOp = IE.getOperand(1);
  1395. Value *IdxOp = IE.getOperand(2);
  1396. if (auto *V = simplifyInsertElementInst(
  1397. VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
  1398. return replaceInstUsesWith(IE, V);
  1399. // Canonicalize type of constant indices to i64 to simplify CSE
  1400. if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp)) {
  1401. if (auto *NewIdx = getPreferredVectorIndex(IndexC))
  1402. return replaceOperand(IE, 2, NewIdx);
  1403. Value *BaseVec, *OtherScalar;
  1404. uint64_t OtherIndexVal;
  1405. if (match(VecOp, m_OneUse(m_InsertElt(m_Value(BaseVec),
  1406. m_Value(OtherScalar),
  1407. m_ConstantInt(OtherIndexVal)))) &&
  1408. !isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
  1409. Value *NewIns = Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
  1410. return InsertElementInst::Create(NewIns, OtherScalar,
  1411. Builder.getInt64(OtherIndexVal));
  1412. }
  1413. }
  1414. // If the scalar is bitcast and inserted into undef, do the insert in the
  1415. // source type followed by bitcast.
  1416. // TODO: Generalize for insert into any constant, not just undef?
  1417. Value *ScalarSrc;
  1418. if (match(VecOp, m_Undef()) &&
  1419. match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
  1420. (ScalarSrc->getType()->isIntegerTy() ||
  1421. ScalarSrc->getType()->isFloatingPointTy())) {
  1422. // inselt undef, (bitcast ScalarSrc), IdxOp -->
  1423. // bitcast (inselt undef, ScalarSrc, IdxOp)
  1424. Type *ScalarTy = ScalarSrc->getType();
  1425. Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
  1426. UndefValue *NewUndef = UndefValue::get(VecTy);
  1427. Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
  1428. return new BitCastInst(NewInsElt, IE.getType());
  1429. }
  1430. // If the vector and scalar are both bitcast from the same element type, do
  1431. // the insert in that source type followed by bitcast.
  1432. Value *VecSrc;
  1433. if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
  1434. match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
  1435. (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
  1436. VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
  1437. cast<VectorType>(VecSrc->getType())->getElementType() ==
  1438. ScalarSrc->getType()) {
  1439. // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
  1440. // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
  1441. Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
  1442. return new BitCastInst(NewInsElt, IE.getType());
  1443. }
  1444. // If the inserted element was extracted from some other fixed-length vector
  1445. // and both indexes are valid constants, try to turn this into a shuffle.
  1446. // Can not handle scalable vector type, the number of elements needed to
  1447. // create shuffle mask is not a compile-time constant.
  1448. uint64_t InsertedIdx, ExtractedIdx;
  1449. Value *ExtVecOp;
  1450. if (isa<FixedVectorType>(IE.getType()) &&
  1451. match(IdxOp, m_ConstantInt(InsertedIdx)) &&
  1452. match(ScalarOp,
  1453. m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
  1454. isa<FixedVectorType>(ExtVecOp->getType()) &&
  1455. ExtractedIdx <
  1456. cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
  1457. // TODO: Looking at the user(s) to determine if this insert is a
  1458. // fold-to-shuffle opportunity does not match the usual instcombine
  1459. // constraints. We should decide if the transform is worthy based only
  1460. // on this instruction and its operands, but that may not work currently.
  1461. //
  1462. // Here, we are trying to avoid creating shuffles before reaching
  1463. // the end of a chain of extract-insert pairs. This is complicated because
  1464. // we do not generally form arbitrary shuffle masks in instcombine
  1465. // (because those may codegen poorly), but collectShuffleElements() does
  1466. // exactly that.
  1467. //
  1468. // The rules for determining what is an acceptable target-independent
  1469. // shuffle mask are fuzzy because they evolve based on the backend's
  1470. // capabilities and real-world impact.
  1471. auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
  1472. if (!Insert.hasOneUse())
  1473. return true;
  1474. auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
  1475. if (!InsertUser)
  1476. return true;
  1477. return false;
  1478. };
  1479. // Try to form a shuffle from a chain of extract-insert ops.
  1480. if (isShuffleRootCandidate(IE)) {
  1481. SmallVector<int, 16> Mask;
  1482. ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
  1483. // The proposed shuffle may be trivial, in which case we shouldn't
  1484. // perform the combine.
  1485. if (LR.first != &IE && LR.second != &IE) {
  1486. // We now have a shuffle of LHS, RHS, Mask.
  1487. if (LR.second == nullptr)
  1488. LR.second = UndefValue::get(LR.first->getType());
  1489. return new ShuffleVectorInst(LR.first, LR.second, Mask);
  1490. }
  1491. }
  1492. }
  1493. if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
  1494. unsigned VWidth = VecTy->getNumElements();
  1495. APInt UndefElts(VWidth, 0);
  1496. APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
  1497. if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
  1498. if (V != &IE)
  1499. return replaceInstUsesWith(IE, V);
  1500. return &IE;
  1501. }
  1502. }
  1503. if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
  1504. return Shuf;
  1505. if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
  1506. return NewInsElt;
  1507. if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
  1508. return Broadcast;
  1509. if (Instruction *Splat = foldInsEltIntoSplat(IE))
  1510. return Splat;
  1511. if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
  1512. return IdentityShuf;
  1513. if (Instruction *Ext = narrowInsElt(IE, Builder))
  1514. return Ext;
  1515. if (Instruction *Ext = foldTruncInsEltPair(IE, DL.isBigEndian(), Builder))
  1516. return Ext;
  1517. return nullptr;
  1518. }
  1519. /// Return true if we can evaluate the specified expression tree if the vector
  1520. /// elements were shuffled in a different order.
  1521. static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
  1522. unsigned Depth = 5) {
  1523. // We can always reorder the elements of a constant.
  1524. if (isa<Constant>(V))
  1525. return true;
  1526. // We won't reorder vector arguments. No IPO here.
  1527. Instruction *I = dyn_cast<Instruction>(V);
  1528. if (!I) return false;
  1529. // Two users may expect different orders of the elements. Don't try it.
  1530. if (!I->hasOneUse())
  1531. return false;
  1532. if (Depth == 0) return false;
  1533. switch (I->getOpcode()) {
  1534. case Instruction::UDiv:
  1535. case Instruction::SDiv:
  1536. case Instruction::URem:
  1537. case Instruction::SRem:
  1538. // Propagating an undefined shuffle mask element to integer div/rem is not
  1539. // allowed because those opcodes can create immediate undefined behavior
  1540. // from an undefined element in an operand.
  1541. if (llvm::is_contained(Mask, -1))
  1542. return false;
  1543. [[fallthrough]];
  1544. case Instruction::Add:
  1545. case Instruction::FAdd:
  1546. case Instruction::Sub:
  1547. case Instruction::FSub:
  1548. case Instruction::Mul:
  1549. case Instruction::FMul:
  1550. case Instruction::FDiv:
  1551. case Instruction::FRem:
  1552. case Instruction::Shl:
  1553. case Instruction::LShr:
  1554. case Instruction::AShr:
  1555. case Instruction::And:
  1556. case Instruction::Or:
  1557. case Instruction::Xor:
  1558. case Instruction::ICmp:
  1559. case Instruction::FCmp:
  1560. case Instruction::Trunc:
  1561. case Instruction::ZExt:
  1562. case Instruction::SExt:
  1563. case Instruction::FPToUI:
  1564. case Instruction::FPToSI:
  1565. case Instruction::UIToFP:
  1566. case Instruction::SIToFP:
  1567. case Instruction::FPTrunc:
  1568. case Instruction::FPExt:
  1569. case Instruction::GetElementPtr: {
  1570. // Bail out if we would create longer vector ops. We could allow creating
  1571. // longer vector ops, but that may result in more expensive codegen.
  1572. Type *ITy = I->getType();
  1573. if (ITy->isVectorTy() &&
  1574. Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
  1575. return false;
  1576. for (Value *Operand : I->operands()) {
  1577. if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
  1578. return false;
  1579. }
  1580. return true;
  1581. }
  1582. case Instruction::InsertElement: {
  1583. ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
  1584. if (!CI) return false;
  1585. int ElementNumber = CI->getLimitedValue();
  1586. // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
  1587. // can't put an element into multiple indices.
  1588. bool SeenOnce = false;
  1589. for (int I : Mask) {
  1590. if (I == ElementNumber) {
  1591. if (SeenOnce)
  1592. return false;
  1593. SeenOnce = true;
  1594. }
  1595. }
  1596. return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
  1597. }
  1598. }
  1599. return false;
  1600. }
  1601. /// Rebuild a new instruction just like 'I' but with the new operands given.
  1602. /// In the event of type mismatch, the type of the operands is correct.
  1603. static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
  1604. // We don't want to use the IRBuilder here because we want the replacement
  1605. // instructions to appear next to 'I', not the builder's insertion point.
  1606. switch (I->getOpcode()) {
  1607. case Instruction::Add:
  1608. case Instruction::FAdd:
  1609. case Instruction::Sub:
  1610. case Instruction::FSub:
  1611. case Instruction::Mul:
  1612. case Instruction::FMul:
  1613. case Instruction::UDiv:
  1614. case Instruction::SDiv:
  1615. case Instruction::FDiv:
  1616. case Instruction::URem:
  1617. case Instruction::SRem:
  1618. case Instruction::FRem:
  1619. case Instruction::Shl:
  1620. case Instruction::LShr:
  1621. case Instruction::AShr:
  1622. case Instruction::And:
  1623. case Instruction::Or:
  1624. case Instruction::Xor: {
  1625. BinaryOperator *BO = cast<BinaryOperator>(I);
  1626. assert(NewOps.size() == 2 && "binary operator with #ops != 2");
  1627. BinaryOperator *New =
  1628. BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
  1629. NewOps[0], NewOps[1], "", BO);
  1630. if (isa<OverflowingBinaryOperator>(BO)) {
  1631. New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
  1632. New->setHasNoSignedWrap(BO->hasNoSignedWrap());
  1633. }
  1634. if (isa<PossiblyExactOperator>(BO)) {
  1635. New->setIsExact(BO->isExact());
  1636. }
  1637. if (isa<FPMathOperator>(BO))
  1638. New->copyFastMathFlags(I);
  1639. return New;
  1640. }
  1641. case Instruction::ICmp:
  1642. assert(NewOps.size() == 2 && "icmp with #ops != 2");
  1643. return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
  1644. NewOps[0], NewOps[1]);
  1645. case Instruction::FCmp:
  1646. assert(NewOps.size() == 2 && "fcmp with #ops != 2");
  1647. return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
  1648. NewOps[0], NewOps[1]);
  1649. case Instruction::Trunc:
  1650. case Instruction::ZExt:
  1651. case Instruction::SExt:
  1652. case Instruction::FPToUI:
  1653. case Instruction::FPToSI:
  1654. case Instruction::UIToFP:
  1655. case Instruction::SIToFP:
  1656. case Instruction::FPTrunc:
  1657. case Instruction::FPExt: {
  1658. // It's possible that the mask has a different number of elements from
  1659. // the original cast. We recompute the destination type to match the mask.
  1660. Type *DestTy = VectorType::get(
  1661. I->getType()->getScalarType(),
  1662. cast<VectorType>(NewOps[0]->getType())->getElementCount());
  1663. assert(NewOps.size() == 1 && "cast with #ops != 1");
  1664. return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
  1665. "", I);
  1666. }
  1667. case Instruction::GetElementPtr: {
  1668. Value *Ptr = NewOps[0];
  1669. ArrayRef<Value*> Idx = NewOps.slice(1);
  1670. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  1671. cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
  1672. GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
  1673. return GEP;
  1674. }
  1675. }
  1676. llvm_unreachable("failed to rebuild vector instructions");
  1677. }
  1678. static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
  1679. // Mask.size() does not need to be equal to the number of vector elements.
  1680. assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
  1681. Type *EltTy = V->getType()->getScalarType();
  1682. Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
  1683. if (match(V, m_Undef()))
  1684. return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
  1685. if (isa<ConstantAggregateZero>(V))
  1686. return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
  1687. if (Constant *C = dyn_cast<Constant>(V))
  1688. return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
  1689. Mask);
  1690. Instruction *I = cast<Instruction>(V);
  1691. switch (I->getOpcode()) {
  1692. case Instruction::Add:
  1693. case Instruction::FAdd:
  1694. case Instruction::Sub:
  1695. case Instruction::FSub:
  1696. case Instruction::Mul:
  1697. case Instruction::FMul:
  1698. case Instruction::UDiv:
  1699. case Instruction::SDiv:
  1700. case Instruction::FDiv:
  1701. case Instruction::URem:
  1702. case Instruction::SRem:
  1703. case Instruction::FRem:
  1704. case Instruction::Shl:
  1705. case Instruction::LShr:
  1706. case Instruction::AShr:
  1707. case Instruction::And:
  1708. case Instruction::Or:
  1709. case Instruction::Xor:
  1710. case Instruction::ICmp:
  1711. case Instruction::FCmp:
  1712. case Instruction::Trunc:
  1713. case Instruction::ZExt:
  1714. case Instruction::SExt:
  1715. case Instruction::FPToUI:
  1716. case Instruction::FPToSI:
  1717. case Instruction::UIToFP:
  1718. case Instruction::SIToFP:
  1719. case Instruction::FPTrunc:
  1720. case Instruction::FPExt:
  1721. case Instruction::Select:
  1722. case Instruction::GetElementPtr: {
  1723. SmallVector<Value*, 8> NewOps;
  1724. bool NeedsRebuild =
  1725. (Mask.size() !=
  1726. cast<FixedVectorType>(I->getType())->getNumElements());
  1727. for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
  1728. Value *V;
  1729. // Recursively call evaluateInDifferentElementOrder on vector arguments
  1730. // as well. E.g. GetElementPtr may have scalar operands even if the
  1731. // return value is a vector, so we need to examine the operand type.
  1732. if (I->getOperand(i)->getType()->isVectorTy())
  1733. V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
  1734. else
  1735. V = I->getOperand(i);
  1736. NewOps.push_back(V);
  1737. NeedsRebuild |= (V != I->getOperand(i));
  1738. }
  1739. if (NeedsRebuild) {
  1740. return buildNew(I, NewOps);
  1741. }
  1742. return I;
  1743. }
  1744. case Instruction::InsertElement: {
  1745. int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
  1746. // The insertelement was inserting at Element. Figure out which element
  1747. // that becomes after shuffling. The answer is guaranteed to be unique
  1748. // by CanEvaluateShuffled.
  1749. bool Found = false;
  1750. int Index = 0;
  1751. for (int e = Mask.size(); Index != e; ++Index) {
  1752. if (Mask[Index] == Element) {
  1753. Found = true;
  1754. break;
  1755. }
  1756. }
  1757. // If element is not in Mask, no need to handle the operand 1 (element to
  1758. // be inserted). Just evaluate values in operand 0 according to Mask.
  1759. if (!Found)
  1760. return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
  1761. Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
  1762. return InsertElementInst::Create(V, I->getOperand(1),
  1763. ConstantInt::get(I32Ty, Index), "", I);
  1764. }
  1765. }
  1766. llvm_unreachable("failed to reorder elements of vector instruction!");
  1767. }
  1768. // Returns true if the shuffle is extracting a contiguous range of values from
  1769. // LHS, for example:
  1770. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  1771. // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
  1772. // Shuffles to: |EE|FF|GG|HH|
  1773. // +--+--+--+--+
  1774. static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
  1775. ArrayRef<int> Mask) {
  1776. unsigned LHSElems =
  1777. cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
  1778. unsigned MaskElems = Mask.size();
  1779. unsigned BegIdx = Mask.front();
  1780. unsigned EndIdx = Mask.back();
  1781. if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
  1782. return false;
  1783. for (unsigned I = 0; I != MaskElems; ++I)
  1784. if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
  1785. return false;
  1786. return true;
  1787. }
  1788. /// These are the ingredients in an alternate form binary operator as described
  1789. /// below.
  1790. struct BinopElts {
  1791. BinaryOperator::BinaryOps Opcode;
  1792. Value *Op0;
  1793. Value *Op1;
  1794. BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
  1795. Value *V0 = nullptr, Value *V1 = nullptr) :
  1796. Opcode(Opc), Op0(V0), Op1(V1) {}
  1797. operator bool() const { return Opcode != 0; }
  1798. };
  1799. /// Binops may be transformed into binops with different opcodes and operands.
  1800. /// Reverse the usual canonicalization to enable folds with the non-canonical
  1801. /// form of the binop. If a transform is possible, return the elements of the
  1802. /// new binop. If not, return invalid elements.
  1803. static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
  1804. Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
  1805. Type *Ty = BO->getType();
  1806. switch (BO->getOpcode()) {
  1807. case Instruction::Shl: {
  1808. // shl X, C --> mul X, (1 << C)
  1809. Constant *C;
  1810. if (match(BO1, m_Constant(C))) {
  1811. Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
  1812. return {Instruction::Mul, BO0, ShlOne};
  1813. }
  1814. break;
  1815. }
  1816. case Instruction::Or: {
  1817. // or X, C --> add X, C (when X and C have no common bits set)
  1818. const APInt *C;
  1819. if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
  1820. return {Instruction::Add, BO0, BO1};
  1821. break;
  1822. }
  1823. case Instruction::Sub:
  1824. // sub 0, X --> mul X, -1
  1825. if (match(BO0, m_ZeroInt()))
  1826. return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
  1827. break;
  1828. default:
  1829. break;
  1830. }
  1831. return {};
  1832. }
  1833. /// A select shuffle of a select shuffle with a shared operand can be reduced
  1834. /// to a single select shuffle. This is an obvious improvement in IR, and the
  1835. /// backend is expected to lower select shuffles efficiently.
  1836. static Instruction *foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf) {
  1837. assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
  1838. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1839. SmallVector<int, 16> Mask;
  1840. Shuf.getShuffleMask(Mask);
  1841. unsigned NumElts = Mask.size();
  1842. // Canonicalize a select shuffle with common operand as Op1.
  1843. auto *ShufOp = dyn_cast<ShuffleVectorInst>(Op0);
  1844. if (ShufOp && ShufOp->isSelect() &&
  1845. (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
  1846. std::swap(Op0, Op1);
  1847. ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
  1848. }
  1849. ShufOp = dyn_cast<ShuffleVectorInst>(Op1);
  1850. if (!ShufOp || !ShufOp->isSelect() ||
  1851. (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
  1852. return nullptr;
  1853. Value *X = ShufOp->getOperand(0), *Y = ShufOp->getOperand(1);
  1854. SmallVector<int, 16> Mask1;
  1855. ShufOp->getShuffleMask(Mask1);
  1856. assert(Mask1.size() == NumElts && "Vector size changed with select shuffle");
  1857. // Canonicalize common operand (Op0) as X (first operand of first shuffle).
  1858. if (Y == Op0) {
  1859. std::swap(X, Y);
  1860. ShuffleVectorInst::commuteShuffleMask(Mask1, NumElts);
  1861. }
  1862. // If the mask chooses from X (operand 0), it stays the same.
  1863. // If the mask chooses from the earlier shuffle, the other mask value is
  1864. // transferred to the combined select shuffle:
  1865. // shuf X, (shuf X, Y, M1), M --> shuf X, Y, M'
  1866. SmallVector<int, 16> NewMask(NumElts);
  1867. for (unsigned i = 0; i != NumElts; ++i)
  1868. NewMask[i] = Mask[i] < (signed)NumElts ? Mask[i] : Mask1[i];
  1869. // A select mask with undef elements might look like an identity mask.
  1870. assert((ShuffleVectorInst::isSelectMask(NewMask) ||
  1871. ShuffleVectorInst::isIdentityMask(NewMask)) &&
  1872. "Unexpected shuffle mask");
  1873. return new ShuffleVectorInst(X, Y, NewMask);
  1874. }
  1875. static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
  1876. assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
  1877. // Are we shuffling together some value and that same value after it has been
  1878. // modified by a binop with a constant?
  1879. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1880. Constant *C;
  1881. bool Op0IsBinop;
  1882. if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
  1883. Op0IsBinop = true;
  1884. else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
  1885. Op0IsBinop = false;
  1886. else
  1887. return nullptr;
  1888. // The identity constant for a binop leaves a variable operand unchanged. For
  1889. // a vector, this is a splat of something like 0, -1, or 1.
  1890. // If there's no identity constant for this binop, we're done.
  1891. auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
  1892. BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
  1893. Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
  1894. if (!IdC)
  1895. return nullptr;
  1896. // Shuffle identity constants into the lanes that return the original value.
  1897. // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
  1898. // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
  1899. // The existing binop constant vector remains in the same operand position.
  1900. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1901. Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
  1902. ConstantExpr::getShuffleVector(IdC, C, Mask);
  1903. bool MightCreatePoisonOrUB =
  1904. is_contained(Mask, UndefMaskElem) &&
  1905. (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
  1906. if (MightCreatePoisonOrUB)
  1907. NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
  1908. // shuf (bop X, C), X, M --> bop X, C'
  1909. // shuf X, (bop X, C), M --> bop X, C'
  1910. Value *X = Op0IsBinop ? Op1 : Op0;
  1911. Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
  1912. NewBO->copyIRFlags(BO);
  1913. // An undef shuffle mask element may propagate as an undef constant element in
  1914. // the new binop. That would produce poison where the original code might not.
  1915. // If we already made a safe constant, then there's no danger.
  1916. if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
  1917. NewBO->dropPoisonGeneratingFlags();
  1918. return NewBO;
  1919. }
  1920. /// If we have an insert of a scalar to a non-zero element of an undefined
  1921. /// vector and then shuffle that value, that's the same as inserting to the zero
  1922. /// element and shuffling. Splatting from the zero element is recognized as the
  1923. /// canonical form of splat.
  1924. static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
  1925. InstCombiner::BuilderTy &Builder) {
  1926. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1927. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1928. Value *X;
  1929. uint64_t IndexC;
  1930. // Match a shuffle that is a splat to a non-zero element.
  1931. if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
  1932. m_ConstantInt(IndexC)))) ||
  1933. !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
  1934. return nullptr;
  1935. // Insert into element 0 of an undef vector.
  1936. UndefValue *UndefVec = UndefValue::get(Shuf.getType());
  1937. Constant *Zero = Builder.getInt32(0);
  1938. Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
  1939. // Splat from element 0. Any mask element that is undefined remains undefined.
  1940. // For example:
  1941. // shuf (inselt undef, X, 2), _, <2,2,undef>
  1942. // --> shuf (inselt undef, X, 0), poison, <0,0,undef>
  1943. unsigned NumMaskElts =
  1944. cast<FixedVectorType>(Shuf.getType())->getNumElements();
  1945. SmallVector<int, 16> NewMask(NumMaskElts, 0);
  1946. for (unsigned i = 0; i != NumMaskElts; ++i)
  1947. if (Mask[i] == UndefMaskElem)
  1948. NewMask[i] = Mask[i];
  1949. return new ShuffleVectorInst(NewIns, NewMask);
  1950. }
  1951. /// Try to fold shuffles that are the equivalent of a vector select.
  1952. Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
  1953. if (!Shuf.isSelect())
  1954. return nullptr;
  1955. // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
  1956. // Commuting undef to operand 0 conflicts with another canonicalization.
  1957. unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
  1958. if (!match(Shuf.getOperand(1), m_Undef()) &&
  1959. Shuf.getMaskValue(0) >= (int)NumElts) {
  1960. // TODO: Can we assert that both operands of a shuffle-select are not undef
  1961. // (otherwise, it would have been folded by instsimplify?
  1962. Shuf.commute();
  1963. return &Shuf;
  1964. }
  1965. if (Instruction *I = foldSelectShuffleOfSelectShuffle(Shuf))
  1966. return I;
  1967. if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
  1968. return I;
  1969. BinaryOperator *B0, *B1;
  1970. if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
  1971. !match(Shuf.getOperand(1), m_BinOp(B1)))
  1972. return nullptr;
  1973. // If one operand is "0 - X", allow that to be viewed as "X * -1"
  1974. // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
  1975. // with a multiply, we will exit because C0/C1 will not be set.
  1976. Value *X, *Y;
  1977. Constant *C0 = nullptr, *C1 = nullptr;
  1978. bool ConstantsAreOp1;
  1979. if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
  1980. match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
  1981. ConstantsAreOp1 = false;
  1982. else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
  1983. m_Neg(m_Value(X)))) &&
  1984. match(B1, m_CombineOr(m_BinOp(m_Value(Y), m_Constant(C1)),
  1985. m_Neg(m_Value(Y)))))
  1986. ConstantsAreOp1 = true;
  1987. else
  1988. return nullptr;
  1989. // We need matching binops to fold the lanes together.
  1990. BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
  1991. BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
  1992. bool DropNSW = false;
  1993. if (ConstantsAreOp1 && Opc0 != Opc1) {
  1994. // TODO: We drop "nsw" if shift is converted into multiply because it may
  1995. // not be correct when the shift amount is BitWidth - 1. We could examine
  1996. // each vector element to determine if it is safe to keep that flag.
  1997. if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
  1998. DropNSW = true;
  1999. if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
  2000. assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
  2001. Opc0 = AltB0.Opcode;
  2002. C0 = cast<Constant>(AltB0.Op1);
  2003. } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
  2004. assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
  2005. Opc1 = AltB1.Opcode;
  2006. C1 = cast<Constant>(AltB1.Op1);
  2007. }
  2008. }
  2009. if (Opc0 != Opc1 || !C0 || !C1)
  2010. return nullptr;
  2011. // The opcodes must be the same. Use a new name to make that clear.
  2012. BinaryOperator::BinaryOps BOpc = Opc0;
  2013. // Select the constant elements needed for the single binop.
  2014. ArrayRef<int> Mask = Shuf.getShuffleMask();
  2015. Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
  2016. // We are moving a binop after a shuffle. When a shuffle has an undefined
  2017. // mask element, the result is undefined, but it is not poison or undefined
  2018. // behavior. That is not necessarily true for div/rem/shift.
  2019. bool MightCreatePoisonOrUB =
  2020. is_contained(Mask, UndefMaskElem) &&
  2021. (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
  2022. if (MightCreatePoisonOrUB)
  2023. NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
  2024. ConstantsAreOp1);
  2025. Value *V;
  2026. if (X == Y) {
  2027. // Remove a binop and the shuffle by rearranging the constant:
  2028. // shuffle (op V, C0), (op V, C1), M --> op V, C'
  2029. // shuffle (op C0, V), (op C1, V), M --> op C', V
  2030. V = X;
  2031. } else {
  2032. // If there are 2 different variable operands, we must create a new shuffle
  2033. // (select) first, so check uses to ensure that we don't end up with more
  2034. // instructions than we started with.
  2035. if (!B0->hasOneUse() && !B1->hasOneUse())
  2036. return nullptr;
  2037. // If we use the original shuffle mask and op1 is *variable*, we would be
  2038. // putting an undef into operand 1 of div/rem/shift. This is either UB or
  2039. // poison. We do not have to guard against UB when *constants* are op1
  2040. // because safe constants guarantee that we do not overflow sdiv/srem (and
  2041. // there's no danger for other opcodes).
  2042. // TODO: To allow this case, create a new shuffle mask with no undefs.
  2043. if (MightCreatePoisonOrUB && !ConstantsAreOp1)
  2044. return nullptr;
  2045. // Note: In general, we do not create new shuffles in InstCombine because we
  2046. // do not know if a target can lower an arbitrary shuffle optimally. In this
  2047. // case, the shuffle uses the existing mask, so there is no additional risk.
  2048. // Select the variable vectors first, then perform the binop:
  2049. // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
  2050. // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
  2051. V = Builder.CreateShuffleVector(X, Y, Mask);
  2052. }
  2053. Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
  2054. Builder.CreateBinOp(BOpc, NewC, V);
  2055. // Flags are intersected from the 2 source binops. But there are 2 exceptions:
  2056. // 1. If we changed an opcode, poison conditions might have changed.
  2057. // 2. If the shuffle had undef mask elements, the new binop might have undefs
  2058. // where the original code did not. But if we already made a safe constant,
  2059. // then there's no danger.
  2060. if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
  2061. NewI->copyIRFlags(B0);
  2062. NewI->andIRFlags(B1);
  2063. if (DropNSW)
  2064. NewI->setHasNoSignedWrap(false);
  2065. if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
  2066. NewI->dropPoisonGeneratingFlags();
  2067. }
  2068. return replaceInstUsesWith(Shuf, NewBO);
  2069. }
  2070. /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
  2071. /// Example (little endian):
  2072. /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
  2073. static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
  2074. bool IsBigEndian) {
  2075. // This must be a bitcasted shuffle of 1 vector integer operand.
  2076. Type *DestType = Shuf.getType();
  2077. Value *X;
  2078. if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
  2079. !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
  2080. return nullptr;
  2081. // The source type must have the same number of elements as the shuffle,
  2082. // and the source element type must be larger than the shuffle element type.
  2083. Type *SrcType = X->getType();
  2084. if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
  2085. cast<FixedVectorType>(SrcType)->getNumElements() !=
  2086. cast<FixedVectorType>(DestType)->getNumElements() ||
  2087. SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
  2088. return nullptr;
  2089. assert(Shuf.changesLength() && !Shuf.increasesLength() &&
  2090. "Expected a shuffle that decreases length");
  2091. // Last, check that the mask chooses the correct low bits for each narrow
  2092. // element in the result.
  2093. uint64_t TruncRatio =
  2094. SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
  2095. ArrayRef<int> Mask = Shuf.getShuffleMask();
  2096. for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
  2097. if (Mask[i] == UndefMaskElem)
  2098. continue;
  2099. uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
  2100. assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
  2101. if (Mask[i] != (int)LSBIndex)
  2102. return nullptr;
  2103. }
  2104. return new TruncInst(X, DestType);
  2105. }
  2106. /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
  2107. /// narrowing (concatenating with undef and extracting back to the original
  2108. /// length). This allows replacing the wide select with a narrow select.
  2109. static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
  2110. InstCombiner::BuilderTy &Builder) {
  2111. // This must be a narrowing identity shuffle. It extracts the 1st N elements
  2112. // of the 1st vector operand of a shuffle.
  2113. if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
  2114. return nullptr;
  2115. // The vector being shuffled must be a vector select that we can eliminate.
  2116. // TODO: The one-use requirement could be eased if X and/or Y are constants.
  2117. Value *Cond, *X, *Y;
  2118. if (!match(Shuf.getOperand(0),
  2119. m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
  2120. return nullptr;
  2121. // We need a narrow condition value. It must be extended with undef elements
  2122. // and have the same number of elements as this shuffle.
  2123. unsigned NarrowNumElts =
  2124. cast<FixedVectorType>(Shuf.getType())->getNumElements();
  2125. Value *NarrowCond;
  2126. if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
  2127. cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
  2128. NarrowNumElts ||
  2129. !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
  2130. return nullptr;
  2131. // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
  2132. // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
  2133. Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
  2134. Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
  2135. return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
  2136. }
  2137. /// Canonicalize FP negate after shuffle.
  2138. static Instruction *foldFNegShuffle(ShuffleVectorInst &Shuf,
  2139. InstCombiner::BuilderTy &Builder) {
  2140. Instruction *FNeg0;
  2141. Value *X;
  2142. if (!match(Shuf.getOperand(0), m_CombineAnd(m_Instruction(FNeg0),
  2143. m_FNeg(m_Value(X)))))
  2144. return nullptr;
  2145. // shuffle (fneg X), Mask --> fneg (shuffle X, Mask)
  2146. if (FNeg0->hasOneUse() && match(Shuf.getOperand(1), m_Undef())) {
  2147. Value *NewShuf = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
  2148. return UnaryOperator::CreateFNegFMF(NewShuf, FNeg0);
  2149. }
  2150. Instruction *FNeg1;
  2151. Value *Y;
  2152. if (!match(Shuf.getOperand(1), m_CombineAnd(m_Instruction(FNeg1),
  2153. m_FNeg(m_Value(Y)))))
  2154. return nullptr;
  2155. // shuffle (fneg X), (fneg Y), Mask --> fneg (shuffle X, Y, Mask)
  2156. if (FNeg0->hasOneUse() || FNeg1->hasOneUse()) {
  2157. Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
  2158. Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewShuf);
  2159. NewFNeg->copyIRFlags(FNeg0);
  2160. NewFNeg->andIRFlags(FNeg1);
  2161. return NewFNeg;
  2162. }
  2163. return nullptr;
  2164. }
  2165. /// Canonicalize casts after shuffle.
  2166. static Instruction *foldCastShuffle(ShuffleVectorInst &Shuf,
  2167. InstCombiner::BuilderTy &Builder) {
  2168. // Do we have 2 matching cast operands?
  2169. auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
  2170. auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
  2171. if (!Cast0 || !Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
  2172. Cast0->getSrcTy() != Cast1->getSrcTy())
  2173. return nullptr;
  2174. // TODO: Allow other opcodes? That would require easing the type restrictions
  2175. // below here.
  2176. CastInst::CastOps CastOpcode = Cast0->getOpcode();
  2177. switch (CastOpcode) {
  2178. case Instruction::FPToSI:
  2179. case Instruction::FPToUI:
  2180. case Instruction::SIToFP:
  2181. case Instruction::UIToFP:
  2182. break;
  2183. default:
  2184. return nullptr;
  2185. }
  2186. VectorType *ShufTy = Shuf.getType();
  2187. VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
  2188. VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
  2189. // TODO: Allow length-increasing shuffles?
  2190. if (ShufTy->getElementCount().getKnownMinValue() >
  2191. ShufOpTy->getElementCount().getKnownMinValue())
  2192. return nullptr;
  2193. // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
  2194. assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
  2195. "Expected fixed vector operands for casts and binary shuffle");
  2196. if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
  2197. return nullptr;
  2198. // At least one of the operands must have only one use (the shuffle).
  2199. if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
  2200. return nullptr;
  2201. // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
  2202. Value *X = Cast0->getOperand(0);
  2203. Value *Y = Cast1->getOperand(0);
  2204. Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
  2205. return CastInst::Create(CastOpcode, NewShuf, ShufTy);
  2206. }
  2207. /// Try to fold an extract subvector operation.
  2208. static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
  2209. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  2210. if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
  2211. return nullptr;
  2212. // Check if we are extracting all bits of an inserted scalar:
  2213. // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
  2214. Value *X;
  2215. if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
  2216. X->getType()->getPrimitiveSizeInBits() ==
  2217. Shuf.getType()->getPrimitiveSizeInBits())
  2218. return new BitCastInst(X, Shuf.getType());
  2219. // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
  2220. Value *Y;
  2221. ArrayRef<int> Mask;
  2222. if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
  2223. return nullptr;
  2224. // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
  2225. // then combining may result in worse codegen.
  2226. if (!Op0->hasOneUse())
  2227. return nullptr;
  2228. // We are extracting a subvector from a shuffle. Remove excess elements from
  2229. // the 1st shuffle mask to eliminate the extract.
  2230. //
  2231. // This transform is conservatively limited to identity extracts because we do
  2232. // not allow arbitrary shuffle mask creation as a target-independent transform
  2233. // (because we can't guarantee that will lower efficiently).
  2234. //
  2235. // If the extracting shuffle has an undef mask element, it transfers to the
  2236. // new shuffle mask. Otherwise, copy the original mask element. Example:
  2237. // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
  2238. // shuf X, Y, <C0, undef, C2, undef>
  2239. unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
  2240. SmallVector<int, 16> NewMask(NumElts);
  2241. assert(NumElts < Mask.size() &&
  2242. "Identity with extract must have less elements than its inputs");
  2243. for (unsigned i = 0; i != NumElts; ++i) {
  2244. int ExtractMaskElt = Shuf.getMaskValue(i);
  2245. int MaskElt = Mask[i];
  2246. NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
  2247. }
  2248. return new ShuffleVectorInst(X, Y, NewMask);
  2249. }
  2250. /// Try to replace a shuffle with an insertelement or try to replace a shuffle
  2251. /// operand with the operand of an insertelement.
  2252. static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
  2253. InstCombinerImpl &IC) {
  2254. Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
  2255. SmallVector<int, 16> Mask;
  2256. Shuf.getShuffleMask(Mask);
  2257. int NumElts = Mask.size();
  2258. int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
  2259. // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
  2260. // not be able to handle it there if the insertelement has >1 use.
  2261. // If the shuffle has an insertelement operand but does not choose the
  2262. // inserted scalar element from that value, then we can replace that shuffle
  2263. // operand with the source vector of the insertelement.
  2264. Value *X;
  2265. uint64_t IdxC;
  2266. if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
  2267. // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
  2268. if (!is_contained(Mask, (int)IdxC))
  2269. return IC.replaceOperand(Shuf, 0, X);
  2270. }
  2271. if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
  2272. // Offset the index constant by the vector width because we are checking for
  2273. // accesses to the 2nd vector input of the shuffle.
  2274. IdxC += InpNumElts;
  2275. // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
  2276. if (!is_contained(Mask, (int)IdxC))
  2277. return IC.replaceOperand(Shuf, 1, X);
  2278. }
  2279. // For the rest of the transform, the shuffle must not change vector sizes.
  2280. // TODO: This restriction could be removed if the insert has only one use
  2281. // (because the transform would require a new length-changing shuffle).
  2282. if (NumElts != InpNumElts)
  2283. return nullptr;
  2284. // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
  2285. auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
  2286. // We need an insertelement with a constant index.
  2287. if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
  2288. m_ConstantInt(IndexC))))
  2289. return false;
  2290. // Test the shuffle mask to see if it splices the inserted scalar into the
  2291. // operand 1 vector of the shuffle.
  2292. int NewInsIndex = -1;
  2293. for (int i = 0; i != NumElts; ++i) {
  2294. // Ignore undef mask elements.
  2295. if (Mask[i] == -1)
  2296. continue;
  2297. // The shuffle takes elements of operand 1 without lane changes.
  2298. if (Mask[i] == NumElts + i)
  2299. continue;
  2300. // The shuffle must choose the inserted scalar exactly once.
  2301. if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
  2302. return false;
  2303. // The shuffle is placing the inserted scalar into element i.
  2304. NewInsIndex = i;
  2305. }
  2306. assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
  2307. // Index is updated to the potentially translated insertion lane.
  2308. IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
  2309. return true;
  2310. };
  2311. // If the shuffle is unnecessary, insert the scalar operand directly into
  2312. // operand 1 of the shuffle. Example:
  2313. // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
  2314. Value *Scalar;
  2315. ConstantInt *IndexC;
  2316. if (isShufflingScalarIntoOp1(Scalar, IndexC))
  2317. return InsertElementInst::Create(V1, Scalar, IndexC);
  2318. // Try again after commuting shuffle. Example:
  2319. // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
  2320. // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
  2321. std::swap(V0, V1);
  2322. ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
  2323. if (isShufflingScalarIntoOp1(Scalar, IndexC))
  2324. return InsertElementInst::Create(V1, Scalar, IndexC);
  2325. return nullptr;
  2326. }
  2327. static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
  2328. // Match the operands as identity with padding (also known as concatenation
  2329. // with undef) shuffles of the same source type. The backend is expected to
  2330. // recreate these concatenations from a shuffle of narrow operands.
  2331. auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
  2332. auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
  2333. if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
  2334. !Shuffle1 || !Shuffle1->isIdentityWithPadding())
  2335. return nullptr;
  2336. // We limit this transform to power-of-2 types because we expect that the
  2337. // backend can convert the simplified IR patterns to identical nodes as the
  2338. // original IR.
  2339. // TODO: If we can verify the same behavior for arbitrary types, the
  2340. // power-of-2 checks can be removed.
  2341. Value *X = Shuffle0->getOperand(0);
  2342. Value *Y = Shuffle1->getOperand(0);
  2343. if (X->getType() != Y->getType() ||
  2344. !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
  2345. !isPowerOf2_32(
  2346. cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
  2347. !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
  2348. match(X, m_Undef()) || match(Y, m_Undef()))
  2349. return nullptr;
  2350. assert(match(Shuffle0->getOperand(1), m_Undef()) &&
  2351. match(Shuffle1->getOperand(1), m_Undef()) &&
  2352. "Unexpected operand for identity shuffle");
  2353. // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
  2354. // operands directly by adjusting the shuffle mask to account for the narrower
  2355. // types:
  2356. // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
  2357. int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
  2358. int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
  2359. assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
  2360. ArrayRef<int> Mask = Shuf.getShuffleMask();
  2361. SmallVector<int, 16> NewMask(Mask.size(), -1);
  2362. for (int i = 0, e = Mask.size(); i != e; ++i) {
  2363. if (Mask[i] == -1)
  2364. continue;
  2365. // If this shuffle is choosing an undef element from 1 of the sources, that
  2366. // element is undef.
  2367. if (Mask[i] < WideElts) {
  2368. if (Shuffle0->getMaskValue(Mask[i]) == -1)
  2369. continue;
  2370. } else {
  2371. if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
  2372. continue;
  2373. }
  2374. // If this shuffle is choosing from the 1st narrow op, the mask element is
  2375. // the same. If this shuffle is choosing from the 2nd narrow op, the mask
  2376. // element is offset down to adjust for the narrow vector widths.
  2377. if (Mask[i] < WideElts) {
  2378. assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
  2379. NewMask[i] = Mask[i];
  2380. } else {
  2381. assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
  2382. NewMask[i] = Mask[i] - (WideElts - NarrowElts);
  2383. }
  2384. }
  2385. return new ShuffleVectorInst(X, Y, NewMask);
  2386. }
  2387. // Splatting the first element of the result of a BinOp, where any of the
  2388. // BinOp's operands are the result of a first element splat can be simplified to
  2389. // splatting the first element of the result of the BinOp
  2390. Instruction *InstCombinerImpl::simplifyBinOpSplats(ShuffleVectorInst &SVI) {
  2391. if (!match(SVI.getOperand(1), m_Undef()) ||
  2392. !match(SVI.getShuffleMask(), m_ZeroMask()))
  2393. return nullptr;
  2394. Value *Op0 = SVI.getOperand(0);
  2395. Value *X, *Y;
  2396. if (!match(Op0, m_BinOp(m_Shuffle(m_Value(X), m_Undef(), m_ZeroMask()),
  2397. m_Value(Y))) &&
  2398. !match(Op0, m_BinOp(m_Value(X),
  2399. m_Shuffle(m_Value(Y), m_Undef(), m_ZeroMask()))))
  2400. return nullptr;
  2401. if (X->getType() != Y->getType())
  2402. return nullptr;
  2403. auto *BinOp = cast<BinaryOperator>(Op0);
  2404. if (!isSafeToSpeculativelyExecute(BinOp))
  2405. return nullptr;
  2406. Value *NewBO = Builder.CreateBinOp(BinOp->getOpcode(), X, Y);
  2407. if (auto NewBOI = dyn_cast<Instruction>(NewBO))
  2408. NewBOI->copyIRFlags(BinOp);
  2409. return new ShuffleVectorInst(NewBO, SVI.getShuffleMask());
  2410. }
  2411. Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  2412. Value *LHS = SVI.getOperand(0);
  2413. Value *RHS = SVI.getOperand(1);
  2414. SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
  2415. if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
  2416. SVI.getType(), ShufQuery))
  2417. return replaceInstUsesWith(SVI, V);
  2418. if (Instruction *I = simplifyBinOpSplats(SVI))
  2419. return I;
  2420. if (isa<ScalableVectorType>(LHS->getType()))
  2421. return nullptr;
  2422. unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
  2423. unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
  2424. // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
  2425. //
  2426. // if X and Y are of the same (vector) type, and the element size is not
  2427. // changed by the bitcasts, we can distribute the bitcasts through the
  2428. // shuffle, hopefully reducing the number of instructions. We make sure that
  2429. // at least one bitcast only has one use, so we don't *increase* the number of
  2430. // instructions here.
  2431. Value *X, *Y;
  2432. if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
  2433. X->getType()->isVectorTy() && X->getType() == Y->getType() &&
  2434. X->getType()->getScalarSizeInBits() ==
  2435. SVI.getType()->getScalarSizeInBits() &&
  2436. (LHS->hasOneUse() || RHS->hasOneUse())) {
  2437. Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
  2438. SVI.getName() + ".uncasted");
  2439. return new BitCastInst(V, SVI.getType());
  2440. }
  2441. ArrayRef<int> Mask = SVI.getShuffleMask();
  2442. Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
  2443. // Peek through a bitcasted shuffle operand by scaling the mask. If the
  2444. // simulated shuffle can simplify, then this shuffle is unnecessary:
  2445. // shuf (bitcast X), undef, Mask --> bitcast X'
  2446. // TODO: This could be extended to allow length-changing shuffles.
  2447. // The transform might also be obsoleted if we allowed canonicalization
  2448. // of bitcasted shuffles.
  2449. if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
  2450. X->getType()->isVectorTy() && VWidth == LHSWidth) {
  2451. // Try to create a scaled mask constant.
  2452. auto *XType = cast<FixedVectorType>(X->getType());
  2453. unsigned XNumElts = XType->getNumElements();
  2454. SmallVector<int, 16> ScaledMask;
  2455. if (XNumElts >= VWidth) {
  2456. assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
  2457. narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
  2458. } else {
  2459. assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
  2460. if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
  2461. ScaledMask.clear();
  2462. }
  2463. if (!ScaledMask.empty()) {
  2464. // If the shuffled source vector simplifies, cast that value to this
  2465. // shuffle's type.
  2466. if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
  2467. ScaledMask, XType, ShufQuery))
  2468. return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
  2469. }
  2470. }
  2471. // shuffle x, x, mask --> shuffle x, undef, mask'
  2472. if (LHS == RHS) {
  2473. assert(!match(RHS, m_Undef()) &&
  2474. "Shuffle with 2 undef ops not simplified?");
  2475. return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
  2476. }
  2477. // shuffle undef, x, mask --> shuffle x, undef, mask'
  2478. if (match(LHS, m_Undef())) {
  2479. SVI.commute();
  2480. return &SVI;
  2481. }
  2482. if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
  2483. return I;
  2484. if (Instruction *I = foldSelectShuffle(SVI))
  2485. return I;
  2486. if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
  2487. return I;
  2488. if (Instruction *I = narrowVectorSelect(SVI, Builder))
  2489. return I;
  2490. if (Instruction *I = foldFNegShuffle(SVI, Builder))
  2491. return I;
  2492. if (Instruction *I = foldCastShuffle(SVI, Builder))
  2493. return I;
  2494. APInt UndefElts(VWidth, 0);
  2495. APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
  2496. if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
  2497. if (V != &SVI)
  2498. return replaceInstUsesWith(SVI, V);
  2499. return &SVI;
  2500. }
  2501. if (Instruction *I = foldIdentityExtractShuffle(SVI))
  2502. return I;
  2503. // These transforms have the potential to lose undef knowledge, so they are
  2504. // intentionally placed after SimplifyDemandedVectorElts().
  2505. if (Instruction *I = foldShuffleWithInsert(SVI, *this))
  2506. return I;
  2507. if (Instruction *I = foldIdentityPaddedShuffles(SVI))
  2508. return I;
  2509. if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
  2510. Value *V = evaluateInDifferentElementOrder(LHS, Mask);
  2511. return replaceInstUsesWith(SVI, V);
  2512. }
  2513. // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
  2514. // a non-vector type. We can instead bitcast the original vector followed by
  2515. // an extract of the desired element:
  2516. //
  2517. // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
  2518. // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
  2519. // %1 = bitcast <4 x i8> %sroa to i32
  2520. // Becomes:
  2521. // %bc = bitcast <16 x i8> %in to <4 x i32>
  2522. // %ext = extractelement <4 x i32> %bc, i32 0
  2523. //
  2524. // If the shuffle is extracting a contiguous range of values from the input
  2525. // vector then each use which is a bitcast of the extracted size can be
  2526. // replaced. This will work if the vector types are compatible, and the begin
  2527. // index is aligned to a value in the casted vector type. If the begin index
  2528. // isn't aligned then we can shuffle the original vector (keeping the same
  2529. // vector type) before extracting.
  2530. //
  2531. // This code will bail out if the target type is fundamentally incompatible
  2532. // with vectors of the source type.
  2533. //
  2534. // Example of <16 x i8>, target type i32:
  2535. // Index range [4,8): v-----------v Will work.
  2536. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  2537. // <16 x i8>: | | | | | | | | | | | | | | | | |
  2538. // <4 x i32>: | | | | |
  2539. // +-----------+-----------+-----------+-----------+
  2540. // Index range [6,10): ^-----------^ Needs an extra shuffle.
  2541. // Target type i40: ^--------------^ Won't work, bail.
  2542. bool MadeChange = false;
  2543. if (isShuffleExtractingFromLHS(SVI, Mask)) {
  2544. Value *V = LHS;
  2545. unsigned MaskElems = Mask.size();
  2546. auto *SrcTy = cast<FixedVectorType>(V->getType());
  2547. unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedValue();
  2548. unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
  2549. assert(SrcElemBitWidth && "vector elements must have a bitwidth");
  2550. unsigned SrcNumElems = SrcTy->getNumElements();
  2551. SmallVector<BitCastInst *, 8> BCs;
  2552. DenseMap<Type *, Value *> NewBCs;
  2553. for (User *U : SVI.users())
  2554. if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
  2555. if (!BC->use_empty())
  2556. // Only visit bitcasts that weren't previously handled.
  2557. BCs.push_back(BC);
  2558. for (BitCastInst *BC : BCs) {
  2559. unsigned BegIdx = Mask.front();
  2560. Type *TgtTy = BC->getDestTy();
  2561. unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
  2562. if (!TgtElemBitWidth)
  2563. continue;
  2564. unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
  2565. bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
  2566. bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
  2567. if (!VecBitWidthsEqual)
  2568. continue;
  2569. if (!VectorType::isValidElementType(TgtTy))
  2570. continue;
  2571. auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
  2572. if (!BegIsAligned) {
  2573. // Shuffle the input so [0,NumElements) contains the output, and
  2574. // [NumElems,SrcNumElems) is undef.
  2575. SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
  2576. for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
  2577. ShuffleMask[I] = Idx;
  2578. V = Builder.CreateShuffleVector(V, ShuffleMask,
  2579. SVI.getName() + ".extract");
  2580. BegIdx = 0;
  2581. }
  2582. unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
  2583. assert(SrcElemsPerTgtElem);
  2584. BegIdx /= SrcElemsPerTgtElem;
  2585. bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
  2586. auto *NewBC =
  2587. BCAlreadyExists
  2588. ? NewBCs[CastSrcTy]
  2589. : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
  2590. if (!BCAlreadyExists)
  2591. NewBCs[CastSrcTy] = NewBC;
  2592. auto *Ext = Builder.CreateExtractElement(
  2593. NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
  2594. // The shufflevector isn't being replaced: the bitcast that used it
  2595. // is. InstCombine will visit the newly-created instructions.
  2596. replaceInstUsesWith(*BC, Ext);
  2597. MadeChange = true;
  2598. }
  2599. }
  2600. // If the LHS is a shufflevector itself, see if we can combine it with this
  2601. // one without producing an unusual shuffle.
  2602. // Cases that might be simplified:
  2603. // 1.
  2604. // x1=shuffle(v1,v2,mask1)
  2605. // x=shuffle(x1,undef,mask)
  2606. // ==>
  2607. // x=shuffle(v1,undef,newMask)
  2608. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
  2609. // 2.
  2610. // x1=shuffle(v1,undef,mask1)
  2611. // x=shuffle(x1,x2,mask)
  2612. // where v1.size() == mask1.size()
  2613. // ==>
  2614. // x=shuffle(v1,x2,newMask)
  2615. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
  2616. // 3.
  2617. // x2=shuffle(v2,undef,mask2)
  2618. // x=shuffle(x1,x2,mask)
  2619. // where v2.size() == mask2.size()
  2620. // ==>
  2621. // x=shuffle(x1,v2,newMask)
  2622. // newMask[i] = (mask[i] < x1.size())
  2623. // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
  2624. // 4.
  2625. // x1=shuffle(v1,undef,mask1)
  2626. // x2=shuffle(v2,undef,mask2)
  2627. // x=shuffle(x1,x2,mask)
  2628. // where v1.size() == v2.size()
  2629. // ==>
  2630. // x=shuffle(v1,v2,newMask)
  2631. // newMask[i] = (mask[i] < x1.size())
  2632. // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
  2633. //
  2634. // Here we are really conservative:
  2635. // we are absolutely afraid of producing a shuffle mask not in the input
  2636. // program, because the code gen may not be smart enough to turn a merged
  2637. // shuffle into two specific shuffles: it may produce worse code. As such,
  2638. // we only merge two shuffles if the result is either a splat or one of the
  2639. // input shuffle masks. In this case, merging the shuffles just removes
  2640. // one instruction, which we know is safe. This is good for things like
  2641. // turning: (splat(splat)) -> splat, or
  2642. // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
  2643. ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
  2644. ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
  2645. if (LHSShuffle)
  2646. if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
  2647. LHSShuffle = nullptr;
  2648. if (RHSShuffle)
  2649. if (!match(RHSShuffle->getOperand(1), m_Undef()))
  2650. RHSShuffle = nullptr;
  2651. if (!LHSShuffle && !RHSShuffle)
  2652. return MadeChange ? &SVI : nullptr;
  2653. Value* LHSOp0 = nullptr;
  2654. Value* LHSOp1 = nullptr;
  2655. Value* RHSOp0 = nullptr;
  2656. unsigned LHSOp0Width = 0;
  2657. unsigned RHSOp0Width = 0;
  2658. if (LHSShuffle) {
  2659. LHSOp0 = LHSShuffle->getOperand(0);
  2660. LHSOp1 = LHSShuffle->getOperand(1);
  2661. LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
  2662. }
  2663. if (RHSShuffle) {
  2664. RHSOp0 = RHSShuffle->getOperand(0);
  2665. RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
  2666. }
  2667. Value* newLHS = LHS;
  2668. Value* newRHS = RHS;
  2669. if (LHSShuffle) {
  2670. // case 1
  2671. if (match(RHS, m_Undef())) {
  2672. newLHS = LHSOp0;
  2673. newRHS = LHSOp1;
  2674. }
  2675. // case 2 or 4
  2676. else if (LHSOp0Width == LHSWidth) {
  2677. newLHS = LHSOp0;
  2678. }
  2679. }
  2680. // case 3 or 4
  2681. if (RHSShuffle && RHSOp0Width == LHSWidth) {
  2682. newRHS = RHSOp0;
  2683. }
  2684. // case 4
  2685. if (LHSOp0 == RHSOp0) {
  2686. newLHS = LHSOp0;
  2687. newRHS = nullptr;
  2688. }
  2689. if (newLHS == LHS && newRHS == RHS)
  2690. return MadeChange ? &SVI : nullptr;
  2691. ArrayRef<int> LHSMask;
  2692. ArrayRef<int> RHSMask;
  2693. if (newLHS != LHS)
  2694. LHSMask = LHSShuffle->getShuffleMask();
  2695. if (RHSShuffle && newRHS != RHS)
  2696. RHSMask = RHSShuffle->getShuffleMask();
  2697. unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
  2698. SmallVector<int, 16> newMask;
  2699. bool isSplat = true;
  2700. int SplatElt = -1;
  2701. // Create a new mask for the new ShuffleVectorInst so that the new
  2702. // ShuffleVectorInst is equivalent to the original one.
  2703. for (unsigned i = 0; i < VWidth; ++i) {
  2704. int eltMask;
  2705. if (Mask[i] < 0) {
  2706. // This element is an undef value.
  2707. eltMask = -1;
  2708. } else if (Mask[i] < (int)LHSWidth) {
  2709. // This element is from left hand side vector operand.
  2710. //
  2711. // If LHS is going to be replaced (case 1, 2, or 4), calculate the
  2712. // new mask value for the element.
  2713. if (newLHS != LHS) {
  2714. eltMask = LHSMask[Mask[i]];
  2715. // If the value selected is an undef value, explicitly specify it
  2716. // with a -1 mask value.
  2717. if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
  2718. eltMask = -1;
  2719. } else
  2720. eltMask = Mask[i];
  2721. } else {
  2722. // This element is from right hand side vector operand
  2723. //
  2724. // If the value selected is an undef value, explicitly specify it
  2725. // with a -1 mask value. (case 1)
  2726. if (match(RHS, m_Undef()))
  2727. eltMask = -1;
  2728. // If RHS is going to be replaced (case 3 or 4), calculate the
  2729. // new mask value for the element.
  2730. else if (newRHS != RHS) {
  2731. eltMask = RHSMask[Mask[i]-LHSWidth];
  2732. // If the value selected is an undef value, explicitly specify it
  2733. // with a -1 mask value.
  2734. if (eltMask >= (int)RHSOp0Width) {
  2735. assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
  2736. "should have been check above");
  2737. eltMask = -1;
  2738. }
  2739. } else
  2740. eltMask = Mask[i]-LHSWidth;
  2741. // If LHS's width is changed, shift the mask value accordingly.
  2742. // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
  2743. // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
  2744. // If newRHS == newLHS, we want to remap any references from newRHS to
  2745. // newLHS so that we can properly identify splats that may occur due to
  2746. // obfuscation across the two vectors.
  2747. if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
  2748. eltMask += newLHSWidth;
  2749. }
  2750. // Check if this could still be a splat.
  2751. if (eltMask >= 0) {
  2752. if (SplatElt >= 0 && SplatElt != eltMask)
  2753. isSplat = false;
  2754. SplatElt = eltMask;
  2755. }
  2756. newMask.push_back(eltMask);
  2757. }
  2758. // If the result mask is equal to one of the original shuffle masks,
  2759. // or is a splat, do the replacement.
  2760. if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
  2761. if (!newRHS)
  2762. newRHS = UndefValue::get(newLHS->getType());
  2763. return new ShuffleVectorInst(newLHS, newRHS, newMask);
  2764. }
  2765. return MadeChange ? &SVI : nullptr;
  2766. }