InstCombineCalls.cpp 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379
  1. //===- InstCombineCalls.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 the visitCall, visitInvoke, and visitCallBr functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/APSInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/FloatingPointMode.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallBitVector.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/AssumeBundleQueries.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/InstructionSimplify.h"
  29. #include "llvm/Analysis/Loads.h"
  30. #include "llvm/Analysis/MemoryBuiltins.h"
  31. #include "llvm/Analysis/TargetTransformInfo.h"
  32. #include "llvm/Analysis/ValueTracking.h"
  33. #include "llvm/Analysis/VectorUtils.h"
  34. #include "llvm/IR/Attributes.h"
  35. #include "llvm/IR/BasicBlock.h"
  36. #include "llvm/IR/Constant.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalVariable.h"
  42. #include "llvm/IR/InlineAsm.h"
  43. #include "llvm/IR/InstrTypes.h"
  44. #include "llvm/IR/Instruction.h"
  45. #include "llvm/IR/Instructions.h"
  46. #include "llvm/IR/IntrinsicInst.h"
  47. #include "llvm/IR/Intrinsics.h"
  48. #include "llvm/IR/IntrinsicsAArch64.h"
  49. #include "llvm/IR/IntrinsicsAMDGPU.h"
  50. #include "llvm/IR/IntrinsicsARM.h"
  51. #include "llvm/IR/IntrinsicsHexagon.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Metadata.h"
  54. #include "llvm/IR/PatternMatch.h"
  55. #include "llvm/IR/Statepoint.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/User.h"
  58. #include "llvm/IR/Value.h"
  59. #include "llvm/IR/ValueHandle.h"
  60. #include "llvm/Support/AtomicOrdering.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/CommandLine.h"
  63. #include "llvm/Support/Compiler.h"
  64. #include "llvm/Support/Debug.h"
  65. #include "llvm/Support/ErrorHandling.h"
  66. #include "llvm/Support/KnownBits.h"
  67. #include "llvm/Support/MathExtras.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  70. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  71. #include "llvm/Transforms/Utils/Local.h"
  72. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  73. #include <algorithm>
  74. #include <cassert>
  75. #include <cstdint>
  76. #include <cstring>
  77. #include <utility>
  78. #include <vector>
  79. #define DEBUG_TYPE "instcombine"
  80. #include "llvm/Transforms/Utils/InstructionWorklist.h"
  81. using namespace llvm;
  82. using namespace PatternMatch;
  83. STATISTIC(NumSimplified, "Number of library calls simplified");
  84. static cl::opt<unsigned> GuardWideningWindow(
  85. "instcombine-guard-widening-window",
  86. cl::init(3),
  87. cl::desc("How wide an instruction window to bypass looking for "
  88. "another guard"));
  89. namespace llvm {
  90. /// enable preservation of attributes in assume like:
  91. /// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
  92. extern cl::opt<bool> EnableKnowledgeRetention;
  93. } // namespace llvm
  94. /// Return the specified type promoted as it would be to pass though a va_arg
  95. /// area.
  96. static Type *getPromotedType(Type *Ty) {
  97. if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
  98. if (ITy->getBitWidth() < 32)
  99. return Type::getInt32Ty(Ty->getContext());
  100. }
  101. return Ty;
  102. }
  103. Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
  104. Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
  105. MaybeAlign CopyDstAlign = MI->getDestAlign();
  106. if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
  107. MI->setDestAlignment(DstAlign);
  108. return MI;
  109. }
  110. Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
  111. MaybeAlign CopySrcAlign = MI->getSourceAlign();
  112. if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
  113. MI->setSourceAlignment(SrcAlign);
  114. return MI;
  115. }
  116. // If we have a store to a location which is known constant, we can conclude
  117. // that the store must be storing the constant value (else the memory
  118. // wouldn't be constant), and this must be a noop.
  119. if (AA->pointsToConstantMemory(MI->getDest())) {
  120. // Set the size of the copy to 0, it will be deleted on the next iteration.
  121. MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
  122. return MI;
  123. }
  124. // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
  125. // load/store.
  126. ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
  127. if (!MemOpLength) return nullptr;
  128. // Source and destination pointer types are always "i8*" for intrinsic. See
  129. // if the size is something we can handle with a single primitive load/store.
  130. // A single load+store correctly handles overlapping memory in the memmove
  131. // case.
  132. uint64_t Size = MemOpLength->getLimitedValue();
  133. assert(Size && "0-sized memory transferring should be removed already.");
  134. if (Size > 8 || (Size&(Size-1)))
  135. return nullptr; // If not 1/2/4/8 bytes, exit.
  136. // If it is an atomic and alignment is less than the size then we will
  137. // introduce the unaligned memory access which will be later transformed
  138. // into libcall in CodeGen. This is not evident performance gain so disable
  139. // it now.
  140. if (isa<AtomicMemTransferInst>(MI))
  141. if (*CopyDstAlign < Size || *CopySrcAlign < Size)
  142. return nullptr;
  143. // Use an integer load+store unless we can find something better.
  144. unsigned SrcAddrSp =
  145. cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
  146. unsigned DstAddrSp =
  147. cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
  148. IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
  149. Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
  150. Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
  151. // If the memcpy has metadata describing the members, see if we can get the
  152. // TBAA tag describing our copy.
  153. MDNode *CopyMD = nullptr;
  154. if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
  155. CopyMD = M;
  156. } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
  157. if (M->getNumOperands() == 3 && M->getOperand(0) &&
  158. mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
  159. mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
  160. M->getOperand(1) &&
  161. mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
  162. mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
  163. Size &&
  164. M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
  165. CopyMD = cast<MDNode>(M->getOperand(2));
  166. }
  167. Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
  168. Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
  169. LoadInst *L = Builder.CreateLoad(IntType, Src);
  170. // Alignment from the mem intrinsic will be better, so use it.
  171. L->setAlignment(*CopySrcAlign);
  172. if (CopyMD)
  173. L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
  174. MDNode *LoopMemParallelMD =
  175. MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  176. if (LoopMemParallelMD)
  177. L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
  178. MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
  179. if (AccessGroupMD)
  180. L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
  181. StoreInst *S = Builder.CreateStore(L, Dest);
  182. // Alignment from the mem intrinsic will be better, so use it.
  183. S->setAlignment(*CopyDstAlign);
  184. if (CopyMD)
  185. S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
  186. if (LoopMemParallelMD)
  187. S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
  188. if (AccessGroupMD)
  189. S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
  190. if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
  191. // non-atomics can be volatile
  192. L->setVolatile(MT->isVolatile());
  193. S->setVolatile(MT->isVolatile());
  194. }
  195. if (isa<AtomicMemTransferInst>(MI)) {
  196. // atomics have to be unordered
  197. L->setOrdering(AtomicOrdering::Unordered);
  198. S->setOrdering(AtomicOrdering::Unordered);
  199. }
  200. // Set the size of the copy to 0, it will be deleted on the next iteration.
  201. MI->setLength(Constant::getNullValue(MemOpLength->getType()));
  202. return MI;
  203. }
  204. Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
  205. const Align KnownAlignment =
  206. getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
  207. MaybeAlign MemSetAlign = MI->getDestAlign();
  208. if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
  209. MI->setDestAlignment(KnownAlignment);
  210. return MI;
  211. }
  212. // If we have a store to a location which is known constant, we can conclude
  213. // that the store must be storing the constant value (else the memory
  214. // wouldn't be constant), and this must be a noop.
  215. if (AA->pointsToConstantMemory(MI->getDest())) {
  216. // Set the size of the copy to 0, it will be deleted on the next iteration.
  217. MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
  218. return MI;
  219. }
  220. // Extract the length and alignment and fill if they are constant.
  221. ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
  222. ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
  223. if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
  224. return nullptr;
  225. const uint64_t Len = LenC->getLimitedValue();
  226. assert(Len && "0-sized memory setting should be removed already.");
  227. const Align Alignment = assumeAligned(MI->getDestAlignment());
  228. // If it is an atomic and alignment is less than the size then we will
  229. // introduce the unaligned memory access which will be later transformed
  230. // into libcall in CodeGen. This is not evident performance gain so disable
  231. // it now.
  232. if (isa<AtomicMemSetInst>(MI))
  233. if (Alignment < Len)
  234. return nullptr;
  235. // memset(s,c,n) -> store s, c (for n=1,2,4,8)
  236. if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
  237. Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
  238. Value *Dest = MI->getDest();
  239. unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
  240. Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
  241. Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
  242. // Extract the fill value and store.
  243. uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
  244. StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
  245. MI->isVolatile());
  246. S->setAlignment(Alignment);
  247. if (isa<AtomicMemSetInst>(MI))
  248. S->setOrdering(AtomicOrdering::Unordered);
  249. // Set the size of the copy to 0, it will be deleted on the next iteration.
  250. MI->setLength(Constant::getNullValue(LenC->getType()));
  251. return MI;
  252. }
  253. return nullptr;
  254. }
  255. // TODO, Obvious Missing Transforms:
  256. // * Narrow width by halfs excluding zero/undef lanes
  257. Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
  258. Value *LoadPtr = II.getArgOperand(0);
  259. const Align Alignment =
  260. cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
  261. // If the mask is all ones or undefs, this is a plain vector load of the 1st
  262. // argument.
  263. if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
  264. LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
  265. "unmaskedload");
  266. L->copyMetadata(II);
  267. return L;
  268. }
  269. // If we can unconditionally load from this address, replace with a
  270. // load/select idiom. TODO: use DT for context sensitive query
  271. if (isDereferenceablePointer(LoadPtr, II.getType(),
  272. II.getModule()->getDataLayout(), &II, nullptr)) {
  273. LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
  274. "unmaskedload");
  275. LI->copyMetadata(II);
  276. return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
  277. }
  278. return nullptr;
  279. }
  280. // TODO, Obvious Missing Transforms:
  281. // * Single constant active lane -> store
  282. // * Narrow width by halfs excluding zero/undef lanes
  283. Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
  284. auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
  285. if (!ConstMask)
  286. return nullptr;
  287. // If the mask is all zeros, this instruction does nothing.
  288. if (ConstMask->isNullValue())
  289. return eraseInstFromFunction(II);
  290. // If the mask is all ones, this is a plain vector store of the 1st argument.
  291. if (ConstMask->isAllOnesValue()) {
  292. Value *StorePtr = II.getArgOperand(1);
  293. Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
  294. StoreInst *S =
  295. new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
  296. S->copyMetadata(II);
  297. return S;
  298. }
  299. if (isa<ScalableVectorType>(ConstMask->getType()))
  300. return nullptr;
  301. // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
  302. APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
  303. APInt UndefElts(DemandedElts.getBitWidth(), 0);
  304. if (Value *V =
  305. SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
  306. return replaceOperand(II, 0, V);
  307. return nullptr;
  308. }
  309. // TODO, Obvious Missing Transforms:
  310. // * Single constant active lane load -> load
  311. // * Dereferenceable address & few lanes -> scalarize speculative load/selects
  312. // * Adjacent vector addresses -> masked.load
  313. // * Narrow width by halfs excluding zero/undef lanes
  314. // * Vector incrementing address -> vector masked load
  315. Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
  316. auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
  317. if (!ConstMask)
  318. return nullptr;
  319. // Vector splat address w/known mask -> scalar load
  320. // Fold the gather to load the source vector first lane
  321. // because it is reloading the same value each time
  322. if (ConstMask->isAllOnesValue())
  323. if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
  324. auto *VecTy = cast<VectorType>(II.getType());
  325. const Align Alignment =
  326. cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
  327. LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
  328. Alignment, "load.scalar");
  329. Value *Shuf =
  330. Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
  331. return replaceInstUsesWith(II, cast<Instruction>(Shuf));
  332. }
  333. return nullptr;
  334. }
  335. // TODO, Obvious Missing Transforms:
  336. // * Single constant active lane -> store
  337. // * Adjacent vector addresses -> masked.store
  338. // * Narrow store width by halfs excluding zero/undef lanes
  339. // * Vector incrementing address -> vector masked store
  340. Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
  341. auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
  342. if (!ConstMask)
  343. return nullptr;
  344. // If the mask is all zeros, a scatter does nothing.
  345. if (ConstMask->isNullValue())
  346. return eraseInstFromFunction(II);
  347. // Vector splat address -> scalar store
  348. if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
  349. // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
  350. if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
  351. Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
  352. StoreInst *S =
  353. new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
  354. S->copyMetadata(II);
  355. return S;
  356. }
  357. // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
  358. // lastlane), ptr
  359. if (ConstMask->isAllOnesValue()) {
  360. Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
  361. VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
  362. ElementCount VF = WideLoadTy->getElementCount();
  363. Constant *EC =
  364. ConstantInt::get(Builder.getInt32Ty(), VF.getKnownMinValue());
  365. Value *RunTimeVF = VF.isScalable() ? Builder.CreateVScale(EC) : EC;
  366. Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
  367. Value *Extract =
  368. Builder.CreateExtractElement(II.getArgOperand(0), LastLane);
  369. StoreInst *S =
  370. new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
  371. S->copyMetadata(II);
  372. return S;
  373. }
  374. }
  375. if (isa<ScalableVectorType>(ConstMask->getType()))
  376. return nullptr;
  377. // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
  378. APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
  379. APInt UndefElts(DemandedElts.getBitWidth(), 0);
  380. if (Value *V =
  381. SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
  382. return replaceOperand(II, 0, V);
  383. if (Value *V =
  384. SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts))
  385. return replaceOperand(II, 1, V);
  386. return nullptr;
  387. }
  388. /// This function transforms launder.invariant.group and strip.invariant.group
  389. /// like:
  390. /// launder(launder(%x)) -> launder(%x) (the result is not the argument)
  391. /// launder(strip(%x)) -> launder(%x)
  392. /// strip(strip(%x)) -> strip(%x) (the result is not the argument)
  393. /// strip(launder(%x)) -> strip(%x)
  394. /// This is legal because it preserves the most recent information about
  395. /// the presence or absence of invariant.group.
  396. static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
  397. InstCombinerImpl &IC) {
  398. auto *Arg = II.getArgOperand(0);
  399. auto *StrippedArg = Arg->stripPointerCasts();
  400. auto *StrippedInvariantGroupsArg = StrippedArg;
  401. while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
  402. if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
  403. Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
  404. break;
  405. StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
  406. }
  407. if (StrippedArg == StrippedInvariantGroupsArg)
  408. return nullptr; // No launders/strips to remove.
  409. Value *Result = nullptr;
  410. if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
  411. Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
  412. else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
  413. Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
  414. else
  415. llvm_unreachable(
  416. "simplifyInvariantGroupIntrinsic only handles launder and strip");
  417. if (Result->getType()->getPointerAddressSpace() !=
  418. II.getType()->getPointerAddressSpace())
  419. Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
  420. if (Result->getType() != II.getType())
  421. Result = IC.Builder.CreateBitCast(Result, II.getType());
  422. return cast<Instruction>(Result);
  423. }
  424. static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
  425. assert((II.getIntrinsicID() == Intrinsic::cttz ||
  426. II.getIntrinsicID() == Intrinsic::ctlz) &&
  427. "Expected cttz or ctlz intrinsic");
  428. bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
  429. Value *Op0 = II.getArgOperand(0);
  430. Value *Op1 = II.getArgOperand(1);
  431. Value *X;
  432. // ctlz(bitreverse(x)) -> cttz(x)
  433. // cttz(bitreverse(x)) -> ctlz(x)
  434. if (match(Op0, m_BitReverse(m_Value(X)))) {
  435. Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
  436. Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
  437. return CallInst::Create(F, {X, II.getArgOperand(1)});
  438. }
  439. if (II.getType()->isIntOrIntVectorTy(1)) {
  440. // ctlz/cttz i1 Op0 --> not Op0
  441. if (match(Op1, m_Zero()))
  442. return BinaryOperator::CreateNot(Op0);
  443. // If zero is poison, then the input can be assumed to be "true", so the
  444. // instruction simplifies to "false".
  445. assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
  446. return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));
  447. }
  448. // If the operand is a select with constant arm(s), try to hoist ctlz/cttz.
  449. if (auto *Sel = dyn_cast<SelectInst>(Op0))
  450. if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
  451. return R;
  452. if (IsTZ) {
  453. // cttz(-x) -> cttz(x)
  454. if (match(Op0, m_Neg(m_Value(X))))
  455. return IC.replaceOperand(II, 0, X);
  456. // cttz(sext(x)) -> cttz(zext(x))
  457. if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
  458. auto *Zext = IC.Builder.CreateZExt(X, II.getType());
  459. auto *CttzZext =
  460. IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
  461. return IC.replaceInstUsesWith(II, CttzZext);
  462. }
  463. // Zext doesn't change the number of trailing zeros, so narrow:
  464. // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
  465. if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
  466. auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
  467. IC.Builder.getTrue());
  468. auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
  469. return IC.replaceInstUsesWith(II, ZextCttz);
  470. }
  471. // cttz(abs(x)) -> cttz(x)
  472. // cttz(nabs(x)) -> cttz(x)
  473. Value *Y;
  474. SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
  475. if (SPF == SPF_ABS || SPF == SPF_NABS)
  476. return IC.replaceOperand(II, 0, X);
  477. if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
  478. return IC.replaceOperand(II, 0, X);
  479. }
  480. KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
  481. // Create a mask for bits above (ctlz) or below (cttz) the first known one.
  482. unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
  483. : Known.countMaxLeadingZeros();
  484. unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
  485. : Known.countMinLeadingZeros();
  486. // If all bits above (ctlz) or below (cttz) the first known one are known
  487. // zero, this value is constant.
  488. // FIXME: This should be in InstSimplify because we're replacing an
  489. // instruction with a constant.
  490. if (PossibleZeros == DefiniteZeros) {
  491. auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
  492. return IC.replaceInstUsesWith(II, C);
  493. }
  494. // If the input to cttz/ctlz is known to be non-zero,
  495. // then change the 'ZeroIsPoison' parameter to 'true'
  496. // because we know the zero behavior can't affect the result.
  497. if (!Known.One.isZero() ||
  498. isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
  499. &IC.getDominatorTree())) {
  500. if (!match(II.getArgOperand(1), m_One()))
  501. return IC.replaceOperand(II, 1, IC.Builder.getTrue());
  502. }
  503. // Add range metadata since known bits can't completely reflect what we know.
  504. // TODO: Handle splat vectors.
  505. auto *IT = dyn_cast<IntegerType>(Op0->getType());
  506. if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
  507. Metadata *LowAndHigh[] = {
  508. ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
  509. ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
  510. II.setMetadata(LLVMContext::MD_range,
  511. MDNode::get(II.getContext(), LowAndHigh));
  512. return &II;
  513. }
  514. return nullptr;
  515. }
  516. static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
  517. assert(II.getIntrinsicID() == Intrinsic::ctpop &&
  518. "Expected ctpop intrinsic");
  519. Type *Ty = II.getType();
  520. unsigned BitWidth = Ty->getScalarSizeInBits();
  521. Value *Op0 = II.getArgOperand(0);
  522. Value *X, *Y;
  523. // ctpop(bitreverse(x)) -> ctpop(x)
  524. // ctpop(bswap(x)) -> ctpop(x)
  525. if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
  526. return IC.replaceOperand(II, 0, X);
  527. // ctpop(rot(x)) -> ctpop(x)
  528. if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
  529. match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
  530. X == Y)
  531. return IC.replaceOperand(II, 0, X);
  532. // ctpop(x | -x) -> bitwidth - cttz(x, false)
  533. if (Op0->hasOneUse() &&
  534. match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
  535. Function *F =
  536. Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
  537. auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
  538. auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
  539. return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
  540. }
  541. // ctpop(~x & (x - 1)) -> cttz(x, false)
  542. if (match(Op0,
  543. m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) {
  544. Function *F =
  545. Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
  546. return CallInst::Create(F, {X, IC.Builder.getFalse()});
  547. }
  548. // Zext doesn't change the number of set bits, so narrow:
  549. // ctpop (zext X) --> zext (ctpop X)
  550. if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
  551. Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
  552. return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
  553. }
  554. // If the operand is a select with constant arm(s), try to hoist ctpop.
  555. if (auto *Sel = dyn_cast<SelectInst>(Op0))
  556. if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
  557. return R;
  558. KnownBits Known(BitWidth);
  559. IC.computeKnownBits(Op0, Known, 0, &II);
  560. // If all bits are zero except for exactly one fixed bit, then the result
  561. // must be 0 or 1, and we can get that answer by shifting to LSB:
  562. // ctpop (X & 32) --> (X & 32) >> 5
  563. if ((~Known.Zero).isPowerOf2())
  564. return BinaryOperator::CreateLShr(
  565. Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
  566. // FIXME: Try to simplify vectors of integers.
  567. auto *IT = dyn_cast<IntegerType>(Ty);
  568. if (!IT)
  569. return nullptr;
  570. // Add range metadata since known bits can't completely reflect what we know.
  571. unsigned MinCount = Known.countMinPopulation();
  572. unsigned MaxCount = Known.countMaxPopulation();
  573. if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
  574. Metadata *LowAndHigh[] = {
  575. ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
  576. ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
  577. II.setMetadata(LLVMContext::MD_range,
  578. MDNode::get(II.getContext(), LowAndHigh));
  579. return &II;
  580. }
  581. return nullptr;
  582. }
  583. /// Convert a table lookup to shufflevector if the mask is constant.
  584. /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
  585. /// which case we could lower the shufflevector with rev64 instructions
  586. /// as it's actually a byte reverse.
  587. static Value *simplifyNeonTbl1(const IntrinsicInst &II,
  588. InstCombiner::BuilderTy &Builder) {
  589. // Bail out if the mask is not a constant.
  590. auto *C = dyn_cast<Constant>(II.getArgOperand(1));
  591. if (!C)
  592. return nullptr;
  593. auto *VecTy = cast<FixedVectorType>(II.getType());
  594. unsigned NumElts = VecTy->getNumElements();
  595. // Only perform this transformation for <8 x i8> vector types.
  596. if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
  597. return nullptr;
  598. int Indexes[8];
  599. for (unsigned I = 0; I < NumElts; ++I) {
  600. Constant *COp = C->getAggregateElement(I);
  601. if (!COp || !isa<ConstantInt>(COp))
  602. return nullptr;
  603. Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
  604. // Make sure the mask indices are in range.
  605. if ((unsigned)Indexes[I] >= NumElts)
  606. return nullptr;
  607. }
  608. auto *V1 = II.getArgOperand(0);
  609. auto *V2 = Constant::getNullValue(V1->getType());
  610. return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes));
  611. }
  612. // Returns true iff the 2 intrinsics have the same operands, limiting the
  613. // comparison to the first NumOperands.
  614. static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
  615. unsigned NumOperands) {
  616. assert(I.arg_size() >= NumOperands && "Not enough operands");
  617. assert(E.arg_size() >= NumOperands && "Not enough operands");
  618. for (unsigned i = 0; i < NumOperands; i++)
  619. if (I.getArgOperand(i) != E.getArgOperand(i))
  620. return false;
  621. return true;
  622. }
  623. // Remove trivially empty start/end intrinsic ranges, i.e. a start
  624. // immediately followed by an end (ignoring debuginfo or other
  625. // start/end intrinsics in between). As this handles only the most trivial
  626. // cases, tracking the nesting level is not needed:
  627. //
  628. // call @llvm.foo.start(i1 0)
  629. // call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
  630. // call @llvm.foo.end(i1 0)
  631. // call @llvm.foo.end(i1 0) ; &I
  632. static bool
  633. removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
  634. std::function<bool(const IntrinsicInst &)> IsStart) {
  635. // We start from the end intrinsic and scan backwards, so that InstCombine
  636. // has already processed (and potentially removed) all the instructions
  637. // before the end intrinsic.
  638. BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
  639. for (; BI != BE; ++BI) {
  640. if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
  641. if (I->isDebugOrPseudoInst() ||
  642. I->getIntrinsicID() == EndI.getIntrinsicID())
  643. continue;
  644. if (IsStart(*I)) {
  645. if (haveSameOperands(EndI, *I, EndI.arg_size())) {
  646. IC.eraseInstFromFunction(*I);
  647. IC.eraseInstFromFunction(EndI);
  648. return true;
  649. }
  650. // Skip start intrinsics that don't pair with this end intrinsic.
  651. continue;
  652. }
  653. }
  654. break;
  655. }
  656. return false;
  657. }
  658. Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
  659. removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
  660. return I.getIntrinsicID() == Intrinsic::vastart ||
  661. I.getIntrinsicID() == Intrinsic::vacopy;
  662. });
  663. return nullptr;
  664. }
  665. static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
  666. assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
  667. Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
  668. if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
  669. Call.setArgOperand(0, Arg1);
  670. Call.setArgOperand(1, Arg0);
  671. return &Call;
  672. }
  673. return nullptr;
  674. }
  675. /// Creates a result tuple for an overflow intrinsic \p II with a given
  676. /// \p Result and a constant \p Overflow value.
  677. static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
  678. Constant *Overflow) {
  679. Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
  680. StructType *ST = cast<StructType>(II->getType());
  681. Constant *Struct = ConstantStruct::get(ST, V);
  682. return InsertValueInst::Create(Struct, Result, 0);
  683. }
  684. Instruction *
  685. InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
  686. WithOverflowInst *WO = cast<WithOverflowInst>(II);
  687. Value *OperationResult = nullptr;
  688. Constant *OverflowResult = nullptr;
  689. if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
  690. WO->getRHS(), *WO, OperationResult, OverflowResult))
  691. return createOverflowTuple(WO, OperationResult, OverflowResult);
  692. return nullptr;
  693. }
  694. static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
  695. const DataLayout &DL, AssumptionCache *AC,
  696. DominatorTree *DT) {
  697. KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
  698. if (Known.isNonNegative())
  699. return false;
  700. if (Known.isNegative())
  701. return true;
  702. return isImpliedByDomCondition(
  703. ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
  704. }
  705. /// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
  706. /// can trigger other combines.
  707. static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
  708. InstCombiner::BuilderTy &Builder) {
  709. Intrinsic::ID MinMaxID = II->getIntrinsicID();
  710. assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
  711. MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
  712. "Expected a min or max intrinsic");
  713. // TODO: Match vectors with undef elements, but undef may not propagate.
  714. Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
  715. Value *X;
  716. const APInt *C0, *C1;
  717. if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
  718. !match(Op1, m_APInt(C1)))
  719. return nullptr;
  720. // Check for necessary no-wrap and overflow constraints.
  721. bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
  722. auto *Add = cast<BinaryOperator>(Op0);
  723. if ((IsSigned && !Add->hasNoSignedWrap()) ||
  724. (!IsSigned && !Add->hasNoUnsignedWrap()))
  725. return nullptr;
  726. // If the constant difference overflows, then instsimplify should reduce the
  727. // min/max to the add or C1.
  728. bool Overflow;
  729. APInt CDiff =
  730. IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
  731. assert(!Overflow && "Expected simplify of min/max");
  732. // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
  733. // Note: the "mismatched" no-overflow setting does not propagate.
  734. Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
  735. Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
  736. return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
  737. : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
  738. }
  739. /// If we have a clamp pattern like max (min X, 42), 41 -- where the output
  740. /// can only be one of two possible constant values -- turn that into a select
  741. /// of constants.
  742. static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
  743. InstCombiner::BuilderTy &Builder) {
  744. Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
  745. Value *X;
  746. const APInt *C0, *C1;
  747. if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
  748. return nullptr;
  749. CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
  750. switch (II->getIntrinsicID()) {
  751. case Intrinsic::smax:
  752. if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
  753. Pred = ICmpInst::ICMP_SGT;
  754. break;
  755. case Intrinsic::smin:
  756. if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
  757. Pred = ICmpInst::ICMP_SLT;
  758. break;
  759. case Intrinsic::umax:
  760. if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
  761. Pred = ICmpInst::ICMP_UGT;
  762. break;
  763. case Intrinsic::umin:
  764. if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
  765. Pred = ICmpInst::ICMP_ULT;
  766. break;
  767. default:
  768. llvm_unreachable("Expected min/max intrinsic");
  769. }
  770. if (Pred == CmpInst::BAD_ICMP_PREDICATE)
  771. return nullptr;
  772. // max (min X, 42), 41 --> X > 41 ? 42 : 41
  773. // min (max X, 42), 43 --> X < 43 ? 42 : 43
  774. Value *Cmp = Builder.CreateICmp(Pred, X, I1);
  775. return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
  776. }
  777. /// Reduce a sequence of min/max intrinsics with a common operand.
  778. static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
  779. // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
  780. auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
  781. auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
  782. Intrinsic::ID MinMaxID = II->getIntrinsicID();
  783. if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
  784. RHS->getIntrinsicID() != MinMaxID ||
  785. (!LHS->hasOneUse() && !RHS->hasOneUse()))
  786. return nullptr;
  787. Value *A = LHS->getArgOperand(0);
  788. Value *B = LHS->getArgOperand(1);
  789. Value *C = RHS->getArgOperand(0);
  790. Value *D = RHS->getArgOperand(1);
  791. // Look for a common operand.
  792. Value *MinMaxOp = nullptr;
  793. Value *ThirdOp = nullptr;
  794. if (LHS->hasOneUse()) {
  795. // If the LHS is only used in this chain and the RHS is used outside of it,
  796. // reuse the RHS min/max because that will eliminate the LHS.
  797. if (D == A || C == A) {
  798. // min(min(a, b), min(c, a)) --> min(min(c, a), b)
  799. // min(min(a, b), min(a, d)) --> min(min(a, d), b)
  800. MinMaxOp = RHS;
  801. ThirdOp = B;
  802. } else if (D == B || C == B) {
  803. // min(min(a, b), min(c, b)) --> min(min(c, b), a)
  804. // min(min(a, b), min(b, d)) --> min(min(b, d), a)
  805. MinMaxOp = RHS;
  806. ThirdOp = A;
  807. }
  808. } else {
  809. assert(RHS->hasOneUse() && "Expected one-use operand");
  810. // Reuse the LHS. This will eliminate the RHS.
  811. if (D == A || D == B) {
  812. // min(min(a, b), min(c, a)) --> min(min(a, b), c)
  813. // min(min(a, b), min(c, b)) --> min(min(a, b), c)
  814. MinMaxOp = LHS;
  815. ThirdOp = C;
  816. } else if (C == A || C == B) {
  817. // min(min(a, b), min(b, d)) --> min(min(a, b), d)
  818. // min(min(a, b), min(c, b)) --> min(min(a, b), d)
  819. MinMaxOp = LHS;
  820. ThirdOp = D;
  821. }
  822. }
  823. if (!MinMaxOp || !ThirdOp)
  824. return nullptr;
  825. Module *Mod = II->getModule();
  826. Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
  827. return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
  828. }
  829. /// CallInst simplification. This mostly only handles folding of intrinsic
  830. /// instructions. For normal calls, it allows visitCallBase to do the heavy
  831. /// lifting.
  832. Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
  833. // Don't try to simplify calls without uses. It will not do anything useful,
  834. // but will result in the following folds being skipped.
  835. if (!CI.use_empty())
  836. if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
  837. return replaceInstUsesWith(CI, V);
  838. if (isFreeCall(&CI, &TLI))
  839. return visitFree(CI);
  840. // If the caller function is nounwind, mark the call as nounwind, even if the
  841. // callee isn't.
  842. if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
  843. CI.setDoesNotThrow();
  844. return &CI;
  845. }
  846. IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
  847. if (!II) return visitCallBase(CI);
  848. // For atomic unordered mem intrinsics if len is not a positive or
  849. // not a multiple of element size then behavior is undefined.
  850. if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
  851. if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
  852. if (NumBytes->getSExtValue() < 0 ||
  853. (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
  854. CreateNonTerminatorUnreachable(AMI);
  855. assert(AMI->getType()->isVoidTy() &&
  856. "non void atomic unordered mem intrinsic");
  857. return eraseInstFromFunction(*AMI);
  858. }
  859. // Intrinsics cannot occur in an invoke or a callbr, so handle them here
  860. // instead of in visitCallBase.
  861. if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
  862. bool Changed = false;
  863. // memmove/cpy/set of zero bytes is a noop.
  864. if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
  865. if (NumBytes->isNullValue())
  866. return eraseInstFromFunction(CI);
  867. if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
  868. if (CI->getZExtValue() == 1) {
  869. // Replace the instruction with just byte operations. We would
  870. // transform other cases to loads/stores, but we don't know if
  871. // alignment is sufficient.
  872. }
  873. }
  874. // No other transformations apply to volatile transfers.
  875. if (auto *M = dyn_cast<MemIntrinsic>(MI))
  876. if (M->isVolatile())
  877. return nullptr;
  878. // If we have a memmove and the source operation is a constant global,
  879. // then the source and dest pointers can't alias, so we can change this
  880. // into a call to memcpy.
  881. if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
  882. if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
  883. if (GVSrc->isConstant()) {
  884. Module *M = CI.getModule();
  885. Intrinsic::ID MemCpyID =
  886. isa<AtomicMemMoveInst>(MMI)
  887. ? Intrinsic::memcpy_element_unordered_atomic
  888. : Intrinsic::memcpy;
  889. Type *Tys[3] = { CI.getArgOperand(0)->getType(),
  890. CI.getArgOperand(1)->getType(),
  891. CI.getArgOperand(2)->getType() };
  892. CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
  893. Changed = true;
  894. }
  895. }
  896. if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
  897. // memmove(x,x,size) -> noop.
  898. if (MTI->getSource() == MTI->getDest())
  899. return eraseInstFromFunction(CI);
  900. }
  901. // If we can determine a pointer alignment that is bigger than currently
  902. // set, update the alignment.
  903. if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
  904. if (Instruction *I = SimplifyAnyMemTransfer(MTI))
  905. return I;
  906. } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
  907. if (Instruction *I = SimplifyAnyMemSet(MSI))
  908. return I;
  909. }
  910. if (Changed) return II;
  911. }
  912. // For fixed width vector result intrinsics, use the generic demanded vector
  913. // support.
  914. if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
  915. auto VWidth = IIFVTy->getNumElements();
  916. APInt UndefElts(VWidth, 0);
  917. APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
  918. if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
  919. if (V != II)
  920. return replaceInstUsesWith(*II, V);
  921. return II;
  922. }
  923. }
  924. if (II->isCommutative()) {
  925. if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
  926. return NewCall;
  927. }
  928. Intrinsic::ID IID = II->getIntrinsicID();
  929. switch (IID) {
  930. case Intrinsic::objectsize:
  931. if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
  932. return replaceInstUsesWith(CI, V);
  933. return nullptr;
  934. case Intrinsic::abs: {
  935. Value *IIOperand = II->getArgOperand(0);
  936. bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
  937. // abs(-x) -> abs(x)
  938. // TODO: Copy nsw if it was present on the neg?
  939. Value *X;
  940. if (match(IIOperand, m_Neg(m_Value(X))))
  941. return replaceOperand(*II, 0, X);
  942. if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
  943. return replaceOperand(*II, 0, X);
  944. if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
  945. return replaceOperand(*II, 0, X);
  946. if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
  947. // abs(x) -> x if x >= 0
  948. if (!*Sign)
  949. return replaceInstUsesWith(*II, IIOperand);
  950. // abs(x) -> -x if x < 0
  951. if (IntMinIsPoison)
  952. return BinaryOperator::CreateNSWNeg(IIOperand);
  953. return BinaryOperator::CreateNeg(IIOperand);
  954. }
  955. // abs (sext X) --> zext (abs X*)
  956. // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
  957. if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
  958. Value *NarrowAbs =
  959. Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
  960. return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
  961. }
  962. // Match a complicated way to check if a number is odd/even:
  963. // abs (srem X, 2) --> and X, 1
  964. const APInt *C;
  965. if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
  966. return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
  967. break;
  968. }
  969. case Intrinsic::umin: {
  970. Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
  971. // umin(x, 1) == zext(x != 0)
  972. if (match(I1, m_One())) {
  973. Value *Zero = Constant::getNullValue(I0->getType());
  974. Value *Cmp = Builder.CreateICmpNE(I0, Zero);
  975. return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
  976. }
  977. LLVM_FALLTHROUGH;
  978. }
  979. case Intrinsic::umax: {
  980. Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
  981. Value *X, *Y;
  982. if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
  983. (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
  984. Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
  985. return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
  986. }
  987. Constant *C;
  988. if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
  989. I0->hasOneUse()) {
  990. Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
  991. if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
  992. Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
  993. return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
  994. }
  995. }
  996. // If both operands of unsigned min/max are sign-extended, it is still ok
  997. // to narrow the operation.
  998. LLVM_FALLTHROUGH;
  999. }
  1000. case Intrinsic::smax:
  1001. case Intrinsic::smin: {
  1002. Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
  1003. Value *X, *Y;
  1004. if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
  1005. (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
  1006. Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
  1007. return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
  1008. }
  1009. Constant *C;
  1010. if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
  1011. I0->hasOneUse()) {
  1012. Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
  1013. if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
  1014. Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
  1015. return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
  1016. }
  1017. }
  1018. if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
  1019. // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
  1020. // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
  1021. // TODO: Canonicalize neg after min/max if I1 is constant.
  1022. if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
  1023. (I0->hasOneUse() || I1->hasOneUse())) {
  1024. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
  1025. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
  1026. return BinaryOperator::CreateNSWNeg(InvMaxMin);
  1027. }
  1028. }
  1029. // If we can eliminate ~A and Y is free to invert:
  1030. // max ~A, Y --> ~(min A, ~Y)
  1031. //
  1032. // Examples:
  1033. // max ~A, ~Y --> ~(min A, Y)
  1034. // max ~A, C --> ~(min A, ~C)
  1035. // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
  1036. auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
  1037. Value *A;
  1038. if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
  1039. !isFreeToInvert(A, A->hasOneUse()) &&
  1040. isFreeToInvert(Y, Y->hasOneUse())) {
  1041. Value *NotY = Builder.CreateNot(Y);
  1042. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
  1043. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
  1044. return BinaryOperator::CreateNot(InvMaxMin);
  1045. }
  1046. return nullptr;
  1047. };
  1048. if (Instruction *I = moveNotAfterMinMax(I0, I1))
  1049. return I;
  1050. if (Instruction *I = moveNotAfterMinMax(I1, I0))
  1051. return I;
  1052. if (Instruction *I = moveAddAfterMinMax(II, Builder))
  1053. return I;
  1054. // smax(X, -X) --> abs(X)
  1055. // smin(X, -X) --> -abs(X)
  1056. // umax(X, -X) --> -abs(X)
  1057. // umin(X, -X) --> abs(X)
  1058. if (isKnownNegation(I0, I1)) {
  1059. // We can choose either operand as the input to abs(), but if we can
  1060. // eliminate the only use of a value, that's better for subsequent
  1061. // transforms/analysis.
  1062. if (I0->hasOneUse() && !I1->hasOneUse())
  1063. std::swap(I0, I1);
  1064. // This is some variant of abs(). See if we can propagate 'nsw' to the abs
  1065. // operation and potentially its negation.
  1066. bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
  1067. Value *Abs = Builder.CreateBinaryIntrinsic(
  1068. Intrinsic::abs, I0,
  1069. ConstantInt::getBool(II->getContext(), IntMinIsPoison));
  1070. // We don't have a "nabs" intrinsic, so negate if needed based on the
  1071. // max/min operation.
  1072. if (IID == Intrinsic::smin || IID == Intrinsic::umax)
  1073. Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
  1074. return replaceInstUsesWith(CI, Abs);
  1075. }
  1076. if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
  1077. return Sel;
  1078. if (Instruction *SAdd = matchSAddSubSat(*II))
  1079. return SAdd;
  1080. if (match(I1, m_ImmConstant()))
  1081. if (auto *Sel = dyn_cast<SelectInst>(I0))
  1082. if (Instruction *R = FoldOpIntoSelect(*II, Sel))
  1083. return R;
  1084. if (Instruction *NewMinMax = factorizeMinMaxTree(II))
  1085. return NewMinMax;
  1086. break;
  1087. }
  1088. case Intrinsic::bswap: {
  1089. Value *IIOperand = II->getArgOperand(0);
  1090. Value *X = nullptr;
  1091. KnownBits Known = computeKnownBits(IIOperand, 0, II);
  1092. uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
  1093. uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
  1094. // bswap(x) -> shift(x) if x has exactly one "active byte"
  1095. if (Known.getBitWidth() - LZ - TZ == 8) {
  1096. assert(LZ != TZ && "active byte cannot be in the middle");
  1097. if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
  1098. return BinaryOperator::CreateNUWShl(
  1099. IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
  1100. // -> lshr(x) if the "active byte" is in the high part of x
  1101. return BinaryOperator::CreateExactLShr(
  1102. IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
  1103. }
  1104. // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
  1105. if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
  1106. unsigned C = X->getType()->getScalarSizeInBits() -
  1107. IIOperand->getType()->getScalarSizeInBits();
  1108. Value *CV = ConstantInt::get(X->getType(), C);
  1109. Value *V = Builder.CreateLShr(X, CV);
  1110. return new TruncInst(V, IIOperand->getType());
  1111. }
  1112. break;
  1113. }
  1114. case Intrinsic::masked_load:
  1115. if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
  1116. return replaceInstUsesWith(CI, SimplifiedMaskedOp);
  1117. break;
  1118. case Intrinsic::masked_store:
  1119. return simplifyMaskedStore(*II);
  1120. case Intrinsic::masked_gather:
  1121. return simplifyMaskedGather(*II);
  1122. case Intrinsic::masked_scatter:
  1123. return simplifyMaskedScatter(*II);
  1124. case Intrinsic::launder_invariant_group:
  1125. case Intrinsic::strip_invariant_group:
  1126. if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
  1127. return replaceInstUsesWith(*II, SkippedBarrier);
  1128. break;
  1129. case Intrinsic::powi:
  1130. if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
  1131. // 0 and 1 are handled in instsimplify
  1132. // powi(x, -1) -> 1/x
  1133. if (Power->isMinusOne())
  1134. return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
  1135. II->getArgOperand(0), II);
  1136. // powi(x, 2) -> x*x
  1137. if (Power->equalsInt(2))
  1138. return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
  1139. II->getArgOperand(0), II);
  1140. if (!Power->getValue()[0]) {
  1141. Value *X;
  1142. // If power is even:
  1143. // powi(-x, p) -> powi(x, p)
  1144. // powi(fabs(x), p) -> powi(x, p)
  1145. // powi(copysign(x, y), p) -> powi(x, p)
  1146. if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
  1147. match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
  1148. match(II->getArgOperand(0),
  1149. m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
  1150. return replaceOperand(*II, 0, X);
  1151. }
  1152. }
  1153. break;
  1154. case Intrinsic::cttz:
  1155. case Intrinsic::ctlz:
  1156. if (auto *I = foldCttzCtlz(*II, *this))
  1157. return I;
  1158. break;
  1159. case Intrinsic::ctpop:
  1160. if (auto *I = foldCtpop(*II, *this))
  1161. return I;
  1162. break;
  1163. case Intrinsic::fshl:
  1164. case Intrinsic::fshr: {
  1165. Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
  1166. Type *Ty = II->getType();
  1167. unsigned BitWidth = Ty->getScalarSizeInBits();
  1168. Constant *ShAmtC;
  1169. if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
  1170. !ShAmtC->containsConstantExpression()) {
  1171. // Canonicalize a shift amount constant operand to modulo the bit-width.
  1172. Constant *WidthC = ConstantInt::get(Ty, BitWidth);
  1173. Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
  1174. if (ModuloC != ShAmtC)
  1175. return replaceOperand(*II, 2, ModuloC);
  1176. assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
  1177. ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
  1178. "Shift amount expected to be modulo bitwidth");
  1179. // Canonicalize funnel shift right by constant to funnel shift left. This
  1180. // is not entirely arbitrary. For historical reasons, the backend may
  1181. // recognize rotate left patterns but miss rotate right patterns.
  1182. if (IID == Intrinsic::fshr) {
  1183. // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
  1184. Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
  1185. Module *Mod = II->getModule();
  1186. Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
  1187. return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
  1188. }
  1189. assert(IID == Intrinsic::fshl &&
  1190. "All funnel shifts by simple constants should go left");
  1191. // fshl(X, 0, C) --> shl X, C
  1192. // fshl(X, undef, C) --> shl X, C
  1193. if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
  1194. return BinaryOperator::CreateShl(Op0, ShAmtC);
  1195. // fshl(0, X, C) --> lshr X, (BW-C)
  1196. // fshl(undef, X, C) --> lshr X, (BW-C)
  1197. if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
  1198. return BinaryOperator::CreateLShr(Op1,
  1199. ConstantExpr::getSub(WidthC, ShAmtC));
  1200. // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
  1201. if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
  1202. Module *Mod = II->getModule();
  1203. Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
  1204. return CallInst::Create(Bswap, { Op0 });
  1205. }
  1206. }
  1207. // Left or right might be masked.
  1208. if (SimplifyDemandedInstructionBits(*II))
  1209. return &CI;
  1210. // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
  1211. // so only the low bits of the shift amount are demanded if the bitwidth is
  1212. // a power-of-2.
  1213. if (!isPowerOf2_32(BitWidth))
  1214. break;
  1215. APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
  1216. KnownBits Op2Known(BitWidth);
  1217. if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
  1218. return &CI;
  1219. break;
  1220. }
  1221. case Intrinsic::uadd_with_overflow:
  1222. case Intrinsic::sadd_with_overflow: {
  1223. if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
  1224. return I;
  1225. // Given 2 constant operands whose sum does not overflow:
  1226. // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
  1227. // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
  1228. Value *X;
  1229. const APInt *C0, *C1;
  1230. Value *Arg0 = II->getArgOperand(0);
  1231. Value *Arg1 = II->getArgOperand(1);
  1232. bool IsSigned = IID == Intrinsic::sadd_with_overflow;
  1233. bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
  1234. : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
  1235. if (HasNWAdd && match(Arg1, m_APInt(C1))) {
  1236. bool Overflow;
  1237. APInt NewC =
  1238. IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
  1239. if (!Overflow)
  1240. return replaceInstUsesWith(
  1241. *II, Builder.CreateBinaryIntrinsic(
  1242. IID, X, ConstantInt::get(Arg1->getType(), NewC)));
  1243. }
  1244. break;
  1245. }
  1246. case Intrinsic::umul_with_overflow:
  1247. case Intrinsic::smul_with_overflow:
  1248. case Intrinsic::usub_with_overflow:
  1249. if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
  1250. return I;
  1251. break;
  1252. case Intrinsic::ssub_with_overflow: {
  1253. if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
  1254. return I;
  1255. Constant *C;
  1256. Value *Arg0 = II->getArgOperand(0);
  1257. Value *Arg1 = II->getArgOperand(1);
  1258. // Given a constant C that is not the minimum signed value
  1259. // for an integer of a given bit width:
  1260. //
  1261. // ssubo X, C -> saddo X, -C
  1262. if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
  1263. Value *NegVal = ConstantExpr::getNeg(C);
  1264. // Build a saddo call that is equivalent to the discovered
  1265. // ssubo call.
  1266. return replaceInstUsesWith(
  1267. *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
  1268. Arg0, NegVal));
  1269. }
  1270. break;
  1271. }
  1272. case Intrinsic::uadd_sat:
  1273. case Intrinsic::sadd_sat:
  1274. case Intrinsic::usub_sat:
  1275. case Intrinsic::ssub_sat: {
  1276. SaturatingInst *SI = cast<SaturatingInst>(II);
  1277. Type *Ty = SI->getType();
  1278. Value *Arg0 = SI->getLHS();
  1279. Value *Arg1 = SI->getRHS();
  1280. // Make use of known overflow information.
  1281. OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
  1282. Arg0, Arg1, SI);
  1283. switch (OR) {
  1284. case OverflowResult::MayOverflow:
  1285. break;
  1286. case OverflowResult::NeverOverflows:
  1287. if (SI->isSigned())
  1288. return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
  1289. else
  1290. return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
  1291. case OverflowResult::AlwaysOverflowsLow: {
  1292. unsigned BitWidth = Ty->getScalarSizeInBits();
  1293. APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
  1294. return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
  1295. }
  1296. case OverflowResult::AlwaysOverflowsHigh: {
  1297. unsigned BitWidth = Ty->getScalarSizeInBits();
  1298. APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
  1299. return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
  1300. }
  1301. }
  1302. // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
  1303. Constant *C;
  1304. if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
  1305. C->isNotMinSignedValue()) {
  1306. Value *NegVal = ConstantExpr::getNeg(C);
  1307. return replaceInstUsesWith(
  1308. *II, Builder.CreateBinaryIntrinsic(
  1309. Intrinsic::sadd_sat, Arg0, NegVal));
  1310. }
  1311. // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
  1312. // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
  1313. // if Val and Val2 have the same sign
  1314. if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
  1315. Value *X;
  1316. const APInt *Val, *Val2;
  1317. APInt NewVal;
  1318. bool IsUnsigned =
  1319. IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
  1320. if (Other->getIntrinsicID() == IID &&
  1321. match(Arg1, m_APInt(Val)) &&
  1322. match(Other->getArgOperand(0), m_Value(X)) &&
  1323. match(Other->getArgOperand(1), m_APInt(Val2))) {
  1324. if (IsUnsigned)
  1325. NewVal = Val->uadd_sat(*Val2);
  1326. else if (Val->isNonNegative() == Val2->isNonNegative()) {
  1327. bool Overflow;
  1328. NewVal = Val->sadd_ov(*Val2, Overflow);
  1329. if (Overflow) {
  1330. // Both adds together may add more than SignedMaxValue
  1331. // without saturating the final result.
  1332. break;
  1333. }
  1334. } else {
  1335. // Cannot fold saturated addition with different signs.
  1336. break;
  1337. }
  1338. return replaceInstUsesWith(
  1339. *II, Builder.CreateBinaryIntrinsic(
  1340. IID, X, ConstantInt::get(II->getType(), NewVal)));
  1341. }
  1342. }
  1343. break;
  1344. }
  1345. case Intrinsic::minnum:
  1346. case Intrinsic::maxnum:
  1347. case Intrinsic::minimum:
  1348. case Intrinsic::maximum: {
  1349. Value *Arg0 = II->getArgOperand(0);
  1350. Value *Arg1 = II->getArgOperand(1);
  1351. Value *X, *Y;
  1352. if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
  1353. (Arg0->hasOneUse() || Arg1->hasOneUse())) {
  1354. // If both operands are negated, invert the call and negate the result:
  1355. // min(-X, -Y) --> -(max(X, Y))
  1356. // max(-X, -Y) --> -(min(X, Y))
  1357. Intrinsic::ID NewIID;
  1358. switch (IID) {
  1359. case Intrinsic::maxnum:
  1360. NewIID = Intrinsic::minnum;
  1361. break;
  1362. case Intrinsic::minnum:
  1363. NewIID = Intrinsic::maxnum;
  1364. break;
  1365. case Intrinsic::maximum:
  1366. NewIID = Intrinsic::minimum;
  1367. break;
  1368. case Intrinsic::minimum:
  1369. NewIID = Intrinsic::maximum;
  1370. break;
  1371. default:
  1372. llvm_unreachable("unexpected intrinsic ID");
  1373. }
  1374. Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
  1375. Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
  1376. FNeg->copyIRFlags(II);
  1377. return FNeg;
  1378. }
  1379. // m(m(X, C2), C1) -> m(X, C)
  1380. const APFloat *C1, *C2;
  1381. if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
  1382. if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
  1383. ((match(M->getArgOperand(0), m_Value(X)) &&
  1384. match(M->getArgOperand(1), m_APFloat(C2))) ||
  1385. (match(M->getArgOperand(1), m_Value(X)) &&
  1386. match(M->getArgOperand(0), m_APFloat(C2))))) {
  1387. APFloat Res(0.0);
  1388. switch (IID) {
  1389. case Intrinsic::maxnum:
  1390. Res = maxnum(*C1, *C2);
  1391. break;
  1392. case Intrinsic::minnum:
  1393. Res = minnum(*C1, *C2);
  1394. break;
  1395. case Intrinsic::maximum:
  1396. Res = maximum(*C1, *C2);
  1397. break;
  1398. case Intrinsic::minimum:
  1399. Res = minimum(*C1, *C2);
  1400. break;
  1401. default:
  1402. llvm_unreachable("unexpected intrinsic ID");
  1403. }
  1404. Instruction *NewCall = Builder.CreateBinaryIntrinsic(
  1405. IID, X, ConstantFP::get(Arg0->getType(), Res), II);
  1406. // TODO: Conservatively intersecting FMF. If Res == C2, the transform
  1407. // was a simplification (so Arg0 and its original flags could
  1408. // propagate?)
  1409. NewCall->andIRFlags(M);
  1410. return replaceInstUsesWith(*II, NewCall);
  1411. }
  1412. }
  1413. // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
  1414. if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
  1415. match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
  1416. X->getType() == Y->getType()) {
  1417. Value *NewCall =
  1418. Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
  1419. return new FPExtInst(NewCall, II->getType());
  1420. }
  1421. // max X, -X --> fabs X
  1422. // min X, -X --> -(fabs X)
  1423. // TODO: Remove one-use limitation? That is obviously better for max.
  1424. // It would be an extra instruction for min (fnabs), but that is
  1425. // still likely better for analysis and codegen.
  1426. if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
  1427. (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
  1428. Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
  1429. if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
  1430. R = Builder.CreateFNegFMF(R, II);
  1431. return replaceInstUsesWith(*II, R);
  1432. }
  1433. break;
  1434. }
  1435. case Intrinsic::fmuladd: {
  1436. // Canonicalize fast fmuladd to the separate fmul + fadd.
  1437. if (II->isFast()) {
  1438. BuilderTy::FastMathFlagGuard Guard(Builder);
  1439. Builder.setFastMathFlags(II->getFastMathFlags());
  1440. Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
  1441. II->getArgOperand(1));
  1442. Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
  1443. Add->takeName(II);
  1444. return replaceInstUsesWith(*II, Add);
  1445. }
  1446. // Try to simplify the underlying FMul.
  1447. if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
  1448. II->getFastMathFlags(),
  1449. SQ.getWithInstruction(II))) {
  1450. auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
  1451. FAdd->copyFastMathFlags(II);
  1452. return FAdd;
  1453. }
  1454. LLVM_FALLTHROUGH;
  1455. }
  1456. case Intrinsic::fma: {
  1457. // fma fneg(x), fneg(y), z -> fma x, y, z
  1458. Value *Src0 = II->getArgOperand(0);
  1459. Value *Src1 = II->getArgOperand(1);
  1460. Value *X, *Y;
  1461. if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
  1462. replaceOperand(*II, 0, X);
  1463. replaceOperand(*II, 1, Y);
  1464. return II;
  1465. }
  1466. // fma fabs(x), fabs(x), z -> fma x, x, z
  1467. if (match(Src0, m_FAbs(m_Value(X))) &&
  1468. match(Src1, m_FAbs(m_Specific(X)))) {
  1469. replaceOperand(*II, 0, X);
  1470. replaceOperand(*II, 1, X);
  1471. return II;
  1472. }
  1473. // Try to simplify the underlying FMul. We can only apply simplifications
  1474. // that do not require rounding.
  1475. if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
  1476. II->getFastMathFlags(),
  1477. SQ.getWithInstruction(II))) {
  1478. auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
  1479. FAdd->copyFastMathFlags(II);
  1480. return FAdd;
  1481. }
  1482. // fma x, y, 0 -> fmul x, y
  1483. // This is always valid for -0.0, but requires nsz for +0.0 as
  1484. // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
  1485. if (match(II->getArgOperand(2), m_NegZeroFP()) ||
  1486. (match(II->getArgOperand(2), m_PosZeroFP()) &&
  1487. II->getFastMathFlags().noSignedZeros()))
  1488. return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
  1489. break;
  1490. }
  1491. case Intrinsic::copysign: {
  1492. Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
  1493. if (SignBitMustBeZero(Sign, &TLI)) {
  1494. // If we know that the sign argument is positive, reduce to FABS:
  1495. // copysign Mag, +Sign --> fabs Mag
  1496. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
  1497. return replaceInstUsesWith(*II, Fabs);
  1498. }
  1499. // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
  1500. const APFloat *C;
  1501. if (match(Sign, m_APFloat(C)) && C->isNegative()) {
  1502. // If we know that the sign argument is negative, reduce to FNABS:
  1503. // copysign Mag, -Sign --> fneg (fabs Mag)
  1504. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
  1505. return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
  1506. }
  1507. // Propagate sign argument through nested calls:
  1508. // copysign Mag, (copysign ?, X) --> copysign Mag, X
  1509. Value *X;
  1510. if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
  1511. return replaceOperand(*II, 1, X);
  1512. // Peek through changes of magnitude's sign-bit. This call rewrites those:
  1513. // copysign (fabs X), Sign --> copysign X, Sign
  1514. // copysign (fneg X), Sign --> copysign X, Sign
  1515. if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
  1516. return replaceOperand(*II, 0, X);
  1517. break;
  1518. }
  1519. case Intrinsic::fabs: {
  1520. Value *Cond, *TVal, *FVal;
  1521. if (match(II->getArgOperand(0),
  1522. m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
  1523. // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
  1524. if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
  1525. CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
  1526. CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
  1527. return SelectInst::Create(Cond, AbsT, AbsF);
  1528. }
  1529. // fabs (select Cond, -FVal, FVal) --> fabs FVal
  1530. if (match(TVal, m_FNeg(m_Specific(FVal))))
  1531. return replaceOperand(*II, 0, FVal);
  1532. // fabs (select Cond, TVal, -TVal) --> fabs TVal
  1533. if (match(FVal, m_FNeg(m_Specific(TVal))))
  1534. return replaceOperand(*II, 0, TVal);
  1535. }
  1536. LLVM_FALLTHROUGH;
  1537. }
  1538. case Intrinsic::ceil:
  1539. case Intrinsic::floor:
  1540. case Intrinsic::round:
  1541. case Intrinsic::roundeven:
  1542. case Intrinsic::nearbyint:
  1543. case Intrinsic::rint:
  1544. case Intrinsic::trunc: {
  1545. Value *ExtSrc;
  1546. if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
  1547. // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
  1548. Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
  1549. return new FPExtInst(NarrowII, II->getType());
  1550. }
  1551. break;
  1552. }
  1553. case Intrinsic::cos:
  1554. case Intrinsic::amdgcn_cos: {
  1555. Value *X;
  1556. Value *Src = II->getArgOperand(0);
  1557. if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
  1558. // cos(-x) -> cos(x)
  1559. // cos(fabs(x)) -> cos(x)
  1560. return replaceOperand(*II, 0, X);
  1561. }
  1562. break;
  1563. }
  1564. case Intrinsic::sin: {
  1565. Value *X;
  1566. if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
  1567. // sin(-x) --> -sin(x)
  1568. Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
  1569. Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
  1570. FNeg->copyFastMathFlags(II);
  1571. return FNeg;
  1572. }
  1573. break;
  1574. }
  1575. case Intrinsic::arm_neon_vtbl1:
  1576. case Intrinsic::aarch64_neon_tbl1:
  1577. if (Value *V = simplifyNeonTbl1(*II, Builder))
  1578. return replaceInstUsesWith(*II, V);
  1579. break;
  1580. case Intrinsic::arm_neon_vmulls:
  1581. case Intrinsic::arm_neon_vmullu:
  1582. case Intrinsic::aarch64_neon_smull:
  1583. case Intrinsic::aarch64_neon_umull: {
  1584. Value *Arg0 = II->getArgOperand(0);
  1585. Value *Arg1 = II->getArgOperand(1);
  1586. // Handle mul by zero first:
  1587. if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
  1588. return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
  1589. }
  1590. // Check for constant LHS & RHS - in this case we just simplify.
  1591. bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
  1592. IID == Intrinsic::aarch64_neon_umull);
  1593. VectorType *NewVT = cast<VectorType>(II->getType());
  1594. if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
  1595. if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
  1596. CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
  1597. CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
  1598. return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
  1599. }
  1600. // Couldn't simplify - canonicalize constant to the RHS.
  1601. std::swap(Arg0, Arg1);
  1602. }
  1603. // Handle mul by one:
  1604. if (Constant *CV1 = dyn_cast<Constant>(Arg1))
  1605. if (ConstantInt *Splat =
  1606. dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
  1607. if (Splat->isOne())
  1608. return CastInst::CreateIntegerCast(Arg0, II->getType(),
  1609. /*isSigned=*/!Zext);
  1610. break;
  1611. }
  1612. case Intrinsic::arm_neon_aesd:
  1613. case Intrinsic::arm_neon_aese:
  1614. case Intrinsic::aarch64_crypto_aesd:
  1615. case Intrinsic::aarch64_crypto_aese: {
  1616. Value *DataArg = II->getArgOperand(0);
  1617. Value *KeyArg = II->getArgOperand(1);
  1618. // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
  1619. Value *Data, *Key;
  1620. if (match(KeyArg, m_ZeroInt()) &&
  1621. match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
  1622. replaceOperand(*II, 0, Data);
  1623. replaceOperand(*II, 1, Key);
  1624. return II;
  1625. }
  1626. break;
  1627. }
  1628. case Intrinsic::hexagon_V6_vandvrt:
  1629. case Intrinsic::hexagon_V6_vandvrt_128B: {
  1630. // Simplify Q -> V -> Q conversion.
  1631. if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
  1632. Intrinsic::ID ID0 = Op0->getIntrinsicID();
  1633. if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
  1634. ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
  1635. break;
  1636. Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
  1637. uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
  1638. uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
  1639. // Check if every byte has common bits in Bytes and Mask.
  1640. uint64_t C = Bytes1 & Mask1;
  1641. if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
  1642. return replaceInstUsesWith(*II, Op0->getArgOperand(0));
  1643. }
  1644. break;
  1645. }
  1646. case Intrinsic::stackrestore: {
  1647. enum class ClassifyResult {
  1648. None,
  1649. Alloca,
  1650. StackRestore,
  1651. CallWithSideEffects,
  1652. };
  1653. auto Classify = [](const Instruction *I) {
  1654. if (isa<AllocaInst>(I))
  1655. return ClassifyResult::Alloca;
  1656. if (auto *CI = dyn_cast<CallInst>(I)) {
  1657. if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
  1658. if (II->getIntrinsicID() == Intrinsic::stackrestore)
  1659. return ClassifyResult::StackRestore;
  1660. if (II->mayHaveSideEffects())
  1661. return ClassifyResult::CallWithSideEffects;
  1662. } else {
  1663. // Consider all non-intrinsic calls to be side effects
  1664. return ClassifyResult::CallWithSideEffects;
  1665. }
  1666. }
  1667. return ClassifyResult::None;
  1668. };
  1669. // If the stacksave and the stackrestore are in the same BB, and there is
  1670. // no intervening call, alloca, or stackrestore of a different stacksave,
  1671. // remove the restore. This can happen when variable allocas are DCE'd.
  1672. if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
  1673. if (SS->getIntrinsicID() == Intrinsic::stacksave &&
  1674. SS->getParent() == II->getParent()) {
  1675. BasicBlock::iterator BI(SS);
  1676. bool CannotRemove = false;
  1677. for (++BI; &*BI != II; ++BI) {
  1678. switch (Classify(&*BI)) {
  1679. case ClassifyResult::None:
  1680. // So far so good, look at next instructions.
  1681. break;
  1682. case ClassifyResult::StackRestore:
  1683. // If we found an intervening stackrestore for a different
  1684. // stacksave, we can't remove the stackrestore. Otherwise, continue.
  1685. if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
  1686. CannotRemove = true;
  1687. break;
  1688. case ClassifyResult::Alloca:
  1689. case ClassifyResult::CallWithSideEffects:
  1690. // If we found an alloca, a non-intrinsic call, or an intrinsic
  1691. // call with side effects, we can't remove the stackrestore.
  1692. CannotRemove = true;
  1693. break;
  1694. }
  1695. if (CannotRemove)
  1696. break;
  1697. }
  1698. if (!CannotRemove)
  1699. return eraseInstFromFunction(CI);
  1700. }
  1701. }
  1702. // Scan down this block to see if there is another stack restore in the
  1703. // same block without an intervening call/alloca.
  1704. BasicBlock::iterator BI(II);
  1705. Instruction *TI = II->getParent()->getTerminator();
  1706. bool CannotRemove = false;
  1707. for (++BI; &*BI != TI; ++BI) {
  1708. switch (Classify(&*BI)) {
  1709. case ClassifyResult::None:
  1710. // So far so good, look at next instructions.
  1711. break;
  1712. case ClassifyResult::StackRestore:
  1713. // If there is a stackrestore below this one, remove this one.
  1714. return eraseInstFromFunction(CI);
  1715. case ClassifyResult::Alloca:
  1716. case ClassifyResult::CallWithSideEffects:
  1717. // If we found an alloca, a non-intrinsic call, or an intrinsic call
  1718. // with side effects (such as llvm.stacksave and llvm.read_register),
  1719. // we can't remove the stack restore.
  1720. CannotRemove = true;
  1721. break;
  1722. }
  1723. if (CannotRemove)
  1724. break;
  1725. }
  1726. // If the stack restore is in a return, resume, or unwind block and if there
  1727. // are no allocas or calls between the restore and the return, nuke the
  1728. // restore.
  1729. if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
  1730. return eraseInstFromFunction(CI);
  1731. break;
  1732. }
  1733. case Intrinsic::lifetime_end:
  1734. // Asan needs to poison memory to detect invalid access which is possible
  1735. // even for empty lifetime range.
  1736. if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
  1737. II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
  1738. II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
  1739. break;
  1740. if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
  1741. return I.getIntrinsicID() == Intrinsic::lifetime_start;
  1742. }))
  1743. return nullptr;
  1744. break;
  1745. case Intrinsic::assume: {
  1746. Value *IIOperand = II->getArgOperand(0);
  1747. SmallVector<OperandBundleDef, 4> OpBundles;
  1748. II->getOperandBundlesAsDefs(OpBundles);
  1749. /// This will remove the boolean Condition from the assume given as
  1750. /// argument and remove the assume if it becomes useless.
  1751. /// always returns nullptr for use as a return values.
  1752. auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
  1753. assert(isa<AssumeInst>(Assume));
  1754. if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
  1755. return eraseInstFromFunction(CI);
  1756. replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
  1757. return nullptr;
  1758. };
  1759. // Remove an assume if it is followed by an identical assume.
  1760. // TODO: Do we need this? Unless there are conflicting assumptions, the
  1761. // computeKnownBits(IIOperand) below here eliminates redundant assumes.
  1762. Instruction *Next = II->getNextNonDebugInstruction();
  1763. if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
  1764. return RemoveConditionFromAssume(Next);
  1765. // Canonicalize assume(a && b) -> assume(a); assume(b);
  1766. // Note: New assumption intrinsics created here are registered by
  1767. // the InstCombineIRInserter object.
  1768. FunctionType *AssumeIntrinsicTy = II->getFunctionType();
  1769. Value *AssumeIntrinsic = II->getCalledOperand();
  1770. Value *A, *B;
  1771. if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
  1772. Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
  1773. II->getName());
  1774. Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
  1775. return eraseInstFromFunction(*II);
  1776. }
  1777. // assume(!(a || b)) -> assume(!a); assume(!b);
  1778. if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
  1779. Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
  1780. Builder.CreateNot(A), OpBundles, II->getName());
  1781. Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
  1782. Builder.CreateNot(B), II->getName());
  1783. return eraseInstFromFunction(*II);
  1784. }
  1785. // assume( (load addr) != null ) -> add 'nonnull' metadata to load
  1786. // (if assume is valid at the load)
  1787. CmpInst::Predicate Pred;
  1788. Instruction *LHS;
  1789. if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
  1790. Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
  1791. LHS->getType()->isPointerTy() &&
  1792. isValidAssumeForContext(II, LHS, &DT)) {
  1793. MDNode *MD = MDNode::get(II->getContext(), None);
  1794. LHS->setMetadata(LLVMContext::MD_nonnull, MD);
  1795. return RemoveConditionFromAssume(II);
  1796. // TODO: apply nonnull return attributes to calls and invokes
  1797. // TODO: apply range metadata for range check patterns?
  1798. }
  1799. // Convert nonnull assume like:
  1800. // %A = icmp ne i32* %PTR, null
  1801. // call void @llvm.assume(i1 %A)
  1802. // into
  1803. // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
  1804. if (EnableKnowledgeRetention &&
  1805. match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
  1806. Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
  1807. if (auto *Replacement = buildAssumeFromKnowledge(
  1808. {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
  1809. Replacement->insertBefore(Next);
  1810. AC.registerAssumption(Replacement);
  1811. return RemoveConditionFromAssume(II);
  1812. }
  1813. }
  1814. // Convert alignment assume like:
  1815. // %B = ptrtoint i32* %A to i64
  1816. // %C = and i64 %B, Constant
  1817. // %D = icmp eq i64 %C, 0
  1818. // call void @llvm.assume(i1 %D)
  1819. // into
  1820. // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
  1821. uint64_t AlignMask;
  1822. if (EnableKnowledgeRetention &&
  1823. match(IIOperand,
  1824. m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
  1825. m_Zero())) &&
  1826. Pred == CmpInst::ICMP_EQ) {
  1827. if (isPowerOf2_64(AlignMask + 1)) {
  1828. uint64_t Offset = 0;
  1829. match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
  1830. if (match(A, m_PtrToInt(m_Value(A)))) {
  1831. /// Note: this doesn't preserve the offset information but merges
  1832. /// offset and alignment.
  1833. /// TODO: we can generate a GEP instead of merging the alignment with
  1834. /// the offset.
  1835. RetainedKnowledge RK{Attribute::Alignment,
  1836. (unsigned)MinAlign(Offset, AlignMask + 1), A};
  1837. if (auto *Replacement =
  1838. buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
  1839. Replacement->insertAfter(II);
  1840. AC.registerAssumption(Replacement);
  1841. }
  1842. return RemoveConditionFromAssume(II);
  1843. }
  1844. }
  1845. }
  1846. /// Canonicalize Knowledge in operand bundles.
  1847. if (EnableKnowledgeRetention && II->hasOperandBundles()) {
  1848. for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
  1849. auto &BOI = II->bundle_op_info_begin()[Idx];
  1850. RetainedKnowledge RK =
  1851. llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
  1852. if (BOI.End - BOI.Begin > 2)
  1853. continue; // Prevent reducing knowledge in an align with offset since
  1854. // extracting a RetainedKnowledge form them looses offset
  1855. // information
  1856. RetainedKnowledge CanonRK =
  1857. llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
  1858. &getAssumptionCache(),
  1859. &getDominatorTree());
  1860. if (CanonRK == RK)
  1861. continue;
  1862. if (!CanonRK) {
  1863. if (BOI.End - BOI.Begin > 0) {
  1864. Worklist.pushValue(II->op_begin()[BOI.Begin]);
  1865. Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
  1866. }
  1867. continue;
  1868. }
  1869. assert(RK.AttrKind == CanonRK.AttrKind);
  1870. if (BOI.End - BOI.Begin > 0)
  1871. II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
  1872. if (BOI.End - BOI.Begin > 1)
  1873. II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
  1874. Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
  1875. if (RK.WasOn)
  1876. Worklist.pushValue(RK.WasOn);
  1877. return II;
  1878. }
  1879. }
  1880. // If there is a dominating assume with the same condition as this one,
  1881. // then this one is redundant, and should be removed.
  1882. KnownBits Known(1);
  1883. computeKnownBits(IIOperand, Known, 0, II);
  1884. if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
  1885. return eraseInstFromFunction(*II);
  1886. // Update the cache of affected values for this assumption (we might be
  1887. // here because we just simplified the condition).
  1888. AC.updateAffectedValues(cast<AssumeInst>(II));
  1889. break;
  1890. }
  1891. case Intrinsic::experimental_guard: {
  1892. // Is this guard followed by another guard? We scan forward over a small
  1893. // fixed window of instructions to handle common cases with conditions
  1894. // computed between guards.
  1895. Instruction *NextInst = II->getNextNonDebugInstruction();
  1896. for (unsigned i = 0; i < GuardWideningWindow; i++) {
  1897. // Note: Using context-free form to avoid compile time blow up
  1898. if (!isSafeToSpeculativelyExecute(NextInst))
  1899. break;
  1900. NextInst = NextInst->getNextNonDebugInstruction();
  1901. }
  1902. Value *NextCond = nullptr;
  1903. if (match(NextInst,
  1904. m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
  1905. Value *CurrCond = II->getArgOperand(0);
  1906. // Remove a guard that it is immediately preceded by an identical guard.
  1907. // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
  1908. if (CurrCond != NextCond) {
  1909. Instruction *MoveI = II->getNextNonDebugInstruction();
  1910. while (MoveI != NextInst) {
  1911. auto *Temp = MoveI;
  1912. MoveI = MoveI->getNextNonDebugInstruction();
  1913. Temp->moveBefore(II);
  1914. }
  1915. replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
  1916. }
  1917. eraseInstFromFunction(*NextInst);
  1918. return II;
  1919. }
  1920. break;
  1921. }
  1922. case Intrinsic::experimental_vector_insert: {
  1923. Value *Vec = II->getArgOperand(0);
  1924. Value *SubVec = II->getArgOperand(1);
  1925. Value *Idx = II->getArgOperand(2);
  1926. auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
  1927. auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
  1928. auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
  1929. // Only canonicalize if the destination vector, Vec, and SubVec are all
  1930. // fixed vectors.
  1931. if (DstTy && VecTy && SubVecTy) {
  1932. unsigned DstNumElts = DstTy->getNumElements();
  1933. unsigned VecNumElts = VecTy->getNumElements();
  1934. unsigned SubVecNumElts = SubVecTy->getNumElements();
  1935. unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
  1936. // An insert that entirely overwrites Vec with SubVec is a nop.
  1937. if (VecNumElts == SubVecNumElts)
  1938. return replaceInstUsesWith(CI, SubVec);
  1939. // Widen SubVec into a vector of the same width as Vec, since
  1940. // shufflevector requires the two input vectors to be the same width.
  1941. // Elements beyond the bounds of SubVec within the widened vector are
  1942. // undefined.
  1943. SmallVector<int, 8> WidenMask;
  1944. unsigned i;
  1945. for (i = 0; i != SubVecNumElts; ++i)
  1946. WidenMask.push_back(i);
  1947. for (; i != VecNumElts; ++i)
  1948. WidenMask.push_back(UndefMaskElem);
  1949. Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
  1950. SmallVector<int, 8> Mask;
  1951. for (unsigned i = 0; i != IdxN; ++i)
  1952. Mask.push_back(i);
  1953. for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
  1954. Mask.push_back(i);
  1955. for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
  1956. Mask.push_back(i);
  1957. Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
  1958. return replaceInstUsesWith(CI, Shuffle);
  1959. }
  1960. break;
  1961. }
  1962. case Intrinsic::experimental_vector_extract: {
  1963. Value *Vec = II->getArgOperand(0);
  1964. Value *Idx = II->getArgOperand(1);
  1965. auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
  1966. auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
  1967. // Only canonicalize if the the destination vector and Vec are fixed
  1968. // vectors.
  1969. if (DstTy && VecTy) {
  1970. unsigned DstNumElts = DstTy->getNumElements();
  1971. unsigned VecNumElts = VecTy->getNumElements();
  1972. unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
  1973. // Extracting the entirety of Vec is a nop.
  1974. if (VecNumElts == DstNumElts) {
  1975. replaceInstUsesWith(CI, Vec);
  1976. return eraseInstFromFunction(CI);
  1977. }
  1978. SmallVector<int, 8> Mask;
  1979. for (unsigned i = 0; i != DstNumElts; ++i)
  1980. Mask.push_back(IdxN + i);
  1981. Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
  1982. return replaceInstUsesWith(CI, Shuffle);
  1983. }
  1984. break;
  1985. }
  1986. case Intrinsic::experimental_vector_reverse: {
  1987. Value *BO0, *BO1, *X, *Y;
  1988. Value *Vec = II->getArgOperand(0);
  1989. if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
  1990. auto *OldBinOp = cast<BinaryOperator>(Vec);
  1991. if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
  1992. m_Value(X)))) {
  1993. // rev(binop rev(X), rev(Y)) --> binop X, Y
  1994. if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
  1995. m_Value(Y))))
  1996. return replaceInstUsesWith(CI,
  1997. BinaryOperator::CreateWithCopiedFlags(
  1998. OldBinOp->getOpcode(), X, Y, OldBinOp,
  1999. OldBinOp->getName(), II));
  2000. // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
  2001. if (isSplatValue(BO1))
  2002. return replaceInstUsesWith(CI,
  2003. BinaryOperator::CreateWithCopiedFlags(
  2004. OldBinOp->getOpcode(), X, BO1,
  2005. OldBinOp, OldBinOp->getName(), II));
  2006. }
  2007. // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
  2008. if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
  2009. m_Value(Y))) &&
  2010. isSplatValue(BO0))
  2011. return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(
  2012. OldBinOp->getOpcode(), BO0, Y,
  2013. OldBinOp, OldBinOp->getName(), II));
  2014. }
  2015. // rev(unop rev(X)) --> unop X
  2016. if (match(Vec, m_OneUse(m_UnOp(
  2017. m_Intrinsic<Intrinsic::experimental_vector_reverse>(
  2018. m_Value(X)))))) {
  2019. auto *OldUnOp = cast<UnaryOperator>(Vec);
  2020. auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
  2021. OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
  2022. return replaceInstUsesWith(CI, NewUnOp);
  2023. }
  2024. break;
  2025. }
  2026. case Intrinsic::vector_reduce_or:
  2027. case Intrinsic::vector_reduce_and: {
  2028. // Canonicalize logical or/and reductions:
  2029. // Or reduction for i1 is represented as:
  2030. // %val = bitcast <ReduxWidth x i1> to iReduxWidth
  2031. // %res = cmp ne iReduxWidth %val, 0
  2032. // And reduction for i1 is represented as:
  2033. // %val = bitcast <ReduxWidth x i1> to iReduxWidth
  2034. // %res = cmp eq iReduxWidth %val, 11111
  2035. Value *Arg = II->getArgOperand(0);
  2036. Value *Vect;
  2037. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2038. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2039. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2040. Value *Res = Builder.CreateBitCast(
  2041. Vect, Builder.getIntNTy(FTy->getNumElements()));
  2042. if (IID == Intrinsic::vector_reduce_and) {
  2043. Res = Builder.CreateICmpEQ(
  2044. Res, ConstantInt::getAllOnesValue(Res->getType()));
  2045. } else {
  2046. assert(IID == Intrinsic::vector_reduce_or &&
  2047. "Expected or reduction.");
  2048. Res = Builder.CreateIsNotNull(Res);
  2049. }
  2050. if (Arg != Vect)
  2051. Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
  2052. II->getType());
  2053. return replaceInstUsesWith(CI, Res);
  2054. }
  2055. }
  2056. LLVM_FALLTHROUGH;
  2057. }
  2058. case Intrinsic::vector_reduce_add: {
  2059. if (IID == Intrinsic::vector_reduce_add) {
  2060. // Convert vector_reduce_add(ZExt(<n x i1>)) to
  2061. // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
  2062. // Convert vector_reduce_add(SExt(<n x i1>)) to
  2063. // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
  2064. // Convert vector_reduce_add(<n x i1>) to
  2065. // Trunc(ctpop(bitcast <n x i1> to in)).
  2066. Value *Arg = II->getArgOperand(0);
  2067. Value *Vect;
  2068. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2069. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2070. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2071. Value *V = Builder.CreateBitCast(
  2072. Vect, Builder.getIntNTy(FTy->getNumElements()));
  2073. Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
  2074. if (Res->getType() != II->getType())
  2075. Res = Builder.CreateZExtOrTrunc(Res, II->getType());
  2076. if (Arg != Vect &&
  2077. cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
  2078. Res = Builder.CreateNeg(Res);
  2079. return replaceInstUsesWith(CI, Res);
  2080. }
  2081. }
  2082. }
  2083. LLVM_FALLTHROUGH;
  2084. }
  2085. case Intrinsic::vector_reduce_xor: {
  2086. if (IID == Intrinsic::vector_reduce_xor) {
  2087. // Exclusive disjunction reduction over the vector with
  2088. // (potentially-extended) i1 element type is actually a
  2089. // (potentially-extended) arithmetic `add` reduction over the original
  2090. // non-extended value:
  2091. // vector_reduce_xor(?ext(<n x i1>))
  2092. // -->
  2093. // ?ext(vector_reduce_add(<n x i1>))
  2094. Value *Arg = II->getArgOperand(0);
  2095. Value *Vect;
  2096. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2097. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2098. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2099. Value *Res = Builder.CreateAddReduce(Vect);
  2100. if (Arg != Vect)
  2101. Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
  2102. II->getType());
  2103. return replaceInstUsesWith(CI, Res);
  2104. }
  2105. }
  2106. }
  2107. LLVM_FALLTHROUGH;
  2108. }
  2109. case Intrinsic::vector_reduce_mul: {
  2110. if (IID == Intrinsic::vector_reduce_mul) {
  2111. // Multiplicative reduction over the vector with (potentially-extended)
  2112. // i1 element type is actually a (potentially zero-extended)
  2113. // logical `and` reduction over the original non-extended value:
  2114. // vector_reduce_mul(?ext(<n x i1>))
  2115. // -->
  2116. // zext(vector_reduce_and(<n x i1>))
  2117. Value *Arg = II->getArgOperand(0);
  2118. Value *Vect;
  2119. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2120. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2121. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2122. Value *Res = Builder.CreateAndReduce(Vect);
  2123. if (Res->getType() != II->getType())
  2124. Res = Builder.CreateZExt(Res, II->getType());
  2125. return replaceInstUsesWith(CI, Res);
  2126. }
  2127. }
  2128. }
  2129. LLVM_FALLTHROUGH;
  2130. }
  2131. case Intrinsic::vector_reduce_umin:
  2132. case Intrinsic::vector_reduce_umax: {
  2133. if (IID == Intrinsic::vector_reduce_umin ||
  2134. IID == Intrinsic::vector_reduce_umax) {
  2135. // UMin/UMax reduction over the vector with (potentially-extended)
  2136. // i1 element type is actually a (potentially-extended)
  2137. // logical `and`/`or` reduction over the original non-extended value:
  2138. // vector_reduce_u{min,max}(?ext(<n x i1>))
  2139. // -->
  2140. // ?ext(vector_reduce_{and,or}(<n x i1>))
  2141. Value *Arg = II->getArgOperand(0);
  2142. Value *Vect;
  2143. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2144. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2145. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2146. Value *Res = IID == Intrinsic::vector_reduce_umin
  2147. ? Builder.CreateAndReduce(Vect)
  2148. : Builder.CreateOrReduce(Vect);
  2149. if (Arg != Vect)
  2150. Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
  2151. II->getType());
  2152. return replaceInstUsesWith(CI, Res);
  2153. }
  2154. }
  2155. }
  2156. LLVM_FALLTHROUGH;
  2157. }
  2158. case Intrinsic::vector_reduce_smin:
  2159. case Intrinsic::vector_reduce_smax: {
  2160. if (IID == Intrinsic::vector_reduce_smin ||
  2161. IID == Intrinsic::vector_reduce_smax) {
  2162. // SMin/SMax reduction over the vector with (potentially-extended)
  2163. // i1 element type is actually a (potentially-extended)
  2164. // logical `and`/`or` reduction over the original non-extended value:
  2165. // vector_reduce_s{min,max}(<n x i1>)
  2166. // -->
  2167. // vector_reduce_{or,and}(<n x i1>)
  2168. // and
  2169. // vector_reduce_s{min,max}(sext(<n x i1>))
  2170. // -->
  2171. // sext(vector_reduce_{or,and}(<n x i1>))
  2172. // and
  2173. // vector_reduce_s{min,max}(zext(<n x i1>))
  2174. // -->
  2175. // zext(vector_reduce_{and,or}(<n x i1>))
  2176. Value *Arg = II->getArgOperand(0);
  2177. Value *Vect;
  2178. if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
  2179. if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
  2180. if (FTy->getElementType() == Builder.getInt1Ty()) {
  2181. Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
  2182. if (Arg != Vect)
  2183. ExtOpc = cast<CastInst>(Arg)->getOpcode();
  2184. Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
  2185. (ExtOpc == Instruction::CastOps::ZExt))
  2186. ? Builder.CreateAndReduce(Vect)
  2187. : Builder.CreateOrReduce(Vect);
  2188. if (Arg != Vect)
  2189. Res = Builder.CreateCast(ExtOpc, Res, II->getType());
  2190. return replaceInstUsesWith(CI, Res);
  2191. }
  2192. }
  2193. }
  2194. LLVM_FALLTHROUGH;
  2195. }
  2196. case Intrinsic::vector_reduce_fmax:
  2197. case Intrinsic::vector_reduce_fmin:
  2198. case Intrinsic::vector_reduce_fadd:
  2199. case Intrinsic::vector_reduce_fmul: {
  2200. bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
  2201. IID != Intrinsic::vector_reduce_fmul) ||
  2202. II->hasAllowReassoc();
  2203. const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
  2204. IID == Intrinsic::vector_reduce_fmul)
  2205. ? 1
  2206. : 0;
  2207. Value *Arg = II->getArgOperand(ArgIdx);
  2208. Value *V;
  2209. ArrayRef<int> Mask;
  2210. if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
  2211. !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
  2212. !cast<ShuffleVectorInst>(Arg)->isSingleSource())
  2213. break;
  2214. int Sz = Mask.size();
  2215. SmallBitVector UsedIndices(Sz);
  2216. for (int Idx : Mask) {
  2217. if (Idx == UndefMaskElem || UsedIndices.test(Idx))
  2218. break;
  2219. UsedIndices.set(Idx);
  2220. }
  2221. // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
  2222. // other changes.
  2223. if (UsedIndices.all()) {
  2224. replaceUse(II->getOperandUse(ArgIdx), V);
  2225. return nullptr;
  2226. }
  2227. break;
  2228. }
  2229. default: {
  2230. // Handle target specific intrinsics
  2231. Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
  2232. if (V.hasValue())
  2233. return V.getValue();
  2234. break;
  2235. }
  2236. }
  2237. // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
  2238. // context, so it is handled in visitCallBase and we should trigger it.
  2239. return visitCallBase(*II);
  2240. }
  2241. // Fence instruction simplification
  2242. Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
  2243. auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
  2244. // This check is solely here to handle arbitrary target-dependent syncscopes.
  2245. // TODO: Can remove if does not matter in practice.
  2246. if (NFI && FI.isIdenticalTo(NFI))
  2247. return eraseInstFromFunction(FI);
  2248. // Returns true if FI1 is identical or stronger fence than FI2.
  2249. auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
  2250. auto FI1SyncScope = FI1->getSyncScopeID();
  2251. // Consider same scope, where scope is global or single-thread.
  2252. if (FI1SyncScope != FI2->getSyncScopeID() ||
  2253. (FI1SyncScope != SyncScope::System &&
  2254. FI1SyncScope != SyncScope::SingleThread))
  2255. return false;
  2256. return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
  2257. };
  2258. if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
  2259. return eraseInstFromFunction(FI);
  2260. if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
  2261. if (isIdenticalOrStrongerFence(PFI, &FI))
  2262. return eraseInstFromFunction(FI);
  2263. return nullptr;
  2264. }
  2265. // InvokeInst simplification
  2266. Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
  2267. return visitCallBase(II);
  2268. }
  2269. // CallBrInst simplification
  2270. Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
  2271. return visitCallBase(CBI);
  2272. }
  2273. /// If this cast does not affect the value passed through the varargs area, we
  2274. /// can eliminate the use of the cast.
  2275. static bool isSafeToEliminateVarargsCast(const CallBase &Call,
  2276. const DataLayout &DL,
  2277. const CastInst *const CI,
  2278. const int ix) {
  2279. if (!CI->isLosslessCast())
  2280. return false;
  2281. // If this is a GC intrinsic, avoid munging types. We need types for
  2282. // statepoint reconstruction in SelectionDAG.
  2283. // TODO: This is probably something which should be expanded to all
  2284. // intrinsics since the entire point of intrinsics is that
  2285. // they are understandable by the optimizer.
  2286. if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
  2287. isa<GCResultInst>(Call))
  2288. return false;
  2289. // Opaque pointers are compatible with any byval types.
  2290. PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
  2291. if (SrcTy->isOpaque())
  2292. return true;
  2293. // The size of ByVal or InAlloca arguments is derived from the type, so we
  2294. // can't change to a type with a different size. If the size were
  2295. // passed explicitly we could avoid this check.
  2296. if (!Call.isPassPointeeByValueArgument(ix))
  2297. return true;
  2298. // The transform currently only handles type replacement for byval, not other
  2299. // type-carrying attributes.
  2300. if (!Call.isByValArgument(ix))
  2301. return false;
  2302. Type *SrcElemTy = SrcTy->getNonOpaquePointerElementType();
  2303. Type *DstElemTy = Call.getParamByValType(ix);
  2304. if (!SrcElemTy->isSized() || !DstElemTy->isSized())
  2305. return false;
  2306. if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
  2307. return false;
  2308. return true;
  2309. }
  2310. Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
  2311. if (!CI->getCalledFunction()) return nullptr;
  2312. // Skip optimizing notail and musttail calls so
  2313. // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
  2314. // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
  2315. if (CI->isMustTailCall() || CI->isNoTailCall())
  2316. return nullptr;
  2317. auto InstCombineRAUW = [this](Instruction *From, Value *With) {
  2318. replaceInstUsesWith(*From, With);
  2319. };
  2320. auto InstCombineErase = [this](Instruction *I) {
  2321. eraseInstFromFunction(*I);
  2322. };
  2323. LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
  2324. InstCombineErase);
  2325. if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
  2326. ++NumSimplified;
  2327. return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
  2328. }
  2329. return nullptr;
  2330. }
  2331. static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
  2332. // Strip off at most one level of pointer casts, looking for an alloca. This
  2333. // is good enough in practice and simpler than handling any number of casts.
  2334. Value *Underlying = TrampMem->stripPointerCasts();
  2335. if (Underlying != TrampMem &&
  2336. (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
  2337. return nullptr;
  2338. if (!isa<AllocaInst>(Underlying))
  2339. return nullptr;
  2340. IntrinsicInst *InitTrampoline = nullptr;
  2341. for (User *U : TrampMem->users()) {
  2342. IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
  2343. if (!II)
  2344. return nullptr;
  2345. if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
  2346. if (InitTrampoline)
  2347. // More than one init_trampoline writes to this value. Give up.
  2348. return nullptr;
  2349. InitTrampoline = II;
  2350. continue;
  2351. }
  2352. if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
  2353. // Allow any number of calls to adjust.trampoline.
  2354. continue;
  2355. return nullptr;
  2356. }
  2357. // No call to init.trampoline found.
  2358. if (!InitTrampoline)
  2359. return nullptr;
  2360. // Check that the alloca is being used in the expected way.
  2361. if (InitTrampoline->getOperand(0) != TrampMem)
  2362. return nullptr;
  2363. return InitTrampoline;
  2364. }
  2365. static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
  2366. Value *TrampMem) {
  2367. // Visit all the previous instructions in the basic block, and try to find a
  2368. // init.trampoline which has a direct path to the adjust.trampoline.
  2369. for (BasicBlock::iterator I = AdjustTramp->getIterator(),
  2370. E = AdjustTramp->getParent()->begin();
  2371. I != E;) {
  2372. Instruction *Inst = &*--I;
  2373. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  2374. if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
  2375. II->getOperand(0) == TrampMem)
  2376. return II;
  2377. if (Inst->mayWriteToMemory())
  2378. return nullptr;
  2379. }
  2380. return nullptr;
  2381. }
  2382. // Given a call to llvm.adjust.trampoline, find and return the corresponding
  2383. // call to llvm.init.trampoline if the call to the trampoline can be optimized
  2384. // to a direct call to a function. Otherwise return NULL.
  2385. static IntrinsicInst *findInitTrampoline(Value *Callee) {
  2386. Callee = Callee->stripPointerCasts();
  2387. IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
  2388. if (!AdjustTramp ||
  2389. AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
  2390. return nullptr;
  2391. Value *TrampMem = AdjustTramp->getOperand(0);
  2392. if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
  2393. return IT;
  2394. if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
  2395. return IT;
  2396. return nullptr;
  2397. }
  2398. void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
  2399. // Note: We only handle cases which can't be driven from generic attributes
  2400. // here. So, for example, nonnull and noalias (which are common properties
  2401. // of some allocation functions) are expected to be handled via annotation
  2402. // of the respective allocator declaration with generic attributes.
  2403. uint64_t Size;
  2404. ObjectSizeOpts Opts;
  2405. if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) {
  2406. // TODO: We really should just emit deref_or_null here and then
  2407. // let the generic inference code combine that with nonnull.
  2408. if (Call.hasRetAttr(Attribute::NonNull))
  2409. Call.addRetAttr(Attribute::getWithDereferenceableBytes(
  2410. Call.getContext(), Size));
  2411. else
  2412. Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(
  2413. Call.getContext(), Size));
  2414. }
  2415. // Add alignment attribute if alignment is a power of two constant.
  2416. Value *Alignment = getAllocAlignment(&Call, TLI);
  2417. if (!Alignment)
  2418. return;
  2419. ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
  2420. if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
  2421. uint64_t AlignmentVal = AlignOpC->getZExtValue();
  2422. if (llvm::isPowerOf2_64(AlignmentVal)) {
  2423. Call.removeRetAttr(Attribute::Alignment);
  2424. Call.addRetAttr(Attribute::getWithAlignment(Call.getContext(),
  2425. Align(AlignmentVal)));
  2426. }
  2427. }
  2428. }
  2429. /// Improvements for call, callbr and invoke instructions.
  2430. Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
  2431. if (isAllocationFn(&Call, &TLI))
  2432. annotateAnyAllocSite(Call, &TLI);
  2433. bool Changed = false;
  2434. // Mark any parameters that are known to be non-null with the nonnull
  2435. // attribute. This is helpful for inlining calls to functions with null
  2436. // checks on their arguments.
  2437. SmallVector<unsigned, 4> ArgNos;
  2438. unsigned ArgNo = 0;
  2439. for (Value *V : Call.args()) {
  2440. if (V->getType()->isPointerTy() &&
  2441. !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
  2442. isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
  2443. ArgNos.push_back(ArgNo);
  2444. ArgNo++;
  2445. }
  2446. assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
  2447. if (!ArgNos.empty()) {
  2448. AttributeList AS = Call.getAttributes();
  2449. LLVMContext &Ctx = Call.getContext();
  2450. AS = AS.addParamAttribute(Ctx, ArgNos,
  2451. Attribute::get(Ctx, Attribute::NonNull));
  2452. Call.setAttributes(AS);
  2453. Changed = true;
  2454. }
  2455. // If the callee is a pointer to a function, attempt to move any casts to the
  2456. // arguments of the call/callbr/invoke.
  2457. Value *Callee = Call.getCalledOperand();
  2458. if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
  2459. return nullptr;
  2460. if (Function *CalleeF = dyn_cast<Function>(Callee)) {
  2461. // Remove the convergent attr on calls when the callee is not convergent.
  2462. if (Call.isConvergent() && !CalleeF->isConvergent() &&
  2463. !CalleeF->isIntrinsic()) {
  2464. LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
  2465. << "\n");
  2466. Call.setNotConvergent();
  2467. return &Call;
  2468. }
  2469. // If the call and callee calling conventions don't match, and neither one
  2470. // of the calling conventions is compatible with C calling convention
  2471. // this call must be unreachable, as the call is undefined.
  2472. if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
  2473. !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
  2474. TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
  2475. !(Call.getCallingConv() == llvm::CallingConv::C &&
  2476. TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
  2477. // Only do this for calls to a function with a body. A prototype may
  2478. // not actually end up matching the implementation's calling conv for a
  2479. // variety of reasons (e.g. it may be written in assembly).
  2480. !CalleeF->isDeclaration()) {
  2481. Instruction *OldCall = &Call;
  2482. CreateNonTerminatorUnreachable(OldCall);
  2483. // If OldCall does not return void then replaceInstUsesWith poison.
  2484. // This allows ValueHandlers and custom metadata to adjust itself.
  2485. if (!OldCall->getType()->isVoidTy())
  2486. replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
  2487. if (isa<CallInst>(OldCall))
  2488. return eraseInstFromFunction(*OldCall);
  2489. // We cannot remove an invoke or a callbr, because it would change thexi
  2490. // CFG, just change the callee to a null pointer.
  2491. cast<CallBase>(OldCall)->setCalledFunction(
  2492. CalleeF->getFunctionType(),
  2493. Constant::getNullValue(CalleeF->getType()));
  2494. return nullptr;
  2495. }
  2496. }
  2497. // Calling a null function pointer is undefined if a null address isn't
  2498. // dereferenceable.
  2499. if ((isa<ConstantPointerNull>(Callee) &&
  2500. !NullPointerIsDefined(Call.getFunction())) ||
  2501. isa<UndefValue>(Callee)) {
  2502. // If Call does not return void then replaceInstUsesWith poison.
  2503. // This allows ValueHandlers and custom metadata to adjust itself.
  2504. if (!Call.getType()->isVoidTy())
  2505. replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
  2506. if (Call.isTerminator()) {
  2507. // Can't remove an invoke or callbr because we cannot change the CFG.
  2508. return nullptr;
  2509. }
  2510. // This instruction is not reachable, just remove it.
  2511. CreateNonTerminatorUnreachable(&Call);
  2512. return eraseInstFromFunction(Call);
  2513. }
  2514. if (IntrinsicInst *II = findInitTrampoline(Callee))
  2515. return transformCallThroughTrampoline(Call, *II);
  2516. // TODO: Drop this transform once opaque pointer transition is done.
  2517. FunctionType *FTy = Call.getFunctionType();
  2518. if (FTy->isVarArg()) {
  2519. int ix = FTy->getNumParams();
  2520. // See if we can optimize any arguments passed through the varargs area of
  2521. // the call.
  2522. for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
  2523. I != E; ++I, ++ix) {
  2524. CastInst *CI = dyn_cast<CastInst>(*I);
  2525. if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
  2526. replaceUse(*I, CI->getOperand(0));
  2527. // Update the byval type to match the pointer type.
  2528. // Not necessary for opaque pointers.
  2529. PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
  2530. if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
  2531. Call.removeParamAttr(ix, Attribute::ByVal);
  2532. Call.addParamAttr(ix, Attribute::getWithByValType(
  2533. Call.getContext(),
  2534. NewTy->getNonOpaquePointerElementType()));
  2535. }
  2536. Changed = true;
  2537. }
  2538. }
  2539. }
  2540. if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
  2541. InlineAsm *IA = cast<InlineAsm>(Callee);
  2542. if (!IA->canThrow()) {
  2543. // Normal inline asm calls cannot throw - mark them
  2544. // 'nounwind'.
  2545. Call.setDoesNotThrow();
  2546. Changed = true;
  2547. }
  2548. }
  2549. // Try to optimize the call if possible, we require DataLayout for most of
  2550. // this. None of these calls are seen as possibly dead so go ahead and
  2551. // delete the instruction now.
  2552. if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
  2553. Instruction *I = tryOptimizeCall(CI);
  2554. // If we changed something return the result, etc. Otherwise let
  2555. // the fallthrough check.
  2556. if (I) return eraseInstFromFunction(*I);
  2557. }
  2558. if (!Call.use_empty() && !Call.isMustTailCall())
  2559. if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
  2560. Type *CallTy = Call.getType();
  2561. Type *RetArgTy = ReturnedArg->getType();
  2562. if (RetArgTy->canLosslesslyBitCastTo(CallTy))
  2563. return replaceInstUsesWith(
  2564. Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
  2565. }
  2566. if (isAllocationFn(&Call, &TLI) &&
  2567. isAllocRemovable(&cast<CallBase>(Call), &TLI))
  2568. return visitAllocSite(Call);
  2569. // Handle intrinsics which can be used in both call and invoke context.
  2570. switch (Call.getIntrinsicID()) {
  2571. case Intrinsic::experimental_gc_statepoint: {
  2572. GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
  2573. SmallPtrSet<Value *, 32> LiveGcValues;
  2574. for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
  2575. GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
  2576. // Remove the relocation if unused.
  2577. if (GCR.use_empty()) {
  2578. eraseInstFromFunction(GCR);
  2579. continue;
  2580. }
  2581. Value *DerivedPtr = GCR.getDerivedPtr();
  2582. Value *BasePtr = GCR.getBasePtr();
  2583. // Undef is undef, even after relocation.
  2584. if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
  2585. replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
  2586. eraseInstFromFunction(GCR);
  2587. continue;
  2588. }
  2589. if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
  2590. // The relocation of null will be null for most any collector.
  2591. // TODO: provide a hook for this in GCStrategy. There might be some
  2592. // weird collector this property does not hold for.
  2593. if (isa<ConstantPointerNull>(DerivedPtr)) {
  2594. // Use null-pointer of gc_relocate's type to replace it.
  2595. replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
  2596. eraseInstFromFunction(GCR);
  2597. continue;
  2598. }
  2599. // isKnownNonNull -> nonnull attribute
  2600. if (!GCR.hasRetAttr(Attribute::NonNull) &&
  2601. isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
  2602. GCR.addRetAttr(Attribute::NonNull);
  2603. // We discovered new fact, re-check users.
  2604. Worklist.pushUsersToWorkList(GCR);
  2605. }
  2606. }
  2607. // If we have two copies of the same pointer in the statepoint argument
  2608. // list, canonicalize to one. This may let us common gc.relocates.
  2609. if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
  2610. GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
  2611. auto *OpIntTy = GCR.getOperand(2)->getType();
  2612. GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
  2613. }
  2614. // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
  2615. // Canonicalize on the type from the uses to the defs
  2616. // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
  2617. LiveGcValues.insert(BasePtr);
  2618. LiveGcValues.insert(DerivedPtr);
  2619. }
  2620. Optional<OperandBundleUse> Bundle =
  2621. GCSP.getOperandBundle(LLVMContext::OB_gc_live);
  2622. unsigned NumOfGCLives = LiveGcValues.size();
  2623. if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
  2624. break;
  2625. // We can reduce the size of gc live bundle.
  2626. DenseMap<Value *, unsigned> Val2Idx;
  2627. std::vector<Value *> NewLiveGc;
  2628. for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
  2629. Value *V = Bundle->Inputs[I];
  2630. if (Val2Idx.count(V))
  2631. continue;
  2632. if (LiveGcValues.count(V)) {
  2633. Val2Idx[V] = NewLiveGc.size();
  2634. NewLiveGc.push_back(V);
  2635. } else
  2636. Val2Idx[V] = NumOfGCLives;
  2637. }
  2638. // Update all gc.relocates
  2639. for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
  2640. GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
  2641. Value *BasePtr = GCR.getBasePtr();
  2642. assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
  2643. "Missed live gc for base pointer");
  2644. auto *OpIntTy1 = GCR.getOperand(1)->getType();
  2645. GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
  2646. Value *DerivedPtr = GCR.getDerivedPtr();
  2647. assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
  2648. "Missed live gc for derived pointer");
  2649. auto *OpIntTy2 = GCR.getOperand(2)->getType();
  2650. GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
  2651. }
  2652. // Create new statepoint instruction.
  2653. OperandBundleDef NewBundle("gc-live", NewLiveGc);
  2654. return CallBase::Create(&Call, NewBundle);
  2655. }
  2656. default: { break; }
  2657. }
  2658. return Changed ? &Call : nullptr;
  2659. }
  2660. /// If the callee is a constexpr cast of a function, attempt to move the cast to
  2661. /// the arguments of the call/callbr/invoke.
  2662. bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
  2663. auto *Callee =
  2664. dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
  2665. if (!Callee)
  2666. return false;
  2667. // If this is a call to a thunk function, don't remove the cast. Thunks are
  2668. // used to transparently forward all incoming parameters and outgoing return
  2669. // values, so it's important to leave the cast in place.
  2670. if (Callee->hasFnAttribute("thunk"))
  2671. return false;
  2672. // If this is a musttail call, the callee's prototype must match the caller's
  2673. // prototype with the exception of pointee types. The code below doesn't
  2674. // implement that, so we can't do this transform.
  2675. // TODO: Do the transform if it only requires adding pointer casts.
  2676. if (Call.isMustTailCall())
  2677. return false;
  2678. Instruction *Caller = &Call;
  2679. const AttributeList &CallerPAL = Call.getAttributes();
  2680. // Okay, this is a cast from a function to a different type. Unless doing so
  2681. // would cause a type conversion of one of our arguments, change this call to
  2682. // be a direct call with arguments casted to the appropriate types.
  2683. FunctionType *FT = Callee->getFunctionType();
  2684. Type *OldRetTy = Caller->getType();
  2685. Type *NewRetTy = FT->getReturnType();
  2686. // Check to see if we are changing the return type...
  2687. if (OldRetTy != NewRetTy) {
  2688. if (NewRetTy->isStructTy())
  2689. return false; // TODO: Handle multiple return values.
  2690. if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
  2691. if (Callee->isDeclaration())
  2692. return false; // Cannot transform this return value.
  2693. if (!Caller->use_empty() &&
  2694. // void -> non-void is handled specially
  2695. !NewRetTy->isVoidTy())
  2696. return false; // Cannot transform this return value.
  2697. }
  2698. if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
  2699. AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
  2700. if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
  2701. return false; // Attribute not compatible with transformed value.
  2702. }
  2703. // If the callbase is an invoke/callbr instruction, and the return value is
  2704. // used by a PHI node in a successor, we cannot change the return type of
  2705. // the call because there is no place to put the cast instruction (without
  2706. // breaking the critical edge). Bail out in this case.
  2707. if (!Caller->use_empty()) {
  2708. if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
  2709. for (User *U : II->users())
  2710. if (PHINode *PN = dyn_cast<PHINode>(U))
  2711. if (PN->getParent() == II->getNormalDest() ||
  2712. PN->getParent() == II->getUnwindDest())
  2713. return false;
  2714. // FIXME: Be conservative for callbr to avoid a quadratic search.
  2715. if (isa<CallBrInst>(Caller))
  2716. return false;
  2717. }
  2718. }
  2719. unsigned NumActualArgs = Call.arg_size();
  2720. unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
  2721. // Prevent us turning:
  2722. // declare void @takes_i32_inalloca(i32* inalloca)
  2723. // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
  2724. //
  2725. // into:
  2726. // call void @takes_i32_inalloca(i32* null)
  2727. //
  2728. // Similarly, avoid folding away bitcasts of byval calls.
  2729. if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
  2730. Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
  2731. Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
  2732. return false;
  2733. auto AI = Call.arg_begin();
  2734. for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
  2735. Type *ParamTy = FT->getParamType(i);
  2736. Type *ActTy = (*AI)->getType();
  2737. if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
  2738. return false; // Cannot transform this parameter value.
  2739. if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
  2740. .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
  2741. return false; // Attribute not compatible with transformed value.
  2742. if (Call.isInAllocaArgument(i))
  2743. return false; // Cannot transform to and from inalloca.
  2744. if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
  2745. return false;
  2746. // If the parameter is passed as a byval argument, then we have to have a
  2747. // sized type and the sized type has to have the same size as the old type.
  2748. if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
  2749. PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
  2750. if (!ParamPTy || !ParamPTy->getPointerElementType()->isSized())
  2751. return false;
  2752. Type *CurElTy = Call.getParamByValType(i);
  2753. if (DL.getTypeAllocSize(CurElTy) !=
  2754. DL.getTypeAllocSize(ParamPTy->getPointerElementType()))
  2755. return false;
  2756. }
  2757. }
  2758. if (Callee->isDeclaration()) {
  2759. // Do not delete arguments unless we have a function body.
  2760. if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
  2761. return false;
  2762. // If the callee is just a declaration, don't change the varargsness of the
  2763. // call. We don't want to introduce a varargs call where one doesn't
  2764. // already exist.
  2765. if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
  2766. return false;
  2767. // If both the callee and the cast type are varargs, we still have to make
  2768. // sure the number of fixed parameters are the same or we have the same
  2769. // ABI issues as if we introduce a varargs call.
  2770. if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
  2771. FT->getNumParams() != Call.getFunctionType()->getNumParams())
  2772. return false;
  2773. }
  2774. if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
  2775. !CallerPAL.isEmpty()) {
  2776. // In this case we have more arguments than the new function type, but we
  2777. // won't be dropping them. Check that these extra arguments have attributes
  2778. // that are compatible with being a vararg call argument.
  2779. unsigned SRetIdx;
  2780. if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
  2781. SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
  2782. return false;
  2783. }
  2784. // Okay, we decided that this is a safe thing to do: go ahead and start
  2785. // inserting cast instructions as necessary.
  2786. SmallVector<Value *, 8> Args;
  2787. SmallVector<AttributeSet, 8> ArgAttrs;
  2788. Args.reserve(NumActualArgs);
  2789. ArgAttrs.reserve(NumActualArgs);
  2790. // Get any return attributes.
  2791. AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
  2792. // If the return value is not being used, the type may not be compatible
  2793. // with the existing attributes. Wipe out any problematic attributes.
  2794. RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
  2795. LLVMContext &Ctx = Call.getContext();
  2796. AI = Call.arg_begin();
  2797. for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
  2798. Type *ParamTy = FT->getParamType(i);
  2799. Value *NewArg = *AI;
  2800. if ((*AI)->getType() != ParamTy)
  2801. NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
  2802. Args.push_back(NewArg);
  2803. // Add any parameter attributes.
  2804. if (CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
  2805. AttrBuilder AB(FT->getContext(), CallerPAL.getParamAttrs(i));
  2806. AB.addByValAttr(NewArg->getType()->getPointerElementType());
  2807. ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
  2808. } else
  2809. ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
  2810. }
  2811. // If the function takes more arguments than the call was taking, add them
  2812. // now.
  2813. for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
  2814. Args.push_back(Constant::getNullValue(FT->getParamType(i)));
  2815. ArgAttrs.push_back(AttributeSet());
  2816. }
  2817. // If we are removing arguments to the function, emit an obnoxious warning.
  2818. if (FT->getNumParams() < NumActualArgs) {
  2819. // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
  2820. if (FT->isVarArg()) {
  2821. // Add all of the arguments in their promoted form to the arg list.
  2822. for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
  2823. Type *PTy = getPromotedType((*AI)->getType());
  2824. Value *NewArg = *AI;
  2825. if (PTy != (*AI)->getType()) {
  2826. // Must promote to pass through va_arg area!
  2827. Instruction::CastOps opcode =
  2828. CastInst::getCastOpcode(*AI, false, PTy, false);
  2829. NewArg = Builder.CreateCast(opcode, *AI, PTy);
  2830. }
  2831. Args.push_back(NewArg);
  2832. // Add any parameter attributes.
  2833. ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
  2834. }
  2835. }
  2836. }
  2837. AttributeSet FnAttrs = CallerPAL.getFnAttrs();
  2838. if (NewRetTy->isVoidTy())
  2839. Caller->setName(""); // Void type should not have a name.
  2840. assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
  2841. "missing argument attributes");
  2842. AttributeList NewCallerPAL = AttributeList::get(
  2843. Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
  2844. SmallVector<OperandBundleDef, 1> OpBundles;
  2845. Call.getOperandBundlesAsDefs(OpBundles);
  2846. CallBase *NewCall;
  2847. if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
  2848. NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
  2849. II->getUnwindDest(), Args, OpBundles);
  2850. } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
  2851. NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
  2852. CBI->getIndirectDests(), Args, OpBundles);
  2853. } else {
  2854. NewCall = Builder.CreateCall(Callee, Args, OpBundles);
  2855. cast<CallInst>(NewCall)->setTailCallKind(
  2856. cast<CallInst>(Caller)->getTailCallKind());
  2857. }
  2858. NewCall->takeName(Caller);
  2859. NewCall->setCallingConv(Call.getCallingConv());
  2860. NewCall->setAttributes(NewCallerPAL);
  2861. // Preserve prof metadata if any.
  2862. NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
  2863. // Insert a cast of the return type as necessary.
  2864. Instruction *NC = NewCall;
  2865. Value *NV = NC;
  2866. if (OldRetTy != NV->getType() && !Caller->use_empty()) {
  2867. if (!NV->getType()->isVoidTy()) {
  2868. NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
  2869. NC->setDebugLoc(Caller->getDebugLoc());
  2870. // If this is an invoke/callbr instruction, we should insert it after the
  2871. // first non-phi instruction in the normal successor block.
  2872. if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
  2873. BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
  2874. InsertNewInstBefore(NC, *I);
  2875. } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
  2876. BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
  2877. InsertNewInstBefore(NC, *I);
  2878. } else {
  2879. // Otherwise, it's a call, just insert cast right after the call.
  2880. InsertNewInstBefore(NC, *Caller);
  2881. }
  2882. Worklist.pushUsersToWorkList(*Caller);
  2883. } else {
  2884. NV = UndefValue::get(Caller->getType());
  2885. }
  2886. }
  2887. if (!Caller->use_empty())
  2888. replaceInstUsesWith(*Caller, NV);
  2889. else if (Caller->hasValueHandle()) {
  2890. if (OldRetTy == NV->getType())
  2891. ValueHandleBase::ValueIsRAUWd(Caller, NV);
  2892. else
  2893. // We cannot call ValueIsRAUWd with a different type, and the
  2894. // actual tracked value will disappear.
  2895. ValueHandleBase::ValueIsDeleted(Caller);
  2896. }
  2897. eraseInstFromFunction(*Caller);
  2898. return true;
  2899. }
  2900. /// Turn a call to a function created by init_trampoline / adjust_trampoline
  2901. /// intrinsic pair into a direct call to the underlying function.
  2902. Instruction *
  2903. InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
  2904. IntrinsicInst &Tramp) {
  2905. Value *Callee = Call.getCalledOperand();
  2906. Type *CalleeTy = Callee->getType();
  2907. FunctionType *FTy = Call.getFunctionType();
  2908. AttributeList Attrs = Call.getAttributes();
  2909. // If the call already has the 'nest' attribute somewhere then give up -
  2910. // otherwise 'nest' would occur twice after splicing in the chain.
  2911. if (Attrs.hasAttrSomewhere(Attribute::Nest))
  2912. return nullptr;
  2913. Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
  2914. FunctionType *NestFTy = NestF->getFunctionType();
  2915. AttributeList NestAttrs = NestF->getAttributes();
  2916. if (!NestAttrs.isEmpty()) {
  2917. unsigned NestArgNo = 0;
  2918. Type *NestTy = nullptr;
  2919. AttributeSet NestAttr;
  2920. // Look for a parameter marked with the 'nest' attribute.
  2921. for (FunctionType::param_iterator I = NestFTy->param_begin(),
  2922. E = NestFTy->param_end();
  2923. I != E; ++NestArgNo, ++I) {
  2924. AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
  2925. if (AS.hasAttribute(Attribute::Nest)) {
  2926. // Record the parameter type and any other attributes.
  2927. NestTy = *I;
  2928. NestAttr = AS;
  2929. break;
  2930. }
  2931. }
  2932. if (NestTy) {
  2933. std::vector<Value*> NewArgs;
  2934. std::vector<AttributeSet> NewArgAttrs;
  2935. NewArgs.reserve(Call.arg_size() + 1);
  2936. NewArgAttrs.reserve(Call.arg_size());
  2937. // Insert the nest argument into the call argument list, which may
  2938. // mean appending it. Likewise for attributes.
  2939. {
  2940. unsigned ArgNo = 0;
  2941. auto I = Call.arg_begin(), E = Call.arg_end();
  2942. do {
  2943. if (ArgNo == NestArgNo) {
  2944. // Add the chain argument and attributes.
  2945. Value *NestVal = Tramp.getArgOperand(2);
  2946. if (NestVal->getType() != NestTy)
  2947. NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
  2948. NewArgs.push_back(NestVal);
  2949. NewArgAttrs.push_back(NestAttr);
  2950. }
  2951. if (I == E)
  2952. break;
  2953. // Add the original argument and attributes.
  2954. NewArgs.push_back(*I);
  2955. NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
  2956. ++ArgNo;
  2957. ++I;
  2958. } while (true);
  2959. }
  2960. // The trampoline may have been bitcast to a bogus type (FTy).
  2961. // Handle this by synthesizing a new function type, equal to FTy
  2962. // with the chain parameter inserted.
  2963. std::vector<Type*> NewTypes;
  2964. NewTypes.reserve(FTy->getNumParams()+1);
  2965. // Insert the chain's type into the list of parameter types, which may
  2966. // mean appending it.
  2967. {
  2968. unsigned ArgNo = 0;
  2969. FunctionType::param_iterator I = FTy->param_begin(),
  2970. E = FTy->param_end();
  2971. do {
  2972. if (ArgNo == NestArgNo)
  2973. // Add the chain's type.
  2974. NewTypes.push_back(NestTy);
  2975. if (I == E)
  2976. break;
  2977. // Add the original type.
  2978. NewTypes.push_back(*I);
  2979. ++ArgNo;
  2980. ++I;
  2981. } while (true);
  2982. }
  2983. // Replace the trampoline call with a direct call. Let the generic
  2984. // code sort out any function type mismatches.
  2985. FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
  2986. FTy->isVarArg());
  2987. Constant *NewCallee =
  2988. NestF->getType() == PointerType::getUnqual(NewFTy) ?
  2989. NestF : ConstantExpr::getBitCast(NestF,
  2990. PointerType::getUnqual(NewFTy));
  2991. AttributeList NewPAL =
  2992. AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
  2993. Attrs.getRetAttrs(), NewArgAttrs);
  2994. SmallVector<OperandBundleDef, 1> OpBundles;
  2995. Call.getOperandBundlesAsDefs(OpBundles);
  2996. Instruction *NewCaller;
  2997. if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
  2998. NewCaller = InvokeInst::Create(NewFTy, NewCallee,
  2999. II->getNormalDest(), II->getUnwindDest(),
  3000. NewArgs, OpBundles);
  3001. cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
  3002. cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
  3003. } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
  3004. NewCaller =
  3005. CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
  3006. CBI->getIndirectDests(), NewArgs, OpBundles);
  3007. cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
  3008. cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
  3009. } else {
  3010. NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
  3011. cast<CallInst>(NewCaller)->setTailCallKind(
  3012. cast<CallInst>(Call).getTailCallKind());
  3013. cast<CallInst>(NewCaller)->setCallingConv(
  3014. cast<CallInst>(Call).getCallingConv());
  3015. cast<CallInst>(NewCaller)->setAttributes(NewPAL);
  3016. }
  3017. NewCaller->setDebugLoc(Call.getDebugLoc());
  3018. return NewCaller;
  3019. }
  3020. }
  3021. // Replace the trampoline call with a direct call. Since there is no 'nest'
  3022. // parameter, there is no need to adjust the argument list. Let the generic
  3023. // code sort out any function type mismatches.
  3024. Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
  3025. Call.setCalledFunction(FTy, NewCallee);
  3026. return &Call;
  3027. }