Expr.h 241 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Expr interface and subclasses.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_AST_EXPR_H
  18. #define LLVM_CLANG_AST_EXPR_H
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTVector.h"
  21. #include "clang/AST/ComputeDependence.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclAccessPair.h"
  24. #include "clang/AST/DependenceFlags.h"
  25. #include "clang/AST/OperationKinds.h"
  26. #include "clang/AST/Stmt.h"
  27. #include "clang/AST/TemplateBase.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/CharInfo.h"
  30. #include "clang/Basic/LangOptions.h"
  31. #include "clang/Basic/SyncScope.h"
  32. #include "clang/Basic/TypeTraits.h"
  33. #include "llvm/ADT/APFloat.h"
  34. #include "llvm/ADT/APSInt.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/ADT/StringRef.h"
  37. #include "llvm/ADT/iterator.h"
  38. #include "llvm/ADT/iterator_range.h"
  39. #include "llvm/Support/AtomicOrdering.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/TrailingObjects.h"
  42. #include <optional>
  43. namespace clang {
  44. class APValue;
  45. class ASTContext;
  46. class BlockDecl;
  47. class CXXBaseSpecifier;
  48. class CXXMemberCallExpr;
  49. class CXXOperatorCallExpr;
  50. class CastExpr;
  51. class Decl;
  52. class IdentifierInfo;
  53. class MaterializeTemporaryExpr;
  54. class NamedDecl;
  55. class ObjCPropertyRefExpr;
  56. class OpaqueValueExpr;
  57. class ParmVarDecl;
  58. class StringLiteral;
  59. class TargetInfo;
  60. class ValueDecl;
  61. /// A simple array of base specifiers.
  62. typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
  63. /// An adjustment to be made to the temporary created when emitting a
  64. /// reference binding, which accesses a particular subobject of that temporary.
  65. struct SubobjectAdjustment {
  66. enum {
  67. DerivedToBaseAdjustment,
  68. FieldAdjustment,
  69. MemberPointerAdjustment
  70. } Kind;
  71. struct DTB {
  72. const CastExpr *BasePath;
  73. const CXXRecordDecl *DerivedClass;
  74. };
  75. struct P {
  76. const MemberPointerType *MPT;
  77. Expr *RHS;
  78. };
  79. union {
  80. struct DTB DerivedToBase;
  81. FieldDecl *Field;
  82. struct P Ptr;
  83. };
  84. SubobjectAdjustment(const CastExpr *BasePath,
  85. const CXXRecordDecl *DerivedClass)
  86. : Kind(DerivedToBaseAdjustment) {
  87. DerivedToBase.BasePath = BasePath;
  88. DerivedToBase.DerivedClass = DerivedClass;
  89. }
  90. SubobjectAdjustment(FieldDecl *Field)
  91. : Kind(FieldAdjustment) {
  92. this->Field = Field;
  93. }
  94. SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
  95. : Kind(MemberPointerAdjustment) {
  96. this->Ptr.MPT = MPT;
  97. this->Ptr.RHS = RHS;
  98. }
  99. };
  100. /// This represents one expression. Note that Expr's are subclasses of Stmt.
  101. /// This allows an expression to be transparently used any place a Stmt is
  102. /// required.
  103. class Expr : public ValueStmt {
  104. QualType TR;
  105. public:
  106. Expr() = delete;
  107. Expr(const Expr&) = delete;
  108. Expr(Expr &&) = delete;
  109. Expr &operator=(const Expr&) = delete;
  110. Expr &operator=(Expr&&) = delete;
  111. protected:
  112. Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
  113. : ValueStmt(SC) {
  114. ExprBits.Dependent = 0;
  115. ExprBits.ValueKind = VK;
  116. ExprBits.ObjectKind = OK;
  117. assert(ExprBits.ObjectKind == OK && "truncated kind");
  118. setType(T);
  119. }
  120. /// Construct an empty expression.
  121. explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
  122. /// Each concrete expr subclass is expected to compute its dependence and call
  123. /// this in the constructor.
  124. void setDependence(ExprDependence Deps) {
  125. ExprBits.Dependent = static_cast<unsigned>(Deps);
  126. }
  127. friend class ASTImporter; // Sets dependence dircetly.
  128. friend class ASTStmtReader; // Sets dependence dircetly.
  129. public:
  130. QualType getType() const { return TR; }
  131. void setType(QualType t) {
  132. // In C++, the type of an expression is always adjusted so that it
  133. // will not have reference type (C++ [expr]p6). Use
  134. // QualType::getNonReferenceType() to retrieve the non-reference
  135. // type. Additionally, inspect Expr::isLvalue to determine whether
  136. // an expression that is adjusted in this manner should be
  137. // considered an lvalue.
  138. assert((t.isNull() || !t->isReferenceType()) &&
  139. "Expressions can't have reference type");
  140. TR = t;
  141. }
  142. ExprDependence getDependence() const {
  143. return static_cast<ExprDependence>(ExprBits.Dependent);
  144. }
  145. /// Determines whether the value of this expression depends on
  146. /// - a template parameter (C++ [temp.dep.constexpr])
  147. /// - or an error, whose resolution is unknown
  148. ///
  149. /// For example, the array bound of "Chars" in the following example is
  150. /// value-dependent.
  151. /// @code
  152. /// template<int Size, char (&Chars)[Size]> struct meta_string;
  153. /// @endcode
  154. bool isValueDependent() const {
  155. return static_cast<bool>(getDependence() & ExprDependence::Value);
  156. }
  157. /// Determines whether the type of this expression depends on
  158. /// - a template paramter (C++ [temp.dep.expr], which means that its type
  159. /// could change from one template instantiation to the next)
  160. /// - or an error
  161. ///
  162. /// For example, the expressions "x" and "x + y" are type-dependent in
  163. /// the following code, but "y" is not type-dependent:
  164. /// @code
  165. /// template<typename T>
  166. /// void add(T x, int y) {
  167. /// x + y;
  168. /// }
  169. /// @endcode
  170. bool isTypeDependent() const {
  171. return static_cast<bool>(getDependence() & ExprDependence::Type);
  172. }
  173. /// Whether this expression is instantiation-dependent, meaning that
  174. /// it depends in some way on
  175. /// - a template parameter (even if neither its type nor (constant) value
  176. /// can change due to the template instantiation)
  177. /// - or an error
  178. ///
  179. /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
  180. /// instantiation-dependent (since it involves a template parameter \c T), but
  181. /// is neither type- nor value-dependent, since the type of the inner
  182. /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
  183. /// \c sizeof is known.
  184. ///
  185. /// \code
  186. /// template<typename T>
  187. /// void f(T x, T y) {
  188. /// sizeof(sizeof(T() + T());
  189. /// }
  190. /// \endcode
  191. ///
  192. /// \code
  193. /// void func(int) {
  194. /// func(); // the expression is instantiation-dependent, because it depends
  195. /// // on an error.
  196. /// }
  197. /// \endcode
  198. bool isInstantiationDependent() const {
  199. return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
  200. }
  201. /// Whether this expression contains an unexpanded parameter
  202. /// pack (for C++11 variadic templates).
  203. ///
  204. /// Given the following function template:
  205. ///
  206. /// \code
  207. /// template<typename F, typename ...Types>
  208. /// void forward(const F &f, Types &&...args) {
  209. /// f(static_cast<Types&&>(args)...);
  210. /// }
  211. /// \endcode
  212. ///
  213. /// The expressions \c args and \c static_cast<Types&&>(args) both
  214. /// contain parameter packs.
  215. bool containsUnexpandedParameterPack() const {
  216. return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
  217. }
  218. /// Whether this expression contains subexpressions which had errors, e.g. a
  219. /// TypoExpr.
  220. bool containsErrors() const {
  221. return static_cast<bool>(getDependence() & ExprDependence::Error);
  222. }
  223. /// getExprLoc - Return the preferred location for the arrow when diagnosing
  224. /// a problem with a generic expression.
  225. SourceLocation getExprLoc() const LLVM_READONLY;
  226. /// Determine whether an lvalue-to-rvalue conversion should implicitly be
  227. /// applied to this expression if it appears as a discarded-value expression
  228. /// in C++11 onwards. This applies to certain forms of volatile glvalues.
  229. bool isReadIfDiscardedInCPlusPlus11() const;
  230. /// isUnusedResultAWarning - Return true if this immediate expression should
  231. /// be warned about if the result is unused. If so, fill in expr, location,
  232. /// and ranges with expr to warn on and source locations/ranges appropriate
  233. /// for a warning.
  234. bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
  235. SourceRange &R1, SourceRange &R2,
  236. ASTContext &Ctx) const;
  237. /// isLValue - True if this expression is an "l-value" according to
  238. /// the rules of the current language. C and C++ give somewhat
  239. /// different rules for this concept, but in general, the result of
  240. /// an l-value expression identifies a specific object whereas the
  241. /// result of an r-value expression is a value detached from any
  242. /// specific storage.
  243. ///
  244. /// C++11 divides the concept of "r-value" into pure r-values
  245. /// ("pr-values") and so-called expiring values ("x-values"), which
  246. /// identify specific objects that can be safely cannibalized for
  247. /// their resources.
  248. bool isLValue() const { return getValueKind() == VK_LValue; }
  249. bool isPRValue() const { return getValueKind() == VK_PRValue; }
  250. bool isXValue() const { return getValueKind() == VK_XValue; }
  251. bool isGLValue() const { return getValueKind() != VK_PRValue; }
  252. enum LValueClassification {
  253. LV_Valid,
  254. LV_NotObjectType,
  255. LV_IncompleteVoidType,
  256. LV_DuplicateVectorComponents,
  257. LV_InvalidExpression,
  258. LV_InvalidMessageExpression,
  259. LV_MemberFunction,
  260. LV_SubObjCPropertySetting,
  261. LV_ClassTemporary,
  262. LV_ArrayTemporary
  263. };
  264. /// Reasons why an expression might not be an l-value.
  265. LValueClassification ClassifyLValue(ASTContext &Ctx) const;
  266. enum isModifiableLvalueResult {
  267. MLV_Valid,
  268. MLV_NotObjectType,
  269. MLV_IncompleteVoidType,
  270. MLV_DuplicateVectorComponents,
  271. MLV_InvalidExpression,
  272. MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
  273. MLV_IncompleteType,
  274. MLV_ConstQualified,
  275. MLV_ConstQualifiedField,
  276. MLV_ConstAddrSpace,
  277. MLV_ArrayType,
  278. MLV_NoSetterProperty,
  279. MLV_MemberFunction,
  280. MLV_SubObjCPropertySetting,
  281. MLV_InvalidMessageExpression,
  282. MLV_ClassTemporary,
  283. MLV_ArrayTemporary
  284. };
  285. /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
  286. /// does not have an incomplete type, does not have a const-qualified type,
  287. /// and if it is a structure or union, does not have any member (including,
  288. /// recursively, any member or element of all contained aggregates or unions)
  289. /// with a const-qualified type.
  290. ///
  291. /// \param Loc [in,out] - A source location which *may* be filled
  292. /// in with the location of the expression making this a
  293. /// non-modifiable lvalue, if specified.
  294. isModifiableLvalueResult
  295. isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
  296. /// The return type of classify(). Represents the C++11 expression
  297. /// taxonomy.
  298. class Classification {
  299. public:
  300. /// The various classification results. Most of these mean prvalue.
  301. enum Kinds {
  302. CL_LValue,
  303. CL_XValue,
  304. CL_Function, // Functions cannot be lvalues in C.
  305. CL_Void, // Void cannot be an lvalue in C.
  306. CL_AddressableVoid, // Void expression whose address can be taken in C.
  307. CL_DuplicateVectorComponents, // A vector shuffle with dupes.
  308. CL_MemberFunction, // An expression referring to a member function
  309. CL_SubObjCPropertySetting,
  310. CL_ClassTemporary, // A temporary of class type, or subobject thereof.
  311. CL_ArrayTemporary, // A temporary of array type.
  312. CL_ObjCMessageRValue, // ObjC message is an rvalue
  313. CL_PRValue // A prvalue for any other reason, of any other type
  314. };
  315. /// The results of modification testing.
  316. enum ModifiableType {
  317. CM_Untested, // testModifiable was false.
  318. CM_Modifiable,
  319. CM_RValue, // Not modifiable because it's an rvalue
  320. CM_Function, // Not modifiable because it's a function; C++ only
  321. CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
  322. CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
  323. CM_ConstQualified,
  324. CM_ConstQualifiedField,
  325. CM_ConstAddrSpace,
  326. CM_ArrayType,
  327. CM_IncompleteType
  328. };
  329. private:
  330. friend class Expr;
  331. unsigned short Kind;
  332. unsigned short Modifiable;
  333. explicit Classification(Kinds k, ModifiableType m)
  334. : Kind(k), Modifiable(m)
  335. {}
  336. public:
  337. Classification() {}
  338. Kinds getKind() const { return static_cast<Kinds>(Kind); }
  339. ModifiableType getModifiable() const {
  340. assert(Modifiable != CM_Untested && "Did not test for modifiability.");
  341. return static_cast<ModifiableType>(Modifiable);
  342. }
  343. bool isLValue() const { return Kind == CL_LValue; }
  344. bool isXValue() const { return Kind == CL_XValue; }
  345. bool isGLValue() const { return Kind <= CL_XValue; }
  346. bool isPRValue() const { return Kind >= CL_Function; }
  347. bool isRValue() const { return Kind >= CL_XValue; }
  348. bool isModifiable() const { return getModifiable() == CM_Modifiable; }
  349. /// Create a simple, modifiably lvalue
  350. static Classification makeSimpleLValue() {
  351. return Classification(CL_LValue, CM_Modifiable);
  352. }
  353. };
  354. /// Classify - Classify this expression according to the C++11
  355. /// expression taxonomy.
  356. ///
  357. /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
  358. /// old lvalue vs rvalue. This function determines the type of expression this
  359. /// is. There are three expression types:
  360. /// - lvalues are classical lvalues as in C++03.
  361. /// - prvalues are equivalent to rvalues in C++03.
  362. /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
  363. /// function returning an rvalue reference.
  364. /// lvalues and xvalues are collectively referred to as glvalues, while
  365. /// prvalues and xvalues together form rvalues.
  366. Classification Classify(ASTContext &Ctx) const {
  367. return ClassifyImpl(Ctx, nullptr);
  368. }
  369. /// ClassifyModifiable - Classify this expression according to the
  370. /// C++11 expression taxonomy, and see if it is valid on the left side
  371. /// of an assignment.
  372. ///
  373. /// This function extends classify in that it also tests whether the
  374. /// expression is modifiable (C99 6.3.2.1p1).
  375. /// \param Loc A source location that might be filled with a relevant location
  376. /// if the expression is not modifiable.
  377. Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
  378. return ClassifyImpl(Ctx, &Loc);
  379. }
  380. /// Returns the set of floating point options that apply to this expression.
  381. /// Only meaningful for operations on floating point values.
  382. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
  383. /// getValueKindForType - Given a formal return or parameter type,
  384. /// give its value kind.
  385. static ExprValueKind getValueKindForType(QualType T) {
  386. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  387. return (isa<LValueReferenceType>(RT)
  388. ? VK_LValue
  389. : (RT->getPointeeType()->isFunctionType()
  390. ? VK_LValue : VK_XValue));
  391. return VK_PRValue;
  392. }
  393. /// getValueKind - The value kind that this expression produces.
  394. ExprValueKind getValueKind() const {
  395. return static_cast<ExprValueKind>(ExprBits.ValueKind);
  396. }
  397. /// getObjectKind - The object kind that this expression produces.
  398. /// Object kinds are meaningful only for expressions that yield an
  399. /// l-value or x-value.
  400. ExprObjectKind getObjectKind() const {
  401. return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
  402. }
  403. bool isOrdinaryOrBitFieldObject() const {
  404. ExprObjectKind OK = getObjectKind();
  405. return (OK == OK_Ordinary || OK == OK_BitField);
  406. }
  407. /// setValueKind - Set the value kind produced by this expression.
  408. void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
  409. /// setObjectKind - Set the object kind produced by this expression.
  410. void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
  411. private:
  412. Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
  413. public:
  414. /// Returns true if this expression is a gl-value that
  415. /// potentially refers to a bit-field.
  416. ///
  417. /// In C++, whether a gl-value refers to a bitfield is essentially
  418. /// an aspect of the value-kind type system.
  419. bool refersToBitField() const { return getObjectKind() == OK_BitField; }
  420. /// If this expression refers to a bit-field, retrieve the
  421. /// declaration of that bit-field.
  422. ///
  423. /// Note that this returns a non-null pointer in subtly different
  424. /// places than refersToBitField returns true. In particular, this can
  425. /// return a non-null pointer even for r-values loaded from
  426. /// bit-fields, but it will return null for a conditional bit-field.
  427. FieldDecl *getSourceBitField();
  428. const FieldDecl *getSourceBitField() const {
  429. return const_cast<Expr*>(this)->getSourceBitField();
  430. }
  431. Decl *getReferencedDeclOfCallee();
  432. const Decl *getReferencedDeclOfCallee() const {
  433. return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
  434. }
  435. /// If this expression is an l-value for an Objective C
  436. /// property, find the underlying property reference expression.
  437. const ObjCPropertyRefExpr *getObjCProperty() const;
  438. /// Check if this expression is the ObjC 'self' implicit parameter.
  439. bool isObjCSelfExpr() const;
  440. /// Returns whether this expression refers to a vector element.
  441. bool refersToVectorElement() const;
  442. /// Returns whether this expression refers to a matrix element.
  443. bool refersToMatrixElement() const {
  444. return getObjectKind() == OK_MatrixComponent;
  445. }
  446. /// Returns whether this expression refers to a global register
  447. /// variable.
  448. bool refersToGlobalRegisterVar() const;
  449. /// Returns whether this expression has a placeholder type.
  450. bool hasPlaceholderType() const {
  451. return getType()->isPlaceholderType();
  452. }
  453. /// Returns whether this expression has a specific placeholder type.
  454. bool hasPlaceholderType(BuiltinType::Kind K) const {
  455. assert(BuiltinType::isPlaceholderTypeKind(K));
  456. if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
  457. return BT->getKind() == K;
  458. return false;
  459. }
  460. /// isKnownToHaveBooleanValue - Return true if this is an integer expression
  461. /// that is known to return 0 or 1. This happens for _Bool/bool expressions
  462. /// but also int expressions which are produced by things like comparisons in
  463. /// C.
  464. ///
  465. /// \param Semantic If true, only return true for expressions that are known
  466. /// to be semantically boolean, which might not be true even for expressions
  467. /// that are known to evaluate to 0/1. For instance, reading an unsigned
  468. /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
  469. /// semantically correspond to a bool.
  470. bool isKnownToHaveBooleanValue(bool Semantic = true) const;
  471. /// Check whether this array fits the idiom of a flexible array member,
  472. /// depending on the value of -fstrict-flex-array.
  473. /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
  474. /// resulting from the substitution of a macro or a template as special sizes.
  475. bool isFlexibleArrayMemberLike(
  476. ASTContext &Context,
  477. LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
  478. bool IgnoreTemplateOrMacroSubstitution = false) const;
  479. /// isIntegerConstantExpr - Return the value if this expression is a valid
  480. /// integer constant expression. If not a valid i-c-e, return std::nullopt
  481. /// and fill in Loc (if specified) with the location of the invalid
  482. /// expression.
  483. ///
  484. /// Note: This does not perform the implicit conversions required by C++11
  485. /// [expr.const]p5.
  486. std::optional<llvm::APSInt>
  487. getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr,
  488. bool isEvaluated = true) const;
  489. bool isIntegerConstantExpr(const ASTContext &Ctx,
  490. SourceLocation *Loc = nullptr) const;
  491. /// isCXX98IntegralConstantExpr - Return true if this expression is an
  492. /// integral constant expression in C++98. Can only be used in C++.
  493. bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
  494. /// isCXX11ConstantExpr - Return true if this expression is a constant
  495. /// expression in C++11. Can only be used in C++.
  496. ///
  497. /// Note: This does not perform the implicit conversions required by C++11
  498. /// [expr.const]p5.
  499. bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
  500. SourceLocation *Loc = nullptr) const;
  501. /// isPotentialConstantExpr - Return true if this function's definition
  502. /// might be usable in a constant expression in C++11, if it were marked
  503. /// constexpr. Return false if the function can never produce a constant
  504. /// expression, along with diagnostics describing why not.
  505. static bool isPotentialConstantExpr(const FunctionDecl *FD,
  506. SmallVectorImpl<
  507. PartialDiagnosticAt> &Diags);
  508. /// isPotentialConstantExprUnevaluted - Return true if this expression might
  509. /// be usable in a constant expression in C++11 in an unevaluated context, if
  510. /// it were in function FD marked constexpr. Return false if the function can
  511. /// never produce a constant expression, along with diagnostics describing
  512. /// why not.
  513. static bool isPotentialConstantExprUnevaluated(Expr *E,
  514. const FunctionDecl *FD,
  515. SmallVectorImpl<
  516. PartialDiagnosticAt> &Diags);
  517. /// isConstantInitializer - Returns true if this expression can be emitted to
  518. /// IR as a constant, and thus can be used as a constant initializer in C.
  519. /// If this expression is not constant and Culprit is non-null,
  520. /// it is used to store the address of first non constant expr.
  521. bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
  522. const Expr **Culprit = nullptr) const;
  523. /// If this expression is an unambiguous reference to a single declaration,
  524. /// in the style of __builtin_function_start, return that declaration. Note
  525. /// that this may return a non-static member function or field in C++ if this
  526. /// expression is a member pointer constant.
  527. const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
  528. /// EvalStatus is a struct with detailed info about an evaluation in progress.
  529. struct EvalStatus {
  530. /// Whether the evaluated expression has side effects.
  531. /// For example, (f() && 0) can be folded, but it still has side effects.
  532. bool HasSideEffects;
  533. /// Whether the evaluation hit undefined behavior.
  534. /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
  535. /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
  536. bool HasUndefinedBehavior;
  537. /// Diag - If this is non-null, it will be filled in with a stack of notes
  538. /// indicating why evaluation failed (or why it failed to produce a constant
  539. /// expression).
  540. /// If the expression is unfoldable, the notes will indicate why it's not
  541. /// foldable. If the expression is foldable, but not a constant expression,
  542. /// the notes will describes why it isn't a constant expression. If the
  543. /// expression *is* a constant expression, no notes will be produced.
  544. SmallVectorImpl<PartialDiagnosticAt> *Diag;
  545. EvalStatus()
  546. : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
  547. // hasSideEffects - Return true if the evaluated expression has
  548. // side effects.
  549. bool hasSideEffects() const {
  550. return HasSideEffects;
  551. }
  552. };
  553. /// EvalResult is a struct with detailed info about an evaluated expression.
  554. struct EvalResult : EvalStatus {
  555. /// Val - This is the value the expression can be folded to.
  556. APValue Val;
  557. // isGlobalLValue - Return true if the evaluated lvalue expression
  558. // is global.
  559. bool isGlobalLValue() const;
  560. };
  561. /// EvaluateAsRValue - Return true if this is a constant which we can fold to
  562. /// an rvalue using any crazy technique (that has nothing to do with language
  563. /// standards) that we want to, even if the expression has side-effects. If
  564. /// this function returns true, it returns the folded constant in Result. If
  565. /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
  566. /// applied.
  567. bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  568. bool InConstantContext = false) const;
  569. /// EvaluateAsBooleanCondition - Return true if this is a constant
  570. /// which we can fold and convert to a boolean condition using
  571. /// any crazy technique that we want to, even if the expression has
  572. /// side-effects.
  573. bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  574. bool InConstantContext = false) const;
  575. enum SideEffectsKind {
  576. SE_NoSideEffects, ///< Strictly evaluate the expression.
  577. SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
  578. ///< arbitrary unmodeled side effects.
  579. SE_AllowSideEffects ///< Allow any unmodeled side effect.
  580. };
  581. /// EvaluateAsInt - Return true if this is a constant which we can fold and
  582. /// convert to an integer, using any crazy technique that we want to.
  583. bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  584. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  585. bool InConstantContext = false) const;
  586. /// EvaluateAsFloat - Return true if this is a constant which we can fold and
  587. /// convert to a floating point value, using any crazy technique that we
  588. /// want to.
  589. bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
  590. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  591. bool InConstantContext = false) const;
  592. /// EvaluateAsFloat - Return true if this is a constant which we can fold and
  593. /// convert to a fixed point value.
  594. bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  595. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  596. bool InConstantContext = false) const;
  597. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  598. /// constant folded without side-effects, but discard the result.
  599. bool isEvaluatable(const ASTContext &Ctx,
  600. SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
  601. /// HasSideEffects - This routine returns true for all those expressions
  602. /// which have any effect other than producing a value. Example is a function
  603. /// call, volatile variable read, or throwing an exception. If
  604. /// IncludePossibleEffects is false, this call treats certain expressions with
  605. /// potential side effects (such as function call-like expressions,
  606. /// instantiation-dependent expressions, or invocations from a macro) as not
  607. /// having side effects.
  608. bool HasSideEffects(const ASTContext &Ctx,
  609. bool IncludePossibleEffects = true) const;
  610. /// Determine whether this expression involves a call to any function
  611. /// that is not trivial.
  612. bool hasNonTrivialCall(const ASTContext &Ctx) const;
  613. /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
  614. /// integer. This must be called on an expression that constant folds to an
  615. /// integer.
  616. llvm::APSInt EvaluateKnownConstInt(
  617. const ASTContext &Ctx,
  618. SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
  619. llvm::APSInt EvaluateKnownConstIntCheckOverflow(
  620. const ASTContext &Ctx,
  621. SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
  622. void EvaluateForOverflow(const ASTContext &Ctx) const;
  623. /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
  624. /// lvalue with link time known address, with no side-effects.
  625. bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  626. bool InConstantContext = false) const;
  627. /// EvaluateAsInitializer - Evaluate an expression as if it were the
  628. /// initializer of the given declaration. Returns true if the initializer
  629. /// can be folded to a constant, and produces any relevant notes. In C++11,
  630. /// notes will be produced if the expression is not a constant expression.
  631. bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
  632. const VarDecl *VD,
  633. SmallVectorImpl<PartialDiagnosticAt> &Notes,
  634. bool IsConstantInitializer) const;
  635. /// EvaluateWithSubstitution - Evaluate an expression as if from the context
  636. /// of a call to the given function with the given arguments, inside an
  637. /// unevaluated context. Returns true if the expression could be folded to a
  638. /// constant.
  639. bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  640. const FunctionDecl *Callee,
  641. ArrayRef<const Expr*> Args,
  642. const Expr *This = nullptr) const;
  643. enum class ConstantExprKind {
  644. /// An integer constant expression (an array bound, enumerator, case value,
  645. /// bit-field width, or similar) or similar.
  646. Normal,
  647. /// A non-class template argument. Such a value is only used for mangling,
  648. /// not for code generation, so can refer to dllimported functions.
  649. NonClassTemplateArgument,
  650. /// A class template argument. Such a value is used for code generation.
  651. ClassTemplateArgument,
  652. /// An immediate invocation. The destruction of the end result of this
  653. /// evaluation is not part of the evaluation, but all other temporaries
  654. /// are destroyed.
  655. ImmediateInvocation,
  656. };
  657. /// Evaluate an expression that is required to be a constant expression. Does
  658. /// not check the syntactic constraints for C and C++98 constant expressions.
  659. bool EvaluateAsConstantExpr(
  660. EvalResult &Result, const ASTContext &Ctx,
  661. ConstantExprKind Kind = ConstantExprKind::Normal) const;
  662. /// If the current Expr is a pointer, this will try to statically
  663. /// determine the number of bytes available where the pointer is pointing.
  664. /// Returns true if all of the above holds and we were able to figure out the
  665. /// size, false otherwise.
  666. ///
  667. /// \param Type - How to evaluate the size of the Expr, as defined by the
  668. /// "type" parameter of __builtin_object_size
  669. bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  670. unsigned Type) const;
  671. /// If the current Expr is a pointer, this will try to statically
  672. /// determine the strlen of the string pointed to.
  673. /// Returns true if all of the above holds and we were able to figure out the
  674. /// strlen, false otherwise.
  675. bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
  676. /// Enumeration used to describe the kind of Null pointer constant
  677. /// returned from \c isNullPointerConstant().
  678. enum NullPointerConstantKind {
  679. /// Expression is not a Null pointer constant.
  680. NPCK_NotNull = 0,
  681. /// Expression is a Null pointer constant built from a zero integer
  682. /// expression that is not a simple, possibly parenthesized, zero literal.
  683. /// C++ Core Issue 903 will classify these expressions as "not pointers"
  684. /// once it is adopted.
  685. /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  686. NPCK_ZeroExpression,
  687. /// Expression is a Null pointer constant built from a literal zero.
  688. NPCK_ZeroLiteral,
  689. /// Expression is a C++11 nullptr.
  690. NPCK_CXX11_nullptr,
  691. /// Expression is a GNU-style __null constant.
  692. NPCK_GNUNull
  693. };
  694. /// Enumeration used to describe how \c isNullPointerConstant()
  695. /// should cope with value-dependent expressions.
  696. enum NullPointerConstantValueDependence {
  697. /// Specifies that the expression should never be value-dependent.
  698. NPC_NeverValueDependent = 0,
  699. /// Specifies that a value-dependent expression of integral or
  700. /// dependent type should be considered a null pointer constant.
  701. NPC_ValueDependentIsNull,
  702. /// Specifies that a value-dependent expression should be considered
  703. /// to never be a null pointer constant.
  704. NPC_ValueDependentIsNotNull
  705. };
  706. /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
  707. /// a Null pointer constant. The return value can further distinguish the
  708. /// kind of NULL pointer constant that was detected.
  709. NullPointerConstantKind isNullPointerConstant(
  710. ASTContext &Ctx,
  711. NullPointerConstantValueDependence NPC) const;
  712. /// isOBJCGCCandidate - Return true if this expression may be used in a read/
  713. /// write barrier.
  714. bool isOBJCGCCandidate(ASTContext &Ctx) const;
  715. /// Returns true if this expression is a bound member function.
  716. bool isBoundMemberFunction(ASTContext &Ctx) const;
  717. /// Given an expression of bound-member type, find the type
  718. /// of the member. Returns null if this is an *overloaded* bound
  719. /// member expression.
  720. static QualType findBoundMemberType(const Expr *expr);
  721. /// Skip past any invisble AST nodes which might surround this
  722. /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
  723. /// but also injected CXXMemberExpr and CXXConstructExpr which represent
  724. /// implicit conversions.
  725. Expr *IgnoreUnlessSpelledInSource();
  726. const Expr *IgnoreUnlessSpelledInSource() const {
  727. return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
  728. }
  729. /// Skip past any implicit casts which might surround this expression until
  730. /// reaching a fixed point. Skips:
  731. /// * ImplicitCastExpr
  732. /// * FullExpr
  733. Expr *IgnoreImpCasts() LLVM_READONLY;
  734. const Expr *IgnoreImpCasts() const {
  735. return const_cast<Expr *>(this)->IgnoreImpCasts();
  736. }
  737. /// Skip past any casts which might surround this expression until reaching
  738. /// a fixed point. Skips:
  739. /// * CastExpr
  740. /// * FullExpr
  741. /// * MaterializeTemporaryExpr
  742. /// * SubstNonTypeTemplateParmExpr
  743. Expr *IgnoreCasts() LLVM_READONLY;
  744. const Expr *IgnoreCasts() const {
  745. return const_cast<Expr *>(this)->IgnoreCasts();
  746. }
  747. /// Skip past any implicit AST nodes which might surround this expression
  748. /// until reaching a fixed point. Skips:
  749. /// * What IgnoreImpCasts() skips
  750. /// * MaterializeTemporaryExpr
  751. /// * CXXBindTemporaryExpr
  752. Expr *IgnoreImplicit() LLVM_READONLY;
  753. const Expr *IgnoreImplicit() const {
  754. return const_cast<Expr *>(this)->IgnoreImplicit();
  755. }
  756. /// Skip past any implicit AST nodes which might surround this expression
  757. /// until reaching a fixed point. Same as IgnoreImplicit, except that it
  758. /// also skips over implicit calls to constructors and conversion functions.
  759. ///
  760. /// FIXME: Should IgnoreImplicit do this?
  761. Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
  762. const Expr *IgnoreImplicitAsWritten() const {
  763. return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
  764. }
  765. /// Skip past any parentheses which might surround this expression until
  766. /// reaching a fixed point. Skips:
  767. /// * ParenExpr
  768. /// * UnaryOperator if `UO_Extension`
  769. /// * GenericSelectionExpr if `!isResultDependent()`
  770. /// * ChooseExpr if `!isConditionDependent()`
  771. /// * ConstantExpr
  772. Expr *IgnoreParens() LLVM_READONLY;
  773. const Expr *IgnoreParens() const {
  774. return const_cast<Expr *>(this)->IgnoreParens();
  775. }
  776. /// Skip past any parentheses and implicit casts which might surround this
  777. /// expression until reaching a fixed point.
  778. /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
  779. /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
  780. /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
  781. /// * What IgnoreParens() skips
  782. /// * What IgnoreImpCasts() skips
  783. /// * MaterializeTemporaryExpr
  784. /// * SubstNonTypeTemplateParmExpr
  785. Expr *IgnoreParenImpCasts() LLVM_READONLY;
  786. const Expr *IgnoreParenImpCasts() const {
  787. return const_cast<Expr *>(this)->IgnoreParenImpCasts();
  788. }
  789. /// Skip past any parentheses and casts which might surround this expression
  790. /// until reaching a fixed point. Skips:
  791. /// * What IgnoreParens() skips
  792. /// * What IgnoreCasts() skips
  793. Expr *IgnoreParenCasts() LLVM_READONLY;
  794. const Expr *IgnoreParenCasts() const {
  795. return const_cast<Expr *>(this)->IgnoreParenCasts();
  796. }
  797. /// Skip conversion operators. If this Expr is a call to a conversion
  798. /// operator, return the argument.
  799. Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
  800. const Expr *IgnoreConversionOperatorSingleStep() const {
  801. return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
  802. }
  803. /// Skip past any parentheses and lvalue casts which might surround this
  804. /// expression until reaching a fixed point. Skips:
  805. /// * What IgnoreParens() skips
  806. /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
  807. /// casts are skipped
  808. /// FIXME: This is intended purely as a temporary workaround for code
  809. /// that hasn't yet been rewritten to do the right thing about those
  810. /// casts, and may disappear along with the last internal use.
  811. Expr *IgnoreParenLValueCasts() LLVM_READONLY;
  812. const Expr *IgnoreParenLValueCasts() const {
  813. return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
  814. }
  815. /// Skip past any parenthese and casts which do not change the value
  816. /// (including ptr->int casts of the same size) until reaching a fixed point.
  817. /// Skips:
  818. /// * What IgnoreParens() skips
  819. /// * CastExpr which do not change the value
  820. /// * SubstNonTypeTemplateParmExpr
  821. Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
  822. const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
  823. return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
  824. }
  825. /// Skip past any parentheses and derived-to-base casts until reaching a
  826. /// fixed point. Skips:
  827. /// * What IgnoreParens() skips
  828. /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
  829. /// CK_UncheckedDerivedToBase and CK_NoOp)
  830. Expr *IgnoreParenBaseCasts() LLVM_READONLY;
  831. const Expr *IgnoreParenBaseCasts() const {
  832. return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
  833. }
  834. /// Determine whether this expression is a default function argument.
  835. ///
  836. /// Default arguments are implicitly generated in the abstract syntax tree
  837. /// by semantic analysis for function calls, object constructions, etc. in
  838. /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
  839. /// this routine also looks through any implicit casts to determine whether
  840. /// the expression is a default argument.
  841. bool isDefaultArgument() const;
  842. /// Determine whether the result of this expression is a
  843. /// temporary object of the given class type.
  844. bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
  845. /// Whether this expression is an implicit reference to 'this' in C++.
  846. bool isImplicitCXXThis() const;
  847. static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
  848. /// For an expression of class type or pointer to class type,
  849. /// return the most derived class decl the expression is known to refer to.
  850. ///
  851. /// If this expression is a cast, this method looks through it to find the
  852. /// most derived decl that can be inferred from the expression.
  853. /// This is valid because derived-to-base conversions have undefined
  854. /// behavior if the object isn't dynamically of the derived type.
  855. const CXXRecordDecl *getBestDynamicClassType() const;
  856. /// Get the inner expression that determines the best dynamic class.
  857. /// If this is a prvalue, we guarantee that it is of the most-derived type
  858. /// for the object itself.
  859. const Expr *getBestDynamicClassTypeExpr() const;
  860. /// Walk outwards from an expression we want to bind a reference to and
  861. /// find the expression whose lifetime needs to be extended. Record
  862. /// the LHSs of comma expressions and adjustments needed along the path.
  863. const Expr *skipRValueSubobjectAdjustments(
  864. SmallVectorImpl<const Expr *> &CommaLHS,
  865. SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
  866. const Expr *skipRValueSubobjectAdjustments() const {
  867. SmallVector<const Expr *, 8> CommaLHSs;
  868. SmallVector<SubobjectAdjustment, 8> Adjustments;
  869. return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  870. }
  871. /// Checks that the two Expr's will refer to the same value as a comparison
  872. /// operand. The caller must ensure that the values referenced by the Expr's
  873. /// are not modified between E1 and E2 or the result my be invalid.
  874. static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
  875. static bool classof(const Stmt *T) {
  876. return T->getStmtClass() >= firstExprConstant &&
  877. T->getStmtClass() <= lastExprConstant;
  878. }
  879. };
  880. // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
  881. // Expr. Verify that we got it right.
  882. static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
  883. llvm::detail::ConstantLog2<alignof(Expr)>::value,
  884. "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
  885. using ConstantExprKind = Expr::ConstantExprKind;
  886. //===----------------------------------------------------------------------===//
  887. // Wrapper Expressions.
  888. //===----------------------------------------------------------------------===//
  889. /// FullExpr - Represents a "full-expression" node.
  890. class FullExpr : public Expr {
  891. protected:
  892. Stmt *SubExpr;
  893. FullExpr(StmtClass SC, Expr *subexpr)
  894. : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
  895. subexpr->getObjectKind()),
  896. SubExpr(subexpr) {
  897. setDependence(computeDependence(this));
  898. }
  899. FullExpr(StmtClass SC, EmptyShell Empty)
  900. : Expr(SC, Empty) {}
  901. public:
  902. const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
  903. Expr *getSubExpr() { return cast<Expr>(SubExpr); }
  904. /// As with any mutator of the AST, be very careful when modifying an
  905. /// existing AST to preserve its invariants.
  906. void setSubExpr(Expr *E) { SubExpr = E; }
  907. static bool classof(const Stmt *T) {
  908. return T->getStmtClass() >= firstFullExprConstant &&
  909. T->getStmtClass() <= lastFullExprConstant;
  910. }
  911. };
  912. /// ConstantExpr - An expression that occurs in a constant context and
  913. /// optionally the result of evaluating the expression.
  914. class ConstantExpr final
  915. : public FullExpr,
  916. private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
  917. static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
  918. "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
  919. "for tail-allocated storage");
  920. friend TrailingObjects;
  921. friend class ASTStmtReader;
  922. friend class ASTStmtWriter;
  923. public:
  924. /// Describes the kind of result that can be tail-allocated.
  925. enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
  926. private:
  927. size_t numTrailingObjects(OverloadToken<APValue>) const {
  928. return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
  929. }
  930. size_t numTrailingObjects(OverloadToken<uint64_t>) const {
  931. return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
  932. }
  933. uint64_t &Int64Result() {
  934. assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
  935. "invalid accessor");
  936. return *getTrailingObjects<uint64_t>();
  937. }
  938. const uint64_t &Int64Result() const {
  939. return const_cast<ConstantExpr *>(this)->Int64Result();
  940. }
  941. APValue &APValueResult() {
  942. assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
  943. "invalid accessor");
  944. return *getTrailingObjects<APValue>();
  945. }
  946. APValue &APValueResult() const {
  947. return const_cast<ConstantExpr *>(this)->APValueResult();
  948. }
  949. ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
  950. bool IsImmediateInvocation);
  951. ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
  952. public:
  953. static ConstantExpr *Create(const ASTContext &Context, Expr *E,
  954. const APValue &Result);
  955. static ConstantExpr *Create(const ASTContext &Context, Expr *E,
  956. ResultStorageKind Storage = RSK_None,
  957. bool IsImmediateInvocation = false);
  958. static ConstantExpr *CreateEmpty(const ASTContext &Context,
  959. ResultStorageKind StorageKind);
  960. static ResultStorageKind getStorageKind(const APValue &Value);
  961. static ResultStorageKind getStorageKind(const Type *T,
  962. const ASTContext &Context);
  963. SourceLocation getBeginLoc() const LLVM_READONLY {
  964. return SubExpr->getBeginLoc();
  965. }
  966. SourceLocation getEndLoc() const LLVM_READONLY {
  967. return SubExpr->getEndLoc();
  968. }
  969. static bool classof(const Stmt *T) {
  970. return T->getStmtClass() == ConstantExprClass;
  971. }
  972. void SetResult(APValue Value, const ASTContext &Context) {
  973. MoveIntoResult(Value, Context);
  974. }
  975. void MoveIntoResult(APValue &Value, const ASTContext &Context);
  976. APValue::ValueKind getResultAPValueKind() const {
  977. return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
  978. }
  979. ResultStorageKind getResultStorageKind() const {
  980. return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
  981. }
  982. bool isImmediateInvocation() const {
  983. return ConstantExprBits.IsImmediateInvocation;
  984. }
  985. bool hasAPValueResult() const {
  986. return ConstantExprBits.APValueKind != APValue::None;
  987. }
  988. APValue getAPValueResult() const;
  989. APValue &getResultAsAPValue() const { return APValueResult(); }
  990. llvm::APSInt getResultAsAPSInt() const;
  991. // Iterators
  992. child_range children() { return child_range(&SubExpr, &SubExpr+1); }
  993. const_child_range children() const {
  994. return const_child_range(&SubExpr, &SubExpr + 1);
  995. }
  996. };
  997. //===----------------------------------------------------------------------===//
  998. // Primary Expressions.
  999. //===----------------------------------------------------------------------===//
  1000. /// OpaqueValueExpr - An expression referring to an opaque object of a
  1001. /// fixed type and value class. These don't correspond to concrete
  1002. /// syntax; instead they're used to express operations (usually copy
  1003. /// operations) on values whose source is generally obvious from
  1004. /// context.
  1005. class OpaqueValueExpr : public Expr {
  1006. friend class ASTStmtReader;
  1007. Expr *SourceExpr;
  1008. public:
  1009. OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
  1010. ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
  1011. : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
  1012. setIsUnique(false);
  1013. OpaqueValueExprBits.Loc = Loc;
  1014. setDependence(computeDependence(this));
  1015. }
  1016. /// Given an expression which invokes a copy constructor --- i.e. a
  1017. /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
  1018. /// find the OpaqueValueExpr that's the source of the construction.
  1019. static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
  1020. explicit OpaqueValueExpr(EmptyShell Empty)
  1021. : Expr(OpaqueValueExprClass, Empty) {}
  1022. /// Retrieve the location of this expression.
  1023. SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
  1024. SourceLocation getBeginLoc() const LLVM_READONLY {
  1025. return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
  1026. }
  1027. SourceLocation getEndLoc() const LLVM_READONLY {
  1028. return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
  1029. }
  1030. SourceLocation getExprLoc() const LLVM_READONLY {
  1031. return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
  1032. }
  1033. child_range children() {
  1034. return child_range(child_iterator(), child_iterator());
  1035. }
  1036. const_child_range children() const {
  1037. return const_child_range(const_child_iterator(), const_child_iterator());
  1038. }
  1039. /// The source expression of an opaque value expression is the
  1040. /// expression which originally generated the value. This is
  1041. /// provided as a convenience for analyses that don't wish to
  1042. /// precisely model the execution behavior of the program.
  1043. ///
  1044. /// The source expression is typically set when building the
  1045. /// expression which binds the opaque value expression in the first
  1046. /// place.
  1047. Expr *getSourceExpr() const { return SourceExpr; }
  1048. void setIsUnique(bool V) {
  1049. assert((!V || SourceExpr) &&
  1050. "unique OVEs are expected to have source expressions");
  1051. OpaqueValueExprBits.IsUnique = V;
  1052. }
  1053. bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
  1054. static bool classof(const Stmt *T) {
  1055. return T->getStmtClass() == OpaqueValueExprClass;
  1056. }
  1057. };
  1058. /// A reference to a declared variable, function, enum, etc.
  1059. /// [C99 6.5.1p2]
  1060. ///
  1061. /// This encodes all the information about how a declaration is referenced
  1062. /// within an expression.
  1063. ///
  1064. /// There are several optional constructs attached to DeclRefExprs only when
  1065. /// they apply in order to conserve memory. These are laid out past the end of
  1066. /// the object, and flags in the DeclRefExprBitfield track whether they exist:
  1067. ///
  1068. /// DeclRefExprBits.HasQualifier:
  1069. /// Specifies when this declaration reference expression has a C++
  1070. /// nested-name-specifier.
  1071. /// DeclRefExprBits.HasFoundDecl:
  1072. /// Specifies when this declaration reference expression has a record of
  1073. /// a NamedDecl (different from the referenced ValueDecl) which was found
  1074. /// during name lookup and/or overload resolution.
  1075. /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
  1076. /// Specifies when this declaration reference expression has an explicit
  1077. /// C++ template keyword and/or template argument list.
  1078. /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
  1079. /// Specifies when this declaration reference expression (validly)
  1080. /// refers to an enclosed local or a captured variable.
  1081. class DeclRefExpr final
  1082. : public Expr,
  1083. private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
  1084. NamedDecl *, ASTTemplateKWAndArgsInfo,
  1085. TemplateArgumentLoc> {
  1086. friend class ASTStmtReader;
  1087. friend class ASTStmtWriter;
  1088. friend TrailingObjects;
  1089. /// The declaration that we are referencing.
  1090. ValueDecl *D;
  1091. /// Provides source/type location info for the declaration name
  1092. /// embedded in D.
  1093. DeclarationNameLoc DNLoc;
  1094. size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
  1095. return hasQualifier();
  1096. }
  1097. size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
  1098. return hasFoundDecl();
  1099. }
  1100. size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
  1101. return hasTemplateKWAndArgsInfo();
  1102. }
  1103. /// Test whether there is a distinct FoundDecl attached to the end of
  1104. /// this DRE.
  1105. bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
  1106. DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
  1107. SourceLocation TemplateKWLoc, ValueDecl *D,
  1108. bool RefersToEnlosingVariableOrCapture,
  1109. const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
  1110. const TemplateArgumentListInfo *TemplateArgs, QualType T,
  1111. ExprValueKind VK, NonOdrUseReason NOUR);
  1112. /// Construct an empty declaration reference expression.
  1113. explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
  1114. public:
  1115. DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
  1116. bool RefersToEnclosingVariableOrCapture, QualType T,
  1117. ExprValueKind VK, SourceLocation L,
  1118. const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
  1119. NonOdrUseReason NOUR = NOUR_None);
  1120. static DeclRefExpr *
  1121. Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
  1122. SourceLocation TemplateKWLoc, ValueDecl *D,
  1123. bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
  1124. QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
  1125. const TemplateArgumentListInfo *TemplateArgs = nullptr,
  1126. NonOdrUseReason NOUR = NOUR_None);
  1127. static DeclRefExpr *
  1128. Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
  1129. SourceLocation TemplateKWLoc, ValueDecl *D,
  1130. bool RefersToEnclosingVariableOrCapture,
  1131. const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
  1132. NamedDecl *FoundD = nullptr,
  1133. const TemplateArgumentListInfo *TemplateArgs = nullptr,
  1134. NonOdrUseReason NOUR = NOUR_None);
  1135. /// Construct an empty declaration reference expression.
  1136. static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
  1137. bool HasFoundDecl,
  1138. bool HasTemplateKWAndArgsInfo,
  1139. unsigned NumTemplateArgs);
  1140. ValueDecl *getDecl() { return D; }
  1141. const ValueDecl *getDecl() const { return D; }
  1142. void setDecl(ValueDecl *NewD);
  1143. DeclarationNameInfo getNameInfo() const {
  1144. return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
  1145. }
  1146. SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
  1147. void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
  1148. SourceLocation getBeginLoc() const LLVM_READONLY;
  1149. SourceLocation getEndLoc() const LLVM_READONLY;
  1150. /// Determine whether this declaration reference was preceded by a
  1151. /// C++ nested-name-specifier, e.g., \c N::foo.
  1152. bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
  1153. /// If the name was qualified, retrieves the nested-name-specifier
  1154. /// that precedes the name, with source-location information.
  1155. NestedNameSpecifierLoc getQualifierLoc() const {
  1156. if (!hasQualifier())
  1157. return NestedNameSpecifierLoc();
  1158. return *getTrailingObjects<NestedNameSpecifierLoc>();
  1159. }
  1160. /// If the name was qualified, retrieves the nested-name-specifier
  1161. /// that precedes the name. Otherwise, returns NULL.
  1162. NestedNameSpecifier *getQualifier() const {
  1163. return getQualifierLoc().getNestedNameSpecifier();
  1164. }
  1165. /// Get the NamedDecl through which this reference occurred.
  1166. ///
  1167. /// This Decl may be different from the ValueDecl actually referred to in the
  1168. /// presence of using declarations, etc. It always returns non-NULL, and may
  1169. /// simple return the ValueDecl when appropriate.
  1170. NamedDecl *getFoundDecl() {
  1171. return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
  1172. }
  1173. /// Get the NamedDecl through which this reference occurred.
  1174. /// See non-const variant.
  1175. const NamedDecl *getFoundDecl() const {
  1176. return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
  1177. }
  1178. bool hasTemplateKWAndArgsInfo() const {
  1179. return DeclRefExprBits.HasTemplateKWAndArgsInfo;
  1180. }
  1181. /// Retrieve the location of the template keyword preceding
  1182. /// this name, if any.
  1183. SourceLocation getTemplateKeywordLoc() const {
  1184. if (!hasTemplateKWAndArgsInfo())
  1185. return SourceLocation();
  1186. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
  1187. }
  1188. /// Retrieve the location of the left angle bracket starting the
  1189. /// explicit template argument list following the name, if any.
  1190. SourceLocation getLAngleLoc() const {
  1191. if (!hasTemplateKWAndArgsInfo())
  1192. return SourceLocation();
  1193. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
  1194. }
  1195. /// Retrieve the location of the right angle bracket ending the
  1196. /// explicit template argument list following the name, if any.
  1197. SourceLocation getRAngleLoc() const {
  1198. if (!hasTemplateKWAndArgsInfo())
  1199. return SourceLocation();
  1200. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
  1201. }
  1202. /// Determines whether the name in this declaration reference
  1203. /// was preceded by the template keyword.
  1204. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
  1205. /// Determines whether this declaration reference was followed by an
  1206. /// explicit template argument list.
  1207. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
  1208. /// Copies the template arguments (if present) into the given
  1209. /// structure.
  1210. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
  1211. if (hasExplicitTemplateArgs())
  1212. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
  1213. getTrailingObjects<TemplateArgumentLoc>(), List);
  1214. }
  1215. /// Retrieve the template arguments provided as part of this
  1216. /// template-id.
  1217. const TemplateArgumentLoc *getTemplateArgs() const {
  1218. if (!hasExplicitTemplateArgs())
  1219. return nullptr;
  1220. return getTrailingObjects<TemplateArgumentLoc>();
  1221. }
  1222. /// Retrieve the number of template arguments provided as part of this
  1223. /// template-id.
  1224. unsigned getNumTemplateArgs() const {
  1225. if (!hasExplicitTemplateArgs())
  1226. return 0;
  1227. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
  1228. }
  1229. ArrayRef<TemplateArgumentLoc> template_arguments() const {
  1230. return {getTemplateArgs(), getNumTemplateArgs()};
  1231. }
  1232. /// Returns true if this expression refers to a function that
  1233. /// was resolved from an overloaded set having size greater than 1.
  1234. bool hadMultipleCandidates() const {
  1235. return DeclRefExprBits.HadMultipleCandidates;
  1236. }
  1237. /// Sets the flag telling whether this expression refers to
  1238. /// a function that was resolved from an overloaded set having size
  1239. /// greater than 1.
  1240. void setHadMultipleCandidates(bool V = true) {
  1241. DeclRefExprBits.HadMultipleCandidates = V;
  1242. }
  1243. /// Is this expression a non-odr-use reference, and if so, why?
  1244. NonOdrUseReason isNonOdrUse() const {
  1245. return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
  1246. }
  1247. /// Does this DeclRefExpr refer to an enclosing local or a captured
  1248. /// variable?
  1249. bool refersToEnclosingVariableOrCapture() const {
  1250. return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
  1251. }
  1252. static bool classof(const Stmt *T) {
  1253. return T->getStmtClass() == DeclRefExprClass;
  1254. }
  1255. // Iterators
  1256. child_range children() {
  1257. return child_range(child_iterator(), child_iterator());
  1258. }
  1259. const_child_range children() const {
  1260. return const_child_range(const_child_iterator(), const_child_iterator());
  1261. }
  1262. };
  1263. /// Used by IntegerLiteral/FloatingLiteral to store the numeric without
  1264. /// leaking memory.
  1265. ///
  1266. /// For large floats/integers, APFloat/APInt will allocate memory from the heap
  1267. /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
  1268. /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
  1269. /// the APFloat/APInt values will never get freed. APNumericStorage uses
  1270. /// ASTContext's allocator for memory allocation.
  1271. class APNumericStorage {
  1272. union {
  1273. uint64_t VAL; ///< Used to store the <= 64 bits integer value.
  1274. uint64_t *pVal; ///< Used to store the >64 bits integer value.
  1275. };
  1276. unsigned BitWidth;
  1277. bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
  1278. APNumericStorage(const APNumericStorage &) = delete;
  1279. void operator=(const APNumericStorage &) = delete;
  1280. protected:
  1281. APNumericStorage() : VAL(0), BitWidth(0) { }
  1282. llvm::APInt getIntValue() const {
  1283. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  1284. if (NumWords > 1)
  1285. return llvm::APInt(BitWidth, NumWords, pVal);
  1286. else
  1287. return llvm::APInt(BitWidth, VAL);
  1288. }
  1289. void setIntValue(const ASTContext &C, const llvm::APInt &Val);
  1290. };
  1291. class APIntStorage : private APNumericStorage {
  1292. public:
  1293. llvm::APInt getValue() const { return getIntValue(); }
  1294. void setValue(const ASTContext &C, const llvm::APInt &Val) {
  1295. setIntValue(C, Val);
  1296. }
  1297. };
  1298. class APFloatStorage : private APNumericStorage {
  1299. public:
  1300. llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
  1301. return llvm::APFloat(Semantics, getIntValue());
  1302. }
  1303. void setValue(const ASTContext &C, const llvm::APFloat &Val) {
  1304. setIntValue(C, Val.bitcastToAPInt());
  1305. }
  1306. };
  1307. class IntegerLiteral : public Expr, public APIntStorage {
  1308. SourceLocation Loc;
  1309. /// Construct an empty integer literal.
  1310. explicit IntegerLiteral(EmptyShell Empty)
  1311. : Expr(IntegerLiteralClass, Empty) { }
  1312. public:
  1313. // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
  1314. // or UnsignedLongLongTy
  1315. IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
  1316. SourceLocation l);
  1317. /// Returns a new integer literal with value 'V' and type 'type'.
  1318. /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
  1319. /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
  1320. /// \param V - the value that the returned integer literal contains.
  1321. static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
  1322. QualType type, SourceLocation l);
  1323. /// Returns a new empty integer literal.
  1324. static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1325. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1326. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1327. /// Retrieve the location of the literal.
  1328. SourceLocation getLocation() const { return Loc; }
  1329. void setLocation(SourceLocation Location) { Loc = Location; }
  1330. static bool classof(const Stmt *T) {
  1331. return T->getStmtClass() == IntegerLiteralClass;
  1332. }
  1333. // Iterators
  1334. child_range children() {
  1335. return child_range(child_iterator(), child_iterator());
  1336. }
  1337. const_child_range children() const {
  1338. return const_child_range(const_child_iterator(), const_child_iterator());
  1339. }
  1340. };
  1341. class FixedPointLiteral : public Expr, public APIntStorage {
  1342. SourceLocation Loc;
  1343. unsigned Scale;
  1344. /// \brief Construct an empty fixed-point literal.
  1345. explicit FixedPointLiteral(EmptyShell Empty)
  1346. : Expr(FixedPointLiteralClass, Empty) {}
  1347. public:
  1348. FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
  1349. SourceLocation l, unsigned Scale);
  1350. // Store the int as is without any bit shifting.
  1351. static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
  1352. const llvm::APInt &V,
  1353. QualType type, SourceLocation l,
  1354. unsigned Scale);
  1355. /// Returns an empty fixed-point literal.
  1356. static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1357. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1358. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1359. /// \brief Retrieve the location of the literal.
  1360. SourceLocation getLocation() const { return Loc; }
  1361. void setLocation(SourceLocation Location) { Loc = Location; }
  1362. unsigned getScale() const { return Scale; }
  1363. void setScale(unsigned S) { Scale = S; }
  1364. static bool classof(const Stmt *T) {
  1365. return T->getStmtClass() == FixedPointLiteralClass;
  1366. }
  1367. std::string getValueAsString(unsigned Radix) const;
  1368. // Iterators
  1369. child_range children() {
  1370. return child_range(child_iterator(), child_iterator());
  1371. }
  1372. const_child_range children() const {
  1373. return const_child_range(const_child_iterator(), const_child_iterator());
  1374. }
  1375. };
  1376. class CharacterLiteral : public Expr {
  1377. public:
  1378. enum CharacterKind {
  1379. Ascii,
  1380. Wide,
  1381. UTF8,
  1382. UTF16,
  1383. UTF32
  1384. };
  1385. private:
  1386. unsigned Value;
  1387. SourceLocation Loc;
  1388. public:
  1389. // type should be IntTy
  1390. CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
  1391. SourceLocation l)
  1392. : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
  1393. Value(value), Loc(l) {
  1394. CharacterLiteralBits.Kind = kind;
  1395. setDependence(ExprDependence::None);
  1396. }
  1397. /// Construct an empty character literal.
  1398. CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
  1399. SourceLocation getLocation() const { return Loc; }
  1400. CharacterKind getKind() const {
  1401. return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
  1402. }
  1403. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1404. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1405. unsigned getValue() const { return Value; }
  1406. void setLocation(SourceLocation Location) { Loc = Location; }
  1407. void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
  1408. void setValue(unsigned Val) { Value = Val; }
  1409. static bool classof(const Stmt *T) {
  1410. return T->getStmtClass() == CharacterLiteralClass;
  1411. }
  1412. static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
  1413. // Iterators
  1414. child_range children() {
  1415. return child_range(child_iterator(), child_iterator());
  1416. }
  1417. const_child_range children() const {
  1418. return const_child_range(const_child_iterator(), const_child_iterator());
  1419. }
  1420. };
  1421. class FloatingLiteral : public Expr, private APFloatStorage {
  1422. SourceLocation Loc;
  1423. FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
  1424. QualType Type, SourceLocation L);
  1425. /// Construct an empty floating-point literal.
  1426. explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
  1427. public:
  1428. static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
  1429. bool isexact, QualType Type, SourceLocation L);
  1430. static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1431. llvm::APFloat getValue() const {
  1432. return APFloatStorage::getValue(getSemantics());
  1433. }
  1434. void setValue(const ASTContext &C, const llvm::APFloat &Val) {
  1435. assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
  1436. APFloatStorage::setValue(C, Val);
  1437. }
  1438. /// Get a raw enumeration value representing the floating-point semantics of
  1439. /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
  1440. llvm::APFloatBase::Semantics getRawSemantics() const {
  1441. return static_cast<llvm::APFloatBase::Semantics>(
  1442. FloatingLiteralBits.Semantics);
  1443. }
  1444. /// Set the raw enumeration value representing the floating-point semantics of
  1445. /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
  1446. void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
  1447. FloatingLiteralBits.Semantics = Sem;
  1448. }
  1449. /// Return the APFloat semantics this literal uses.
  1450. const llvm::fltSemantics &getSemantics() const {
  1451. return llvm::APFloatBase::EnumToSemantics(
  1452. static_cast<llvm::APFloatBase::Semantics>(
  1453. FloatingLiteralBits.Semantics));
  1454. }
  1455. /// Set the APFloat semantics this literal uses.
  1456. void setSemantics(const llvm::fltSemantics &Sem) {
  1457. FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
  1458. }
  1459. bool isExact() const { return FloatingLiteralBits.IsExact; }
  1460. void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
  1461. /// getValueAsApproximateDouble - This returns the value as an inaccurate
  1462. /// double. Note that this may cause loss of precision, but is useful for
  1463. /// debugging dumps, etc.
  1464. double getValueAsApproximateDouble() const;
  1465. SourceLocation getLocation() const { return Loc; }
  1466. void setLocation(SourceLocation L) { Loc = L; }
  1467. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1468. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1469. static bool classof(const Stmt *T) {
  1470. return T->getStmtClass() == FloatingLiteralClass;
  1471. }
  1472. // Iterators
  1473. child_range children() {
  1474. return child_range(child_iterator(), child_iterator());
  1475. }
  1476. const_child_range children() const {
  1477. return const_child_range(const_child_iterator(), const_child_iterator());
  1478. }
  1479. };
  1480. /// ImaginaryLiteral - We support imaginary integer and floating point literals,
  1481. /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
  1482. /// IntegerLiteral classes. Instances of this class always have a Complex type
  1483. /// whose element type matches the subexpression.
  1484. ///
  1485. class ImaginaryLiteral : public Expr {
  1486. Stmt *Val;
  1487. public:
  1488. ImaginaryLiteral(Expr *val, QualType Ty)
  1489. : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
  1490. setDependence(ExprDependence::None);
  1491. }
  1492. /// Build an empty imaginary literal.
  1493. explicit ImaginaryLiteral(EmptyShell Empty)
  1494. : Expr(ImaginaryLiteralClass, Empty) { }
  1495. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  1496. Expr *getSubExpr() { return cast<Expr>(Val); }
  1497. void setSubExpr(Expr *E) { Val = E; }
  1498. SourceLocation getBeginLoc() const LLVM_READONLY {
  1499. return Val->getBeginLoc();
  1500. }
  1501. SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
  1502. static bool classof(const Stmt *T) {
  1503. return T->getStmtClass() == ImaginaryLiteralClass;
  1504. }
  1505. // Iterators
  1506. child_range children() { return child_range(&Val, &Val+1); }
  1507. const_child_range children() const {
  1508. return const_child_range(&Val, &Val + 1);
  1509. }
  1510. };
  1511. /// StringLiteral - This represents a string literal expression, e.g. "foo"
  1512. /// or L"bar" (wide strings). The actual string data can be obtained with
  1513. /// getBytes() and is NOT null-terminated. The length of the string data is
  1514. /// determined by calling getByteLength().
  1515. ///
  1516. /// The C type for a string is always a ConstantArrayType. In C++, the char
  1517. /// type is const qualified, in C it is not.
  1518. ///
  1519. /// Note that strings in C can be formed by concatenation of multiple string
  1520. /// literal pptokens in translation phase #6. This keeps track of the locations
  1521. /// of each of these pieces.
  1522. ///
  1523. /// Strings in C can also be truncated and extended by assigning into arrays,
  1524. /// e.g. with constructs like:
  1525. /// char X[2] = "foobar";
  1526. /// In this case, getByteLength() will return 6, but the string literal will
  1527. /// have type "char[2]".
  1528. class StringLiteral final
  1529. : public Expr,
  1530. private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
  1531. char> {
  1532. friend class ASTStmtReader;
  1533. friend TrailingObjects;
  1534. /// StringLiteral is followed by several trailing objects. They are in order:
  1535. ///
  1536. /// * A single unsigned storing the length in characters of this string. The
  1537. /// length in bytes is this length times the width of a single character.
  1538. /// Always present and stored as a trailing objects because storing it in
  1539. /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
  1540. /// due to alignment requirements. If you add some data to StringLiteral,
  1541. /// consider moving it inside StringLiteral.
  1542. ///
  1543. /// * An array of getNumConcatenated() SourceLocation, one for each of the
  1544. /// token this string is made of.
  1545. ///
  1546. /// * An array of getByteLength() char used to store the string data.
  1547. public:
  1548. enum StringKind { Ordinary, Wide, UTF8, UTF16, UTF32 };
  1549. private:
  1550. unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
  1551. unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
  1552. return getNumConcatenated();
  1553. }
  1554. unsigned numTrailingObjects(OverloadToken<char>) const {
  1555. return getByteLength();
  1556. }
  1557. char *getStrDataAsChar() { return getTrailingObjects<char>(); }
  1558. const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
  1559. const uint16_t *getStrDataAsUInt16() const {
  1560. return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
  1561. }
  1562. const uint32_t *getStrDataAsUInt32() const {
  1563. return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
  1564. }
  1565. /// Build a string literal.
  1566. StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
  1567. bool Pascal, QualType Ty, const SourceLocation *Loc,
  1568. unsigned NumConcatenated);
  1569. /// Build an empty string literal.
  1570. StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
  1571. unsigned CharByteWidth);
  1572. /// Map a target and string kind to the appropriate character width.
  1573. static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
  1574. /// Set one of the string literal token.
  1575. void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
  1576. assert(TokNum < getNumConcatenated() && "Invalid tok number");
  1577. getTrailingObjects<SourceLocation>()[TokNum] = L;
  1578. }
  1579. public:
  1580. /// This is the "fully general" constructor that allows representation of
  1581. /// strings formed from multiple concatenated tokens.
  1582. static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
  1583. StringKind Kind, bool Pascal, QualType Ty,
  1584. const SourceLocation *Loc,
  1585. unsigned NumConcatenated);
  1586. /// Simple constructor for string literals made from one token.
  1587. static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
  1588. StringKind Kind, bool Pascal, QualType Ty,
  1589. SourceLocation Loc) {
  1590. return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
  1591. }
  1592. /// Construct an empty string literal.
  1593. static StringLiteral *CreateEmpty(const ASTContext &Ctx,
  1594. unsigned NumConcatenated, unsigned Length,
  1595. unsigned CharByteWidth);
  1596. StringRef getString() const {
  1597. assert(getCharByteWidth() == 1 &&
  1598. "This function is used in places that assume strings use char");
  1599. return StringRef(getStrDataAsChar(), getByteLength());
  1600. }
  1601. /// Allow access to clients that need the byte representation, such as
  1602. /// ASTWriterStmt::VisitStringLiteral().
  1603. StringRef getBytes() const {
  1604. // FIXME: StringRef may not be the right type to use as a result for this.
  1605. return StringRef(getStrDataAsChar(), getByteLength());
  1606. }
  1607. void outputString(raw_ostream &OS) const;
  1608. uint32_t getCodeUnit(size_t i) const {
  1609. assert(i < getLength() && "out of bounds access");
  1610. switch (getCharByteWidth()) {
  1611. case 1:
  1612. return static_cast<unsigned char>(getStrDataAsChar()[i]);
  1613. case 2:
  1614. return getStrDataAsUInt16()[i];
  1615. case 4:
  1616. return getStrDataAsUInt32()[i];
  1617. }
  1618. llvm_unreachable("Unsupported character width!");
  1619. }
  1620. unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
  1621. unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
  1622. unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
  1623. StringKind getKind() const {
  1624. return static_cast<StringKind>(StringLiteralBits.Kind);
  1625. }
  1626. bool isOrdinary() const { return getKind() == Ordinary; }
  1627. bool isWide() const { return getKind() == Wide; }
  1628. bool isUTF8() const { return getKind() == UTF8; }
  1629. bool isUTF16() const { return getKind() == UTF16; }
  1630. bool isUTF32() const { return getKind() == UTF32; }
  1631. bool isPascal() const { return StringLiteralBits.IsPascal; }
  1632. bool containsNonAscii() const {
  1633. for (auto c : getString())
  1634. if (!isASCII(c))
  1635. return true;
  1636. return false;
  1637. }
  1638. bool containsNonAsciiOrNull() const {
  1639. for (auto c : getString())
  1640. if (!isASCII(c) || !c)
  1641. return true;
  1642. return false;
  1643. }
  1644. /// getNumConcatenated - Get the number of string literal tokens that were
  1645. /// concatenated in translation phase #6 to form this string literal.
  1646. unsigned getNumConcatenated() const {
  1647. return StringLiteralBits.NumConcatenated;
  1648. }
  1649. /// Get one of the string literal token.
  1650. SourceLocation getStrTokenLoc(unsigned TokNum) const {
  1651. assert(TokNum < getNumConcatenated() && "Invalid tok number");
  1652. return getTrailingObjects<SourceLocation>()[TokNum];
  1653. }
  1654. /// getLocationOfByte - Return a source location that points to the specified
  1655. /// byte of this string literal.
  1656. ///
  1657. /// Strings are amazingly complex. They can be formed from multiple tokens
  1658. /// and can have escape sequences in them in addition to the usual trigraph
  1659. /// and escaped newline business. This routine handles this complexity.
  1660. ///
  1661. SourceLocation
  1662. getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
  1663. const LangOptions &Features, const TargetInfo &Target,
  1664. unsigned *StartToken = nullptr,
  1665. unsigned *StartTokenByteOffset = nullptr) const;
  1666. typedef const SourceLocation *tokloc_iterator;
  1667. tokloc_iterator tokloc_begin() const {
  1668. return getTrailingObjects<SourceLocation>();
  1669. }
  1670. tokloc_iterator tokloc_end() const {
  1671. return getTrailingObjects<SourceLocation>() + getNumConcatenated();
  1672. }
  1673. SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
  1674. SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
  1675. static bool classof(const Stmt *T) {
  1676. return T->getStmtClass() == StringLiteralClass;
  1677. }
  1678. // Iterators
  1679. child_range children() {
  1680. return child_range(child_iterator(), child_iterator());
  1681. }
  1682. const_child_range children() const {
  1683. return const_child_range(const_child_iterator(), const_child_iterator());
  1684. }
  1685. };
  1686. /// [C99 6.4.2.2] - A predefined identifier such as __func__.
  1687. class PredefinedExpr final
  1688. : public Expr,
  1689. private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
  1690. friend class ASTStmtReader;
  1691. friend TrailingObjects;
  1692. // PredefinedExpr is optionally followed by a single trailing
  1693. // "Stmt *" for the predefined identifier. It is present if and only if
  1694. // hasFunctionName() is true and is always a "StringLiteral *".
  1695. public:
  1696. enum IdentKind {
  1697. Func,
  1698. Function,
  1699. LFunction, // Same as Function, but as wide string.
  1700. FuncDName,
  1701. FuncSig,
  1702. LFuncSig, // Same as FuncSig, but as wide string
  1703. PrettyFunction,
  1704. /// The same as PrettyFunction, except that the
  1705. /// 'virtual' keyword is omitted for virtual member functions.
  1706. PrettyFunctionNoVirtual
  1707. };
  1708. private:
  1709. PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
  1710. StringLiteral *SL);
  1711. explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
  1712. /// True if this PredefinedExpr has storage for a function name.
  1713. bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
  1714. void setFunctionName(StringLiteral *SL) {
  1715. assert(hasFunctionName() &&
  1716. "This PredefinedExpr has no storage for a function name!");
  1717. *getTrailingObjects<Stmt *>() = SL;
  1718. }
  1719. public:
  1720. /// Create a PredefinedExpr.
  1721. static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
  1722. QualType FNTy, IdentKind IK, StringLiteral *SL);
  1723. /// Create an empty PredefinedExpr.
  1724. static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
  1725. bool HasFunctionName);
  1726. IdentKind getIdentKind() const {
  1727. return static_cast<IdentKind>(PredefinedExprBits.Kind);
  1728. }
  1729. SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
  1730. void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
  1731. StringLiteral *getFunctionName() {
  1732. return hasFunctionName()
  1733. ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
  1734. : nullptr;
  1735. }
  1736. const StringLiteral *getFunctionName() const {
  1737. return hasFunctionName()
  1738. ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
  1739. : nullptr;
  1740. }
  1741. static StringRef getIdentKindName(IdentKind IK);
  1742. StringRef getIdentKindName() const {
  1743. return getIdentKindName(getIdentKind());
  1744. }
  1745. static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
  1746. SourceLocation getBeginLoc() const { return getLocation(); }
  1747. SourceLocation getEndLoc() const { return getLocation(); }
  1748. static bool classof(const Stmt *T) {
  1749. return T->getStmtClass() == PredefinedExprClass;
  1750. }
  1751. // Iterators
  1752. child_range children() {
  1753. return child_range(getTrailingObjects<Stmt *>(),
  1754. getTrailingObjects<Stmt *>() + hasFunctionName());
  1755. }
  1756. const_child_range children() const {
  1757. return const_child_range(getTrailingObjects<Stmt *>(),
  1758. getTrailingObjects<Stmt *>() + hasFunctionName());
  1759. }
  1760. };
  1761. // This represents a use of the __builtin_sycl_unique_stable_name, which takes a
  1762. // type-id, and at CodeGen time emits a unique string representation of the
  1763. // type in a way that permits us to properly encode information about the SYCL
  1764. // kernels.
  1765. class SYCLUniqueStableNameExpr final : public Expr {
  1766. friend class ASTStmtReader;
  1767. SourceLocation OpLoc, LParen, RParen;
  1768. TypeSourceInfo *TypeInfo;
  1769. SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
  1770. SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
  1771. SourceLocation RParen, QualType ResultTy,
  1772. TypeSourceInfo *TSI);
  1773. void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
  1774. void setLocation(SourceLocation L) { OpLoc = L; }
  1775. void setLParenLocation(SourceLocation L) { LParen = L; }
  1776. void setRParenLocation(SourceLocation L) { RParen = L; }
  1777. public:
  1778. TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
  1779. const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
  1780. static SYCLUniqueStableNameExpr *
  1781. Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
  1782. SourceLocation RParen, TypeSourceInfo *TSI);
  1783. static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
  1784. SourceLocation getBeginLoc() const { return getLocation(); }
  1785. SourceLocation getEndLoc() const { return RParen; }
  1786. SourceLocation getLocation() const { return OpLoc; }
  1787. SourceLocation getLParenLocation() const { return LParen; }
  1788. SourceLocation getRParenLocation() const { return RParen; }
  1789. static bool classof(const Stmt *T) {
  1790. return T->getStmtClass() == SYCLUniqueStableNameExprClass;
  1791. }
  1792. // Iterators
  1793. child_range children() {
  1794. return child_range(child_iterator(), child_iterator());
  1795. }
  1796. const_child_range children() const {
  1797. return const_child_range(const_child_iterator(), const_child_iterator());
  1798. }
  1799. // Convenience function to generate the name of the currently stored type.
  1800. std::string ComputeName(ASTContext &Context) const;
  1801. // Get the generated name of the type. Note that this only works after all
  1802. // kernels have been instantiated.
  1803. static std::string ComputeName(ASTContext &Context, QualType Ty);
  1804. };
  1805. /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
  1806. /// AST node is only formed if full location information is requested.
  1807. class ParenExpr : public Expr {
  1808. SourceLocation L, R;
  1809. Stmt *Val;
  1810. public:
  1811. ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
  1812. : Expr(ParenExprClass, val->getType(), val->getValueKind(),
  1813. val->getObjectKind()),
  1814. L(l), R(r), Val(val) {
  1815. setDependence(computeDependence(this));
  1816. }
  1817. /// Construct an empty parenthesized expression.
  1818. explicit ParenExpr(EmptyShell Empty)
  1819. : Expr(ParenExprClass, Empty) { }
  1820. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  1821. Expr *getSubExpr() { return cast<Expr>(Val); }
  1822. void setSubExpr(Expr *E) { Val = E; }
  1823. SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
  1824. SourceLocation getEndLoc() const LLVM_READONLY { return R; }
  1825. /// Get the location of the left parentheses '('.
  1826. SourceLocation getLParen() const { return L; }
  1827. void setLParen(SourceLocation Loc) { L = Loc; }
  1828. /// Get the location of the right parentheses ')'.
  1829. SourceLocation getRParen() const { return R; }
  1830. void setRParen(SourceLocation Loc) { R = Loc; }
  1831. static bool classof(const Stmt *T) {
  1832. return T->getStmtClass() == ParenExprClass;
  1833. }
  1834. // Iterators
  1835. child_range children() { return child_range(&Val, &Val+1); }
  1836. const_child_range children() const {
  1837. return const_child_range(&Val, &Val + 1);
  1838. }
  1839. };
  1840. /// UnaryOperator - This represents the unary-expression's (except sizeof and
  1841. /// alignof), the postinc/postdec operators from postfix-expression, and various
  1842. /// extensions.
  1843. ///
  1844. /// Notes on various nodes:
  1845. ///
  1846. /// Real/Imag - These return the real/imag part of a complex operand. If
  1847. /// applied to a non-complex value, the former returns its operand and the
  1848. /// later returns zero in the type of the operand.
  1849. ///
  1850. class UnaryOperator final
  1851. : public Expr,
  1852. private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
  1853. Stmt *Val;
  1854. size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
  1855. return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
  1856. }
  1857. FPOptionsOverride &getTrailingFPFeatures() {
  1858. assert(UnaryOperatorBits.HasFPFeatures);
  1859. return *getTrailingObjects<FPOptionsOverride>();
  1860. }
  1861. const FPOptionsOverride &getTrailingFPFeatures() const {
  1862. assert(UnaryOperatorBits.HasFPFeatures);
  1863. return *getTrailingObjects<FPOptionsOverride>();
  1864. }
  1865. public:
  1866. typedef UnaryOperatorKind Opcode;
  1867. protected:
  1868. UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
  1869. ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
  1870. bool CanOverflow, FPOptionsOverride FPFeatures);
  1871. /// Build an empty unary operator.
  1872. explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
  1873. : Expr(UnaryOperatorClass, Empty) {
  1874. UnaryOperatorBits.Opc = UO_AddrOf;
  1875. UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
  1876. }
  1877. public:
  1878. static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
  1879. static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
  1880. QualType type, ExprValueKind VK,
  1881. ExprObjectKind OK, SourceLocation l,
  1882. bool CanOverflow, FPOptionsOverride FPFeatures);
  1883. Opcode getOpcode() const {
  1884. return static_cast<Opcode>(UnaryOperatorBits.Opc);
  1885. }
  1886. void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
  1887. Expr *getSubExpr() const { return cast<Expr>(Val); }
  1888. void setSubExpr(Expr *E) { Val = E; }
  1889. /// getOperatorLoc - Return the location of the operator.
  1890. SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
  1891. void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
  1892. /// Returns true if the unary operator can cause an overflow. For instance,
  1893. /// signed int i = INT_MAX; i++;
  1894. /// signed char c = CHAR_MAX; c++;
  1895. /// Due to integer promotions, c++ is promoted to an int before the postfix
  1896. /// increment, and the result is an int that cannot overflow. However, i++
  1897. /// can overflow.
  1898. bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
  1899. void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
  1900. // Get the FP contractability status of this operator. Only meaningful for
  1901. // operations on floating point types.
  1902. bool isFPContractableWithinStatement(const LangOptions &LO) const {
  1903. return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
  1904. }
  1905. // Get the FENV_ACCESS status of this operator. Only meaningful for
  1906. // operations on floating point types.
  1907. bool isFEnvAccessOn(const LangOptions &LO) const {
  1908. return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
  1909. }
  1910. /// isPostfix - Return true if this is a postfix operation, like x++.
  1911. static bool isPostfix(Opcode Op) {
  1912. return Op == UO_PostInc || Op == UO_PostDec;
  1913. }
  1914. /// isPrefix - Return true if this is a prefix operation, like --x.
  1915. static bool isPrefix(Opcode Op) {
  1916. return Op == UO_PreInc || Op == UO_PreDec;
  1917. }
  1918. bool isPrefix() const { return isPrefix(getOpcode()); }
  1919. bool isPostfix() const { return isPostfix(getOpcode()); }
  1920. static bool isIncrementOp(Opcode Op) {
  1921. return Op == UO_PreInc || Op == UO_PostInc;
  1922. }
  1923. bool isIncrementOp() const {
  1924. return isIncrementOp(getOpcode());
  1925. }
  1926. static bool isDecrementOp(Opcode Op) {
  1927. return Op == UO_PreDec || Op == UO_PostDec;
  1928. }
  1929. bool isDecrementOp() const {
  1930. return isDecrementOp(getOpcode());
  1931. }
  1932. static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
  1933. bool isIncrementDecrementOp() const {
  1934. return isIncrementDecrementOp(getOpcode());
  1935. }
  1936. static bool isArithmeticOp(Opcode Op) {
  1937. return Op >= UO_Plus && Op <= UO_LNot;
  1938. }
  1939. bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
  1940. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  1941. /// corresponds to, e.g. "sizeof" or "[pre]++"
  1942. static StringRef getOpcodeStr(Opcode Op);
  1943. /// Retrieve the unary opcode that corresponds to the given
  1944. /// overloaded operator.
  1945. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
  1946. /// Retrieve the overloaded operator kind that corresponds to
  1947. /// the given unary opcode.
  1948. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
  1949. SourceLocation getBeginLoc() const LLVM_READONLY {
  1950. return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
  1951. }
  1952. SourceLocation getEndLoc() const LLVM_READONLY {
  1953. return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
  1954. }
  1955. SourceLocation getExprLoc() const { return getOperatorLoc(); }
  1956. static bool classof(const Stmt *T) {
  1957. return T->getStmtClass() == UnaryOperatorClass;
  1958. }
  1959. // Iterators
  1960. child_range children() { return child_range(&Val, &Val+1); }
  1961. const_child_range children() const {
  1962. return const_child_range(&Val, &Val + 1);
  1963. }
  1964. /// Is FPFeatures in Trailing Storage?
  1965. bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
  1966. /// Get FPFeatures from trailing storage.
  1967. FPOptionsOverride getStoredFPFeatures() const {
  1968. return getTrailingFPFeatures();
  1969. }
  1970. protected:
  1971. /// Set FPFeatures in trailing storage, used only by Serialization
  1972. void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
  1973. public:
  1974. // Get the FP features status of this operator. Only meaningful for
  1975. // operations on floating point types.
  1976. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  1977. if (UnaryOperatorBits.HasFPFeatures)
  1978. return getStoredFPFeatures().applyOverrides(LO);
  1979. return FPOptions::defaultWithoutTrailingStorage(LO);
  1980. }
  1981. FPOptionsOverride getFPOptionsOverride() const {
  1982. if (UnaryOperatorBits.HasFPFeatures)
  1983. return getStoredFPFeatures();
  1984. return FPOptionsOverride();
  1985. }
  1986. friend TrailingObjects;
  1987. friend class ASTReader;
  1988. friend class ASTStmtReader;
  1989. friend class ASTStmtWriter;
  1990. };
  1991. /// Helper class for OffsetOfExpr.
  1992. // __builtin_offsetof(type, identifier(.identifier|[expr])*)
  1993. class OffsetOfNode {
  1994. public:
  1995. /// The kind of offsetof node we have.
  1996. enum Kind {
  1997. /// An index into an array.
  1998. Array = 0x00,
  1999. /// A field.
  2000. Field = 0x01,
  2001. /// A field in a dependent type, known only by its name.
  2002. Identifier = 0x02,
  2003. /// An implicit indirection through a C++ base class, when the
  2004. /// field found is in a base class.
  2005. Base = 0x03
  2006. };
  2007. private:
  2008. enum { MaskBits = 2, Mask = 0x03 };
  2009. /// The source range that covers this part of the designator.
  2010. SourceRange Range;
  2011. /// The data describing the designator, which comes in three
  2012. /// different forms, depending on the lower two bits.
  2013. /// - An unsigned index into the array of Expr*'s stored after this node
  2014. /// in memory, for [constant-expression] designators.
  2015. /// - A FieldDecl*, for references to a known field.
  2016. /// - An IdentifierInfo*, for references to a field with a given name
  2017. /// when the class type is dependent.
  2018. /// - A CXXBaseSpecifier*, for references that look at a field in a
  2019. /// base class.
  2020. uintptr_t Data;
  2021. public:
  2022. /// Create an offsetof node that refers to an array element.
  2023. OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
  2024. SourceLocation RBracketLoc)
  2025. : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
  2026. /// Create an offsetof node that refers to a field.
  2027. OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
  2028. : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
  2029. Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
  2030. /// Create an offsetof node that refers to an identifier.
  2031. OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
  2032. SourceLocation NameLoc)
  2033. : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
  2034. Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
  2035. /// Create an offsetof node that refers into a C++ base class.
  2036. explicit OffsetOfNode(const CXXBaseSpecifier *Base)
  2037. : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
  2038. /// Determine what kind of offsetof node this is.
  2039. Kind getKind() const { return static_cast<Kind>(Data & Mask); }
  2040. /// For an array element node, returns the index into the array
  2041. /// of expressions.
  2042. unsigned getArrayExprIndex() const {
  2043. assert(getKind() == Array);
  2044. return Data >> 2;
  2045. }
  2046. /// For a field offsetof node, returns the field.
  2047. FieldDecl *getField() const {
  2048. assert(getKind() == Field);
  2049. return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
  2050. }
  2051. /// For a field or identifier offsetof node, returns the name of
  2052. /// the field.
  2053. IdentifierInfo *getFieldName() const;
  2054. /// For a base class node, returns the base specifier.
  2055. CXXBaseSpecifier *getBase() const {
  2056. assert(getKind() == Base);
  2057. return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
  2058. }
  2059. /// Retrieve the source range that covers this offsetof node.
  2060. ///
  2061. /// For an array element node, the source range contains the locations of
  2062. /// the square brackets. For a field or identifier node, the source range
  2063. /// contains the location of the period (if there is one) and the
  2064. /// identifier.
  2065. SourceRange getSourceRange() const LLVM_READONLY { return Range; }
  2066. SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
  2067. SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
  2068. };
  2069. /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
  2070. /// offsetof(record-type, member-designator). For example, given:
  2071. /// @code
  2072. /// struct S {
  2073. /// float f;
  2074. /// double d;
  2075. /// };
  2076. /// struct T {
  2077. /// int i;
  2078. /// struct S s[10];
  2079. /// };
  2080. /// @endcode
  2081. /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
  2082. class OffsetOfExpr final
  2083. : public Expr,
  2084. private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
  2085. SourceLocation OperatorLoc, RParenLoc;
  2086. // Base type;
  2087. TypeSourceInfo *TSInfo;
  2088. // Number of sub-components (i.e. instances of OffsetOfNode).
  2089. unsigned NumComps;
  2090. // Number of sub-expressions (i.e. array subscript expressions).
  2091. unsigned NumExprs;
  2092. size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
  2093. return NumComps;
  2094. }
  2095. OffsetOfExpr(const ASTContext &C, QualType type,
  2096. SourceLocation OperatorLoc, TypeSourceInfo *tsi,
  2097. ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
  2098. SourceLocation RParenLoc);
  2099. explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
  2100. : Expr(OffsetOfExprClass, EmptyShell()),
  2101. TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
  2102. public:
  2103. static OffsetOfExpr *Create(const ASTContext &C, QualType type,
  2104. SourceLocation OperatorLoc, TypeSourceInfo *tsi,
  2105. ArrayRef<OffsetOfNode> comps,
  2106. ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
  2107. static OffsetOfExpr *CreateEmpty(const ASTContext &C,
  2108. unsigned NumComps, unsigned NumExprs);
  2109. /// getOperatorLoc - Return the location of the operator.
  2110. SourceLocation getOperatorLoc() const { return OperatorLoc; }
  2111. void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
  2112. /// Return the location of the right parentheses.
  2113. SourceLocation getRParenLoc() const { return RParenLoc; }
  2114. void setRParenLoc(SourceLocation R) { RParenLoc = R; }
  2115. TypeSourceInfo *getTypeSourceInfo() const {
  2116. return TSInfo;
  2117. }
  2118. void setTypeSourceInfo(TypeSourceInfo *tsi) {
  2119. TSInfo = tsi;
  2120. }
  2121. const OffsetOfNode &getComponent(unsigned Idx) const {
  2122. assert(Idx < NumComps && "Subscript out of range");
  2123. return getTrailingObjects<OffsetOfNode>()[Idx];
  2124. }
  2125. void setComponent(unsigned Idx, OffsetOfNode ON) {
  2126. assert(Idx < NumComps && "Subscript out of range");
  2127. getTrailingObjects<OffsetOfNode>()[Idx] = ON;
  2128. }
  2129. unsigned getNumComponents() const {
  2130. return NumComps;
  2131. }
  2132. Expr* getIndexExpr(unsigned Idx) {
  2133. assert(Idx < NumExprs && "Subscript out of range");
  2134. return getTrailingObjects<Expr *>()[Idx];
  2135. }
  2136. const Expr *getIndexExpr(unsigned Idx) const {
  2137. assert(Idx < NumExprs && "Subscript out of range");
  2138. return getTrailingObjects<Expr *>()[Idx];
  2139. }
  2140. void setIndexExpr(unsigned Idx, Expr* E) {
  2141. assert(Idx < NumComps && "Subscript out of range");
  2142. getTrailingObjects<Expr *>()[Idx] = E;
  2143. }
  2144. unsigned getNumExpressions() const {
  2145. return NumExprs;
  2146. }
  2147. SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
  2148. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  2149. static bool classof(const Stmt *T) {
  2150. return T->getStmtClass() == OffsetOfExprClass;
  2151. }
  2152. // Iterators
  2153. child_range children() {
  2154. Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
  2155. return child_range(begin, begin + NumExprs);
  2156. }
  2157. const_child_range children() const {
  2158. Stmt *const *begin =
  2159. reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
  2160. return const_child_range(begin, begin + NumExprs);
  2161. }
  2162. friend TrailingObjects;
  2163. };
  2164. /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
  2165. /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
  2166. /// vec_step (OpenCL 1.1 6.11.12).
  2167. class UnaryExprOrTypeTraitExpr : public Expr {
  2168. union {
  2169. TypeSourceInfo *Ty;
  2170. Stmt *Ex;
  2171. } Argument;
  2172. SourceLocation OpLoc, RParenLoc;
  2173. public:
  2174. UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
  2175. QualType resultType, SourceLocation op,
  2176. SourceLocation rp)
  2177. : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
  2178. OK_Ordinary),
  2179. OpLoc(op), RParenLoc(rp) {
  2180. assert(ExprKind <= UETT_Last && "invalid enum value!");
  2181. UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
  2182. assert(static_cast<unsigned>(ExprKind) ==
  2183. UnaryExprOrTypeTraitExprBits.Kind &&
  2184. "UnaryExprOrTypeTraitExprBits.Kind overflow!");
  2185. UnaryExprOrTypeTraitExprBits.IsType = true;
  2186. Argument.Ty = TInfo;
  2187. setDependence(computeDependence(this));
  2188. }
  2189. UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
  2190. QualType resultType, SourceLocation op,
  2191. SourceLocation rp);
  2192. /// Construct an empty sizeof/alignof expression.
  2193. explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
  2194. : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
  2195. UnaryExprOrTypeTrait getKind() const {
  2196. return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
  2197. }
  2198. void setKind(UnaryExprOrTypeTrait K) {
  2199. assert(K <= UETT_Last && "invalid enum value!");
  2200. UnaryExprOrTypeTraitExprBits.Kind = K;
  2201. assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
  2202. "UnaryExprOrTypeTraitExprBits.Kind overflow!");
  2203. }
  2204. bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
  2205. QualType getArgumentType() const {
  2206. return getArgumentTypeInfo()->getType();
  2207. }
  2208. TypeSourceInfo *getArgumentTypeInfo() const {
  2209. assert(isArgumentType() && "calling getArgumentType() when arg is expr");
  2210. return Argument.Ty;
  2211. }
  2212. Expr *getArgumentExpr() {
  2213. assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
  2214. return static_cast<Expr*>(Argument.Ex);
  2215. }
  2216. const Expr *getArgumentExpr() const {
  2217. return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
  2218. }
  2219. void setArgument(Expr *E) {
  2220. Argument.Ex = E;
  2221. UnaryExprOrTypeTraitExprBits.IsType = false;
  2222. }
  2223. void setArgument(TypeSourceInfo *TInfo) {
  2224. Argument.Ty = TInfo;
  2225. UnaryExprOrTypeTraitExprBits.IsType = true;
  2226. }
  2227. /// Gets the argument type, or the type of the argument expression, whichever
  2228. /// is appropriate.
  2229. QualType getTypeOfArgument() const {
  2230. return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
  2231. }
  2232. SourceLocation getOperatorLoc() const { return OpLoc; }
  2233. void setOperatorLoc(SourceLocation L) { OpLoc = L; }
  2234. SourceLocation getRParenLoc() const { return RParenLoc; }
  2235. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  2236. SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
  2237. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  2238. static bool classof(const Stmt *T) {
  2239. return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
  2240. }
  2241. // Iterators
  2242. child_range children();
  2243. const_child_range children() const;
  2244. };
  2245. //===----------------------------------------------------------------------===//
  2246. // Postfix Operators.
  2247. //===----------------------------------------------------------------------===//
  2248. /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
  2249. class ArraySubscriptExpr : public Expr {
  2250. enum { LHS, RHS, END_EXPR };
  2251. Stmt *SubExprs[END_EXPR];
  2252. bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
  2253. public:
  2254. ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
  2255. ExprObjectKind OK, SourceLocation rbracketloc)
  2256. : Expr(ArraySubscriptExprClass, t, VK, OK) {
  2257. SubExprs[LHS] = lhs;
  2258. SubExprs[RHS] = rhs;
  2259. ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
  2260. setDependence(computeDependence(this));
  2261. }
  2262. /// Create an empty array subscript expression.
  2263. explicit ArraySubscriptExpr(EmptyShell Shell)
  2264. : Expr(ArraySubscriptExprClass, Shell) { }
  2265. /// An array access can be written A[4] or 4[A] (both are equivalent).
  2266. /// - getBase() and getIdx() always present the normalized view: A[4].
  2267. /// In this case getBase() returns "A" and getIdx() returns "4".
  2268. /// - getLHS() and getRHS() present the syntactic view. e.g. for
  2269. /// 4[A] getLHS() returns "4".
  2270. /// Note: Because vector element access is also written A[4] we must
  2271. /// predicate the format conversion in getBase and getIdx only on the
  2272. /// the type of the RHS, as it is possible for the LHS to be a vector of
  2273. /// integer type
  2274. Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
  2275. const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  2276. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  2277. Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
  2278. const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  2279. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  2280. Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
  2281. const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
  2282. Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
  2283. const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
  2284. SourceLocation getBeginLoc() const LLVM_READONLY {
  2285. return getLHS()->getBeginLoc();
  2286. }
  2287. SourceLocation getEndLoc() const { return getRBracketLoc(); }
  2288. SourceLocation getRBracketLoc() const {
  2289. return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
  2290. }
  2291. void setRBracketLoc(SourceLocation L) {
  2292. ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
  2293. }
  2294. SourceLocation getExprLoc() const LLVM_READONLY {
  2295. return getBase()->getExprLoc();
  2296. }
  2297. static bool classof(const Stmt *T) {
  2298. return T->getStmtClass() == ArraySubscriptExprClass;
  2299. }
  2300. // Iterators
  2301. child_range children() {
  2302. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  2303. }
  2304. const_child_range children() const {
  2305. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2306. }
  2307. };
  2308. /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
  2309. /// extension.
  2310. /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
  2311. /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
  2312. /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
  2313. /// exist during the initial construction of the AST.
  2314. class MatrixSubscriptExpr : public Expr {
  2315. enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
  2316. Stmt *SubExprs[END_EXPR];
  2317. public:
  2318. MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
  2319. SourceLocation RBracketLoc)
  2320. : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
  2321. OK_MatrixComponent) {
  2322. SubExprs[BASE] = Base;
  2323. SubExprs[ROW_IDX] = RowIdx;
  2324. SubExprs[COLUMN_IDX] = ColumnIdx;
  2325. ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
  2326. setDependence(computeDependence(this));
  2327. }
  2328. /// Create an empty matrix subscript expression.
  2329. explicit MatrixSubscriptExpr(EmptyShell Shell)
  2330. : Expr(MatrixSubscriptExprClass, Shell) {}
  2331. bool isIncomplete() const {
  2332. bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
  2333. assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
  2334. "expressions without column index must be marked as incomplete");
  2335. return IsIncomplete;
  2336. }
  2337. Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
  2338. const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
  2339. void setBase(Expr *E) { SubExprs[BASE] = E; }
  2340. Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
  2341. const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
  2342. void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
  2343. Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
  2344. const Expr *getColumnIdx() const {
  2345. assert(!isIncomplete() &&
  2346. "cannot get the column index of an incomplete expression");
  2347. return cast<Expr>(SubExprs[COLUMN_IDX]);
  2348. }
  2349. void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
  2350. SourceLocation getBeginLoc() const LLVM_READONLY {
  2351. return getBase()->getBeginLoc();
  2352. }
  2353. SourceLocation getEndLoc() const { return getRBracketLoc(); }
  2354. SourceLocation getExprLoc() const LLVM_READONLY {
  2355. return getBase()->getExprLoc();
  2356. }
  2357. SourceLocation getRBracketLoc() const {
  2358. return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
  2359. }
  2360. void setRBracketLoc(SourceLocation L) {
  2361. ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
  2362. }
  2363. static bool classof(const Stmt *T) {
  2364. return T->getStmtClass() == MatrixSubscriptExprClass;
  2365. }
  2366. // Iterators
  2367. child_range children() {
  2368. return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2369. }
  2370. const_child_range children() const {
  2371. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2372. }
  2373. };
  2374. /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
  2375. /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
  2376. /// while its subclasses may represent alternative syntax that (semantically)
  2377. /// results in a function call. For example, CXXOperatorCallExpr is
  2378. /// a subclass for overloaded operator calls that use operator syntax, e.g.,
  2379. /// "str1 + str2" to resolve to a function call.
  2380. class CallExpr : public Expr {
  2381. enum { FN = 0, PREARGS_START = 1 };
  2382. /// The number of arguments in the call expression.
  2383. unsigned NumArgs;
  2384. /// The location of the right parenthese. This has a different meaning for
  2385. /// the derived classes of CallExpr.
  2386. SourceLocation RParenLoc;
  2387. // CallExpr store some data in trailing objects. However since CallExpr
  2388. // is used a base of other expression classes we cannot use
  2389. // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
  2390. // and casts.
  2391. //
  2392. // The trailing objects are in order:
  2393. //
  2394. // * A single "Stmt *" for the callee expression.
  2395. //
  2396. // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
  2397. //
  2398. // * An array of getNumArgs() "Stmt *" for the argument expressions.
  2399. //
  2400. // * An optional of type FPOptionsOverride.
  2401. //
  2402. // Note that we store the offset in bytes from the this pointer to the start
  2403. // of the trailing objects. It would be perfectly possible to compute it
  2404. // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
  2405. // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
  2406. // compute this once and then load the offset from the bit-fields of Stmt,
  2407. // instead of re-computing the offset each time the trailing objects are
  2408. // accessed.
  2409. /// Return a pointer to the start of the trailing array of "Stmt *".
  2410. Stmt **getTrailingStmts() {
  2411. return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
  2412. CallExprBits.OffsetToTrailingObjects);
  2413. }
  2414. Stmt *const *getTrailingStmts() const {
  2415. return const_cast<CallExpr *>(this)->getTrailingStmts();
  2416. }
  2417. /// Map a statement class to the appropriate offset in bytes from the
  2418. /// this pointer to the trailing objects.
  2419. static unsigned offsetToTrailingObjects(StmtClass SC);
  2420. unsigned getSizeOfTrailingStmts() const {
  2421. return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
  2422. }
  2423. size_t getOffsetOfTrailingFPFeatures() const {
  2424. assert(hasStoredFPFeatures());
  2425. return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
  2426. }
  2427. public:
  2428. enum class ADLCallKind : bool { NotADL, UsesADL };
  2429. static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
  2430. static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
  2431. protected:
  2432. /// Build a call expression, assuming that appropriate storage has been
  2433. /// allocated for the trailing objects.
  2434. CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
  2435. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  2436. SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
  2437. unsigned MinNumArgs, ADLCallKind UsesADL);
  2438. /// Build an empty call expression, for deserialization.
  2439. CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
  2440. bool hasFPFeatures, EmptyShell Empty);
  2441. /// Return the size in bytes needed for the trailing objects.
  2442. /// Used by the derived classes to allocate the right amount of storage.
  2443. static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
  2444. bool HasFPFeatures) {
  2445. return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
  2446. HasFPFeatures * sizeof(FPOptionsOverride);
  2447. }
  2448. Stmt *getPreArg(unsigned I) {
  2449. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2450. return getTrailingStmts()[PREARGS_START + I];
  2451. }
  2452. const Stmt *getPreArg(unsigned I) const {
  2453. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2454. return getTrailingStmts()[PREARGS_START + I];
  2455. }
  2456. void setPreArg(unsigned I, Stmt *PreArg) {
  2457. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2458. getTrailingStmts()[PREARGS_START + I] = PreArg;
  2459. }
  2460. unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
  2461. /// Return a pointer to the trailing FPOptions
  2462. FPOptionsOverride *getTrailingFPFeatures() {
  2463. assert(hasStoredFPFeatures());
  2464. return reinterpret_cast<FPOptionsOverride *>(
  2465. reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
  2466. getSizeOfTrailingStmts());
  2467. }
  2468. const FPOptionsOverride *getTrailingFPFeatures() const {
  2469. assert(hasStoredFPFeatures());
  2470. return reinterpret_cast<const FPOptionsOverride *>(
  2471. reinterpret_cast<const char *>(this) +
  2472. CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
  2473. }
  2474. public:
  2475. /// Create a call expression.
  2476. /// \param Fn The callee expression,
  2477. /// \param Args The argument array,
  2478. /// \param Ty The type of the call expression (which is *not* the return
  2479. /// type in general),
  2480. /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
  2481. /// \param RParenLoc The location of the right parenthesis in the call
  2482. /// expression.
  2483. /// \param FPFeatures Floating-point features associated with the call,
  2484. /// \param MinNumArgs Specifies the minimum number of arguments. The actual
  2485. /// number of arguments will be the greater of Args.size()
  2486. /// and MinNumArgs. This is used in a few places to allocate
  2487. /// enough storage for the default arguments.
  2488. /// \param UsesADL Specifies whether the callee was found through
  2489. /// argument-dependent lookup.
  2490. ///
  2491. /// Note that you can use CreateTemporary if you need a temporary call
  2492. /// expression on the stack.
  2493. static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
  2494. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  2495. SourceLocation RParenLoc,
  2496. FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
  2497. ADLCallKind UsesADL = NotADL);
  2498. /// Create a temporary call expression with no arguments in the memory
  2499. /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
  2500. /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
  2501. ///
  2502. /// \code{.cpp}
  2503. /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
  2504. /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
  2505. /// \endcode
  2506. static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
  2507. ExprValueKind VK, SourceLocation RParenLoc,
  2508. ADLCallKind UsesADL = NotADL);
  2509. /// Create an empty call expression, for deserialization.
  2510. static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
  2511. bool HasFPFeatures, EmptyShell Empty);
  2512. Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
  2513. const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
  2514. void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
  2515. ADLCallKind getADLCallKind() const {
  2516. return static_cast<ADLCallKind>(CallExprBits.UsesADL);
  2517. }
  2518. void setADLCallKind(ADLCallKind V = UsesADL) {
  2519. CallExprBits.UsesADL = static_cast<bool>(V);
  2520. }
  2521. bool usesADL() const { return getADLCallKind() == UsesADL; }
  2522. bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
  2523. Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
  2524. const Decl *getCalleeDecl() const {
  2525. return getCallee()->getReferencedDeclOfCallee();
  2526. }
  2527. /// If the callee is a FunctionDecl, return it. Otherwise return null.
  2528. FunctionDecl *getDirectCallee() {
  2529. return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
  2530. }
  2531. const FunctionDecl *getDirectCallee() const {
  2532. return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
  2533. }
  2534. /// getNumArgs - Return the number of actual arguments to this call.
  2535. unsigned getNumArgs() const { return NumArgs; }
  2536. /// Retrieve the call arguments.
  2537. Expr **getArgs() {
  2538. return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
  2539. getNumPreArgs());
  2540. }
  2541. const Expr *const *getArgs() const {
  2542. return reinterpret_cast<const Expr *const *>(
  2543. getTrailingStmts() + PREARGS_START + getNumPreArgs());
  2544. }
  2545. /// getArg - Return the specified argument.
  2546. Expr *getArg(unsigned Arg) {
  2547. assert(Arg < getNumArgs() && "Arg access out of range!");
  2548. return getArgs()[Arg];
  2549. }
  2550. const Expr *getArg(unsigned Arg) const {
  2551. assert(Arg < getNumArgs() && "Arg access out of range!");
  2552. return getArgs()[Arg];
  2553. }
  2554. /// setArg - Set the specified argument.
  2555. /// ! the dependence bits might be stale after calling this setter, it is
  2556. /// *caller*'s responsibility to recompute them by calling
  2557. /// computeDependence().
  2558. void setArg(unsigned Arg, Expr *ArgExpr) {
  2559. assert(Arg < getNumArgs() && "Arg access out of range!");
  2560. getArgs()[Arg] = ArgExpr;
  2561. }
  2562. /// Compute and set dependence bits.
  2563. void computeDependence() {
  2564. setDependence(clang::computeDependence(
  2565. this, llvm::ArrayRef(
  2566. reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
  2567. getNumPreArgs())));
  2568. }
  2569. /// Reduce the number of arguments in this call expression. This is used for
  2570. /// example during error recovery to drop extra arguments. There is no way
  2571. /// to perform the opposite because: 1.) We don't track how much storage
  2572. /// we have for the argument array 2.) This would potentially require growing
  2573. /// the argument array, something we cannot support since the arguments are
  2574. /// stored in a trailing array.
  2575. void shrinkNumArgs(unsigned NewNumArgs) {
  2576. assert((NewNumArgs <= getNumArgs()) &&
  2577. "shrinkNumArgs cannot increase the number of arguments!");
  2578. NumArgs = NewNumArgs;
  2579. }
  2580. /// Bluntly set a new number of arguments without doing any checks whatsoever.
  2581. /// Only used during construction of a CallExpr in a few places in Sema.
  2582. /// FIXME: Find a way to remove it.
  2583. void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
  2584. typedef ExprIterator arg_iterator;
  2585. typedef ConstExprIterator const_arg_iterator;
  2586. typedef llvm::iterator_range<arg_iterator> arg_range;
  2587. typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
  2588. arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
  2589. const_arg_range arguments() const {
  2590. return const_arg_range(arg_begin(), arg_end());
  2591. }
  2592. arg_iterator arg_begin() {
  2593. return getTrailingStmts() + PREARGS_START + getNumPreArgs();
  2594. }
  2595. arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
  2596. const_arg_iterator arg_begin() const {
  2597. return getTrailingStmts() + PREARGS_START + getNumPreArgs();
  2598. }
  2599. const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
  2600. /// This method provides fast access to all the subexpressions of
  2601. /// a CallExpr without going through the slower virtual child_iterator
  2602. /// interface. This provides efficient reverse iteration of the
  2603. /// subexpressions. This is currently used for CFG construction.
  2604. ArrayRef<Stmt *> getRawSubExprs() {
  2605. return llvm::ArrayRef(getTrailingStmts(),
  2606. PREARGS_START + getNumPreArgs() + getNumArgs());
  2607. }
  2608. /// Get FPOptionsOverride from trailing storage.
  2609. FPOptionsOverride getStoredFPFeatures() const {
  2610. assert(hasStoredFPFeatures());
  2611. return *getTrailingFPFeatures();
  2612. }
  2613. /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
  2614. void setStoredFPFeatures(FPOptionsOverride F) {
  2615. assert(hasStoredFPFeatures());
  2616. *getTrailingFPFeatures() = F;
  2617. }
  2618. // Get the FP features status of this operator. Only meaningful for
  2619. // operations on floating point types.
  2620. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  2621. if (hasStoredFPFeatures())
  2622. return getStoredFPFeatures().applyOverrides(LO);
  2623. return FPOptions::defaultWithoutTrailingStorage(LO);
  2624. }
  2625. FPOptionsOverride getFPFeatures() const {
  2626. if (hasStoredFPFeatures())
  2627. return getStoredFPFeatures();
  2628. return FPOptionsOverride();
  2629. }
  2630. /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
  2631. /// of the callee. If not, return 0.
  2632. unsigned getBuiltinCallee() const;
  2633. /// Returns \c true if this is a call to a builtin which does not
  2634. /// evaluate side-effects within its arguments.
  2635. bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
  2636. /// getCallReturnType - Get the return type of the call expr. This is not
  2637. /// always the type of the expr itself, if the return type is a reference
  2638. /// type.
  2639. QualType getCallReturnType(const ASTContext &Ctx) const;
  2640. /// Returns the WarnUnusedResultAttr that is either declared on the called
  2641. /// function, or its return type declaration.
  2642. const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
  2643. /// Returns true if this call expression should warn on unused results.
  2644. bool hasUnusedResultAttr(const ASTContext &Ctx) const {
  2645. return getUnusedResultAttr(Ctx) != nullptr;
  2646. }
  2647. SourceLocation getRParenLoc() const { return RParenLoc; }
  2648. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  2649. SourceLocation getBeginLoc() const LLVM_READONLY;
  2650. SourceLocation getEndLoc() const LLVM_READONLY;
  2651. /// Return true if this is a call to __assume() or __builtin_assume() with
  2652. /// a non-value-dependent constant parameter evaluating as false.
  2653. bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
  2654. /// Used by Sema to implement MSVC-compatible delayed name lookup.
  2655. /// (Usually Exprs themselves should set dependence).
  2656. void markDependentForPostponedNameLookup() {
  2657. setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
  2658. }
  2659. bool isCallToStdMove() const;
  2660. static bool classof(const Stmt *T) {
  2661. return T->getStmtClass() >= firstCallExprConstant &&
  2662. T->getStmtClass() <= lastCallExprConstant;
  2663. }
  2664. // Iterators
  2665. child_range children() {
  2666. return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
  2667. getNumPreArgs() + getNumArgs());
  2668. }
  2669. const_child_range children() const {
  2670. return const_child_range(getTrailingStmts(),
  2671. getTrailingStmts() + PREARGS_START +
  2672. getNumPreArgs() + getNumArgs());
  2673. }
  2674. };
  2675. /// Extra data stored in some MemberExpr objects.
  2676. struct MemberExprNameQualifier {
  2677. /// The nested-name-specifier that qualifies the name, including
  2678. /// source-location information.
  2679. NestedNameSpecifierLoc QualifierLoc;
  2680. /// The DeclAccessPair through which the MemberDecl was found due to
  2681. /// name qualifiers.
  2682. DeclAccessPair FoundDecl;
  2683. };
  2684. /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
  2685. ///
  2686. class MemberExpr final
  2687. : public Expr,
  2688. private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
  2689. ASTTemplateKWAndArgsInfo,
  2690. TemplateArgumentLoc> {
  2691. friend class ASTReader;
  2692. friend class ASTStmtReader;
  2693. friend class ASTStmtWriter;
  2694. friend TrailingObjects;
  2695. /// Base - the expression for the base pointer or structure references. In
  2696. /// X.F, this is "X".
  2697. Stmt *Base;
  2698. /// MemberDecl - This is the decl being referenced by the field/member name.
  2699. /// In X.F, this is the decl referenced by F.
  2700. ValueDecl *MemberDecl;
  2701. /// MemberDNLoc - Provides source/type location info for the
  2702. /// declaration name embedded in MemberDecl.
  2703. DeclarationNameLoc MemberDNLoc;
  2704. /// MemberLoc - This is the location of the member name.
  2705. SourceLocation MemberLoc;
  2706. size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
  2707. return hasQualifierOrFoundDecl();
  2708. }
  2709. size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
  2710. return hasTemplateKWAndArgsInfo();
  2711. }
  2712. bool hasQualifierOrFoundDecl() const {
  2713. return MemberExprBits.HasQualifierOrFoundDecl;
  2714. }
  2715. bool hasTemplateKWAndArgsInfo() const {
  2716. return MemberExprBits.HasTemplateKWAndArgsInfo;
  2717. }
  2718. MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
  2719. ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
  2720. QualType T, ExprValueKind VK, ExprObjectKind OK,
  2721. NonOdrUseReason NOUR);
  2722. MemberExpr(EmptyShell Empty)
  2723. : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
  2724. public:
  2725. static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
  2726. SourceLocation OperatorLoc,
  2727. NestedNameSpecifierLoc QualifierLoc,
  2728. SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
  2729. DeclAccessPair FoundDecl,
  2730. DeclarationNameInfo MemberNameInfo,
  2731. const TemplateArgumentListInfo *TemplateArgs,
  2732. QualType T, ExprValueKind VK, ExprObjectKind OK,
  2733. NonOdrUseReason NOUR);
  2734. /// Create an implicit MemberExpr, with no location, qualifier, template
  2735. /// arguments, and so on. Suitable only for non-static member access.
  2736. static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
  2737. bool IsArrow, ValueDecl *MemberDecl,
  2738. QualType T, ExprValueKind VK,
  2739. ExprObjectKind OK) {
  2740. return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
  2741. SourceLocation(), MemberDecl,
  2742. DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
  2743. DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
  2744. }
  2745. static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
  2746. bool HasFoundDecl,
  2747. bool HasTemplateKWAndArgsInfo,
  2748. unsigned NumTemplateArgs);
  2749. void setBase(Expr *E) { Base = E; }
  2750. Expr *getBase() const { return cast<Expr>(Base); }
  2751. /// Retrieve the member declaration to which this expression refers.
  2752. ///
  2753. /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
  2754. /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
  2755. ValueDecl *getMemberDecl() const { return MemberDecl; }
  2756. void setMemberDecl(ValueDecl *D);
  2757. /// Retrieves the declaration found by lookup.
  2758. DeclAccessPair getFoundDecl() const {
  2759. if (!hasQualifierOrFoundDecl())
  2760. return DeclAccessPair::make(getMemberDecl(),
  2761. getMemberDecl()->getAccess());
  2762. return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
  2763. }
  2764. /// Determines whether this member expression actually had
  2765. /// a C++ nested-name-specifier prior to the name of the member, e.g.,
  2766. /// x->Base::foo.
  2767. bool hasQualifier() const { return getQualifier() != nullptr; }
  2768. /// If the member name was qualified, retrieves the
  2769. /// nested-name-specifier that precedes the member name, with source-location
  2770. /// information.
  2771. NestedNameSpecifierLoc getQualifierLoc() const {
  2772. if (!hasQualifierOrFoundDecl())
  2773. return NestedNameSpecifierLoc();
  2774. return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
  2775. }
  2776. /// If the member name was qualified, retrieves the
  2777. /// nested-name-specifier that precedes the member name. Otherwise, returns
  2778. /// NULL.
  2779. NestedNameSpecifier *getQualifier() const {
  2780. return getQualifierLoc().getNestedNameSpecifier();
  2781. }
  2782. /// Retrieve the location of the template keyword preceding
  2783. /// the member name, if any.
  2784. SourceLocation getTemplateKeywordLoc() const {
  2785. if (!hasTemplateKWAndArgsInfo())
  2786. return SourceLocation();
  2787. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
  2788. }
  2789. /// Retrieve the location of the left angle bracket starting the
  2790. /// explicit template argument list following the member name, if any.
  2791. SourceLocation getLAngleLoc() const {
  2792. if (!hasTemplateKWAndArgsInfo())
  2793. return SourceLocation();
  2794. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
  2795. }
  2796. /// Retrieve the location of the right angle bracket ending the
  2797. /// explicit template argument list following the member name, if any.
  2798. SourceLocation getRAngleLoc() const {
  2799. if (!hasTemplateKWAndArgsInfo())
  2800. return SourceLocation();
  2801. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
  2802. }
  2803. /// Determines whether the member name was preceded by the template keyword.
  2804. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
  2805. /// Determines whether the member name was followed by an
  2806. /// explicit template argument list.
  2807. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
  2808. /// Copies the template arguments (if present) into the given
  2809. /// structure.
  2810. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
  2811. if (hasExplicitTemplateArgs())
  2812. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
  2813. getTrailingObjects<TemplateArgumentLoc>(), List);
  2814. }
  2815. /// Retrieve the template arguments provided as part of this
  2816. /// template-id.
  2817. const TemplateArgumentLoc *getTemplateArgs() const {
  2818. if (!hasExplicitTemplateArgs())
  2819. return nullptr;
  2820. return getTrailingObjects<TemplateArgumentLoc>();
  2821. }
  2822. /// Retrieve the number of template arguments provided as part of this
  2823. /// template-id.
  2824. unsigned getNumTemplateArgs() const {
  2825. if (!hasExplicitTemplateArgs())
  2826. return 0;
  2827. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
  2828. }
  2829. ArrayRef<TemplateArgumentLoc> template_arguments() const {
  2830. return {getTemplateArgs(), getNumTemplateArgs()};
  2831. }
  2832. /// Retrieve the member declaration name info.
  2833. DeclarationNameInfo getMemberNameInfo() const {
  2834. return DeclarationNameInfo(MemberDecl->getDeclName(),
  2835. MemberLoc, MemberDNLoc);
  2836. }
  2837. SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
  2838. bool isArrow() const { return MemberExprBits.IsArrow; }
  2839. void setArrow(bool A) { MemberExprBits.IsArrow = A; }
  2840. /// getMemberLoc - Return the location of the "member", in X->F, it is the
  2841. /// location of 'F'.
  2842. SourceLocation getMemberLoc() const { return MemberLoc; }
  2843. void setMemberLoc(SourceLocation L) { MemberLoc = L; }
  2844. SourceLocation getBeginLoc() const LLVM_READONLY;
  2845. SourceLocation getEndLoc() const LLVM_READONLY;
  2846. SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
  2847. /// Determine whether the base of this explicit is implicit.
  2848. bool isImplicitAccess() const {
  2849. return getBase() && getBase()->isImplicitCXXThis();
  2850. }
  2851. /// Returns true if this member expression refers to a method that
  2852. /// was resolved from an overloaded set having size greater than 1.
  2853. bool hadMultipleCandidates() const {
  2854. return MemberExprBits.HadMultipleCandidates;
  2855. }
  2856. /// Sets the flag telling whether this expression refers to
  2857. /// a method that was resolved from an overloaded set having size
  2858. /// greater than 1.
  2859. void setHadMultipleCandidates(bool V = true) {
  2860. MemberExprBits.HadMultipleCandidates = V;
  2861. }
  2862. /// Returns true if virtual dispatch is performed.
  2863. /// If the member access is fully qualified, (i.e. X::f()), virtual
  2864. /// dispatching is not performed. In -fapple-kext mode qualified
  2865. /// calls to virtual method will still go through the vtable.
  2866. bool performsVirtualDispatch(const LangOptions &LO) const {
  2867. return LO.AppleKext || !hasQualifier();
  2868. }
  2869. /// Is this expression a non-odr-use reference, and if so, why?
  2870. /// This is only meaningful if the named member is a static member.
  2871. NonOdrUseReason isNonOdrUse() const {
  2872. return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
  2873. }
  2874. static bool classof(const Stmt *T) {
  2875. return T->getStmtClass() == MemberExprClass;
  2876. }
  2877. // Iterators
  2878. child_range children() { return child_range(&Base, &Base+1); }
  2879. const_child_range children() const {
  2880. return const_child_range(&Base, &Base + 1);
  2881. }
  2882. };
  2883. /// CompoundLiteralExpr - [C99 6.5.2.5]
  2884. ///
  2885. class CompoundLiteralExpr : public Expr {
  2886. /// LParenLoc - If non-null, this is the location of the left paren in a
  2887. /// compound literal like "(int){4}". This can be null if this is a
  2888. /// synthesized compound expression.
  2889. SourceLocation LParenLoc;
  2890. /// The type as written. This can be an incomplete array type, in
  2891. /// which case the actual expression type will be different.
  2892. /// The int part of the pair stores whether this expr is file scope.
  2893. llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
  2894. Stmt *Init;
  2895. public:
  2896. CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
  2897. QualType T, ExprValueKind VK, Expr *init, bool fileScope)
  2898. : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
  2899. LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
  2900. setDependence(computeDependence(this));
  2901. }
  2902. /// Construct an empty compound literal.
  2903. explicit CompoundLiteralExpr(EmptyShell Empty)
  2904. : Expr(CompoundLiteralExprClass, Empty) { }
  2905. const Expr *getInitializer() const { return cast<Expr>(Init); }
  2906. Expr *getInitializer() { return cast<Expr>(Init); }
  2907. void setInitializer(Expr *E) { Init = E; }
  2908. bool isFileScope() const { return TInfoAndScope.getInt(); }
  2909. void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
  2910. SourceLocation getLParenLoc() const { return LParenLoc; }
  2911. void setLParenLoc(SourceLocation L) { LParenLoc = L; }
  2912. TypeSourceInfo *getTypeSourceInfo() const {
  2913. return TInfoAndScope.getPointer();
  2914. }
  2915. void setTypeSourceInfo(TypeSourceInfo *tinfo) {
  2916. TInfoAndScope.setPointer(tinfo);
  2917. }
  2918. SourceLocation getBeginLoc() const LLVM_READONLY {
  2919. // FIXME: Init should never be null.
  2920. if (!Init)
  2921. return SourceLocation();
  2922. if (LParenLoc.isInvalid())
  2923. return Init->getBeginLoc();
  2924. return LParenLoc;
  2925. }
  2926. SourceLocation getEndLoc() const LLVM_READONLY {
  2927. // FIXME: Init should never be null.
  2928. if (!Init)
  2929. return SourceLocation();
  2930. return Init->getEndLoc();
  2931. }
  2932. static bool classof(const Stmt *T) {
  2933. return T->getStmtClass() == CompoundLiteralExprClass;
  2934. }
  2935. // Iterators
  2936. child_range children() { return child_range(&Init, &Init+1); }
  2937. const_child_range children() const {
  2938. return const_child_range(&Init, &Init + 1);
  2939. }
  2940. };
  2941. /// CastExpr - Base class for type casts, including both implicit
  2942. /// casts (ImplicitCastExpr) and explicit casts that have some
  2943. /// representation in the source code (ExplicitCastExpr's derived
  2944. /// classes).
  2945. class CastExpr : public Expr {
  2946. Stmt *Op;
  2947. bool CastConsistency() const;
  2948. const CXXBaseSpecifier * const *path_buffer() const {
  2949. return const_cast<CastExpr*>(this)->path_buffer();
  2950. }
  2951. CXXBaseSpecifier **path_buffer();
  2952. friend class ASTStmtReader;
  2953. protected:
  2954. CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
  2955. Expr *op, unsigned BasePathSize, bool HasFPFeatures)
  2956. : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
  2957. CastExprBits.Kind = kind;
  2958. CastExprBits.PartOfExplicitCast = false;
  2959. CastExprBits.BasePathSize = BasePathSize;
  2960. assert((CastExprBits.BasePathSize == BasePathSize) &&
  2961. "BasePathSize overflow!");
  2962. assert(CastConsistency());
  2963. CastExprBits.HasFPFeatures = HasFPFeatures;
  2964. }
  2965. /// Construct an empty cast.
  2966. CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
  2967. bool HasFPFeatures)
  2968. : Expr(SC, Empty) {
  2969. CastExprBits.PartOfExplicitCast = false;
  2970. CastExprBits.BasePathSize = BasePathSize;
  2971. CastExprBits.HasFPFeatures = HasFPFeatures;
  2972. assert((CastExprBits.BasePathSize == BasePathSize) &&
  2973. "BasePathSize overflow!");
  2974. }
  2975. /// Return a pointer to the trailing FPOptions.
  2976. /// \pre hasStoredFPFeatures() == true
  2977. FPOptionsOverride *getTrailingFPFeatures();
  2978. const FPOptionsOverride *getTrailingFPFeatures() const {
  2979. return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
  2980. }
  2981. public:
  2982. CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
  2983. void setCastKind(CastKind K) { CastExprBits.Kind = K; }
  2984. static const char *getCastKindName(CastKind CK);
  2985. const char *getCastKindName() const { return getCastKindName(getCastKind()); }
  2986. Expr *getSubExpr() { return cast<Expr>(Op); }
  2987. const Expr *getSubExpr() const { return cast<Expr>(Op); }
  2988. void setSubExpr(Expr *E) { Op = E; }
  2989. /// Retrieve the cast subexpression as it was written in the source
  2990. /// code, looking through any implicit casts or other intermediate nodes
  2991. /// introduced by semantic analysis.
  2992. Expr *getSubExprAsWritten();
  2993. const Expr *getSubExprAsWritten() const {
  2994. return const_cast<CastExpr *>(this)->getSubExprAsWritten();
  2995. }
  2996. /// If this cast applies a user-defined conversion, retrieve the conversion
  2997. /// function that it invokes.
  2998. NamedDecl *getConversionFunction() const;
  2999. typedef CXXBaseSpecifier **path_iterator;
  3000. typedef const CXXBaseSpecifier *const *path_const_iterator;
  3001. bool path_empty() const { return path_size() == 0; }
  3002. unsigned path_size() const { return CastExprBits.BasePathSize; }
  3003. path_iterator path_begin() { return path_buffer(); }
  3004. path_iterator path_end() { return path_buffer() + path_size(); }
  3005. path_const_iterator path_begin() const { return path_buffer(); }
  3006. path_const_iterator path_end() const { return path_buffer() + path_size(); }
  3007. llvm::iterator_range<path_iterator> path() {
  3008. return llvm::make_range(path_begin(), path_end());
  3009. }
  3010. llvm::iterator_range<path_const_iterator> path() const {
  3011. return llvm::make_range(path_begin(), path_end());
  3012. }
  3013. const FieldDecl *getTargetUnionField() const {
  3014. assert(getCastKind() == CK_ToUnion);
  3015. return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
  3016. }
  3017. bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
  3018. /// Get FPOptionsOverride from trailing storage.
  3019. FPOptionsOverride getStoredFPFeatures() const {
  3020. assert(hasStoredFPFeatures());
  3021. return *getTrailingFPFeatures();
  3022. }
  3023. // Get the FP features status of this operation. Only meaningful for
  3024. // operations on floating point types.
  3025. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  3026. if (hasStoredFPFeatures())
  3027. return getStoredFPFeatures().applyOverrides(LO);
  3028. return FPOptions::defaultWithoutTrailingStorage(LO);
  3029. }
  3030. FPOptionsOverride getFPFeatures() const {
  3031. if (hasStoredFPFeatures())
  3032. return getStoredFPFeatures();
  3033. return FPOptionsOverride();
  3034. }
  3035. static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
  3036. QualType opType);
  3037. static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
  3038. QualType opType);
  3039. static bool classof(const Stmt *T) {
  3040. return T->getStmtClass() >= firstCastExprConstant &&
  3041. T->getStmtClass() <= lastCastExprConstant;
  3042. }
  3043. // Iterators
  3044. child_range children() { return child_range(&Op, &Op+1); }
  3045. const_child_range children() const { return const_child_range(&Op, &Op + 1); }
  3046. };
  3047. /// ImplicitCastExpr - Allows us to explicitly represent implicit type
  3048. /// conversions, which have no direct representation in the original
  3049. /// source code. For example: converting T[]->T*, void f()->void
  3050. /// (*f)(), float->double, short->int, etc.
  3051. ///
  3052. /// In C, implicit casts always produce rvalues. However, in C++, an
  3053. /// implicit cast whose result is being bound to a reference will be
  3054. /// an lvalue or xvalue. For example:
  3055. ///
  3056. /// @code
  3057. /// class Base { };
  3058. /// class Derived : public Base { };
  3059. /// Derived &&ref();
  3060. /// void f(Derived d) {
  3061. /// Base& b = d; // initializer is an ImplicitCastExpr
  3062. /// // to an lvalue of type Base
  3063. /// Base&& r = ref(); // initializer is an ImplicitCastExpr
  3064. /// // to an xvalue of type Base
  3065. /// }
  3066. /// @endcode
  3067. class ImplicitCastExpr final
  3068. : public CastExpr,
  3069. private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
  3070. FPOptionsOverride> {
  3071. ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
  3072. unsigned BasePathLength, FPOptionsOverride FPO,
  3073. ExprValueKind VK)
  3074. : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
  3075. FPO.requiresTrailingStorage()) {
  3076. setDependence(computeDependence(this));
  3077. if (hasStoredFPFeatures())
  3078. *getTrailingFPFeatures() = FPO;
  3079. }
  3080. /// Construct an empty implicit cast.
  3081. explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
  3082. bool HasFPFeatures)
  3083. : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
  3084. unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
  3085. return path_size();
  3086. }
  3087. public:
  3088. enum OnStack_t { OnStack };
  3089. ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
  3090. ExprValueKind VK, FPOptionsOverride FPO)
  3091. : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
  3092. FPO.requiresTrailingStorage()) {
  3093. if (hasStoredFPFeatures())
  3094. *getTrailingFPFeatures() = FPO;
  3095. }
  3096. bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
  3097. void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
  3098. CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
  3099. }
  3100. static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
  3101. CastKind Kind, Expr *Operand,
  3102. const CXXCastPath *BasePath,
  3103. ExprValueKind Cat, FPOptionsOverride FPO);
  3104. static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
  3105. unsigned PathSize, bool HasFPFeatures);
  3106. SourceLocation getBeginLoc() const LLVM_READONLY {
  3107. return getSubExpr()->getBeginLoc();
  3108. }
  3109. SourceLocation getEndLoc() const LLVM_READONLY {
  3110. return getSubExpr()->getEndLoc();
  3111. }
  3112. static bool classof(const Stmt *T) {
  3113. return T->getStmtClass() == ImplicitCastExprClass;
  3114. }
  3115. friend TrailingObjects;
  3116. friend class CastExpr;
  3117. };
  3118. /// ExplicitCastExpr - An explicit cast written in the source
  3119. /// code.
  3120. ///
  3121. /// This class is effectively an abstract class, because it provides
  3122. /// the basic representation of an explicitly-written cast without
  3123. /// specifying which kind of cast (C cast, functional cast, static
  3124. /// cast, etc.) was written; specific derived classes represent the
  3125. /// particular style of cast and its location information.
  3126. ///
  3127. /// Unlike implicit casts, explicit cast nodes have two different
  3128. /// types: the type that was written into the source code, and the
  3129. /// actual type of the expression as determined by semantic
  3130. /// analysis. These types may differ slightly. For example, in C++ one
  3131. /// can cast to a reference type, which indicates that the resulting
  3132. /// expression will be an lvalue or xvalue. The reference type, however,
  3133. /// will not be used as the type of the expression.
  3134. class ExplicitCastExpr : public CastExpr {
  3135. /// TInfo - Source type info for the (written) type
  3136. /// this expression is casting to.
  3137. TypeSourceInfo *TInfo;
  3138. protected:
  3139. ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
  3140. CastKind kind, Expr *op, unsigned PathSize,
  3141. bool HasFPFeatures, TypeSourceInfo *writtenTy)
  3142. : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
  3143. TInfo(writtenTy) {
  3144. setDependence(computeDependence(this));
  3145. }
  3146. /// Construct an empty explicit cast.
  3147. ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
  3148. bool HasFPFeatures)
  3149. : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
  3150. public:
  3151. /// getTypeInfoAsWritten - Returns the type source info for the type
  3152. /// that this expression is casting to.
  3153. TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
  3154. void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
  3155. /// getTypeAsWritten - Returns the type that this expression is
  3156. /// casting to, as written in the source code.
  3157. QualType getTypeAsWritten() const { return TInfo->getType(); }
  3158. static bool classof(const Stmt *T) {
  3159. return T->getStmtClass() >= firstExplicitCastExprConstant &&
  3160. T->getStmtClass() <= lastExplicitCastExprConstant;
  3161. }
  3162. };
  3163. /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
  3164. /// cast in C++ (C++ [expr.cast]), which uses the syntax
  3165. /// (Type)expr. For example: @c (int)f.
  3166. class CStyleCastExpr final
  3167. : public ExplicitCastExpr,
  3168. private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
  3169. FPOptionsOverride> {
  3170. SourceLocation LPLoc; // the location of the left paren
  3171. SourceLocation RPLoc; // the location of the right paren
  3172. CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
  3173. unsigned PathSize, FPOptionsOverride FPO,
  3174. TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
  3175. : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
  3176. FPO.requiresTrailingStorage(), writtenTy),
  3177. LPLoc(l), RPLoc(r) {
  3178. if (hasStoredFPFeatures())
  3179. *getTrailingFPFeatures() = FPO;
  3180. }
  3181. /// Construct an empty C-style explicit cast.
  3182. explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
  3183. bool HasFPFeatures)
  3184. : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
  3185. unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
  3186. return path_size();
  3187. }
  3188. public:
  3189. static CStyleCastExpr *
  3190. Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
  3191. Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
  3192. TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
  3193. static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
  3194. unsigned PathSize, bool HasFPFeatures);
  3195. SourceLocation getLParenLoc() const { return LPLoc; }
  3196. void setLParenLoc(SourceLocation L) { LPLoc = L; }
  3197. SourceLocation getRParenLoc() const { return RPLoc; }
  3198. void setRParenLoc(SourceLocation L) { RPLoc = L; }
  3199. SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
  3200. SourceLocation getEndLoc() const LLVM_READONLY {
  3201. return getSubExpr()->getEndLoc();
  3202. }
  3203. static bool classof(const Stmt *T) {
  3204. return T->getStmtClass() == CStyleCastExprClass;
  3205. }
  3206. friend TrailingObjects;
  3207. friend class CastExpr;
  3208. };
  3209. /// A builtin binary operation expression such as "x + y" or "x <= y".
  3210. ///
  3211. /// This expression node kind describes a builtin binary operation,
  3212. /// such as "x + y" for integer values "x" and "y". The operands will
  3213. /// already have been converted to appropriate types (e.g., by
  3214. /// performing promotions or conversions).
  3215. ///
  3216. /// In C++, where operators may be overloaded, a different kind of
  3217. /// expression node (CXXOperatorCallExpr) is used to express the
  3218. /// invocation of an overloaded operator with operator syntax. Within
  3219. /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
  3220. /// used to store an expression "x + y" depends on the subexpressions
  3221. /// for x and y. If neither x or y is type-dependent, and the "+"
  3222. /// operator resolves to a built-in operation, BinaryOperator will be
  3223. /// used to express the computation (x and y may still be
  3224. /// value-dependent). If either x or y is type-dependent, or if the
  3225. /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
  3226. /// be used to express the computation.
  3227. class BinaryOperator : public Expr {
  3228. enum { LHS, RHS, END_EXPR };
  3229. Stmt *SubExprs[END_EXPR];
  3230. public:
  3231. typedef BinaryOperatorKind Opcode;
  3232. protected:
  3233. size_t offsetOfTrailingStorage() const;
  3234. /// Return a pointer to the trailing FPOptions
  3235. FPOptionsOverride *getTrailingFPFeatures() {
  3236. assert(BinaryOperatorBits.HasFPFeatures);
  3237. return reinterpret_cast<FPOptionsOverride *>(
  3238. reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
  3239. }
  3240. const FPOptionsOverride *getTrailingFPFeatures() const {
  3241. assert(BinaryOperatorBits.HasFPFeatures);
  3242. return reinterpret_cast<const FPOptionsOverride *>(
  3243. reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
  3244. }
  3245. /// Build a binary operator, assuming that appropriate storage has been
  3246. /// allocated for the trailing objects when needed.
  3247. BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
  3248. QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
  3249. SourceLocation opLoc, FPOptionsOverride FPFeatures);
  3250. /// Construct an empty binary operator.
  3251. explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
  3252. BinaryOperatorBits.Opc = BO_Comma;
  3253. }
  3254. public:
  3255. static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
  3256. static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
  3257. Opcode opc, QualType ResTy, ExprValueKind VK,
  3258. ExprObjectKind OK, SourceLocation opLoc,
  3259. FPOptionsOverride FPFeatures);
  3260. SourceLocation getExprLoc() const { return getOperatorLoc(); }
  3261. SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
  3262. void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
  3263. Opcode getOpcode() const {
  3264. return static_cast<Opcode>(BinaryOperatorBits.Opc);
  3265. }
  3266. void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
  3267. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3268. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  3269. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3270. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  3271. SourceLocation getBeginLoc() const LLVM_READONLY {
  3272. return getLHS()->getBeginLoc();
  3273. }
  3274. SourceLocation getEndLoc() const LLVM_READONLY {
  3275. return getRHS()->getEndLoc();
  3276. }
  3277. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  3278. /// corresponds to, e.g. "<<=".
  3279. static StringRef getOpcodeStr(Opcode Op);
  3280. StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
  3281. /// Retrieve the binary opcode that corresponds to the given
  3282. /// overloaded operator.
  3283. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
  3284. /// Retrieve the overloaded operator kind that corresponds to
  3285. /// the given binary opcode.
  3286. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
  3287. /// predicates to categorize the respective opcodes.
  3288. static bool isPtrMemOp(Opcode Opc) {
  3289. return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
  3290. }
  3291. bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
  3292. static bool isMultiplicativeOp(Opcode Opc) {
  3293. return Opc >= BO_Mul && Opc <= BO_Rem;
  3294. }
  3295. bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
  3296. static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
  3297. bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
  3298. static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
  3299. bool isShiftOp() const { return isShiftOp(getOpcode()); }
  3300. static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
  3301. bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
  3302. static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
  3303. bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
  3304. static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
  3305. bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
  3306. static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
  3307. bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
  3308. static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
  3309. bool isCommaOp() const { return isCommaOp(getOpcode()); }
  3310. static Opcode negateComparisonOp(Opcode Opc) {
  3311. switch (Opc) {
  3312. default:
  3313. llvm_unreachable("Not a comparison operator.");
  3314. case BO_LT: return BO_GE;
  3315. case BO_GT: return BO_LE;
  3316. case BO_LE: return BO_GT;
  3317. case BO_GE: return BO_LT;
  3318. case BO_EQ: return BO_NE;
  3319. case BO_NE: return BO_EQ;
  3320. }
  3321. }
  3322. static Opcode reverseComparisonOp(Opcode Opc) {
  3323. switch (Opc) {
  3324. default:
  3325. llvm_unreachable("Not a comparison operator.");
  3326. case BO_LT: return BO_GT;
  3327. case BO_GT: return BO_LT;
  3328. case BO_LE: return BO_GE;
  3329. case BO_GE: return BO_LE;
  3330. case BO_EQ:
  3331. case BO_NE:
  3332. return Opc;
  3333. }
  3334. }
  3335. static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
  3336. bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
  3337. static bool isAssignmentOp(Opcode Opc) {
  3338. return Opc >= BO_Assign && Opc <= BO_OrAssign;
  3339. }
  3340. bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
  3341. static bool isCompoundAssignmentOp(Opcode Opc) {
  3342. return Opc > BO_Assign && Opc <= BO_OrAssign;
  3343. }
  3344. bool isCompoundAssignmentOp() const {
  3345. return isCompoundAssignmentOp(getOpcode());
  3346. }
  3347. static Opcode getOpForCompoundAssignment(Opcode Opc) {
  3348. assert(isCompoundAssignmentOp(Opc));
  3349. if (Opc >= BO_AndAssign)
  3350. return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
  3351. else
  3352. return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
  3353. }
  3354. static bool isShiftAssignOp(Opcode Opc) {
  3355. return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
  3356. }
  3357. bool isShiftAssignOp() const {
  3358. return isShiftAssignOp(getOpcode());
  3359. }
  3360. // Return true if a binary operator using the specified opcode and operands
  3361. // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
  3362. // integer to a pointer.
  3363. static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
  3364. Expr *LHS, Expr *RHS);
  3365. static bool classof(const Stmt *S) {
  3366. return S->getStmtClass() >= firstBinaryOperatorConstant &&
  3367. S->getStmtClass() <= lastBinaryOperatorConstant;
  3368. }
  3369. // Iterators
  3370. child_range children() {
  3371. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3372. }
  3373. const_child_range children() const {
  3374. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3375. }
  3376. /// Set and fetch the bit that shows whether FPFeatures needs to be
  3377. /// allocated in Trailing Storage
  3378. void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
  3379. bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
  3380. /// Get FPFeatures from trailing storage
  3381. FPOptionsOverride getStoredFPFeatures() const {
  3382. assert(hasStoredFPFeatures());
  3383. return *getTrailingFPFeatures();
  3384. }
  3385. /// Set FPFeatures in trailing storage, used only by Serialization
  3386. void setStoredFPFeatures(FPOptionsOverride F) {
  3387. assert(BinaryOperatorBits.HasFPFeatures);
  3388. *getTrailingFPFeatures() = F;
  3389. }
  3390. // Get the FP features status of this operator. Only meaningful for
  3391. // operations on floating point types.
  3392. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  3393. if (BinaryOperatorBits.HasFPFeatures)
  3394. return getStoredFPFeatures().applyOverrides(LO);
  3395. return FPOptions::defaultWithoutTrailingStorage(LO);
  3396. }
  3397. // This is used in ASTImporter
  3398. FPOptionsOverride getFPFeatures() const {
  3399. if (BinaryOperatorBits.HasFPFeatures)
  3400. return getStoredFPFeatures();
  3401. return FPOptionsOverride();
  3402. }
  3403. // Get the FP contractability status of this operator. Only meaningful for
  3404. // operations on floating point types.
  3405. bool isFPContractableWithinStatement(const LangOptions &LO) const {
  3406. return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
  3407. }
  3408. // Get the FENV_ACCESS status of this operator. Only meaningful for
  3409. // operations on floating point types.
  3410. bool isFEnvAccessOn(const LangOptions &LO) const {
  3411. return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
  3412. }
  3413. protected:
  3414. BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
  3415. QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
  3416. SourceLocation opLoc, FPOptionsOverride FPFeatures,
  3417. bool dead2);
  3418. /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
  3419. BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
  3420. BinaryOperatorBits.Opc = BO_MulAssign;
  3421. }
  3422. /// Return the size in bytes needed for the trailing objects.
  3423. /// Used to allocate the right amount of storage.
  3424. static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
  3425. return HasFPFeatures * sizeof(FPOptionsOverride);
  3426. }
  3427. };
  3428. /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
  3429. /// track of the type the operation is performed in. Due to the semantics of
  3430. /// these operators, the operands are promoted, the arithmetic performed, an
  3431. /// implicit conversion back to the result type done, then the assignment takes
  3432. /// place. This captures the intermediate type which the computation is done
  3433. /// in.
  3434. class CompoundAssignOperator : public BinaryOperator {
  3435. QualType ComputationLHSType;
  3436. QualType ComputationResultType;
  3437. /// Construct an empty CompoundAssignOperator.
  3438. explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
  3439. bool hasFPFeatures)
  3440. : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
  3441. protected:
  3442. CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
  3443. QualType ResType, ExprValueKind VK, ExprObjectKind OK,
  3444. SourceLocation OpLoc, FPOptionsOverride FPFeatures,
  3445. QualType CompLHSType, QualType CompResultType)
  3446. : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
  3447. true),
  3448. ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
  3449. assert(isCompoundAssignmentOp() &&
  3450. "Only should be used for compound assignments");
  3451. }
  3452. public:
  3453. static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
  3454. bool hasFPFeatures);
  3455. static CompoundAssignOperator *
  3456. Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
  3457. ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
  3458. FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
  3459. QualType CompResultType = QualType());
  3460. // The two computation types are the type the LHS is converted
  3461. // to for the computation and the type of the result; the two are
  3462. // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
  3463. QualType getComputationLHSType() const { return ComputationLHSType; }
  3464. void setComputationLHSType(QualType T) { ComputationLHSType = T; }
  3465. QualType getComputationResultType() const { return ComputationResultType; }
  3466. void setComputationResultType(QualType T) { ComputationResultType = T; }
  3467. static bool classof(const Stmt *S) {
  3468. return S->getStmtClass() == CompoundAssignOperatorClass;
  3469. }
  3470. };
  3471. inline size_t BinaryOperator::offsetOfTrailingStorage() const {
  3472. assert(BinaryOperatorBits.HasFPFeatures);
  3473. return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
  3474. : sizeof(BinaryOperator);
  3475. }
  3476. /// AbstractConditionalOperator - An abstract base class for
  3477. /// ConditionalOperator and BinaryConditionalOperator.
  3478. class AbstractConditionalOperator : public Expr {
  3479. SourceLocation QuestionLoc, ColonLoc;
  3480. friend class ASTStmtReader;
  3481. protected:
  3482. AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
  3483. ExprObjectKind OK, SourceLocation qloc,
  3484. SourceLocation cloc)
  3485. : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
  3486. AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
  3487. : Expr(SC, Empty) { }
  3488. public:
  3489. // getCond - Return the expression representing the condition for
  3490. // the ?: operator.
  3491. Expr *getCond() const;
  3492. // getTrueExpr - Return the subexpression representing the value of
  3493. // the expression if the condition evaluates to true.
  3494. Expr *getTrueExpr() const;
  3495. // getFalseExpr - Return the subexpression representing the value of
  3496. // the expression if the condition evaluates to false. This is
  3497. // the same as getRHS.
  3498. Expr *getFalseExpr() const;
  3499. SourceLocation getQuestionLoc() const { return QuestionLoc; }
  3500. SourceLocation getColonLoc() const { return ColonLoc; }
  3501. static bool classof(const Stmt *T) {
  3502. return T->getStmtClass() == ConditionalOperatorClass ||
  3503. T->getStmtClass() == BinaryConditionalOperatorClass;
  3504. }
  3505. };
  3506. /// ConditionalOperator - The ?: ternary operator. The GNU "missing
  3507. /// middle" extension is a BinaryConditionalOperator.
  3508. class ConditionalOperator : public AbstractConditionalOperator {
  3509. enum { COND, LHS, RHS, END_EXPR };
  3510. Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
  3511. friend class ASTStmtReader;
  3512. public:
  3513. ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
  3514. SourceLocation CLoc, Expr *rhs, QualType t,
  3515. ExprValueKind VK, ExprObjectKind OK)
  3516. : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
  3517. CLoc) {
  3518. SubExprs[COND] = cond;
  3519. SubExprs[LHS] = lhs;
  3520. SubExprs[RHS] = rhs;
  3521. setDependence(computeDependence(this));
  3522. }
  3523. /// Build an empty conditional operator.
  3524. explicit ConditionalOperator(EmptyShell Empty)
  3525. : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
  3526. // getCond - Return the expression representing the condition for
  3527. // the ?: operator.
  3528. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3529. // getTrueExpr - Return the subexpression representing the value of
  3530. // the expression if the condition evaluates to true.
  3531. Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
  3532. // getFalseExpr - Return the subexpression representing the value of
  3533. // the expression if the condition evaluates to false. This is
  3534. // the same as getRHS.
  3535. Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
  3536. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3537. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3538. SourceLocation getBeginLoc() const LLVM_READONLY {
  3539. return getCond()->getBeginLoc();
  3540. }
  3541. SourceLocation getEndLoc() const LLVM_READONLY {
  3542. return getRHS()->getEndLoc();
  3543. }
  3544. static bool classof(const Stmt *T) {
  3545. return T->getStmtClass() == ConditionalOperatorClass;
  3546. }
  3547. // Iterators
  3548. child_range children() {
  3549. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3550. }
  3551. const_child_range children() const {
  3552. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3553. }
  3554. };
  3555. /// BinaryConditionalOperator - The GNU extension to the conditional
  3556. /// operator which allows the middle operand to be omitted.
  3557. ///
  3558. /// This is a different expression kind on the assumption that almost
  3559. /// every client ends up needing to know that these are different.
  3560. class BinaryConditionalOperator : public AbstractConditionalOperator {
  3561. enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
  3562. /// - the common condition/left-hand-side expression, which will be
  3563. /// evaluated as the opaque value
  3564. /// - the condition, expressed in terms of the opaque value
  3565. /// - the left-hand-side, expressed in terms of the opaque value
  3566. /// - the right-hand-side
  3567. Stmt *SubExprs[NUM_SUBEXPRS];
  3568. OpaqueValueExpr *OpaqueValue;
  3569. friend class ASTStmtReader;
  3570. public:
  3571. BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
  3572. Expr *cond, Expr *lhs, Expr *rhs,
  3573. SourceLocation qloc, SourceLocation cloc,
  3574. QualType t, ExprValueKind VK, ExprObjectKind OK)
  3575. : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
  3576. qloc, cloc),
  3577. OpaqueValue(opaqueValue) {
  3578. SubExprs[COMMON] = common;
  3579. SubExprs[COND] = cond;
  3580. SubExprs[LHS] = lhs;
  3581. SubExprs[RHS] = rhs;
  3582. assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
  3583. setDependence(computeDependence(this));
  3584. }
  3585. /// Build an empty conditional operator.
  3586. explicit BinaryConditionalOperator(EmptyShell Empty)
  3587. : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
  3588. /// getCommon - Return the common expression, written to the
  3589. /// left of the condition. The opaque value will be bound to the
  3590. /// result of this expression.
  3591. Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
  3592. /// getOpaqueValue - Return the opaque value placeholder.
  3593. OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
  3594. /// getCond - Return the condition expression; this is defined
  3595. /// in terms of the opaque value.
  3596. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3597. /// getTrueExpr - Return the subexpression which will be
  3598. /// evaluated if the condition evaluates to true; this is defined
  3599. /// in terms of the opaque value.
  3600. Expr *getTrueExpr() const {
  3601. return cast<Expr>(SubExprs[LHS]);
  3602. }
  3603. /// getFalseExpr - Return the subexpression which will be
  3604. /// evaluated if the condnition evaluates to false; this is
  3605. /// defined in terms of the opaque value.
  3606. Expr *getFalseExpr() const {
  3607. return cast<Expr>(SubExprs[RHS]);
  3608. }
  3609. SourceLocation getBeginLoc() const LLVM_READONLY {
  3610. return getCommon()->getBeginLoc();
  3611. }
  3612. SourceLocation getEndLoc() const LLVM_READONLY {
  3613. return getFalseExpr()->getEndLoc();
  3614. }
  3615. static bool classof(const Stmt *T) {
  3616. return T->getStmtClass() == BinaryConditionalOperatorClass;
  3617. }
  3618. // Iterators
  3619. child_range children() {
  3620. return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
  3621. }
  3622. const_child_range children() const {
  3623. return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
  3624. }
  3625. };
  3626. inline Expr *AbstractConditionalOperator::getCond() const {
  3627. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3628. return co->getCond();
  3629. return cast<BinaryConditionalOperator>(this)->getCond();
  3630. }
  3631. inline Expr *AbstractConditionalOperator::getTrueExpr() const {
  3632. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3633. return co->getTrueExpr();
  3634. return cast<BinaryConditionalOperator>(this)->getTrueExpr();
  3635. }
  3636. inline Expr *AbstractConditionalOperator::getFalseExpr() const {
  3637. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3638. return co->getFalseExpr();
  3639. return cast<BinaryConditionalOperator>(this)->getFalseExpr();
  3640. }
  3641. /// AddrLabelExpr - The GNU address of label extension, representing &&label.
  3642. class AddrLabelExpr : public Expr {
  3643. SourceLocation AmpAmpLoc, LabelLoc;
  3644. LabelDecl *Label;
  3645. public:
  3646. AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
  3647. QualType t)
  3648. : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
  3649. LabelLoc(LLoc), Label(L) {
  3650. setDependence(ExprDependence::None);
  3651. }
  3652. /// Build an empty address of a label expression.
  3653. explicit AddrLabelExpr(EmptyShell Empty)
  3654. : Expr(AddrLabelExprClass, Empty) { }
  3655. SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
  3656. void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
  3657. SourceLocation getLabelLoc() const { return LabelLoc; }
  3658. void setLabelLoc(SourceLocation L) { LabelLoc = L; }
  3659. SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
  3660. SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
  3661. LabelDecl *getLabel() const { return Label; }
  3662. void setLabel(LabelDecl *L) { Label = L; }
  3663. static bool classof(const Stmt *T) {
  3664. return T->getStmtClass() == AddrLabelExprClass;
  3665. }
  3666. // Iterators
  3667. child_range children() {
  3668. return child_range(child_iterator(), child_iterator());
  3669. }
  3670. const_child_range children() const {
  3671. return const_child_range(const_child_iterator(), const_child_iterator());
  3672. }
  3673. };
  3674. /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
  3675. /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
  3676. /// takes the value of the last subexpression.
  3677. ///
  3678. /// A StmtExpr is always an r-value; values "returned" out of a
  3679. /// StmtExpr will be copied.
  3680. class StmtExpr : public Expr {
  3681. Stmt *SubStmt;
  3682. SourceLocation LParenLoc, RParenLoc;
  3683. public:
  3684. StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
  3685. SourceLocation RParenLoc, unsigned TemplateDepth)
  3686. : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
  3687. LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
  3688. setDependence(computeDependence(this, TemplateDepth));
  3689. // FIXME: A templated statement expression should have an associated
  3690. // DeclContext so that nested declarations always have a dependent context.
  3691. StmtExprBits.TemplateDepth = TemplateDepth;
  3692. }
  3693. /// Build an empty statement expression.
  3694. explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
  3695. CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
  3696. const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
  3697. void setSubStmt(CompoundStmt *S) { SubStmt = S; }
  3698. SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
  3699. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3700. SourceLocation getLParenLoc() const { return LParenLoc; }
  3701. void setLParenLoc(SourceLocation L) { LParenLoc = L; }
  3702. SourceLocation getRParenLoc() const { return RParenLoc; }
  3703. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3704. unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
  3705. static bool classof(const Stmt *T) {
  3706. return T->getStmtClass() == StmtExprClass;
  3707. }
  3708. // Iterators
  3709. child_range children() { return child_range(&SubStmt, &SubStmt+1); }
  3710. const_child_range children() const {
  3711. return const_child_range(&SubStmt, &SubStmt + 1);
  3712. }
  3713. };
  3714. /// ShuffleVectorExpr - clang-specific builtin-in function
  3715. /// __builtin_shufflevector.
  3716. /// This AST node represents a operator that does a constant
  3717. /// shuffle, similar to LLVM's shufflevector instruction. It takes
  3718. /// two vectors and a variable number of constant indices,
  3719. /// and returns the appropriately shuffled vector.
  3720. class ShuffleVectorExpr : public Expr {
  3721. SourceLocation BuiltinLoc, RParenLoc;
  3722. // SubExprs - the list of values passed to the __builtin_shufflevector
  3723. // function. The first two are vectors, and the rest are constant
  3724. // indices. The number of values in this list is always
  3725. // 2+the number of indices in the vector type.
  3726. Stmt **SubExprs;
  3727. unsigned NumExprs;
  3728. public:
  3729. ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
  3730. SourceLocation BLoc, SourceLocation RP);
  3731. /// Build an empty vector-shuffle expression.
  3732. explicit ShuffleVectorExpr(EmptyShell Empty)
  3733. : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
  3734. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3735. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3736. SourceLocation getRParenLoc() const { return RParenLoc; }
  3737. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3738. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3739. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3740. static bool classof(const Stmt *T) {
  3741. return T->getStmtClass() == ShuffleVectorExprClass;
  3742. }
  3743. /// getNumSubExprs - Return the size of the SubExprs array. This includes the
  3744. /// constant expression, the actual arguments passed in, and the function
  3745. /// pointers.
  3746. unsigned getNumSubExprs() const { return NumExprs; }
  3747. /// Retrieve the array of expressions.
  3748. Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
  3749. /// getExpr - Return the Expr at the specified index.
  3750. Expr *getExpr(unsigned Index) {
  3751. assert((Index < NumExprs) && "Arg access out of range!");
  3752. return cast<Expr>(SubExprs[Index]);
  3753. }
  3754. const Expr *getExpr(unsigned Index) const {
  3755. assert((Index < NumExprs) && "Arg access out of range!");
  3756. return cast<Expr>(SubExprs[Index]);
  3757. }
  3758. void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
  3759. llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
  3760. assert((N < NumExprs - 2) && "Shuffle idx out of range!");
  3761. return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
  3762. }
  3763. // Iterators
  3764. child_range children() {
  3765. return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
  3766. }
  3767. const_child_range children() const {
  3768. return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
  3769. }
  3770. };
  3771. /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
  3772. /// This AST node provides support for converting a vector type to another
  3773. /// vector type of the same arity.
  3774. class ConvertVectorExpr : public Expr {
  3775. private:
  3776. Stmt *SrcExpr;
  3777. TypeSourceInfo *TInfo;
  3778. SourceLocation BuiltinLoc, RParenLoc;
  3779. friend class ASTReader;
  3780. friend class ASTStmtReader;
  3781. explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
  3782. public:
  3783. ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
  3784. ExprValueKind VK, ExprObjectKind OK,
  3785. SourceLocation BuiltinLoc, SourceLocation RParenLoc)
  3786. : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
  3787. TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
  3788. setDependence(computeDependence(this));
  3789. }
  3790. /// getSrcExpr - Return the Expr to be converted.
  3791. Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
  3792. /// getTypeSourceInfo - Return the destination type.
  3793. TypeSourceInfo *getTypeSourceInfo() const {
  3794. return TInfo;
  3795. }
  3796. void setTypeSourceInfo(TypeSourceInfo *ti) {
  3797. TInfo = ti;
  3798. }
  3799. /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
  3800. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3801. /// getRParenLoc - Return the location of final right parenthesis.
  3802. SourceLocation getRParenLoc() const { return RParenLoc; }
  3803. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3804. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3805. static bool classof(const Stmt *T) {
  3806. return T->getStmtClass() == ConvertVectorExprClass;
  3807. }
  3808. // Iterators
  3809. child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
  3810. const_child_range children() const {
  3811. return const_child_range(&SrcExpr, &SrcExpr + 1);
  3812. }
  3813. };
  3814. /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
  3815. /// This AST node is similar to the conditional operator (?:) in C, with
  3816. /// the following exceptions:
  3817. /// - the test expression must be a integer constant expression.
  3818. /// - the expression returned acts like the chosen subexpression in every
  3819. /// visible way: the type is the same as that of the chosen subexpression,
  3820. /// and all predicates (whether it's an l-value, whether it's an integer
  3821. /// constant expression, etc.) return the same result as for the chosen
  3822. /// sub-expression.
  3823. class ChooseExpr : public Expr {
  3824. enum { COND, LHS, RHS, END_EXPR };
  3825. Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
  3826. SourceLocation BuiltinLoc, RParenLoc;
  3827. bool CondIsTrue;
  3828. public:
  3829. ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
  3830. ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
  3831. bool condIsTrue)
  3832. : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
  3833. CondIsTrue(condIsTrue) {
  3834. SubExprs[COND] = cond;
  3835. SubExprs[LHS] = lhs;
  3836. SubExprs[RHS] = rhs;
  3837. setDependence(computeDependence(this));
  3838. }
  3839. /// Build an empty __builtin_choose_expr.
  3840. explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
  3841. /// isConditionTrue - Return whether the condition is true (i.e. not
  3842. /// equal to zero).
  3843. bool isConditionTrue() const {
  3844. assert(!isConditionDependent() &&
  3845. "Dependent condition isn't true or false");
  3846. return CondIsTrue;
  3847. }
  3848. void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
  3849. bool isConditionDependent() const {
  3850. return getCond()->isTypeDependent() || getCond()->isValueDependent();
  3851. }
  3852. /// getChosenSubExpr - Return the subexpression chosen according to the
  3853. /// condition.
  3854. Expr *getChosenSubExpr() const {
  3855. return isConditionTrue() ? getLHS() : getRHS();
  3856. }
  3857. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3858. void setCond(Expr *E) { SubExprs[COND] = E; }
  3859. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3860. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  3861. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3862. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  3863. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3864. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3865. SourceLocation getRParenLoc() const { return RParenLoc; }
  3866. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3867. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3868. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3869. static bool classof(const Stmt *T) {
  3870. return T->getStmtClass() == ChooseExprClass;
  3871. }
  3872. // Iterators
  3873. child_range children() {
  3874. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3875. }
  3876. const_child_range children() const {
  3877. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3878. }
  3879. };
  3880. /// GNUNullExpr - Implements the GNU __null extension, which is a name
  3881. /// for a null pointer constant that has integral type (e.g., int or
  3882. /// long) and is the same size and alignment as a pointer. The __null
  3883. /// extension is typically only used by system headers, which define
  3884. /// NULL as __null in C++ rather than using 0 (which is an integer
  3885. /// that may not match the size of a pointer).
  3886. class GNUNullExpr : public Expr {
  3887. /// TokenLoc - The location of the __null keyword.
  3888. SourceLocation TokenLoc;
  3889. public:
  3890. GNUNullExpr(QualType Ty, SourceLocation Loc)
  3891. : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
  3892. setDependence(ExprDependence::None);
  3893. }
  3894. /// Build an empty GNU __null expression.
  3895. explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
  3896. /// getTokenLocation - The location of the __null token.
  3897. SourceLocation getTokenLocation() const { return TokenLoc; }
  3898. void setTokenLocation(SourceLocation L) { TokenLoc = L; }
  3899. SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
  3900. SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
  3901. static bool classof(const Stmt *T) {
  3902. return T->getStmtClass() == GNUNullExprClass;
  3903. }
  3904. // Iterators
  3905. child_range children() {
  3906. return child_range(child_iterator(), child_iterator());
  3907. }
  3908. const_child_range children() const {
  3909. return const_child_range(const_child_iterator(), const_child_iterator());
  3910. }
  3911. };
  3912. /// Represents a call to the builtin function \c __builtin_va_arg.
  3913. class VAArgExpr : public Expr {
  3914. Stmt *Val;
  3915. llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
  3916. SourceLocation BuiltinLoc, RParenLoc;
  3917. public:
  3918. VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
  3919. SourceLocation RPLoc, QualType t, bool IsMS)
  3920. : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
  3921. TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
  3922. setDependence(computeDependence(this));
  3923. }
  3924. /// Create an empty __builtin_va_arg expression.
  3925. explicit VAArgExpr(EmptyShell Empty)
  3926. : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
  3927. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  3928. Expr *getSubExpr() { return cast<Expr>(Val); }
  3929. void setSubExpr(Expr *E) { Val = E; }
  3930. /// Returns whether this is really a Win64 ABI va_arg expression.
  3931. bool isMicrosoftABI() const { return TInfo.getInt(); }
  3932. void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
  3933. TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
  3934. void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
  3935. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3936. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3937. SourceLocation getRParenLoc() const { return RParenLoc; }
  3938. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3939. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3940. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3941. static bool classof(const Stmt *T) {
  3942. return T->getStmtClass() == VAArgExprClass;
  3943. }
  3944. // Iterators
  3945. child_range children() { return child_range(&Val, &Val+1); }
  3946. const_child_range children() const {
  3947. return const_child_range(&Val, &Val + 1);
  3948. }
  3949. };
  3950. /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
  3951. /// __builtin_FUNCTION(), __builtin_FILE(), or __builtin_source_location().
  3952. class SourceLocExpr final : public Expr {
  3953. SourceLocation BuiltinLoc, RParenLoc;
  3954. DeclContext *ParentContext;
  3955. public:
  3956. enum IdentKind { Function, File, Line, Column, SourceLocStruct };
  3957. SourceLocExpr(const ASTContext &Ctx, IdentKind Type, QualType ResultTy,
  3958. SourceLocation BLoc, SourceLocation RParenLoc,
  3959. DeclContext *Context);
  3960. /// Build an empty call expression.
  3961. explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
  3962. /// Return the result of evaluating this SourceLocExpr in the specified
  3963. /// (and possibly null) default argument or initialization context.
  3964. APValue EvaluateInContext(const ASTContext &Ctx,
  3965. const Expr *DefaultExpr) const;
  3966. /// Return a string representing the name of the specific builtin function.
  3967. StringRef getBuiltinStr() const;
  3968. IdentKind getIdentKind() const {
  3969. return static_cast<IdentKind>(SourceLocExprBits.Kind);
  3970. }
  3971. bool isIntType() const {
  3972. switch (getIdentKind()) {
  3973. case File:
  3974. case Function:
  3975. case SourceLocStruct:
  3976. return false;
  3977. case Line:
  3978. case Column:
  3979. return true;
  3980. }
  3981. llvm_unreachable("unknown source location expression kind");
  3982. }
  3983. /// If the SourceLocExpr has been resolved return the subexpression
  3984. /// representing the resolved value. Otherwise return null.
  3985. const DeclContext *getParentContext() const { return ParentContext; }
  3986. DeclContext *getParentContext() { return ParentContext; }
  3987. SourceLocation getLocation() const { return BuiltinLoc; }
  3988. SourceLocation getBeginLoc() const { return BuiltinLoc; }
  3989. SourceLocation getEndLoc() const { return RParenLoc; }
  3990. child_range children() {
  3991. return child_range(child_iterator(), child_iterator());
  3992. }
  3993. const_child_range children() const {
  3994. return const_child_range(child_iterator(), child_iterator());
  3995. }
  3996. static bool classof(const Stmt *T) {
  3997. return T->getStmtClass() == SourceLocExprClass;
  3998. }
  3999. private:
  4000. friend class ASTStmtReader;
  4001. };
  4002. /// Describes an C or C++ initializer list.
  4003. ///
  4004. /// InitListExpr describes an initializer list, which can be used to
  4005. /// initialize objects of different types, including
  4006. /// struct/class/union types, arrays, and vectors. For example:
  4007. ///
  4008. /// @code
  4009. /// struct foo x = { 1, { 2, 3 } };
  4010. /// @endcode
  4011. ///
  4012. /// Prior to semantic analysis, an initializer list will represent the
  4013. /// initializer list as written by the user, but will have the
  4014. /// placeholder type "void". This initializer list is called the
  4015. /// syntactic form of the initializer, and may contain C99 designated
  4016. /// initializers (represented as DesignatedInitExprs), initializations
  4017. /// of subobject members without explicit braces, and so on. Clients
  4018. /// interested in the original syntax of the initializer list should
  4019. /// use the syntactic form of the initializer list.
  4020. ///
  4021. /// After semantic analysis, the initializer list will represent the
  4022. /// semantic form of the initializer, where the initializations of all
  4023. /// subobjects are made explicit with nested InitListExpr nodes and
  4024. /// C99 designators have been eliminated by placing the designated
  4025. /// initializations into the subobject they initialize. Additionally,
  4026. /// any "holes" in the initialization, where no initializer has been
  4027. /// specified for a particular subobject, will be replaced with
  4028. /// implicitly-generated ImplicitValueInitExpr expressions that
  4029. /// value-initialize the subobjects. Note, however, that the
  4030. /// initializer lists may still have fewer initializers than there are
  4031. /// elements to initialize within the object.
  4032. ///
  4033. /// After semantic analysis has completed, given an initializer list,
  4034. /// method isSemanticForm() returns true if and only if this is the
  4035. /// semantic form of the initializer list (note: the same AST node
  4036. /// may at the same time be the syntactic form).
  4037. /// Given the semantic form of the initializer list, one can retrieve
  4038. /// the syntactic form of that initializer list (when different)
  4039. /// using method getSyntacticForm(); the method returns null if applied
  4040. /// to a initializer list which is already in syntactic form.
  4041. /// Similarly, given the syntactic form (i.e., an initializer list such
  4042. /// that isSemanticForm() returns false), one can retrieve the semantic
  4043. /// form using method getSemanticForm().
  4044. /// Since many initializer lists have the same syntactic and semantic forms,
  4045. /// getSyntacticForm() may return NULL, indicating that the current
  4046. /// semantic initializer list also serves as its syntactic form.
  4047. class InitListExpr : public Expr {
  4048. // FIXME: Eliminate this vector in favor of ASTContext allocation
  4049. typedef ASTVector<Stmt *> InitExprsTy;
  4050. InitExprsTy InitExprs;
  4051. SourceLocation LBraceLoc, RBraceLoc;
  4052. /// The alternative form of the initializer list (if it exists).
  4053. /// The int part of the pair stores whether this initializer list is
  4054. /// in semantic form. If not null, the pointer points to:
  4055. /// - the syntactic form, if this is in semantic form;
  4056. /// - the semantic form, if this is in syntactic form.
  4057. llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
  4058. /// Either:
  4059. /// If this initializer list initializes an array with more elements than
  4060. /// there are initializers in the list, specifies an expression to be used
  4061. /// for value initialization of the rest of the elements.
  4062. /// Or
  4063. /// If this initializer list initializes a union, specifies which
  4064. /// field within the union will be initialized.
  4065. llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
  4066. public:
  4067. InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
  4068. ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
  4069. /// Build an empty initializer list.
  4070. explicit InitListExpr(EmptyShell Empty)
  4071. : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
  4072. unsigned getNumInits() const { return InitExprs.size(); }
  4073. /// Retrieve the set of initializers.
  4074. Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
  4075. /// Retrieve the set of initializers.
  4076. Expr * const *getInits() const {
  4077. return reinterpret_cast<Expr * const *>(InitExprs.data());
  4078. }
  4079. ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); }
  4080. ArrayRef<Expr *> inits() const {
  4081. return llvm::ArrayRef(getInits(), getNumInits());
  4082. }
  4083. const Expr *getInit(unsigned Init) const {
  4084. assert(Init < getNumInits() && "Initializer access out of range!");
  4085. return cast_or_null<Expr>(InitExprs[Init]);
  4086. }
  4087. Expr *getInit(unsigned Init) {
  4088. assert(Init < getNumInits() && "Initializer access out of range!");
  4089. return cast_or_null<Expr>(InitExprs[Init]);
  4090. }
  4091. void setInit(unsigned Init, Expr *expr) {
  4092. assert(Init < getNumInits() && "Initializer access out of range!");
  4093. InitExprs[Init] = expr;
  4094. if (expr)
  4095. setDependence(getDependence() | expr->getDependence());
  4096. }
  4097. /// Mark the semantic form of the InitListExpr as error when the semantic
  4098. /// analysis fails.
  4099. void markError() {
  4100. assert(isSemanticForm());
  4101. setDependence(getDependence() | ExprDependence::ErrorDependent);
  4102. }
  4103. /// Reserve space for some number of initializers.
  4104. void reserveInits(const ASTContext &C, unsigned NumInits);
  4105. /// Specify the number of initializers
  4106. ///
  4107. /// If there are more than @p NumInits initializers, the remaining
  4108. /// initializers will be destroyed. If there are fewer than @p
  4109. /// NumInits initializers, NULL expressions will be added for the
  4110. /// unknown initializers.
  4111. void resizeInits(const ASTContext &Context, unsigned NumInits);
  4112. /// Updates the initializer at index @p Init with the new
  4113. /// expression @p expr, and returns the old expression at that
  4114. /// location.
  4115. ///
  4116. /// When @p Init is out of range for this initializer list, the
  4117. /// initializer list will be extended with NULL expressions to
  4118. /// accommodate the new entry.
  4119. Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
  4120. /// If this initializer list initializes an array with more elements
  4121. /// than there are initializers in the list, specifies an expression to be
  4122. /// used for value initialization of the rest of the elements.
  4123. Expr *getArrayFiller() {
  4124. return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
  4125. }
  4126. const Expr *getArrayFiller() const {
  4127. return const_cast<InitListExpr *>(this)->getArrayFiller();
  4128. }
  4129. void setArrayFiller(Expr *filler);
  4130. /// Return true if this is an array initializer and its array "filler"
  4131. /// has been set.
  4132. bool hasArrayFiller() const { return getArrayFiller(); }
  4133. /// If this initializes a union, specifies which field in the
  4134. /// union to initialize.
  4135. ///
  4136. /// Typically, this field is the first named field within the
  4137. /// union. However, a designated initializer can specify the
  4138. /// initialization of a different field within the union.
  4139. FieldDecl *getInitializedFieldInUnion() {
  4140. return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
  4141. }
  4142. const FieldDecl *getInitializedFieldInUnion() const {
  4143. return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
  4144. }
  4145. void setInitializedFieldInUnion(FieldDecl *FD) {
  4146. assert((FD == nullptr
  4147. || getInitializedFieldInUnion() == nullptr
  4148. || getInitializedFieldInUnion() == FD)
  4149. && "Only one field of a union may be initialized at a time!");
  4150. ArrayFillerOrUnionFieldInit = FD;
  4151. }
  4152. // Explicit InitListExpr's originate from source code (and have valid source
  4153. // locations). Implicit InitListExpr's are created by the semantic analyzer.
  4154. // FIXME: This is wrong; InitListExprs created by semantic analysis have
  4155. // valid source locations too!
  4156. bool isExplicit() const {
  4157. return LBraceLoc.isValid() && RBraceLoc.isValid();
  4158. }
  4159. // Is this an initializer for an array of characters, initialized by a string
  4160. // literal or an @encode?
  4161. bool isStringLiteralInit() const;
  4162. /// Is this a transparent initializer list (that is, an InitListExpr that is
  4163. /// purely syntactic, and whose semantics are that of the sole contained
  4164. /// initializer)?
  4165. bool isTransparent() const;
  4166. /// Is this the zero initializer {0} in a language which considers it
  4167. /// idiomatic?
  4168. bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
  4169. SourceLocation getLBraceLoc() const { return LBraceLoc; }
  4170. void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
  4171. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  4172. void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
  4173. bool isSemanticForm() const { return AltForm.getInt(); }
  4174. InitListExpr *getSemanticForm() const {
  4175. return isSemanticForm() ? nullptr : AltForm.getPointer();
  4176. }
  4177. bool isSyntacticForm() const {
  4178. return !AltForm.getInt() || !AltForm.getPointer();
  4179. }
  4180. InitListExpr *getSyntacticForm() const {
  4181. return isSemanticForm() ? AltForm.getPointer() : nullptr;
  4182. }
  4183. void setSyntacticForm(InitListExpr *Init) {
  4184. AltForm.setPointer(Init);
  4185. AltForm.setInt(true);
  4186. Init->AltForm.setPointer(this);
  4187. Init->AltForm.setInt(false);
  4188. }
  4189. bool hadArrayRangeDesignator() const {
  4190. return InitListExprBits.HadArrayRangeDesignator != 0;
  4191. }
  4192. void sawArrayRangeDesignator(bool ARD = true) {
  4193. InitListExprBits.HadArrayRangeDesignator = ARD;
  4194. }
  4195. SourceLocation getBeginLoc() const LLVM_READONLY;
  4196. SourceLocation getEndLoc() const LLVM_READONLY;
  4197. static bool classof(const Stmt *T) {
  4198. return T->getStmtClass() == InitListExprClass;
  4199. }
  4200. // Iterators
  4201. child_range children() {
  4202. const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
  4203. return child_range(cast_away_const(CCR.begin()),
  4204. cast_away_const(CCR.end()));
  4205. }
  4206. const_child_range children() const {
  4207. // FIXME: This does not include the array filler expression.
  4208. if (InitExprs.empty())
  4209. return const_child_range(const_child_iterator(), const_child_iterator());
  4210. return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
  4211. }
  4212. typedef InitExprsTy::iterator iterator;
  4213. typedef InitExprsTy::const_iterator const_iterator;
  4214. typedef InitExprsTy::reverse_iterator reverse_iterator;
  4215. typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
  4216. iterator begin() { return InitExprs.begin(); }
  4217. const_iterator begin() const { return InitExprs.begin(); }
  4218. iterator end() { return InitExprs.end(); }
  4219. const_iterator end() const { return InitExprs.end(); }
  4220. reverse_iterator rbegin() { return InitExprs.rbegin(); }
  4221. const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
  4222. reverse_iterator rend() { return InitExprs.rend(); }
  4223. const_reverse_iterator rend() const { return InitExprs.rend(); }
  4224. friend class ASTStmtReader;
  4225. friend class ASTStmtWriter;
  4226. };
  4227. /// Represents a C99 designated initializer expression.
  4228. ///
  4229. /// A designated initializer expression (C99 6.7.8) contains one or
  4230. /// more designators (which can be field designators, array
  4231. /// designators, or GNU array-range designators) followed by an
  4232. /// expression that initializes the field or element(s) that the
  4233. /// designators refer to. For example, given:
  4234. ///
  4235. /// @code
  4236. /// struct point {
  4237. /// double x;
  4238. /// double y;
  4239. /// };
  4240. /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
  4241. /// @endcode
  4242. ///
  4243. /// The InitListExpr contains three DesignatedInitExprs, the first of
  4244. /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
  4245. /// designators, one array designator for @c [2] followed by one field
  4246. /// designator for @c .y. The initialization expression will be 1.0.
  4247. class DesignatedInitExpr final
  4248. : public Expr,
  4249. private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
  4250. public:
  4251. /// Forward declaration of the Designator class.
  4252. class Designator;
  4253. private:
  4254. /// The location of the '=' or ':' prior to the actual initializer
  4255. /// expression.
  4256. SourceLocation EqualOrColonLoc;
  4257. /// Whether this designated initializer used the GNU deprecated
  4258. /// syntax rather than the C99 '=' syntax.
  4259. unsigned GNUSyntax : 1;
  4260. /// The number of designators in this initializer expression.
  4261. unsigned NumDesignators : 15;
  4262. /// The number of subexpressions of this initializer expression,
  4263. /// which contains both the initializer and any additional
  4264. /// expressions used by array and array-range designators.
  4265. unsigned NumSubExprs : 16;
  4266. /// The designators in this designated initialization
  4267. /// expression.
  4268. Designator *Designators;
  4269. DesignatedInitExpr(const ASTContext &C, QualType Ty,
  4270. llvm::ArrayRef<Designator> Designators,
  4271. SourceLocation EqualOrColonLoc, bool GNUSyntax,
  4272. ArrayRef<Expr *> IndexExprs, Expr *Init);
  4273. explicit DesignatedInitExpr(unsigned NumSubExprs)
  4274. : Expr(DesignatedInitExprClass, EmptyShell()),
  4275. NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
  4276. public:
  4277. /// A field designator, e.g., ".x".
  4278. struct FieldDesignator {
  4279. /// Refers to the field that is being initialized. The low bit
  4280. /// of this field determines whether this is actually a pointer
  4281. /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
  4282. /// initially constructed, a field designator will store an
  4283. /// IdentifierInfo*. After semantic analysis has resolved that
  4284. /// name, the field designator will instead store a FieldDecl*.
  4285. uintptr_t NameOrField;
  4286. /// The location of the '.' in the designated initializer.
  4287. SourceLocation DotLoc;
  4288. /// The location of the field name in the designated initializer.
  4289. SourceLocation FieldLoc;
  4290. };
  4291. /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
  4292. struct ArrayOrRangeDesignator {
  4293. /// Location of the first index expression within the designated
  4294. /// initializer expression's list of subexpressions.
  4295. unsigned Index;
  4296. /// The location of the '[' starting the array range designator.
  4297. SourceLocation LBracketLoc;
  4298. /// The location of the ellipsis separating the start and end
  4299. /// indices. Only valid for GNU array-range designators.
  4300. SourceLocation EllipsisLoc;
  4301. /// The location of the ']' terminating the array range designator.
  4302. SourceLocation RBracketLoc;
  4303. };
  4304. /// Represents a single C99 designator.
  4305. ///
  4306. /// @todo This class is infuriatingly similar to clang::Designator,
  4307. /// but minor differences (storing indices vs. storing pointers)
  4308. /// keep us from reusing it. Try harder, later, to rectify these
  4309. /// differences.
  4310. class Designator {
  4311. /// The kind of designator this describes.
  4312. enum {
  4313. FieldDesignator,
  4314. ArrayDesignator,
  4315. ArrayRangeDesignator
  4316. } Kind;
  4317. union {
  4318. /// A field designator, e.g., ".x".
  4319. struct FieldDesignator Field;
  4320. /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
  4321. struct ArrayOrRangeDesignator ArrayOrRange;
  4322. };
  4323. friend class DesignatedInitExpr;
  4324. public:
  4325. Designator() {}
  4326. /// Initializes a field designator.
  4327. Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
  4328. SourceLocation FieldLoc)
  4329. : Kind(FieldDesignator) {
  4330. new (&Field) DesignatedInitExpr::FieldDesignator;
  4331. Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
  4332. Field.DotLoc = DotLoc;
  4333. Field.FieldLoc = FieldLoc;
  4334. }
  4335. /// Initializes an array designator.
  4336. Designator(unsigned Index, SourceLocation LBracketLoc,
  4337. SourceLocation RBracketLoc)
  4338. : Kind(ArrayDesignator) {
  4339. new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
  4340. ArrayOrRange.Index = Index;
  4341. ArrayOrRange.LBracketLoc = LBracketLoc;
  4342. ArrayOrRange.EllipsisLoc = SourceLocation();
  4343. ArrayOrRange.RBracketLoc = RBracketLoc;
  4344. }
  4345. /// Initializes a GNU array-range designator.
  4346. Designator(unsigned Index, SourceLocation LBracketLoc,
  4347. SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
  4348. : Kind(ArrayRangeDesignator) {
  4349. new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
  4350. ArrayOrRange.Index = Index;
  4351. ArrayOrRange.LBracketLoc = LBracketLoc;
  4352. ArrayOrRange.EllipsisLoc = EllipsisLoc;
  4353. ArrayOrRange.RBracketLoc = RBracketLoc;
  4354. }
  4355. bool isFieldDesignator() const { return Kind == FieldDesignator; }
  4356. bool isArrayDesignator() const { return Kind == ArrayDesignator; }
  4357. bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
  4358. IdentifierInfo *getFieldName() const;
  4359. FieldDecl *getField() const {
  4360. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4361. if (Field.NameOrField & 0x01)
  4362. return nullptr;
  4363. else
  4364. return reinterpret_cast<FieldDecl *>(Field.NameOrField);
  4365. }
  4366. void setField(FieldDecl *FD) {
  4367. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4368. Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
  4369. }
  4370. SourceLocation getDotLoc() const {
  4371. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4372. return Field.DotLoc;
  4373. }
  4374. SourceLocation getFieldLoc() const {
  4375. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4376. return Field.FieldLoc;
  4377. }
  4378. SourceLocation getLBracketLoc() const {
  4379. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4380. "Only valid on an array or array-range designator");
  4381. return ArrayOrRange.LBracketLoc;
  4382. }
  4383. SourceLocation getRBracketLoc() const {
  4384. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4385. "Only valid on an array or array-range designator");
  4386. return ArrayOrRange.RBracketLoc;
  4387. }
  4388. SourceLocation getEllipsisLoc() const {
  4389. assert(Kind == ArrayRangeDesignator &&
  4390. "Only valid on an array-range designator");
  4391. return ArrayOrRange.EllipsisLoc;
  4392. }
  4393. unsigned getFirstExprIndex() const {
  4394. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4395. "Only valid on an array or array-range designator");
  4396. return ArrayOrRange.Index;
  4397. }
  4398. SourceLocation getBeginLoc() const LLVM_READONLY {
  4399. if (Kind == FieldDesignator)
  4400. return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
  4401. else
  4402. return getLBracketLoc();
  4403. }
  4404. SourceLocation getEndLoc() const LLVM_READONLY {
  4405. return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
  4406. }
  4407. SourceRange getSourceRange() const LLVM_READONLY {
  4408. return SourceRange(getBeginLoc(), getEndLoc());
  4409. }
  4410. };
  4411. static DesignatedInitExpr *Create(const ASTContext &C,
  4412. llvm::ArrayRef<Designator> Designators,
  4413. ArrayRef<Expr*> IndexExprs,
  4414. SourceLocation EqualOrColonLoc,
  4415. bool GNUSyntax, Expr *Init);
  4416. static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
  4417. unsigned NumIndexExprs);
  4418. /// Returns the number of designators in this initializer.
  4419. unsigned size() const { return NumDesignators; }
  4420. // Iterator access to the designators.
  4421. llvm::MutableArrayRef<Designator> designators() {
  4422. return {Designators, NumDesignators};
  4423. }
  4424. llvm::ArrayRef<Designator> designators() const {
  4425. return {Designators, NumDesignators};
  4426. }
  4427. Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
  4428. const Designator *getDesignator(unsigned Idx) const {
  4429. return &designators()[Idx];
  4430. }
  4431. void setDesignators(const ASTContext &C, const Designator *Desigs,
  4432. unsigned NumDesigs);
  4433. Expr *getArrayIndex(const Designator &D) const;
  4434. Expr *getArrayRangeStart(const Designator &D) const;
  4435. Expr *getArrayRangeEnd(const Designator &D) const;
  4436. /// Retrieve the location of the '=' that precedes the
  4437. /// initializer value itself, if present.
  4438. SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
  4439. void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
  4440. /// Whether this designated initializer should result in direct-initialization
  4441. /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
  4442. bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
  4443. /// Determines whether this designated initializer used the
  4444. /// deprecated GNU syntax for designated initializers.
  4445. bool usesGNUSyntax() const { return GNUSyntax; }
  4446. void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
  4447. /// Retrieve the initializer value.
  4448. Expr *getInit() const {
  4449. return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
  4450. }
  4451. void setInit(Expr *init) {
  4452. *child_begin() = init;
  4453. }
  4454. /// Retrieve the total number of subexpressions in this
  4455. /// designated initializer expression, including the actual
  4456. /// initialized value and any expressions that occur within array
  4457. /// and array-range designators.
  4458. unsigned getNumSubExprs() const { return NumSubExprs; }
  4459. Expr *getSubExpr(unsigned Idx) const {
  4460. assert(Idx < NumSubExprs && "Subscript out of range");
  4461. return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
  4462. }
  4463. void setSubExpr(unsigned Idx, Expr *E) {
  4464. assert(Idx < NumSubExprs && "Subscript out of range");
  4465. getTrailingObjects<Stmt *>()[Idx] = E;
  4466. }
  4467. /// Replaces the designator at index @p Idx with the series
  4468. /// of designators in [First, Last).
  4469. void ExpandDesignator(const ASTContext &C, unsigned Idx,
  4470. const Designator *First, const Designator *Last);
  4471. SourceRange getDesignatorsSourceRange() const;
  4472. SourceLocation getBeginLoc() const LLVM_READONLY;
  4473. SourceLocation getEndLoc() const LLVM_READONLY;
  4474. static bool classof(const Stmt *T) {
  4475. return T->getStmtClass() == DesignatedInitExprClass;
  4476. }
  4477. // Iterators
  4478. child_range children() {
  4479. Stmt **begin = getTrailingObjects<Stmt *>();
  4480. return child_range(begin, begin + NumSubExprs);
  4481. }
  4482. const_child_range children() const {
  4483. Stmt * const *begin = getTrailingObjects<Stmt *>();
  4484. return const_child_range(begin, begin + NumSubExprs);
  4485. }
  4486. friend TrailingObjects;
  4487. };
  4488. /// Represents a place-holder for an object not to be initialized by
  4489. /// anything.
  4490. ///
  4491. /// This only makes sense when it appears as part of an updater of a
  4492. /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
  4493. /// initializes a big object, and the NoInitExpr's mark the spots within the
  4494. /// big object not to be overwritten by the updater.
  4495. ///
  4496. /// \see DesignatedInitUpdateExpr
  4497. class NoInitExpr : public Expr {
  4498. public:
  4499. explicit NoInitExpr(QualType ty)
  4500. : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
  4501. setDependence(computeDependence(this));
  4502. }
  4503. explicit NoInitExpr(EmptyShell Empty)
  4504. : Expr(NoInitExprClass, Empty) { }
  4505. static bool classof(const Stmt *T) {
  4506. return T->getStmtClass() == NoInitExprClass;
  4507. }
  4508. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4509. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4510. // Iterators
  4511. child_range children() {
  4512. return child_range(child_iterator(), child_iterator());
  4513. }
  4514. const_child_range children() const {
  4515. return const_child_range(const_child_iterator(), const_child_iterator());
  4516. }
  4517. };
  4518. // In cases like:
  4519. // struct Q { int a, b, c; };
  4520. // Q *getQ();
  4521. // void foo() {
  4522. // struct A { Q q; } a = { *getQ(), .q.b = 3 };
  4523. // }
  4524. //
  4525. // We will have an InitListExpr for a, with type A, and then a
  4526. // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
  4527. // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
  4528. //
  4529. class DesignatedInitUpdateExpr : public Expr {
  4530. // BaseAndUpdaterExprs[0] is the base expression;
  4531. // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
  4532. Stmt *BaseAndUpdaterExprs[2];
  4533. public:
  4534. DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
  4535. Expr *baseExprs, SourceLocation rBraceLoc);
  4536. explicit DesignatedInitUpdateExpr(EmptyShell Empty)
  4537. : Expr(DesignatedInitUpdateExprClass, Empty) { }
  4538. SourceLocation getBeginLoc() const LLVM_READONLY;
  4539. SourceLocation getEndLoc() const LLVM_READONLY;
  4540. static bool classof(const Stmt *T) {
  4541. return T->getStmtClass() == DesignatedInitUpdateExprClass;
  4542. }
  4543. Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
  4544. void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
  4545. InitListExpr *getUpdater() const {
  4546. return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
  4547. }
  4548. void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
  4549. // Iterators
  4550. // children = the base and the updater
  4551. child_range children() {
  4552. return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
  4553. }
  4554. const_child_range children() const {
  4555. return const_child_range(&BaseAndUpdaterExprs[0],
  4556. &BaseAndUpdaterExprs[0] + 2);
  4557. }
  4558. };
  4559. /// Represents a loop initializing the elements of an array.
  4560. ///
  4561. /// The need to initialize the elements of an array occurs in a number of
  4562. /// contexts:
  4563. ///
  4564. /// * in the implicit copy/move constructor for a class with an array member
  4565. /// * when a lambda-expression captures an array by value
  4566. /// * when a decomposition declaration decomposes an array
  4567. ///
  4568. /// There are two subexpressions: a common expression (the source array)
  4569. /// that is evaluated once up-front, and a per-element initializer that
  4570. /// runs once for each array element.
  4571. ///
  4572. /// Within the per-element initializer, the common expression may be referenced
  4573. /// via an OpaqueValueExpr, and the current index may be obtained via an
  4574. /// ArrayInitIndexExpr.
  4575. class ArrayInitLoopExpr : public Expr {
  4576. Stmt *SubExprs[2];
  4577. explicit ArrayInitLoopExpr(EmptyShell Empty)
  4578. : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
  4579. public:
  4580. explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
  4581. : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
  4582. SubExprs{CommonInit, ElementInit} {
  4583. setDependence(computeDependence(this));
  4584. }
  4585. /// Get the common subexpression shared by all initializations (the source
  4586. /// array).
  4587. OpaqueValueExpr *getCommonExpr() const {
  4588. return cast<OpaqueValueExpr>(SubExprs[0]);
  4589. }
  4590. /// Get the initializer to use for each array element.
  4591. Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
  4592. llvm::APInt getArraySize() const {
  4593. return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
  4594. ->getSize();
  4595. }
  4596. static bool classof(const Stmt *S) {
  4597. return S->getStmtClass() == ArrayInitLoopExprClass;
  4598. }
  4599. SourceLocation getBeginLoc() const LLVM_READONLY {
  4600. return getCommonExpr()->getBeginLoc();
  4601. }
  4602. SourceLocation getEndLoc() const LLVM_READONLY {
  4603. return getCommonExpr()->getEndLoc();
  4604. }
  4605. child_range children() {
  4606. return child_range(SubExprs, SubExprs + 2);
  4607. }
  4608. const_child_range children() const {
  4609. return const_child_range(SubExprs, SubExprs + 2);
  4610. }
  4611. friend class ASTReader;
  4612. friend class ASTStmtReader;
  4613. friend class ASTStmtWriter;
  4614. };
  4615. /// Represents the index of the current element of an array being
  4616. /// initialized by an ArrayInitLoopExpr. This can only appear within the
  4617. /// subexpression of an ArrayInitLoopExpr.
  4618. class ArrayInitIndexExpr : public Expr {
  4619. explicit ArrayInitIndexExpr(EmptyShell Empty)
  4620. : Expr(ArrayInitIndexExprClass, Empty) {}
  4621. public:
  4622. explicit ArrayInitIndexExpr(QualType T)
  4623. : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
  4624. setDependence(ExprDependence::None);
  4625. }
  4626. static bool classof(const Stmt *S) {
  4627. return S->getStmtClass() == ArrayInitIndexExprClass;
  4628. }
  4629. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4630. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4631. child_range children() {
  4632. return child_range(child_iterator(), child_iterator());
  4633. }
  4634. const_child_range children() const {
  4635. return const_child_range(const_child_iterator(), const_child_iterator());
  4636. }
  4637. friend class ASTReader;
  4638. friend class ASTStmtReader;
  4639. };
  4640. /// Represents an implicitly-generated value initialization of
  4641. /// an object of a given type.
  4642. ///
  4643. /// Implicit value initializations occur within semantic initializer
  4644. /// list expressions (InitListExpr) as placeholders for subobject
  4645. /// initializations not explicitly specified by the user.
  4646. ///
  4647. /// \see InitListExpr
  4648. class ImplicitValueInitExpr : public Expr {
  4649. public:
  4650. explicit ImplicitValueInitExpr(QualType ty)
  4651. : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
  4652. setDependence(computeDependence(this));
  4653. }
  4654. /// Construct an empty implicit value initialization.
  4655. explicit ImplicitValueInitExpr(EmptyShell Empty)
  4656. : Expr(ImplicitValueInitExprClass, Empty) { }
  4657. static bool classof(const Stmt *T) {
  4658. return T->getStmtClass() == ImplicitValueInitExprClass;
  4659. }
  4660. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4661. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4662. // Iterators
  4663. child_range children() {
  4664. return child_range(child_iterator(), child_iterator());
  4665. }
  4666. const_child_range children() const {
  4667. return const_child_range(const_child_iterator(), const_child_iterator());
  4668. }
  4669. };
  4670. class ParenListExpr final
  4671. : public Expr,
  4672. private llvm::TrailingObjects<ParenListExpr, Stmt *> {
  4673. friend class ASTStmtReader;
  4674. friend TrailingObjects;
  4675. /// The location of the left and right parentheses.
  4676. SourceLocation LParenLoc, RParenLoc;
  4677. /// Build a paren list.
  4678. ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
  4679. SourceLocation RParenLoc);
  4680. /// Build an empty paren list.
  4681. ParenListExpr(EmptyShell Empty, unsigned NumExprs);
  4682. public:
  4683. /// Create a paren list.
  4684. static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
  4685. ArrayRef<Expr *> Exprs,
  4686. SourceLocation RParenLoc);
  4687. /// Create an empty paren list.
  4688. static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
  4689. /// Return the number of expressions in this paren list.
  4690. unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
  4691. Expr *getExpr(unsigned Init) {
  4692. assert(Init < getNumExprs() && "Initializer access out of range!");
  4693. return getExprs()[Init];
  4694. }
  4695. const Expr *getExpr(unsigned Init) const {
  4696. return const_cast<ParenListExpr *>(this)->getExpr(Init);
  4697. }
  4698. Expr **getExprs() {
  4699. return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
  4700. }
  4701. ArrayRef<Expr *> exprs() { return llvm::ArrayRef(getExprs(), getNumExprs()); }
  4702. SourceLocation getLParenLoc() const { return LParenLoc; }
  4703. SourceLocation getRParenLoc() const { return RParenLoc; }
  4704. SourceLocation getBeginLoc() const { return getLParenLoc(); }
  4705. SourceLocation getEndLoc() const { return getRParenLoc(); }
  4706. static bool classof(const Stmt *T) {
  4707. return T->getStmtClass() == ParenListExprClass;
  4708. }
  4709. // Iterators
  4710. child_range children() {
  4711. return child_range(getTrailingObjects<Stmt *>(),
  4712. getTrailingObjects<Stmt *>() + getNumExprs());
  4713. }
  4714. const_child_range children() const {
  4715. return const_child_range(getTrailingObjects<Stmt *>(),
  4716. getTrailingObjects<Stmt *>() + getNumExprs());
  4717. }
  4718. };
  4719. /// Represents a C11 generic selection.
  4720. ///
  4721. /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
  4722. /// expression, followed by one or more generic associations. Each generic
  4723. /// association specifies a type name and an expression, or "default" and an
  4724. /// expression (in which case it is known as a default generic association).
  4725. /// The type and value of the generic selection are identical to those of its
  4726. /// result expression, which is defined as the expression in the generic
  4727. /// association with a type name that is compatible with the type of the
  4728. /// controlling expression, or the expression in the default generic association
  4729. /// if no types are compatible. For example:
  4730. ///
  4731. /// @code
  4732. /// _Generic(X, double: 1, float: 2, default: 3)
  4733. /// @endcode
  4734. ///
  4735. /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
  4736. /// or 3 if "hello".
  4737. ///
  4738. /// As an extension, generic selections are allowed in C++, where the following
  4739. /// additional semantics apply:
  4740. ///
  4741. /// Any generic selection whose controlling expression is type-dependent or
  4742. /// which names a dependent type in its association list is result-dependent,
  4743. /// which means that the choice of result expression is dependent.
  4744. /// Result-dependent generic associations are both type- and value-dependent.
  4745. class GenericSelectionExpr final
  4746. : public Expr,
  4747. private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
  4748. TypeSourceInfo *> {
  4749. friend class ASTStmtReader;
  4750. friend class ASTStmtWriter;
  4751. friend TrailingObjects;
  4752. /// The number of association expressions and the index of the result
  4753. /// expression in the case where the generic selection expression is not
  4754. /// result-dependent. The result index is equal to ResultDependentIndex
  4755. /// if and only if the generic selection expression is result-dependent.
  4756. unsigned NumAssocs, ResultIndex;
  4757. enum : unsigned {
  4758. ResultDependentIndex = std::numeric_limits<unsigned>::max(),
  4759. ControllingIndex = 0,
  4760. AssocExprStartIndex = 1
  4761. };
  4762. /// The location of the "default" and of the right parenthesis.
  4763. SourceLocation DefaultLoc, RParenLoc;
  4764. // GenericSelectionExpr is followed by several trailing objects.
  4765. // They are (in order):
  4766. //
  4767. // * A single Stmt * for the controlling expression.
  4768. // * An array of getNumAssocs() Stmt * for the association expressions.
  4769. // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
  4770. // association expressions.
  4771. unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
  4772. // Add one to account for the controlling expression; the remainder
  4773. // are the associated expressions.
  4774. return 1 + getNumAssocs();
  4775. }
  4776. unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
  4777. return getNumAssocs();
  4778. }
  4779. template <bool Const> class AssociationIteratorTy;
  4780. /// Bundle together an association expression and its TypeSourceInfo.
  4781. /// The Const template parameter is for the const and non-const versions
  4782. /// of AssociationTy.
  4783. template <bool Const> class AssociationTy {
  4784. friend class GenericSelectionExpr;
  4785. template <bool OtherConst> friend class AssociationIteratorTy;
  4786. using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
  4787. using TSIPtrTy =
  4788. std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
  4789. ExprPtrTy E;
  4790. TSIPtrTy TSI;
  4791. bool Selected;
  4792. AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
  4793. : E(E), TSI(TSI), Selected(Selected) {}
  4794. public:
  4795. ExprPtrTy getAssociationExpr() const { return E; }
  4796. TSIPtrTy getTypeSourceInfo() const { return TSI; }
  4797. QualType getType() const { return TSI ? TSI->getType() : QualType(); }
  4798. bool isSelected() const { return Selected; }
  4799. AssociationTy *operator->() { return this; }
  4800. const AssociationTy *operator->() const { return this; }
  4801. }; // class AssociationTy
  4802. /// Iterator over const and non-const Association objects. The Association
  4803. /// objects are created on the fly when the iterator is dereferenced.
  4804. /// This abstract over how exactly the association expressions and the
  4805. /// corresponding TypeSourceInfo * are stored.
  4806. template <bool Const>
  4807. class AssociationIteratorTy
  4808. : public llvm::iterator_facade_base<
  4809. AssociationIteratorTy<Const>, std::input_iterator_tag,
  4810. AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
  4811. AssociationTy<Const>> {
  4812. friend class GenericSelectionExpr;
  4813. // FIXME: This iterator could conceptually be a random access iterator, and
  4814. // it would be nice if we could strengthen the iterator category someday.
  4815. // However this iterator does not satisfy two requirements of forward
  4816. // iterators:
  4817. // a) reference = T& or reference = const T&
  4818. // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
  4819. // if *It1 and *It2 are bound to the same objects.
  4820. // An alternative design approach was discussed during review;
  4821. // store an Association object inside the iterator, and return a reference
  4822. // to it when dereferenced. This idea was discarded beacuse of nasty
  4823. // lifetime issues:
  4824. // AssociationIterator It = ...;
  4825. // const Association &Assoc = *It++; // Oops, Assoc is dangling.
  4826. using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
  4827. using StmtPtrPtrTy =
  4828. std::conditional_t<Const, const Stmt *const *, Stmt **>;
  4829. using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
  4830. TypeSourceInfo **>;
  4831. StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
  4832. TSIPtrPtrTy TSI; // Kept in sync with E.
  4833. unsigned Offset = 0, SelectedOffset = 0;
  4834. AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
  4835. unsigned SelectedOffset)
  4836. : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
  4837. public:
  4838. AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
  4839. typename BaseTy::reference operator*() const {
  4840. return AssociationTy<Const>(cast<Expr>(*E), *TSI,
  4841. Offset == SelectedOffset);
  4842. }
  4843. typename BaseTy::pointer operator->() const { return **this; }
  4844. using BaseTy::operator++;
  4845. AssociationIteratorTy &operator++() {
  4846. ++E;
  4847. ++TSI;
  4848. ++Offset;
  4849. return *this;
  4850. }
  4851. bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
  4852. }; // class AssociationIterator
  4853. /// Build a non-result-dependent generic selection expression.
  4854. GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
  4855. Expr *ControllingExpr,
  4856. ArrayRef<TypeSourceInfo *> AssocTypes,
  4857. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4858. SourceLocation RParenLoc,
  4859. bool ContainsUnexpandedParameterPack,
  4860. unsigned ResultIndex);
  4861. /// Build a result-dependent generic selection expression.
  4862. GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
  4863. Expr *ControllingExpr,
  4864. ArrayRef<TypeSourceInfo *> AssocTypes,
  4865. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4866. SourceLocation RParenLoc,
  4867. bool ContainsUnexpandedParameterPack);
  4868. /// Build an empty generic selection expression for deserialization.
  4869. explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
  4870. public:
  4871. /// Create a non-result-dependent generic selection expression.
  4872. static GenericSelectionExpr *
  4873. Create(const ASTContext &Context, SourceLocation GenericLoc,
  4874. Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
  4875. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4876. SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
  4877. unsigned ResultIndex);
  4878. /// Create a result-dependent generic selection expression.
  4879. static GenericSelectionExpr *
  4880. Create(const ASTContext &Context, SourceLocation GenericLoc,
  4881. Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
  4882. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4883. SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
  4884. /// Create an empty generic selection expression for deserialization.
  4885. static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
  4886. unsigned NumAssocs);
  4887. using Association = AssociationTy<false>;
  4888. using ConstAssociation = AssociationTy<true>;
  4889. using AssociationIterator = AssociationIteratorTy<false>;
  4890. using ConstAssociationIterator = AssociationIteratorTy<true>;
  4891. using association_range = llvm::iterator_range<AssociationIterator>;
  4892. using const_association_range =
  4893. llvm::iterator_range<ConstAssociationIterator>;
  4894. /// The number of association expressions.
  4895. unsigned getNumAssocs() const { return NumAssocs; }
  4896. /// The zero-based index of the result expression's generic association in
  4897. /// the generic selection's association list. Defined only if the
  4898. /// generic selection is not result-dependent.
  4899. unsigned getResultIndex() const {
  4900. assert(!isResultDependent() &&
  4901. "Generic selection is result-dependent but getResultIndex called!");
  4902. return ResultIndex;
  4903. }
  4904. /// Whether this generic selection is result-dependent.
  4905. bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
  4906. /// Return the controlling expression of this generic selection expression.
  4907. Expr *getControllingExpr() {
  4908. return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
  4909. }
  4910. const Expr *getControllingExpr() const {
  4911. return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
  4912. }
  4913. /// Return the result expression of this controlling expression. Defined if
  4914. /// and only if the generic selection expression is not result-dependent.
  4915. Expr *getResultExpr() {
  4916. return cast<Expr>(
  4917. getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
  4918. }
  4919. const Expr *getResultExpr() const {
  4920. return cast<Expr>(
  4921. getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
  4922. }
  4923. ArrayRef<Expr *> getAssocExprs() const {
  4924. return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
  4925. AssocExprStartIndex),
  4926. NumAssocs};
  4927. }
  4928. ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
  4929. return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
  4930. }
  4931. /// Return the Ith association expression with its TypeSourceInfo,
  4932. /// bundled together in GenericSelectionExpr::(Const)Association.
  4933. Association getAssociation(unsigned I) {
  4934. assert(I < getNumAssocs() &&
  4935. "Out-of-range index in GenericSelectionExpr::getAssociation!");
  4936. return Association(
  4937. cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
  4938. getTrailingObjects<TypeSourceInfo *>()[I],
  4939. !isResultDependent() && (getResultIndex() == I));
  4940. }
  4941. ConstAssociation getAssociation(unsigned I) const {
  4942. assert(I < getNumAssocs() &&
  4943. "Out-of-range index in GenericSelectionExpr::getAssociation!");
  4944. return ConstAssociation(
  4945. cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
  4946. getTrailingObjects<TypeSourceInfo *>()[I],
  4947. !isResultDependent() && (getResultIndex() == I));
  4948. }
  4949. association_range associations() {
  4950. AssociationIterator Begin(getTrailingObjects<Stmt *>() +
  4951. AssocExprStartIndex,
  4952. getTrailingObjects<TypeSourceInfo *>(),
  4953. /*Offset=*/0, ResultIndex);
  4954. AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
  4955. /*Offset=*/NumAssocs, ResultIndex);
  4956. return llvm::make_range(Begin, End);
  4957. }
  4958. const_association_range associations() const {
  4959. ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
  4960. AssocExprStartIndex,
  4961. getTrailingObjects<TypeSourceInfo *>(),
  4962. /*Offset=*/0, ResultIndex);
  4963. ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
  4964. /*Offset=*/NumAssocs, ResultIndex);
  4965. return llvm::make_range(Begin, End);
  4966. }
  4967. SourceLocation getGenericLoc() const {
  4968. return GenericSelectionExprBits.GenericLoc;
  4969. }
  4970. SourceLocation getDefaultLoc() const { return DefaultLoc; }
  4971. SourceLocation getRParenLoc() const { return RParenLoc; }
  4972. SourceLocation getBeginLoc() const { return getGenericLoc(); }
  4973. SourceLocation getEndLoc() const { return getRParenLoc(); }
  4974. static bool classof(const Stmt *T) {
  4975. return T->getStmtClass() == GenericSelectionExprClass;
  4976. }
  4977. child_range children() {
  4978. return child_range(getTrailingObjects<Stmt *>(),
  4979. getTrailingObjects<Stmt *>() +
  4980. numTrailingObjects(OverloadToken<Stmt *>()));
  4981. }
  4982. const_child_range children() const {
  4983. return const_child_range(getTrailingObjects<Stmt *>(),
  4984. getTrailingObjects<Stmt *>() +
  4985. numTrailingObjects(OverloadToken<Stmt *>()));
  4986. }
  4987. };
  4988. //===----------------------------------------------------------------------===//
  4989. // Clang Extensions
  4990. //===----------------------------------------------------------------------===//
  4991. /// ExtVectorElementExpr - This represents access to specific elements of a
  4992. /// vector, and may occur on the left hand side or right hand side. For example
  4993. /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
  4994. ///
  4995. /// Note that the base may have either vector or pointer to vector type, just
  4996. /// like a struct field reference.
  4997. ///
  4998. class ExtVectorElementExpr : public Expr {
  4999. Stmt *Base;
  5000. IdentifierInfo *Accessor;
  5001. SourceLocation AccessorLoc;
  5002. public:
  5003. ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
  5004. IdentifierInfo &accessor, SourceLocation loc)
  5005. : Expr(ExtVectorElementExprClass, ty, VK,
  5006. (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
  5007. Base(base), Accessor(&accessor), AccessorLoc(loc) {
  5008. setDependence(computeDependence(this));
  5009. }
  5010. /// Build an empty vector element expression.
  5011. explicit ExtVectorElementExpr(EmptyShell Empty)
  5012. : Expr(ExtVectorElementExprClass, Empty) { }
  5013. const Expr *getBase() const { return cast<Expr>(Base); }
  5014. Expr *getBase() { return cast<Expr>(Base); }
  5015. void setBase(Expr *E) { Base = E; }
  5016. IdentifierInfo &getAccessor() const { return *Accessor; }
  5017. void setAccessor(IdentifierInfo *II) { Accessor = II; }
  5018. SourceLocation getAccessorLoc() const { return AccessorLoc; }
  5019. void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
  5020. /// getNumElements - Get the number of components being selected.
  5021. unsigned getNumElements() const;
  5022. /// containsDuplicateElements - Return true if any element access is
  5023. /// repeated.
  5024. bool containsDuplicateElements() const;
  5025. /// getEncodedElementAccess - Encode the elements accessed into an llvm
  5026. /// aggregate Constant of ConstantInt(s).
  5027. void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
  5028. SourceLocation getBeginLoc() const LLVM_READONLY {
  5029. return getBase()->getBeginLoc();
  5030. }
  5031. SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
  5032. /// isArrow - Return true if the base expression is a pointer to vector,
  5033. /// return false if the base expression is a vector.
  5034. bool isArrow() const;
  5035. static bool classof(const Stmt *T) {
  5036. return T->getStmtClass() == ExtVectorElementExprClass;
  5037. }
  5038. // Iterators
  5039. child_range children() { return child_range(&Base, &Base+1); }
  5040. const_child_range children() const {
  5041. return const_child_range(&Base, &Base + 1);
  5042. }
  5043. };
  5044. /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
  5045. /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
  5046. class BlockExpr : public Expr {
  5047. protected:
  5048. BlockDecl *TheBlock;
  5049. public:
  5050. BlockExpr(BlockDecl *BD, QualType ty)
  5051. : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
  5052. setDependence(computeDependence(this));
  5053. }
  5054. /// Build an empty block expression.
  5055. explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
  5056. const BlockDecl *getBlockDecl() const { return TheBlock; }
  5057. BlockDecl *getBlockDecl() { return TheBlock; }
  5058. void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
  5059. // Convenience functions for probing the underlying BlockDecl.
  5060. SourceLocation getCaretLocation() const;
  5061. const Stmt *getBody() const;
  5062. Stmt *getBody();
  5063. SourceLocation getBeginLoc() const LLVM_READONLY {
  5064. return getCaretLocation();
  5065. }
  5066. SourceLocation getEndLoc() const LLVM_READONLY {
  5067. return getBody()->getEndLoc();
  5068. }
  5069. /// getFunctionType - Return the underlying function type for this block.
  5070. const FunctionProtoType *getFunctionType() const;
  5071. static bool classof(const Stmt *T) {
  5072. return T->getStmtClass() == BlockExprClass;
  5073. }
  5074. // Iterators
  5075. child_range children() {
  5076. return child_range(child_iterator(), child_iterator());
  5077. }
  5078. const_child_range children() const {
  5079. return const_child_range(const_child_iterator(), const_child_iterator());
  5080. }
  5081. };
  5082. /// Copy initialization expr of a __block variable and a boolean flag that
  5083. /// indicates whether the expression can throw.
  5084. struct BlockVarCopyInit {
  5085. BlockVarCopyInit() = default;
  5086. BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
  5087. : ExprAndFlag(CopyExpr, CanThrow) {}
  5088. void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
  5089. ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
  5090. }
  5091. Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
  5092. bool canThrow() const { return ExprAndFlag.getInt(); }
  5093. llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
  5094. };
  5095. /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
  5096. /// This AST node provides support for reinterpreting a type to another
  5097. /// type of the same size.
  5098. class AsTypeExpr : public Expr {
  5099. private:
  5100. Stmt *SrcExpr;
  5101. SourceLocation BuiltinLoc, RParenLoc;
  5102. friend class ASTReader;
  5103. friend class ASTStmtReader;
  5104. explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
  5105. public:
  5106. AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
  5107. ExprObjectKind OK, SourceLocation BuiltinLoc,
  5108. SourceLocation RParenLoc)
  5109. : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
  5110. BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
  5111. setDependence(computeDependence(this));
  5112. }
  5113. /// getSrcExpr - Return the Expr to be converted.
  5114. Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
  5115. /// getBuiltinLoc - Return the location of the __builtin_astype token.
  5116. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  5117. /// getRParenLoc - Return the location of final right parenthesis.
  5118. SourceLocation getRParenLoc() const { return RParenLoc; }
  5119. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  5120. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  5121. static bool classof(const Stmt *T) {
  5122. return T->getStmtClass() == AsTypeExprClass;
  5123. }
  5124. // Iterators
  5125. child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
  5126. const_child_range children() const {
  5127. return const_child_range(&SrcExpr, &SrcExpr + 1);
  5128. }
  5129. };
  5130. /// PseudoObjectExpr - An expression which accesses a pseudo-object
  5131. /// l-value. A pseudo-object is an abstract object, accesses to which
  5132. /// are translated to calls. The pseudo-object expression has a
  5133. /// syntactic form, which shows how the expression was actually
  5134. /// written in the source code, and a semantic form, which is a series
  5135. /// of expressions to be executed in order which detail how the
  5136. /// operation is actually evaluated. Optionally, one of the semantic
  5137. /// forms may also provide a result value for the expression.
  5138. ///
  5139. /// If any of the semantic-form expressions is an OpaqueValueExpr,
  5140. /// that OVE is required to have a source expression, and it is bound
  5141. /// to the result of that source expression. Such OVEs may appear
  5142. /// only in subsequent semantic-form expressions and as
  5143. /// sub-expressions of the syntactic form.
  5144. ///
  5145. /// PseudoObjectExpr should be used only when an operation can be
  5146. /// usefully described in terms of fairly simple rewrite rules on
  5147. /// objects and functions that are meant to be used by end-developers.
  5148. /// For example, under the Itanium ABI, dynamic casts are implemented
  5149. /// as a call to a runtime function called __dynamic_cast; using this
  5150. /// class to describe that would be inappropriate because that call is
  5151. /// not really part of the user-visible semantics, and instead the
  5152. /// cast is properly reflected in the AST and IR-generation has been
  5153. /// taught to generate the call as necessary. In contrast, an
  5154. /// Objective-C property access is semantically defined to be
  5155. /// equivalent to a particular message send, and this is very much
  5156. /// part of the user model. The name of this class encourages this
  5157. /// modelling design.
  5158. class PseudoObjectExpr final
  5159. : public Expr,
  5160. private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
  5161. // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
  5162. // Always at least two, because the first sub-expression is the
  5163. // syntactic form.
  5164. // PseudoObjectExprBits.ResultIndex - The index of the
  5165. // sub-expression holding the result. 0 means the result is void,
  5166. // which is unambiguous because it's the index of the syntactic
  5167. // form. Note that this is therefore 1 higher than the value passed
  5168. // in to Create, which is an index within the semantic forms.
  5169. // Note also that ASTStmtWriter assumes this encoding.
  5170. Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
  5171. const Expr * const *getSubExprsBuffer() const {
  5172. return getTrailingObjects<Expr *>();
  5173. }
  5174. PseudoObjectExpr(QualType type, ExprValueKind VK,
  5175. Expr *syntactic, ArrayRef<Expr*> semantic,
  5176. unsigned resultIndex);
  5177. PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
  5178. unsigned getNumSubExprs() const {
  5179. return PseudoObjectExprBits.NumSubExprs;
  5180. }
  5181. public:
  5182. /// NoResult - A value for the result index indicating that there is
  5183. /// no semantic result.
  5184. enum : unsigned { NoResult = ~0U };
  5185. static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
  5186. ArrayRef<Expr*> semantic,
  5187. unsigned resultIndex);
  5188. static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
  5189. unsigned numSemanticExprs);
  5190. /// Return the syntactic form of this expression, i.e. the
  5191. /// expression it actually looks like. Likely to be expressed in
  5192. /// terms of OpaqueValueExprs bound in the semantic form.
  5193. Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
  5194. const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
  5195. /// Return the index of the result-bearing expression into the semantics
  5196. /// expressions, or PseudoObjectExpr::NoResult if there is none.
  5197. unsigned getResultExprIndex() const {
  5198. if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
  5199. return PseudoObjectExprBits.ResultIndex - 1;
  5200. }
  5201. /// Return the result-bearing expression, or null if there is none.
  5202. Expr *getResultExpr() {
  5203. if (PseudoObjectExprBits.ResultIndex == 0)
  5204. return nullptr;
  5205. return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
  5206. }
  5207. const Expr *getResultExpr() const {
  5208. return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
  5209. }
  5210. unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
  5211. typedef Expr * const *semantics_iterator;
  5212. typedef const Expr * const *const_semantics_iterator;
  5213. semantics_iterator semantics_begin() {
  5214. return getSubExprsBuffer() + 1;
  5215. }
  5216. const_semantics_iterator semantics_begin() const {
  5217. return getSubExprsBuffer() + 1;
  5218. }
  5219. semantics_iterator semantics_end() {
  5220. return getSubExprsBuffer() + getNumSubExprs();
  5221. }
  5222. const_semantics_iterator semantics_end() const {
  5223. return getSubExprsBuffer() + getNumSubExprs();
  5224. }
  5225. llvm::iterator_range<semantics_iterator> semantics() {
  5226. return llvm::make_range(semantics_begin(), semantics_end());
  5227. }
  5228. llvm::iterator_range<const_semantics_iterator> semantics() const {
  5229. return llvm::make_range(semantics_begin(), semantics_end());
  5230. }
  5231. Expr *getSemanticExpr(unsigned index) {
  5232. assert(index + 1 < getNumSubExprs());
  5233. return getSubExprsBuffer()[index + 1];
  5234. }
  5235. const Expr *getSemanticExpr(unsigned index) const {
  5236. return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
  5237. }
  5238. SourceLocation getExprLoc() const LLVM_READONLY {
  5239. return getSyntacticForm()->getExprLoc();
  5240. }
  5241. SourceLocation getBeginLoc() const LLVM_READONLY {
  5242. return getSyntacticForm()->getBeginLoc();
  5243. }
  5244. SourceLocation getEndLoc() const LLVM_READONLY {
  5245. return getSyntacticForm()->getEndLoc();
  5246. }
  5247. child_range children() {
  5248. const_child_range CCR =
  5249. const_cast<const PseudoObjectExpr *>(this)->children();
  5250. return child_range(cast_away_const(CCR.begin()),
  5251. cast_away_const(CCR.end()));
  5252. }
  5253. const_child_range children() const {
  5254. Stmt *const *cs = const_cast<Stmt *const *>(
  5255. reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
  5256. return const_child_range(cs, cs + getNumSubExprs());
  5257. }
  5258. static bool classof(const Stmt *T) {
  5259. return T->getStmtClass() == PseudoObjectExprClass;
  5260. }
  5261. friend TrailingObjects;
  5262. friend class ASTStmtReader;
  5263. };
  5264. /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
  5265. /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
  5266. /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
  5267. /// and corresponding __opencl_atomic_* for OpenCL 2.0.
  5268. /// All of these instructions take one primary pointer, at least one memory
  5269. /// order. The instructions for which getScopeModel returns non-null value
  5270. /// take one synch scope.
  5271. class AtomicExpr : public Expr {
  5272. public:
  5273. enum AtomicOp {
  5274. #define BUILTIN(ID, TYPE, ATTRS)
  5275. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
  5276. #include "clang/Basic/Builtins.def"
  5277. // Avoid trailing comma
  5278. BI_First = 0
  5279. };
  5280. private:
  5281. /// Location of sub-expressions.
  5282. /// The location of Scope sub-expression is NumSubExprs - 1, which is
  5283. /// not fixed, therefore is not defined in enum.
  5284. enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
  5285. Stmt *SubExprs[END_EXPR + 1];
  5286. unsigned NumSubExprs;
  5287. SourceLocation BuiltinLoc, RParenLoc;
  5288. AtomicOp Op;
  5289. friend class ASTStmtReader;
  5290. public:
  5291. AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
  5292. AtomicOp op, SourceLocation RP);
  5293. /// Determine the number of arguments the specified atomic builtin
  5294. /// should have.
  5295. static unsigned getNumSubExprs(AtomicOp Op);
  5296. /// Build an empty AtomicExpr.
  5297. explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
  5298. Expr *getPtr() const {
  5299. return cast<Expr>(SubExprs[PTR]);
  5300. }
  5301. Expr *getOrder() const {
  5302. return cast<Expr>(SubExprs[ORDER]);
  5303. }
  5304. Expr *getScope() const {
  5305. assert(getScopeModel() && "No scope");
  5306. return cast<Expr>(SubExprs[NumSubExprs - 1]);
  5307. }
  5308. Expr *getVal1() const {
  5309. if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
  5310. return cast<Expr>(SubExprs[ORDER]);
  5311. assert(NumSubExprs > VAL1);
  5312. return cast<Expr>(SubExprs[VAL1]);
  5313. }
  5314. Expr *getOrderFail() const {
  5315. assert(NumSubExprs > ORDER_FAIL);
  5316. return cast<Expr>(SubExprs[ORDER_FAIL]);
  5317. }
  5318. Expr *getVal2() const {
  5319. if (Op == AO__atomic_exchange)
  5320. return cast<Expr>(SubExprs[ORDER_FAIL]);
  5321. assert(NumSubExprs > VAL2);
  5322. return cast<Expr>(SubExprs[VAL2]);
  5323. }
  5324. Expr *getWeak() const {
  5325. assert(NumSubExprs > WEAK);
  5326. return cast<Expr>(SubExprs[WEAK]);
  5327. }
  5328. QualType getValueType() const;
  5329. AtomicOp getOp() const { return Op; }
  5330. unsigned getNumSubExprs() const { return NumSubExprs; }
  5331. Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
  5332. const Expr * const *getSubExprs() const {
  5333. return reinterpret_cast<Expr * const *>(SubExprs);
  5334. }
  5335. bool isVolatile() const {
  5336. return getPtr()->getType()->getPointeeType().isVolatileQualified();
  5337. }
  5338. bool isCmpXChg() const {
  5339. return getOp() == AO__c11_atomic_compare_exchange_strong ||
  5340. getOp() == AO__c11_atomic_compare_exchange_weak ||
  5341. getOp() == AO__hip_atomic_compare_exchange_strong ||
  5342. getOp() == AO__opencl_atomic_compare_exchange_strong ||
  5343. getOp() == AO__opencl_atomic_compare_exchange_weak ||
  5344. getOp() == AO__hip_atomic_compare_exchange_weak ||
  5345. getOp() == AO__atomic_compare_exchange ||
  5346. getOp() == AO__atomic_compare_exchange_n;
  5347. }
  5348. bool isOpenCL() const {
  5349. return getOp() >= AO__opencl_atomic_init &&
  5350. getOp() <= AO__opencl_atomic_fetch_max;
  5351. }
  5352. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  5353. SourceLocation getRParenLoc() const { return RParenLoc; }
  5354. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  5355. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  5356. static bool classof(const Stmt *T) {
  5357. return T->getStmtClass() == AtomicExprClass;
  5358. }
  5359. // Iterators
  5360. child_range children() {
  5361. return child_range(SubExprs, SubExprs+NumSubExprs);
  5362. }
  5363. const_child_range children() const {
  5364. return const_child_range(SubExprs, SubExprs + NumSubExprs);
  5365. }
  5366. /// Get atomic scope model for the atomic op code.
  5367. /// \return empty atomic scope model if the atomic op code does not have
  5368. /// scope operand.
  5369. static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
  5370. auto Kind =
  5371. (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
  5372. ? AtomicScopeModelKind::OpenCL
  5373. : (Op >= AO__hip_atomic_load && Op <= AO__hip_atomic_fetch_max)
  5374. ? AtomicScopeModelKind::HIP
  5375. : AtomicScopeModelKind::None;
  5376. return AtomicScopeModel::create(Kind);
  5377. }
  5378. /// Get atomic scope model.
  5379. /// \return empty atomic scope model if this atomic expression does not have
  5380. /// scope operand.
  5381. std::unique_ptr<AtomicScopeModel> getScopeModel() const {
  5382. return getScopeModel(getOp());
  5383. }
  5384. };
  5385. /// TypoExpr - Internal placeholder for expressions where typo correction
  5386. /// still needs to be performed and/or an error diagnostic emitted.
  5387. class TypoExpr : public Expr {
  5388. // The location for the typo name.
  5389. SourceLocation TypoLoc;
  5390. public:
  5391. TypoExpr(QualType T, SourceLocation TypoLoc)
  5392. : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
  5393. assert(T->isDependentType() && "TypoExpr given a non-dependent type");
  5394. setDependence(ExprDependence::TypeValueInstantiation |
  5395. ExprDependence::Error);
  5396. }
  5397. child_range children() {
  5398. return child_range(child_iterator(), child_iterator());
  5399. }
  5400. const_child_range children() const {
  5401. return const_child_range(const_child_iterator(), const_child_iterator());
  5402. }
  5403. SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; }
  5404. SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; }
  5405. static bool classof(const Stmt *T) {
  5406. return T->getStmtClass() == TypoExprClass;
  5407. }
  5408. };
  5409. /// Frontend produces RecoveryExprs on semantic errors that prevent creating
  5410. /// other well-formed expressions. E.g. when type-checking of a binary operator
  5411. /// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
  5412. /// to produce a recovery expression storing left and right operands.
  5413. ///
  5414. /// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
  5415. /// preserve expressions in AST that would otherwise be dropped. It captures
  5416. /// subexpressions of some expression that we could not construct and source
  5417. /// range covered by the expression.
  5418. ///
  5419. /// By default, RecoveryExpr uses dependence-bits to take advantage of existing
  5420. /// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
  5421. /// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
  5422. /// addition to that, clang does not report most errors on dependent
  5423. /// expressions, so we get rid of bogus errors for free. However, note that
  5424. /// unlike other dependent expressions, RecoveryExpr can be produced in
  5425. /// non-template contexts.
  5426. ///
  5427. /// We will preserve the type in RecoveryExpr when the type is known, e.g.
  5428. /// preserving the return type for a broken non-overloaded function call, a
  5429. /// overloaded call where all candidates have the same return type. In this
  5430. /// case, the expression is not type-dependent (unless the known type is itself
  5431. /// dependent)
  5432. ///
  5433. /// One can also reliably suppress all bogus errors on expressions containing
  5434. /// recovery expressions by examining results of Expr::containsErrors().
  5435. class RecoveryExpr final : public Expr,
  5436. private llvm::TrailingObjects<RecoveryExpr, Expr *> {
  5437. public:
  5438. static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
  5439. SourceLocation BeginLoc, SourceLocation EndLoc,
  5440. ArrayRef<Expr *> SubExprs);
  5441. static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
  5442. ArrayRef<Expr *> subExpressions() {
  5443. auto *B = getTrailingObjects<Expr *>();
  5444. return llvm::ArrayRef(B, B + NumExprs);
  5445. }
  5446. ArrayRef<const Expr *> subExpressions() const {
  5447. return const_cast<RecoveryExpr *>(this)->subExpressions();
  5448. }
  5449. child_range children() {
  5450. Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
  5451. return child_range(B, B + NumExprs);
  5452. }
  5453. SourceLocation getBeginLoc() const { return BeginLoc; }
  5454. SourceLocation getEndLoc() const { return EndLoc; }
  5455. static bool classof(const Stmt *T) {
  5456. return T->getStmtClass() == RecoveryExprClass;
  5457. }
  5458. private:
  5459. RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
  5460. SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
  5461. RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
  5462. : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
  5463. size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
  5464. SourceLocation BeginLoc, EndLoc;
  5465. unsigned NumExprs;
  5466. friend TrailingObjects;
  5467. friend class ASTStmtReader;
  5468. friend class ASTStmtWriter;
  5469. };
  5470. } // end namespace clang
  5471. #endif // LLVM_CLANG_AST_EXPR_H
  5472. #ifdef __GNUC__
  5473. #pragma GCC diagnostic pop
  5474. #endif