Instructions.h 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335
  1. //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
  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 exposes the class definitions of all of the subclasses of the
  10. // Instruction class. This is meant to be an easy way to get access to all
  11. // instruction subclasses.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_IR_INSTRUCTIONS_H
  15. #define LLVM_IR_INSTRUCTIONS_H
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/Bitfields.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/ADT/iterator.h"
  24. #include "llvm/ADT/iterator_range.h"
  25. #include "llvm/IR/Attributes.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/CallingConv.h"
  28. #include "llvm/IR/CFG.h"
  29. #include "llvm/IR/Constant.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/IR/InstrTypes.h"
  33. #include "llvm/IR/Instruction.h"
  34. #include "llvm/IR/OperandTraits.h"
  35. #include "llvm/IR/Type.h"
  36. #include "llvm/IR/Use.h"
  37. #include "llvm/IR/User.h"
  38. #include "llvm/IR/Value.h"
  39. #include "llvm/Support/AtomicOrdering.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include <cassert>
  43. #include <cstddef>
  44. #include <cstdint>
  45. #include <iterator>
  46. namespace llvm {
  47. class APInt;
  48. class ConstantInt;
  49. class DataLayout;
  50. class LLVMContext;
  51. //===----------------------------------------------------------------------===//
  52. // AllocaInst Class
  53. //===----------------------------------------------------------------------===//
  54. /// an instruction to allocate memory on the stack
  55. class AllocaInst : public UnaryInstruction {
  56. Type *AllocatedType;
  57. using AlignmentField = AlignmentBitfieldElementT<0>;
  58. using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>;
  59. using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>;
  60. static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField,
  61. SwiftErrorField>(),
  62. "Bitfields must be contiguous");
  63. protected:
  64. // Note: Instruction needs to be a friend here to call cloneImpl.
  65. friend class Instruction;
  66. AllocaInst *cloneImpl() const;
  67. public:
  68. explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  69. const Twine &Name, Instruction *InsertBefore);
  70. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  71. const Twine &Name, BasicBlock *InsertAtEnd);
  72. AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
  73. Instruction *InsertBefore);
  74. AllocaInst(Type *Ty, unsigned AddrSpace,
  75. const Twine &Name, BasicBlock *InsertAtEnd);
  76. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
  77. const Twine &Name = "", Instruction *InsertBefore = nullptr);
  78. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
  79. const Twine &Name, BasicBlock *InsertAtEnd);
  80. /// Return true if there is an allocation size parameter to the allocation
  81. /// instruction that is not 1.
  82. bool isArrayAllocation() const;
  83. /// Get the number of elements allocated. For a simple allocation of a single
  84. /// element, this will return a constant 1 value.
  85. const Value *getArraySize() const { return getOperand(0); }
  86. Value *getArraySize() { return getOperand(0); }
  87. /// Overload to return most specific pointer type.
  88. PointerType *getType() const {
  89. return cast<PointerType>(Instruction::getType());
  90. }
  91. /// Get allocation size in bits. Returns None if size can't be determined,
  92. /// e.g. in case of a VLA.
  93. Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const;
  94. /// Return the type that is being allocated by the instruction.
  95. Type *getAllocatedType() const { return AllocatedType; }
  96. /// for use only in special circumstances that need to generically
  97. /// transform a whole instruction (eg: IR linking and vectorization).
  98. void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
  99. /// Return the alignment of the memory that is being allocated by the
  100. /// instruction.
  101. Align getAlign() const {
  102. return Align(1ULL << getSubclassData<AlignmentField>());
  103. }
  104. void setAlignment(Align Align) {
  105. setSubclassData<AlignmentField>(Log2(Align));
  106. }
  107. // FIXME: Remove this one transition to Align is over.
  108. unsigned getAlignment() const { return getAlign().value(); }
  109. /// Return true if this alloca is in the entry block of the function and is a
  110. /// constant size. If so, the code generator will fold it into the
  111. /// prolog/epilog code, so it is basically free.
  112. bool isStaticAlloca() const;
  113. /// Return true if this alloca is used as an inalloca argument to a call. Such
  114. /// allocas are never considered static even if they are in the entry block.
  115. bool isUsedWithInAlloca() const {
  116. return getSubclassData<UsedWithInAllocaField>();
  117. }
  118. /// Specify whether this alloca is used to represent the arguments to a call.
  119. void setUsedWithInAlloca(bool V) {
  120. setSubclassData<UsedWithInAllocaField>(V);
  121. }
  122. /// Return true if this alloca is used as a swifterror argument to a call.
  123. bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); }
  124. /// Specify whether this alloca is used to represent a swifterror.
  125. void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); }
  126. // Methods for support type inquiry through isa, cast, and dyn_cast:
  127. static bool classof(const Instruction *I) {
  128. return (I->getOpcode() == Instruction::Alloca);
  129. }
  130. static bool classof(const Value *V) {
  131. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  132. }
  133. private:
  134. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  135. // method so that subclasses cannot accidentally use it.
  136. template <typename Bitfield>
  137. void setSubclassData(typename Bitfield::Type Value) {
  138. Instruction::setSubclassData<Bitfield>(Value);
  139. }
  140. };
  141. //===----------------------------------------------------------------------===//
  142. // LoadInst Class
  143. //===----------------------------------------------------------------------===//
  144. /// An instruction for reading from memory. This uses the SubclassData field in
  145. /// Value to store whether or not the load is volatile.
  146. class LoadInst : public UnaryInstruction {
  147. using VolatileField = BoolBitfieldElementT<0>;
  148. using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
  149. using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
  150. static_assert(
  151. Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
  152. "Bitfields must be contiguous");
  153. void AssertOK();
  154. protected:
  155. // Note: Instruction needs to be a friend here to call cloneImpl.
  156. friend class Instruction;
  157. LoadInst *cloneImpl() const;
  158. public:
  159. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr,
  160. Instruction *InsertBefore);
  161. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
  162. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  163. Instruction *InsertBefore);
  164. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  165. BasicBlock *InsertAtEnd);
  166. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  167. Align Align, Instruction *InsertBefore = nullptr);
  168. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  169. Align Align, BasicBlock *InsertAtEnd);
  170. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  171. Align Align, AtomicOrdering Order,
  172. SyncScope::ID SSID = SyncScope::System,
  173. Instruction *InsertBefore = nullptr);
  174. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  175. Align Align, AtomicOrdering Order, SyncScope::ID SSID,
  176. BasicBlock *InsertAtEnd);
  177. /// Return true if this is a load from a volatile memory location.
  178. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  179. /// Specify whether this is a volatile load or not.
  180. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  181. /// Return the alignment of the access that is being performed.
  182. /// FIXME: Remove this function once transition to Align is over.
  183. /// Use getAlign() instead.
  184. unsigned getAlignment() const { return getAlign().value(); }
  185. /// Return the alignment of the access that is being performed.
  186. Align getAlign() const {
  187. return Align(1ULL << (getSubclassData<AlignmentField>()));
  188. }
  189. void setAlignment(Align Align) {
  190. setSubclassData<AlignmentField>(Log2(Align));
  191. }
  192. /// Returns the ordering constraint of this load instruction.
  193. AtomicOrdering getOrdering() const {
  194. return getSubclassData<OrderingField>();
  195. }
  196. /// Sets the ordering constraint of this load instruction. May not be Release
  197. /// or AcquireRelease.
  198. void setOrdering(AtomicOrdering Ordering) {
  199. setSubclassData<OrderingField>(Ordering);
  200. }
  201. /// Returns the synchronization scope ID of this load instruction.
  202. SyncScope::ID getSyncScopeID() const {
  203. return SSID;
  204. }
  205. /// Sets the synchronization scope ID of this load instruction.
  206. void setSyncScopeID(SyncScope::ID SSID) {
  207. this->SSID = SSID;
  208. }
  209. /// Sets the ordering constraint and the synchronization scope ID of this load
  210. /// instruction.
  211. void setAtomic(AtomicOrdering Ordering,
  212. SyncScope::ID SSID = SyncScope::System) {
  213. setOrdering(Ordering);
  214. setSyncScopeID(SSID);
  215. }
  216. bool isSimple() const { return !isAtomic() && !isVolatile(); }
  217. bool isUnordered() const {
  218. return (getOrdering() == AtomicOrdering::NotAtomic ||
  219. getOrdering() == AtomicOrdering::Unordered) &&
  220. !isVolatile();
  221. }
  222. Value *getPointerOperand() { return getOperand(0); }
  223. const Value *getPointerOperand() const { return getOperand(0); }
  224. static unsigned getPointerOperandIndex() { return 0U; }
  225. Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
  226. /// Returns the address space of the pointer operand.
  227. unsigned getPointerAddressSpace() const {
  228. return getPointerOperandType()->getPointerAddressSpace();
  229. }
  230. // Methods for support type inquiry through isa, cast, and dyn_cast:
  231. static bool classof(const Instruction *I) {
  232. return I->getOpcode() == Instruction::Load;
  233. }
  234. static bool classof(const Value *V) {
  235. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  236. }
  237. private:
  238. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  239. // method so that subclasses cannot accidentally use it.
  240. template <typename Bitfield>
  241. void setSubclassData(typename Bitfield::Type Value) {
  242. Instruction::setSubclassData<Bitfield>(Value);
  243. }
  244. /// The synchronization scope ID of this load instruction. Not quite enough
  245. /// room in SubClassData for everything, so synchronization scope ID gets its
  246. /// own field.
  247. SyncScope::ID SSID;
  248. };
  249. //===----------------------------------------------------------------------===//
  250. // StoreInst Class
  251. //===----------------------------------------------------------------------===//
  252. /// An instruction for storing to memory.
  253. class StoreInst : public Instruction {
  254. using VolatileField = BoolBitfieldElementT<0>;
  255. using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
  256. using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
  257. static_assert(
  258. Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
  259. "Bitfields must be contiguous");
  260. void AssertOK();
  261. protected:
  262. // Note: Instruction needs to be a friend here to call cloneImpl.
  263. friend class Instruction;
  264. StoreInst *cloneImpl() const;
  265. public:
  266. StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
  267. StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
  268. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore);
  269. StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
  270. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  271. Instruction *InsertBefore = nullptr);
  272. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  273. BasicBlock *InsertAtEnd);
  274. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  275. AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
  276. Instruction *InsertBefore = nullptr);
  277. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  278. AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
  279. // allocate space for exactly two operands
  280. void *operator new(size_t s) {
  281. return User::operator new(s, 2);
  282. }
  283. /// Return true if this is a store to a volatile memory location.
  284. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  285. /// Specify whether this is a volatile store or not.
  286. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  287. /// Transparently provide more efficient getOperand methods.
  288. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  289. /// Return the alignment of the access that is being performed
  290. /// FIXME: Remove this function once transition to Align is over.
  291. /// Use getAlign() instead.
  292. unsigned getAlignment() const { return getAlign().value(); }
  293. Align getAlign() const {
  294. return Align(1ULL << (getSubclassData<AlignmentField>()));
  295. }
  296. void setAlignment(Align Align) {
  297. setSubclassData<AlignmentField>(Log2(Align));
  298. }
  299. /// Returns the ordering constraint of this store instruction.
  300. AtomicOrdering getOrdering() const {
  301. return getSubclassData<OrderingField>();
  302. }
  303. /// Sets the ordering constraint of this store instruction. May not be
  304. /// Acquire or AcquireRelease.
  305. void setOrdering(AtomicOrdering Ordering) {
  306. setSubclassData<OrderingField>(Ordering);
  307. }
  308. /// Returns the synchronization scope ID of this store instruction.
  309. SyncScope::ID getSyncScopeID() const {
  310. return SSID;
  311. }
  312. /// Sets the synchronization scope ID of this store instruction.
  313. void setSyncScopeID(SyncScope::ID SSID) {
  314. this->SSID = SSID;
  315. }
  316. /// Sets the ordering constraint and the synchronization scope ID of this
  317. /// store instruction.
  318. void setAtomic(AtomicOrdering Ordering,
  319. SyncScope::ID SSID = SyncScope::System) {
  320. setOrdering(Ordering);
  321. setSyncScopeID(SSID);
  322. }
  323. bool isSimple() const { return !isAtomic() && !isVolatile(); }
  324. bool isUnordered() const {
  325. return (getOrdering() == AtomicOrdering::NotAtomic ||
  326. getOrdering() == AtomicOrdering::Unordered) &&
  327. !isVolatile();
  328. }
  329. Value *getValueOperand() { return getOperand(0); }
  330. const Value *getValueOperand() const { return getOperand(0); }
  331. Value *getPointerOperand() { return getOperand(1); }
  332. const Value *getPointerOperand() const { return getOperand(1); }
  333. static unsigned getPointerOperandIndex() { return 1U; }
  334. Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
  335. /// Returns the address space of the pointer operand.
  336. unsigned getPointerAddressSpace() const {
  337. return getPointerOperandType()->getPointerAddressSpace();
  338. }
  339. // Methods for support type inquiry through isa, cast, and dyn_cast:
  340. static bool classof(const Instruction *I) {
  341. return I->getOpcode() == Instruction::Store;
  342. }
  343. static bool classof(const Value *V) {
  344. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  345. }
  346. private:
  347. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  348. // method so that subclasses cannot accidentally use it.
  349. template <typename Bitfield>
  350. void setSubclassData(typename Bitfield::Type Value) {
  351. Instruction::setSubclassData<Bitfield>(Value);
  352. }
  353. /// The synchronization scope ID of this store instruction. Not quite enough
  354. /// room in SubClassData for everything, so synchronization scope ID gets its
  355. /// own field.
  356. SyncScope::ID SSID;
  357. };
  358. template <>
  359. struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
  360. };
  361. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
  362. //===----------------------------------------------------------------------===//
  363. // FenceInst Class
  364. //===----------------------------------------------------------------------===//
  365. /// An instruction for ordering other memory operations.
  366. class FenceInst : public Instruction {
  367. using OrderingField = AtomicOrderingBitfieldElementT<0>;
  368. void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
  369. protected:
  370. // Note: Instruction needs to be a friend here to call cloneImpl.
  371. friend class Instruction;
  372. FenceInst *cloneImpl() const;
  373. public:
  374. // Ordering may only be Acquire, Release, AcquireRelease, or
  375. // SequentiallyConsistent.
  376. FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  377. SyncScope::ID SSID = SyncScope::System,
  378. Instruction *InsertBefore = nullptr);
  379. FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
  380. BasicBlock *InsertAtEnd);
  381. // allocate space for exactly zero operands
  382. void *operator new(size_t s) {
  383. return User::operator new(s, 0);
  384. }
  385. /// Returns the ordering constraint of this fence instruction.
  386. AtomicOrdering getOrdering() const {
  387. return getSubclassData<OrderingField>();
  388. }
  389. /// Sets the ordering constraint of this fence instruction. May only be
  390. /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
  391. void setOrdering(AtomicOrdering Ordering) {
  392. setSubclassData<OrderingField>(Ordering);
  393. }
  394. /// Returns the synchronization scope ID of this fence instruction.
  395. SyncScope::ID getSyncScopeID() const {
  396. return SSID;
  397. }
  398. /// Sets the synchronization scope ID of this fence instruction.
  399. void setSyncScopeID(SyncScope::ID SSID) {
  400. this->SSID = SSID;
  401. }
  402. // Methods for support type inquiry through isa, cast, and dyn_cast:
  403. static bool classof(const Instruction *I) {
  404. return I->getOpcode() == Instruction::Fence;
  405. }
  406. static bool classof(const Value *V) {
  407. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  408. }
  409. private:
  410. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  411. // method so that subclasses cannot accidentally use it.
  412. template <typename Bitfield>
  413. void setSubclassData(typename Bitfield::Type Value) {
  414. Instruction::setSubclassData<Bitfield>(Value);
  415. }
  416. /// The synchronization scope ID of this fence instruction. Not quite enough
  417. /// room in SubClassData for everything, so synchronization scope ID gets its
  418. /// own field.
  419. SyncScope::ID SSID;
  420. };
  421. //===----------------------------------------------------------------------===//
  422. // AtomicCmpXchgInst Class
  423. //===----------------------------------------------------------------------===//
  424. /// An instruction that atomically checks whether a
  425. /// specified value is in a memory location, and, if it is, stores a new value
  426. /// there. The value returned by this instruction is a pair containing the
  427. /// original value as first element, and an i1 indicating success (true) or
  428. /// failure (false) as second element.
  429. ///
  430. class AtomicCmpXchgInst : public Instruction {
  431. void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align,
  432. AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
  433. SyncScope::ID SSID);
  434. template <unsigned Offset>
  435. using AtomicOrderingBitfieldElement =
  436. typename Bitfield::Element<AtomicOrdering, Offset, 3,
  437. AtomicOrdering::LAST>;
  438. protected:
  439. // Note: Instruction needs to be a friend here to call cloneImpl.
  440. friend class Instruction;
  441. AtomicCmpXchgInst *cloneImpl() const;
  442. public:
  443. AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
  444. AtomicOrdering SuccessOrdering,
  445. AtomicOrdering FailureOrdering, SyncScope::ID SSID,
  446. Instruction *InsertBefore = nullptr);
  447. AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
  448. AtomicOrdering SuccessOrdering,
  449. AtomicOrdering FailureOrdering, SyncScope::ID SSID,
  450. BasicBlock *InsertAtEnd);
  451. // allocate space for exactly three operands
  452. void *operator new(size_t s) {
  453. return User::operator new(s, 3);
  454. }
  455. using VolatileField = BoolBitfieldElementT<0>;
  456. using WeakField = BoolBitfieldElementT<VolatileField::NextBit>;
  457. using SuccessOrderingField =
  458. AtomicOrderingBitfieldElementT<WeakField::NextBit>;
  459. using FailureOrderingField =
  460. AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>;
  461. using AlignmentField =
  462. AlignmentBitfieldElementT<FailureOrderingField::NextBit>;
  463. static_assert(
  464. Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField,
  465. FailureOrderingField, AlignmentField>(),
  466. "Bitfields must be contiguous");
  467. /// Return the alignment of the memory that is being allocated by the
  468. /// instruction.
  469. Align getAlign() const {
  470. return Align(1ULL << getSubclassData<AlignmentField>());
  471. }
  472. void setAlignment(Align Align) {
  473. setSubclassData<AlignmentField>(Log2(Align));
  474. }
  475. /// Return true if this is a cmpxchg from a volatile memory
  476. /// location.
  477. ///
  478. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  479. /// Specify whether this is a volatile cmpxchg.
  480. ///
  481. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  482. /// Return true if this cmpxchg may spuriously fail.
  483. bool isWeak() const { return getSubclassData<WeakField>(); }
  484. void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); }
  485. /// Transparently provide more efficient getOperand methods.
  486. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  487. static bool isValidSuccessOrdering(AtomicOrdering Ordering) {
  488. return Ordering != AtomicOrdering::NotAtomic &&
  489. Ordering != AtomicOrdering::Unordered;
  490. }
  491. static bool isValidFailureOrdering(AtomicOrdering Ordering) {
  492. return Ordering != AtomicOrdering::NotAtomic &&
  493. Ordering != AtomicOrdering::Unordered &&
  494. Ordering != AtomicOrdering::AcquireRelease &&
  495. Ordering != AtomicOrdering::Release;
  496. }
  497. /// Returns the success ordering constraint of this cmpxchg instruction.
  498. AtomicOrdering getSuccessOrdering() const {
  499. return getSubclassData<SuccessOrderingField>();
  500. }
  501. /// Sets the success ordering constraint of this cmpxchg instruction.
  502. void setSuccessOrdering(AtomicOrdering Ordering) {
  503. assert(isValidSuccessOrdering(Ordering) &&
  504. "invalid CmpXchg success ordering");
  505. setSubclassData<SuccessOrderingField>(Ordering);
  506. }
  507. /// Returns the failure ordering constraint of this cmpxchg instruction.
  508. AtomicOrdering getFailureOrdering() const {
  509. return getSubclassData<FailureOrderingField>();
  510. }
  511. /// Sets the failure ordering constraint of this cmpxchg instruction.
  512. void setFailureOrdering(AtomicOrdering Ordering) {
  513. assert(isValidFailureOrdering(Ordering) &&
  514. "invalid CmpXchg failure ordering");
  515. setSubclassData<FailureOrderingField>(Ordering);
  516. }
  517. /// Returns the synchronization scope ID of this cmpxchg instruction.
  518. SyncScope::ID getSyncScopeID() const {
  519. return SSID;
  520. }
  521. /// Sets the synchronization scope ID of this cmpxchg instruction.
  522. void setSyncScopeID(SyncScope::ID SSID) {
  523. this->SSID = SSID;
  524. }
  525. Value *getPointerOperand() { return getOperand(0); }
  526. const Value *getPointerOperand() const { return getOperand(0); }
  527. static unsigned getPointerOperandIndex() { return 0U; }
  528. Value *getCompareOperand() { return getOperand(1); }
  529. const Value *getCompareOperand() const { return getOperand(1); }
  530. Value *getNewValOperand() { return getOperand(2); }
  531. const Value *getNewValOperand() const { return getOperand(2); }
  532. /// Returns the address space of the pointer operand.
  533. unsigned getPointerAddressSpace() const {
  534. return getPointerOperand()->getType()->getPointerAddressSpace();
  535. }
  536. /// Returns the strongest permitted ordering on failure, given the
  537. /// desired ordering on success.
  538. ///
  539. /// If the comparison in a cmpxchg operation fails, there is no atomic store
  540. /// so release semantics cannot be provided. So this function drops explicit
  541. /// Release requests from the AtomicOrdering. A SequentiallyConsistent
  542. /// operation would remain SequentiallyConsistent.
  543. static AtomicOrdering
  544. getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
  545. switch (SuccessOrdering) {
  546. default:
  547. llvm_unreachable("invalid cmpxchg success ordering");
  548. case AtomicOrdering::Release:
  549. case AtomicOrdering::Monotonic:
  550. return AtomicOrdering::Monotonic;
  551. case AtomicOrdering::AcquireRelease:
  552. case AtomicOrdering::Acquire:
  553. return AtomicOrdering::Acquire;
  554. case AtomicOrdering::SequentiallyConsistent:
  555. return AtomicOrdering::SequentiallyConsistent;
  556. }
  557. }
  558. // Methods for support type inquiry through isa, cast, and dyn_cast:
  559. static bool classof(const Instruction *I) {
  560. return I->getOpcode() == Instruction::AtomicCmpXchg;
  561. }
  562. static bool classof(const Value *V) {
  563. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  564. }
  565. private:
  566. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  567. // method so that subclasses cannot accidentally use it.
  568. template <typename Bitfield>
  569. void setSubclassData(typename Bitfield::Type Value) {
  570. Instruction::setSubclassData<Bitfield>(Value);
  571. }
  572. /// The synchronization scope ID of this cmpxchg instruction. Not quite
  573. /// enough room in SubClassData for everything, so synchronization scope ID
  574. /// gets its own field.
  575. SyncScope::ID SSID;
  576. };
  577. template <>
  578. struct OperandTraits<AtomicCmpXchgInst> :
  579. public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
  580. };
  581. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
  582. //===----------------------------------------------------------------------===//
  583. // AtomicRMWInst Class
  584. //===----------------------------------------------------------------------===//
  585. /// an instruction that atomically reads a memory location,
  586. /// combines it with another value, and then stores the result back. Returns
  587. /// the old value.
  588. ///
  589. class AtomicRMWInst : public Instruction {
  590. protected:
  591. // Note: Instruction needs to be a friend here to call cloneImpl.
  592. friend class Instruction;
  593. AtomicRMWInst *cloneImpl() const;
  594. public:
  595. /// This enumeration lists the possible modifications atomicrmw can make. In
  596. /// the descriptions, 'p' is the pointer to the instruction's memory location,
  597. /// 'old' is the initial value of *p, and 'v' is the other value passed to the
  598. /// instruction. These instructions always return 'old'.
  599. enum BinOp : unsigned {
  600. /// *p = v
  601. Xchg,
  602. /// *p = old + v
  603. Add,
  604. /// *p = old - v
  605. Sub,
  606. /// *p = old & v
  607. And,
  608. /// *p = ~(old & v)
  609. Nand,
  610. /// *p = old | v
  611. Or,
  612. /// *p = old ^ v
  613. Xor,
  614. /// *p = old >signed v ? old : v
  615. Max,
  616. /// *p = old <signed v ? old : v
  617. Min,
  618. /// *p = old >unsigned v ? old : v
  619. UMax,
  620. /// *p = old <unsigned v ? old : v
  621. UMin,
  622. /// *p = old + v
  623. FAdd,
  624. /// *p = old - v
  625. FSub,
  626. FIRST_BINOP = Xchg,
  627. LAST_BINOP = FSub,
  628. BAD_BINOP
  629. };
  630. private:
  631. template <unsigned Offset>
  632. using AtomicOrderingBitfieldElement =
  633. typename Bitfield::Element<AtomicOrdering, Offset, 3,
  634. AtomicOrdering::LAST>;
  635. template <unsigned Offset>
  636. using BinOpBitfieldElement =
  637. typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>;
  638. public:
  639. AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
  640. AtomicOrdering Ordering, SyncScope::ID SSID,
  641. Instruction *InsertBefore = nullptr);
  642. AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
  643. AtomicOrdering Ordering, SyncScope::ID SSID,
  644. BasicBlock *InsertAtEnd);
  645. // allocate space for exactly two operands
  646. void *operator new(size_t s) {
  647. return User::operator new(s, 2);
  648. }
  649. using VolatileField = BoolBitfieldElementT<0>;
  650. using AtomicOrderingField =
  651. AtomicOrderingBitfieldElementT<VolatileField::NextBit>;
  652. using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>;
  653. using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>;
  654. static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField,
  655. OperationField, AlignmentField>(),
  656. "Bitfields must be contiguous");
  657. BinOp getOperation() const { return getSubclassData<OperationField>(); }
  658. static StringRef getOperationName(BinOp Op);
  659. static bool isFPOperation(BinOp Op) {
  660. switch (Op) {
  661. case AtomicRMWInst::FAdd:
  662. case AtomicRMWInst::FSub:
  663. return true;
  664. default:
  665. return false;
  666. }
  667. }
  668. void setOperation(BinOp Operation) {
  669. setSubclassData<OperationField>(Operation);
  670. }
  671. /// Return the alignment of the memory that is being allocated by the
  672. /// instruction.
  673. Align getAlign() const {
  674. return Align(1ULL << getSubclassData<AlignmentField>());
  675. }
  676. void setAlignment(Align Align) {
  677. setSubclassData<AlignmentField>(Log2(Align));
  678. }
  679. /// Return true if this is a RMW on a volatile memory location.
  680. ///
  681. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  682. /// Specify whether this is a volatile RMW or not.
  683. ///
  684. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  685. /// Transparently provide more efficient getOperand methods.
  686. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  687. /// Returns the ordering constraint of this rmw instruction.
  688. AtomicOrdering getOrdering() const {
  689. return getSubclassData<AtomicOrderingField>();
  690. }
  691. /// Sets the ordering constraint of this rmw instruction.
  692. void setOrdering(AtomicOrdering Ordering) {
  693. assert(Ordering != AtomicOrdering::NotAtomic &&
  694. "atomicrmw instructions can only be atomic.");
  695. setSubclassData<AtomicOrderingField>(Ordering);
  696. }
  697. /// Returns the synchronization scope ID of this rmw instruction.
  698. SyncScope::ID getSyncScopeID() const {
  699. return SSID;
  700. }
  701. /// Sets the synchronization scope ID of this rmw instruction.
  702. void setSyncScopeID(SyncScope::ID SSID) {
  703. this->SSID = SSID;
  704. }
  705. Value *getPointerOperand() { return getOperand(0); }
  706. const Value *getPointerOperand() const { return getOperand(0); }
  707. static unsigned getPointerOperandIndex() { return 0U; }
  708. Value *getValOperand() { return getOperand(1); }
  709. const Value *getValOperand() const { return getOperand(1); }
  710. /// Returns the address space of the pointer operand.
  711. unsigned getPointerAddressSpace() const {
  712. return getPointerOperand()->getType()->getPointerAddressSpace();
  713. }
  714. bool isFloatingPointOperation() const {
  715. return isFPOperation(getOperation());
  716. }
  717. // Methods for support type inquiry through isa, cast, and dyn_cast:
  718. static bool classof(const Instruction *I) {
  719. return I->getOpcode() == Instruction::AtomicRMW;
  720. }
  721. static bool classof(const Value *V) {
  722. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  723. }
  724. private:
  725. void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align,
  726. AtomicOrdering Ordering, SyncScope::ID SSID);
  727. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  728. // method so that subclasses cannot accidentally use it.
  729. template <typename Bitfield>
  730. void setSubclassData(typename Bitfield::Type Value) {
  731. Instruction::setSubclassData<Bitfield>(Value);
  732. }
  733. /// The synchronization scope ID of this rmw instruction. Not quite enough
  734. /// room in SubClassData for everything, so synchronization scope ID gets its
  735. /// own field.
  736. SyncScope::ID SSID;
  737. };
  738. template <>
  739. struct OperandTraits<AtomicRMWInst>
  740. : public FixedNumOperandTraits<AtomicRMWInst,2> {
  741. };
  742. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
  743. //===----------------------------------------------------------------------===//
  744. // GetElementPtrInst Class
  745. //===----------------------------------------------------------------------===//
  746. // checkGEPType - Simple wrapper function to give a better assertion failure
  747. // message on bad indexes for a gep instruction.
  748. //
  749. inline Type *checkGEPType(Type *Ty) {
  750. assert(Ty && "Invalid GetElementPtrInst indices for type!");
  751. return Ty;
  752. }
  753. /// an instruction for type-safe pointer arithmetic to
  754. /// access elements of arrays and structs
  755. ///
  756. class GetElementPtrInst : public Instruction {
  757. Type *SourceElementType;
  758. Type *ResultElementType;
  759. GetElementPtrInst(const GetElementPtrInst &GEPI);
  760. /// Constructors - Create a getelementptr instruction with a base pointer an
  761. /// list of indices. The first ctor can optionally insert before an existing
  762. /// instruction, the second appends the new instruction to the specified
  763. /// BasicBlock.
  764. inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
  765. ArrayRef<Value *> IdxList, unsigned Values,
  766. const Twine &NameStr, Instruction *InsertBefore);
  767. inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
  768. ArrayRef<Value *> IdxList, unsigned Values,
  769. const Twine &NameStr, BasicBlock *InsertAtEnd);
  770. void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
  771. protected:
  772. // Note: Instruction needs to be a friend here to call cloneImpl.
  773. friend class Instruction;
  774. GetElementPtrInst *cloneImpl() const;
  775. public:
  776. static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
  777. ArrayRef<Value *> IdxList,
  778. const Twine &NameStr = "",
  779. Instruction *InsertBefore = nullptr) {
  780. unsigned Values = 1 + unsigned(IdxList.size());
  781. if (!PointeeType) {
  782. PointeeType =
  783. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
  784. } else {
  785. assert(cast<PointerType>(Ptr->getType()->getScalarType())
  786. ->isOpaqueOrPointeeTypeMatches(PointeeType));
  787. }
  788. return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
  789. NameStr, InsertBefore);
  790. }
  791. static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
  792. ArrayRef<Value *> IdxList,
  793. const Twine &NameStr,
  794. BasicBlock *InsertAtEnd) {
  795. unsigned Values = 1 + unsigned(IdxList.size());
  796. if (!PointeeType) {
  797. PointeeType =
  798. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
  799. } else {
  800. assert(cast<PointerType>(Ptr->getType()->getScalarType())
  801. ->isOpaqueOrPointeeTypeMatches(PointeeType));
  802. }
  803. return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
  804. NameStr, InsertAtEnd);
  805. }
  806. /// Create an "inbounds" getelementptr. See the documentation for the
  807. /// "inbounds" flag in LangRef.html for details.
  808. static GetElementPtrInst *CreateInBounds(Value *Ptr,
  809. ArrayRef<Value *> IdxList,
  810. const Twine &NameStr = "",
  811. Instruction *InsertBefore = nullptr){
  812. return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
  813. }
  814. static GetElementPtrInst *
  815. CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
  816. const Twine &NameStr = "",
  817. Instruction *InsertBefore = nullptr) {
  818. GetElementPtrInst *GEP =
  819. Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
  820. GEP->setIsInBounds(true);
  821. return GEP;
  822. }
  823. static GetElementPtrInst *CreateInBounds(Value *Ptr,
  824. ArrayRef<Value *> IdxList,
  825. const Twine &NameStr,
  826. BasicBlock *InsertAtEnd) {
  827. return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
  828. }
  829. static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
  830. ArrayRef<Value *> IdxList,
  831. const Twine &NameStr,
  832. BasicBlock *InsertAtEnd) {
  833. GetElementPtrInst *GEP =
  834. Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
  835. GEP->setIsInBounds(true);
  836. return GEP;
  837. }
  838. /// Transparently provide more efficient getOperand methods.
  839. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  840. Type *getSourceElementType() const { return SourceElementType; }
  841. void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
  842. void setResultElementType(Type *Ty) { ResultElementType = Ty; }
  843. Type *getResultElementType() const {
  844. assert(ResultElementType ==
  845. cast<PointerType>(getType()->getScalarType())->getElementType());
  846. return ResultElementType;
  847. }
  848. /// Returns the address space of this instruction's pointer type.
  849. unsigned getAddressSpace() const {
  850. // Note that this is always the same as the pointer operand's address space
  851. // and that is cheaper to compute, so cheat here.
  852. return getPointerAddressSpace();
  853. }
  854. /// Returns the result type of a getelementptr with the given source
  855. /// element type and indexes.
  856. ///
  857. /// Null is returned if the indices are invalid for the specified
  858. /// source element type.
  859. static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
  860. static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
  861. static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
  862. /// Return the type of the element at the given index of an indexable
  863. /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})".
  864. ///
  865. /// Returns null if the type can't be indexed, or the given index is not
  866. /// legal for the given type.
  867. static Type *getTypeAtIndex(Type *Ty, Value *Idx);
  868. static Type *getTypeAtIndex(Type *Ty, uint64_t Idx);
  869. inline op_iterator idx_begin() { return op_begin()+1; }
  870. inline const_op_iterator idx_begin() const { return op_begin()+1; }
  871. inline op_iterator idx_end() { return op_end(); }
  872. inline const_op_iterator idx_end() const { return op_end(); }
  873. inline iterator_range<op_iterator> indices() {
  874. return make_range(idx_begin(), idx_end());
  875. }
  876. inline iterator_range<const_op_iterator> indices() const {
  877. return make_range(idx_begin(), idx_end());
  878. }
  879. Value *getPointerOperand() {
  880. return getOperand(0);
  881. }
  882. const Value *getPointerOperand() const {
  883. return getOperand(0);
  884. }
  885. static unsigned getPointerOperandIndex() {
  886. return 0U; // get index for modifying correct operand.
  887. }
  888. /// Method to return the pointer operand as a
  889. /// PointerType.
  890. Type *getPointerOperandType() const {
  891. return getPointerOperand()->getType();
  892. }
  893. /// Returns the address space of the pointer operand.
  894. unsigned getPointerAddressSpace() const {
  895. return getPointerOperandType()->getPointerAddressSpace();
  896. }
  897. /// Returns the pointer type returned by the GEP
  898. /// instruction, which may be a vector of pointers.
  899. static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
  900. ArrayRef<Value *> IdxList) {
  901. Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
  902. Ptr->getType()->getPointerAddressSpace());
  903. // Vector GEP
  904. if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) {
  905. ElementCount EltCount = PtrVTy->getElementCount();
  906. return VectorType::get(PtrTy, EltCount);
  907. }
  908. for (Value *Index : IdxList)
  909. if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) {
  910. ElementCount EltCount = IndexVTy->getElementCount();
  911. return VectorType::get(PtrTy, EltCount);
  912. }
  913. // Scalar GEP
  914. return PtrTy;
  915. }
  916. unsigned getNumIndices() const { // Note: always non-negative
  917. return getNumOperands() - 1;
  918. }
  919. bool hasIndices() const {
  920. return getNumOperands() > 1;
  921. }
  922. /// Return true if all of the indices of this GEP are
  923. /// zeros. If so, the result pointer and the first operand have the same
  924. /// value, just potentially different types.
  925. bool hasAllZeroIndices() const;
  926. /// Return true if all of the indices of this GEP are
  927. /// constant integers. If so, the result pointer and the first operand have
  928. /// a constant offset between them.
  929. bool hasAllConstantIndices() const;
  930. /// Set or clear the inbounds flag on this GEP instruction.
  931. /// See LangRef.html for the meaning of inbounds on a getelementptr.
  932. void setIsInBounds(bool b = true);
  933. /// Determine whether the GEP has the inbounds flag.
  934. bool isInBounds() const;
  935. /// Accumulate the constant address offset of this GEP if possible.
  936. ///
  937. /// This routine accepts an APInt into which it will accumulate the constant
  938. /// offset of this GEP if the GEP is in fact constant. If the GEP is not
  939. /// all-constant, it returns false and the value of the offset APInt is
  940. /// undefined (it is *not* preserved!). The APInt passed into this routine
  941. /// must be at least as wide as the IntPtr type for the address space of
  942. /// the base GEP pointer.
  943. bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
  944. // Methods for support type inquiry through isa, cast, and dyn_cast:
  945. static bool classof(const Instruction *I) {
  946. return (I->getOpcode() == Instruction::GetElementPtr);
  947. }
  948. static bool classof(const Value *V) {
  949. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  950. }
  951. };
  952. template <>
  953. struct OperandTraits<GetElementPtrInst> :
  954. public VariadicOperandTraits<GetElementPtrInst, 1> {
  955. };
  956. GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
  957. ArrayRef<Value *> IdxList, unsigned Values,
  958. const Twine &NameStr,
  959. Instruction *InsertBefore)
  960. : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
  961. OperandTraits<GetElementPtrInst>::op_end(this) - Values,
  962. Values, InsertBefore),
  963. SourceElementType(PointeeType),
  964. ResultElementType(getIndexedType(PointeeType, IdxList)) {
  965. assert(ResultElementType ==
  966. cast<PointerType>(getType()->getScalarType())->getElementType());
  967. init(Ptr, IdxList, NameStr);
  968. }
  969. GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
  970. ArrayRef<Value *> IdxList, unsigned Values,
  971. const Twine &NameStr,
  972. BasicBlock *InsertAtEnd)
  973. : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
  974. OperandTraits<GetElementPtrInst>::op_end(this) - Values,
  975. Values, InsertAtEnd),
  976. SourceElementType(PointeeType),
  977. ResultElementType(getIndexedType(PointeeType, IdxList)) {
  978. assert(ResultElementType ==
  979. cast<PointerType>(getType()->getScalarType())->getElementType());
  980. init(Ptr, IdxList, NameStr);
  981. }
  982. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
  983. //===----------------------------------------------------------------------===//
  984. // ICmpInst Class
  985. //===----------------------------------------------------------------------===//
  986. /// This instruction compares its operands according to the predicate given
  987. /// to the constructor. It only operates on integers or pointers. The operands
  988. /// must be identical types.
  989. /// Represent an integer comparison operator.
  990. class ICmpInst: public CmpInst {
  991. void AssertOK() {
  992. assert(isIntPredicate() &&
  993. "Invalid ICmp predicate value");
  994. assert(getOperand(0)->getType() == getOperand(1)->getType() &&
  995. "Both operands to ICmp instruction are not of the same type!");
  996. // Check that the operands are the right type
  997. assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
  998. getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
  999. "Invalid operand types for ICmp instruction");
  1000. }
  1001. protected:
  1002. // Note: Instruction needs to be a friend here to call cloneImpl.
  1003. friend class Instruction;
  1004. /// Clone an identical ICmpInst
  1005. ICmpInst *cloneImpl() const;
  1006. public:
  1007. /// Constructor with insert-before-instruction semantics.
  1008. ICmpInst(
  1009. Instruction *InsertBefore, ///< Where to insert
  1010. Predicate pred, ///< The predicate to use for the comparison
  1011. Value *LHS, ///< The left-hand-side of the expression
  1012. Value *RHS, ///< The right-hand-side of the expression
  1013. const Twine &NameStr = "" ///< Name of the instruction
  1014. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1015. Instruction::ICmp, pred, LHS, RHS, NameStr,
  1016. InsertBefore) {
  1017. #ifndef NDEBUG
  1018. AssertOK();
  1019. #endif
  1020. }
  1021. /// Constructor with insert-at-end semantics.
  1022. ICmpInst(
  1023. BasicBlock &InsertAtEnd, ///< Block to insert into.
  1024. Predicate pred, ///< The predicate to use for the comparison
  1025. Value *LHS, ///< The left-hand-side of the expression
  1026. Value *RHS, ///< The right-hand-side of the expression
  1027. const Twine &NameStr = "" ///< Name of the instruction
  1028. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1029. Instruction::ICmp, pred, LHS, RHS, NameStr,
  1030. &InsertAtEnd) {
  1031. #ifndef NDEBUG
  1032. AssertOK();
  1033. #endif
  1034. }
  1035. /// Constructor with no-insertion semantics
  1036. ICmpInst(
  1037. Predicate pred, ///< The predicate to use for the comparison
  1038. Value *LHS, ///< The left-hand-side of the expression
  1039. Value *RHS, ///< The right-hand-side of the expression
  1040. const Twine &NameStr = "" ///< Name of the instruction
  1041. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1042. Instruction::ICmp, pred, LHS, RHS, NameStr) {
  1043. #ifndef NDEBUG
  1044. AssertOK();
  1045. #endif
  1046. }
  1047. /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
  1048. /// @returns the predicate that would be the result if the operand were
  1049. /// regarded as signed.
  1050. /// Return the signed version of the predicate
  1051. Predicate getSignedPredicate() const {
  1052. return getSignedPredicate(getPredicate());
  1053. }
  1054. /// This is a static version that you can use without an instruction.
  1055. /// Return the signed version of the predicate.
  1056. static Predicate getSignedPredicate(Predicate pred);
  1057. /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
  1058. /// @returns the predicate that would be the result if the operand were
  1059. /// regarded as unsigned.
  1060. /// Return the unsigned version of the predicate
  1061. Predicate getUnsignedPredicate() const {
  1062. return getUnsignedPredicate(getPredicate());
  1063. }
  1064. /// This is a static version that you can use without an instruction.
  1065. /// Return the unsigned version of the predicate.
  1066. static Predicate getUnsignedPredicate(Predicate pred);
  1067. /// Return true if this predicate is either EQ or NE. This also
  1068. /// tests for commutativity.
  1069. static bool isEquality(Predicate P) {
  1070. return P == ICMP_EQ || P == ICMP_NE;
  1071. }
  1072. /// Return true if this predicate is either EQ or NE. This also
  1073. /// tests for commutativity.
  1074. bool isEquality() const {
  1075. return isEquality(getPredicate());
  1076. }
  1077. /// @returns true if the predicate of this ICmpInst is commutative
  1078. /// Determine if this relation is commutative.
  1079. bool isCommutative() const { return isEquality(); }
  1080. /// Return true if the predicate is relational (not EQ or NE).
  1081. ///
  1082. bool isRelational() const {
  1083. return !isEquality();
  1084. }
  1085. /// Return true if the predicate is relational (not EQ or NE).
  1086. ///
  1087. static bool isRelational(Predicate P) {
  1088. return !isEquality(P);
  1089. }
  1090. /// Return true if the predicate is SGT or UGT.
  1091. ///
  1092. static bool isGT(Predicate P) {
  1093. return P == ICMP_SGT || P == ICMP_UGT;
  1094. }
  1095. /// Return true if the predicate is SLT or ULT.
  1096. ///
  1097. static bool isLT(Predicate P) {
  1098. return P == ICMP_SLT || P == ICMP_ULT;
  1099. }
  1100. /// Return true if the predicate is SGE or UGE.
  1101. ///
  1102. static bool isGE(Predicate P) {
  1103. return P == ICMP_SGE || P == ICMP_UGE;
  1104. }
  1105. /// Return true if the predicate is SLE or ULE.
  1106. ///
  1107. static bool isLE(Predicate P) {
  1108. return P == ICMP_SLE || P == ICMP_ULE;
  1109. }
  1110. /// Exchange the two operands to this instruction in such a way that it does
  1111. /// not modify the semantics of the instruction. The predicate value may be
  1112. /// changed to retain the same result if the predicate is order dependent
  1113. /// (e.g. ult).
  1114. /// Swap operands and adjust predicate.
  1115. void swapOperands() {
  1116. setPredicate(getSwappedPredicate());
  1117. Op<0>().swap(Op<1>());
  1118. }
  1119. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1120. static bool classof(const Instruction *I) {
  1121. return I->getOpcode() == Instruction::ICmp;
  1122. }
  1123. static bool classof(const Value *V) {
  1124. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1125. }
  1126. };
  1127. //===----------------------------------------------------------------------===//
  1128. // FCmpInst Class
  1129. //===----------------------------------------------------------------------===//
  1130. /// This instruction compares its operands according to the predicate given
  1131. /// to the constructor. It only operates on floating point values or packed
  1132. /// vectors of floating point values. The operands must be identical types.
  1133. /// Represents a floating point comparison operator.
  1134. class FCmpInst: public CmpInst {
  1135. void AssertOK() {
  1136. assert(isFPPredicate() && "Invalid FCmp predicate value");
  1137. assert(getOperand(0)->getType() == getOperand(1)->getType() &&
  1138. "Both operands to FCmp instruction are not of the same type!");
  1139. // Check that the operands are the right type
  1140. assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
  1141. "Invalid operand types for FCmp instruction");
  1142. }
  1143. protected:
  1144. // Note: Instruction needs to be a friend here to call cloneImpl.
  1145. friend class Instruction;
  1146. /// Clone an identical FCmpInst
  1147. FCmpInst *cloneImpl() const;
  1148. public:
  1149. /// Constructor with insert-before-instruction semantics.
  1150. FCmpInst(
  1151. Instruction *InsertBefore, ///< Where to insert
  1152. Predicate pred, ///< The predicate to use for the comparison
  1153. Value *LHS, ///< The left-hand-side of the expression
  1154. Value *RHS, ///< The right-hand-side of the expression
  1155. const Twine &NameStr = "" ///< Name of the instruction
  1156. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1157. Instruction::FCmp, pred, LHS, RHS, NameStr,
  1158. InsertBefore) {
  1159. AssertOK();
  1160. }
  1161. /// Constructor with insert-at-end semantics.
  1162. FCmpInst(
  1163. BasicBlock &InsertAtEnd, ///< Block to insert into.
  1164. Predicate pred, ///< The predicate to use for the comparison
  1165. Value *LHS, ///< The left-hand-side of the expression
  1166. Value *RHS, ///< The right-hand-side of the expression
  1167. const Twine &NameStr = "" ///< Name of the instruction
  1168. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1169. Instruction::FCmp, pred, LHS, RHS, NameStr,
  1170. &InsertAtEnd) {
  1171. AssertOK();
  1172. }
  1173. /// Constructor with no-insertion semantics
  1174. FCmpInst(
  1175. Predicate Pred, ///< The predicate to use for the comparison
  1176. Value *LHS, ///< The left-hand-side of the expression
  1177. Value *RHS, ///< The right-hand-side of the expression
  1178. const Twine &NameStr = "", ///< Name of the instruction
  1179. Instruction *FlagsSource = nullptr
  1180. ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
  1181. RHS, NameStr, nullptr, FlagsSource) {
  1182. AssertOK();
  1183. }
  1184. /// @returns true if the predicate of this instruction is EQ or NE.
  1185. /// Determine if this is an equality predicate.
  1186. static bool isEquality(Predicate Pred) {
  1187. return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
  1188. Pred == FCMP_UNE;
  1189. }
  1190. /// @returns true if the predicate of this instruction is EQ or NE.
  1191. /// Determine if this is an equality predicate.
  1192. bool isEquality() const { return isEquality(getPredicate()); }
  1193. /// @returns true if the predicate of this instruction is commutative.
  1194. /// Determine if this is a commutative predicate.
  1195. bool isCommutative() const {
  1196. return isEquality() ||
  1197. getPredicate() == FCMP_FALSE ||
  1198. getPredicate() == FCMP_TRUE ||
  1199. getPredicate() == FCMP_ORD ||
  1200. getPredicate() == FCMP_UNO;
  1201. }
  1202. /// @returns true if the predicate is relational (not EQ or NE).
  1203. /// Determine if this a relational predicate.
  1204. bool isRelational() const { return !isEquality(); }
  1205. /// Exchange the two operands to this instruction in such a way that it does
  1206. /// not modify the semantics of the instruction. The predicate value may be
  1207. /// changed to retain the same result if the predicate is order dependent
  1208. /// (e.g. ult).
  1209. /// Swap operands and adjust predicate.
  1210. void swapOperands() {
  1211. setPredicate(getSwappedPredicate());
  1212. Op<0>().swap(Op<1>());
  1213. }
  1214. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  1215. static bool classof(const Instruction *I) {
  1216. return I->getOpcode() == Instruction::FCmp;
  1217. }
  1218. static bool classof(const Value *V) {
  1219. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1220. }
  1221. };
  1222. //===----------------------------------------------------------------------===//
  1223. /// This class represents a function call, abstracting a target
  1224. /// machine's calling convention. This class uses low bit of the SubClassData
  1225. /// field to indicate whether or not this is a tail call. The rest of the bits
  1226. /// hold the calling convention of the call.
  1227. ///
  1228. class CallInst : public CallBase {
  1229. CallInst(const CallInst &CI);
  1230. /// Construct a CallInst given a range of arguments.
  1231. /// Construct a CallInst from a range of arguments
  1232. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1233. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1234. Instruction *InsertBefore);
  1235. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1236. const Twine &NameStr, Instruction *InsertBefore)
  1237. : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
  1238. /// Construct a CallInst given a range of arguments.
  1239. /// Construct a CallInst from a range of arguments
  1240. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1241. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1242. BasicBlock *InsertAtEnd);
  1243. explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
  1244. Instruction *InsertBefore);
  1245. CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
  1246. BasicBlock *InsertAtEnd);
  1247. void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
  1248. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  1249. void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
  1250. /// Compute the number of operands to allocate.
  1251. static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
  1252. // We need one operand for the called function, plus the input operand
  1253. // counts provided.
  1254. return 1 + NumArgs + NumBundleInputs;
  1255. }
  1256. protected:
  1257. // Note: Instruction needs to be a friend here to call cloneImpl.
  1258. friend class Instruction;
  1259. CallInst *cloneImpl() const;
  1260. public:
  1261. static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
  1262. Instruction *InsertBefore = nullptr) {
  1263. return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
  1264. }
  1265. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1266. const Twine &NameStr,
  1267. Instruction *InsertBefore = nullptr) {
  1268. return new (ComputeNumOperands(Args.size()))
  1269. CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
  1270. }
  1271. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1272. ArrayRef<OperandBundleDef> Bundles = None,
  1273. const Twine &NameStr = "",
  1274. Instruction *InsertBefore = nullptr) {
  1275. const int NumOperands =
  1276. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  1277. const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  1278. return new (NumOperands, DescriptorBytes)
  1279. CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
  1280. }
  1281. static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
  1282. BasicBlock *InsertAtEnd) {
  1283. return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
  1284. }
  1285. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1286. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1287. return new (ComputeNumOperands(Args.size()))
  1288. CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
  1289. }
  1290. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1291. ArrayRef<OperandBundleDef> Bundles,
  1292. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1293. const int NumOperands =
  1294. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  1295. const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  1296. return new (NumOperands, DescriptorBytes)
  1297. CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
  1298. }
  1299. static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
  1300. Instruction *InsertBefore = nullptr) {
  1301. return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
  1302. InsertBefore);
  1303. }
  1304. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1305. ArrayRef<OperandBundleDef> Bundles = None,
  1306. const Twine &NameStr = "",
  1307. Instruction *InsertBefore = nullptr) {
  1308. return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
  1309. NameStr, InsertBefore);
  1310. }
  1311. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1312. const Twine &NameStr,
  1313. Instruction *InsertBefore = nullptr) {
  1314. return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
  1315. InsertBefore);
  1316. }
  1317. static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
  1318. BasicBlock *InsertAtEnd) {
  1319. return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
  1320. InsertAtEnd);
  1321. }
  1322. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1323. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1324. return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
  1325. InsertAtEnd);
  1326. }
  1327. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1328. ArrayRef<OperandBundleDef> Bundles,
  1329. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1330. return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
  1331. NameStr, InsertAtEnd);
  1332. }
  1333. /// Create a clone of \p CI with a different set of operand bundles and
  1334. /// insert it before \p InsertPt.
  1335. ///
  1336. /// The returned call instruction is identical \p CI in every way except that
  1337. /// the operand bundles for the new instruction are set to the operand bundles
  1338. /// in \p Bundles.
  1339. static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
  1340. Instruction *InsertPt = nullptr);
  1341. /// Generate the IR for a call to malloc:
  1342. /// 1. Compute the malloc call's argument as the specified type's size,
  1343. /// possibly multiplied by the array size if the array size is not
  1344. /// constant 1.
  1345. /// 2. Call malloc with that argument.
  1346. /// 3. Bitcast the result of the malloc call to the specified type.
  1347. static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
  1348. Type *AllocTy, Value *AllocSize,
  1349. Value *ArraySize = nullptr,
  1350. Function *MallocF = nullptr,
  1351. const Twine &Name = "");
  1352. static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
  1353. Type *AllocTy, Value *AllocSize,
  1354. Value *ArraySize = nullptr,
  1355. Function *MallocF = nullptr,
  1356. const Twine &Name = "");
  1357. static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
  1358. Type *AllocTy, Value *AllocSize,
  1359. Value *ArraySize = nullptr,
  1360. ArrayRef<OperandBundleDef> Bundles = None,
  1361. Function *MallocF = nullptr,
  1362. const Twine &Name = "");
  1363. static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
  1364. Type *AllocTy, Value *AllocSize,
  1365. Value *ArraySize = nullptr,
  1366. ArrayRef<OperandBundleDef> Bundles = None,
  1367. Function *MallocF = nullptr,
  1368. const Twine &Name = "");
  1369. /// Generate the IR for a call to the builtin free function.
  1370. static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
  1371. static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
  1372. static Instruction *CreateFree(Value *Source,
  1373. ArrayRef<OperandBundleDef> Bundles,
  1374. Instruction *InsertBefore);
  1375. static Instruction *CreateFree(Value *Source,
  1376. ArrayRef<OperandBundleDef> Bundles,
  1377. BasicBlock *InsertAtEnd);
  1378. // Note that 'musttail' implies 'tail'.
  1379. enum TailCallKind : unsigned {
  1380. TCK_None = 0,
  1381. TCK_Tail = 1,
  1382. TCK_MustTail = 2,
  1383. TCK_NoTail = 3,
  1384. TCK_LAST = TCK_NoTail
  1385. };
  1386. using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>;
  1387. static_assert(
  1388. Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(),
  1389. "Bitfields must be contiguous");
  1390. TailCallKind getTailCallKind() const {
  1391. return getSubclassData<TailCallKindField>();
  1392. }
  1393. bool isTailCall() const {
  1394. TailCallKind Kind = getTailCallKind();
  1395. return Kind == TCK_Tail || Kind == TCK_MustTail;
  1396. }
  1397. bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; }
  1398. bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; }
  1399. void setTailCallKind(TailCallKind TCK) {
  1400. setSubclassData<TailCallKindField>(TCK);
  1401. }
  1402. void setTailCall(bool IsTc = true) {
  1403. setTailCallKind(IsTc ? TCK_Tail : TCK_None);
  1404. }
  1405. /// Return true if the call can return twice
  1406. bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
  1407. void setCanReturnTwice() {
  1408. addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
  1409. }
  1410. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1411. static bool classof(const Instruction *I) {
  1412. return I->getOpcode() == Instruction::Call;
  1413. }
  1414. static bool classof(const Value *V) {
  1415. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1416. }
  1417. /// Updates profile metadata by scaling it by \p S / \p T.
  1418. void updateProfWeight(uint64_t S, uint64_t T);
  1419. private:
  1420. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  1421. // method so that subclasses cannot accidentally use it.
  1422. template <typename Bitfield>
  1423. void setSubclassData(typename Bitfield::Type Value) {
  1424. Instruction::setSubclassData<Bitfield>(Value);
  1425. }
  1426. };
  1427. CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1428. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1429. BasicBlock *InsertAtEnd)
  1430. : CallBase(Ty->getReturnType(), Instruction::Call,
  1431. OperandTraits<CallBase>::op_end(this) -
  1432. (Args.size() + CountBundleInputs(Bundles) + 1),
  1433. unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
  1434. InsertAtEnd) {
  1435. init(Ty, Func, Args, Bundles, NameStr);
  1436. }
  1437. CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1438. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1439. Instruction *InsertBefore)
  1440. : CallBase(Ty->getReturnType(), Instruction::Call,
  1441. OperandTraits<CallBase>::op_end(this) -
  1442. (Args.size() + CountBundleInputs(Bundles) + 1),
  1443. unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
  1444. InsertBefore) {
  1445. init(Ty, Func, Args, Bundles, NameStr);
  1446. }
  1447. //===----------------------------------------------------------------------===//
  1448. // SelectInst Class
  1449. //===----------------------------------------------------------------------===//
  1450. /// This class represents the LLVM 'select' instruction.
  1451. ///
  1452. class SelectInst : public Instruction {
  1453. SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
  1454. Instruction *InsertBefore)
  1455. : Instruction(S1->getType(), Instruction::Select,
  1456. &Op<0>(), 3, InsertBefore) {
  1457. init(C, S1, S2);
  1458. setName(NameStr);
  1459. }
  1460. SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
  1461. BasicBlock *InsertAtEnd)
  1462. : Instruction(S1->getType(), Instruction::Select,
  1463. &Op<0>(), 3, InsertAtEnd) {
  1464. init(C, S1, S2);
  1465. setName(NameStr);
  1466. }
  1467. void init(Value *C, Value *S1, Value *S2) {
  1468. assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
  1469. Op<0>() = C;
  1470. Op<1>() = S1;
  1471. Op<2>() = S2;
  1472. }
  1473. protected:
  1474. // Note: Instruction needs to be a friend here to call cloneImpl.
  1475. friend class Instruction;
  1476. SelectInst *cloneImpl() const;
  1477. public:
  1478. static SelectInst *Create(Value *C, Value *S1, Value *S2,
  1479. const Twine &NameStr = "",
  1480. Instruction *InsertBefore = nullptr,
  1481. Instruction *MDFrom = nullptr) {
  1482. SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
  1483. if (MDFrom)
  1484. Sel->copyMetadata(*MDFrom);
  1485. return Sel;
  1486. }
  1487. static SelectInst *Create(Value *C, Value *S1, Value *S2,
  1488. const Twine &NameStr,
  1489. BasicBlock *InsertAtEnd) {
  1490. return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
  1491. }
  1492. const Value *getCondition() const { return Op<0>(); }
  1493. const Value *getTrueValue() const { return Op<1>(); }
  1494. const Value *getFalseValue() const { return Op<2>(); }
  1495. Value *getCondition() { return Op<0>(); }
  1496. Value *getTrueValue() { return Op<1>(); }
  1497. Value *getFalseValue() { return Op<2>(); }
  1498. void setCondition(Value *V) { Op<0>() = V; }
  1499. void setTrueValue(Value *V) { Op<1>() = V; }
  1500. void setFalseValue(Value *V) { Op<2>() = V; }
  1501. /// Swap the true and false values of the select instruction.
  1502. /// This doesn't swap prof metadata.
  1503. void swapValues() { Op<1>().swap(Op<2>()); }
  1504. /// Return a string if the specified operands are invalid
  1505. /// for a select operation, otherwise return null.
  1506. static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
  1507. /// Transparently provide more efficient getOperand methods.
  1508. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1509. OtherOps getOpcode() const {
  1510. return static_cast<OtherOps>(Instruction::getOpcode());
  1511. }
  1512. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1513. static bool classof(const Instruction *I) {
  1514. return I->getOpcode() == Instruction::Select;
  1515. }
  1516. static bool classof(const Value *V) {
  1517. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1518. }
  1519. };
  1520. template <>
  1521. struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
  1522. };
  1523. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
  1524. //===----------------------------------------------------------------------===//
  1525. // VAArgInst Class
  1526. //===----------------------------------------------------------------------===//
  1527. /// This class represents the va_arg llvm instruction, which returns
  1528. /// an argument of the specified type given a va_list and increments that list
  1529. ///
  1530. class VAArgInst : public UnaryInstruction {
  1531. protected:
  1532. // Note: Instruction needs to be a friend here to call cloneImpl.
  1533. friend class Instruction;
  1534. VAArgInst *cloneImpl() const;
  1535. public:
  1536. VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
  1537. Instruction *InsertBefore = nullptr)
  1538. : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
  1539. setName(NameStr);
  1540. }
  1541. VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
  1542. BasicBlock *InsertAtEnd)
  1543. : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
  1544. setName(NameStr);
  1545. }
  1546. Value *getPointerOperand() { return getOperand(0); }
  1547. const Value *getPointerOperand() const { return getOperand(0); }
  1548. static unsigned getPointerOperandIndex() { return 0U; }
  1549. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1550. static bool classof(const Instruction *I) {
  1551. return I->getOpcode() == VAArg;
  1552. }
  1553. static bool classof(const Value *V) {
  1554. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1555. }
  1556. };
  1557. //===----------------------------------------------------------------------===//
  1558. // ExtractElementInst Class
  1559. //===----------------------------------------------------------------------===//
  1560. /// This instruction extracts a single (scalar)
  1561. /// element from a VectorType value
  1562. ///
  1563. class ExtractElementInst : public Instruction {
  1564. ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
  1565. Instruction *InsertBefore = nullptr);
  1566. ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
  1567. BasicBlock *InsertAtEnd);
  1568. protected:
  1569. // Note: Instruction needs to be a friend here to call cloneImpl.
  1570. friend class Instruction;
  1571. ExtractElementInst *cloneImpl() const;
  1572. public:
  1573. static ExtractElementInst *Create(Value *Vec, Value *Idx,
  1574. const Twine &NameStr = "",
  1575. Instruction *InsertBefore = nullptr) {
  1576. return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
  1577. }
  1578. static ExtractElementInst *Create(Value *Vec, Value *Idx,
  1579. const Twine &NameStr,
  1580. BasicBlock *InsertAtEnd) {
  1581. return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
  1582. }
  1583. /// Return true if an extractelement instruction can be
  1584. /// formed with the specified operands.
  1585. static bool isValidOperands(const Value *Vec, const Value *Idx);
  1586. Value *getVectorOperand() { return Op<0>(); }
  1587. Value *getIndexOperand() { return Op<1>(); }
  1588. const Value *getVectorOperand() const { return Op<0>(); }
  1589. const Value *getIndexOperand() const { return Op<1>(); }
  1590. VectorType *getVectorOperandType() const {
  1591. return cast<VectorType>(getVectorOperand()->getType());
  1592. }
  1593. /// Transparently provide more efficient getOperand methods.
  1594. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1595. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1596. static bool classof(const Instruction *I) {
  1597. return I->getOpcode() == Instruction::ExtractElement;
  1598. }
  1599. static bool classof(const Value *V) {
  1600. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1601. }
  1602. };
  1603. template <>
  1604. struct OperandTraits<ExtractElementInst> :
  1605. public FixedNumOperandTraits<ExtractElementInst, 2> {
  1606. };
  1607. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
  1608. //===----------------------------------------------------------------------===//
  1609. // InsertElementInst Class
  1610. //===----------------------------------------------------------------------===//
  1611. /// This instruction inserts a single (scalar)
  1612. /// element into a VectorType value
  1613. ///
  1614. class InsertElementInst : public Instruction {
  1615. InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
  1616. const Twine &NameStr = "",
  1617. Instruction *InsertBefore = nullptr);
  1618. InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
  1619. BasicBlock *InsertAtEnd);
  1620. protected:
  1621. // Note: Instruction needs to be a friend here to call cloneImpl.
  1622. friend class Instruction;
  1623. InsertElementInst *cloneImpl() const;
  1624. public:
  1625. static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
  1626. const Twine &NameStr = "",
  1627. Instruction *InsertBefore = nullptr) {
  1628. return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
  1629. }
  1630. static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
  1631. const Twine &NameStr,
  1632. BasicBlock *InsertAtEnd) {
  1633. return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
  1634. }
  1635. /// Return true if an insertelement instruction can be
  1636. /// formed with the specified operands.
  1637. static bool isValidOperands(const Value *Vec, const Value *NewElt,
  1638. const Value *Idx);
  1639. /// Overload to return most specific vector type.
  1640. ///
  1641. VectorType *getType() const {
  1642. return cast<VectorType>(Instruction::getType());
  1643. }
  1644. /// Transparently provide more efficient getOperand methods.
  1645. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1646. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1647. static bool classof(const Instruction *I) {
  1648. return I->getOpcode() == Instruction::InsertElement;
  1649. }
  1650. static bool classof(const Value *V) {
  1651. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1652. }
  1653. };
  1654. template <>
  1655. struct OperandTraits<InsertElementInst> :
  1656. public FixedNumOperandTraits<InsertElementInst, 3> {
  1657. };
  1658. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
  1659. //===----------------------------------------------------------------------===//
  1660. // ShuffleVectorInst Class
  1661. //===----------------------------------------------------------------------===//
  1662. constexpr int UndefMaskElem = -1;
  1663. /// This instruction constructs a fixed permutation of two
  1664. /// input vectors.
  1665. ///
  1666. /// For each element of the result vector, the shuffle mask selects an element
  1667. /// from one of the input vectors to copy to the result. Non-negative elements
  1668. /// in the mask represent an index into the concatenated pair of input vectors.
  1669. /// UndefMaskElem (-1) specifies that the result element is undefined.
  1670. ///
  1671. /// For scalable vectors, all the elements of the mask must be 0 or -1. This
  1672. /// requirement may be relaxed in the future.
  1673. class ShuffleVectorInst : public Instruction {
  1674. SmallVector<int, 4> ShuffleMask;
  1675. Constant *ShuffleMaskForBitcode;
  1676. protected:
  1677. // Note: Instruction needs to be a friend here to call cloneImpl.
  1678. friend class Instruction;
  1679. ShuffleVectorInst *cloneImpl() const;
  1680. public:
  1681. ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1682. const Twine &NameStr = "",
  1683. Instruction *InsertBefor = nullptr);
  1684. ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1685. const Twine &NameStr, BasicBlock *InsertAtEnd);
  1686. ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1687. const Twine &NameStr = "",
  1688. Instruction *InsertBefor = nullptr);
  1689. ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1690. const Twine &NameStr, BasicBlock *InsertAtEnd);
  1691. void *operator new(size_t s) { return User::operator new(s, 2); }
  1692. /// Swap the operands and adjust the mask to preserve the semantics
  1693. /// of the instruction.
  1694. void commute();
  1695. /// Return true if a shufflevector instruction can be
  1696. /// formed with the specified operands.
  1697. static bool isValidOperands(const Value *V1, const Value *V2,
  1698. const Value *Mask);
  1699. static bool isValidOperands(const Value *V1, const Value *V2,
  1700. ArrayRef<int> Mask);
  1701. /// Overload to return most specific vector type.
  1702. ///
  1703. VectorType *getType() const {
  1704. return cast<VectorType>(Instruction::getType());
  1705. }
  1706. /// Transparently provide more efficient getOperand methods.
  1707. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1708. /// Return the shuffle mask value of this instruction for the given element
  1709. /// index. Return UndefMaskElem if the element is undef.
  1710. int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; }
  1711. /// Convert the input shuffle mask operand to a vector of integers. Undefined
  1712. /// elements of the mask are returned as UndefMaskElem.
  1713. static void getShuffleMask(const Constant *Mask,
  1714. SmallVectorImpl<int> &Result);
  1715. /// Return the mask for this instruction as a vector of integers. Undefined
  1716. /// elements of the mask are returned as UndefMaskElem.
  1717. void getShuffleMask(SmallVectorImpl<int> &Result) const {
  1718. Result.assign(ShuffleMask.begin(), ShuffleMask.end());
  1719. }
  1720. /// Return the mask for this instruction, for use in bitcode.
  1721. ///
  1722. /// TODO: This is temporary until we decide a new bitcode encoding for
  1723. /// shufflevector.
  1724. Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; }
  1725. static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask,
  1726. Type *ResultTy);
  1727. void setShuffleMask(ArrayRef<int> Mask);
  1728. ArrayRef<int> getShuffleMask() const { return ShuffleMask; }
  1729. /// Return true if this shuffle returns a vector with a different number of
  1730. /// elements than its source vectors.
  1731. /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
  1732. /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
  1733. bool changesLength() const {
  1734. unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
  1735. ->getElementCount()
  1736. .getKnownMinValue();
  1737. unsigned NumMaskElts = ShuffleMask.size();
  1738. return NumSourceElts != NumMaskElts;
  1739. }
  1740. /// Return true if this shuffle returns a vector with a greater number of
  1741. /// elements than its source vectors.
  1742. /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
  1743. bool increasesLength() const {
  1744. unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
  1745. ->getElementCount()
  1746. .getKnownMinValue();
  1747. unsigned NumMaskElts = ShuffleMask.size();
  1748. return NumSourceElts < NumMaskElts;
  1749. }
  1750. /// Return true if this shuffle mask chooses elements from exactly one source
  1751. /// vector.
  1752. /// Example: <7,5,undef,7>
  1753. /// This assumes that vector operands are the same length as the mask.
  1754. static bool isSingleSourceMask(ArrayRef<int> Mask);
  1755. static bool isSingleSourceMask(const Constant *Mask) {
  1756. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1757. SmallVector<int, 16> MaskAsInts;
  1758. getShuffleMask(Mask, MaskAsInts);
  1759. return isSingleSourceMask(MaskAsInts);
  1760. }
  1761. /// Return true if this shuffle chooses elements from exactly one source
  1762. /// vector without changing the length of that vector.
  1763. /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
  1764. /// TODO: Optionally allow length-changing shuffles.
  1765. bool isSingleSource() const {
  1766. return !changesLength() && isSingleSourceMask(ShuffleMask);
  1767. }
  1768. /// Return true if this shuffle mask chooses elements from exactly one source
  1769. /// vector without lane crossings. A shuffle using this mask is not
  1770. /// necessarily a no-op because it may change the number of elements from its
  1771. /// input vectors or it may provide demanded bits knowledge via undef lanes.
  1772. /// Example: <undef,undef,2,3>
  1773. static bool isIdentityMask(ArrayRef<int> Mask);
  1774. static bool isIdentityMask(const Constant *Mask) {
  1775. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1776. SmallVector<int, 16> MaskAsInts;
  1777. getShuffleMask(Mask, MaskAsInts);
  1778. return isIdentityMask(MaskAsInts);
  1779. }
  1780. /// Return true if this shuffle chooses elements from exactly one source
  1781. /// vector without lane crossings and does not change the number of elements
  1782. /// from its input vectors.
  1783. /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
  1784. bool isIdentity() const {
  1785. return !changesLength() && isIdentityMask(ShuffleMask);
  1786. }
  1787. /// Return true if this shuffle lengthens exactly one source vector with
  1788. /// undefs in the high elements.
  1789. bool isIdentityWithPadding() const;
  1790. /// Return true if this shuffle extracts the first N elements of exactly one
  1791. /// source vector.
  1792. bool isIdentityWithExtract() const;
  1793. /// Return true if this shuffle concatenates its 2 source vectors. This
  1794. /// returns false if either input is undefined. In that case, the shuffle is
  1795. /// is better classified as an identity with padding operation.
  1796. bool isConcat() const;
  1797. /// Return true if this shuffle mask chooses elements from its source vectors
  1798. /// without lane crossings. A shuffle using this mask would be
  1799. /// equivalent to a vector select with a constant condition operand.
  1800. /// Example: <4,1,6,undef>
  1801. /// This returns false if the mask does not choose from both input vectors.
  1802. /// In that case, the shuffle is better classified as an identity shuffle.
  1803. /// This assumes that vector operands are the same length as the mask
  1804. /// (a length-changing shuffle can never be equivalent to a vector select).
  1805. static bool isSelectMask(ArrayRef<int> Mask);
  1806. static bool isSelectMask(const Constant *Mask) {
  1807. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1808. SmallVector<int, 16> MaskAsInts;
  1809. getShuffleMask(Mask, MaskAsInts);
  1810. return isSelectMask(MaskAsInts);
  1811. }
  1812. /// Return true if this shuffle chooses elements from its source vectors
  1813. /// without lane crossings and all operands have the same number of elements.
  1814. /// In other words, this shuffle is equivalent to a vector select with a
  1815. /// constant condition operand.
  1816. /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
  1817. /// This returns false if the mask does not choose from both input vectors.
  1818. /// In that case, the shuffle is better classified as an identity shuffle.
  1819. /// TODO: Optionally allow length-changing shuffles.
  1820. bool isSelect() const {
  1821. return !changesLength() && isSelectMask(ShuffleMask);
  1822. }
  1823. /// Return true if this shuffle mask swaps the order of elements from exactly
  1824. /// one source vector.
  1825. /// Example: <7,6,undef,4>
  1826. /// This assumes that vector operands are the same length as the mask.
  1827. static bool isReverseMask(ArrayRef<int> Mask);
  1828. static bool isReverseMask(const Constant *Mask) {
  1829. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1830. SmallVector<int, 16> MaskAsInts;
  1831. getShuffleMask(Mask, MaskAsInts);
  1832. return isReverseMask(MaskAsInts);
  1833. }
  1834. /// Return true if this shuffle swaps the order of elements from exactly
  1835. /// one source vector.
  1836. /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
  1837. /// TODO: Optionally allow length-changing shuffles.
  1838. bool isReverse() const {
  1839. return !changesLength() && isReverseMask(ShuffleMask);
  1840. }
  1841. /// Return true if this shuffle mask chooses all elements with the same value
  1842. /// as the first element of exactly one source vector.
  1843. /// Example: <4,undef,undef,4>
  1844. /// This assumes that vector operands are the same length as the mask.
  1845. static bool isZeroEltSplatMask(ArrayRef<int> Mask);
  1846. static bool isZeroEltSplatMask(const Constant *Mask) {
  1847. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1848. SmallVector<int, 16> MaskAsInts;
  1849. getShuffleMask(Mask, MaskAsInts);
  1850. return isZeroEltSplatMask(MaskAsInts);
  1851. }
  1852. /// Return true if all elements of this shuffle are the same value as the
  1853. /// first element of exactly one source vector without changing the length
  1854. /// of that vector.
  1855. /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
  1856. /// TODO: Optionally allow length-changing shuffles.
  1857. /// TODO: Optionally allow splats from other elements.
  1858. bool isZeroEltSplat() const {
  1859. return !changesLength() && isZeroEltSplatMask(ShuffleMask);
  1860. }
  1861. /// Return true if this shuffle mask is a transpose mask.
  1862. /// Transpose vector masks transpose a 2xn matrix. They read corresponding
  1863. /// even- or odd-numbered vector elements from two n-dimensional source
  1864. /// vectors and write each result into consecutive elements of an
  1865. /// n-dimensional destination vector. Two shuffles are necessary to complete
  1866. /// the transpose, one for the even elements and another for the odd elements.
  1867. /// This description closely follows how the TRN1 and TRN2 AArch64
  1868. /// instructions operate.
  1869. ///
  1870. /// For example, a simple 2x2 matrix can be transposed with:
  1871. ///
  1872. /// ; Original matrix
  1873. /// m0 = < a, b >
  1874. /// m1 = < c, d >
  1875. ///
  1876. /// ; Transposed matrix
  1877. /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
  1878. /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
  1879. ///
  1880. /// For matrices having greater than n columns, the resulting nx2 transposed
  1881. /// matrix is stored in two result vectors such that one vector contains
  1882. /// interleaved elements from all the even-numbered rows and the other vector
  1883. /// contains interleaved elements from all the odd-numbered rows. For example,
  1884. /// a 2x4 matrix can be transposed with:
  1885. ///
  1886. /// ; Original matrix
  1887. /// m0 = < a, b, c, d >
  1888. /// m1 = < e, f, g, h >
  1889. ///
  1890. /// ; Transposed matrix
  1891. /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
  1892. /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
  1893. static bool isTransposeMask(ArrayRef<int> Mask);
  1894. static bool isTransposeMask(const Constant *Mask) {
  1895. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1896. SmallVector<int, 16> MaskAsInts;
  1897. getShuffleMask(Mask, MaskAsInts);
  1898. return isTransposeMask(MaskAsInts);
  1899. }
  1900. /// Return true if this shuffle transposes the elements of its inputs without
  1901. /// changing the length of the vectors. This operation may also be known as a
  1902. /// merge or interleave. See the description for isTransposeMask() for the
  1903. /// exact specification.
  1904. /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
  1905. bool isTranspose() const {
  1906. return !changesLength() && isTransposeMask(ShuffleMask);
  1907. }
  1908. /// Return true if this shuffle mask is an extract subvector mask.
  1909. /// A valid extract subvector mask returns a smaller vector from a single
  1910. /// source operand. The base extraction index is returned as well.
  1911. static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
  1912. int &Index);
  1913. static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
  1914. int &Index) {
  1915. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1916. // Not possible to express a shuffle mask for a scalable vector for this
  1917. // case.
  1918. if (isa<ScalableVectorType>(Mask->getType()))
  1919. return false;
  1920. SmallVector<int, 16> MaskAsInts;
  1921. getShuffleMask(Mask, MaskAsInts);
  1922. return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
  1923. }
  1924. /// Return true if this shuffle mask is an extract subvector mask.
  1925. bool isExtractSubvectorMask(int &Index) const {
  1926. // Not possible to express a shuffle mask for a scalable vector for this
  1927. // case.
  1928. if (isa<ScalableVectorType>(getType()))
  1929. return false;
  1930. int NumSrcElts =
  1931. cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  1932. return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index);
  1933. }
  1934. /// Change values in a shuffle permute mask assuming the two vector operands
  1935. /// of length InVecNumElts have swapped position.
  1936. static void commuteShuffleMask(MutableArrayRef<int> Mask,
  1937. unsigned InVecNumElts) {
  1938. for (int &Idx : Mask) {
  1939. if (Idx == -1)
  1940. continue;
  1941. Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
  1942. assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
  1943. "shufflevector mask index out of range");
  1944. }
  1945. }
  1946. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1947. static bool classof(const Instruction *I) {
  1948. return I->getOpcode() == Instruction::ShuffleVector;
  1949. }
  1950. static bool classof(const Value *V) {
  1951. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1952. }
  1953. };
  1954. template <>
  1955. struct OperandTraits<ShuffleVectorInst>
  1956. : public FixedNumOperandTraits<ShuffleVectorInst, 2> {};
  1957. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
  1958. //===----------------------------------------------------------------------===//
  1959. // ExtractValueInst Class
  1960. //===----------------------------------------------------------------------===//
  1961. /// This instruction extracts a struct member or array
  1962. /// element value from an aggregate value.
  1963. ///
  1964. class ExtractValueInst : public UnaryInstruction {
  1965. SmallVector<unsigned, 4> Indices;
  1966. ExtractValueInst(const ExtractValueInst &EVI);
  1967. /// Constructors - Create a extractvalue instruction with a base aggregate
  1968. /// value and a list of indices. The first ctor can optionally insert before
  1969. /// an existing instruction, the second appends the new instruction to the
  1970. /// specified BasicBlock.
  1971. inline ExtractValueInst(Value *Agg,
  1972. ArrayRef<unsigned> Idxs,
  1973. const Twine &NameStr,
  1974. Instruction *InsertBefore);
  1975. inline ExtractValueInst(Value *Agg,
  1976. ArrayRef<unsigned> Idxs,
  1977. const Twine &NameStr, BasicBlock *InsertAtEnd);
  1978. void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
  1979. protected:
  1980. // Note: Instruction needs to be a friend here to call cloneImpl.
  1981. friend class Instruction;
  1982. ExtractValueInst *cloneImpl() const;
  1983. public:
  1984. static ExtractValueInst *Create(Value *Agg,
  1985. ArrayRef<unsigned> Idxs,
  1986. const Twine &NameStr = "",
  1987. Instruction *InsertBefore = nullptr) {
  1988. return new
  1989. ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
  1990. }
  1991. static ExtractValueInst *Create(Value *Agg,
  1992. ArrayRef<unsigned> Idxs,
  1993. const Twine &NameStr,
  1994. BasicBlock *InsertAtEnd) {
  1995. return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
  1996. }
  1997. /// Returns the type of the element that would be extracted
  1998. /// with an extractvalue instruction with the specified parameters.
  1999. ///
  2000. /// Null is returned if the indices are invalid for the specified type.
  2001. static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
  2002. using idx_iterator = const unsigned*;
  2003. inline idx_iterator idx_begin() const { return Indices.begin(); }
  2004. inline idx_iterator idx_end() const { return Indices.end(); }
  2005. inline iterator_range<idx_iterator> indices() const {
  2006. return make_range(idx_begin(), idx_end());
  2007. }
  2008. Value *getAggregateOperand() {
  2009. return getOperand(0);
  2010. }
  2011. const Value *getAggregateOperand() const {
  2012. return getOperand(0);
  2013. }
  2014. static unsigned getAggregateOperandIndex() {
  2015. return 0U; // get index for modifying correct operand
  2016. }
  2017. ArrayRef<unsigned> getIndices() const {
  2018. return Indices;
  2019. }
  2020. unsigned getNumIndices() const {
  2021. return (unsigned)Indices.size();
  2022. }
  2023. bool hasIndices() const {
  2024. return true;
  2025. }
  2026. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2027. static bool classof(const Instruction *I) {
  2028. return I->getOpcode() == Instruction::ExtractValue;
  2029. }
  2030. static bool classof(const Value *V) {
  2031. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2032. }
  2033. };
  2034. ExtractValueInst::ExtractValueInst(Value *Agg,
  2035. ArrayRef<unsigned> Idxs,
  2036. const Twine &NameStr,
  2037. Instruction *InsertBefore)
  2038. : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
  2039. ExtractValue, Agg, InsertBefore) {
  2040. init(Idxs, NameStr);
  2041. }
  2042. ExtractValueInst::ExtractValueInst(Value *Agg,
  2043. ArrayRef<unsigned> Idxs,
  2044. const Twine &NameStr,
  2045. BasicBlock *InsertAtEnd)
  2046. : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
  2047. ExtractValue, Agg, InsertAtEnd) {
  2048. init(Idxs, NameStr);
  2049. }
  2050. //===----------------------------------------------------------------------===//
  2051. // InsertValueInst Class
  2052. //===----------------------------------------------------------------------===//
  2053. /// This instruction inserts a struct field of array element
  2054. /// value into an aggregate value.
  2055. ///
  2056. class InsertValueInst : public Instruction {
  2057. SmallVector<unsigned, 4> Indices;
  2058. InsertValueInst(const InsertValueInst &IVI);
  2059. /// Constructors - Create a insertvalue instruction with a base aggregate
  2060. /// value, a value to insert, and a list of indices. The first ctor can
  2061. /// optionally insert before an existing instruction, the second appends
  2062. /// the new instruction to the specified BasicBlock.
  2063. inline InsertValueInst(Value *Agg, Value *Val,
  2064. ArrayRef<unsigned> Idxs,
  2065. const Twine &NameStr,
  2066. Instruction *InsertBefore);
  2067. inline InsertValueInst(Value *Agg, Value *Val,
  2068. ArrayRef<unsigned> Idxs,
  2069. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2070. /// Constructors - These two constructors are convenience methods because one
  2071. /// and two index insertvalue instructions are so common.
  2072. InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
  2073. const Twine &NameStr = "",
  2074. Instruction *InsertBefore = nullptr);
  2075. InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
  2076. BasicBlock *InsertAtEnd);
  2077. void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  2078. const Twine &NameStr);
  2079. protected:
  2080. // Note: Instruction needs to be a friend here to call cloneImpl.
  2081. friend class Instruction;
  2082. InsertValueInst *cloneImpl() const;
  2083. public:
  2084. // allocate space for exactly two operands
  2085. void *operator new(size_t s) {
  2086. return User::operator new(s, 2);
  2087. }
  2088. static InsertValueInst *Create(Value *Agg, Value *Val,
  2089. ArrayRef<unsigned> Idxs,
  2090. const Twine &NameStr = "",
  2091. Instruction *InsertBefore = nullptr) {
  2092. return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
  2093. }
  2094. static InsertValueInst *Create(Value *Agg, Value *Val,
  2095. ArrayRef<unsigned> Idxs,
  2096. const Twine &NameStr,
  2097. BasicBlock *InsertAtEnd) {
  2098. return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
  2099. }
  2100. /// Transparently provide more efficient getOperand methods.
  2101. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2102. using idx_iterator = const unsigned*;
  2103. inline idx_iterator idx_begin() const { return Indices.begin(); }
  2104. inline idx_iterator idx_end() const { return Indices.end(); }
  2105. inline iterator_range<idx_iterator> indices() const {
  2106. return make_range(idx_begin(), idx_end());
  2107. }
  2108. Value *getAggregateOperand() {
  2109. return getOperand(0);
  2110. }
  2111. const Value *getAggregateOperand() const {
  2112. return getOperand(0);
  2113. }
  2114. static unsigned getAggregateOperandIndex() {
  2115. return 0U; // get index for modifying correct operand
  2116. }
  2117. Value *getInsertedValueOperand() {
  2118. return getOperand(1);
  2119. }
  2120. const Value *getInsertedValueOperand() const {
  2121. return getOperand(1);
  2122. }
  2123. static unsigned getInsertedValueOperandIndex() {
  2124. return 1U; // get index for modifying correct operand
  2125. }
  2126. ArrayRef<unsigned> getIndices() const {
  2127. return Indices;
  2128. }
  2129. unsigned getNumIndices() const {
  2130. return (unsigned)Indices.size();
  2131. }
  2132. bool hasIndices() const {
  2133. return true;
  2134. }
  2135. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2136. static bool classof(const Instruction *I) {
  2137. return I->getOpcode() == Instruction::InsertValue;
  2138. }
  2139. static bool classof(const Value *V) {
  2140. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2141. }
  2142. };
  2143. template <>
  2144. struct OperandTraits<InsertValueInst> :
  2145. public FixedNumOperandTraits<InsertValueInst, 2> {
  2146. };
  2147. InsertValueInst::InsertValueInst(Value *Agg,
  2148. Value *Val,
  2149. ArrayRef<unsigned> Idxs,
  2150. const Twine &NameStr,
  2151. Instruction *InsertBefore)
  2152. : Instruction(Agg->getType(), InsertValue,
  2153. OperandTraits<InsertValueInst>::op_begin(this),
  2154. 2, InsertBefore) {
  2155. init(Agg, Val, Idxs, NameStr);
  2156. }
  2157. InsertValueInst::InsertValueInst(Value *Agg,
  2158. Value *Val,
  2159. ArrayRef<unsigned> Idxs,
  2160. const Twine &NameStr,
  2161. BasicBlock *InsertAtEnd)
  2162. : Instruction(Agg->getType(), InsertValue,
  2163. OperandTraits<InsertValueInst>::op_begin(this),
  2164. 2, InsertAtEnd) {
  2165. init(Agg, Val, Idxs, NameStr);
  2166. }
  2167. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
  2168. //===----------------------------------------------------------------------===//
  2169. // PHINode Class
  2170. //===----------------------------------------------------------------------===//
  2171. // PHINode - The PHINode class is used to represent the magical mystical PHI
  2172. // node, that can not exist in nature, but can be synthesized in a computer
  2173. // scientist's overactive imagination.
  2174. //
  2175. class PHINode : public Instruction {
  2176. /// The number of operands actually allocated. NumOperands is
  2177. /// the number actually in use.
  2178. unsigned ReservedSpace;
  2179. PHINode(const PHINode &PN);
  2180. explicit PHINode(Type *Ty, unsigned NumReservedValues,
  2181. const Twine &NameStr = "",
  2182. Instruction *InsertBefore = nullptr)
  2183. : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
  2184. ReservedSpace(NumReservedValues) {
  2185. assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!");
  2186. setName(NameStr);
  2187. allocHungoffUses(ReservedSpace);
  2188. }
  2189. PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
  2190. BasicBlock *InsertAtEnd)
  2191. : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
  2192. ReservedSpace(NumReservedValues) {
  2193. assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!");
  2194. setName(NameStr);
  2195. allocHungoffUses(ReservedSpace);
  2196. }
  2197. protected:
  2198. // Note: Instruction needs to be a friend here to call cloneImpl.
  2199. friend class Instruction;
  2200. PHINode *cloneImpl() const;
  2201. // allocHungoffUses - this is more complicated than the generic
  2202. // User::allocHungoffUses, because we have to allocate Uses for the incoming
  2203. // values and pointers to the incoming blocks, all in one allocation.
  2204. void allocHungoffUses(unsigned N) {
  2205. User::allocHungoffUses(N, /* IsPhi */ true);
  2206. }
  2207. public:
  2208. /// Constructors - NumReservedValues is a hint for the number of incoming
  2209. /// edges that this phi node will have (use 0 if you really have no idea).
  2210. static PHINode *Create(Type *Ty, unsigned NumReservedValues,
  2211. const Twine &NameStr = "",
  2212. Instruction *InsertBefore = nullptr) {
  2213. return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
  2214. }
  2215. static PHINode *Create(Type *Ty, unsigned NumReservedValues,
  2216. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  2217. return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
  2218. }
  2219. /// Provide fast operand accessors
  2220. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2221. // Block iterator interface. This provides access to the list of incoming
  2222. // basic blocks, which parallels the list of incoming values.
  2223. using block_iterator = BasicBlock **;
  2224. using const_block_iterator = BasicBlock * const *;
  2225. block_iterator block_begin() {
  2226. return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
  2227. }
  2228. const_block_iterator block_begin() const {
  2229. return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
  2230. }
  2231. block_iterator block_end() {
  2232. return block_begin() + getNumOperands();
  2233. }
  2234. const_block_iterator block_end() const {
  2235. return block_begin() + getNumOperands();
  2236. }
  2237. iterator_range<block_iterator> blocks() {
  2238. return make_range(block_begin(), block_end());
  2239. }
  2240. iterator_range<const_block_iterator> blocks() const {
  2241. return make_range(block_begin(), block_end());
  2242. }
  2243. op_range incoming_values() { return operands(); }
  2244. const_op_range incoming_values() const { return operands(); }
  2245. /// Return the number of incoming edges
  2246. ///
  2247. unsigned getNumIncomingValues() const { return getNumOperands(); }
  2248. /// Return incoming value number x
  2249. ///
  2250. Value *getIncomingValue(unsigned i) const {
  2251. return getOperand(i);
  2252. }
  2253. void setIncomingValue(unsigned i, Value *V) {
  2254. assert(V && "PHI node got a null value!");
  2255. assert(getType() == V->getType() &&
  2256. "All operands to PHI node must be the same type as the PHI node!");
  2257. setOperand(i, V);
  2258. }
  2259. static unsigned getOperandNumForIncomingValue(unsigned i) {
  2260. return i;
  2261. }
  2262. static unsigned getIncomingValueNumForOperand(unsigned i) {
  2263. return i;
  2264. }
  2265. /// Return incoming basic block number @p i.
  2266. ///
  2267. BasicBlock *getIncomingBlock(unsigned i) const {
  2268. return block_begin()[i];
  2269. }
  2270. /// Return incoming basic block corresponding
  2271. /// to an operand of the PHI.
  2272. ///
  2273. BasicBlock *getIncomingBlock(const Use &U) const {
  2274. assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
  2275. return getIncomingBlock(unsigned(&U - op_begin()));
  2276. }
  2277. /// Return incoming basic block corresponding
  2278. /// to value use iterator.
  2279. ///
  2280. BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
  2281. return getIncomingBlock(I.getUse());
  2282. }
  2283. void setIncomingBlock(unsigned i, BasicBlock *BB) {
  2284. assert(BB && "PHI node got a null basic block!");
  2285. block_begin()[i] = BB;
  2286. }
  2287. /// Replace every incoming basic block \p Old to basic block \p New.
  2288. void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
  2289. assert(New && Old && "PHI node got a null basic block!");
  2290. for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
  2291. if (getIncomingBlock(Op) == Old)
  2292. setIncomingBlock(Op, New);
  2293. }
  2294. /// Add an incoming value to the end of the PHI list
  2295. ///
  2296. void addIncoming(Value *V, BasicBlock *BB) {
  2297. if (getNumOperands() == ReservedSpace)
  2298. growOperands(); // Get more space!
  2299. // Initialize some new operands.
  2300. setNumHungOffUseOperands(getNumOperands() + 1);
  2301. setIncomingValue(getNumOperands() - 1, V);
  2302. setIncomingBlock(getNumOperands() - 1, BB);
  2303. }
  2304. /// Remove an incoming value. This is useful if a
  2305. /// predecessor basic block is deleted. The value removed is returned.
  2306. ///
  2307. /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
  2308. /// is true), the PHI node is destroyed and any uses of it are replaced with
  2309. /// dummy values. The only time there should be zero incoming values to a PHI
  2310. /// node is when the block is dead, so this strategy is sound.
  2311. ///
  2312. Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
  2313. Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
  2314. int Idx = getBasicBlockIndex(BB);
  2315. assert(Idx >= 0 && "Invalid basic block argument to remove!");
  2316. return removeIncomingValue(Idx, DeletePHIIfEmpty);
  2317. }
  2318. /// Return the first index of the specified basic
  2319. /// block in the value list for this PHI. Returns -1 if no instance.
  2320. ///
  2321. int getBasicBlockIndex(const BasicBlock *BB) const {
  2322. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  2323. if (block_begin()[i] == BB)
  2324. return i;
  2325. return -1;
  2326. }
  2327. Value *getIncomingValueForBlock(const BasicBlock *BB) const {
  2328. int Idx = getBasicBlockIndex(BB);
  2329. assert(Idx >= 0 && "Invalid basic block argument!");
  2330. return getIncomingValue(Idx);
  2331. }
  2332. /// Set every incoming value(s) for block \p BB to \p V.
  2333. void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
  2334. assert(BB && "PHI node got a null basic block!");
  2335. bool Found = false;
  2336. for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
  2337. if (getIncomingBlock(Op) == BB) {
  2338. Found = true;
  2339. setIncomingValue(Op, V);
  2340. }
  2341. (void)Found;
  2342. assert(Found && "Invalid basic block argument to set!");
  2343. }
  2344. /// If the specified PHI node always merges together the
  2345. /// same value, return the value, otherwise return null.
  2346. Value *hasConstantValue() const;
  2347. /// Whether the specified PHI node always merges
  2348. /// together the same value, assuming undefs are equal to a unique
  2349. /// non-undef value.
  2350. bool hasConstantOrUndefValue() const;
  2351. /// If the PHI node is complete which means all of its parent's predecessors
  2352. /// have incoming value in this PHI, return true, otherwise return false.
  2353. bool isComplete() const {
  2354. return llvm::all_of(predecessors(getParent()),
  2355. [this](const BasicBlock *Pred) {
  2356. return getBasicBlockIndex(Pred) >= 0;
  2357. });
  2358. }
  2359. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  2360. static bool classof(const Instruction *I) {
  2361. return I->getOpcode() == Instruction::PHI;
  2362. }
  2363. static bool classof(const Value *V) {
  2364. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2365. }
  2366. private:
  2367. void growOperands();
  2368. };
  2369. template <>
  2370. struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
  2371. };
  2372. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
  2373. //===----------------------------------------------------------------------===//
  2374. // LandingPadInst Class
  2375. //===----------------------------------------------------------------------===//
  2376. //===---------------------------------------------------------------------------
  2377. /// The landingpad instruction holds all of the information
  2378. /// necessary to generate correct exception handling. The landingpad instruction
  2379. /// cannot be moved from the top of a landing pad block, which itself is
  2380. /// accessible only from the 'unwind' edge of an invoke. This uses the
  2381. /// SubclassData field in Value to store whether or not the landingpad is a
  2382. /// cleanup.
  2383. ///
  2384. class LandingPadInst : public Instruction {
  2385. using CleanupField = BoolBitfieldElementT<0>;
  2386. /// The number of operands actually allocated. NumOperands is
  2387. /// the number actually in use.
  2388. unsigned ReservedSpace;
  2389. LandingPadInst(const LandingPadInst &LP);
  2390. public:
  2391. enum ClauseType { Catch, Filter };
  2392. private:
  2393. explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  2394. const Twine &NameStr, Instruction *InsertBefore);
  2395. explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  2396. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2397. // Allocate space for exactly zero operands.
  2398. void *operator new(size_t s) {
  2399. return User::operator new(s);
  2400. }
  2401. void growOperands(unsigned Size);
  2402. void init(unsigned NumReservedValues, const Twine &NameStr);
  2403. protected:
  2404. // Note: Instruction needs to be a friend here to call cloneImpl.
  2405. friend class Instruction;
  2406. LandingPadInst *cloneImpl() const;
  2407. public:
  2408. /// Constructors - NumReservedClauses is a hint for the number of incoming
  2409. /// clauses that this landingpad will have (use 0 if you really have no idea).
  2410. static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
  2411. const Twine &NameStr = "",
  2412. Instruction *InsertBefore = nullptr);
  2413. static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
  2414. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2415. /// Provide fast operand accessors
  2416. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2417. /// Return 'true' if this landingpad instruction is a
  2418. /// cleanup. I.e., it should be run when unwinding even if its landing pad
  2419. /// doesn't catch the exception.
  2420. bool isCleanup() const { return getSubclassData<CleanupField>(); }
  2421. /// Indicate that this landingpad instruction is a cleanup.
  2422. void setCleanup(bool V) { setSubclassData<CleanupField>(V); }
  2423. /// Add a catch or filter clause to the landing pad.
  2424. void addClause(Constant *ClauseVal);
  2425. /// Get the value of the clause at index Idx. Use isCatch/isFilter to
  2426. /// determine what type of clause this is.
  2427. Constant *getClause(unsigned Idx) const {
  2428. return cast<Constant>(getOperandList()[Idx]);
  2429. }
  2430. /// Return 'true' if the clause and index Idx is a catch clause.
  2431. bool isCatch(unsigned Idx) const {
  2432. return !isa<ArrayType>(getOperandList()[Idx]->getType());
  2433. }
  2434. /// Return 'true' if the clause and index Idx is a filter clause.
  2435. bool isFilter(unsigned Idx) const {
  2436. return isa<ArrayType>(getOperandList()[Idx]->getType());
  2437. }
  2438. /// Get the number of clauses for this landing pad.
  2439. unsigned getNumClauses() const { return getNumOperands(); }
  2440. /// Grow the size of the operand list to accommodate the new
  2441. /// number of clauses.
  2442. void reserveClauses(unsigned Size) { growOperands(Size); }
  2443. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2444. static bool classof(const Instruction *I) {
  2445. return I->getOpcode() == Instruction::LandingPad;
  2446. }
  2447. static bool classof(const Value *V) {
  2448. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2449. }
  2450. };
  2451. template <>
  2452. struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
  2453. };
  2454. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
  2455. //===----------------------------------------------------------------------===//
  2456. // ReturnInst Class
  2457. //===----------------------------------------------------------------------===//
  2458. //===---------------------------------------------------------------------------
  2459. /// Return a value (possibly void), from a function. Execution
  2460. /// does not continue in this function any longer.
  2461. ///
  2462. class ReturnInst : public Instruction {
  2463. ReturnInst(const ReturnInst &RI);
  2464. private:
  2465. // ReturnInst constructors:
  2466. // ReturnInst() - 'ret void' instruction
  2467. // ReturnInst( null) - 'ret void' instruction
  2468. // ReturnInst(Value* X) - 'ret X' instruction
  2469. // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
  2470. // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
  2471. // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
  2472. // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
  2473. //
  2474. // NOTE: If the Value* passed is of type void then the constructor behaves as
  2475. // if it was passed NULL.
  2476. explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
  2477. Instruction *InsertBefore = nullptr);
  2478. ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
  2479. explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
  2480. protected:
  2481. // Note: Instruction needs to be a friend here to call cloneImpl.
  2482. friend class Instruction;
  2483. ReturnInst *cloneImpl() const;
  2484. public:
  2485. static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
  2486. Instruction *InsertBefore = nullptr) {
  2487. return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
  2488. }
  2489. static ReturnInst* Create(LLVMContext &C, Value *retVal,
  2490. BasicBlock *InsertAtEnd) {
  2491. return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
  2492. }
  2493. static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
  2494. return new(0) ReturnInst(C, InsertAtEnd);
  2495. }
  2496. /// Provide fast operand accessors
  2497. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2498. /// Convenience accessor. Returns null if there is no return value.
  2499. Value *getReturnValue() const {
  2500. return getNumOperands() != 0 ? getOperand(0) : nullptr;
  2501. }
  2502. unsigned getNumSuccessors() const { return 0; }
  2503. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2504. static bool classof(const Instruction *I) {
  2505. return (I->getOpcode() == Instruction::Ret);
  2506. }
  2507. static bool classof(const Value *V) {
  2508. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2509. }
  2510. private:
  2511. BasicBlock *getSuccessor(unsigned idx) const {
  2512. llvm_unreachable("ReturnInst has no successors!");
  2513. }
  2514. void setSuccessor(unsigned idx, BasicBlock *B) {
  2515. llvm_unreachable("ReturnInst has no successors!");
  2516. }
  2517. };
  2518. template <>
  2519. struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
  2520. };
  2521. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
  2522. //===----------------------------------------------------------------------===//
  2523. // BranchInst Class
  2524. //===----------------------------------------------------------------------===//
  2525. //===---------------------------------------------------------------------------
  2526. /// Conditional or Unconditional Branch instruction.
  2527. ///
  2528. class BranchInst : public Instruction {
  2529. /// Ops list - Branches are strange. The operands are ordered:
  2530. /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
  2531. /// they don't have to check for cond/uncond branchness. These are mostly
  2532. /// accessed relative from op_end().
  2533. BranchInst(const BranchInst &BI);
  2534. // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
  2535. // BranchInst(BB *B) - 'br B'
  2536. // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
  2537. // BranchInst(BB* B, Inst *I) - 'br B' insert before I
  2538. // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
  2539. // BranchInst(BB* B, BB *I) - 'br B' insert at end
  2540. // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
  2541. explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
  2542. BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  2543. Instruction *InsertBefore = nullptr);
  2544. BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
  2545. BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  2546. BasicBlock *InsertAtEnd);
  2547. void AssertOK();
  2548. protected:
  2549. // Note: Instruction needs to be a friend here to call cloneImpl.
  2550. friend class Instruction;
  2551. BranchInst *cloneImpl() const;
  2552. public:
  2553. /// Iterator type that casts an operand to a basic block.
  2554. ///
  2555. /// This only makes sense because the successors are stored as adjacent
  2556. /// operands for branch instructions.
  2557. struct succ_op_iterator
  2558. : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
  2559. std::random_access_iterator_tag, BasicBlock *,
  2560. ptrdiff_t, BasicBlock *, BasicBlock *> {
  2561. explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
  2562. BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  2563. BasicBlock *operator->() const { return operator*(); }
  2564. };
  2565. /// The const version of `succ_op_iterator`.
  2566. struct const_succ_op_iterator
  2567. : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
  2568. std::random_access_iterator_tag,
  2569. const BasicBlock *, ptrdiff_t, const BasicBlock *,
  2570. const BasicBlock *> {
  2571. explicit const_succ_op_iterator(const_value_op_iterator I)
  2572. : iterator_adaptor_base(I) {}
  2573. const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  2574. const BasicBlock *operator->() const { return operator*(); }
  2575. };
  2576. static BranchInst *Create(BasicBlock *IfTrue,
  2577. Instruction *InsertBefore = nullptr) {
  2578. return new(1) BranchInst(IfTrue, InsertBefore);
  2579. }
  2580. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
  2581. Value *Cond, Instruction *InsertBefore = nullptr) {
  2582. return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
  2583. }
  2584. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
  2585. return new(1) BranchInst(IfTrue, InsertAtEnd);
  2586. }
  2587. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
  2588. Value *Cond, BasicBlock *InsertAtEnd) {
  2589. return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
  2590. }
  2591. /// Transparently provide more efficient getOperand methods.
  2592. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2593. bool isUnconditional() const { return getNumOperands() == 1; }
  2594. bool isConditional() const { return getNumOperands() == 3; }
  2595. Value *getCondition() const {
  2596. assert(isConditional() && "Cannot get condition of an uncond branch!");
  2597. return Op<-3>();
  2598. }
  2599. void setCondition(Value *V) {
  2600. assert(isConditional() && "Cannot set condition of unconditional branch!");
  2601. Op<-3>() = V;
  2602. }
  2603. unsigned getNumSuccessors() const { return 1+isConditional(); }
  2604. BasicBlock *getSuccessor(unsigned i) const {
  2605. assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
  2606. return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
  2607. }
  2608. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  2609. assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
  2610. *(&Op<-1>() - idx) = NewSucc;
  2611. }
  2612. /// Swap the successors of this branch instruction.
  2613. ///
  2614. /// Swaps the successors of the branch instruction. This also swaps any
  2615. /// branch weight metadata associated with the instruction so that it
  2616. /// continues to map correctly to each operand.
  2617. void swapSuccessors();
  2618. iterator_range<succ_op_iterator> successors() {
  2619. return make_range(
  2620. succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
  2621. succ_op_iterator(value_op_end()));
  2622. }
  2623. iterator_range<const_succ_op_iterator> successors() const {
  2624. return make_range(const_succ_op_iterator(
  2625. std::next(value_op_begin(), isConditional() ? 1 : 0)),
  2626. const_succ_op_iterator(value_op_end()));
  2627. }
  2628. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2629. static bool classof(const Instruction *I) {
  2630. return (I->getOpcode() == Instruction::Br);
  2631. }
  2632. static bool classof(const Value *V) {
  2633. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2634. }
  2635. };
  2636. template <>
  2637. struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
  2638. };
  2639. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
  2640. //===----------------------------------------------------------------------===//
  2641. // SwitchInst Class
  2642. //===----------------------------------------------------------------------===//
  2643. //===---------------------------------------------------------------------------
  2644. /// Multiway switch
  2645. ///
  2646. class SwitchInst : public Instruction {
  2647. unsigned ReservedSpace;
  2648. // Operand[0] = Value to switch on
  2649. // Operand[1] = Default basic block destination
  2650. // Operand[2n ] = Value to match
  2651. // Operand[2n+1] = BasicBlock to go to on match
  2652. SwitchInst(const SwitchInst &SI);
  2653. /// Create a new switch instruction, specifying a value to switch on and a
  2654. /// default destination. The number of additional cases can be specified here
  2655. /// to make memory allocation more efficient. This constructor can also
  2656. /// auto-insert before another instruction.
  2657. SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2658. Instruction *InsertBefore);
  2659. /// Create a new switch instruction, specifying a value to switch on and a
  2660. /// default destination. The number of additional cases can be specified here
  2661. /// to make memory allocation more efficient. This constructor also
  2662. /// auto-inserts at the end of the specified BasicBlock.
  2663. SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2664. BasicBlock *InsertAtEnd);
  2665. // allocate space for exactly zero operands
  2666. void *operator new(size_t s) {
  2667. return User::operator new(s);
  2668. }
  2669. void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
  2670. void growOperands();
  2671. protected:
  2672. // Note: Instruction needs to be a friend here to call cloneImpl.
  2673. friend class Instruction;
  2674. SwitchInst *cloneImpl() const;
  2675. public:
  2676. // -2
  2677. static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
  2678. template <typename CaseHandleT> class CaseIteratorImpl;
  2679. /// A handle to a particular switch case. It exposes a convenient interface
  2680. /// to both the case value and the successor block.
  2681. ///
  2682. /// We define this as a template and instantiate it to form both a const and
  2683. /// non-const handle.
  2684. template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
  2685. class CaseHandleImpl {
  2686. // Directly befriend both const and non-const iterators.
  2687. friend class SwitchInst::CaseIteratorImpl<
  2688. CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
  2689. protected:
  2690. // Expose the switch type we're parameterized with to the iterator.
  2691. using SwitchInstType = SwitchInstT;
  2692. SwitchInstT *SI;
  2693. ptrdiff_t Index;
  2694. CaseHandleImpl() = default;
  2695. CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
  2696. public:
  2697. /// Resolves case value for current case.
  2698. ConstantIntT *getCaseValue() const {
  2699. assert((unsigned)Index < SI->getNumCases() &&
  2700. "Index out the number of cases.");
  2701. return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
  2702. }
  2703. /// Resolves successor for current case.
  2704. BasicBlockT *getCaseSuccessor() const {
  2705. assert(((unsigned)Index < SI->getNumCases() ||
  2706. (unsigned)Index == DefaultPseudoIndex) &&
  2707. "Index out the number of cases.");
  2708. return SI->getSuccessor(getSuccessorIndex());
  2709. }
  2710. /// Returns number of current case.
  2711. unsigned getCaseIndex() const { return Index; }
  2712. /// Returns successor index for current case successor.
  2713. unsigned getSuccessorIndex() const {
  2714. assert(((unsigned)Index == DefaultPseudoIndex ||
  2715. (unsigned)Index < SI->getNumCases()) &&
  2716. "Index out the number of cases.");
  2717. return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
  2718. }
  2719. bool operator==(const CaseHandleImpl &RHS) const {
  2720. assert(SI == RHS.SI && "Incompatible operators.");
  2721. return Index == RHS.Index;
  2722. }
  2723. };
  2724. using ConstCaseHandle =
  2725. CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
  2726. class CaseHandle
  2727. : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
  2728. friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
  2729. public:
  2730. CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
  2731. /// Sets the new value for current case.
  2732. void setValue(ConstantInt *V) {
  2733. assert((unsigned)Index < SI->getNumCases() &&
  2734. "Index out the number of cases.");
  2735. SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
  2736. }
  2737. /// Sets the new successor for current case.
  2738. void setSuccessor(BasicBlock *S) {
  2739. SI->setSuccessor(getSuccessorIndex(), S);
  2740. }
  2741. };
  2742. template <typename CaseHandleT>
  2743. class CaseIteratorImpl
  2744. : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
  2745. std::random_access_iterator_tag,
  2746. CaseHandleT> {
  2747. using SwitchInstT = typename CaseHandleT::SwitchInstType;
  2748. CaseHandleT Case;
  2749. public:
  2750. /// Default constructed iterator is in an invalid state until assigned to
  2751. /// a case for a particular switch.
  2752. CaseIteratorImpl() = default;
  2753. /// Initializes case iterator for given SwitchInst and for given
  2754. /// case number.
  2755. CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
  2756. /// Initializes case iterator for given SwitchInst and for given
  2757. /// successor index.
  2758. static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
  2759. unsigned SuccessorIndex) {
  2760. assert(SuccessorIndex < SI->getNumSuccessors() &&
  2761. "Successor index # out of range!");
  2762. return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
  2763. : CaseIteratorImpl(SI, DefaultPseudoIndex);
  2764. }
  2765. /// Support converting to the const variant. This will be a no-op for const
  2766. /// variant.
  2767. operator CaseIteratorImpl<ConstCaseHandle>() const {
  2768. return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
  2769. }
  2770. CaseIteratorImpl &operator+=(ptrdiff_t N) {
  2771. // Check index correctness after addition.
  2772. // Note: Index == getNumCases() means end().
  2773. assert(Case.Index + N >= 0 &&
  2774. (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
  2775. "Case.Index out the number of cases.");
  2776. Case.Index += N;
  2777. return *this;
  2778. }
  2779. CaseIteratorImpl &operator-=(ptrdiff_t N) {
  2780. // Check index correctness after subtraction.
  2781. // Note: Case.Index == getNumCases() means end().
  2782. assert(Case.Index - N >= 0 &&
  2783. (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
  2784. "Case.Index out the number of cases.");
  2785. Case.Index -= N;
  2786. return *this;
  2787. }
  2788. ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
  2789. assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
  2790. return Case.Index - RHS.Case.Index;
  2791. }
  2792. bool operator==(const CaseIteratorImpl &RHS) const {
  2793. return Case == RHS.Case;
  2794. }
  2795. bool operator<(const CaseIteratorImpl &RHS) const {
  2796. assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
  2797. return Case.Index < RHS.Case.Index;
  2798. }
  2799. CaseHandleT &operator*() { return Case; }
  2800. const CaseHandleT &operator*() const { return Case; }
  2801. };
  2802. using CaseIt = CaseIteratorImpl<CaseHandle>;
  2803. using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
  2804. static SwitchInst *Create(Value *Value, BasicBlock *Default,
  2805. unsigned NumCases,
  2806. Instruction *InsertBefore = nullptr) {
  2807. return new SwitchInst(Value, Default, NumCases, InsertBefore);
  2808. }
  2809. static SwitchInst *Create(Value *Value, BasicBlock *Default,
  2810. unsigned NumCases, BasicBlock *InsertAtEnd) {
  2811. return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
  2812. }
  2813. /// Provide fast operand accessors
  2814. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2815. // Accessor Methods for Switch stmt
  2816. Value *getCondition() const { return getOperand(0); }
  2817. void setCondition(Value *V) { setOperand(0, V); }
  2818. BasicBlock *getDefaultDest() const {
  2819. return cast<BasicBlock>(getOperand(1));
  2820. }
  2821. void setDefaultDest(BasicBlock *DefaultCase) {
  2822. setOperand(1, reinterpret_cast<Value*>(DefaultCase));
  2823. }
  2824. /// Return the number of 'cases' in this switch instruction, excluding the
  2825. /// default case.
  2826. unsigned getNumCases() const {
  2827. return getNumOperands()/2 - 1;
  2828. }
  2829. /// Returns a read/write iterator that points to the first case in the
  2830. /// SwitchInst.
  2831. CaseIt case_begin() {
  2832. return CaseIt(this, 0);
  2833. }
  2834. /// Returns a read-only iterator that points to the first case in the
  2835. /// SwitchInst.
  2836. ConstCaseIt case_begin() const {
  2837. return ConstCaseIt(this, 0);
  2838. }
  2839. /// Returns a read/write iterator that points one past the last in the
  2840. /// SwitchInst.
  2841. CaseIt case_end() {
  2842. return CaseIt(this, getNumCases());
  2843. }
  2844. /// Returns a read-only iterator that points one past the last in the
  2845. /// SwitchInst.
  2846. ConstCaseIt case_end() const {
  2847. return ConstCaseIt(this, getNumCases());
  2848. }
  2849. /// Iteration adapter for range-for loops.
  2850. iterator_range<CaseIt> cases() {
  2851. return make_range(case_begin(), case_end());
  2852. }
  2853. /// Constant iteration adapter for range-for loops.
  2854. iterator_range<ConstCaseIt> cases() const {
  2855. return make_range(case_begin(), case_end());
  2856. }
  2857. /// Returns an iterator that points to the default case.
  2858. /// Note: this iterator allows to resolve successor only. Attempt
  2859. /// to resolve case value causes an assertion.
  2860. /// Also note, that increment and decrement also causes an assertion and
  2861. /// makes iterator invalid.
  2862. CaseIt case_default() {
  2863. return CaseIt(this, DefaultPseudoIndex);
  2864. }
  2865. ConstCaseIt case_default() const {
  2866. return ConstCaseIt(this, DefaultPseudoIndex);
  2867. }
  2868. /// Search all of the case values for the specified constant. If it is
  2869. /// explicitly handled, return the case iterator of it, otherwise return
  2870. /// default case iterator to indicate that it is handled by the default
  2871. /// handler.
  2872. CaseIt findCaseValue(const ConstantInt *C) {
  2873. CaseIt I = llvm::find_if(
  2874. cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
  2875. if (I != case_end())
  2876. return I;
  2877. return case_default();
  2878. }
  2879. ConstCaseIt findCaseValue(const ConstantInt *C) const {
  2880. ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
  2881. return Case.getCaseValue() == C;
  2882. });
  2883. if (I != case_end())
  2884. return I;
  2885. return case_default();
  2886. }
  2887. /// Finds the unique case value for a given successor. Returns null if the
  2888. /// successor is not found, not unique, or is the default case.
  2889. ConstantInt *findCaseDest(BasicBlock *BB) {
  2890. if (BB == getDefaultDest())
  2891. return nullptr;
  2892. ConstantInt *CI = nullptr;
  2893. for (auto Case : cases()) {
  2894. if (Case.getCaseSuccessor() != BB)
  2895. continue;
  2896. if (CI)
  2897. return nullptr; // Multiple cases lead to BB.
  2898. CI = Case.getCaseValue();
  2899. }
  2900. return CI;
  2901. }
  2902. /// Add an entry to the switch instruction.
  2903. /// Note:
  2904. /// This action invalidates case_end(). Old case_end() iterator will
  2905. /// point to the added case.
  2906. void addCase(ConstantInt *OnVal, BasicBlock *Dest);
  2907. /// This method removes the specified case and its successor from the switch
  2908. /// instruction. Note that this operation may reorder the remaining cases at
  2909. /// index idx and above.
  2910. /// Note:
  2911. /// This action invalidates iterators for all cases following the one removed,
  2912. /// including the case_end() iterator. It returns an iterator for the next
  2913. /// case.
  2914. CaseIt removeCase(CaseIt I);
  2915. unsigned getNumSuccessors() const { return getNumOperands()/2; }
  2916. BasicBlock *getSuccessor(unsigned idx) const {
  2917. assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
  2918. return cast<BasicBlock>(getOperand(idx*2+1));
  2919. }
  2920. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  2921. assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
  2922. setOperand(idx * 2 + 1, NewSucc);
  2923. }
  2924. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2925. static bool classof(const Instruction *I) {
  2926. return I->getOpcode() == Instruction::Switch;
  2927. }
  2928. static bool classof(const Value *V) {
  2929. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2930. }
  2931. };
  2932. /// A wrapper class to simplify modification of SwitchInst cases along with
  2933. /// their prof branch_weights metadata.
  2934. class SwitchInstProfUpdateWrapper {
  2935. SwitchInst &SI;
  2936. Optional<SmallVector<uint32_t, 8> > Weights = None;
  2937. bool Changed = false;
  2938. protected:
  2939. static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
  2940. MDNode *buildProfBranchWeightsMD();
  2941. void init();
  2942. public:
  2943. using CaseWeightOpt = Optional<uint32_t>;
  2944. SwitchInst *operator->() { return &SI; }
  2945. SwitchInst &operator*() { return SI; }
  2946. operator SwitchInst *() { return &SI; }
  2947. SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
  2948. ~SwitchInstProfUpdateWrapper() {
  2949. if (Changed)
  2950. SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
  2951. }
  2952. /// Delegate the call to the underlying SwitchInst::removeCase() and remove
  2953. /// correspondent branch weight.
  2954. SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
  2955. /// Delegate the call to the underlying SwitchInst::addCase() and set the
  2956. /// specified branch weight for the added case.
  2957. void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
  2958. /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
  2959. /// this object to not touch the underlying SwitchInst in destructor.
  2960. SymbolTableList<Instruction>::iterator eraseFromParent();
  2961. void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
  2962. CaseWeightOpt getSuccessorWeight(unsigned idx);
  2963. static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
  2964. };
  2965. template <>
  2966. struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
  2967. };
  2968. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
  2969. //===----------------------------------------------------------------------===//
  2970. // IndirectBrInst Class
  2971. //===----------------------------------------------------------------------===//
  2972. //===---------------------------------------------------------------------------
  2973. /// Indirect Branch Instruction.
  2974. ///
  2975. class IndirectBrInst : public Instruction {
  2976. unsigned ReservedSpace;
  2977. // Operand[0] = Address to jump to
  2978. // Operand[n+1] = n-th destination
  2979. IndirectBrInst(const IndirectBrInst &IBI);
  2980. /// Create a new indirectbr instruction, specifying an
  2981. /// Address to jump to. The number of expected destinations can be specified
  2982. /// here to make memory allocation more efficient. This constructor can also
  2983. /// autoinsert before another instruction.
  2984. IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
  2985. /// Create a new indirectbr instruction, specifying an
  2986. /// Address to jump to. The number of expected destinations can be specified
  2987. /// here to make memory allocation more efficient. This constructor also
  2988. /// autoinserts at the end of the specified BasicBlock.
  2989. IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
  2990. // allocate space for exactly zero operands
  2991. void *operator new(size_t s) {
  2992. return User::operator new(s);
  2993. }
  2994. void init(Value *Address, unsigned NumDests);
  2995. void growOperands();
  2996. protected:
  2997. // Note: Instruction needs to be a friend here to call cloneImpl.
  2998. friend class Instruction;
  2999. IndirectBrInst *cloneImpl() const;
  3000. public:
  3001. /// Iterator type that casts an operand to a basic block.
  3002. ///
  3003. /// This only makes sense because the successors are stored as adjacent
  3004. /// operands for indirectbr instructions.
  3005. struct succ_op_iterator
  3006. : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
  3007. std::random_access_iterator_tag, BasicBlock *,
  3008. ptrdiff_t, BasicBlock *, BasicBlock *> {
  3009. explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
  3010. BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  3011. BasicBlock *operator->() const { return operator*(); }
  3012. };
  3013. /// The const version of `succ_op_iterator`.
  3014. struct const_succ_op_iterator
  3015. : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
  3016. std::random_access_iterator_tag,
  3017. const BasicBlock *, ptrdiff_t, const BasicBlock *,
  3018. const BasicBlock *> {
  3019. explicit const_succ_op_iterator(const_value_op_iterator I)
  3020. : iterator_adaptor_base(I) {}
  3021. const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  3022. const BasicBlock *operator->() const { return operator*(); }
  3023. };
  3024. static IndirectBrInst *Create(Value *Address, unsigned NumDests,
  3025. Instruction *InsertBefore = nullptr) {
  3026. return new IndirectBrInst(Address, NumDests, InsertBefore);
  3027. }
  3028. static IndirectBrInst *Create(Value *Address, unsigned NumDests,
  3029. BasicBlock *InsertAtEnd) {
  3030. return new IndirectBrInst(Address, NumDests, InsertAtEnd);
  3031. }
  3032. /// Provide fast operand accessors.
  3033. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3034. // Accessor Methods for IndirectBrInst instruction.
  3035. Value *getAddress() { return getOperand(0); }
  3036. const Value *getAddress() const { return getOperand(0); }
  3037. void setAddress(Value *V) { setOperand(0, V); }
  3038. /// return the number of possible destinations in this
  3039. /// indirectbr instruction.
  3040. unsigned getNumDestinations() const { return getNumOperands()-1; }
  3041. /// Return the specified destination.
  3042. BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
  3043. const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
  3044. /// Add a destination.
  3045. ///
  3046. void addDestination(BasicBlock *Dest);
  3047. /// This method removes the specified successor from the
  3048. /// indirectbr instruction.
  3049. void removeDestination(unsigned i);
  3050. unsigned getNumSuccessors() const { return getNumOperands()-1; }
  3051. BasicBlock *getSuccessor(unsigned i) const {
  3052. return cast<BasicBlock>(getOperand(i+1));
  3053. }
  3054. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3055. setOperand(i + 1, NewSucc);
  3056. }
  3057. iterator_range<succ_op_iterator> successors() {
  3058. return make_range(succ_op_iterator(std::next(value_op_begin())),
  3059. succ_op_iterator(value_op_end()));
  3060. }
  3061. iterator_range<const_succ_op_iterator> successors() const {
  3062. return make_range(const_succ_op_iterator(std::next(value_op_begin())),
  3063. const_succ_op_iterator(value_op_end()));
  3064. }
  3065. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3066. static bool classof(const Instruction *I) {
  3067. return I->getOpcode() == Instruction::IndirectBr;
  3068. }
  3069. static bool classof(const Value *V) {
  3070. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3071. }
  3072. };
  3073. template <>
  3074. struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
  3075. };
  3076. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
  3077. //===----------------------------------------------------------------------===//
  3078. // InvokeInst Class
  3079. //===----------------------------------------------------------------------===//
  3080. /// Invoke instruction. The SubclassData field is used to hold the
  3081. /// calling convention of the call.
  3082. ///
  3083. class InvokeInst : public CallBase {
  3084. /// The number of operands for this call beyond the called function,
  3085. /// arguments, and operand bundles.
  3086. static constexpr int NumExtraOperands = 2;
  3087. /// The index from the end of the operand array to the normal destination.
  3088. static constexpr int NormalDestOpEndIdx = -3;
  3089. /// The index from the end of the operand array to the unwind destination.
  3090. static constexpr int UnwindDestOpEndIdx = -2;
  3091. InvokeInst(const InvokeInst &BI);
  3092. /// Construct an InvokeInst given a range of arguments.
  3093. ///
  3094. /// Construct an InvokeInst from a range of arguments
  3095. inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3096. BasicBlock *IfException, ArrayRef<Value *> Args,
  3097. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3098. const Twine &NameStr, Instruction *InsertBefore);
  3099. inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3100. BasicBlock *IfException, ArrayRef<Value *> Args,
  3101. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3102. const Twine &NameStr, BasicBlock *InsertAtEnd);
  3103. void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3104. BasicBlock *IfException, ArrayRef<Value *> Args,
  3105. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  3106. /// Compute the number of operands to allocate.
  3107. static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
  3108. // We need one operand for the called function, plus our extra operands and
  3109. // the input operand counts provided.
  3110. return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
  3111. }
  3112. protected:
  3113. // Note: Instruction needs to be a friend here to call cloneImpl.
  3114. friend class Instruction;
  3115. InvokeInst *cloneImpl() const;
  3116. public:
  3117. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3118. BasicBlock *IfException, ArrayRef<Value *> Args,
  3119. const Twine &NameStr,
  3120. Instruction *InsertBefore = nullptr) {
  3121. int NumOperands = ComputeNumOperands(Args.size());
  3122. return new (NumOperands)
  3123. InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
  3124. NameStr, InsertBefore);
  3125. }
  3126. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3127. BasicBlock *IfException, ArrayRef<Value *> Args,
  3128. ArrayRef<OperandBundleDef> Bundles = None,
  3129. const Twine &NameStr = "",
  3130. Instruction *InsertBefore = nullptr) {
  3131. int NumOperands =
  3132. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  3133. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3134. return new (NumOperands, DescriptorBytes)
  3135. InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
  3136. NameStr, InsertBefore);
  3137. }
  3138. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3139. BasicBlock *IfException, ArrayRef<Value *> Args,
  3140. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3141. int NumOperands = ComputeNumOperands(Args.size());
  3142. return new (NumOperands)
  3143. InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
  3144. NameStr, InsertAtEnd);
  3145. }
  3146. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3147. BasicBlock *IfException, ArrayRef<Value *> Args,
  3148. ArrayRef<OperandBundleDef> Bundles,
  3149. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3150. int NumOperands =
  3151. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  3152. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3153. return new (NumOperands, DescriptorBytes)
  3154. InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
  3155. NameStr, InsertAtEnd);
  3156. }
  3157. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3158. BasicBlock *IfException, ArrayRef<Value *> Args,
  3159. const Twine &NameStr,
  3160. Instruction *InsertBefore = nullptr) {
  3161. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3162. IfException, Args, None, NameStr, InsertBefore);
  3163. }
  3164. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3165. BasicBlock *IfException, ArrayRef<Value *> Args,
  3166. ArrayRef<OperandBundleDef> Bundles = None,
  3167. const Twine &NameStr = "",
  3168. Instruction *InsertBefore = nullptr) {
  3169. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3170. IfException, Args, Bundles, NameStr, InsertBefore);
  3171. }
  3172. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3173. BasicBlock *IfException, ArrayRef<Value *> Args,
  3174. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3175. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3176. IfException, Args, NameStr, InsertAtEnd);
  3177. }
  3178. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3179. BasicBlock *IfException, ArrayRef<Value *> Args,
  3180. ArrayRef<OperandBundleDef> Bundles,
  3181. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3182. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3183. IfException, Args, Bundles, NameStr, InsertAtEnd);
  3184. }
  3185. /// Create a clone of \p II with a different set of operand bundles and
  3186. /// insert it before \p InsertPt.
  3187. ///
  3188. /// The returned invoke instruction is identical to \p II in every way except
  3189. /// that the operand bundles for the new instruction are set to the operand
  3190. /// bundles in \p Bundles.
  3191. static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
  3192. Instruction *InsertPt = nullptr);
  3193. // get*Dest - Return the destination basic blocks...
  3194. BasicBlock *getNormalDest() const {
  3195. return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
  3196. }
  3197. BasicBlock *getUnwindDest() const {
  3198. return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
  3199. }
  3200. void setNormalDest(BasicBlock *B) {
  3201. Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
  3202. }
  3203. void setUnwindDest(BasicBlock *B) {
  3204. Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
  3205. }
  3206. /// Get the landingpad instruction from the landing pad
  3207. /// block (the unwind destination).
  3208. LandingPadInst *getLandingPadInst() const;
  3209. BasicBlock *getSuccessor(unsigned i) const {
  3210. assert(i < 2 && "Successor # out of range for invoke!");
  3211. return i == 0 ? getNormalDest() : getUnwindDest();
  3212. }
  3213. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3214. assert(i < 2 && "Successor # out of range for invoke!");
  3215. if (i == 0)
  3216. setNormalDest(NewSucc);
  3217. else
  3218. setUnwindDest(NewSucc);
  3219. }
  3220. unsigned getNumSuccessors() const { return 2; }
  3221. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3222. static bool classof(const Instruction *I) {
  3223. return (I->getOpcode() == Instruction::Invoke);
  3224. }
  3225. static bool classof(const Value *V) {
  3226. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3227. }
  3228. private:
  3229. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3230. // method so that subclasses cannot accidentally use it.
  3231. template <typename Bitfield>
  3232. void setSubclassData(typename Bitfield::Type Value) {
  3233. Instruction::setSubclassData<Bitfield>(Value);
  3234. }
  3235. };
  3236. InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3237. BasicBlock *IfException, ArrayRef<Value *> Args,
  3238. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3239. const Twine &NameStr, Instruction *InsertBefore)
  3240. : CallBase(Ty->getReturnType(), Instruction::Invoke,
  3241. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3242. InsertBefore) {
  3243. init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
  3244. }
  3245. InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3246. BasicBlock *IfException, ArrayRef<Value *> Args,
  3247. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3248. const Twine &NameStr, BasicBlock *InsertAtEnd)
  3249. : CallBase(Ty->getReturnType(), Instruction::Invoke,
  3250. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3251. InsertAtEnd) {
  3252. init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
  3253. }
  3254. //===----------------------------------------------------------------------===//
  3255. // CallBrInst Class
  3256. //===----------------------------------------------------------------------===//
  3257. /// CallBr instruction, tracking function calls that may not return control but
  3258. /// instead transfer it to a third location. The SubclassData field is used to
  3259. /// hold the calling convention of the call.
  3260. ///
  3261. class CallBrInst : public CallBase {
  3262. unsigned NumIndirectDests;
  3263. CallBrInst(const CallBrInst &BI);
  3264. /// Construct a CallBrInst given a range of arguments.
  3265. ///
  3266. /// Construct a CallBrInst from a range of arguments
  3267. inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3268. ArrayRef<BasicBlock *> IndirectDests,
  3269. ArrayRef<Value *> Args,
  3270. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3271. const Twine &NameStr, Instruction *InsertBefore);
  3272. inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3273. ArrayRef<BasicBlock *> IndirectDests,
  3274. ArrayRef<Value *> Args,
  3275. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3276. const Twine &NameStr, BasicBlock *InsertAtEnd);
  3277. void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
  3278. ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
  3279. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  3280. /// Should the Indirect Destinations change, scan + update the Arg list.
  3281. void updateArgBlockAddresses(unsigned i, BasicBlock *B);
  3282. /// Compute the number of operands to allocate.
  3283. static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
  3284. int NumBundleInputs = 0) {
  3285. // We need one operand for the called function, plus our extra operands and
  3286. // the input operand counts provided.
  3287. return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
  3288. }
  3289. protected:
  3290. // Note: Instruction needs to be a friend here to call cloneImpl.
  3291. friend class Instruction;
  3292. CallBrInst *cloneImpl() const;
  3293. public:
  3294. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3295. BasicBlock *DefaultDest,
  3296. ArrayRef<BasicBlock *> IndirectDests,
  3297. ArrayRef<Value *> Args, const Twine &NameStr,
  3298. Instruction *InsertBefore = nullptr) {
  3299. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
  3300. return new (NumOperands)
  3301. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
  3302. NumOperands, NameStr, InsertBefore);
  3303. }
  3304. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3305. BasicBlock *DefaultDest,
  3306. ArrayRef<BasicBlock *> IndirectDests,
  3307. ArrayRef<Value *> Args,
  3308. ArrayRef<OperandBundleDef> Bundles = None,
  3309. const Twine &NameStr = "",
  3310. Instruction *InsertBefore = nullptr) {
  3311. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
  3312. CountBundleInputs(Bundles));
  3313. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3314. return new (NumOperands, DescriptorBytes)
  3315. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
  3316. NumOperands, NameStr, InsertBefore);
  3317. }
  3318. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3319. BasicBlock *DefaultDest,
  3320. ArrayRef<BasicBlock *> IndirectDests,
  3321. ArrayRef<Value *> Args, const Twine &NameStr,
  3322. BasicBlock *InsertAtEnd) {
  3323. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
  3324. return new (NumOperands)
  3325. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
  3326. NumOperands, NameStr, InsertAtEnd);
  3327. }
  3328. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3329. BasicBlock *DefaultDest,
  3330. ArrayRef<BasicBlock *> IndirectDests,
  3331. ArrayRef<Value *> Args,
  3332. ArrayRef<OperandBundleDef> Bundles,
  3333. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3334. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
  3335. CountBundleInputs(Bundles));
  3336. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3337. return new (NumOperands, DescriptorBytes)
  3338. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
  3339. NumOperands, NameStr, InsertAtEnd);
  3340. }
  3341. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3342. ArrayRef<BasicBlock *> IndirectDests,
  3343. ArrayRef<Value *> Args, const Twine &NameStr,
  3344. Instruction *InsertBefore = nullptr) {
  3345. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3346. IndirectDests, Args, NameStr, InsertBefore);
  3347. }
  3348. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3349. ArrayRef<BasicBlock *> IndirectDests,
  3350. ArrayRef<Value *> Args,
  3351. ArrayRef<OperandBundleDef> Bundles = None,
  3352. const Twine &NameStr = "",
  3353. Instruction *InsertBefore = nullptr) {
  3354. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3355. IndirectDests, Args, Bundles, NameStr, InsertBefore);
  3356. }
  3357. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3358. ArrayRef<BasicBlock *> IndirectDests,
  3359. ArrayRef<Value *> Args, const Twine &NameStr,
  3360. BasicBlock *InsertAtEnd) {
  3361. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3362. IndirectDests, Args, NameStr, InsertAtEnd);
  3363. }
  3364. static CallBrInst *Create(FunctionCallee Func,
  3365. BasicBlock *DefaultDest,
  3366. ArrayRef<BasicBlock *> IndirectDests,
  3367. ArrayRef<Value *> Args,
  3368. ArrayRef<OperandBundleDef> Bundles,
  3369. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3370. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3371. IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
  3372. }
  3373. /// Create a clone of \p CBI with a different set of operand bundles and
  3374. /// insert it before \p InsertPt.
  3375. ///
  3376. /// The returned callbr instruction is identical to \p CBI in every way
  3377. /// except that the operand bundles for the new instruction are set to the
  3378. /// operand bundles in \p Bundles.
  3379. static CallBrInst *Create(CallBrInst *CBI,
  3380. ArrayRef<OperandBundleDef> Bundles,
  3381. Instruction *InsertPt = nullptr);
  3382. /// Return the number of callbr indirect dest labels.
  3383. ///
  3384. unsigned getNumIndirectDests() const { return NumIndirectDests; }
  3385. /// getIndirectDestLabel - Return the i-th indirect dest label.
  3386. ///
  3387. Value *getIndirectDestLabel(unsigned i) const {
  3388. assert(i < getNumIndirectDests() && "Out of bounds!");
  3389. return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
  3390. 1);
  3391. }
  3392. Value *getIndirectDestLabelUse(unsigned i) const {
  3393. assert(i < getNumIndirectDests() && "Out of bounds!");
  3394. return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
  3395. 1);
  3396. }
  3397. // Return the destination basic blocks...
  3398. BasicBlock *getDefaultDest() const {
  3399. return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
  3400. }
  3401. BasicBlock *getIndirectDest(unsigned i) const {
  3402. return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
  3403. }
  3404. SmallVector<BasicBlock *, 16> getIndirectDests() const {
  3405. SmallVector<BasicBlock *, 16> IndirectDests;
  3406. for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
  3407. IndirectDests.push_back(getIndirectDest(i));
  3408. return IndirectDests;
  3409. }
  3410. void setDefaultDest(BasicBlock *B) {
  3411. *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
  3412. }
  3413. void setIndirectDest(unsigned i, BasicBlock *B) {
  3414. updateArgBlockAddresses(i, B);
  3415. *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
  3416. }
  3417. BasicBlock *getSuccessor(unsigned i) const {
  3418. assert(i < getNumSuccessors() + 1 &&
  3419. "Successor # out of range for callbr!");
  3420. return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
  3421. }
  3422. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3423. assert(i < getNumIndirectDests() + 1 &&
  3424. "Successor # out of range for callbr!");
  3425. return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
  3426. }
  3427. unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
  3428. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3429. static bool classof(const Instruction *I) {
  3430. return (I->getOpcode() == Instruction::CallBr);
  3431. }
  3432. static bool classof(const Value *V) {
  3433. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3434. }
  3435. private:
  3436. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3437. // method so that subclasses cannot accidentally use it.
  3438. template <typename Bitfield>
  3439. void setSubclassData(typename Bitfield::Type Value) {
  3440. Instruction::setSubclassData<Bitfield>(Value);
  3441. }
  3442. };
  3443. CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3444. ArrayRef<BasicBlock *> IndirectDests,
  3445. ArrayRef<Value *> Args,
  3446. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3447. const Twine &NameStr, Instruction *InsertBefore)
  3448. : CallBase(Ty->getReturnType(), Instruction::CallBr,
  3449. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3450. InsertBefore) {
  3451. init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
  3452. }
  3453. CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3454. ArrayRef<BasicBlock *> IndirectDests,
  3455. ArrayRef<Value *> Args,
  3456. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3457. const Twine &NameStr, BasicBlock *InsertAtEnd)
  3458. : CallBase(Ty->getReturnType(), Instruction::CallBr,
  3459. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3460. InsertAtEnd) {
  3461. init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
  3462. }
  3463. //===----------------------------------------------------------------------===//
  3464. // ResumeInst Class
  3465. //===----------------------------------------------------------------------===//
  3466. //===---------------------------------------------------------------------------
  3467. /// Resume the propagation of an exception.
  3468. ///
  3469. class ResumeInst : public Instruction {
  3470. ResumeInst(const ResumeInst &RI);
  3471. explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
  3472. ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
  3473. protected:
  3474. // Note: Instruction needs to be a friend here to call cloneImpl.
  3475. friend class Instruction;
  3476. ResumeInst *cloneImpl() const;
  3477. public:
  3478. static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
  3479. return new(1) ResumeInst(Exn, InsertBefore);
  3480. }
  3481. static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
  3482. return new(1) ResumeInst(Exn, InsertAtEnd);
  3483. }
  3484. /// Provide fast operand accessors
  3485. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3486. /// Convenience accessor.
  3487. Value *getValue() const { return Op<0>(); }
  3488. unsigned getNumSuccessors() const { return 0; }
  3489. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3490. static bool classof(const Instruction *I) {
  3491. return I->getOpcode() == Instruction::Resume;
  3492. }
  3493. static bool classof(const Value *V) {
  3494. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3495. }
  3496. private:
  3497. BasicBlock *getSuccessor(unsigned idx) const {
  3498. llvm_unreachable("ResumeInst has no successors!");
  3499. }
  3500. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  3501. llvm_unreachable("ResumeInst has no successors!");
  3502. }
  3503. };
  3504. template <>
  3505. struct OperandTraits<ResumeInst> :
  3506. public FixedNumOperandTraits<ResumeInst, 1> {
  3507. };
  3508. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
  3509. //===----------------------------------------------------------------------===//
  3510. // CatchSwitchInst Class
  3511. //===----------------------------------------------------------------------===//
  3512. class CatchSwitchInst : public Instruction {
  3513. using UnwindDestField = BoolBitfieldElementT<0>;
  3514. /// The number of operands actually allocated. NumOperands is
  3515. /// the number actually in use.
  3516. unsigned ReservedSpace;
  3517. // Operand[0] = Outer scope
  3518. // Operand[1] = Unwind block destination
  3519. // Operand[n] = BasicBlock to go to on match
  3520. CatchSwitchInst(const CatchSwitchInst &CSI);
  3521. /// Create a new switch instruction, specifying a
  3522. /// default destination. The number of additional handlers can be specified
  3523. /// here to make memory allocation more efficient.
  3524. /// This constructor can also autoinsert before another instruction.
  3525. CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  3526. unsigned NumHandlers, const Twine &NameStr,
  3527. Instruction *InsertBefore);
  3528. /// Create a new switch instruction, specifying a
  3529. /// default destination. The number of additional handlers can be specified
  3530. /// here to make memory allocation more efficient.
  3531. /// This constructor also autoinserts at the end of the specified BasicBlock.
  3532. CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  3533. unsigned NumHandlers, const Twine &NameStr,
  3534. BasicBlock *InsertAtEnd);
  3535. // allocate space for exactly zero operands
  3536. void *operator new(size_t s) { return User::operator new(s); }
  3537. void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
  3538. void growOperands(unsigned Size);
  3539. protected:
  3540. // Note: Instruction needs to be a friend here to call cloneImpl.
  3541. friend class Instruction;
  3542. CatchSwitchInst *cloneImpl() const;
  3543. public:
  3544. static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
  3545. unsigned NumHandlers,
  3546. const Twine &NameStr = "",
  3547. Instruction *InsertBefore = nullptr) {
  3548. return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
  3549. InsertBefore);
  3550. }
  3551. static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
  3552. unsigned NumHandlers, const Twine &NameStr,
  3553. BasicBlock *InsertAtEnd) {
  3554. return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
  3555. InsertAtEnd);
  3556. }
  3557. /// Provide fast operand accessors
  3558. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3559. // Accessor Methods for CatchSwitch stmt
  3560. Value *getParentPad() const { return getOperand(0); }
  3561. void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
  3562. // Accessor Methods for CatchSwitch stmt
  3563. bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
  3564. bool unwindsToCaller() const { return !hasUnwindDest(); }
  3565. BasicBlock *getUnwindDest() const {
  3566. if (hasUnwindDest())
  3567. return cast<BasicBlock>(getOperand(1));
  3568. return nullptr;
  3569. }
  3570. void setUnwindDest(BasicBlock *UnwindDest) {
  3571. assert(UnwindDest);
  3572. assert(hasUnwindDest());
  3573. setOperand(1, UnwindDest);
  3574. }
  3575. /// return the number of 'handlers' in this catchswitch
  3576. /// instruction, except the default handler
  3577. unsigned getNumHandlers() const {
  3578. if (hasUnwindDest())
  3579. return getNumOperands() - 2;
  3580. return getNumOperands() - 1;
  3581. }
  3582. private:
  3583. static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
  3584. static const BasicBlock *handler_helper(const Value *V) {
  3585. return cast<BasicBlock>(V);
  3586. }
  3587. public:
  3588. using DerefFnTy = BasicBlock *(*)(Value *);
  3589. using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
  3590. using handler_range = iterator_range<handler_iterator>;
  3591. using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
  3592. using const_handler_iterator =
  3593. mapped_iterator<const_op_iterator, ConstDerefFnTy>;
  3594. using const_handler_range = iterator_range<const_handler_iterator>;
  3595. /// Returns an iterator that points to the first handler in CatchSwitchInst.
  3596. handler_iterator handler_begin() {
  3597. op_iterator It = op_begin() + 1;
  3598. if (hasUnwindDest())
  3599. ++It;
  3600. return handler_iterator(It, DerefFnTy(handler_helper));
  3601. }
  3602. /// Returns an iterator that points to the first handler in the
  3603. /// CatchSwitchInst.
  3604. const_handler_iterator handler_begin() const {
  3605. const_op_iterator It = op_begin() + 1;
  3606. if (hasUnwindDest())
  3607. ++It;
  3608. return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
  3609. }
  3610. /// Returns a read-only iterator that points one past the last
  3611. /// handler in the CatchSwitchInst.
  3612. handler_iterator handler_end() {
  3613. return handler_iterator(op_end(), DerefFnTy(handler_helper));
  3614. }
  3615. /// Returns an iterator that points one past the last handler in the
  3616. /// CatchSwitchInst.
  3617. const_handler_iterator handler_end() const {
  3618. return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
  3619. }
  3620. /// iteration adapter for range-for loops.
  3621. handler_range handlers() {
  3622. return make_range(handler_begin(), handler_end());
  3623. }
  3624. /// iteration adapter for range-for loops.
  3625. const_handler_range handlers() const {
  3626. return make_range(handler_begin(), handler_end());
  3627. }
  3628. /// Add an entry to the switch instruction...
  3629. /// Note:
  3630. /// This action invalidates handler_end(). Old handler_end() iterator will
  3631. /// point to the added handler.
  3632. void addHandler(BasicBlock *Dest);
  3633. void removeHandler(handler_iterator HI);
  3634. unsigned getNumSuccessors() const { return getNumOperands() - 1; }
  3635. BasicBlock *getSuccessor(unsigned Idx) const {
  3636. assert(Idx < getNumSuccessors() &&
  3637. "Successor # out of range for catchswitch!");
  3638. return cast<BasicBlock>(getOperand(Idx + 1));
  3639. }
  3640. void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
  3641. assert(Idx < getNumSuccessors() &&
  3642. "Successor # out of range for catchswitch!");
  3643. setOperand(Idx + 1, NewSucc);
  3644. }
  3645. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3646. static bool classof(const Instruction *I) {
  3647. return I->getOpcode() == Instruction::CatchSwitch;
  3648. }
  3649. static bool classof(const Value *V) {
  3650. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3651. }
  3652. };
  3653. template <>
  3654. struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
  3655. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
  3656. //===----------------------------------------------------------------------===//
  3657. // CleanupPadInst Class
  3658. //===----------------------------------------------------------------------===//
  3659. class CleanupPadInst : public FuncletPadInst {
  3660. private:
  3661. explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
  3662. unsigned Values, const Twine &NameStr,
  3663. Instruction *InsertBefore)
  3664. : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
  3665. NameStr, InsertBefore) {}
  3666. explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
  3667. unsigned Values, const Twine &NameStr,
  3668. BasicBlock *InsertAtEnd)
  3669. : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
  3670. NameStr, InsertAtEnd) {}
  3671. public:
  3672. static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
  3673. const Twine &NameStr = "",
  3674. Instruction *InsertBefore = nullptr) {
  3675. unsigned Values = 1 + Args.size();
  3676. return new (Values)
  3677. CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
  3678. }
  3679. static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
  3680. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3681. unsigned Values = 1 + Args.size();
  3682. return new (Values)
  3683. CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
  3684. }
  3685. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3686. static bool classof(const Instruction *I) {
  3687. return I->getOpcode() == Instruction::CleanupPad;
  3688. }
  3689. static bool classof(const Value *V) {
  3690. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3691. }
  3692. };
  3693. //===----------------------------------------------------------------------===//
  3694. // CatchPadInst Class
  3695. //===----------------------------------------------------------------------===//
  3696. class CatchPadInst : public FuncletPadInst {
  3697. private:
  3698. explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
  3699. unsigned Values, const Twine &NameStr,
  3700. Instruction *InsertBefore)
  3701. : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
  3702. NameStr, InsertBefore) {}
  3703. explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
  3704. unsigned Values, const Twine &NameStr,
  3705. BasicBlock *InsertAtEnd)
  3706. : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
  3707. NameStr, InsertAtEnd) {}
  3708. public:
  3709. static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
  3710. const Twine &NameStr = "",
  3711. Instruction *InsertBefore = nullptr) {
  3712. unsigned Values = 1 + Args.size();
  3713. return new (Values)
  3714. CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
  3715. }
  3716. static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
  3717. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3718. unsigned Values = 1 + Args.size();
  3719. return new (Values)
  3720. CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
  3721. }
  3722. /// Convenience accessors
  3723. CatchSwitchInst *getCatchSwitch() const {
  3724. return cast<CatchSwitchInst>(Op<-1>());
  3725. }
  3726. void setCatchSwitch(Value *CatchSwitch) {
  3727. assert(CatchSwitch);
  3728. Op<-1>() = CatchSwitch;
  3729. }
  3730. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3731. static bool classof(const Instruction *I) {
  3732. return I->getOpcode() == Instruction::CatchPad;
  3733. }
  3734. static bool classof(const Value *V) {
  3735. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3736. }
  3737. };
  3738. //===----------------------------------------------------------------------===//
  3739. // CatchReturnInst Class
  3740. //===----------------------------------------------------------------------===//
  3741. class CatchReturnInst : public Instruction {
  3742. CatchReturnInst(const CatchReturnInst &RI);
  3743. CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
  3744. CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
  3745. void init(Value *CatchPad, BasicBlock *BB);
  3746. protected:
  3747. // Note: Instruction needs to be a friend here to call cloneImpl.
  3748. friend class Instruction;
  3749. CatchReturnInst *cloneImpl() const;
  3750. public:
  3751. static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
  3752. Instruction *InsertBefore = nullptr) {
  3753. assert(CatchPad);
  3754. assert(BB);
  3755. return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
  3756. }
  3757. static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
  3758. BasicBlock *InsertAtEnd) {
  3759. assert(CatchPad);
  3760. assert(BB);
  3761. return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
  3762. }
  3763. /// Provide fast operand accessors
  3764. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3765. /// Convenience accessors.
  3766. CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
  3767. void setCatchPad(CatchPadInst *CatchPad) {
  3768. assert(CatchPad);
  3769. Op<0>() = CatchPad;
  3770. }
  3771. BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
  3772. void setSuccessor(BasicBlock *NewSucc) {
  3773. assert(NewSucc);
  3774. Op<1>() = NewSucc;
  3775. }
  3776. unsigned getNumSuccessors() const { return 1; }
  3777. /// Get the parentPad of this catchret's catchpad's catchswitch.
  3778. /// The successor block is implicitly a member of this funclet.
  3779. Value *getCatchSwitchParentPad() const {
  3780. return getCatchPad()->getCatchSwitch()->getParentPad();
  3781. }
  3782. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3783. static bool classof(const Instruction *I) {
  3784. return (I->getOpcode() == Instruction::CatchRet);
  3785. }
  3786. static bool classof(const Value *V) {
  3787. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3788. }
  3789. private:
  3790. BasicBlock *getSuccessor(unsigned Idx) const {
  3791. assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
  3792. return getSuccessor();
  3793. }
  3794. void setSuccessor(unsigned Idx, BasicBlock *B) {
  3795. assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
  3796. setSuccessor(B);
  3797. }
  3798. };
  3799. template <>
  3800. struct OperandTraits<CatchReturnInst>
  3801. : public FixedNumOperandTraits<CatchReturnInst, 2> {};
  3802. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
  3803. //===----------------------------------------------------------------------===//
  3804. // CleanupReturnInst Class
  3805. //===----------------------------------------------------------------------===//
  3806. class CleanupReturnInst : public Instruction {
  3807. using UnwindDestField = BoolBitfieldElementT<0>;
  3808. private:
  3809. CleanupReturnInst(const CleanupReturnInst &RI);
  3810. CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
  3811. Instruction *InsertBefore = nullptr);
  3812. CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
  3813. BasicBlock *InsertAtEnd);
  3814. void init(Value *CleanupPad, BasicBlock *UnwindBB);
  3815. protected:
  3816. // Note: Instruction needs to be a friend here to call cloneImpl.
  3817. friend class Instruction;
  3818. CleanupReturnInst *cloneImpl() const;
  3819. public:
  3820. static CleanupReturnInst *Create(Value *CleanupPad,
  3821. BasicBlock *UnwindBB = nullptr,
  3822. Instruction *InsertBefore = nullptr) {
  3823. assert(CleanupPad);
  3824. unsigned Values = 1;
  3825. if (UnwindBB)
  3826. ++Values;
  3827. return new (Values)
  3828. CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
  3829. }
  3830. static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
  3831. BasicBlock *InsertAtEnd) {
  3832. assert(CleanupPad);
  3833. unsigned Values = 1;
  3834. if (UnwindBB)
  3835. ++Values;
  3836. return new (Values)
  3837. CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
  3838. }
  3839. /// Provide fast operand accessors
  3840. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3841. bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
  3842. bool unwindsToCaller() const { return !hasUnwindDest(); }
  3843. /// Convenience accessor.
  3844. CleanupPadInst *getCleanupPad() const {
  3845. return cast<CleanupPadInst>(Op<0>());
  3846. }
  3847. void setCleanupPad(CleanupPadInst *CleanupPad) {
  3848. assert(CleanupPad);
  3849. Op<0>() = CleanupPad;
  3850. }
  3851. unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
  3852. BasicBlock *getUnwindDest() const {
  3853. return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
  3854. }
  3855. void setUnwindDest(BasicBlock *NewDest) {
  3856. assert(NewDest);
  3857. assert(hasUnwindDest());
  3858. Op<1>() = NewDest;
  3859. }
  3860. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3861. static bool classof(const Instruction *I) {
  3862. return (I->getOpcode() == Instruction::CleanupRet);
  3863. }
  3864. static bool classof(const Value *V) {
  3865. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3866. }
  3867. private:
  3868. BasicBlock *getSuccessor(unsigned Idx) const {
  3869. assert(Idx == 0);
  3870. return getUnwindDest();
  3871. }
  3872. void setSuccessor(unsigned Idx, BasicBlock *B) {
  3873. assert(Idx == 0);
  3874. setUnwindDest(B);
  3875. }
  3876. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3877. // method so that subclasses cannot accidentally use it.
  3878. template <typename Bitfield>
  3879. void setSubclassData(typename Bitfield::Type Value) {
  3880. Instruction::setSubclassData<Bitfield>(Value);
  3881. }
  3882. };
  3883. template <>
  3884. struct OperandTraits<CleanupReturnInst>
  3885. : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
  3886. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
  3887. //===----------------------------------------------------------------------===//
  3888. // UnreachableInst Class
  3889. //===----------------------------------------------------------------------===//
  3890. //===---------------------------------------------------------------------------
  3891. /// This function has undefined behavior. In particular, the
  3892. /// presence of this instruction indicates some higher level knowledge that the
  3893. /// end of the block cannot be reached.
  3894. ///
  3895. class UnreachableInst : public Instruction {
  3896. protected:
  3897. // Note: Instruction needs to be a friend here to call cloneImpl.
  3898. friend class Instruction;
  3899. UnreachableInst *cloneImpl() const;
  3900. public:
  3901. explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
  3902. explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
  3903. // allocate space for exactly zero operands
  3904. void *operator new(size_t s) {
  3905. return User::operator new(s, 0);
  3906. }
  3907. unsigned getNumSuccessors() const { return 0; }
  3908. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3909. static bool classof(const Instruction *I) {
  3910. return I->getOpcode() == Instruction::Unreachable;
  3911. }
  3912. static bool classof(const Value *V) {
  3913. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3914. }
  3915. private:
  3916. BasicBlock *getSuccessor(unsigned idx) const {
  3917. llvm_unreachable("UnreachableInst has no successors!");
  3918. }
  3919. void setSuccessor(unsigned idx, BasicBlock *B) {
  3920. llvm_unreachable("UnreachableInst has no successors!");
  3921. }
  3922. };
  3923. //===----------------------------------------------------------------------===//
  3924. // TruncInst Class
  3925. //===----------------------------------------------------------------------===//
  3926. /// This class represents a truncation of integer types.
  3927. class TruncInst : public CastInst {
  3928. protected:
  3929. // Note: Instruction needs to be a friend here to call cloneImpl.
  3930. friend class Instruction;
  3931. /// Clone an identical TruncInst
  3932. TruncInst *cloneImpl() const;
  3933. public:
  3934. /// Constructor with insert-before-instruction semantics
  3935. TruncInst(
  3936. Value *S, ///< The value to be truncated
  3937. Type *Ty, ///< The (smaller) type to truncate to
  3938. const Twine &NameStr = "", ///< A name for the new instruction
  3939. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  3940. );
  3941. /// Constructor with insert-at-end-of-block semantics
  3942. TruncInst(
  3943. Value *S, ///< The value to be truncated
  3944. Type *Ty, ///< The (smaller) type to truncate to
  3945. const Twine &NameStr, ///< A name for the new instruction
  3946. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  3947. );
  3948. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3949. static bool classof(const Instruction *I) {
  3950. return I->getOpcode() == Trunc;
  3951. }
  3952. static bool classof(const Value *V) {
  3953. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3954. }
  3955. };
  3956. //===----------------------------------------------------------------------===//
  3957. // ZExtInst Class
  3958. //===----------------------------------------------------------------------===//
  3959. /// This class represents zero extension of integer types.
  3960. class ZExtInst : public CastInst {
  3961. protected:
  3962. // Note: Instruction needs to be a friend here to call cloneImpl.
  3963. friend class Instruction;
  3964. /// Clone an identical ZExtInst
  3965. ZExtInst *cloneImpl() const;
  3966. public:
  3967. /// Constructor with insert-before-instruction semantics
  3968. ZExtInst(
  3969. Value *S, ///< The value to be zero extended
  3970. Type *Ty, ///< The type to zero extend to
  3971. const Twine &NameStr = "", ///< A name for the new instruction
  3972. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  3973. );
  3974. /// Constructor with insert-at-end semantics.
  3975. ZExtInst(
  3976. Value *S, ///< The value to be zero extended
  3977. Type *Ty, ///< The type to zero extend to
  3978. const Twine &NameStr, ///< A name for the new instruction
  3979. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  3980. );
  3981. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3982. static bool classof(const Instruction *I) {
  3983. return I->getOpcode() == ZExt;
  3984. }
  3985. static bool classof(const Value *V) {
  3986. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3987. }
  3988. };
  3989. //===----------------------------------------------------------------------===//
  3990. // SExtInst Class
  3991. //===----------------------------------------------------------------------===//
  3992. /// This class represents a sign extension of integer types.
  3993. class SExtInst : public CastInst {
  3994. protected:
  3995. // Note: Instruction needs to be a friend here to call cloneImpl.
  3996. friend class Instruction;
  3997. /// Clone an identical SExtInst
  3998. SExtInst *cloneImpl() const;
  3999. public:
  4000. /// Constructor with insert-before-instruction semantics
  4001. SExtInst(
  4002. Value *S, ///< The value to be sign extended
  4003. Type *Ty, ///< The type to sign extend to
  4004. const Twine &NameStr = "", ///< A name for the new instruction
  4005. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4006. );
  4007. /// Constructor with insert-at-end-of-block semantics
  4008. SExtInst(
  4009. Value *S, ///< The value to be sign extended
  4010. Type *Ty, ///< The type to sign extend to
  4011. const Twine &NameStr, ///< A name for the new instruction
  4012. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4013. );
  4014. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4015. static bool classof(const Instruction *I) {
  4016. return I->getOpcode() == SExt;
  4017. }
  4018. static bool classof(const Value *V) {
  4019. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4020. }
  4021. };
  4022. //===----------------------------------------------------------------------===//
  4023. // FPTruncInst Class
  4024. //===----------------------------------------------------------------------===//
  4025. /// This class represents a truncation of floating point types.
  4026. class FPTruncInst : public CastInst {
  4027. protected:
  4028. // Note: Instruction needs to be a friend here to call cloneImpl.
  4029. friend class Instruction;
  4030. /// Clone an identical FPTruncInst
  4031. FPTruncInst *cloneImpl() const;
  4032. public:
  4033. /// Constructor with insert-before-instruction semantics
  4034. FPTruncInst(
  4035. Value *S, ///< The value to be truncated
  4036. Type *Ty, ///< The type to truncate to
  4037. const Twine &NameStr = "", ///< A name for the new instruction
  4038. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4039. );
  4040. /// Constructor with insert-before-instruction semantics
  4041. FPTruncInst(
  4042. Value *S, ///< The value to be truncated
  4043. Type *Ty, ///< The type to truncate to
  4044. const Twine &NameStr, ///< A name for the new instruction
  4045. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4046. );
  4047. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4048. static bool classof(const Instruction *I) {
  4049. return I->getOpcode() == FPTrunc;
  4050. }
  4051. static bool classof(const Value *V) {
  4052. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4053. }
  4054. };
  4055. //===----------------------------------------------------------------------===//
  4056. // FPExtInst Class
  4057. //===----------------------------------------------------------------------===//
  4058. /// This class represents an extension of floating point types.
  4059. class FPExtInst : public CastInst {
  4060. protected:
  4061. // Note: Instruction needs to be a friend here to call cloneImpl.
  4062. friend class Instruction;
  4063. /// Clone an identical FPExtInst
  4064. FPExtInst *cloneImpl() const;
  4065. public:
  4066. /// Constructor with insert-before-instruction semantics
  4067. FPExtInst(
  4068. Value *S, ///< The value to be extended
  4069. Type *Ty, ///< The type to extend to
  4070. const Twine &NameStr = "", ///< A name for the new instruction
  4071. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4072. );
  4073. /// Constructor with insert-at-end-of-block semantics
  4074. FPExtInst(
  4075. Value *S, ///< The value to be extended
  4076. Type *Ty, ///< The type to extend to
  4077. const Twine &NameStr, ///< A name for the new instruction
  4078. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4079. );
  4080. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4081. static bool classof(const Instruction *I) {
  4082. return I->getOpcode() == FPExt;
  4083. }
  4084. static bool classof(const Value *V) {
  4085. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4086. }
  4087. };
  4088. //===----------------------------------------------------------------------===//
  4089. // UIToFPInst Class
  4090. //===----------------------------------------------------------------------===//
  4091. /// This class represents a cast unsigned integer to floating point.
  4092. class UIToFPInst : public CastInst {
  4093. protected:
  4094. // Note: Instruction needs to be a friend here to call cloneImpl.
  4095. friend class Instruction;
  4096. /// Clone an identical UIToFPInst
  4097. UIToFPInst *cloneImpl() const;
  4098. public:
  4099. /// Constructor with insert-before-instruction semantics
  4100. UIToFPInst(
  4101. Value *S, ///< The value to be converted
  4102. Type *Ty, ///< The type to convert to
  4103. const Twine &NameStr = "", ///< A name for the new instruction
  4104. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4105. );
  4106. /// Constructor with insert-at-end-of-block semantics
  4107. UIToFPInst(
  4108. Value *S, ///< The value to be converted
  4109. Type *Ty, ///< The type to convert to
  4110. const Twine &NameStr, ///< A name for the new instruction
  4111. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4112. );
  4113. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4114. static bool classof(const Instruction *I) {
  4115. return I->getOpcode() == UIToFP;
  4116. }
  4117. static bool classof(const Value *V) {
  4118. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4119. }
  4120. };
  4121. //===----------------------------------------------------------------------===//
  4122. // SIToFPInst Class
  4123. //===----------------------------------------------------------------------===//
  4124. /// This class represents a cast from signed integer to floating point.
  4125. class SIToFPInst : public CastInst {
  4126. protected:
  4127. // Note: Instruction needs to be a friend here to call cloneImpl.
  4128. friend class Instruction;
  4129. /// Clone an identical SIToFPInst
  4130. SIToFPInst *cloneImpl() const;
  4131. public:
  4132. /// Constructor with insert-before-instruction semantics
  4133. SIToFPInst(
  4134. Value *S, ///< The value to be converted
  4135. Type *Ty, ///< The type to convert to
  4136. const Twine &NameStr = "", ///< A name for the new instruction
  4137. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4138. );
  4139. /// Constructor with insert-at-end-of-block semantics
  4140. SIToFPInst(
  4141. Value *S, ///< The value to be converted
  4142. Type *Ty, ///< The type to convert to
  4143. const Twine &NameStr, ///< A name for the new instruction
  4144. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4145. );
  4146. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4147. static bool classof(const Instruction *I) {
  4148. return I->getOpcode() == SIToFP;
  4149. }
  4150. static bool classof(const Value *V) {
  4151. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4152. }
  4153. };
  4154. //===----------------------------------------------------------------------===//
  4155. // FPToUIInst Class
  4156. //===----------------------------------------------------------------------===//
  4157. /// This class represents a cast from floating point to unsigned integer
  4158. class FPToUIInst : public CastInst {
  4159. protected:
  4160. // Note: Instruction needs to be a friend here to call cloneImpl.
  4161. friend class Instruction;
  4162. /// Clone an identical FPToUIInst
  4163. FPToUIInst *cloneImpl() const;
  4164. public:
  4165. /// Constructor with insert-before-instruction semantics
  4166. FPToUIInst(
  4167. Value *S, ///< The value to be converted
  4168. Type *Ty, ///< The type to convert to
  4169. const Twine &NameStr = "", ///< A name for the new instruction
  4170. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4171. );
  4172. /// Constructor with insert-at-end-of-block semantics
  4173. FPToUIInst(
  4174. Value *S, ///< The value to be converted
  4175. Type *Ty, ///< The type to convert to
  4176. const Twine &NameStr, ///< A name for the new instruction
  4177. BasicBlock *InsertAtEnd ///< Where to insert the new instruction
  4178. );
  4179. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4180. static bool classof(const Instruction *I) {
  4181. return I->getOpcode() == FPToUI;
  4182. }
  4183. static bool classof(const Value *V) {
  4184. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4185. }
  4186. };
  4187. //===----------------------------------------------------------------------===//
  4188. // FPToSIInst Class
  4189. //===----------------------------------------------------------------------===//
  4190. /// This class represents a cast from floating point to signed integer.
  4191. class FPToSIInst : public CastInst {
  4192. protected:
  4193. // Note: Instruction needs to be a friend here to call cloneImpl.
  4194. friend class Instruction;
  4195. /// Clone an identical FPToSIInst
  4196. FPToSIInst *cloneImpl() const;
  4197. public:
  4198. /// Constructor with insert-before-instruction semantics
  4199. FPToSIInst(
  4200. Value *S, ///< The value to be converted
  4201. Type *Ty, ///< The type to convert to
  4202. const Twine &NameStr = "", ///< A name for the new instruction
  4203. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4204. );
  4205. /// Constructor with insert-at-end-of-block semantics
  4206. FPToSIInst(
  4207. Value *S, ///< The value to be converted
  4208. Type *Ty, ///< The type to convert to
  4209. const Twine &NameStr, ///< A name for the new instruction
  4210. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4211. );
  4212. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4213. static bool classof(const Instruction *I) {
  4214. return I->getOpcode() == FPToSI;
  4215. }
  4216. static bool classof(const Value *V) {
  4217. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4218. }
  4219. };
  4220. //===----------------------------------------------------------------------===//
  4221. // IntToPtrInst Class
  4222. //===----------------------------------------------------------------------===//
  4223. /// This class represents a cast from an integer to a pointer.
  4224. class IntToPtrInst : public CastInst {
  4225. public:
  4226. // Note: Instruction needs to be a friend here to call cloneImpl.
  4227. friend class Instruction;
  4228. /// Constructor with insert-before-instruction semantics
  4229. IntToPtrInst(
  4230. Value *S, ///< The value to be converted
  4231. Type *Ty, ///< The type to convert to
  4232. const Twine &NameStr = "", ///< A name for the new instruction
  4233. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4234. );
  4235. /// Constructor with insert-at-end-of-block semantics
  4236. IntToPtrInst(
  4237. Value *S, ///< The value to be converted
  4238. Type *Ty, ///< The type to convert to
  4239. const Twine &NameStr, ///< A name for the new instruction
  4240. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4241. );
  4242. /// Clone an identical IntToPtrInst.
  4243. IntToPtrInst *cloneImpl() const;
  4244. /// Returns the address space of this instruction's pointer type.
  4245. unsigned getAddressSpace() const {
  4246. return getType()->getPointerAddressSpace();
  4247. }
  4248. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4249. static bool classof(const Instruction *I) {
  4250. return I->getOpcode() == IntToPtr;
  4251. }
  4252. static bool classof(const Value *V) {
  4253. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4254. }
  4255. };
  4256. //===----------------------------------------------------------------------===//
  4257. // PtrToIntInst Class
  4258. //===----------------------------------------------------------------------===//
  4259. /// This class represents a cast from a pointer to an integer.
  4260. class PtrToIntInst : public CastInst {
  4261. protected:
  4262. // Note: Instruction needs to be a friend here to call cloneImpl.
  4263. friend class Instruction;
  4264. /// Clone an identical PtrToIntInst.
  4265. PtrToIntInst *cloneImpl() const;
  4266. public:
  4267. /// Constructor with insert-before-instruction semantics
  4268. PtrToIntInst(
  4269. Value *S, ///< The value to be converted
  4270. Type *Ty, ///< The type to convert to
  4271. const Twine &NameStr = "", ///< A name for the new instruction
  4272. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4273. );
  4274. /// Constructor with insert-at-end-of-block semantics
  4275. PtrToIntInst(
  4276. Value *S, ///< The value to be converted
  4277. Type *Ty, ///< The type to convert to
  4278. const Twine &NameStr, ///< A name for the new instruction
  4279. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4280. );
  4281. /// Gets the pointer operand.
  4282. Value *getPointerOperand() { return getOperand(0); }
  4283. /// Gets the pointer operand.
  4284. const Value *getPointerOperand() const { return getOperand(0); }
  4285. /// Gets the operand index of the pointer operand.
  4286. static unsigned getPointerOperandIndex() { return 0U; }
  4287. /// Returns the address space of the pointer operand.
  4288. unsigned getPointerAddressSpace() const {
  4289. return getPointerOperand()->getType()->getPointerAddressSpace();
  4290. }
  4291. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4292. static bool classof(const Instruction *I) {
  4293. return I->getOpcode() == PtrToInt;
  4294. }
  4295. static bool classof(const Value *V) {
  4296. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4297. }
  4298. };
  4299. //===----------------------------------------------------------------------===//
  4300. // BitCastInst Class
  4301. //===----------------------------------------------------------------------===//
  4302. /// This class represents a no-op cast from one type to another.
  4303. class BitCastInst : public CastInst {
  4304. protected:
  4305. // Note: Instruction needs to be a friend here to call cloneImpl.
  4306. friend class Instruction;
  4307. /// Clone an identical BitCastInst.
  4308. BitCastInst *cloneImpl() const;
  4309. public:
  4310. /// Constructor with insert-before-instruction semantics
  4311. BitCastInst(
  4312. Value *S, ///< The value to be casted
  4313. Type *Ty, ///< The type to casted to
  4314. const Twine &NameStr = "", ///< A name for the new instruction
  4315. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4316. );
  4317. /// Constructor with insert-at-end-of-block semantics
  4318. BitCastInst(
  4319. Value *S, ///< The value to be casted
  4320. Type *Ty, ///< The type to casted to
  4321. const Twine &NameStr, ///< A name for the new instruction
  4322. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4323. );
  4324. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4325. static bool classof(const Instruction *I) {
  4326. return I->getOpcode() == BitCast;
  4327. }
  4328. static bool classof(const Value *V) {
  4329. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4330. }
  4331. };
  4332. //===----------------------------------------------------------------------===//
  4333. // AddrSpaceCastInst Class
  4334. //===----------------------------------------------------------------------===//
  4335. /// This class represents a conversion between pointers from one address space
  4336. /// to another.
  4337. class AddrSpaceCastInst : public CastInst {
  4338. protected:
  4339. // Note: Instruction needs to be a friend here to call cloneImpl.
  4340. friend class Instruction;
  4341. /// Clone an identical AddrSpaceCastInst.
  4342. AddrSpaceCastInst *cloneImpl() const;
  4343. public:
  4344. /// Constructor with insert-before-instruction semantics
  4345. AddrSpaceCastInst(
  4346. Value *S, ///< The value to be casted
  4347. Type *Ty, ///< The type to casted to
  4348. const Twine &NameStr = "", ///< A name for the new instruction
  4349. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4350. );
  4351. /// Constructor with insert-at-end-of-block semantics
  4352. AddrSpaceCastInst(
  4353. Value *S, ///< The value to be casted
  4354. Type *Ty, ///< The type to casted to
  4355. const Twine &NameStr, ///< A name for the new instruction
  4356. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4357. );
  4358. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4359. static bool classof(const Instruction *I) {
  4360. return I->getOpcode() == AddrSpaceCast;
  4361. }
  4362. static bool classof(const Value *V) {
  4363. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4364. }
  4365. /// Gets the pointer operand.
  4366. Value *getPointerOperand() {
  4367. return getOperand(0);
  4368. }
  4369. /// Gets the pointer operand.
  4370. const Value *getPointerOperand() const {
  4371. return getOperand(0);
  4372. }
  4373. /// Gets the operand index of the pointer operand.
  4374. static unsigned getPointerOperandIndex() {
  4375. return 0U;
  4376. }
  4377. /// Returns the address space of the pointer operand.
  4378. unsigned getSrcAddressSpace() const {
  4379. return getPointerOperand()->getType()->getPointerAddressSpace();
  4380. }
  4381. /// Returns the address space of the result.
  4382. unsigned getDestAddressSpace() const {
  4383. return getType()->getPointerAddressSpace();
  4384. }
  4385. };
  4386. /// A helper function that returns the pointer operand of a load or store
  4387. /// instruction. Returns nullptr if not load or store.
  4388. inline const Value *getLoadStorePointerOperand(const Value *V) {
  4389. if (auto *Load = dyn_cast<LoadInst>(V))
  4390. return Load->getPointerOperand();
  4391. if (auto *Store = dyn_cast<StoreInst>(V))
  4392. return Store->getPointerOperand();
  4393. return nullptr;
  4394. }
  4395. inline Value *getLoadStorePointerOperand(Value *V) {
  4396. return const_cast<Value *>(
  4397. getLoadStorePointerOperand(static_cast<const Value *>(V)));
  4398. }
  4399. /// A helper function that returns the pointer operand of a load, store
  4400. /// or GEP instruction. Returns nullptr if not load, store, or GEP.
  4401. inline const Value *getPointerOperand(const Value *V) {
  4402. if (auto *Ptr = getLoadStorePointerOperand(V))
  4403. return Ptr;
  4404. if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
  4405. return Gep->getPointerOperand();
  4406. return nullptr;
  4407. }
  4408. inline Value *getPointerOperand(Value *V) {
  4409. return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
  4410. }
  4411. /// A helper function that returns the alignment of load or store instruction.
  4412. inline Align getLoadStoreAlignment(Value *I) {
  4413. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4414. "Expected Load or Store instruction");
  4415. if (auto *LI = dyn_cast<LoadInst>(I))
  4416. return LI->getAlign();
  4417. return cast<StoreInst>(I)->getAlign();
  4418. }
  4419. /// A helper function that returns the address space of the pointer operand of
  4420. /// load or store instruction.
  4421. inline unsigned getLoadStoreAddressSpace(Value *I) {
  4422. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4423. "Expected Load or Store instruction");
  4424. if (auto *LI = dyn_cast<LoadInst>(I))
  4425. return LI->getPointerAddressSpace();
  4426. return cast<StoreInst>(I)->getPointerAddressSpace();
  4427. }
  4428. /// A helper function that returns the type of a load or store instruction.
  4429. inline Type *getLoadStoreType(Value *I) {
  4430. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4431. "Expected Load or Store instruction");
  4432. if (auto *LI = dyn_cast<LoadInst>(I))
  4433. return LI->getType();
  4434. return cast<StoreInst>(I)->getValueOperand()->getType();
  4435. }
  4436. //===----------------------------------------------------------------------===//
  4437. // FreezeInst Class
  4438. //===----------------------------------------------------------------------===//
  4439. /// This class represents a freeze function that returns random concrete
  4440. /// value if an operand is either a poison value or an undef value
  4441. class FreezeInst : public UnaryInstruction {
  4442. protected:
  4443. // Note: Instruction needs to be a friend here to call cloneImpl.
  4444. friend class Instruction;
  4445. /// Clone an identical FreezeInst
  4446. FreezeInst *cloneImpl() const;
  4447. public:
  4448. explicit FreezeInst(Value *S,
  4449. const Twine &NameStr = "",
  4450. Instruction *InsertBefore = nullptr);
  4451. FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd);
  4452. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4453. static inline bool classof(const Instruction *I) {
  4454. return I->getOpcode() == Freeze;
  4455. }
  4456. static inline bool classof(const Value *V) {
  4457. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4458. }
  4459. };
  4460. } // end namespace llvm
  4461. #endif // LLVM_IR_INSTRUCTIONS_H