ExprConstant.cpp 330 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr constant evaluator.
  11. //
  12. // Constant expression evaluation produces four main results:
  13. //
  14. // * A success/failure flag indicating whether constant folding was successful.
  15. // This is the 'bool' return value used by most of the code in this file. A
  16. // 'false' return value indicates that constant folding has failed, and any
  17. // appropriate diagnostic has already been produced.
  18. //
  19. // * An evaluated result, valid only if constant folding has not failed.
  20. //
  21. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  22. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  23. // where it is possible to determine the evaluated result regardless.
  24. //
  25. // * A set of notes indicating why the evaluation was not a constant expression
  26. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  27. // too, why the expression could not be folded.
  28. //
  29. // If we are checking for a potential constant expression, failure to constant
  30. // fold a potential constant sub-expression will be indicated by a 'false'
  31. // return value (the expression could not be folded) and no diagnostic (the
  32. // expression is not necessarily non-constant).
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "clang/AST/APValue.h"
  36. #include "clang/AST/ASTContext.h"
  37. #include "clang/AST/ASTDiagnostic.h"
  38. #include "clang/AST/CharUnits.h"
  39. #include "clang/AST/Expr.h"
  40. #include "clang/AST/RecordLayout.h"
  41. #include "clang/AST/StmtVisitor.h"
  42. #include "clang/AST/TypeLoc.h"
  43. #include "clang/Basic/Builtins.h"
  44. #include "clang/Basic/TargetInfo.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cstring>
  48. #include <functional>
  49. #include "llvm/Support/OacrIgnoreCond.h" // HLSL Change - constant evaluator is language-dependant
  50. #include "dxc/HlslIntrinsicOp.h" // HLSL Change
  51. using namespace clang;
  52. using llvm::APSInt;
  53. using llvm::APFloat;
  54. static bool IsGlobalLValue(APValue::LValueBase B);
  55. // HLSL Change Starts - reuse code from CallExpr::getBuiltinCallee
  56. static const FunctionDecl *GetCallExprFunction(const CallExpr *CE) {
  57. const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE->getCallee());
  58. if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
  59. return 0;
  60. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
  61. if (!DRE)
  62. return 0;
  63. const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
  64. if (!FDecl)
  65. return 0;
  66. if (!FDecl->getIdentifier())
  67. return 0;
  68. return FDecl;
  69. }
  70. // Returns true if the given InitListExpr is for constructing a HLSL vector
  71. // with the matching number of initializers and each initializer has the
  72. // matching element type.
  73. static bool IsHLSLVecInitList(const Expr* expr) {
  74. if (const auto* initExpr = dyn_cast<InitListExpr>(expr)) {
  75. const QualType vecType = initExpr->getType();
  76. if (!hlsl::IsHLSLVecType(vecType))
  77. return false;
  78. const uint32_t size = hlsl::GetHLSLVecSize(vecType);
  79. const QualType elemType = hlsl::GetHLSLVecElementType(vecType).getCanonicalType();
  80. if (initExpr->getNumInits() != size)
  81. return false;
  82. for (uint32_t i = 0; i < size; ++i)
  83. if (initExpr->getInit(i)->getType().getCanonicalType() != elemType)
  84. return false;
  85. return true;
  86. }
  87. return false;
  88. }
  89. // HLSL Change Ends
  90. namespace {
  91. struct LValue;
  92. struct CallStackFrame;
  93. struct EvalInfo;
  94. static QualType getType(APValue::LValueBase B) {
  95. if (!B) return QualType();
  96. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  97. return D->getType();
  98. const Expr *Base = B.get<const Expr*>();
  99. // For a materialized temporary, the type of the temporary we materialized
  100. // may not be the type of the expression.
  101. if (const MaterializeTemporaryExpr *MTE =
  102. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  103. SmallVector<const Expr *, 2> CommaLHSs;
  104. SmallVector<SubobjectAdjustment, 2> Adjustments;
  105. const Expr *Temp = MTE->GetTemporaryExpr();
  106. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  107. Adjustments);
  108. // Keep any cv-qualifiers from the reference if we generated a temporary
  109. // for it.
  110. if (Inner != Temp)
  111. return Inner->getType();
  112. }
  113. return Base->getType();
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// field or base class.
  117. static
  118. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  119. APValue::BaseOrMemberType Value;
  120. Value.setFromOpaqueValue(E.BaseOrMember);
  121. return Value;
  122. }
  123. /// Get an LValue path entry, which is known to not be an array index, as a
  124. /// field declaration.
  125. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  126. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  127. }
  128. /// Get an LValue path entry, which is known to not be an array index, as a
  129. /// base class declaration.
  130. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  131. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  132. }
  133. /// Determine whether this LValue path entry for a base class names a virtual
  134. /// base class.
  135. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  136. return getAsBaseOrMember(E).getInt();
  137. }
  138. /// Find the path length and type of the most-derived subobject in the given
  139. /// path, and find the size of the containing array, if any.
  140. static
  141. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  142. ArrayRef<APValue::LValuePathEntry> Path,
  143. uint64_t &ArraySize, QualType &Type) {
  144. unsigned MostDerivedLength = 0;
  145. Type = Base;
  146. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  147. if (Type->isArrayType()) {
  148. const ConstantArrayType *CAT =
  149. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  150. Type = CAT->getElementType();
  151. ArraySize = CAT->getSize().getZExtValue();
  152. MostDerivedLength = I + 1;
  153. } else if (Type->isAnyComplexType()) {
  154. const ComplexType *CT = Type->castAs<ComplexType>();
  155. Type = CT->getElementType();
  156. ArraySize = 2;
  157. MostDerivedLength = I + 1;
  158. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  159. Type = FD->getType();
  160. ArraySize = 0;
  161. MostDerivedLength = I + 1;
  162. } else {
  163. // Path[I] describes a base class.
  164. ArraySize = 0;
  165. }
  166. }
  167. return MostDerivedLength;
  168. }
  169. // The order of this enum is important for diagnostics.
  170. enum CheckSubobjectKind {
  171. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  172. CSK_This, CSK_Real, CSK_Imag
  173. };
  174. /// A path from a glvalue to a subobject of that glvalue.
  175. struct SubobjectDesignator {
  176. /// True if the subobject was named in a manner not supported by C++11. Such
  177. /// lvalues can still be folded, but they are not core constant expressions
  178. /// and we cannot perform lvalue-to-rvalue conversions on them.
  179. bool Invalid : 1;
  180. /// Is this a pointer one past the end of an object?
  181. bool IsOnePastTheEnd : 1;
  182. /// The length of the path to the most-derived object of which this is a
  183. /// subobject.
  184. unsigned MostDerivedPathLength : 30;
  185. /// The size of the array of which the most-derived object is an element, or
  186. /// 0 if the most-derived object is not an array element.
  187. uint64_t MostDerivedArraySize;
  188. /// The type of the most derived object referred to by this address.
  189. QualType MostDerivedType;
  190. typedef APValue::LValuePathEntry PathEntry;
  191. /// The entries on the path from the glvalue to the designated subobject.
  192. SmallVector<PathEntry, 8> Entries;
  193. SubobjectDesignator() : Invalid(true) {}
  194. explicit SubobjectDesignator(QualType T)
  195. : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
  196. MostDerivedArraySize(0), MostDerivedType(T) {}
  197. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  198. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  199. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  200. if (!Invalid) {
  201. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  202. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  203. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  204. if (V.getLValueBase())
  205. MostDerivedPathLength =
  206. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  207. V.getLValuePath(), MostDerivedArraySize,
  208. MostDerivedType);
  209. }
  210. }
  211. void setInvalid() {
  212. Invalid = true;
  213. Entries.clear();
  214. }
  215. /// Determine whether this is a one-past-the-end pointer.
  216. bool isOnePastTheEnd() const {
  217. assert(!Invalid);
  218. if (IsOnePastTheEnd)
  219. return true;
  220. if (MostDerivedArraySize &&
  221. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  222. return true;
  223. return false;
  224. }
  225. /// Check that this refers to a valid subobject.
  226. bool isValidSubobject() const {
  227. if (Invalid)
  228. return false;
  229. return !isOnePastTheEnd();
  230. }
  231. /// Check that this refers to a valid subobject, and if not, produce a
  232. /// relevant diagnostic and set the designator as invalid.
  233. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  234. /// Update this designator to refer to the first element within this array.
  235. void addArrayUnchecked(const ConstantArrayType *CAT) {
  236. PathEntry Entry;
  237. Entry.ArrayIndex = 0;
  238. Entries.push_back(Entry);
  239. // This is a most-derived object.
  240. MostDerivedType = CAT->getElementType();
  241. MostDerivedArraySize = CAT->getSize().getZExtValue();
  242. MostDerivedPathLength = Entries.size();
  243. }
  244. /// Update this designator to refer to the given base or member of this
  245. /// object.
  246. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  247. PathEntry Entry;
  248. APValue::BaseOrMemberType Value(D, Virtual);
  249. Entry.BaseOrMember = Value.getOpaqueValue();
  250. Entries.push_back(Entry);
  251. // If this isn't a base class, it's a new most-derived object.
  252. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  253. MostDerivedType = FD->getType();
  254. MostDerivedArraySize = 0;
  255. MostDerivedPathLength = Entries.size();
  256. }
  257. }
  258. /// Update this designator to refer to the given complex component.
  259. void addComplexUnchecked(QualType EltTy, bool Imag) {
  260. PathEntry Entry;
  261. Entry.ArrayIndex = Imag;
  262. Entries.push_back(Entry);
  263. // This is technically a most-derived object, though in practice this
  264. // is unlikely to matter.
  265. MostDerivedType = EltTy;
  266. MostDerivedArraySize = 2;
  267. MostDerivedPathLength = Entries.size();
  268. }
  269. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  270. /// Add N to the address of this subobject.
  271. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  272. if (Invalid) return;
  273. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
  274. Entries.back().ArrayIndex += N;
  275. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  276. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  277. setInvalid();
  278. }
  279. return;
  280. }
  281. // [expr.add]p4: For the purposes of these operators, a pointer to a
  282. // nonarray object behaves the same as a pointer to the first element of
  283. // an array of length one with the type of the object as its element type.
  284. if (IsOnePastTheEnd && N == (uint64_t)-1)
  285. IsOnePastTheEnd = false;
  286. else if (!IsOnePastTheEnd && N == 1)
  287. IsOnePastTheEnd = true;
  288. else if (N != 0) {
  289. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  290. setInvalid();
  291. }
  292. }
  293. };
  294. /// A stack frame in the constexpr call stack.
  295. struct CallStackFrame {
  296. EvalInfo &Info;
  297. /// Parent - The caller of this stack frame.
  298. CallStackFrame *Caller;
  299. /// CallLoc - The location of the call expression for this call.
  300. SourceLocation CallLoc;
  301. /// Callee - The function which was called.
  302. const FunctionDecl *Callee;
  303. /// Index - The call index of this call.
  304. unsigned Index;
  305. /// This - The binding for the this pointer in this call, if any.
  306. const LValue *This;
  307. /// Arguments - Parameter bindings for this function call, indexed by
  308. /// parameters' function scope indices.
  309. APValue *Arguments;
  310. // Note that we intentionally use std::map here so that references to
  311. // values are stable.
  312. typedef std::map<const void*, APValue> MapTy;
  313. typedef MapTy::const_iterator temp_iterator;
  314. /// Temporaries - Temporary lvalues materialized within this stack frame.
  315. MapTy Temporaries;
  316. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  317. const FunctionDecl *Callee, const LValue *This,
  318. APValue *Arguments);
  319. ~CallStackFrame();
  320. APValue *getTemporary(const void *Key) {
  321. MapTy::iterator I = Temporaries.find(Key);
  322. return I == Temporaries.end() ? nullptr : &I->second;
  323. }
  324. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  325. };
  326. /// Temporarily override 'this'.
  327. class ThisOverrideRAII {
  328. public:
  329. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  330. : Frame(Frame), OldThis(Frame.This) {
  331. if (Enable)
  332. Frame.This = NewThis;
  333. }
  334. ~ThisOverrideRAII() {
  335. Frame.This = OldThis;
  336. }
  337. private:
  338. CallStackFrame &Frame;
  339. const LValue *OldThis;
  340. };
  341. /// A partial diagnostic which we might know in advance that we are not going
  342. /// to emit.
  343. class OptionalDiagnostic {
  344. PartialDiagnostic *Diag;
  345. public:
  346. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  347. : Diag(Diag) {}
  348. template<typename T>
  349. OptionalDiagnostic &operator<<(const T &v) {
  350. if (Diag)
  351. *Diag << v;
  352. return *this;
  353. }
  354. OptionalDiagnostic &operator<<(const APSInt &I) {
  355. if (Diag) {
  356. SmallVector<char, 32> Buffer;
  357. I.toString(Buffer);
  358. *Diag << StringRef(Buffer.data(), Buffer.size());
  359. }
  360. return *this;
  361. }
  362. OptionalDiagnostic &operator<<(const APFloat &F) {
  363. if (Diag) {
  364. // FIXME: Force the precision of the source value down so we don't
  365. // print digits which are usually useless (we don't really care here if
  366. // we truncate a digit by accident in edge cases). Ideally,
  367. // APFloat::toString would automatically print the shortest
  368. // representation which rounds to the correct value, but it's a bit
  369. // tricky to implement.
  370. unsigned precision =
  371. llvm::APFloat::semanticsPrecision(F.getSemantics());
  372. precision = (precision * 59 + 195) / 196;
  373. SmallVector<char, 32> Buffer;
  374. F.toString(Buffer, precision);
  375. *Diag << StringRef(Buffer.data(), Buffer.size());
  376. }
  377. return *this;
  378. }
  379. };
  380. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  381. class Cleanup {
  382. llvm::PointerIntPair<APValue*, 1, bool> Value;
  383. public:
  384. Cleanup(APValue *Val, bool IsLifetimeExtended)
  385. : Value(Val, IsLifetimeExtended) {}
  386. bool isLifetimeExtended() const { return Value.getInt(); }
  387. void endLifetime() {
  388. *Value.getPointer() = APValue();
  389. }
  390. };
  391. /// EvalInfo - This is a private struct used by the evaluator to capture
  392. /// information about a subexpression as it is folded. It retains information
  393. /// about the AST context, but also maintains information about the folded
  394. /// expression.
  395. ///
  396. /// If an expression could be evaluated, it is still possible it is not a C
  397. /// "integer constant expression" or constant expression. If not, this struct
  398. /// captures information about how and why not.
  399. ///
  400. /// One bit of information passed *into* the request for constant folding
  401. /// indicates whether the subexpression is "evaluated" or not according to C
  402. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  403. /// evaluate the expression regardless of what the RHS is, but C only allows
  404. /// certain things in certain situations.
  405. struct EvalInfo {
  406. ASTContext &Ctx;
  407. /// EvalStatus - Contains information about the evaluation.
  408. Expr::EvalStatus &EvalStatus;
  409. /// CurrentCall - The top of the constexpr call stack.
  410. CallStackFrame *CurrentCall;
  411. /// CallStackDepth - The number of calls in the call stack right now.
  412. unsigned CallStackDepth;
  413. /// NextCallIndex - The next call index to assign.
  414. unsigned NextCallIndex;
  415. /// StepsLeft - The remaining number of evaluation steps we're permitted
  416. /// to perform. This is essentially a limit for the number of statements
  417. /// we will evaluate.
  418. unsigned StepsLeft;
  419. /// BottomFrame - The frame in which evaluation started. This must be
  420. /// initialized after CurrentCall and CallStackDepth.
  421. CallStackFrame BottomFrame;
  422. /// A stack of values whose lifetimes end at the end of some surrounding
  423. /// evaluation frame.
  424. llvm::SmallVector<Cleanup, 16> CleanupStack;
  425. /// EvaluatingDecl - This is the declaration whose initializer is being
  426. /// evaluated, if any.
  427. APValue::LValueBase EvaluatingDecl;
  428. /// EvaluatingDeclValue - This is the value being constructed for the
  429. /// declaration whose initializer is being evaluated, if any.
  430. APValue *EvaluatingDeclValue;
  431. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  432. /// notes attached to it will also be stored, otherwise they will not be.
  433. bool HasActiveDiagnostic;
  434. enum EvaluationMode {
  435. /// Evaluate as a constant expression. Stop if we find that the expression
  436. /// is not a constant expression.
  437. EM_ConstantExpression,
  438. /// Evaluate as a potential constant expression. Keep going if we hit a
  439. /// construct that we can't evaluate yet (because we don't yet know the
  440. /// value of something) but stop if we hit something that could never be
  441. /// a constant expression.
  442. EM_PotentialConstantExpression,
  443. /// Fold the expression to a constant. Stop if we hit a side-effect that
  444. /// we can't model.
  445. EM_ConstantFold,
  446. /// Evaluate the expression looking for integer overflow and similar
  447. /// issues. Don't worry about side-effects, and try to visit all
  448. /// subexpressions.
  449. EM_EvaluateForOverflow,
  450. /// Evaluate in any way we know how. Don't worry about side-effects that
  451. /// can't be modeled.
  452. EM_IgnoreSideEffects,
  453. /// Evaluate as a constant expression. Stop if we find that the expression
  454. /// is not a constant expression. Some expressions can be retried in the
  455. /// optimizer if we don't constant fold them here, but in an unevaluated
  456. /// context we try to fold them immediately since the optimizer never
  457. /// gets a chance to look at it.
  458. EM_ConstantExpressionUnevaluated,
  459. /// Evaluate as a potential constant expression. Keep going if we hit a
  460. /// construct that we can't evaluate yet (because we don't yet know the
  461. /// value of something) but stop if we hit something that could never be
  462. /// a constant expression. Some expressions can be retried in the
  463. /// optimizer if we don't constant fold them here, but in an unevaluated
  464. /// context we try to fold them immediately since the optimizer never
  465. /// gets a chance to look at it.
  466. EM_PotentialConstantExpressionUnevaluated
  467. } EvalMode;
  468. /// Are we checking whether the expression is a potential constant
  469. /// expression?
  470. bool checkingPotentialConstantExpression() const {
  471. return EvalMode == EM_PotentialConstantExpression ||
  472. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  473. }
  474. /// Are we checking an expression for overflow?
  475. // FIXME: We should check for any kind of undefined or suspicious behavior
  476. // in such constructs, not just overflow.
  477. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  478. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  479. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  480. CallStackDepth(0), NextCallIndex(1),
  481. StepsLeft(getLangOpts().ConstexprStepLimit),
  482. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  483. EvaluatingDecl((const ValueDecl *)nullptr),
  484. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  485. EvalMode(Mode) {}
  486. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  487. EvaluatingDecl = Base;
  488. EvaluatingDeclValue = &Value;
  489. }
  490. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  491. bool CheckCallLimit(SourceLocation Loc) {
  492. // Don't perform any constexpr calls (other than the call we're checking)
  493. // when checking a potential constant expression.
  494. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  495. return false;
  496. if (NextCallIndex == 0) {
  497. // NextCallIndex has wrapped around.
  498. Diag(Loc, diag::note_constexpr_call_limit_exceeded);
  499. return false;
  500. }
  501. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  502. return true;
  503. Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
  504. << getLangOpts().ConstexprCallDepth;
  505. return false;
  506. }
  507. CallStackFrame *getCallFrame(unsigned CallIndex) {
  508. assert(CallIndex && "no call index in getCallFrame");
  509. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  510. // be null in this loop.
  511. CallStackFrame *Frame = CurrentCall;
  512. while (Frame->Index > CallIndex)
  513. Frame = Frame->Caller;
  514. return (Frame->Index == CallIndex) ? Frame : nullptr;
  515. }
  516. bool nextStep(const Stmt *S) {
  517. if (!StepsLeft) {
  518. Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
  519. return false;
  520. }
  521. --StepsLeft;
  522. return true;
  523. }
  524. private:
  525. /// Add a diagnostic to the diagnostics list.
  526. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  527. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  528. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  529. return EvalStatus.Diag->back().second;
  530. }
  531. /// Add notes containing a call stack to the current point of evaluation.
  532. void addCallStack(unsigned Limit);
  533. public:
  534. /// Diagnose that the evaluation cannot be folded.
  535. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
  536. = diag::note_invalid_subexpr_in_const_expr,
  537. unsigned ExtraNotes = 0) {
  538. if (EvalStatus.Diag) {
  539. // If we have a prior diagnostic, it will be noting that the expression
  540. // isn't a constant expression. This diagnostic is more important,
  541. // unless we require this evaluation to produce a constant expression.
  542. //
  543. // FIXME: We might want to show both diagnostics to the user in
  544. // EM_ConstantFold mode.
  545. if (!EvalStatus.Diag->empty()) {
  546. switch (EvalMode) {
  547. case EM_ConstantFold:
  548. case EM_IgnoreSideEffects:
  549. case EM_EvaluateForOverflow:
  550. if (!EvalStatus.HasSideEffects)
  551. break;
  552. // We've had side-effects; we want the diagnostic from them, not
  553. // some later problem.
  554. case EM_ConstantExpression:
  555. case EM_PotentialConstantExpression:
  556. case EM_ConstantExpressionUnevaluated:
  557. case EM_PotentialConstantExpressionUnevaluated:
  558. HasActiveDiagnostic = false;
  559. return OptionalDiagnostic();
  560. }
  561. }
  562. unsigned CallStackNotes = CallStackDepth - 1;
  563. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  564. if (Limit)
  565. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  566. if (checkingPotentialConstantExpression())
  567. CallStackNotes = 0;
  568. HasActiveDiagnostic = true;
  569. EvalStatus.Diag->clear();
  570. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  571. addDiag(Loc, DiagId);
  572. if (!checkingPotentialConstantExpression())
  573. addCallStack(Limit);
  574. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  575. }
  576. HasActiveDiagnostic = false;
  577. return OptionalDiagnostic();
  578. }
  579. OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
  580. = diag::note_invalid_subexpr_in_const_expr,
  581. unsigned ExtraNotes = 0) {
  582. if (EvalStatus.Diag)
  583. return Diag(E->getExprLoc(), DiagId, ExtraNotes);
  584. HasActiveDiagnostic = false;
  585. return OptionalDiagnostic();
  586. }
  587. /// Diagnose that the evaluation does not produce a C++11 core constant
  588. /// expression.
  589. ///
  590. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  591. /// EM_PotentialConstantExpression mode and we produce one of these.
  592. template<typename LocArg>
  593. OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
  594. = diag::note_invalid_subexpr_in_const_expr,
  595. unsigned ExtraNotes = 0) {
  596. // Don't override a previous diagnostic. Don't bother collecting
  597. // diagnostics if we're evaluating for overflow.
  598. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  599. HasActiveDiagnostic = false;
  600. return OptionalDiagnostic();
  601. }
  602. return Diag(Loc, DiagId, ExtraNotes);
  603. }
  604. /// Add a note to a prior diagnostic.
  605. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  606. if (!HasActiveDiagnostic)
  607. return OptionalDiagnostic();
  608. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  609. }
  610. /// Add a stack of notes to a prior diagnostic.
  611. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  612. if (HasActiveDiagnostic) {
  613. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  614. Diags.begin(), Diags.end());
  615. }
  616. }
  617. /// Should we continue evaluation after encountering a side-effect that we
  618. /// couldn't model?
  619. bool keepEvaluatingAfterSideEffect() {
  620. switch (EvalMode) {
  621. case EM_PotentialConstantExpression:
  622. case EM_PotentialConstantExpressionUnevaluated:
  623. case EM_EvaluateForOverflow:
  624. case EM_IgnoreSideEffects:
  625. return true;
  626. case EM_ConstantExpression:
  627. case EM_ConstantExpressionUnevaluated:
  628. case EM_ConstantFold:
  629. return false;
  630. }
  631. llvm_unreachable("Missed EvalMode case");
  632. }
  633. /// Note that we have had a side-effect, and determine whether we should
  634. /// keep evaluating.
  635. bool noteSideEffect() {
  636. EvalStatus.HasSideEffects = true;
  637. return keepEvaluatingAfterSideEffect();
  638. }
  639. /// Should we continue evaluation as much as possible after encountering a
  640. /// construct which can't be reduced to a value?
  641. bool keepEvaluatingAfterFailure() {
  642. if (!StepsLeft)
  643. return false;
  644. switch (EvalMode) {
  645. case EM_PotentialConstantExpression:
  646. case EM_PotentialConstantExpressionUnevaluated:
  647. case EM_EvaluateForOverflow:
  648. return true;
  649. case EM_ConstantExpression:
  650. case EM_ConstantExpressionUnevaluated:
  651. case EM_ConstantFold:
  652. case EM_IgnoreSideEffects:
  653. return false;
  654. }
  655. llvm_unreachable("Missed EvalMode case");
  656. }
  657. };
  658. /// Object used to treat all foldable expressions as constant expressions.
  659. struct FoldConstant {
  660. EvalInfo &Info;
  661. bool Enabled;
  662. bool HadNoPriorDiags;
  663. EvalInfo::EvaluationMode OldMode;
  664. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  665. : Info(Info),
  666. Enabled(Enabled),
  667. HadNoPriorDiags(Info.EvalStatus.Diag &&
  668. Info.EvalStatus.Diag->empty() &&
  669. !Info.EvalStatus.HasSideEffects),
  670. OldMode(Info.EvalMode) {
  671. if (Enabled &&
  672. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  673. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  674. Info.EvalMode = EvalInfo::EM_ConstantFold;
  675. }
  676. void keepDiagnostics() { Enabled = false; }
  677. ~FoldConstant() {
  678. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  679. !Info.EvalStatus.HasSideEffects)
  680. Info.EvalStatus.Diag->clear();
  681. Info.EvalMode = OldMode;
  682. }
  683. };
  684. /// RAII object used to suppress diagnostics and side-effects from a
  685. /// speculative evaluation.
  686. class SpeculativeEvaluationRAII {
  687. EvalInfo &Info;
  688. Expr::EvalStatus Old;
  689. public:
  690. SpeculativeEvaluationRAII(EvalInfo &Info,
  691. SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  692. : Info(Info), Old(Info.EvalStatus) {
  693. Info.EvalStatus.Diag = NewDiag;
  694. // If we're speculatively evaluating, we may have skipped over some
  695. // evaluations and missed out a side effect.
  696. Info.EvalStatus.HasSideEffects = true;
  697. }
  698. ~SpeculativeEvaluationRAII() {
  699. Info.EvalStatus = Old;
  700. }
  701. };
  702. /// RAII object wrapping a full-expression or block scope, and handling
  703. /// the ending of the lifetime of temporaries created within it.
  704. template<bool IsFullExpression>
  705. class ScopeRAII {
  706. EvalInfo &Info;
  707. unsigned OldStackSize;
  708. public:
  709. ScopeRAII(EvalInfo &Info)
  710. : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
  711. ~ScopeRAII() {
  712. // Body moved to a static method to encourage the compiler to inline away
  713. // instances of this class.
  714. cleanup(Info, OldStackSize);
  715. }
  716. private:
  717. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  718. unsigned NewEnd = OldStackSize;
  719. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  720. I != N; ++I) {
  721. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  722. // Full-expression cleanup of a lifetime-extended temporary: nothing
  723. // to do, just move this cleanup to the right place in the stack.
  724. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  725. ++NewEnd;
  726. } else {
  727. // End the lifetime of the object.
  728. Info.CleanupStack[I].endLifetime();
  729. }
  730. }
  731. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  732. Info.CleanupStack.end());
  733. }
  734. };
  735. typedef ScopeRAII<false> BlockScopeRAII;
  736. typedef ScopeRAII<true> FullExpressionRAII;
  737. }
  738. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  739. CheckSubobjectKind CSK) {
  740. if (Invalid)
  741. return false;
  742. if (isOnePastTheEnd()) {
  743. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  744. << CSK;
  745. setInvalid();
  746. return false;
  747. }
  748. return true;
  749. }
  750. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  751. const Expr *E, uint64_t N) {
  752. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
  753. Info.CCEDiag(E, diag::note_constexpr_array_index)
  754. << static_cast<int>(N) << /*array*/ 0
  755. << static_cast<unsigned>(MostDerivedArraySize);
  756. else
  757. Info.CCEDiag(E, diag::note_constexpr_array_index)
  758. << static_cast<int>(N) << /*non-array*/ 1;
  759. setInvalid();
  760. }
  761. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  762. const FunctionDecl *Callee, const LValue *This,
  763. APValue *Arguments)
  764. : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
  765. Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
  766. Info.CurrentCall = this;
  767. ++Info.CallStackDepth;
  768. }
  769. CallStackFrame::~CallStackFrame() {
  770. assert(Info.CurrentCall == this && "calls retired out of order");
  771. --Info.CallStackDepth;
  772. Info.CurrentCall = Caller;
  773. }
  774. APValue &CallStackFrame::createTemporary(const void *Key,
  775. bool IsLifetimeExtended) {
  776. APValue &Result = Temporaries[Key];
  777. assert(Result.isUninit() && "temporary created multiple times");
  778. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  779. return Result;
  780. }
  781. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  782. void EvalInfo::addCallStack(unsigned Limit) {
  783. // Determine which calls to skip, if any.
  784. unsigned ActiveCalls = CallStackDepth - 1;
  785. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  786. if (Limit && Limit < ActiveCalls) {
  787. SkipStart = Limit / 2 + Limit % 2;
  788. SkipEnd = ActiveCalls - Limit / 2;
  789. }
  790. // Walk the call stack and add the diagnostics.
  791. unsigned CallIdx = 0;
  792. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  793. Frame = Frame->Caller, ++CallIdx) {
  794. // Skip this call?
  795. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  796. if (CallIdx == SkipStart) {
  797. // Note that we're skipping calls.
  798. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  799. << unsigned(ActiveCalls - Limit);
  800. }
  801. continue;
  802. }
  803. SmallVector<char, 128> Buffer;
  804. llvm::raw_svector_ostream Out(Buffer);
  805. describeCall(Frame, Out);
  806. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  807. }
  808. }
  809. namespace {
  810. struct ComplexValue {
  811. private:
  812. bool IsInt;
  813. public:
  814. APSInt IntReal, IntImag;
  815. APFloat FloatReal, FloatImag;
  816. ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
  817. void makeComplexFloat() { IsInt = false; }
  818. bool isComplexFloat() const { return !IsInt; }
  819. APFloat &getComplexFloatReal() { return FloatReal; }
  820. APFloat &getComplexFloatImag() { return FloatImag; }
  821. void makeComplexInt() { IsInt = true; }
  822. bool isComplexInt() const { return IsInt; }
  823. APSInt &getComplexIntReal() { return IntReal; }
  824. APSInt &getComplexIntImag() { return IntImag; }
  825. void moveInto(APValue &v) const {
  826. if (isComplexFloat())
  827. v = APValue(FloatReal, FloatImag);
  828. else
  829. v = APValue(IntReal, IntImag);
  830. }
  831. void setFrom(const APValue &v) {
  832. assert(v.isComplexFloat() || v.isComplexInt());
  833. if (v.isComplexFloat()) {
  834. makeComplexFloat();
  835. FloatReal = v.getComplexFloatReal();
  836. FloatImag = v.getComplexFloatImag();
  837. } else {
  838. makeComplexInt();
  839. IntReal = v.getComplexIntReal();
  840. IntImag = v.getComplexIntImag();
  841. }
  842. }
  843. };
  844. struct LValue {
  845. APValue::LValueBase Base;
  846. CharUnits Offset;
  847. unsigned CallIndex;
  848. SubobjectDesignator Designator;
  849. const APValue::LValueBase getLValueBase() const { return Base; }
  850. CharUnits &getLValueOffset() { return Offset; }
  851. const CharUnits &getLValueOffset() const { return Offset; }
  852. unsigned getLValueCallIndex() const { return CallIndex; }
  853. SubobjectDesignator &getLValueDesignator() { return Designator; }
  854. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  855. void moveInto(APValue &V) const {
  856. if (Designator.Invalid)
  857. V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
  858. else
  859. V = APValue(Base, Offset, Designator.Entries,
  860. Designator.IsOnePastTheEnd, CallIndex);
  861. }
  862. void setFrom(ASTContext &Ctx, const APValue &V) {
  863. assert(V.isLValue());
  864. Base = V.getLValueBase();
  865. Offset = V.getLValueOffset();
  866. CallIndex = V.getLValueCallIndex();
  867. Designator = SubobjectDesignator(Ctx, V);
  868. }
  869. void set(APValue::LValueBase B, unsigned I = 0) {
  870. Base = B;
  871. Offset = CharUnits::Zero();
  872. CallIndex = I;
  873. Designator = SubobjectDesignator(getType(B));
  874. }
  875. // Check that this LValue is not based on a null pointer. If it is, produce
  876. // a diagnostic and mark the designator as invalid.
  877. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  878. CheckSubobjectKind CSK) {
  879. if (Designator.Invalid)
  880. return false;
  881. if (!Base) {
  882. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  883. << CSK;
  884. Designator.setInvalid();
  885. return false;
  886. }
  887. return true;
  888. }
  889. // Check this LValue refers to an object. If not, set the designator to be
  890. // invalid and emit a diagnostic.
  891. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  892. // Outside C++11, do not build a designator referring to a subobject of
  893. // any object: we won't use such a designator for anything.
  894. if (!Info.getLangOpts().CPlusPlus11)
  895. Designator.setInvalid();
  896. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  897. Designator.checkSubobject(Info, E, CSK);
  898. }
  899. void addDecl(EvalInfo &Info, const Expr *E,
  900. const Decl *D, bool Virtual = false) {
  901. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  902. Designator.addDeclUnchecked(D, Virtual);
  903. }
  904. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  905. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  906. Designator.addArrayUnchecked(CAT);
  907. }
  908. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  909. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  910. Designator.addComplexUnchecked(EltTy, Imag);
  911. }
  912. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  913. if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
  914. Designator.adjustIndex(Info, E, N);
  915. }
  916. };
  917. struct MemberPtr {
  918. MemberPtr() {}
  919. explicit MemberPtr(const ValueDecl *Decl) :
  920. DeclAndIsDerivedMember(Decl, false), Path() {}
  921. /// The member or (direct or indirect) field referred to by this member
  922. /// pointer, or 0 if this is a null member pointer.
  923. const ValueDecl *getDecl() const {
  924. return DeclAndIsDerivedMember.getPointer();
  925. }
  926. /// Is this actually a member of some type derived from the relevant class?
  927. bool isDerivedMember() const {
  928. return DeclAndIsDerivedMember.getInt();
  929. }
  930. /// Get the class which the declaration actually lives in.
  931. const CXXRecordDecl *getContainingRecord() const {
  932. return cast<CXXRecordDecl>(
  933. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  934. }
  935. void moveInto(APValue &V) const {
  936. V = APValue(getDecl(), isDerivedMember(), Path);
  937. }
  938. void setFrom(const APValue &V) {
  939. assert(V.isMemberPointer());
  940. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  941. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  942. Path.clear();
  943. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  944. Path.insert(Path.end(), P.begin(), P.end());
  945. }
  946. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  947. /// whether the member is a member of some class derived from the class type
  948. /// of the member pointer.
  949. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  950. /// Path - The path of base/derived classes from the member declaration's
  951. /// class (exclusive) to the class type of the member pointer (inclusive).
  952. SmallVector<const CXXRecordDecl*, 4> Path;
  953. /// Perform a cast towards the class of the Decl (either up or down the
  954. /// hierarchy).
  955. bool castBack(const CXXRecordDecl *Class) {
  956. assert(!Path.empty());
  957. const CXXRecordDecl *Expected;
  958. if (Path.size() >= 2)
  959. Expected = Path[Path.size() - 2];
  960. else
  961. Expected = getContainingRecord();
  962. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  963. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  964. // if B does not contain the original member and is not a base or
  965. // derived class of the class containing the original member, the result
  966. // of the cast is undefined.
  967. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  968. // (D::*). We consider that to be a language defect.
  969. return false;
  970. }
  971. Path.pop_back();
  972. return true;
  973. }
  974. /// Perform a base-to-derived member pointer cast.
  975. bool castToDerived(const CXXRecordDecl *Derived) {
  976. if (!getDecl())
  977. return true;
  978. if (!isDerivedMember()) {
  979. Path.push_back(Derived);
  980. return true;
  981. }
  982. if (!castBack(Derived))
  983. return false;
  984. if (Path.empty())
  985. DeclAndIsDerivedMember.setInt(false);
  986. return true;
  987. }
  988. /// Perform a derived-to-base member pointer cast.
  989. bool castToBase(const CXXRecordDecl *Base) {
  990. if (!getDecl())
  991. return true;
  992. if (Path.empty())
  993. DeclAndIsDerivedMember.setInt(true);
  994. if (isDerivedMember()) {
  995. Path.push_back(Base);
  996. return true;
  997. }
  998. return castBack(Base);
  999. }
  1000. };
  1001. /// Compare two member pointers, which are assumed to be of the same type.
  1002. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1003. if (!LHS.getDecl() || !RHS.getDecl())
  1004. return !LHS.getDecl() && !RHS.getDecl();
  1005. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1006. return false;
  1007. return LHS.Path == RHS.Path;
  1008. }
  1009. }
  1010. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1011. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1012. const LValue &This, const Expr *E,
  1013. bool AllowNonLiteralTypes = false);
  1014. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  1015. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  1016. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1017. EvalInfo &Info);
  1018. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1019. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1020. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1021. EvalInfo &Info);
  1022. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1023. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1024. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
  1025. //===----------------------------------------------------------------------===//
  1026. // Misc utilities
  1027. //===----------------------------------------------------------------------===//
  1028. /// Produce a string describing the given constexpr call.
  1029. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1030. unsigned ArgIndex = 0;
  1031. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1032. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1033. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1034. if (!IsMemberCall)
  1035. Out << *Frame->Callee << '(';
  1036. if (Frame->This && IsMemberCall) {
  1037. APValue Val;
  1038. Frame->This->moveInto(Val);
  1039. Val.printPretty(Out, Frame->Info.Ctx,
  1040. Frame->This->Designator.MostDerivedType);
  1041. // FIXME: Add parens around Val if needed.
  1042. Out << "->" << *Frame->Callee << '(';
  1043. IsMemberCall = false;
  1044. }
  1045. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1046. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1047. if (ArgIndex > (unsigned)IsMemberCall)
  1048. Out << ", ";
  1049. const ParmVarDecl *Param = *I;
  1050. const APValue &Arg = Frame->Arguments[ArgIndex];
  1051. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1052. if (ArgIndex == 0 && IsMemberCall)
  1053. Out << "->" << *Frame->Callee << '(';
  1054. }
  1055. Out << ')';
  1056. }
  1057. /// Evaluate an expression to see if it had side-effects, and discard its
  1058. /// result.
  1059. /// \return \c true if the caller should keep evaluating.
  1060. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1061. APValue Scratch;
  1062. if (!Evaluate(Scratch, Info, E))
  1063. // We don't need the value, but we might have skipped a side effect here.
  1064. return Info.noteSideEffect();
  1065. return true;
  1066. }
  1067. /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
  1068. /// return its existing value.
  1069. static int64_t getExtValue(const APSInt &Value) {
  1070. return Value.isSigned() ? Value.getSExtValue()
  1071. : static_cast<int64_t>(Value.getZExtValue());
  1072. }
  1073. /// Should this call expression be treated as a string literal?
  1074. static bool IsStringLiteralCall(const CallExpr *E) {
  1075. unsigned Builtin = E->getBuiltinCallee();
  1076. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1077. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1078. }
  1079. static bool IsGlobalLValue(APValue::LValueBase B) {
  1080. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1081. // constant expression of pointer type that evaluates to...
  1082. // ... a null pointer value, or a prvalue core constant expression of type
  1083. // std::nullptr_t.
  1084. if (!B) return true;
  1085. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1086. // ... the address of an object with static storage duration,
  1087. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1088. return VD->hasGlobalStorage();
  1089. // ... the address of a function,
  1090. return isa<FunctionDecl>(D);
  1091. }
  1092. const Expr *E = B.get<const Expr*>();
  1093. switch (E->getStmtClass()) {
  1094. default:
  1095. return false;
  1096. case Expr::CompoundLiteralExprClass: {
  1097. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1098. return CLE->isFileScope() && CLE->isLValue();
  1099. }
  1100. case Expr::MaterializeTemporaryExprClass:
  1101. // A materialized temporary might have been lifetime-extended to static
  1102. // storage duration.
  1103. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1104. // A string literal has static storage duration.
  1105. case Expr::StringLiteralClass:
  1106. case Expr::PredefinedExprClass:
  1107. case Expr::ObjCStringLiteralClass:
  1108. case Expr::ObjCEncodeExprClass:
  1109. case Expr::CXXTypeidExprClass:
  1110. case Expr::CXXUuidofExprClass:
  1111. return true;
  1112. case Expr::CallExprClass:
  1113. return IsStringLiteralCall(cast<CallExpr>(E));
  1114. // For GCC compatibility, &&label has static storage duration.
  1115. case Expr::AddrLabelExprClass:
  1116. return true;
  1117. // A Block literal expression may be used as the initialization value for
  1118. // Block variables at global or local static scope.
  1119. case Expr::BlockExprClass:
  1120. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1121. case Expr::ImplicitValueInitExprClass:
  1122. // FIXME:
  1123. // We can never form an lvalue with an implicit value initialization as its
  1124. // base through expression evaluation, so these only appear in one case: the
  1125. // implicit variable declaration we invent when checking whether a constexpr
  1126. // constructor can produce a constant expression. We must assume that such
  1127. // an expression might be a global lvalue.
  1128. return true;
  1129. }
  1130. }
  1131. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1132. assert(Base && "no location for a null lvalue");
  1133. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1134. if (VD)
  1135. Info.Note(VD->getLocation(), diag::note_declared_at);
  1136. else
  1137. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1138. diag::note_constexpr_temporary_here);
  1139. }
  1140. /// Check that this reference or pointer core constant expression is a valid
  1141. /// value for an address or reference constant expression. Return true if we
  1142. /// can fold this expression, whether or not it's a constant expression.
  1143. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1144. QualType Type, const LValue &LVal) {
  1145. bool IsReferenceType = Type->isReferenceType();
  1146. APValue::LValueBase Base = LVal.getLValueBase();
  1147. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1148. // Check that the object is a global. Note that the fake 'this' object we
  1149. // manufacture when checking potential constant expressions is conservatively
  1150. // assumed to be global here.
  1151. if (!IsGlobalLValue(Base)) {
  1152. if (Info.getLangOpts().CPlusPlus11) {
  1153. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1154. Info.Diag(Loc, diag::note_constexpr_non_global, 1)
  1155. << IsReferenceType << !Designator.Entries.empty()
  1156. << !!VD << VD;
  1157. NoteLValueLocation(Info, Base);
  1158. } else {
  1159. Info.Diag(Loc);
  1160. }
  1161. // Don't allow references to temporaries to escape.
  1162. return false;
  1163. }
  1164. assert((Info.checkingPotentialConstantExpression() ||
  1165. LVal.getLValueCallIndex() == 0) &&
  1166. "have call index for global lvalue");
  1167. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1168. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1169. // Check if this is a thread-local variable.
  1170. if (Var->getTLSKind())
  1171. return false;
  1172. // A dllimport variable never acts like a constant.
  1173. if (Var->hasAttr<DLLImportAttr>())
  1174. return false;
  1175. }
  1176. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1177. // __declspec(dllimport) must be handled very carefully:
  1178. // We must never initialize an expression with the thunk in C++.
  1179. // Doing otherwise would allow the same id-expression to yield
  1180. // different addresses for the same function in different translation
  1181. // units. However, this means that we must dynamically initialize the
  1182. // expression with the contents of the import address table at runtime.
  1183. //
  1184. // The C language has no notion of ODR; furthermore, it has no notion of
  1185. // dynamic initialization. This means that we are permitted to
  1186. // perform initialization with the address of the thunk.
  1187. if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
  1188. return false;
  1189. }
  1190. }
  1191. // Allow address constant expressions to be past-the-end pointers. This is
  1192. // an extension: the standard requires them to point to an object.
  1193. if (!IsReferenceType)
  1194. return true;
  1195. // A reference constant expression must refer to an object.
  1196. if (!Base) {
  1197. // FIXME: diagnostic
  1198. Info.CCEDiag(Loc);
  1199. return true;
  1200. }
  1201. // Does this refer one past the end of some object?
  1202. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1203. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1204. Info.Diag(Loc, diag::note_constexpr_past_end, 1)
  1205. << !Designator.Entries.empty() << !!VD << VD;
  1206. NoteLValueLocation(Info, Base);
  1207. }
  1208. return true;
  1209. }
  1210. /// Check that this core constant expression is of literal type, and if not,
  1211. /// produce an appropriate diagnostic.
  1212. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1213. const LValue *This = nullptr) {
  1214. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1215. return true;
  1216. // C++1y: A constant initializer for an object o [...] may also invoke
  1217. // constexpr constructors for o and its subobjects even if those objects
  1218. // are of non-literal class types.
  1219. if (Info.getLangOpts().CPlusPlus14 && This &&
  1220. Info.EvaluatingDecl == This->getLValueBase())
  1221. return true;
  1222. // Prvalue constant expressions must be of literal types.
  1223. if (Info.getLangOpts().CPlusPlus11)
  1224. Info.Diag(E, diag::note_constexpr_nonliteral)
  1225. << E->getType();
  1226. else
  1227. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1228. return false;
  1229. }
  1230. /// Check that this core constant expression value is a valid value for a
  1231. /// constant expression. If not, report an appropriate diagnostic. Does not
  1232. /// check that the expression is of literal type.
  1233. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  1234. QualType Type, const APValue &Value) {
  1235. if (Value.isUninit()) {
  1236. Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
  1237. << true << Type;
  1238. return false;
  1239. }
  1240. // We allow _Atomic(T) to be initialized from anything that T can be
  1241. // initialized from.
  1242. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1243. Type = AT->getValueType();
  1244. // Core issue 1454: For a literal constant expression of array or class type,
  1245. // each subobject of its value shall have been initialized by a constant
  1246. // expression.
  1247. if (Value.isArray()) {
  1248. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1249. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1250. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1251. Value.getArrayInitializedElt(I)))
  1252. return false;
  1253. }
  1254. if (!Value.hasArrayFiller())
  1255. return true;
  1256. return CheckConstantExpression(Info, DiagLoc, EltTy,
  1257. Value.getArrayFiller());
  1258. }
  1259. if (Value.isUnion() && Value.getUnionField()) {
  1260. return CheckConstantExpression(Info, DiagLoc,
  1261. Value.getUnionField()->getType(),
  1262. Value.getUnionValue());
  1263. }
  1264. if (Value.isStruct()) {
  1265. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1266. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1267. unsigned BaseIndex = 0;
  1268. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  1269. End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
  1270. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1271. Value.getStructBase(BaseIndex)))
  1272. return false;
  1273. }
  1274. }
  1275. for (const auto *I : RD->fields()) {
  1276. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1277. Value.getStructField(I->getFieldIndex())))
  1278. return false;
  1279. }
  1280. }
  1281. if (Value.isLValue()) {
  1282. LValue LVal;
  1283. LVal.setFrom(Info.Ctx, Value);
  1284. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
  1285. }
  1286. // Everything else is fine.
  1287. return true;
  1288. }
  1289. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1290. return LVal.Base.dyn_cast<const ValueDecl*>();
  1291. }
  1292. static bool IsLiteralLValue(const LValue &Value) {
  1293. if (Value.CallIndex)
  1294. return false;
  1295. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1296. return E && !isa<MaterializeTemporaryExpr>(E);
  1297. }
  1298. static bool IsWeakLValue(const LValue &Value) {
  1299. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1300. return Decl && Decl->isWeak();
  1301. }
  1302. static bool isZeroSized(const LValue &Value) {
  1303. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1304. if (Decl && isa<VarDecl>(Decl)) {
  1305. QualType Ty = Decl->getType();
  1306. if (Ty->isArrayType())
  1307. return Ty->isIncompleteType() ||
  1308. Decl->getASTContext().getTypeSize(Ty) == 0;
  1309. }
  1310. return false;
  1311. }
  1312. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1313. // A null base expression indicates a null pointer. These are always
  1314. // evaluatable, and they are false unless the offset is zero.
  1315. if (!Value.getLValueBase()) {
  1316. Result = !Value.getLValueOffset().isZero();
  1317. return true;
  1318. }
  1319. // We have a non-null base. These are generally known to be true, but if it's
  1320. // a weak declaration it can be null at runtime.
  1321. Result = true;
  1322. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1323. return !Decl || !Decl->isWeak();
  1324. }
  1325. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1326. switch (Val.getKind()) {
  1327. case APValue::Uninitialized:
  1328. return false;
  1329. case APValue::Int:
  1330. Result = Val.getInt().getBoolValue();
  1331. return true;
  1332. case APValue::Float:
  1333. Result = !Val.getFloat().isZero();
  1334. return true;
  1335. case APValue::ComplexInt:
  1336. Result = Val.getComplexIntReal().getBoolValue() ||
  1337. Val.getComplexIntImag().getBoolValue();
  1338. return true;
  1339. case APValue::ComplexFloat:
  1340. Result = !Val.getComplexFloatReal().isZero() ||
  1341. !Val.getComplexFloatImag().isZero();
  1342. return true;
  1343. case APValue::LValue:
  1344. return EvalPointerValueAsBool(Val, Result);
  1345. case APValue::MemberPointer:
  1346. Result = Val.getMemberPointerDecl();
  1347. return true;
  1348. case APValue::Vector:
  1349. case APValue::Array:
  1350. case APValue::Struct:
  1351. case APValue::Union:
  1352. case APValue::AddrLabelDiff:
  1353. return false;
  1354. }
  1355. llvm_unreachable("unknown APValue kind");
  1356. }
  1357. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1358. EvalInfo &Info) {
  1359. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1360. APValue Val;
  1361. if (!Evaluate(Val, Info, E))
  1362. return false;
  1363. return HandleConversionToBool(Val, Result);
  1364. }
  1365. template<typename T>
  1366. static void HandleOverflow(EvalInfo &Info, const Expr *E,
  1367. const T &SrcValue, QualType DestType) {
  1368. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1369. << SrcValue << DestType;
  1370. }
  1371. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1372. QualType SrcType, const APFloat &Value,
  1373. QualType DestType, APSInt &Result) {
  1374. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1375. // Determine whether we are converting to unsigned or signed.
  1376. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1377. Result = APSInt(DestWidth, !DestSigned);
  1378. bool ignored;
  1379. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1380. & APFloat::opInvalidOp)
  1381. HandleOverflow(Info, E, Value, DestType);
  1382. return true;
  1383. }
  1384. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1385. QualType SrcType, QualType DestType,
  1386. APFloat &Result) {
  1387. APFloat Value = Result;
  1388. bool ignored;
  1389. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1390. APFloat::rmNearestTiesToEven, &ignored)
  1391. & APFloat::opOverflow)
  1392. HandleOverflow(Info, E, Value, DestType);
  1393. return true;
  1394. }
  1395. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1396. QualType DestType, QualType SrcType,
  1397. APSInt &Value) {
  1398. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1399. APSInt Result = Value;
  1400. // Figure out if this is a truncate, extend or noop cast.
  1401. // If the input is signed, do a sign extend, noop, or truncate.
  1402. Result = Result.extOrTrunc(DestWidth);
  1403. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1404. return Result;
  1405. }
  1406. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1407. QualType SrcType, const APSInt &Value,
  1408. QualType DestType, APFloat &Result) {
  1409. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1410. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1411. APFloat::rmNearestTiesToEven)
  1412. & APFloat::opOverflow)
  1413. HandleOverflow(Info, E, Value, DestType);
  1414. return true;
  1415. }
  1416. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1417. APValue &Value, const FieldDecl *FD) {
  1418. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1419. if (!Value.isInt()) {
  1420. // Trying to store a pointer-cast-to-integer into a bitfield.
  1421. // FIXME: In this case, we should provide the diagnostic for casting
  1422. // a pointer to an integer.
  1423. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1424. Info.Diag(E);
  1425. return false;
  1426. }
  1427. APSInt &Int = Value.getInt();
  1428. unsigned OldBitWidth = Int.getBitWidth();
  1429. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1430. if (NewBitWidth < OldBitWidth)
  1431. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1432. return true;
  1433. }
  1434. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1435. llvm::APInt &Res) {
  1436. APValue SVal;
  1437. if (!Evaluate(SVal, Info, E))
  1438. return false;
  1439. if (SVal.isInt()) {
  1440. Res = SVal.getInt();
  1441. return true;
  1442. }
  1443. if (SVal.isFloat()) {
  1444. Res = SVal.getFloat().bitcastToAPInt();
  1445. return true;
  1446. }
  1447. if (SVal.isVector()) {
  1448. QualType VecTy = E->getType();
  1449. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1450. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1451. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1452. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1453. Res = llvm::APInt::getNullValue(VecSize);
  1454. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1455. APValue &Elt = SVal.getVectorElt(i);
  1456. llvm::APInt EltAsInt;
  1457. if (Elt.isInt()) {
  1458. EltAsInt = Elt.getInt();
  1459. } else if (Elt.isFloat()) {
  1460. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1461. } else {
  1462. // Don't try to handle vectors of anything other than int or float
  1463. // (not sure if it's possible to hit this case).
  1464. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1465. return false;
  1466. }
  1467. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1468. if (BigEndian)
  1469. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1470. else
  1471. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1472. }
  1473. return true;
  1474. }
  1475. // Give up if the input isn't an int, float, or vector. For example, we
  1476. // reject "(v4i16)(intptr_t)&a".
  1477. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1478. return false;
  1479. }
  1480. /// Perform the given integer operation, which is known to need at most BitWidth
  1481. /// bits, and check for overflow in the original type (if that type was not an
  1482. /// unsigned type).
  1483. template<typename Operation>
  1484. static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1485. const APSInt &LHS, const APSInt &RHS,
  1486. unsigned BitWidth, Operation Op) {
  1487. if (LHS.isUnsigned())
  1488. return Op(LHS, RHS);
  1489. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1490. APSInt Result = Value.trunc(LHS.getBitWidth());
  1491. if (Result.extend(BitWidth) != Value) {
  1492. if (Info.checkingForOverflow())
  1493. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1494. diag::warn_integer_constant_overflow)
  1495. << Result.toString(10) << E->getType();
  1496. else
  1497. HandleOverflow(Info, E, Value, E->getType());
  1498. }
  1499. return Result;
  1500. }
  1501. /// Perform the given binary integer operation.
  1502. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1503. BinaryOperatorKind Opcode, APSInt RHS,
  1504. APSInt &Result) {
  1505. switch (Opcode) {
  1506. default:
  1507. Info.Diag(E);
  1508. return false;
  1509. case BO_Mul:
  1510. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1511. std::multiplies<APSInt>());
  1512. return true;
  1513. case BO_Add:
  1514. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1515. std::plus<APSInt>());
  1516. return true;
  1517. case BO_Sub:
  1518. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1519. std::minus<APSInt>());
  1520. return true;
  1521. case BO_And: Result = LHS & RHS; return true;
  1522. case BO_Xor: Result = LHS ^ RHS; return true;
  1523. case BO_Or: Result = LHS | RHS; return true;
  1524. case BO_Div:
  1525. case BO_Rem:
  1526. if (RHS == 0) {
  1527. Info.Diag(E, diag::note_expr_divide_by_zero);
  1528. return false;
  1529. }
  1530. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
  1531. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1532. LHS.isSigned() && LHS.isMinSignedValue())
  1533. HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  1534. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1535. return true;
  1536. case BO_Shl: {
  1537. if (Info.getLangOpts().OpenCL)
  1538. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1539. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1540. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1541. RHS.isUnsigned());
  1542. else if (RHS.isSigned() && RHS.isNegative()) {
  1543. // During constant-folding, a negative shift is an opposite shift. Such
  1544. // a shift is not a constant expression.
  1545. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1546. RHS = -RHS;
  1547. goto shift_right;
  1548. }
  1549. shift_left:
  1550. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1551. // the shifted type.
  1552. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1553. if (SA != RHS) {
  1554. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1555. << RHS << E->getType() << LHS.getBitWidth();
  1556. } else if (LHS.isSigned()) {
  1557. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1558. // operand, and must not overflow the corresponding unsigned type.
  1559. if (LHS.isNegative())
  1560. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  1561. else if (LHS.countLeadingZeros() < SA)
  1562. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  1563. }
  1564. Result = LHS << SA;
  1565. return true;
  1566. }
  1567. case BO_Shr: {
  1568. if (Info.getLangOpts().OpenCL)
  1569. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1570. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1571. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1572. RHS.isUnsigned());
  1573. else if (RHS.isSigned() && RHS.isNegative()) {
  1574. // During constant-folding, a negative shift is an opposite shift. Such a
  1575. // shift is not a constant expression.
  1576. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1577. RHS = -RHS;
  1578. goto shift_left;
  1579. }
  1580. shift_right:
  1581. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  1582. // shifted type.
  1583. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1584. if (SA != RHS)
  1585. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1586. << RHS << E->getType() << LHS.getBitWidth();
  1587. Result = LHS >> SA;
  1588. return true;
  1589. }
  1590. case BO_LT: Result = LHS < RHS; return true;
  1591. case BO_GT: Result = LHS > RHS; return true;
  1592. case BO_LE: Result = LHS <= RHS; return true;
  1593. case BO_GE: Result = LHS >= RHS; return true;
  1594. case BO_EQ: Result = LHS == RHS; return true;
  1595. case BO_NE: Result = LHS != RHS; return true;
  1596. }
  1597. }
  1598. /// Perform the given binary floating-point operation, in-place, on LHS.
  1599. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  1600. APFloat &LHS, BinaryOperatorKind Opcode,
  1601. const APFloat &RHS) {
  1602. switch (Opcode) {
  1603. default:
  1604. Info.Diag(E);
  1605. return false;
  1606. case BO_Mul:
  1607. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  1608. break;
  1609. case BO_Add:
  1610. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  1611. break;
  1612. case BO_Sub:
  1613. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  1614. break;
  1615. case BO_Div:
  1616. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  1617. break;
  1618. }
  1619. if (LHS.isInfinity() || LHS.isNaN())
  1620. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  1621. return true;
  1622. }
  1623. /// Cast an lvalue referring to a base subobject to a derived class, by
  1624. /// truncating the lvalue's path to the given length.
  1625. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1626. const RecordDecl *TruncatedType,
  1627. unsigned TruncatedElements) {
  1628. SubobjectDesignator &D = Result.Designator;
  1629. // Check we actually point to a derived class object.
  1630. if (TruncatedElements == D.Entries.size())
  1631. return true;
  1632. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1633. "not casting to a derived class");
  1634. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1635. return false;
  1636. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1637. const RecordDecl *RD = TruncatedType;
  1638. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1639. if (RD->isInvalidDecl()) return false;
  1640. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1641. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1642. if (isVirtualBaseClass(D.Entries[I]))
  1643. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1644. else
  1645. Result.Offset -= Layout.getBaseClassOffset(Base);
  1646. RD = Base;
  1647. }
  1648. D.Entries.resize(TruncatedElements);
  1649. return true;
  1650. }
  1651. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1652. const CXXRecordDecl *Derived,
  1653. const CXXRecordDecl *Base,
  1654. const ASTRecordLayout *RL = nullptr) {
  1655. if (!RL) {
  1656. if (Derived->isInvalidDecl()) return false;
  1657. RL = &Info.Ctx.getASTRecordLayout(Derived);
  1658. }
  1659. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1660. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1661. return true;
  1662. }
  1663. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1664. const CXXRecordDecl *DerivedDecl,
  1665. const CXXBaseSpecifier *Base) {
  1666. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1667. if (!Base->isVirtual())
  1668. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1669. SubobjectDesignator &D = Obj.Designator;
  1670. if (D.Invalid)
  1671. return false;
  1672. // Extract most-derived object and corresponding type.
  1673. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1674. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1675. return false;
  1676. // Find the virtual base class.
  1677. if (DerivedDecl->isInvalidDecl()) return false;
  1678. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1679. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1680. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1681. return true;
  1682. }
  1683. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  1684. QualType Type, LValue &Result) {
  1685. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  1686. PathE = E->path_end();
  1687. PathI != PathE; ++PathI) {
  1688. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  1689. *PathI))
  1690. return false;
  1691. Type = (*PathI)->getType();
  1692. }
  1693. return true;
  1694. }
  1695. /// Update LVal to refer to the given field, which must be a member of the type
  1696. /// currently described by LVal.
  1697. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1698. const FieldDecl *FD,
  1699. const ASTRecordLayout *RL = nullptr) {
  1700. if (!RL) {
  1701. if (FD->getParent()->isInvalidDecl()) return false;
  1702. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1703. }
  1704. unsigned I = FD->getFieldIndex();
  1705. LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
  1706. LVal.addDecl(Info, E, FD);
  1707. return true;
  1708. }
  1709. /// Update LVal to refer to the given indirect field.
  1710. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1711. LValue &LVal,
  1712. const IndirectFieldDecl *IFD) {
  1713. for (const auto *C : IFD->chain())
  1714. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  1715. return false;
  1716. return true;
  1717. }
  1718. /// Get the size of the given type in char units.
  1719. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  1720. QualType Type, CharUnits &Size) {
  1721. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1722. // extension.
  1723. if (Type->isVoidType() || Type->isFunctionType()) {
  1724. Size = CharUnits::One();
  1725. return true;
  1726. }
  1727. if (!Type->isConstantSizeType()) {
  1728. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1729. // FIXME: Better diagnostic.
  1730. Info.Diag(Loc);
  1731. return false;
  1732. }
  1733. Size = Info.Ctx.getTypeSizeInChars(Type);
  1734. return true;
  1735. }
  1736. /// Update a pointer value to model pointer arithmetic.
  1737. /// \param Info - Information about the ongoing evaluation.
  1738. /// \param E - The expression being evaluated, for diagnostic purposes.
  1739. /// \param LVal - The pointer value to be updated.
  1740. /// \param EltTy - The pointee type represented by LVal.
  1741. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1742. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1743. LValue &LVal, QualType EltTy,
  1744. int64_t Adjustment) {
  1745. CharUnits SizeOfPointee;
  1746. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  1747. return false;
  1748. // Compute the new offset in the appropriate width.
  1749. LVal.Offset += Adjustment * SizeOfPointee;
  1750. LVal.adjustIndex(Info, E, Adjustment);
  1751. return true;
  1752. }
  1753. /// Update an lvalue to refer to a component of a complex number.
  1754. /// \param Info - Information about the ongoing evaluation.
  1755. /// \param LVal - The lvalue to be updated.
  1756. /// \param EltTy - The complex number's component type.
  1757. /// \param Imag - False for the real component, true for the imaginary.
  1758. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  1759. LValue &LVal, QualType EltTy,
  1760. bool Imag) {
  1761. if (Imag) {
  1762. CharUnits SizeOfComponent;
  1763. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  1764. return false;
  1765. LVal.Offset += SizeOfComponent;
  1766. }
  1767. LVal.addComplex(Info, E, EltTy, Imag);
  1768. return true;
  1769. }
  1770. /// Try to evaluate the initializer for a variable declaration.
  1771. ///
  1772. /// \param Info Information about the ongoing evaluation.
  1773. /// \param E An expression to be used when printing diagnostics.
  1774. /// \param VD The variable whose initializer should be obtained.
  1775. /// \param Frame The frame in which the variable was created. Must be null
  1776. /// if this variable is not local to the evaluation.
  1777. /// \param Result Filled in with a pointer to the value of the variable.
  1778. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1779. const VarDecl *VD, CallStackFrame *Frame,
  1780. APValue *&Result) {
  1781. // If this is a parameter to an active constexpr function call, perform
  1782. // argument substitution.
  1783. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1784. // Assume arguments of a potential constant expression are unknown
  1785. // constant expressions.
  1786. if (Info.checkingPotentialConstantExpression())
  1787. return false;
  1788. if (!Frame || !Frame->Arguments) {
  1789. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1790. return false;
  1791. }
  1792. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  1793. return true;
  1794. }
  1795. // If this is a local variable, dig out its value.
  1796. if (Frame) {
  1797. Result = Frame->getTemporary(VD);
  1798. assert(Result && "missing value for local variable");
  1799. return true;
  1800. }
  1801. // Dig out the initializer, and use the declaration which it's attached to.
  1802. const Expr *Init = VD->getAnyInitializer(VD);
  1803. if (!Init || Init->isValueDependent()) {
  1804. // If we're checking a potential constant expression, the variable could be
  1805. // initialized later.
  1806. if (!Info.checkingPotentialConstantExpression())
  1807. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1808. return false;
  1809. }
  1810. // If we're currently evaluating the initializer of this declaration, use that
  1811. // in-flight value.
  1812. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  1813. Result = Info.EvaluatingDeclValue;
  1814. return true;
  1815. }
  1816. // Never evaluate the initializer of a weak variable. We can't be sure that
  1817. // this is the definition which will be used.
  1818. if (VD->isWeak()) {
  1819. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1820. return false;
  1821. }
  1822. // HLSL Change Begin - External variable is in cbuffer, cannot use as immediate.
  1823. if (VD->hasExternalFormalLinkage() &&
  1824. !isa<EnumConstantDecl>(VD))
  1825. return false;
  1826. // HLSL Change End.
  1827. // Check that we can fold the initializer. In C++, we will have already done
  1828. // this in the cases where it matters for conformance.
  1829. SmallVector<PartialDiagnosticAt, 8> Notes;
  1830. if (!VD->evaluateValue(Notes)) {
  1831. Info.Diag(E, diag::note_constexpr_var_init_non_constant,
  1832. Notes.size() + 1) << VD;
  1833. Info.Note(VD->getLocation(), diag::note_declared_at);
  1834. Info.addNotes(Notes);
  1835. return false;
  1836. } else if (!VD->checkInitIsICE()) {
  1837. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  1838. Notes.size() + 1) << VD;
  1839. Info.Note(VD->getLocation(), diag::note_declared_at);
  1840. Info.addNotes(Notes);
  1841. }
  1842. Result = VD->getEvaluatedValue();
  1843. return true;
  1844. }
  1845. static bool IsConstNonVolatile(QualType T) {
  1846. Qualifiers Quals = T.getQualifiers();
  1847. return Quals.hasConst() && !Quals.hasVolatile();
  1848. }
  1849. /// Get the base index of the given base class within an APValue representing
  1850. /// the given derived class.
  1851. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1852. const CXXRecordDecl *Base) {
  1853. Base = Base->getCanonicalDecl();
  1854. unsigned Index = 0;
  1855. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  1856. E = Derived->bases_end(); I != E; ++I, ++Index) {
  1857. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  1858. return Index;
  1859. }
  1860. llvm_unreachable("base class missing from derived class's bases list");
  1861. }
  1862. /// Extract the value of a character from a string literal.
  1863. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  1864. uint64_t Index) {
  1865. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  1866. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  1867. Lit = PE->getFunctionName();
  1868. const StringLiteral *S = cast<StringLiteral>(Lit);
  1869. const ConstantArrayType *CAT =
  1870. Info.Ctx.getAsConstantArrayType(S->getType());
  1871. assert(CAT && "string literal isn't an array");
  1872. QualType CharType = CAT->getElementType();
  1873. assert(CharType->isIntegerType() && "unexpected character type");
  1874. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1875. CharType->isUnsignedIntegerType());
  1876. if (Index < S->getLength())
  1877. Value = S->getCodeUnit(Index);
  1878. return Value;
  1879. }
  1880. // Expand a string literal into an array of characters.
  1881. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  1882. APValue &Result) {
  1883. const StringLiteral *S = cast<StringLiteral>(Lit);
  1884. const ConstantArrayType *CAT =
  1885. Info.Ctx.getAsConstantArrayType(S->getType());
  1886. assert(CAT && "string literal isn't an array");
  1887. QualType CharType = CAT->getElementType();
  1888. assert(CharType->isIntegerType() && "unexpected character type");
  1889. unsigned Elts = CAT->getSize().getZExtValue();
  1890. Result = APValue(APValue::UninitArray(),
  1891. std::min(S->getLength(), Elts), Elts);
  1892. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1893. CharType->isUnsignedIntegerType());
  1894. if (Result.hasArrayFiller())
  1895. Result.getArrayFiller() = APValue(Value);
  1896. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  1897. Value = S->getCodeUnit(I);
  1898. Result.getArrayInitializedElt(I) = APValue(Value);
  1899. }
  1900. }
  1901. // Expand an array so that it has more than Index filled elements.
  1902. static void expandArray(APValue &Array, unsigned Index) {
  1903. unsigned Size = Array.getArraySize();
  1904. assert(Index < Size);
  1905. // Always at least double the number of elements for which we store a value.
  1906. unsigned OldElts = Array.getArrayInitializedElts();
  1907. unsigned NewElts = std::max(Index+1, OldElts * 2);
  1908. NewElts = std::min(Size, std::max(NewElts, 8u));
  1909. // Copy the data across.
  1910. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  1911. for (unsigned I = 0; I != OldElts; ++I)
  1912. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  1913. for (unsigned I = OldElts; I != NewElts; ++I)
  1914. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  1915. if (NewValue.hasArrayFiller())
  1916. NewValue.getArrayFiller() = Array.getArrayFiller();
  1917. Array.swap(NewValue);
  1918. }
  1919. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  1920. /// conversion. If it's of class type, we may assume that the copy operation
  1921. /// is trivial. Note that this is never true for a union type with fields
  1922. /// (because the copy always "reads" the active member) and always true for
  1923. /// a non-class type.
  1924. static bool isReadByLvalueToRvalueConversion(QualType T) {
  1925. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1926. if (!RD || (RD->isUnion() && !RD->field_empty()))
  1927. return true;
  1928. if (RD->isEmpty())
  1929. return false;
  1930. for (auto *Field : RD->fields())
  1931. if (isReadByLvalueToRvalueConversion(Field->getType()))
  1932. return true;
  1933. for (auto &BaseSpec : RD->bases())
  1934. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  1935. return true;
  1936. return false;
  1937. }
  1938. /// Diagnose an attempt to read from any unreadable field within the specified
  1939. /// type, which might be a class type.
  1940. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  1941. QualType T) {
  1942. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1943. if (!RD)
  1944. return false;
  1945. if (!RD->hasMutableFields())
  1946. return false;
  1947. for (auto *Field : RD->fields()) {
  1948. // If we're actually going to read this field in some way, then it can't
  1949. // be mutable. If we're in a union, then assigning to a mutable field
  1950. // (even an empty one) can change the active member, so that's not OK.
  1951. // FIXME: Add core issue number for the union case.
  1952. if (Field->isMutable() &&
  1953. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  1954. Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  1955. Info.Note(Field->getLocation(), diag::note_declared_at);
  1956. return true;
  1957. }
  1958. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  1959. return true;
  1960. }
  1961. for (auto &BaseSpec : RD->bases())
  1962. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  1963. return true;
  1964. // All mutable fields were empty, and thus not actually read.
  1965. return false;
  1966. }
  1967. /// Kinds of access we can perform on an object, for diagnostics.
  1968. enum AccessKinds {
  1969. AK_Read,
  1970. AK_Assign,
  1971. AK_Increment,
  1972. AK_Decrement
  1973. };
  1974. /// A handle to a complete object (an object that is not a subobject of
  1975. /// another object).
  1976. struct CompleteObject {
  1977. /// The value of the complete object.
  1978. APValue *Value;
  1979. /// The type of the complete object.
  1980. QualType Type;
  1981. CompleteObject() : Value(nullptr) {}
  1982. CompleteObject(APValue *Value, QualType Type)
  1983. : Value(Value), Type(Type) {
  1984. assert(Value && "missing value for complete object");
  1985. }
  1986. explicit operator bool() const { return Value; }
  1987. };
  1988. /// Find the designated sub-object of an rvalue.
  1989. template<typename SubobjectHandler>
  1990. typename SubobjectHandler::result_type
  1991. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  1992. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  1993. if (Sub.Invalid)
  1994. // A diagnostic will have already been produced.
  1995. return handler.failed();
  1996. if (Sub.isOnePastTheEnd()) {
  1997. if (Info.getLangOpts().CPlusPlus11)
  1998. Info.Diag(E, diag::note_constexpr_access_past_end)
  1999. << handler.AccessKind;
  2000. else
  2001. Info.Diag(E);
  2002. return handler.failed();
  2003. }
  2004. APValue *O = Obj.Value;
  2005. QualType ObjType = Obj.Type;
  2006. const FieldDecl *LastField = nullptr;
  2007. // Walk the designator's path to find the subobject.
  2008. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2009. if (O->isUninit()) {
  2010. if (!Info.checkingPotentialConstantExpression())
  2011. Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2012. return handler.failed();
  2013. }
  2014. if (I == N) {
  2015. // If we are reading an object of class type, there may still be more
  2016. // things we need to check: if there are any mutable subobjects, we
  2017. // cannot perform this read. (This only happens when performing a trivial
  2018. // copy or assignment.)
  2019. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2020. diagnoseUnreadableFields(Info, E, ObjType))
  2021. return handler.failed();
  2022. if (!handler.found(*O, ObjType))
  2023. return false;
  2024. // If we modified a bit-field, truncate it to the right width.
  2025. if (handler.AccessKind != AK_Read &&
  2026. LastField && LastField->isBitField() &&
  2027. !truncateBitfieldValue(Info, E, *O, LastField))
  2028. return false;
  2029. return true;
  2030. }
  2031. LastField = nullptr;
  2032. if (ObjType->isArrayType()) {
  2033. // Next subobject is an array element.
  2034. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2035. assert(CAT && "vla in literal type?");
  2036. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2037. if (CAT->getSize().ule(Index)) {
  2038. // Note, it should not be possible to form a pointer with a valid
  2039. // designator which points more than one past the end of the array.
  2040. if (Info.getLangOpts().CPlusPlus11)
  2041. Info.Diag(E, diag::note_constexpr_access_past_end)
  2042. << handler.AccessKind;
  2043. else
  2044. Info.Diag(E);
  2045. return handler.failed();
  2046. }
  2047. ObjType = CAT->getElementType();
  2048. // An array object is represented as either an Array APValue or as an
  2049. // LValue which refers to a string literal.
  2050. if (O->isLValue()) {
  2051. assert(I == N - 1 && "extracting subobject of character?");
  2052. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2053. if (handler.AccessKind != AK_Read)
  2054. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2055. *O);
  2056. else
  2057. return handler.foundString(*O, ObjType, Index);
  2058. }
  2059. if (O->getArrayInitializedElts() > Index)
  2060. O = &O->getArrayInitializedElt(Index);
  2061. else if (handler.AccessKind != AK_Read) {
  2062. expandArray(*O, Index);
  2063. O = &O->getArrayInitializedElt(Index);
  2064. } else
  2065. O = &O->getArrayFiller();
  2066. } else if (ObjType->isAnyComplexType()) {
  2067. // Next subobject is a complex number.
  2068. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2069. if (Index > 1) {
  2070. if (Info.getLangOpts().CPlusPlus11)
  2071. Info.Diag(E, diag::note_constexpr_access_past_end)
  2072. << handler.AccessKind;
  2073. else
  2074. Info.Diag(E);
  2075. return handler.failed();
  2076. }
  2077. bool WasConstQualified = ObjType.isConstQualified();
  2078. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2079. if (WasConstQualified)
  2080. ObjType.addConst();
  2081. assert(I == N - 1 && "extracting subobject of scalar?");
  2082. if (O->isComplexInt()) {
  2083. return handler.found(Index ? O->getComplexIntImag()
  2084. : O->getComplexIntReal(), ObjType);
  2085. } else {
  2086. assert(O->isComplexFloat());
  2087. return handler.found(Index ? O->getComplexFloatImag()
  2088. : O->getComplexFloatReal(), ObjType);
  2089. }
  2090. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2091. if (Field->isMutable() && handler.AccessKind == AK_Read) {
  2092. Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
  2093. << Field;
  2094. Info.Note(Field->getLocation(), diag::note_declared_at);
  2095. return handler.failed();
  2096. }
  2097. // Next subobject is a class, struct or union field.
  2098. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2099. if (RD->isUnion()) {
  2100. const FieldDecl *UnionField = O->getUnionField();
  2101. if (!UnionField ||
  2102. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2103. Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
  2104. << handler.AccessKind << Field << !UnionField << UnionField;
  2105. return handler.failed();
  2106. }
  2107. O = &O->getUnionValue();
  2108. } else
  2109. O = &O->getStructField(Field->getFieldIndex());
  2110. bool WasConstQualified = ObjType.isConstQualified();
  2111. ObjType = Field->getType();
  2112. if (WasConstQualified && !Field->isMutable())
  2113. ObjType.addConst();
  2114. if (ObjType.isVolatileQualified()) {
  2115. if (Info.getLangOpts().CPlusPlus) {
  2116. // FIXME: Include a description of the path to the volatile subobject.
  2117. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2118. << handler.AccessKind << 2 << Field;
  2119. Info.Note(Field->getLocation(), diag::note_declared_at);
  2120. } else {
  2121. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  2122. }
  2123. return handler.failed();
  2124. }
  2125. LastField = Field;
  2126. } else {
  2127. // Next subobject is a base class.
  2128. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2129. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2130. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2131. bool WasConstQualified = ObjType.isConstQualified();
  2132. ObjType = Info.Ctx.getRecordType(Base);
  2133. if (WasConstQualified)
  2134. ObjType.addConst();
  2135. }
  2136. }
  2137. }
  2138. namespace {
  2139. struct ExtractSubobjectHandler {
  2140. EvalInfo &Info;
  2141. APValue &Result;
  2142. static const AccessKinds AccessKind = AK_Read;
  2143. typedef bool result_type;
  2144. bool failed() { return false; }
  2145. bool found(APValue &Subobj, QualType SubobjType) {
  2146. Result = Subobj;
  2147. return true;
  2148. }
  2149. bool found(APSInt &Value, QualType SubobjType) {
  2150. Result = APValue(Value);
  2151. return true;
  2152. }
  2153. bool found(APFloat &Value, QualType SubobjType) {
  2154. Result = APValue(Value);
  2155. return true;
  2156. }
  2157. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2158. Result = APValue(extractStringLiteralCharacter(
  2159. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2160. return true;
  2161. }
  2162. };
  2163. } // end anonymous namespace
  2164. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2165. /// Extract the designated sub-object of an rvalue.
  2166. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2167. const CompleteObject &Obj,
  2168. const SubobjectDesignator &Sub,
  2169. APValue &Result) {
  2170. ExtractSubobjectHandler Handler = { Info, Result };
  2171. return findSubobject(Info, E, Obj, Sub, Handler);
  2172. }
  2173. namespace {
  2174. struct ModifySubobjectHandler {
  2175. EvalInfo &Info;
  2176. APValue &NewVal;
  2177. const Expr *E;
  2178. typedef bool result_type;
  2179. static const AccessKinds AccessKind = AK_Assign;
  2180. bool checkConst(QualType QT) {
  2181. // Assigning to a const object has undefined behavior.
  2182. if (QT.isConstQualified()) {
  2183. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2184. return false;
  2185. }
  2186. return true;
  2187. }
  2188. bool failed() { return false; }
  2189. bool found(APValue &Subobj, QualType SubobjType) {
  2190. if (!checkConst(SubobjType))
  2191. return false;
  2192. // We've been given ownership of NewVal, so just swap it in.
  2193. Subobj.swap(NewVal);
  2194. return true;
  2195. }
  2196. bool found(APSInt &Value, QualType SubobjType) {
  2197. if (!checkConst(SubobjType))
  2198. return false;
  2199. if (!NewVal.isInt()) {
  2200. // Maybe trying to write a cast pointer value into a complex?
  2201. Info.Diag(E);
  2202. return false;
  2203. }
  2204. Value = NewVal.getInt();
  2205. return true;
  2206. }
  2207. bool found(APFloat &Value, QualType SubobjType) {
  2208. if (!checkConst(SubobjType))
  2209. return false;
  2210. Value = NewVal.getFloat();
  2211. return true;
  2212. }
  2213. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2214. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2215. }
  2216. };
  2217. } // end anonymous namespace
  2218. const AccessKinds ModifySubobjectHandler::AccessKind;
  2219. /// Update the designated sub-object of an rvalue to the given value.
  2220. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2221. const CompleteObject &Obj,
  2222. const SubobjectDesignator &Sub,
  2223. APValue &NewVal) {
  2224. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2225. return findSubobject(Info, E, Obj, Sub, Handler);
  2226. }
  2227. /// Find the position where two subobject designators diverge, or equivalently
  2228. /// the length of the common initial subsequence.
  2229. static unsigned FindDesignatorMismatch(QualType ObjType,
  2230. const SubobjectDesignator &A,
  2231. const SubobjectDesignator &B,
  2232. bool &WasArrayIndex) {
  2233. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2234. for (/**/; I != N; ++I) {
  2235. if (!ObjType.isNull() &&
  2236. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2237. // Next subobject is an array element.
  2238. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2239. WasArrayIndex = true;
  2240. return I;
  2241. }
  2242. if (ObjType->isAnyComplexType())
  2243. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2244. else
  2245. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2246. } else {
  2247. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2248. WasArrayIndex = false;
  2249. return I;
  2250. }
  2251. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2252. // Next subobject is a field.
  2253. ObjType = FD->getType();
  2254. else
  2255. // Next subobject is a base class.
  2256. ObjType = QualType();
  2257. }
  2258. }
  2259. WasArrayIndex = false;
  2260. return I;
  2261. }
  2262. /// Determine whether the given subobject designators refer to elements of the
  2263. /// same array object.
  2264. static bool AreElementsOfSameArray(QualType ObjType,
  2265. const SubobjectDesignator &A,
  2266. const SubobjectDesignator &B) {
  2267. if (A.Entries.size() != B.Entries.size())
  2268. return false;
  2269. bool IsArray = A.MostDerivedArraySize != 0;
  2270. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2271. // A is a subobject of the array element.
  2272. return false;
  2273. // If A (and B) designates an array element, the last entry will be the array
  2274. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2275. // of length 1' case, and the entire path must match.
  2276. bool WasArrayIndex;
  2277. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2278. return CommonLength >= A.Entries.size() - IsArray;
  2279. }
  2280. /// Find the complete object to which an LValue refers.
  2281. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2282. AccessKinds AK, const LValue &LVal,
  2283. QualType LValType) {
  2284. if (!LVal.Base) {
  2285. Info.Diag(E, diag::note_constexpr_access_null) << AK;
  2286. return CompleteObject();
  2287. }
  2288. CallStackFrame *Frame = nullptr;
  2289. if (LVal.CallIndex) {
  2290. Frame = Info.getCallFrame(LVal.CallIndex);
  2291. if (!Frame) {
  2292. Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
  2293. << AK << LVal.Base.is<const ValueDecl*>();
  2294. NoteLValueLocation(Info, LVal.Base);
  2295. return CompleteObject();
  2296. }
  2297. }
  2298. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2299. // is not a constant expression (even if the object is non-volatile). We also
  2300. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2301. // semantics.
  2302. if (LValType.isVolatileQualified()) {
  2303. if (Info.getLangOpts().CPlusPlus)
  2304. Info.Diag(E, diag::note_constexpr_access_volatile_type)
  2305. << AK << LValType;
  2306. else
  2307. Info.Diag(E);
  2308. return CompleteObject();
  2309. }
  2310. // Compute value storage location and type of base object.
  2311. APValue *BaseVal = nullptr;
  2312. QualType BaseType = getType(LVal.Base);
  2313. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2314. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2315. // In C++11, constexpr, non-volatile variables initialized with constant
  2316. // expressions are constant expressions too. Inside constexpr functions,
  2317. // parameters are constant expressions even if they're non-const.
  2318. // In C++1y, objects local to a constant expression (those with a Frame) are
  2319. // both readable and writable inside constant expressions.
  2320. // In C, such things can also be folded, although they are not ICEs.
  2321. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2322. if (VD) {
  2323. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2324. VD = VDef;
  2325. }
  2326. if (!VD || VD->isInvalidDecl()) {
  2327. Info.Diag(E);
  2328. return CompleteObject();
  2329. }
  2330. // Accesses of volatile-qualified objects are not allowed.
  2331. if (BaseType.isVolatileQualified()) {
  2332. if (Info.getLangOpts().CPlusPlus) {
  2333. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2334. << AK << 1 << VD;
  2335. Info.Note(VD->getLocation(), diag::note_declared_at);
  2336. } else {
  2337. Info.Diag(E);
  2338. }
  2339. return CompleteObject();
  2340. }
  2341. // Unless we're looking at a local variable or argument in a constexpr call,
  2342. // the variable we're reading must be const.
  2343. if (!Frame) {
  2344. if (Info.getLangOpts().CPlusPlus14 &&
  2345. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2346. // OK, we can read and modify an object if we're in the process of
  2347. // evaluating its initializer, because its lifetime began in this
  2348. // evaluation.
  2349. } else if (AK != AK_Read) {
  2350. // All the remaining cases only permit reading.
  2351. Info.Diag(E, diag::note_constexpr_modify_global);
  2352. return CompleteObject();
  2353. } else if (VD->isConstexpr()) {
  2354. // OK, we can read this variable.
  2355. } else if (BaseType->isIntegralOrEnumerationType()) {
  2356. if (!BaseType.isConstQualified()) {
  2357. if (Info.getLangOpts().CPlusPlus) {
  2358. Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2359. Info.Note(VD->getLocation(), diag::note_declared_at);
  2360. } else {
  2361. Info.Diag(E);
  2362. }
  2363. return CompleteObject();
  2364. }
  2365. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2366. // We support folding of const floating-point types, in order to make
  2367. // static const data members of such types (supported as an extension)
  2368. // more useful.
  2369. if (Info.getLangOpts().CPlusPlus11) {
  2370. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2371. Info.Note(VD->getLocation(), diag::note_declared_at);
  2372. } else {
  2373. Info.CCEDiag(E);
  2374. }
  2375. } else {
  2376. // FIXME: Allow folding of values of any literal type in all languages.
  2377. if (Info.getLangOpts().CPlusPlus11) {
  2378. Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2379. Info.Note(VD->getLocation(), diag::note_declared_at);
  2380. } else {
  2381. Info.Diag(E);
  2382. }
  2383. return CompleteObject();
  2384. }
  2385. }
  2386. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
  2387. return CompleteObject();
  2388. } else {
  2389. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2390. if (!Frame) {
  2391. if (const MaterializeTemporaryExpr *MTE =
  2392. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2393. assert(MTE->getStorageDuration() == SD_Static &&
  2394. "should have a frame for a non-global materialized temporary");
  2395. // Per C++1y [expr.const]p2:
  2396. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2397. // - a [...] glvalue of integral or enumeration type that refers to
  2398. // a non-volatile const object [...]
  2399. // [...]
  2400. // - a [...] glvalue of literal type that refers to a non-volatile
  2401. // object whose lifetime began within the evaluation of e.
  2402. //
  2403. // C++11 misses the 'began within the evaluation of e' check and
  2404. // instead allows all temporaries, including things like:
  2405. // int &&r = 1;
  2406. // int x = ++r;
  2407. // constexpr int k = r;
  2408. // Therefore we use the C++1y rules in C++11 too.
  2409. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2410. const ValueDecl *ED = MTE->getExtendingDecl();
  2411. if (!(BaseType.isConstQualified() &&
  2412. BaseType->isIntegralOrEnumerationType()) &&
  2413. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2414. Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2415. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2416. return CompleteObject();
  2417. }
  2418. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2419. assert(BaseVal && "got reference to unevaluated temporary");
  2420. } else {
  2421. Info.Diag(E);
  2422. return CompleteObject();
  2423. }
  2424. } else {
  2425. BaseVal = Frame->getTemporary(Base);
  2426. assert(BaseVal && "missing value for temporary");
  2427. }
  2428. // Volatile temporary objects cannot be accessed in constant expressions.
  2429. if (BaseType.isVolatileQualified()) {
  2430. if (Info.getLangOpts().CPlusPlus) {
  2431. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2432. << AK << 0;
  2433. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2434. } else {
  2435. Info.Diag(E);
  2436. }
  2437. return CompleteObject();
  2438. }
  2439. }
  2440. // During the construction of an object, it is not yet 'const'.
  2441. // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
  2442. // and this doesn't do quite the right thing for const subobjects of the
  2443. // object under construction.
  2444. if (LVal.getLValueBase() == Info.EvaluatingDecl) {
  2445. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2446. BaseType.removeLocalConst();
  2447. }
  2448. // In C++1y, we can't safely access any mutable state when we might be
  2449. // evaluating after an unmodeled side effect or an evaluation failure.
  2450. //
  2451. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2452. // to be read here (but take care with 'mutable' fields).
  2453. if (Frame && Info.getLangOpts().CPlusPlus14 &&
  2454. (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
  2455. return CompleteObject();
  2456. return CompleteObject(BaseVal, BaseType);
  2457. }
  2458. /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2459. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2460. /// glvalue referred to by an entity of reference type.
  2461. ///
  2462. /// \param Info - Information about the ongoing evaluation.
  2463. /// \param Conv - The expression for which we are performing the conversion.
  2464. /// Used for diagnostics.
  2465. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2466. /// case of a non-class type).
  2467. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2468. /// \param RVal - The produced value will be placed here.
  2469. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2470. QualType Type,
  2471. const LValue &LVal, APValue &RVal) {
  2472. if (LVal.Designator.Invalid)
  2473. return false;
  2474. // Check for special cases where there is no existing APValue to look at.
  2475. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2476. if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
  2477. !Type.isVolatileQualified()) {
  2478. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2479. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2480. // initializer until now for such expressions. Such an expression can't be
  2481. // an ICE in C, so this only matters for fold.
  2482. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  2483. if (Type.isVolatileQualified()) {
  2484. Info.Diag(Conv);
  2485. return false;
  2486. }
  2487. APValue Lit;
  2488. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2489. return false;
  2490. CompleteObject LitObj(&Lit, Base->getType());
  2491. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2492. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2493. // We represent a string literal array as an lvalue pointing at the
  2494. // corresponding expression, rather than building an array of chars.
  2495. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2496. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2497. CompleteObject StrObj(&Str, Base->getType());
  2498. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2499. }
  2500. }
  2501. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  2502. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  2503. }
  2504. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  2505. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2506. QualType LValType, APValue &Val) {
  2507. if (LVal.Designator.Invalid)
  2508. return false;
  2509. if (!Info.getLangOpts().CPlusPlus14) {
  2510. Info.Diag(E);
  2511. return false;
  2512. }
  2513. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2514. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  2515. }
  2516. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  2517. return T->isSignedIntegerType() &&
  2518. Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  2519. }
  2520. namespace {
  2521. struct CompoundAssignSubobjectHandler {
  2522. EvalInfo &Info;
  2523. const Expr *E;
  2524. QualType PromotedLHSType;
  2525. BinaryOperatorKind Opcode;
  2526. const APValue &RHS;
  2527. static const AccessKinds AccessKind = AK_Assign;
  2528. typedef bool result_type;
  2529. bool checkConst(QualType QT) {
  2530. // Assigning to a const object has undefined behavior.
  2531. if (QT.isConstQualified()) {
  2532. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2533. return false;
  2534. }
  2535. return true;
  2536. }
  2537. bool failed() { return false; }
  2538. bool found(APValue &Subobj, QualType SubobjType) {
  2539. switch (Subobj.getKind()) {
  2540. case APValue::Int:
  2541. return found(Subobj.getInt(), SubobjType);
  2542. case APValue::Float:
  2543. return found(Subobj.getFloat(), SubobjType);
  2544. case APValue::ComplexInt:
  2545. case APValue::ComplexFloat:
  2546. // FIXME: Implement complex compound assignment.
  2547. Info.Diag(E);
  2548. return false;
  2549. case APValue::LValue:
  2550. return foundPointer(Subobj, SubobjType);
  2551. default:
  2552. // FIXME: can this happen?
  2553. Info.Diag(E);
  2554. return false;
  2555. }
  2556. }
  2557. bool found(APSInt &Value, QualType SubobjType) {
  2558. if (!checkConst(SubobjType))
  2559. return false;
  2560. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  2561. // We don't support compound assignment on integer-cast-to-pointer
  2562. // values.
  2563. Info.Diag(E);
  2564. return false;
  2565. }
  2566. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  2567. SubobjType, Value);
  2568. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  2569. return false;
  2570. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  2571. return true;
  2572. }
  2573. bool found(APFloat &Value, QualType SubobjType) {
  2574. return checkConst(SubobjType) &&
  2575. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  2576. Value) &&
  2577. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  2578. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  2579. }
  2580. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2581. if (!checkConst(SubobjType))
  2582. return false;
  2583. QualType PointeeType;
  2584. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2585. PointeeType = PT->getPointeeType();
  2586. if (PointeeType.isNull() || !RHS.isInt() ||
  2587. (Opcode != BO_Add && Opcode != BO_Sub)) {
  2588. Info.Diag(E);
  2589. return false;
  2590. }
  2591. int64_t Offset = getExtValue(RHS.getInt());
  2592. if (Opcode == BO_Sub)
  2593. Offset = -Offset;
  2594. LValue LVal;
  2595. LVal.setFrom(Info.Ctx, Subobj);
  2596. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  2597. return false;
  2598. LVal.moveInto(Subobj);
  2599. return true;
  2600. }
  2601. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2602. llvm_unreachable("shouldn't encounter string elements here");
  2603. }
  2604. };
  2605. } // end anonymous namespace
  2606. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  2607. /// Perform a compound assignment of LVal <op>= RVal.
  2608. static bool handleCompoundAssignment(
  2609. EvalInfo &Info, const Expr *E,
  2610. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  2611. BinaryOperatorKind Opcode, const APValue &RVal) {
  2612. if (LVal.Designator.Invalid)
  2613. return false;
  2614. if (!Info.getLangOpts().CPlusPlus14) {
  2615. Info.Diag(E);
  2616. return false;
  2617. }
  2618. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2619. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  2620. RVal };
  2621. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2622. }
  2623. namespace {
  2624. struct IncDecSubobjectHandler {
  2625. EvalInfo &Info;
  2626. const Expr *E;
  2627. AccessKinds AccessKind;
  2628. APValue *Old;
  2629. typedef bool result_type;
  2630. bool checkConst(QualType QT) {
  2631. // Assigning to a const object has undefined behavior.
  2632. if (QT.isConstQualified()) {
  2633. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2634. return false;
  2635. }
  2636. return true;
  2637. }
  2638. bool failed() { return false; }
  2639. bool found(APValue &Subobj, QualType SubobjType) {
  2640. // Stash the old value. Also clear Old, so we don't clobber it later
  2641. // if we're post-incrementing a complex.
  2642. if (Old) {
  2643. *Old = Subobj;
  2644. Old = nullptr;
  2645. }
  2646. switch (Subobj.getKind()) {
  2647. case APValue::Int:
  2648. return found(Subobj.getInt(), SubobjType);
  2649. case APValue::Float:
  2650. return found(Subobj.getFloat(), SubobjType);
  2651. case APValue::ComplexInt:
  2652. return found(Subobj.getComplexIntReal(),
  2653. SubobjType->castAs<ComplexType>()->getElementType()
  2654. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2655. case APValue::ComplexFloat:
  2656. return found(Subobj.getComplexFloatReal(),
  2657. SubobjType->castAs<ComplexType>()->getElementType()
  2658. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2659. case APValue::LValue:
  2660. return foundPointer(Subobj, SubobjType);
  2661. default:
  2662. // FIXME: can this happen?
  2663. Info.Diag(E);
  2664. return false;
  2665. }
  2666. }
  2667. bool found(APSInt &Value, QualType SubobjType) {
  2668. if (!checkConst(SubobjType))
  2669. return false;
  2670. if (!SubobjType->isIntegerType()) {
  2671. // We don't support increment / decrement on integer-cast-to-pointer
  2672. // values.
  2673. Info.Diag(E);
  2674. return false;
  2675. }
  2676. if (Old) *Old = APValue(Value);
  2677. // bool arithmetic promotes to int, and the conversion back to bool
  2678. // doesn't reduce mod 2^n, so special-case it.
  2679. if (SubobjType->isBooleanType()) {
  2680. if (AccessKind == AK_Increment)
  2681. Value = 1;
  2682. else
  2683. Value = !Value;
  2684. return true;
  2685. }
  2686. bool WasNegative = Value.isNegative();
  2687. if (AccessKind == AK_Increment) {
  2688. ++Value;
  2689. if (!WasNegative && Value.isNegative() &&
  2690. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2691. APSInt ActualValue(Value, /*IsUnsigned*/true);
  2692. HandleOverflow(Info, E, ActualValue, SubobjType);
  2693. }
  2694. } else {
  2695. --Value;
  2696. if (WasNegative && !Value.isNegative() &&
  2697. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2698. unsigned BitWidth = Value.getBitWidth();
  2699. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  2700. ActualValue.setBit(BitWidth);
  2701. HandleOverflow(Info, E, ActualValue, SubobjType);
  2702. }
  2703. }
  2704. return true;
  2705. }
  2706. bool found(APFloat &Value, QualType SubobjType) {
  2707. if (!checkConst(SubobjType))
  2708. return false;
  2709. if (Old) *Old = APValue(Value);
  2710. APFloat One(Value.getSemantics(), 1);
  2711. if (AccessKind == AK_Increment)
  2712. Value.add(One, APFloat::rmNearestTiesToEven);
  2713. else
  2714. Value.subtract(One, APFloat::rmNearestTiesToEven);
  2715. return true;
  2716. }
  2717. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2718. if (!checkConst(SubobjType))
  2719. return false;
  2720. QualType PointeeType;
  2721. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2722. PointeeType = PT->getPointeeType();
  2723. else {
  2724. Info.Diag(E);
  2725. return false;
  2726. }
  2727. LValue LVal;
  2728. LVal.setFrom(Info.Ctx, Subobj);
  2729. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  2730. AccessKind == AK_Increment ? 1 : -1))
  2731. return false;
  2732. LVal.moveInto(Subobj);
  2733. return true;
  2734. }
  2735. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2736. llvm_unreachable("shouldn't encounter string elements here");
  2737. }
  2738. };
  2739. } // end anonymous namespace
  2740. /// Perform an increment or decrement on LVal.
  2741. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2742. QualType LValType, bool IsIncrement, APValue *Old) {
  2743. if (LVal.Designator.Invalid)
  2744. return false;
  2745. if (!Info.getLangOpts().CPlusPlus14) {
  2746. Info.Diag(E);
  2747. return false;
  2748. }
  2749. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  2750. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  2751. IncDecSubobjectHandler Handler = { Info, E, AK, Old };
  2752. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2753. }
  2754. /// Build an lvalue for the object argument of a member function call.
  2755. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  2756. LValue &This) {
  2757. if (Object->getType()->isPointerType())
  2758. return EvaluatePointer(Object, This, Info);
  2759. if (Object->isGLValue())
  2760. return EvaluateLValue(Object, This, Info);
  2761. if (Object->getType()->isLiteralType(Info.Ctx))
  2762. return EvaluateTemporary(Object, This, Info);
  2763. Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  2764. return false;
  2765. }
  2766. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  2767. /// lvalue referring to the result.
  2768. ///
  2769. /// \param Info - Information about the ongoing evaluation.
  2770. /// \param LV - An lvalue referring to the base of the member pointer.
  2771. /// \param RHS - The member pointer expression.
  2772. /// \param IncludeMember - Specifies whether the member itself is included in
  2773. /// the resulting LValue subobject designator. This is not possible when
  2774. /// creating a bound member function.
  2775. /// \return The field or method declaration to which the member pointer refers,
  2776. /// or 0 if evaluation fails.
  2777. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  2778. QualType LVType,
  2779. LValue &LV,
  2780. const Expr *RHS,
  2781. bool IncludeMember = true) {
  2782. MemberPtr MemPtr;
  2783. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  2784. return nullptr;
  2785. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  2786. // member value, the behavior is undefined.
  2787. if (!MemPtr.getDecl()) {
  2788. // FIXME: Specific diagnostic.
  2789. Info.Diag(RHS);
  2790. return nullptr;
  2791. }
  2792. if (MemPtr.isDerivedMember()) {
  2793. // This is a member of some derived class. Truncate LV appropriately.
  2794. // The end of the derived-to-base path for the base object must match the
  2795. // derived-to-base path for the member pointer.
  2796. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  2797. LV.Designator.Entries.size()) {
  2798. Info.Diag(RHS);
  2799. return nullptr;
  2800. }
  2801. unsigned PathLengthToMember =
  2802. LV.Designator.Entries.size() - MemPtr.Path.size();
  2803. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  2804. const CXXRecordDecl *LVDecl = getAsBaseClass(
  2805. LV.Designator.Entries[PathLengthToMember + I]);
  2806. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  2807. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  2808. Info.Diag(RHS);
  2809. return nullptr;
  2810. }
  2811. }
  2812. // Truncate the lvalue to the appropriate derived class.
  2813. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  2814. PathLengthToMember))
  2815. return nullptr;
  2816. } else if (!MemPtr.Path.empty()) {
  2817. // Extend the LValue path with the member pointer's path.
  2818. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  2819. MemPtr.Path.size() + IncludeMember);
  2820. // Walk down to the appropriate base class.
  2821. if (const PointerType *PT = LVType->getAs<PointerType>())
  2822. LVType = PT->getPointeeType();
  2823. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  2824. assert(RD && "member pointer access on non-class-type expression");
  2825. // The first class in the path is that of the lvalue.
  2826. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  2827. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  2828. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  2829. return nullptr;
  2830. RD = Base;
  2831. }
  2832. // Finally cast to the class containing the member.
  2833. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  2834. MemPtr.getContainingRecord()))
  2835. return nullptr;
  2836. }
  2837. // Add the member. Note that we cannot build bound member functions here.
  2838. if (IncludeMember) {
  2839. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  2840. if (!HandleLValueMember(Info, RHS, LV, FD))
  2841. return nullptr;
  2842. } else if (const IndirectFieldDecl *IFD =
  2843. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  2844. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  2845. return nullptr;
  2846. } else {
  2847. llvm_unreachable("can't construct reference to bound member function");
  2848. }
  2849. }
  2850. return MemPtr.getDecl();
  2851. }
  2852. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  2853. const BinaryOperator *BO,
  2854. LValue &LV,
  2855. bool IncludeMember = true) {
  2856. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  2857. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  2858. if (Info.keepEvaluatingAfterFailure()) {
  2859. MemberPtr MemPtr;
  2860. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  2861. }
  2862. return nullptr;
  2863. }
  2864. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  2865. BO->getRHS(), IncludeMember);
  2866. }
  2867. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  2868. /// the provided lvalue, which currently refers to the base object.
  2869. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  2870. LValue &Result) {
  2871. SubobjectDesignator &D = Result.Designator;
  2872. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  2873. return false;
  2874. QualType TargetQT = E->getType();
  2875. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  2876. TargetQT = PT->getPointeeType();
  2877. // Check this cast lands within the final derived-to-base subobject path.
  2878. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  2879. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  2880. << D.MostDerivedType << TargetQT;
  2881. return false;
  2882. }
  2883. // Check the type of the final cast. We don't need to check the path,
  2884. // since a cast can only be formed if the path is unique.
  2885. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  2886. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  2887. const CXXRecordDecl *FinalType;
  2888. if (NewEntriesSize == D.MostDerivedPathLength)
  2889. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  2890. else
  2891. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  2892. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  2893. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  2894. << D.MostDerivedType << TargetQT;
  2895. return false;
  2896. }
  2897. // Truncate the lvalue to the appropriate derived class.
  2898. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  2899. }
  2900. namespace {
  2901. enum EvalStmtResult {
  2902. /// Evaluation failed.
  2903. ESR_Failed,
  2904. /// Hit a 'return' statement.
  2905. ESR_Returned,
  2906. /// Evaluation succeeded.
  2907. ESR_Succeeded,
  2908. /// Hit a 'continue' statement.
  2909. ESR_Continue,
  2910. /// Hit a 'break' statement.
  2911. ESR_Break,
  2912. /// Still scanning for 'case' or 'default' statement.
  2913. ESR_CaseNotFound
  2914. };
  2915. }
  2916. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  2917. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2918. // We don't need to evaluate the initializer for a static local.
  2919. if (!VD->hasLocalStorage())
  2920. return true;
  2921. LValue Result;
  2922. Result.set(VD, Info.CurrentCall->Index);
  2923. APValue &Val = Info.CurrentCall->createTemporary(VD, true);
  2924. const Expr *InitE = VD->getInit();
  2925. if (!InitE) {
  2926. Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
  2927. << false << VD->getType();
  2928. Val = APValue();
  2929. return false;
  2930. }
  2931. if (InitE->isValueDependent())
  2932. return false;
  2933. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  2934. // Wipe out any partially-computed value, to allow tracking that this
  2935. // evaluation failed.
  2936. Val = APValue();
  2937. return false;
  2938. }
  2939. }
  2940. return true;
  2941. }
  2942. /// Evaluate a condition (either a variable declaration or an expression).
  2943. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  2944. const Expr *Cond, bool &Result) {
  2945. FullExpressionRAII Scope(Info);
  2946. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  2947. return false;
  2948. return EvaluateAsBooleanCondition(Cond, Result, Info);
  2949. }
  2950. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  2951. const Stmt *S,
  2952. const SwitchCase *SC = nullptr);
  2953. /// Evaluate the body of a loop, and translate the result as appropriate.
  2954. static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
  2955. const Stmt *Body,
  2956. const SwitchCase *Case = nullptr) {
  2957. BlockScopeRAII Scope(Info);
  2958. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  2959. case ESR_Break:
  2960. return ESR_Succeeded;
  2961. case ESR_Succeeded:
  2962. case ESR_Continue:
  2963. return ESR_Continue;
  2964. case ESR_Failed:
  2965. case ESR_Returned:
  2966. case ESR_CaseNotFound:
  2967. return ESR;
  2968. }
  2969. llvm_unreachable("Invalid EvalStmtResult!");
  2970. }
  2971. /// Evaluate a switch statement.
  2972. static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
  2973. const SwitchStmt *SS) {
  2974. BlockScopeRAII Scope(Info);
  2975. // Evaluate the switch condition.
  2976. APSInt Value;
  2977. {
  2978. FullExpressionRAII Scope(Info);
  2979. if (SS->getConditionVariable() &&
  2980. !EvaluateDecl(Info, SS->getConditionVariable()))
  2981. return ESR_Failed;
  2982. if (!EvaluateInteger(SS->getCond(), Value, Info))
  2983. return ESR_Failed;
  2984. }
  2985. // Find the switch case corresponding to the value of the condition.
  2986. // FIXME: Cache this lookup.
  2987. const SwitchCase *Found = nullptr;
  2988. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  2989. SC = SC->getNextSwitchCase()) {
  2990. if (isa<DefaultStmt>(SC)) {
  2991. Found = SC;
  2992. continue;
  2993. }
  2994. const CaseStmt *CS = cast<CaseStmt>(SC);
  2995. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  2996. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  2997. : LHS;
  2998. if (LHS <= Value && Value <= RHS) {
  2999. Found = SC;
  3000. break;
  3001. }
  3002. }
  3003. if (!Found)
  3004. return ESR_Succeeded;
  3005. // Search the switch body for the switch case and evaluate it from there.
  3006. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3007. case ESR_Break:
  3008. return ESR_Succeeded;
  3009. case ESR_Succeeded:
  3010. case ESR_Continue:
  3011. case ESR_Failed:
  3012. case ESR_Returned:
  3013. return ESR;
  3014. case ESR_CaseNotFound:
  3015. // This can only happen if the switch case is nested within a statement
  3016. // expression. We have no intention of supporting that.
  3017. Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
  3018. return ESR_Failed;
  3019. }
  3020. llvm_unreachable("Invalid EvalStmtResult!");
  3021. }
  3022. // Evaluate a statement.
  3023. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  3024. const Stmt *S, const SwitchCase *Case) {
  3025. if (!Info.nextStep(S))
  3026. return ESR_Failed;
  3027. // If we're hunting down a 'case' or 'default' label, recurse through
  3028. // substatements until we hit the label.
  3029. if (Case) {
  3030. // FIXME: We don't start the lifetime of objects whose initialization we
  3031. // jump over. However, such objects must be of class type with a trivial
  3032. // default constructor that initialize all subobjects, so must be empty,
  3033. // so this almost never matters.
  3034. switch (S->getStmtClass()) {
  3035. case Stmt::CompoundStmtClass:
  3036. // FIXME: Precompute which substatement of a compound statement we
  3037. // would jump to, and go straight there rather than performing a
  3038. // linear scan each time.
  3039. case Stmt::LabelStmtClass:
  3040. case Stmt::AttributedStmtClass:
  3041. case Stmt::DoStmtClass:
  3042. break;
  3043. case Stmt::CaseStmtClass:
  3044. case Stmt::DefaultStmtClass:
  3045. if (Case == S)
  3046. Case = nullptr;
  3047. break;
  3048. case Stmt::IfStmtClass: {
  3049. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3050. // straight there rather than scanning both sides.
  3051. const IfStmt *IS = cast<IfStmt>(S);
  3052. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3053. // preceded by our switch label.
  3054. BlockScopeRAII Scope(Info);
  3055. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3056. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3057. return ESR;
  3058. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3059. }
  3060. case Stmt::WhileStmtClass: {
  3061. EvalStmtResult ESR =
  3062. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3063. if (ESR != ESR_Continue)
  3064. return ESR;
  3065. break;
  3066. }
  3067. case Stmt::ForStmtClass: {
  3068. const ForStmt *FS = cast<ForStmt>(S);
  3069. EvalStmtResult ESR =
  3070. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3071. if (ESR != ESR_Continue)
  3072. return ESR;
  3073. if (FS->getInc()) {
  3074. FullExpressionRAII IncScope(Info);
  3075. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3076. return ESR_Failed;
  3077. }
  3078. break;
  3079. }
  3080. case Stmt::DeclStmtClass:
  3081. // FIXME: If the variable has initialization that can't be jumped over,
  3082. // bail out of any immediately-surrounding compound-statement too.
  3083. default:
  3084. return ESR_CaseNotFound;
  3085. }
  3086. }
  3087. switch (S->getStmtClass()) {
  3088. default:
  3089. if (const Expr *E = dyn_cast<Expr>(S)) {
  3090. // Don't bother evaluating beyond an expression-statement which couldn't
  3091. // be evaluated.
  3092. FullExpressionRAII Scope(Info);
  3093. if (!EvaluateIgnoredValue(Info, E))
  3094. return ESR_Failed;
  3095. return ESR_Succeeded;
  3096. }
  3097. Info.Diag(S->getLocStart());
  3098. return ESR_Failed;
  3099. case Stmt::NullStmtClass:
  3100. return ESR_Succeeded;
  3101. case Stmt::DeclStmtClass: {
  3102. const DeclStmt *DS = cast<DeclStmt>(S);
  3103. for (const auto *DclIt : DS->decls()) {
  3104. // Each declaration initialization is its own full-expression.
  3105. // FIXME: This isn't quite right; if we're performing aggregate
  3106. // initialization, each braced subexpression is its own full-expression.
  3107. FullExpressionRAII Scope(Info);
  3108. if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
  3109. return ESR_Failed;
  3110. }
  3111. return ESR_Succeeded;
  3112. }
  3113. case Stmt::ReturnStmtClass: {
  3114. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3115. FullExpressionRAII Scope(Info);
  3116. if (RetExpr && !Evaluate(Result, Info, RetExpr))
  3117. return ESR_Failed;
  3118. return ESR_Returned;
  3119. }
  3120. case Stmt::CompoundStmtClass: {
  3121. BlockScopeRAII Scope(Info);
  3122. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3123. for (const auto *BI : CS->body()) {
  3124. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3125. if (ESR == ESR_Succeeded)
  3126. Case = nullptr;
  3127. else if (ESR != ESR_CaseNotFound)
  3128. return ESR;
  3129. }
  3130. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3131. }
  3132. case Stmt::IfStmtClass: {
  3133. const IfStmt *IS = cast<IfStmt>(S);
  3134. // Evaluate the condition, as either a var decl or as an expression.
  3135. BlockScopeRAII Scope(Info);
  3136. bool Cond;
  3137. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3138. return ESR_Failed;
  3139. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3140. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3141. if (ESR != ESR_Succeeded)
  3142. return ESR;
  3143. }
  3144. return ESR_Succeeded;
  3145. }
  3146. case Stmt::WhileStmtClass: {
  3147. const WhileStmt *WS = cast<WhileStmt>(S);
  3148. while (true) {
  3149. BlockScopeRAII Scope(Info);
  3150. bool Continue;
  3151. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3152. Continue))
  3153. return ESR_Failed;
  3154. if (!Continue)
  3155. break;
  3156. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3157. if (ESR != ESR_Continue)
  3158. return ESR;
  3159. }
  3160. return ESR_Succeeded;
  3161. }
  3162. case Stmt::DoStmtClass: {
  3163. const DoStmt *DS = cast<DoStmt>(S);
  3164. bool Continue;
  3165. do {
  3166. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3167. if (ESR != ESR_Continue)
  3168. return ESR;
  3169. Case = nullptr;
  3170. FullExpressionRAII CondScope(Info);
  3171. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3172. return ESR_Failed;
  3173. } while (Continue);
  3174. return ESR_Succeeded;
  3175. }
  3176. case Stmt::ForStmtClass: {
  3177. const ForStmt *FS = cast<ForStmt>(S);
  3178. BlockScopeRAII Scope(Info);
  3179. if (FS->getInit()) {
  3180. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3181. if (ESR != ESR_Succeeded)
  3182. return ESR;
  3183. }
  3184. while (true) {
  3185. BlockScopeRAII Scope(Info);
  3186. bool Continue = true;
  3187. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3188. FS->getCond(), Continue))
  3189. return ESR_Failed;
  3190. if (!Continue)
  3191. break;
  3192. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3193. if (ESR != ESR_Continue)
  3194. return ESR;
  3195. if (FS->getInc()) {
  3196. FullExpressionRAII IncScope(Info);
  3197. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3198. return ESR_Failed;
  3199. }
  3200. }
  3201. return ESR_Succeeded;
  3202. }
  3203. case Stmt::CXXForRangeStmtClass: {
  3204. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3205. BlockScopeRAII Scope(Info);
  3206. // Initialize the __range variable.
  3207. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3208. if (ESR != ESR_Succeeded)
  3209. return ESR;
  3210. // Create the __begin and __end iterators.
  3211. ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
  3212. if (ESR != ESR_Succeeded)
  3213. return ESR;
  3214. while (true) {
  3215. // Condition: __begin != __end.
  3216. {
  3217. bool Continue = true;
  3218. FullExpressionRAII CondExpr(Info);
  3219. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3220. return ESR_Failed;
  3221. if (!Continue)
  3222. break;
  3223. }
  3224. // User's variable declaration, initialized by *__begin.
  3225. BlockScopeRAII InnerScope(Info);
  3226. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3227. if (ESR != ESR_Succeeded)
  3228. return ESR;
  3229. // Loop body.
  3230. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3231. if (ESR != ESR_Continue)
  3232. return ESR;
  3233. // Increment: ++__begin
  3234. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3235. return ESR_Failed;
  3236. }
  3237. return ESR_Succeeded;
  3238. }
  3239. case Stmt::SwitchStmtClass:
  3240. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3241. case Stmt::ContinueStmtClass:
  3242. return ESR_Continue;
  3243. case Stmt::BreakStmtClass:
  3244. return ESR_Break;
  3245. case Stmt::LabelStmtClass:
  3246. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3247. case Stmt::AttributedStmtClass:
  3248. // As a general principle, C++11 attributes can be ignored without
  3249. // any semantic impact.
  3250. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3251. Case);
  3252. case Stmt::CaseStmtClass:
  3253. case Stmt::DefaultStmtClass:
  3254. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3255. }
  3256. }
  3257. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3258. /// default constructor. If so, we'll fold it whether or not it's marked as
  3259. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3260. /// so we need special handling.
  3261. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3262. const CXXConstructorDecl *CD,
  3263. bool IsValueInitialization) {
  3264. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3265. return false;
  3266. // Value-initialization does not call a trivial default constructor, so such a
  3267. // call is a core constant expression whether or not the constructor is
  3268. // constexpr.
  3269. if (!CD->isConstexpr() && !IsValueInitialization) {
  3270. if (Info.getLangOpts().CPlusPlus11) {
  3271. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3272. // we should be much more explicit about why it's not constexpr.
  3273. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3274. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3275. Info.Note(CD->getLocation(), diag::note_declared_at);
  3276. } else {
  3277. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3278. }
  3279. }
  3280. return true;
  3281. }
  3282. /// CheckConstexprFunction - Check that a function can be called in a constant
  3283. /// expression.
  3284. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3285. const FunctionDecl *Declaration,
  3286. const FunctionDecl *Definition) {
  3287. // Potential constant expressions can contain calls to declared, but not yet
  3288. // defined, constexpr functions.
  3289. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3290. Declaration->isConstexpr())
  3291. return false;
  3292. // Bail out with no diagnostic if the function declaration itself is invalid.
  3293. // We will have produced a relevant diagnostic while parsing it.
  3294. if (Declaration->isInvalidDecl())
  3295. return false;
  3296. // Can we evaluate this function call?
  3297. if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
  3298. return true;
  3299. if (Info.getLangOpts().CPlusPlus11) {
  3300. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3301. // FIXME: If DiagDecl is an implicitly-declared special member function, we
  3302. // should be much more explicit about why it's not constexpr.
  3303. Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3304. << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
  3305. << DiagDecl;
  3306. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3307. } else {
  3308. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3309. }
  3310. return false;
  3311. }
  3312. /// Determine if a class has any fields that might need to be copied by a
  3313. /// trivial copy or move operation.
  3314. static bool hasFields(const CXXRecordDecl *RD) {
  3315. if (!RD || RD->isEmpty())
  3316. return false;
  3317. for (auto *FD : RD->fields()) {
  3318. if (FD->isUnnamedBitfield())
  3319. continue;
  3320. return true;
  3321. }
  3322. for (auto &Base : RD->bases())
  3323. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3324. return true;
  3325. return false;
  3326. }
  3327. namespace {
  3328. typedef SmallVector<APValue, 8> ArgVector;
  3329. }
  3330. /// EvaluateArgs - Evaluate the arguments to a function call.
  3331. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3332. EvalInfo &Info) {
  3333. bool Success = true;
  3334. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3335. I != E; ++I) {
  3336. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3337. // If we're checking for a potential constant expression, evaluate all
  3338. // initializers even if some of them fail.
  3339. if (!Info.keepEvaluatingAfterFailure())
  3340. return false;
  3341. Success = false;
  3342. }
  3343. }
  3344. return Success;
  3345. }
  3346. // HLSL Change Starts
  3347. /// Evaluate an HLSL intrinsic call.
  3348. static bool HandleIntrinsicCall(SourceLocation CallLoc, unsigned opcode,
  3349. const LValue *This, ArrayRef<const Expr *> Args,
  3350. EvalInfo &Info, APValue &Result) {
  3351. ArgVector ArgValues(Args.size());
  3352. if (!EvaluateArgs(Args, ArgValues, Info))
  3353. return false;
  3354. if (!Info.CheckCallLimit(CallLoc))
  3355. return false;
  3356. switch ((hlsl::IntrinsicOp)opcode) {
  3357. case hlsl::IntrinsicOp::IOP_asuint:
  3358. assert(Args.size() == 1 && "else call should be invalid");
  3359. if (ArgValues[0].isInt()) {
  3360. Result = ArgValues[0];
  3361. }
  3362. else if (ArgValues[0].isFloat()) {
  3363. const bool isUnsignedTrue = true;
  3364. Result = APValue(APSInt(ArgValues[0].getFloat().bitcastToAPInt(), isUnsignedTrue));
  3365. }
  3366. else {
  3367. // TODO: consider a better error message here
  3368. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3369. return false;
  3370. }
  3371. return true;
  3372. case hlsl::IntrinsicOp::IOP_max:
  3373. assert(Args.size() == 2 && "else call should be invalid");
  3374. assert(ArgValues[0].getKind() == ArgValues[1].getKind() && "else call is invalid");
  3375. if (ArgValues[0].isInt()) {
  3376. Result = ArgValues[0].getInt() > ArgValues[1].getInt() ? ArgValues[0] : ArgValues[1];
  3377. }
  3378. else if (ArgValues[0].isFloat()) {
  3379. // TODO: handle NaNs properly
  3380. APFloat::cmpResult r = ArgValues[0].getFloat().compare(ArgValues[1].getFloat());
  3381. Result = (r == APFloat::cmpGreaterThan) ? ArgValues[0] : ArgValues[1];
  3382. }
  3383. else {
  3384. // TODO: consider a better error message here
  3385. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3386. return false;
  3387. }
  3388. return true;
  3389. default:
  3390. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3391. return false;
  3392. }
  3393. }
  3394. // HLSL Change Ends
  3395. /// Evaluate a function call.
  3396. static bool HandleFunctionCall(SourceLocation CallLoc,
  3397. const FunctionDecl *Callee, const LValue *This,
  3398. ArrayRef<const Expr*> Args, const Stmt *Body,
  3399. EvalInfo &Info, APValue &Result) {
  3400. ArgVector ArgValues(Args.size());
  3401. if (!EvaluateArgs(Args, ArgValues, Info))
  3402. return false;
  3403. if (!Info.CheckCallLimit(CallLoc))
  3404. return false;
  3405. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3406. // For a trivial copy or move assignment, perform an APValue copy. This is
  3407. // essential for unions, where the operations performed by the assignment
  3408. // operator cannot be represented as statements.
  3409. //
  3410. // Skip this for non-union classes with no fields; in that case, the defaulted
  3411. // copy/move does not actually read the object.
  3412. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3413. if (MD && MD->isDefaulted() &&
  3414. (MD->getParent()->isUnion() ||
  3415. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3416. assert(This &&
  3417. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3418. LValue RHS;
  3419. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3420. APValue RHSValue;
  3421. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3422. RHS, RHSValue))
  3423. return false;
  3424. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3425. RHSValue))
  3426. return false;
  3427. This->moveInto(Result);
  3428. return true;
  3429. }
  3430. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
  3431. if (ESR == ESR_Succeeded) {
  3432. if (Callee->getReturnType()->isVoidType())
  3433. return true;
  3434. Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
  3435. }
  3436. return ESR == ESR_Returned;
  3437. }
  3438. /// Evaluate a constructor call.
  3439. static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
  3440. ArrayRef<const Expr*> Args,
  3441. const CXXConstructorDecl *Definition,
  3442. EvalInfo &Info, APValue &Result) {
  3443. ArgVector ArgValues(Args.size());
  3444. if (!EvaluateArgs(Args, ArgValues, Info))
  3445. return false;
  3446. if (!Info.CheckCallLimit(CallLoc))
  3447. return false;
  3448. const CXXRecordDecl *RD = Definition->getParent();
  3449. if (RD->getNumVBases()) {
  3450. Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3451. return false;
  3452. }
  3453. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
  3454. // If it's a delegating constructor, just delegate.
  3455. if (Definition->isDelegatingConstructor()) {
  3456. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3457. {
  3458. FullExpressionRAII InitScope(Info);
  3459. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3460. return false;
  3461. }
  3462. return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
  3463. }
  3464. // For a trivial copy or move constructor, perform an APValue copy. This is
  3465. // essential for unions (or classes with anonymous union members), where the
  3466. // operations performed by the constructor cannot be represented by
  3467. // ctor-initializers.
  3468. //
  3469. // Skip this for empty non-union classes; we should not perform an
  3470. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3471. // actually read them.
  3472. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  3473. (Definition->getParent()->isUnion() ||
  3474. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  3475. LValue RHS;
  3476. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3477. return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3478. RHS, Result);
  3479. }
  3480. // Reserve space for the struct members.
  3481. if (!RD->isUnion() && Result.isUninit())
  3482. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3483. std::distance(RD->field_begin(), RD->field_end()));
  3484. if (RD->isInvalidDecl()) return false;
  3485. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  3486. // A scope for temporaries lifetime-extended by reference members.
  3487. BlockScopeRAII LifetimeExtendedScope(Info);
  3488. bool Success = true;
  3489. unsigned BasesSeen = 0;
  3490. #ifndef NDEBUG
  3491. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  3492. #endif
  3493. for (const auto *I : Definition->inits()) {
  3494. LValue Subobject = This;
  3495. APValue *Value = &Result;
  3496. // Determine the subobject to initialize.
  3497. FieldDecl *FD = nullptr;
  3498. if (I->isBaseInitializer()) {
  3499. QualType BaseType(I->getBaseClass(), 0);
  3500. #ifndef NDEBUG
  3501. // Non-virtual base classes are initialized in the order in the class
  3502. // definition. We have already checked for virtual base classes.
  3503. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  3504. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  3505. "base class initializers not in expected order");
  3506. ++BaseIt;
  3507. #endif
  3508. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  3509. BaseType->getAsCXXRecordDecl(), &Layout))
  3510. return false;
  3511. Value = &Result.getStructBase(BasesSeen++);
  3512. } else if ((FD = I->getMember())) {
  3513. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  3514. return false;
  3515. if (RD->isUnion()) {
  3516. Result = APValue(FD);
  3517. Value = &Result.getUnionValue();
  3518. } else {
  3519. Value = &Result.getStructField(FD->getFieldIndex());
  3520. }
  3521. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  3522. // Walk the indirect field decl's chain to find the object to initialize,
  3523. // and make sure we've initialized every step along it.
  3524. for (auto *C : IFD->chain()) {
  3525. FD = cast<FieldDecl>(C);
  3526. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  3527. // Switch the union field if it differs. This happens if we had
  3528. // preceding zero-initialization, and we're now initializing a union
  3529. // subobject other than the first.
  3530. // FIXME: In this case, the values of the other subobjects are
  3531. // specified, since zero-initialization sets all padding bits to zero.
  3532. if (Value->isUninit() ||
  3533. (Value->isUnion() && Value->getUnionField() != FD)) {
  3534. if (CD->isUnion())
  3535. *Value = APValue(FD);
  3536. else
  3537. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  3538. std::distance(CD->field_begin(), CD->field_end()));
  3539. }
  3540. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  3541. return false;
  3542. if (CD->isUnion())
  3543. Value = &Value->getUnionValue();
  3544. else
  3545. Value = &Value->getStructField(FD->getFieldIndex());
  3546. }
  3547. } else {
  3548. llvm_unreachable("unknown base initializer kind");
  3549. }
  3550. FullExpressionRAII InitScope(Info);
  3551. if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
  3552. (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
  3553. *Value, FD))) {
  3554. // If we're checking for a potential constant expression, evaluate all
  3555. // initializers even if some of them fail.
  3556. if (!Info.keepEvaluatingAfterFailure())
  3557. return false;
  3558. Success = false;
  3559. }
  3560. }
  3561. return Success &&
  3562. EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
  3563. }
  3564. //===----------------------------------------------------------------------===//
  3565. // Generic Evaluation
  3566. //===----------------------------------------------------------------------===//
  3567. namespace {
  3568. template <class Derived>
  3569. class ExprEvaluatorBase
  3570. : public ConstStmtVisitor<Derived, bool> {
  3571. private:
  3572. bool DerivedSuccess(const APValue &V, const Expr *E) {
  3573. return static_cast<Derived*>(this)->Success(V, E);
  3574. }
  3575. bool DerivedZeroInitialization(const Expr *E) {
  3576. return static_cast<Derived*>(this)->ZeroInitialization(E);
  3577. }
  3578. // Check whether a conditional operator with a non-constant condition is a
  3579. // potential constant expression. If neither arm is a potential constant
  3580. // expression, then the conditional operator is not either.
  3581. template<typename ConditionalOperator>
  3582. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  3583. assert(Info.checkingPotentialConstantExpression());
  3584. // Speculatively evaluate both arms.
  3585. {
  3586. SmallVector<PartialDiagnosticAt, 8> Diag;
  3587. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  3588. StmtVisitorTy::Visit(E->getFalseExpr());
  3589. if (Diag.empty())
  3590. return;
  3591. Diag.clear();
  3592. StmtVisitorTy::Visit(E->getTrueExpr());
  3593. if (Diag.empty())
  3594. return;
  3595. }
  3596. Error(E, diag::note_constexpr_conditional_never_const);
  3597. }
  3598. template<typename ConditionalOperator>
  3599. bool HandleConditionalOperator(const ConditionalOperator *E) {
  3600. bool BoolResult;
  3601. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  3602. if (Info.checkingPotentialConstantExpression())
  3603. CheckPotentialConstantConditional(E);
  3604. return false;
  3605. }
  3606. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  3607. return StmtVisitorTy::Visit(EvalExpr);
  3608. }
  3609. protected:
  3610. EvalInfo &Info;
  3611. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  3612. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  3613. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  3614. return Info.CCEDiag(E, D);
  3615. }
  3616. bool ZeroInitialization(const Expr *E) { return Error(E); }
  3617. public:
  3618. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  3619. EvalInfo &getEvalInfo() { return Info; }
  3620. /// Report an evaluation error. This should only be called when an error is
  3621. /// first discovered. When propagating an error, just return false.
  3622. bool Error(const Expr *E, diag::kind D) {
  3623. Info.Diag(E, D);
  3624. return false;
  3625. }
  3626. bool Error(const Expr *E) {
  3627. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  3628. }
  3629. bool VisitStmt(const Stmt *) {
  3630. llvm_unreachable("Expression evaluator should not be called on stmts");
  3631. }
  3632. bool VisitExpr(const Expr *E) {
  3633. return Error(E);
  3634. }
  3635. bool VisitParenExpr(const ParenExpr *E)
  3636. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3637. bool VisitUnaryExtension(const UnaryOperator *E)
  3638. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3639. bool VisitUnaryPlus(const UnaryOperator *E)
  3640. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3641. bool VisitChooseExpr(const ChooseExpr *E)
  3642. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  3643. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  3644. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  3645. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  3646. { return StmtVisitorTy::Visit(E->getReplacement()); }
  3647. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  3648. { return StmtVisitorTy::Visit(E->getExpr()); }
  3649. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  3650. // The initializer may not have been parsed yet, or might be erroneous.
  3651. if (!E->getExpr())
  3652. return Error(E);
  3653. return StmtVisitorTy::Visit(E->getExpr());
  3654. }
  3655. // We cannot create any objects for which cleanups are required, so there is
  3656. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  3657. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  3658. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3659. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  3660. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  3661. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3662. }
  3663. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  3664. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  3665. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3666. }
  3667. bool VisitBinaryOperator(const BinaryOperator *E) {
  3668. switch (E->getOpcode()) {
  3669. default:
  3670. return Error(E);
  3671. case BO_Comma:
  3672. VisitIgnoredValue(E->getLHS());
  3673. return StmtVisitorTy::Visit(E->getRHS());
  3674. case BO_PtrMemD:
  3675. case BO_PtrMemI: {
  3676. LValue Obj;
  3677. if (!HandleMemberPointerAccess(Info, E, Obj))
  3678. return false;
  3679. APValue Result;
  3680. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  3681. return false;
  3682. return DerivedSuccess(Result, E);
  3683. }
  3684. }
  3685. }
  3686. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  3687. // Evaluate and cache the common expression. We treat it as a temporary,
  3688. // even though it's not quite the same thing.
  3689. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  3690. Info, E->getCommon()))
  3691. return false;
  3692. return HandleConditionalOperator(E);
  3693. }
  3694. bool VisitConditionalOperator(const ConditionalOperator *E) {
  3695. bool IsBcpCall = false;
  3696. // If the condition (ignoring parens) is a __builtin_constant_p call,
  3697. // the result is a constant expression if it can be folded without
  3698. // side-effects. This is an important GNU extension. See GCC PR38377
  3699. // for discussion.
  3700. if (const CallExpr *CallCE =
  3701. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  3702. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  3703. IsBcpCall = true;
  3704. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  3705. // constant expression; we can't check whether it's potentially foldable.
  3706. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  3707. return false;
  3708. FoldConstant Fold(Info, IsBcpCall);
  3709. if (!HandleConditionalOperator(E)) {
  3710. Fold.keepDiagnostics();
  3711. return false;
  3712. }
  3713. return true;
  3714. }
  3715. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  3716. if (APValue *Value = Info.CurrentCall->getTemporary(E))
  3717. return DerivedSuccess(*Value, E);
  3718. const Expr *Source = E->getSourceExpr();
  3719. if (!Source)
  3720. return Error(E);
  3721. if (Source == E) { // sanity checking.
  3722. assert(0 && "OpaqueValueExpr recursively refers to itself");
  3723. return Error(E);
  3724. }
  3725. return StmtVisitorTy::Visit(Source);
  3726. }
  3727. bool VisitCallExpr(const CallExpr *E) {
  3728. const Expr *Callee = E->getCallee()->IgnoreParens();
  3729. QualType CalleeType = Callee->getType();
  3730. const FunctionDecl *FD = nullptr;
  3731. LValue *This = nullptr, ThisVal;
  3732. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  3733. bool HasQualifier = false;
  3734. // Extract function decl and 'this' pointer from the callee.
  3735. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  3736. const ValueDecl *Member = nullptr;
  3737. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  3738. // Explicit bound member calls, such as x.f() or p->g();
  3739. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  3740. return false;
  3741. Member = ME->getMemberDecl();
  3742. This = &ThisVal;
  3743. HasQualifier = ME->hasQualifier();
  3744. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  3745. // Indirect bound member calls ('.*' or '->*').
  3746. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  3747. if (!Member) return false;
  3748. This = &ThisVal;
  3749. } else
  3750. return Error(Callee);
  3751. FD = dyn_cast<FunctionDecl>(Member);
  3752. if (!FD)
  3753. return Error(Callee);
  3754. } else if (CalleeType->isFunctionPointerType()) {
  3755. LValue Call;
  3756. if (!EvaluatePointer(Callee, Call, Info))
  3757. return false;
  3758. if (!Call.getLValueOffset().isZero())
  3759. return Error(Callee);
  3760. FD = dyn_cast_or_null<FunctionDecl>(
  3761. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  3762. if (!FD)
  3763. return Error(Callee);
  3764. // Overloaded operator calls to member functions are represented as normal
  3765. // calls with '*this' as the first argument.
  3766. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  3767. if (MD && !MD->isStatic()) {
  3768. // FIXME: When selecting an implicit conversion for an overloaded
  3769. // operator delete, we sometimes try to evaluate calls to conversion
  3770. // operators without a 'this' parameter!
  3771. if (Args.empty())
  3772. return Error(E);
  3773. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  3774. return false;
  3775. This = &ThisVal;
  3776. Args = Args.slice(1);
  3777. }
  3778. // Don't call function pointers which have been cast to some other type.
  3779. if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
  3780. return Error(E);
  3781. } else
  3782. return Error(E);
  3783. if (This && !This->checkSubobject(Info, E, CSK_This))
  3784. return false;
  3785. // HLSL Changes Start
  3786. {
  3787. unsigned opcode;
  3788. StringRef group;
  3789. if (hlsl::GetIntrinsicOp(FD, opcode, group)) {
  3790. APValue opResult;
  3791. if (!HandleIntrinsicCall(E->getExprLoc(), opcode, This, Args, Info,
  3792. opResult)) {
  3793. return false;
  3794. }
  3795. return DerivedSuccess(opResult, E);
  3796. }
  3797. }
  3798. // HLSL Changes End
  3799. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  3800. // calls to such functions in constant expressions.
  3801. if (This && !HasQualifier &&
  3802. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  3803. return Error(E, diag::note_constexpr_virtual_call);
  3804. const FunctionDecl *Definition = nullptr;
  3805. Stmt *Body = FD->getBody(Definition);
  3806. APValue Result;
  3807. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
  3808. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
  3809. Info, Result))
  3810. return false;
  3811. return DerivedSuccess(Result, E);
  3812. }
  3813. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  3814. return StmtVisitorTy::Visit(E->getInitializer());
  3815. }
  3816. bool VisitInitListExpr(const InitListExpr *E) {
  3817. if (E->getNumInits() == 0)
  3818. return DerivedZeroInitialization(E);
  3819. if (Info.getLangOpts().HLSL && !E->getType()->isScalarType() && !IsHLSLVecInitList(E)) return Error(E); // HLSL Change
  3820. if (E->getNumInits() == 1)
  3821. return StmtVisitorTy::Visit(E->getInit(0));
  3822. return Error(E);
  3823. }
  3824. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  3825. return DerivedZeroInitialization(E);
  3826. }
  3827. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  3828. return DerivedZeroInitialization(E);
  3829. }
  3830. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  3831. return DerivedZeroInitialization(E);
  3832. }
  3833. /// A member expression where the object is a prvalue is itself a prvalue.
  3834. bool VisitMemberExpr(const MemberExpr *E) {
  3835. assert(!E->isArrow() && "missing call to bound member function?");
  3836. APValue Val;
  3837. if (!Evaluate(Val, Info, E->getBase()))
  3838. return false;
  3839. QualType BaseTy = E->getBase()->getType();
  3840. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  3841. if (!FD) return Error(E);
  3842. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  3843. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  3844. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  3845. CompleteObject Obj(&Val, BaseTy);
  3846. SubobjectDesignator Designator(BaseTy);
  3847. Designator.addDeclUnchecked(FD);
  3848. APValue Result;
  3849. return extractSubobject(Info, E, Obj, Designator, Result) &&
  3850. DerivedSuccess(Result, E);
  3851. }
  3852. bool VisitCastExpr(const CastExpr *E) {
  3853. // HLSL Change Begins
  3854. if (Info.getLangOpts().HLSL) {
  3855. const auto* subExpr = E->getSubExpr();
  3856. if (subExpr->getStmtClass() == Stmt::InitListExprClass && !IsHLSLVecInitList(subExpr) && !subExpr->getType()->isScalarType())
  3857. return Error(E);
  3858. }
  3859. // HLSL Change Ends
  3860. switch (E->getCastKind()) {
  3861. default:
  3862. break;
  3863. case CK_AtomicToNonAtomic: {
  3864. APValue AtomicVal;
  3865. if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
  3866. return false;
  3867. return DerivedSuccess(AtomicVal, E);
  3868. }
  3869. case CK_NoOp:
  3870. case CK_UserDefinedConversion:
  3871. return StmtVisitorTy::Visit(E->getSubExpr());
  3872. case CK_LValueToRValue: {
  3873. LValue LVal;
  3874. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  3875. return false;
  3876. APValue RVal;
  3877. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  3878. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  3879. LVal, RVal))
  3880. return false;
  3881. return DerivedSuccess(RVal, E);
  3882. }
  3883. }
  3884. return Error(E);
  3885. }
  3886. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  3887. return VisitUnaryPostIncDec(UO);
  3888. }
  3889. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  3890. return VisitUnaryPostIncDec(UO);
  3891. }
  3892. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  3893. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  3894. return Error(UO);
  3895. LValue LVal;
  3896. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  3897. return false;
  3898. APValue RVal;
  3899. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  3900. UO->isIncrementOp(), &RVal))
  3901. return false;
  3902. return DerivedSuccess(RVal, UO);
  3903. }
  3904. bool VisitStmtExpr(const StmtExpr *E) {
  3905. // We will have checked the full-expressions inside the statement expression
  3906. // when they were completed, and don't need to check them again now.
  3907. if (Info.checkingForOverflow())
  3908. return Error(E);
  3909. BlockScopeRAII Scope(Info);
  3910. const CompoundStmt *CS = E->getSubStmt();
  3911. if (CS->body_empty())
  3912. return true;
  3913. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  3914. BE = CS->body_end();
  3915. /**/; ++BI) {
  3916. if (BI + 1 == BE) {
  3917. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  3918. if (!FinalExpr) {
  3919. Info.Diag((*BI)->getLocStart(),
  3920. diag::note_constexpr_stmt_expr_unsupported);
  3921. return false;
  3922. }
  3923. return this->Visit(FinalExpr);
  3924. }
  3925. APValue ReturnValue;
  3926. EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
  3927. if (ESR != ESR_Succeeded) {
  3928. // FIXME: If the statement-expression terminated due to 'return',
  3929. // 'break', or 'continue', it would be nice to propagate that to
  3930. // the outer statement evaluation rather than bailing out.
  3931. if (ESR != ESR_Failed)
  3932. Info.Diag((*BI)->getLocStart(),
  3933. diag::note_constexpr_stmt_expr_unsupported);
  3934. return false;
  3935. }
  3936. }
  3937. llvm_unreachable("Return from function from the loop above.");
  3938. }
  3939. /// Visit a value which is evaluated, but whose value is ignored.
  3940. void VisitIgnoredValue(const Expr *E) {
  3941. EvaluateIgnoredValue(Info, E);
  3942. }
  3943. };
  3944. }
  3945. //===----------------------------------------------------------------------===//
  3946. // Common base class for lvalue and temporary evaluation.
  3947. //===----------------------------------------------------------------------===//
  3948. namespace {
  3949. template<class Derived>
  3950. class LValueExprEvaluatorBase
  3951. : public ExprEvaluatorBase<Derived> {
  3952. protected:
  3953. LValue &Result;
  3954. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  3955. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  3956. bool Success(APValue::LValueBase B) {
  3957. Result.set(B);
  3958. return true;
  3959. }
  3960. public:
  3961. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  3962. ExprEvaluatorBaseTy(Info), Result(Result) {}
  3963. bool Success(const APValue &V, const Expr *E) {
  3964. Result.setFrom(this->Info.Ctx, V);
  3965. return true;
  3966. }
  3967. bool VisitMemberExpr(const MemberExpr *E) {
  3968. // Handle non-static data members.
  3969. QualType BaseTy;
  3970. if (E->isArrow()) {
  3971. if (!EvaluatePointer(E->getBase(), Result, this->Info))
  3972. return false;
  3973. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  3974. } else if (E->getBase()->isRValue()) {
  3975. assert(E->getBase()->getType()->isRecordType());
  3976. if (!EvaluateTemporary(E->getBase(), Result, this->Info))
  3977. return false;
  3978. BaseTy = E->getBase()->getType();
  3979. } else {
  3980. if (!this->Visit(E->getBase()))
  3981. return false;
  3982. BaseTy = E->getBase()->getType();
  3983. }
  3984. const ValueDecl *MD = E->getMemberDecl();
  3985. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  3986. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  3987. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  3988. (void)BaseTy;
  3989. if (!HandleLValueMember(this->Info, E, Result, FD))
  3990. return false;
  3991. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  3992. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  3993. return false;
  3994. } else
  3995. return this->Error(E);
  3996. if (MD->getType()->isReferenceType()) {
  3997. APValue RefValue;
  3998. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  3999. RefValue))
  4000. return false;
  4001. return Success(RefValue, E);
  4002. }
  4003. return true;
  4004. }
  4005. bool VisitBinaryOperator(const BinaryOperator *E) {
  4006. switch (E->getOpcode()) {
  4007. default:
  4008. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4009. case BO_PtrMemD:
  4010. case BO_PtrMemI:
  4011. return HandleMemberPointerAccess(this->Info, E, Result);
  4012. }
  4013. }
  4014. bool VisitCastExpr(const CastExpr *E) {
  4015. switch (E->getCastKind()) {
  4016. default:
  4017. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4018. case CK_DerivedToBase:
  4019. case CK_UncheckedDerivedToBase:
  4020. if (!this->Visit(E->getSubExpr()))
  4021. return false;
  4022. // Now figure out the necessary offset to add to the base LV to get from
  4023. // the derived class to the base class.
  4024. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4025. Result);
  4026. }
  4027. }
  4028. };
  4029. }
  4030. //===----------------------------------------------------------------------===//
  4031. // LValue Evaluation
  4032. //
  4033. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4034. // function designators (in C), decl references to void objects (in C), and
  4035. // temporaries (if building with -Wno-address-of-temporary).
  4036. //
  4037. // LValue evaluation produces values comprising a base expression of one of the
  4038. // following types:
  4039. // - Declarations
  4040. // * VarDecl
  4041. // * FunctionDecl
  4042. // - Literals
  4043. // * CompoundLiteralExpr in C
  4044. // * StringLiteral
  4045. // * CXXTypeidExpr
  4046. // * PredefinedExpr
  4047. // * ObjCStringLiteralExpr
  4048. // * ObjCEncodeExpr
  4049. // * AddrLabelExpr
  4050. // * BlockExpr
  4051. // * CallExpr for a MakeStringConstant builtin
  4052. // - Locals and temporaries
  4053. // * MaterializeTemporaryExpr
  4054. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4055. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4056. // from the AST (FIXME).
  4057. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4058. // CallIndex, for a lifetime-extended temporary.
  4059. // plus an offset in bytes.
  4060. //===----------------------------------------------------------------------===//
  4061. namespace {
  4062. class LValueExprEvaluator
  4063. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4064. public:
  4065. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  4066. LValueExprEvaluatorBaseTy(Info, Result) {}
  4067. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4068. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4069. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4070. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4071. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4072. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4073. bool VisitMemberExpr(const MemberExpr *E);
  4074. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4075. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4076. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4077. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4078. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4079. bool VisitUnaryDeref(const UnaryOperator *E);
  4080. bool VisitUnaryReal(const UnaryOperator *E);
  4081. bool VisitUnaryImag(const UnaryOperator *E);
  4082. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4083. return VisitUnaryPreIncDec(UO);
  4084. }
  4085. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4086. return VisitUnaryPreIncDec(UO);
  4087. }
  4088. bool VisitBinAssign(const BinaryOperator *BO);
  4089. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4090. bool VisitCastExpr(const CastExpr *E) {
  4091. switch (E->getCastKind()) {
  4092. default:
  4093. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4094. case CK_LValueBitCast:
  4095. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4096. if (!Visit(E->getSubExpr()))
  4097. return false;
  4098. Result.Designator.setInvalid();
  4099. return true;
  4100. case CK_BaseToDerived:
  4101. if (!Visit(E->getSubExpr()))
  4102. return false;
  4103. return HandleBaseToDerivedCast(Info, E, Result);
  4104. }
  4105. }
  4106. };
  4107. } // end anonymous namespace
  4108. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4109. /// expressions which are not glvalues, in two cases:
  4110. /// * function designators in C, and
  4111. /// * "extern void" objects
  4112. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
  4113. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4114. E->getType()->isVoidType());
  4115. return LValueExprEvaluator(Info, Result).Visit(E);
  4116. }
  4117. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4118. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4119. return Success(FD);
  4120. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4121. return VisitVarDecl(E, VD);
  4122. return Error(E);
  4123. }
  4124. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4125. CallStackFrame *Frame = nullptr;
  4126. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
  4127. Frame = Info.CurrentCall;
  4128. if (!VD->getType()->isReferenceType()) {
  4129. if (Frame) {
  4130. Result.set(VD, Frame->Index);
  4131. return true;
  4132. }
  4133. return Success(VD);
  4134. }
  4135. APValue *V;
  4136. if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
  4137. return false;
  4138. if (V->isUninit()) {
  4139. if (!Info.checkingPotentialConstantExpression())
  4140. Info.Diag(E, diag::note_constexpr_use_uninit_reference);
  4141. return false;
  4142. }
  4143. return Success(*V, E);
  4144. }
  4145. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4146. const MaterializeTemporaryExpr *E) {
  4147. // Walk through the expression to find the materialized temporary itself.
  4148. SmallVector<const Expr *, 2> CommaLHSs;
  4149. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4150. const Expr *Inner = E->GetTemporaryExpr()->
  4151. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4152. // If we passed any comma operators, evaluate their LHSs.
  4153. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4154. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4155. return false;
  4156. // A materialized temporary with static storage duration can appear within the
  4157. // result of a constant expression evaluation, so we need to preserve its
  4158. // value for use outside this evaluation.
  4159. APValue *Value;
  4160. if (E->getStorageDuration() == SD_Static) {
  4161. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4162. *Value = APValue();
  4163. Result.set(E);
  4164. } else {
  4165. Value = &Info.CurrentCall->
  4166. createTemporary(E, E->getStorageDuration() == SD_Automatic);
  4167. Result.set(E, Info.CurrentCall->Index);
  4168. }
  4169. QualType Type = Inner->getType();
  4170. // Materialize the temporary itself.
  4171. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4172. (E->getStorageDuration() == SD_Static &&
  4173. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4174. *Value = APValue();
  4175. return false;
  4176. }
  4177. // Adjust our lvalue to refer to the desired subobject.
  4178. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4179. --I;
  4180. switch (Adjustments[I].Kind) {
  4181. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4182. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4183. Type, Result))
  4184. return false;
  4185. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4186. break;
  4187. case SubobjectAdjustment::FieldAdjustment:
  4188. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4189. return false;
  4190. Type = Adjustments[I].Field->getType();
  4191. break;
  4192. case SubobjectAdjustment::MemberPointerAdjustment:
  4193. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4194. Adjustments[I].Ptr.RHS))
  4195. return false;
  4196. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4197. break;
  4198. }
  4199. }
  4200. return true;
  4201. }
  4202. bool
  4203. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4204. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  4205. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4206. // only see this when folding in C, so there's no standard to follow here.
  4207. return Success(E);
  4208. }
  4209. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4210. if (!E->isPotentiallyEvaluated())
  4211. return Success(E);
  4212. Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
  4213. << E->getExprOperand()->getType()
  4214. << E->getExprOperand()->getSourceRange();
  4215. return false;
  4216. }
  4217. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4218. return Success(E);
  4219. }
  4220. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4221. // Handle static data members.
  4222. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4223. VisitIgnoredValue(E->getBase());
  4224. return VisitVarDecl(E, VD);
  4225. }
  4226. // Handle static member functions.
  4227. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4228. if (MD->isStatic()) {
  4229. VisitIgnoredValue(E->getBase());
  4230. return Success(MD);
  4231. }
  4232. }
  4233. // Handle non-static data members.
  4234. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4235. }
  4236. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4237. // FIXME: Deal with vectors as array subscript bases.
  4238. if (E->getBase()->getType()->isVectorType())
  4239. return Error(E);
  4240. if (this->getEvalInfo().Ctx.getLangOpts().HLSL) { // HLSL Change
  4241. return Error(E); // TODO: handle arrays
  4242. } else {
  4243. if (!EvaluatePointer(E->getBase(), Result, Info))
  4244. return false;
  4245. }
  4246. APSInt Index;
  4247. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4248. return false;
  4249. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
  4250. getExtValue(Index));
  4251. }
  4252. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4253. return EvaluatePointer(E->getSubExpr(), Result, Info);
  4254. }
  4255. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4256. if (!Visit(E->getSubExpr()))
  4257. return false;
  4258. // __real is a no-op on scalar lvalues.
  4259. if (E->getSubExpr()->getType()->isAnyComplexType())
  4260. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4261. return true;
  4262. }
  4263. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4264. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4265. "lvalue __imag__ on scalar?");
  4266. if (!Visit(E->getSubExpr()))
  4267. return false;
  4268. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4269. return true;
  4270. }
  4271. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4272. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4273. return Error(UO);
  4274. if (!this->Visit(UO->getSubExpr()))
  4275. return false;
  4276. return handleIncDec(
  4277. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4278. UO->isIncrementOp(), nullptr);
  4279. }
  4280. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4281. const CompoundAssignOperator *CAO) {
  4282. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4283. return Error(CAO);
  4284. APValue RHS;
  4285. // The overall lvalue result is the result of evaluating the LHS.
  4286. if (!this->Visit(CAO->getLHS())) {
  4287. if (Info.keepEvaluatingAfterFailure())
  4288. Evaluate(RHS, this->Info, CAO->getRHS());
  4289. return false;
  4290. }
  4291. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4292. return false;
  4293. return handleCompoundAssignment(
  4294. this->Info, CAO,
  4295. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4296. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4297. }
  4298. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4299. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4300. return Error(E);
  4301. APValue NewVal;
  4302. if (!this->Visit(E->getLHS())) {
  4303. if (Info.keepEvaluatingAfterFailure())
  4304. Evaluate(NewVal, this->Info, E->getRHS());
  4305. return false;
  4306. }
  4307. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4308. return false;
  4309. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4310. NewVal);
  4311. }
  4312. //===----------------------------------------------------------------------===//
  4313. // Pointer Evaluation
  4314. //===----------------------------------------------------------------------===//
  4315. namespace {
  4316. class PointerExprEvaluator
  4317. : public ExprEvaluatorBase<PointerExprEvaluator> {
  4318. LValue &Result;
  4319. bool Success(const Expr *E) {
  4320. Result.set(E);
  4321. return true;
  4322. }
  4323. public:
  4324. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  4325. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4326. bool Success(const APValue &V, const Expr *E) {
  4327. Result.setFrom(Info.Ctx, V);
  4328. return true;
  4329. }
  4330. bool ZeroInitialization(const Expr *E) {
  4331. return Success((Expr*)nullptr);
  4332. }
  4333. bool VisitBinaryOperator(const BinaryOperator *E);
  4334. bool VisitCastExpr(const CastExpr* E);
  4335. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4336. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  4337. { return Success(E); }
  4338. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
  4339. { return Success(E); }
  4340. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  4341. { return Success(E); }
  4342. bool VisitCallExpr(const CallExpr *E);
  4343. bool VisitBlockExpr(const BlockExpr *E) {
  4344. if (!E->getBlockDecl()->hasCaptures())
  4345. return Success(E);
  4346. return Error(E);
  4347. }
  4348. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  4349. // Can't look at 'this' when checking a potential constant expression.
  4350. if (Info.checkingPotentialConstantExpression())
  4351. return false;
  4352. if (!Info.CurrentCall->This) {
  4353. if (Info.getLangOpts().CPlusPlus11)
  4354. Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
  4355. else
  4356. Info.Diag(E);
  4357. return false;
  4358. }
  4359. Result = *Info.CurrentCall->This;
  4360. return true;
  4361. }
  4362. // FIXME: Missing: @protocol, @selector
  4363. };
  4364. } // end anonymous namespace
  4365. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  4366. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  4367. return PointerExprEvaluator(Info, Result).Visit(E);
  4368. }
  4369. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4370. if (E->getOpcode() != BO_Add &&
  4371. E->getOpcode() != BO_Sub)
  4372. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4373. const Expr *PExp = E->getLHS();
  4374. const Expr *IExp = E->getRHS();
  4375. if (IExp->getType()->isPointerType())
  4376. std::swap(PExp, IExp);
  4377. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  4378. if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
  4379. return false;
  4380. llvm::APSInt Offset;
  4381. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  4382. return false;
  4383. int64_t AdditionalOffset = getExtValue(Offset);
  4384. if (E->getOpcode() == BO_Sub)
  4385. AdditionalOffset = -AdditionalOffset;
  4386. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  4387. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  4388. AdditionalOffset);
  4389. }
  4390. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4391. return EvaluateLValue(E->getSubExpr(), Result, Info);
  4392. }
  4393. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  4394. const Expr* SubExpr = E->getSubExpr();
  4395. switch (E->getCastKind()) {
  4396. default:
  4397. break;
  4398. case CK_BitCast:
  4399. case CK_CPointerToObjCPointerCast:
  4400. case CK_BlockPointerToObjCPointerCast:
  4401. case CK_AnyPointerToBlockPointerCast:
  4402. case CK_AddressSpaceConversion:
  4403. if (!Visit(SubExpr))
  4404. return false;
  4405. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  4406. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  4407. // also static_casts, but we disallow them as a resolution to DR1312.
  4408. if (!E->getType()->isVoidPointerType()) {
  4409. Result.Designator.setInvalid();
  4410. if (SubExpr->getType()->isVoidPointerType())
  4411. CCEDiag(E, diag::note_constexpr_invalid_cast)
  4412. << 3 << SubExpr->getType();
  4413. else
  4414. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4415. }
  4416. return true;
  4417. case CK_DerivedToBase:
  4418. case CK_UncheckedDerivedToBase:
  4419. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  4420. return false;
  4421. if (!Result.Base && Result.Offset.isZero())
  4422. return true;
  4423. // Now figure out the necessary offset to add to the base LV to get from
  4424. // the derived class to the base class.
  4425. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  4426. castAs<PointerType>()->getPointeeType(),
  4427. Result);
  4428. case CK_BaseToDerived:
  4429. if (!Visit(E->getSubExpr()))
  4430. return false;
  4431. if (!Result.Base && Result.Offset.isZero())
  4432. return true;
  4433. return HandleBaseToDerivedCast(Info, E, Result);
  4434. case CK_NullToPointer:
  4435. VisitIgnoredValue(E->getSubExpr());
  4436. return ZeroInitialization(E);
  4437. case CK_IntegralToPointer: {
  4438. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4439. APValue Value;
  4440. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  4441. break;
  4442. if (Value.isInt()) {
  4443. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  4444. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  4445. Result.Base = (Expr*)nullptr;
  4446. Result.Offset = CharUnits::fromQuantity(N);
  4447. Result.CallIndex = 0;
  4448. Result.Designator.setInvalid();
  4449. return true;
  4450. } else {
  4451. // Cast is of an lvalue, no need to change value.
  4452. Result.setFrom(Info.Ctx, Value);
  4453. return true;
  4454. }
  4455. }
  4456. case CK_ArrayToPointerDecay:
  4457. if (SubExpr->isGLValue()) {
  4458. if (!EvaluateLValue(SubExpr, Result, Info))
  4459. return false;
  4460. } else {
  4461. Result.set(SubExpr, Info.CurrentCall->Index);
  4462. if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
  4463. Info, Result, SubExpr))
  4464. return false;
  4465. }
  4466. // The result is a pointer to the first element of the array.
  4467. if (const ConstantArrayType *CAT
  4468. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  4469. Result.addArray(Info, E, CAT);
  4470. else
  4471. Result.Designator.setInvalid();
  4472. return true;
  4473. case CK_FunctionToPointerDecay:
  4474. return EvaluateLValue(SubExpr, Result, Info);
  4475. }
  4476. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4477. }
  4478. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
  4479. // C++ [expr.alignof]p3:
  4480. // When alignof is applied to a reference type, the result is the
  4481. // alignment of the referenced type.
  4482. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4483. T = Ref->getPointeeType();
  4484. // __alignof is defined to return the preferred alignment.
  4485. return Info.Ctx.toCharUnitsFromBits(
  4486. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4487. }
  4488. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
  4489. E = E->IgnoreParens();
  4490. // The kinds of expressions that we have special-case logic here for
  4491. // should be kept up to date with the special checks for those
  4492. // expressions in Sema.
  4493. // alignof decl is always accepted, even if it doesn't make sense: we default
  4494. // to 1 in those cases.
  4495. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4496. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4497. /*RefAsPointee*/true);
  4498. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4499. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4500. /*RefAsPointee*/true);
  4501. return GetAlignOfType(Info, E->getType());
  4502. }
  4503. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4504. if (IsStringLiteralCall(E))
  4505. return Success(E);
  4506. switch (E->getBuiltinCallee()) {
  4507. case Builtin::BI__builtin_addressof:
  4508. return EvaluateLValue(E->getArg(0), Result, Info);
  4509. case Builtin::BI__builtin_assume_aligned: {
  4510. // We need to be very careful here because: if the pointer does not have the
  4511. // asserted alignment, then the behavior is undefined, and undefined
  4512. // behavior is non-constant.
  4513. if (!EvaluatePointer(E->getArg(0), Result, Info))
  4514. return false;
  4515. LValue OffsetResult(Result);
  4516. APSInt Alignment;
  4517. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  4518. return false;
  4519. CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
  4520. if (E->getNumArgs() > 2) {
  4521. APSInt Offset;
  4522. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  4523. return false;
  4524. int64_t AdditionalOffset = -getExtValue(Offset);
  4525. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  4526. }
  4527. // If there is a base object, then it must have the correct alignment.
  4528. if (OffsetResult.Base) {
  4529. CharUnits BaseAlignment;
  4530. if (const ValueDecl *VD =
  4531. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  4532. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  4533. } else {
  4534. BaseAlignment =
  4535. GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
  4536. }
  4537. if (BaseAlignment < Align) {
  4538. Result.Designator.setInvalid();
  4539. // FIXME: Quantities here cast to integers because the plural modifier
  4540. // does not work on APSInts yet.
  4541. CCEDiag(E->getArg(0),
  4542. diag::note_constexpr_baa_insufficient_alignment) << 0
  4543. << (int) BaseAlignment.getQuantity()
  4544. << (unsigned) getExtValue(Alignment);
  4545. return false;
  4546. }
  4547. }
  4548. // The offset must also have the correct alignment.
  4549. if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
  4550. Result.Designator.setInvalid();
  4551. APSInt Offset(64, false);
  4552. Offset = OffsetResult.Offset.getQuantity();
  4553. if (OffsetResult.Base)
  4554. CCEDiag(E->getArg(0),
  4555. diag::note_constexpr_baa_insufficient_alignment) << 1
  4556. << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
  4557. else
  4558. CCEDiag(E->getArg(0),
  4559. diag::note_constexpr_baa_value_insufficient_alignment)
  4560. << Offset << (unsigned) getExtValue(Alignment);
  4561. return false;
  4562. }
  4563. return true;
  4564. }
  4565. default:
  4566. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4567. }
  4568. }
  4569. //===----------------------------------------------------------------------===//
  4570. // Member Pointer Evaluation
  4571. //===----------------------------------------------------------------------===//
  4572. namespace {
  4573. class MemberPointerExprEvaluator
  4574. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  4575. MemberPtr &Result;
  4576. bool Success(const ValueDecl *D) {
  4577. Result = MemberPtr(D);
  4578. return true;
  4579. }
  4580. public:
  4581. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  4582. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  4583. bool Success(const APValue &V, const Expr *E) {
  4584. Result.setFrom(V);
  4585. return true;
  4586. }
  4587. bool ZeroInitialization(const Expr *E) {
  4588. return Success((const ValueDecl*)nullptr);
  4589. }
  4590. bool VisitCastExpr(const CastExpr *E);
  4591. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4592. };
  4593. } // end anonymous namespace
  4594. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  4595. EvalInfo &Info) {
  4596. assert(E->isRValue() && E->getType()->isMemberPointerType());
  4597. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  4598. }
  4599. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4600. switch (E->getCastKind()) {
  4601. default:
  4602. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4603. case CK_NullToMemberPointer:
  4604. VisitIgnoredValue(E->getSubExpr());
  4605. return ZeroInitialization(E);
  4606. case CK_BaseToDerivedMemberPointer: {
  4607. if (!Visit(E->getSubExpr()))
  4608. return false;
  4609. if (E->path_empty())
  4610. return true;
  4611. // Base-to-derived member pointer casts store the path in derived-to-base
  4612. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  4613. // the wrong end of the derived->base arc, so stagger the path by one class.
  4614. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  4615. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  4616. PathI != PathE; ++PathI) {
  4617. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4618. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  4619. if (!Result.castToDerived(Derived))
  4620. return Error(E);
  4621. }
  4622. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  4623. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  4624. return Error(E);
  4625. return true;
  4626. }
  4627. case CK_DerivedToBaseMemberPointer:
  4628. if (!Visit(E->getSubExpr()))
  4629. return false;
  4630. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  4631. PathE = E->path_end(); PathI != PathE; ++PathI) {
  4632. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4633. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  4634. if (!Result.castToBase(Base))
  4635. return Error(E);
  4636. }
  4637. return true;
  4638. }
  4639. }
  4640. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4641. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  4642. // member can be formed.
  4643. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  4644. }
  4645. //===----------------------------------------------------------------------===//
  4646. // Record Evaluation
  4647. //===----------------------------------------------------------------------===//
  4648. namespace {
  4649. class RecordExprEvaluator
  4650. : public ExprEvaluatorBase<RecordExprEvaluator> {
  4651. const LValue &This;
  4652. APValue &Result;
  4653. public:
  4654. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  4655. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  4656. bool Success(const APValue &V, const Expr *E) {
  4657. Result = V;
  4658. return true;
  4659. }
  4660. bool ZeroInitialization(const Expr *E);
  4661. bool VisitCastExpr(const CastExpr *E);
  4662. bool VisitInitListExpr(const InitListExpr *E);
  4663. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  4664. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  4665. };
  4666. }
  4667. /// Perform zero-initialization on an object of non-union class type.
  4668. /// C++11 [dcl.init]p5:
  4669. /// To zero-initialize an object or reference of type T means:
  4670. /// [...]
  4671. /// -- if T is a (possibly cv-qualified) non-union class type,
  4672. /// each non-static data member and each base-class subobject is
  4673. /// zero-initialized
  4674. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  4675. const RecordDecl *RD,
  4676. const LValue &This, APValue &Result) {
  4677. assert(!RD->isUnion() && "Expected non-union class type");
  4678. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  4679. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  4680. std::distance(RD->field_begin(), RD->field_end()));
  4681. if (RD->isInvalidDecl()) return false;
  4682. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4683. if (CD) {
  4684. unsigned Index = 0;
  4685. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  4686. End = CD->bases_end(); I != End; ++I, ++Index) {
  4687. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  4688. LValue Subobject = This;
  4689. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  4690. return false;
  4691. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  4692. Result.getStructBase(Index)))
  4693. return false;
  4694. }
  4695. }
  4696. for (const auto *I : RD->fields()) {
  4697. // -- if T is a reference type, no initialization is performed.
  4698. if (I->getType()->isReferenceType())
  4699. continue;
  4700. LValue Subobject = This;
  4701. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  4702. return false;
  4703. ImplicitValueInitExpr VIE(I->getType());
  4704. if (!EvaluateInPlace(
  4705. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  4706. return false;
  4707. }
  4708. return true;
  4709. }
  4710. bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
  4711. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  4712. if (RD->isInvalidDecl()) return false;
  4713. if (RD->isUnion()) {
  4714. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  4715. // object's first non-static named data member is zero-initialized
  4716. RecordDecl::field_iterator I = RD->field_begin();
  4717. if (I == RD->field_end()) {
  4718. Result = APValue((const FieldDecl*)nullptr);
  4719. return true;
  4720. }
  4721. LValue Subobject = This;
  4722. if (!HandleLValueMember(Info, E, Subobject, *I))
  4723. return false;
  4724. Result = APValue(*I);
  4725. ImplicitValueInitExpr VIE(I->getType());
  4726. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  4727. }
  4728. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  4729. Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
  4730. return false;
  4731. }
  4732. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  4733. }
  4734. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4735. switch (E->getCastKind()) {
  4736. default:
  4737. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4738. case CK_ConstructorConversion:
  4739. return Visit(E->getSubExpr());
  4740. case CK_DerivedToBase:
  4741. case CK_UncheckedDerivedToBase: {
  4742. APValue DerivedObject;
  4743. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  4744. return false;
  4745. if (!DerivedObject.isStruct())
  4746. return Error(E->getSubExpr());
  4747. // Derived-to-base rvalue conversion: just slice off the derived part.
  4748. APValue *Value = &DerivedObject;
  4749. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  4750. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  4751. PathE = E->path_end(); PathI != PathE; ++PathI) {
  4752. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  4753. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  4754. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  4755. RD = Base;
  4756. }
  4757. Result = *Value;
  4758. return true;
  4759. }
  4760. }
  4761. }
  4762. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  4763. if (Info.getLangOpts().HLSL) return false; // HLSL Change
  4764. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  4765. if (RD->isInvalidDecl()) return false;
  4766. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4767. if (RD->isUnion()) {
  4768. const FieldDecl *Field = E->getInitializedFieldInUnion();
  4769. Result = APValue(Field);
  4770. if (!Field)
  4771. return true;
  4772. // If the initializer list for a union does not contain any elements, the
  4773. // first element of the union is value-initialized.
  4774. // FIXME: The element should be initialized from an initializer list.
  4775. // Is this difference ever observable for initializer lists which
  4776. // we don't build?
  4777. ImplicitValueInitExpr VIE(Field->getType());
  4778. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  4779. LValue Subobject = This;
  4780. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  4781. return false;
  4782. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  4783. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  4784. isa<CXXDefaultInitExpr>(InitExpr));
  4785. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  4786. }
  4787. assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
  4788. "initializer list for class with base classes");
  4789. Result = APValue(APValue::UninitStruct(), 0,
  4790. std::distance(RD->field_begin(), RD->field_end()));
  4791. unsigned ElementNo = 0;
  4792. bool Success = true;
  4793. for (const auto *Field : RD->fields()) {
  4794. // Anonymous bit-fields are not considered members of the class for
  4795. // purposes of aggregate initialization.
  4796. if (Field->isUnnamedBitfield())
  4797. continue;
  4798. LValue Subobject = This;
  4799. bool HaveInit = ElementNo < E->getNumInits();
  4800. // FIXME: Diagnostics here should point to the end of the initializer
  4801. // list, not the start.
  4802. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  4803. Subobject, Field, &Layout))
  4804. return false;
  4805. // Perform an implicit value-initialization for members beyond the end of
  4806. // the initializer list.
  4807. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  4808. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  4809. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  4810. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  4811. isa<CXXDefaultInitExpr>(Init));
  4812. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  4813. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  4814. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  4815. FieldVal, Field))) {
  4816. if (!Info.keepEvaluatingAfterFailure())
  4817. return false;
  4818. Success = false;
  4819. }
  4820. }
  4821. return Success;
  4822. }
  4823. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  4824. const CXXConstructorDecl *FD = E->getConstructor();
  4825. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  4826. bool ZeroInit = E->requiresZeroInitialization();
  4827. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  4828. // If we've already performed zero-initialization, we're already done.
  4829. if (!Result.isUninit())
  4830. return true;
  4831. // We can get here in two different ways:
  4832. // 1) We're performing value-initialization, and should zero-initialize
  4833. // the object, or
  4834. // 2) We're performing default-initialization of an object with a trivial
  4835. // constexpr default constructor, in which case we should start the
  4836. // lifetimes of all the base subobjects (there can be no data member
  4837. // subobjects in this case) per [basic.life]p1.
  4838. // Either way, ZeroInitialization is appropriate.
  4839. return ZeroInitialization(E);
  4840. }
  4841. const FunctionDecl *Definition = nullptr;
  4842. FD->getBody(Definition);
  4843. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  4844. return false;
  4845. // Avoid materializing a temporary for an elidable copy/move constructor.
  4846. if (E->isElidable() && !ZeroInit)
  4847. if (const MaterializeTemporaryExpr *ME
  4848. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  4849. return Visit(ME->GetTemporaryExpr());
  4850. if (ZeroInit && !ZeroInitialization(E))
  4851. return false;
  4852. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4853. return HandleConstructorCall(E->getExprLoc(), This, Args,
  4854. cast<CXXConstructorDecl>(Definition), Info,
  4855. Result);
  4856. }
  4857. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  4858. const CXXStdInitializerListExpr *E) {
  4859. const ConstantArrayType *ArrayType =
  4860. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  4861. LValue Array;
  4862. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  4863. return false;
  4864. // Get a pointer to the first element of the array.
  4865. Array.addArray(Info, E, ArrayType);
  4866. // FIXME: Perform the checks on the field types in SemaInit.
  4867. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  4868. RecordDecl::field_iterator Field = Record->field_begin();
  4869. if (Field == Record->field_end())
  4870. return Error(E);
  4871. // Start pointer.
  4872. if (!Field->getType()->isPointerType() ||
  4873. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  4874. ArrayType->getElementType()))
  4875. return Error(E);
  4876. // FIXME: What if the initializer_list type has base classes, etc?
  4877. Result = APValue(APValue::UninitStruct(), 0, 2);
  4878. Array.moveInto(Result.getStructField(0));
  4879. if (++Field == Record->field_end())
  4880. return Error(E);
  4881. if (Field->getType()->isPointerType() &&
  4882. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  4883. ArrayType->getElementType())) {
  4884. // End pointer.
  4885. if (!HandleLValueArrayAdjustment(Info, E, Array,
  4886. ArrayType->getElementType(),
  4887. ArrayType->getSize().getZExtValue()))
  4888. return false;
  4889. Array.moveInto(Result.getStructField(1));
  4890. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  4891. // Length.
  4892. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  4893. else
  4894. return Error(E);
  4895. if (++Field != Record->field_end())
  4896. return Error(E);
  4897. return true;
  4898. }
  4899. static bool EvaluateRecord(const Expr *E, const LValue &This,
  4900. APValue &Result, EvalInfo &Info) {
  4901. assert(E->isRValue() && E->getType()->isRecordType() &&
  4902. "can't evaluate expression as a record rvalue");
  4903. return RecordExprEvaluator(Info, This, Result).Visit(E);
  4904. }
  4905. //===----------------------------------------------------------------------===//
  4906. // Temporary Evaluation
  4907. //
  4908. // Temporaries are represented in the AST as rvalues, but generally behave like
  4909. // lvalues. The full-object of which the temporary is a subobject is implicitly
  4910. // materialized so that a reference can bind to it.
  4911. //===----------------------------------------------------------------------===//
  4912. namespace {
  4913. class TemporaryExprEvaluator
  4914. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  4915. public:
  4916. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  4917. LValueExprEvaluatorBaseTy(Info, Result) {}
  4918. /// Visit an expression which constructs the value of this temporary.
  4919. bool VisitConstructExpr(const Expr *E) {
  4920. Result.set(E, Info.CurrentCall->Index);
  4921. return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
  4922. Info, Result, E);
  4923. }
  4924. bool VisitCastExpr(const CastExpr *E) {
  4925. switch (E->getCastKind()) {
  4926. default:
  4927. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4928. case CK_ConstructorConversion:
  4929. return VisitConstructExpr(E->getSubExpr());
  4930. }
  4931. }
  4932. bool VisitInitListExpr(const InitListExpr *E) {
  4933. if (Info.getLangOpts().HLSL && !IsHLSLVecInitList(E)) return Error(E); // HLSL Change
  4934. return VisitConstructExpr(E);
  4935. }
  4936. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  4937. return VisitConstructExpr(E);
  4938. }
  4939. bool VisitCallExpr(const CallExpr *E) {
  4940. return VisitConstructExpr(E);
  4941. }
  4942. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  4943. return VisitConstructExpr(E);
  4944. }
  4945. };
  4946. } // end anonymous namespace
  4947. /// Evaluate an expression of record type as a temporary.
  4948. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  4949. assert(E->isRValue() && E->getType()->isRecordType());
  4950. return TemporaryExprEvaluator(Info, Result).Visit(E);
  4951. }
  4952. //===----------------------------------------------------------------------===//
  4953. // Vector Evaluation
  4954. //===----------------------------------------------------------------------===//
  4955. namespace {
  4956. class VectorExprEvaluator
  4957. : public ExprEvaluatorBase<VectorExprEvaluator> {
  4958. APValue &Result;
  4959. public:
  4960. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  4961. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4962. bool Success(const ArrayRef<APValue> &V, const Expr *E) {
  4963. // HLSL Change Begins.
  4964. const VectorType *VT = nullptr;
  4965. if (hlsl::IsHLSLVecType(E->getType())) {
  4966. VT = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx,
  4967. E->getType());
  4968. } else
  4969. VT = E->getType()->castAs<VectorType>();
  4970. // HLSL Change Ends.
  4971. assert(V.size() == VT->getNumElements());
  4972. // FIXME: remove this APValue copy.
  4973. Result = APValue(V.data(), V.size());
  4974. return true;
  4975. }
  4976. bool Success(const APValue &V, const Expr *E) {
  4977. assert(V.isVector());
  4978. Result = V;
  4979. return true;
  4980. }
  4981. bool ZeroInitialization(const Expr *E);
  4982. bool VisitUnaryReal(const UnaryOperator *E)
  4983. { return Visit(E->getSubExpr()); }
  4984. bool VisitCastExpr(const CastExpr* E);
  4985. bool VisitInitListExpr(const InitListExpr *E);
  4986. bool VisitHLSLVectorElementExpr(const HLSLVectorElementExpr *E);
  4987. bool VisitUnaryImag(const UnaryOperator *E);
  4988. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  4989. // binary comparisons, binary and/or/xor,
  4990. // shufflevector, ExtVectorElementExpr
  4991. };
  4992. } // end anonymous namespace
  4993. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  4994. assert(E->isRValue() && (E->getType()->isVectorType() || hlsl::IsHLSLVecType(E->getType())) &&"not a vector rvalue"); // HLSL Change
  4995. return VectorExprEvaluator(Info, Result).Visit(E);
  4996. }
  4997. bool VectorExprEvaluator::VisitHLSLVectorElementExpr(
  4998. const HLSLVectorElementExpr *E) {
  4999. SmallVector<APValue, 4> Elts;
  5000. const Expr *baseExpr = E->getBase();
  5001. // Handling cases where HLSLVectorElement access into constant vector.
  5002. // For example: float4 a = (0.0).xxxx;
  5003. if (Evaluate(Result, Info, baseExpr) && !Info.EvalStatus.HasSideEffects &&
  5004. Result.getKind() == APValue::ValueKind::Vector) {
  5005. hlsl::VectorMemberAccessPositions accessor = E->getEncodedElementAccess();
  5006. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5007. uint32_t selector;
  5008. accessor.GetPosition(i, &selector);
  5009. Elts.push_back(Result.getVectorElt(selector));
  5010. }
  5011. return Success(Elts, E);
  5012. }
  5013. // TODO: Other cases may be added for other APValue::ValueKind.
  5014. return false;
  5015. }
  5016. bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
  5017. // HLSL Change Begins.
  5018. const VectorType *VTy;
  5019. if (Info.getLangOpts().HLSL && hlsl::IsHLSLVecType(E->getType())) {
  5020. VTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx, E->getType());
  5021. } else {
  5022. VTy = E->getType()->castAs<VectorType>();
  5023. }
  5024. // HLSL Change Ends.
  5025. unsigned NElts = VTy->getNumElements();
  5026. const Expr *SE = E->getSubExpr();
  5027. QualType SETy = SE->getType();
  5028. switch (E->getCastKind()) {
  5029. // HLSL Change Begins.
  5030. case CK_HLSLCC_FloatingCast: {
  5031. if (!Visit(SE))
  5032. return Error(E);
  5033. SmallVector<APValue, 4> Elts;
  5034. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5035. APValue Elem = Result.getVectorElt(i);
  5036. HandleFloatToFloatCast(
  5037. Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5038. hlsl::GetHLSLVecElementType(E->getType()), Elem.getFloat());
  5039. Elts.push_back(Elem);
  5040. }
  5041. return Success(Elts, E);
  5042. }
  5043. case CK_HLSLCC_IntegralToFloating: {
  5044. if (!Visit(SE))
  5045. return Error(E);
  5046. SmallVector<APValue, 4> Elts;
  5047. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5048. APFloat ElemFloat(0.0);
  5049. HandleIntToFloatCast(Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5050. Result.getVectorElt(i).getInt(),
  5051. hlsl::GetHLSLVecElementType(E->getType()),
  5052. ElemFloat);
  5053. Elts.push_back(APValue(ElemFloat));
  5054. }
  5055. return Success(Elts, E);
  5056. }
  5057. case CK_HLSLCC_FloatingToIntegral: {
  5058. if (!Visit(SE))
  5059. return Error(E);
  5060. SmallVector<APValue, 4> Elts;
  5061. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5062. APSInt ElemInt;
  5063. HandleFloatToIntCast(Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5064. Result.getVectorElt(i).getFloat(),
  5065. hlsl::GetHLSLVecElementType(E->getType()), ElemInt);
  5066. Elts.push_back(APValue(ElemInt));
  5067. }
  5068. return Success(Elts, E);
  5069. }
  5070. // HLSL Change Ends.
  5071. case CK_HLSLVectorSplat: // HLSL Change
  5072. case CK_VectorSplat: {
  5073. APValue Val = APValue();
  5074. if (SETy->isIntegerType()) {
  5075. APSInt IntResult;
  5076. if (!EvaluateInteger(SE, IntResult, Info))
  5077. return false;
  5078. Val = APValue(IntResult);
  5079. } else if (SETy->isRealFloatingType()) {
  5080. APFloat F(0.0);
  5081. if (!EvaluateFloat(SE, F, Info))
  5082. return false;
  5083. Val = APValue(F);
  5084. } else {
  5085. return Error(E);
  5086. }
  5087. // Splat and create vector APValue.
  5088. SmallVector<APValue, 4> Elts(NElts, Val);
  5089. return Success(Elts, E);
  5090. }
  5091. case CK_BitCast: {
  5092. // Evaluate the operand into an APInt we can extract from.
  5093. llvm::APInt SValInt;
  5094. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  5095. return false;
  5096. // Extract the elements
  5097. QualType EltTy = VTy->getElementType();
  5098. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  5099. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  5100. SmallVector<APValue, 4> Elts;
  5101. if (EltTy->isRealFloatingType()) {
  5102. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  5103. unsigned FloatEltSize = EltSize;
  5104. if (&Sem == &APFloat::x87DoubleExtended)
  5105. FloatEltSize = 80;
  5106. for (unsigned i = 0; i < NElts; i++) {
  5107. llvm::APInt Elt;
  5108. if (BigEndian)
  5109. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  5110. else
  5111. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  5112. Elts.push_back(APValue(APFloat(Sem, Elt)));
  5113. }
  5114. } else if (EltTy->isIntegerType()) {
  5115. for (unsigned i = 0; i < NElts; i++) {
  5116. llvm::APInt Elt;
  5117. if (BigEndian)
  5118. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  5119. else
  5120. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  5121. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  5122. }
  5123. } else {
  5124. return Error(E);
  5125. }
  5126. return Success(Elts, E);
  5127. }
  5128. default:
  5129. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5130. }
  5131. }
  5132. bool
  5133. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5134. // HLSL Change Begins.
  5135. if (Info.getLangOpts().HLSL) {
  5136. QualType Ty = E->getType();
  5137. if (!hlsl::IsHLSLVecType(Ty))
  5138. return Error(E); // HLSL Change
  5139. unsigned vecSize = hlsl::GetHLSLVecSize(Ty);
  5140. // TODO: support all cases.
  5141. if (E->getNumInits() != vecSize)
  5142. return Error(E); // HLSL Change
  5143. }
  5144. // HLSL Change Ends.
  5145. const VectorType *VT = nullptr;
  5146. // HLSL Change Begins.
  5147. if (hlsl::IsHLSLVecType(E->getType())) {
  5148. VT = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx,
  5149. E->getType());
  5150. } else
  5151. VT = E->getType()->castAs<VectorType>();
  5152. // HLSL Change Ends.
  5153. unsigned NumInits = E->getNumInits();
  5154. unsigned NumElements = VT->getNumElements();
  5155. QualType EltTy = VT->getElementType();
  5156. SmallVector<APValue, 4> Elements;
  5157. // The number of initializers can be less than the number of
  5158. // vector elements. For OpenCL, this can be due to nested vector
  5159. // initialization. For GCC compatibility, missing trailing elements
  5160. // should be initialized with zeroes.
  5161. unsigned CountInits = 0, CountElts = 0;
  5162. while (CountElts < NumElements) {
  5163. // Handle nested vector initialization.
  5164. if (CountInits < NumInits
  5165. && (E->getInit(CountInits)->getType()->isVectorType() ||
  5166. // HLSL Change Begins.
  5167. (Info.getLangOpts().HLSL &&
  5168. hlsl::IsHLSLVecType(E->getInit(CountInits)->getType())))) {
  5169. // HLSL Change Ends.
  5170. APValue v;
  5171. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  5172. return Error(E);
  5173. unsigned vlen = v.getVectorLength();
  5174. for (unsigned j = 0; j < vlen; j++)
  5175. Elements.push_back(v.getVectorElt(j));
  5176. CountElts += vlen;
  5177. } else if (EltTy->isIntegerType()) {
  5178. llvm::APSInt sInt(32);
  5179. if (CountInits < NumInits) {
  5180. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  5181. return false;
  5182. } else // trailing integer zero.
  5183. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  5184. Elements.push_back(APValue(sInt));
  5185. CountElts++;
  5186. } else {
  5187. llvm::APFloat f(0.0);
  5188. if (CountInits < NumInits) {
  5189. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  5190. return false;
  5191. } else // trailing float zero.
  5192. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  5193. Elements.push_back(APValue(f));
  5194. CountElts++;
  5195. }
  5196. CountInits++;
  5197. }
  5198. return Success(Elements, E);
  5199. }
  5200. bool
  5201. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  5202. const VectorType *VT = E->getType()->getAs<VectorType>();
  5203. QualType EltTy = VT->getElementType();
  5204. APValue ZeroElement;
  5205. if (EltTy->isIntegerType())
  5206. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  5207. else
  5208. ZeroElement =
  5209. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  5210. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  5211. return Success(Elements, E);
  5212. }
  5213. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5214. VisitIgnoredValue(E->getSubExpr());
  5215. return ZeroInitialization(E);
  5216. }
  5217. //===----------------------------------------------------------------------===//
  5218. // Array Evaluation
  5219. //===----------------------------------------------------------------------===//
  5220. namespace {
  5221. class ArrayExprEvaluator
  5222. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  5223. const LValue &This;
  5224. APValue &Result;
  5225. public:
  5226. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  5227. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  5228. bool Success(const APValue &V, const Expr *E) {
  5229. assert((V.isArray() || V.isLValue()) &&
  5230. "expected array or string literal");
  5231. Result = V;
  5232. return true;
  5233. }
  5234. bool ZeroInitialization(const Expr *E) {
  5235. const ConstantArrayType *CAT =
  5236. Info.Ctx.getAsConstantArrayType(E->getType());
  5237. if (!CAT)
  5238. return Error(E);
  5239. Result = APValue(APValue::UninitArray(), 0,
  5240. CAT->getSize().getZExtValue());
  5241. if (!Result.hasArrayFiller()) return true;
  5242. // Zero-initialize all elements.
  5243. LValue Subobject = This;
  5244. Subobject.addArray(Info, E, CAT);
  5245. ImplicitValueInitExpr VIE(CAT->getElementType());
  5246. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  5247. }
  5248. bool VisitInitListExpr(const InitListExpr *E);
  5249. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  5250. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  5251. const LValue &Subobject,
  5252. APValue *Value, QualType Type);
  5253. };
  5254. } // end anonymous namespace
  5255. static bool EvaluateArray(const Expr *E, const LValue &This,
  5256. APValue &Result, EvalInfo &Info) {
  5257. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  5258. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  5259. }
  5260. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5261. if (Info.getLangOpts().HLSL) return Error(E); // HLSL Change
  5262. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  5263. if (!CAT)
  5264. return Error(E);
  5265. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  5266. // an appropriately-typed string literal enclosed in braces.
  5267. if (E->isStringLiteralInit()) {
  5268. LValue LV;
  5269. if (!EvaluateLValue(E->getInit(0), LV, Info))
  5270. return false;
  5271. APValue Val;
  5272. LV.moveInto(Val);
  5273. return Success(Val, E);
  5274. }
  5275. bool Success = true;
  5276. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  5277. "zero-initialized array shouldn't have any initialized elts");
  5278. APValue Filler;
  5279. if (Result.isArray() && Result.hasArrayFiller())
  5280. Filler = Result.getArrayFiller();
  5281. unsigned NumEltsToInit = E->getNumInits();
  5282. unsigned NumElts = CAT->getSize().getZExtValue();
  5283. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  5284. // If the initializer might depend on the array index, run it for each
  5285. // array element. For now, just whitelist non-class value-initialization.
  5286. if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
  5287. NumEltsToInit = NumElts;
  5288. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  5289. // If the array was previously zero-initialized, preserve the
  5290. // zero-initialized values.
  5291. if (!Filler.isUninit()) {
  5292. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  5293. Result.getArrayInitializedElt(I) = Filler;
  5294. if (Result.hasArrayFiller())
  5295. Result.getArrayFiller() = Filler;
  5296. }
  5297. LValue Subobject = This;
  5298. Subobject.addArray(Info, E, CAT);
  5299. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  5300. const Expr *Init =
  5301. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  5302. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  5303. Info, Subobject, Init) ||
  5304. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  5305. CAT->getElementType(), 1)) {
  5306. if (!Info.keepEvaluatingAfterFailure())
  5307. return false;
  5308. Success = false;
  5309. }
  5310. }
  5311. if (!Result.hasArrayFiller())
  5312. return Success;
  5313. // If we get here, we have a trivial filler, which we can just evaluate
  5314. // once and splat over the rest of the array elements.
  5315. assert(FillerExpr && "no array filler for incomplete init list");
  5316. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  5317. FillerExpr) && Success;
  5318. }
  5319. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5320. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  5321. }
  5322. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5323. const LValue &Subobject,
  5324. APValue *Value,
  5325. QualType Type) {
  5326. bool HadZeroInit = !Value->isUninit();
  5327. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  5328. unsigned N = CAT->getSize().getZExtValue();
  5329. // Preserve the array filler if we had prior zero-initialization.
  5330. APValue Filler =
  5331. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  5332. : APValue();
  5333. *Value = APValue(APValue::UninitArray(), N, N);
  5334. if (HadZeroInit)
  5335. for (unsigned I = 0; I != N; ++I)
  5336. Value->getArrayInitializedElt(I) = Filler;
  5337. // Initialize the elements.
  5338. LValue ArrayElt = Subobject;
  5339. ArrayElt.addArray(Info, E, CAT);
  5340. for (unsigned I = 0; I != N; ++I)
  5341. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  5342. CAT->getElementType()) ||
  5343. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  5344. CAT->getElementType(), 1))
  5345. return false;
  5346. return true;
  5347. }
  5348. if (!Type->isRecordType())
  5349. return Error(E);
  5350. const CXXConstructorDecl *FD = E->getConstructor();
  5351. bool ZeroInit = E->requiresZeroInitialization();
  5352. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5353. if (HadZeroInit)
  5354. return true;
  5355. // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
  5356. ImplicitValueInitExpr VIE(Type);
  5357. return EvaluateInPlace(*Value, Info, Subobject, &VIE);
  5358. }
  5359. const FunctionDecl *Definition = nullptr;
  5360. FD->getBody(Definition);
  5361. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  5362. return false;
  5363. if (ZeroInit && !HadZeroInit) {
  5364. ImplicitValueInitExpr VIE(Type);
  5365. if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
  5366. return false;
  5367. }
  5368. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5369. return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
  5370. cast<CXXConstructorDecl>(Definition),
  5371. Info, *Value);
  5372. }
  5373. //===----------------------------------------------------------------------===//
  5374. // Integer Evaluation
  5375. //
  5376. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  5377. // types and back in constant folding. Integer values are thus represented
  5378. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  5379. //===----------------------------------------------------------------------===//
  5380. namespace {
  5381. class IntExprEvaluator
  5382. : public ExprEvaluatorBase<IntExprEvaluator> {
  5383. APValue &Result;
  5384. public:
  5385. IntExprEvaluator(EvalInfo &info, APValue &result)
  5386. : ExprEvaluatorBaseTy(info), Result(result) {}
  5387. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  5388. assert(E->getType()->isIntegralOrEnumerationType() &&
  5389. "Invalid evaluation result.");
  5390. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  5391. "Invalid evaluation result.");
  5392. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5393. "Invalid evaluation result.");
  5394. Result = APValue(SI);
  5395. return true;
  5396. }
  5397. bool Success(const llvm::APSInt &SI, const Expr *E) {
  5398. return Success(SI, E, Result);
  5399. }
  5400. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  5401. assert(E->getType()->isIntegralOrEnumerationType() &&
  5402. "Invalid evaluation result.");
  5403. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5404. "Invalid evaluation result.");
  5405. Result = APValue(APSInt(I));
  5406. Result.getInt().setIsUnsigned(
  5407. E->getType()->isUnsignedIntegerOrEnumerationType());
  5408. return true;
  5409. }
  5410. bool Success(const llvm::APInt &I, const Expr *E) {
  5411. return Success(I, E, Result);
  5412. }
  5413. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  5414. assert(E->getType()->isIntegralOrEnumerationType() &&
  5415. "Invalid evaluation result.");
  5416. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  5417. return true;
  5418. }
  5419. bool Success(uint64_t Value, const Expr *E) {
  5420. return Success(Value, E, Result);
  5421. }
  5422. bool Success(CharUnits Size, const Expr *E) {
  5423. return Success(Size.getQuantity(), E);
  5424. }
  5425. bool Success(const APValue &V, const Expr *E) {
  5426. if (V.isLValue() || V.isAddrLabelDiff()) {
  5427. Result = V;
  5428. return true;
  5429. }
  5430. return Success(V.getInt(), E);
  5431. }
  5432. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  5433. //===--------------------------------------------------------------------===//
  5434. // Visitor Methods
  5435. //===--------------------------------------------------------------------===//
  5436. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  5437. return Success(E->getValue(), E);
  5438. }
  5439. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  5440. return Success(E->getValue(), E);
  5441. }
  5442. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  5443. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5444. if (CheckReferencedDecl(E, E->getDecl()))
  5445. return true;
  5446. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  5447. }
  5448. bool VisitMemberExpr(const MemberExpr *E) {
  5449. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  5450. VisitIgnoredValue(E->getBase());
  5451. return true;
  5452. }
  5453. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  5454. }
  5455. bool VisitCallExpr(const CallExpr *E);
  5456. bool VisitBinaryOperator(const BinaryOperator *E);
  5457. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  5458. bool VisitUnaryOperator(const UnaryOperator *E);
  5459. bool VisitCastExpr(const CastExpr* E);
  5460. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  5461. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  5462. return Success(E->getValue(), E);
  5463. }
  5464. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  5465. return Success(E->getValue(), E);
  5466. }
  5467. // Note, GNU defines __null as an integer, not a pointer.
  5468. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  5469. return ZeroInitialization(E);
  5470. }
  5471. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  5472. return Success(E->getValue(), E);
  5473. }
  5474. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  5475. return Success(E->getValue(), E);
  5476. }
  5477. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  5478. return Success(E->getValue(), E);
  5479. }
  5480. bool VisitUnaryReal(const UnaryOperator *E);
  5481. bool VisitUnaryImag(const UnaryOperator *E);
  5482. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  5483. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  5484. private:
  5485. static QualType GetObjectType(APValue::LValueBase B);
  5486. bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
  5487. // FIXME: Missing: array subscript of vector, member of vector
  5488. };
  5489. } // end anonymous namespace
  5490. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  5491. /// produce either the integer value or a pointer.
  5492. ///
  5493. /// GCC has a heinous extension which folds casts between pointer types and
  5494. /// pointer-sized integral types. We support this by allowing the evaluation of
  5495. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  5496. /// Some simple arithmetic on such values is supported (they are treated much
  5497. /// like char*).
  5498. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  5499. EvalInfo &Info) {
  5500. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  5501. return IntExprEvaluator(Info, Result).Visit(E);
  5502. }
  5503. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  5504. APValue Val;
  5505. if (!EvaluateIntegerOrLValue(E, Val, Info))
  5506. return false;
  5507. if (!Val.isInt()) {
  5508. // FIXME: It would be better to produce the diagnostic for casting
  5509. // a pointer to an integer.
  5510. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  5511. return false;
  5512. }
  5513. Result = Val.getInt();
  5514. return true;
  5515. }
  5516. /// Check whether the given declaration can be directly converted to an integral
  5517. /// rvalue. If not, no diagnostic is produced; there are other things we can
  5518. /// try.
  5519. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  5520. // Enums are integer constant exprs.
  5521. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  5522. // Check for signedness/width mismatches between E type and ECD value.
  5523. bool SameSign = (ECD->getInitVal().isSigned()
  5524. == E->getType()->isSignedIntegerOrEnumerationType());
  5525. bool SameWidth = (ECD->getInitVal().getBitWidth()
  5526. == Info.Ctx.getIntWidth(E->getType()));
  5527. if (SameSign && SameWidth)
  5528. return Success(ECD->getInitVal(), E);
  5529. else {
  5530. // Get rid of mismatch (otherwise Success assertions will fail)
  5531. // by computing a new value matching the type of E.
  5532. llvm::APSInt Val = ECD->getInitVal();
  5533. if (!SameSign)
  5534. Val.setIsSigned(!ECD->getInitVal().isSigned());
  5535. if (!SameWidth)
  5536. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  5537. return Success(Val, E);
  5538. }
  5539. }
  5540. return false;
  5541. }
  5542. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  5543. /// as GCC.
  5544. static int EvaluateBuiltinClassifyType(const CallExpr *E) {
  5545. // The following enum mimics the values returned by GCC.
  5546. // FIXME: Does GCC differ between lvalue and rvalue references here?
  5547. enum gcc_type_class {
  5548. no_type_class = -1,
  5549. void_type_class, integer_type_class, char_type_class,
  5550. enumeral_type_class, boolean_type_class,
  5551. pointer_type_class, reference_type_class, offset_type_class,
  5552. real_type_class, complex_type_class,
  5553. function_type_class, method_type_class,
  5554. record_type_class, union_type_class,
  5555. array_type_class, string_type_class,
  5556. lang_type_class
  5557. };
  5558. // If no argument was supplied, default to "no_type_class". This isn't
  5559. // ideal, however it is what gcc does.
  5560. if (E->getNumArgs() == 0)
  5561. return no_type_class;
  5562. QualType ArgTy = E->getArg(0)->getType();
  5563. if (ArgTy->isVoidType())
  5564. return void_type_class;
  5565. else if (ArgTy->isEnumeralType())
  5566. return enumeral_type_class;
  5567. else if (ArgTy->isBooleanType())
  5568. return boolean_type_class;
  5569. else if (ArgTy->isCharType())
  5570. return string_type_class; // gcc doesn't appear to use char_type_class
  5571. else if (ArgTy->isIntegerType())
  5572. return integer_type_class;
  5573. else if (ArgTy->isPointerType())
  5574. return pointer_type_class;
  5575. else if (ArgTy->isReferenceType())
  5576. return reference_type_class;
  5577. else if (ArgTy->isRealType())
  5578. return real_type_class;
  5579. else if (ArgTy->isComplexType())
  5580. return complex_type_class;
  5581. else if (ArgTy->isFunctionType())
  5582. return function_type_class;
  5583. else if (ArgTy->isStructureOrClassType())
  5584. return record_type_class;
  5585. else if (ArgTy->isUnionType())
  5586. return union_type_class;
  5587. else if (ArgTy->isArrayType())
  5588. return array_type_class;
  5589. else if (ArgTy->isUnionType())
  5590. return union_type_class;
  5591. else // FIXME: offset_type_class, method_type_class, & lang_type_class?
  5592. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5593. }
  5594. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  5595. /// __builtin_constant_p when applied to the given lvalue.
  5596. ///
  5597. /// An lvalue is only "constant" if it is a pointer or reference to the first
  5598. /// character of a string literal.
  5599. template<typename LValue>
  5600. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  5601. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  5602. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  5603. }
  5604. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  5605. /// GCC as we can manage.
  5606. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  5607. QualType ArgType = Arg->getType();
  5608. // __builtin_constant_p always has one operand. The rules which gcc follows
  5609. // are not precisely documented, but are as follows:
  5610. //
  5611. // - If the operand is of integral, floating, complex or enumeration type,
  5612. // and can be folded to a known value of that type, it returns 1.
  5613. // - If the operand and can be folded to a pointer to the first character
  5614. // of a string literal (or such a pointer cast to an integral type), it
  5615. // returns 1.
  5616. //
  5617. // Otherwise, it returns 0.
  5618. //
  5619. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  5620. // its support for this does not currently work.
  5621. if (ArgType->isIntegralOrEnumerationType()) {
  5622. Expr::EvalResult Result;
  5623. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  5624. return false;
  5625. APValue &V = Result.Val;
  5626. if (V.getKind() == APValue::Int)
  5627. return true;
  5628. return EvaluateBuiltinConstantPForLValue(V);
  5629. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  5630. return Arg->isEvaluatable(Ctx);
  5631. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  5632. LValue LV;
  5633. Expr::EvalStatus Status;
  5634. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  5635. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  5636. : EvaluatePointer(Arg, LV, Info)) &&
  5637. !Status.HasSideEffects)
  5638. return EvaluateBuiltinConstantPForLValue(LV);
  5639. }
  5640. // Anything else isn't considered to be sufficiently constant.
  5641. return false;
  5642. }
  5643. /// Retrieves the "underlying object type" of the given expression,
  5644. /// as used by __builtin_object_size.
  5645. QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
  5646. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  5647. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  5648. return VD->getType();
  5649. } else if (const Expr *E = B.get<const Expr*>()) {
  5650. if (isa<CompoundLiteralExpr>(E))
  5651. return E->getType();
  5652. }
  5653. return QualType();
  5654. }
  5655. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
  5656. LValue Base;
  5657. {
  5658. // The operand of __builtin_object_size is never evaluated for side-effects.
  5659. // If there are any, but we can determine the pointed-to object anyway, then
  5660. // ignore the side-effects.
  5661. SpeculativeEvaluationRAII SpeculativeEval(Info);
  5662. if (!EvaluatePointer(E->getArg(0), Base, Info))
  5663. return false;
  5664. }
  5665. if (!Base.getLValueBase()) {
  5666. // It is not possible to determine which objects ptr points to at compile time,
  5667. // __builtin_object_size should return (size_t) -1 for type 0 or 1
  5668. // and (size_t) 0 for type 2 or 3.
  5669. llvm::APSInt TypeIntVaue;
  5670. const Expr *ExprType = E->getArg(1);
  5671. if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
  5672. return false;
  5673. if (TypeIntVaue == 0 || TypeIntVaue == 1)
  5674. return Success(-1, E);
  5675. if (TypeIntVaue == 2 || TypeIntVaue == 3)
  5676. return Success(0, E);
  5677. return Error(E);
  5678. }
  5679. QualType T = GetObjectType(Base.getLValueBase());
  5680. if (T.isNull() ||
  5681. T->isIncompleteType() ||
  5682. T->isFunctionType() ||
  5683. T->isVariablyModifiedType() ||
  5684. T->isDependentType())
  5685. return Error(E);
  5686. CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
  5687. CharUnits Offset = Base.getLValueOffset();
  5688. if (!Offset.isNegative() && Offset <= Size)
  5689. Size -= Offset;
  5690. else
  5691. Size = CharUnits::Zero();
  5692. return Success(Size, E);
  5693. }
  5694. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5695. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  5696. default:
  5697. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  5698. case Builtin::BI__builtin_object_size: {
  5699. if (TryEvaluateBuiltinObjectSize(E))
  5700. return true;
  5701. // If evaluating the argument has side-effects, we can't determine the size
  5702. // of the object, and so we lower it to unknown now. CodeGen relies on us to
  5703. // handle all cases where the expression has side-effects.
  5704. if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
  5705. if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
  5706. return Success(-1ULL, E);
  5707. return Success(0, E);
  5708. }
  5709. // Expression had no side effects, but we couldn't statically determine the
  5710. // size of the referenced object.
  5711. switch (Info.EvalMode) {
  5712. case EvalInfo::EM_ConstantExpression:
  5713. case EvalInfo::EM_PotentialConstantExpression:
  5714. case EvalInfo::EM_ConstantFold:
  5715. case EvalInfo::EM_EvaluateForOverflow:
  5716. case EvalInfo::EM_IgnoreSideEffects:
  5717. return Error(E);
  5718. case EvalInfo::EM_ConstantExpressionUnevaluated:
  5719. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  5720. return Success(-1ULL, E);
  5721. }
  5722. }
  5723. case Builtin::BI__builtin_bswap16:
  5724. case Builtin::BI__builtin_bswap32:
  5725. case Builtin::BI__builtin_bswap64: {
  5726. APSInt Val;
  5727. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5728. return false;
  5729. return Success(Val.byteSwap(), E);
  5730. }
  5731. case Builtin::BI__builtin_classify_type:
  5732. return Success(EvaluateBuiltinClassifyType(E), E);
  5733. // FIXME: BI__builtin_clrsb
  5734. // FIXME: BI__builtin_clrsbl
  5735. // FIXME: BI__builtin_clrsbll
  5736. case Builtin::BI__builtin_clz:
  5737. case Builtin::BI__builtin_clzl:
  5738. case Builtin::BI__builtin_clzll:
  5739. case Builtin::BI__builtin_clzs: {
  5740. APSInt Val;
  5741. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5742. return false;
  5743. if (!Val)
  5744. return Error(E);
  5745. return Success(Val.countLeadingZeros(), E);
  5746. }
  5747. case Builtin::BI__builtin_constant_p:
  5748. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  5749. case Builtin::BI__builtin_ctz:
  5750. case Builtin::BI__builtin_ctzl:
  5751. case Builtin::BI__builtin_ctzll:
  5752. case Builtin::BI__builtin_ctzs: {
  5753. APSInt Val;
  5754. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5755. return false;
  5756. if (!Val)
  5757. return Error(E);
  5758. return Success(Val.countTrailingZeros(), E);
  5759. }
  5760. case Builtin::BI__builtin_eh_return_data_regno: {
  5761. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  5762. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  5763. return Success(Operand, E);
  5764. }
  5765. case Builtin::BI__builtin_expect:
  5766. return Visit(E->getArg(0));
  5767. case Builtin::BI__builtin_ffs:
  5768. case Builtin::BI__builtin_ffsl:
  5769. case Builtin::BI__builtin_ffsll: {
  5770. APSInt Val;
  5771. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5772. return false;
  5773. unsigned N = Val.countTrailingZeros();
  5774. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  5775. }
  5776. case Builtin::BI__builtin_fpclassify: {
  5777. APFloat Val(0.0);
  5778. if (!EvaluateFloat(E->getArg(5), Val, Info))
  5779. return false;
  5780. unsigned Arg;
  5781. switch (Val.getCategory()) {
  5782. case APFloat::fcNaN: Arg = 0; break;
  5783. case APFloat::fcInfinity: Arg = 1; break;
  5784. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  5785. case APFloat::fcZero: Arg = 4; break;
  5786. }
  5787. return Visit(E->getArg(Arg));
  5788. }
  5789. case Builtin::BI__builtin_isinf_sign: {
  5790. APFloat Val(0.0);
  5791. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5792. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  5793. }
  5794. case Builtin::BI__builtin_isinf: {
  5795. APFloat Val(0.0);
  5796. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5797. Success(Val.isInfinity() ? 1 : 0, E);
  5798. }
  5799. case Builtin::BI__builtin_isfinite: {
  5800. APFloat Val(0.0);
  5801. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5802. Success(Val.isFinite() ? 1 : 0, E);
  5803. }
  5804. case Builtin::BI__builtin_isnan: {
  5805. APFloat Val(0.0);
  5806. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5807. Success(Val.isNaN() ? 1 : 0, E);
  5808. }
  5809. case Builtin::BI__builtin_isnormal: {
  5810. APFloat Val(0.0);
  5811. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5812. Success(Val.isNormal() ? 1 : 0, E);
  5813. }
  5814. case Builtin::BI__builtin_parity:
  5815. case Builtin::BI__builtin_parityl:
  5816. case Builtin::BI__builtin_parityll: {
  5817. APSInt Val;
  5818. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5819. return false;
  5820. return Success(Val.countPopulation() % 2, E);
  5821. }
  5822. case Builtin::BI__builtin_popcount:
  5823. case Builtin::BI__builtin_popcountl:
  5824. case Builtin::BI__builtin_popcountll: {
  5825. APSInt Val;
  5826. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5827. return false;
  5828. return Success(Val.countPopulation(), E);
  5829. }
  5830. case Builtin::BIstrlen:
  5831. // A call to strlen is not a constant expression.
  5832. if (Info.getLangOpts().CPlusPlus11)
  5833. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5834. << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
  5835. else
  5836. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5837. // Fall through.
  5838. case Builtin::BI__builtin_strlen: {
  5839. // As an extension, we support __builtin_strlen() as a constant expression,
  5840. // and support folding strlen() to a constant.
  5841. LValue String;
  5842. if (!EvaluatePointer(E->getArg(0), String, Info))
  5843. return false;
  5844. // Fast path: if it's a string literal, search the string value.
  5845. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  5846. String.getLValueBase().dyn_cast<const Expr *>())) {
  5847. // The string literal may have embedded null characters. Find the first
  5848. // one and truncate there.
  5849. StringRef Str = S->getBytes();
  5850. int64_t Off = String.Offset.getQuantity();
  5851. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  5852. S->getCharByteWidth() == 1) {
  5853. Str = Str.substr(Off);
  5854. StringRef::size_type Pos = Str.find(0);
  5855. if (Pos != StringRef::npos)
  5856. Str = Str.substr(0, Pos);
  5857. return Success(Str.size(), E);
  5858. }
  5859. // Fall through to slow path to issue appropriate diagnostic.
  5860. }
  5861. // Slow path: scan the bytes of the string looking for the terminating 0.
  5862. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5863. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  5864. APValue Char;
  5865. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  5866. !Char.isInt())
  5867. return false;
  5868. if (!Char.getInt())
  5869. return Success(Strlen, E);
  5870. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  5871. return false;
  5872. }
  5873. }
  5874. case Builtin::BI__atomic_always_lock_free:
  5875. case Builtin::BI__atomic_is_lock_free:
  5876. case Builtin::BI__c11_atomic_is_lock_free: {
  5877. APSInt SizeVal;
  5878. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  5879. return false;
  5880. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  5881. // of two less than the maximum inline atomic width, we know it is
  5882. // lock-free. If the size isn't a power of two, or greater than the
  5883. // maximum alignment where we promote atomics, we know it is not lock-free
  5884. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  5885. // the answer can only be determined at runtime; for example, 16-byte
  5886. // atomics have lock-free implementations on some, but not all,
  5887. // x86-64 processors.
  5888. // Check power-of-two.
  5889. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  5890. if (Size.isPowerOfTwo()) {
  5891. // Check against inlining width.
  5892. unsigned InlineWidthBits =
  5893. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  5894. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  5895. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  5896. Size == CharUnits::One() ||
  5897. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  5898. Expr::NPC_NeverValueDependent))
  5899. // OK, we will inline appropriately-aligned operations of this size,
  5900. // and _Atomic(T) is appropriately-aligned.
  5901. return Success(1, E);
  5902. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  5903. castAs<PointerType>()->getPointeeType();
  5904. if (!PointeeType->isIncompleteType() &&
  5905. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  5906. // OK, we will inline operations on this object.
  5907. return Success(1, E);
  5908. }
  5909. }
  5910. }
  5911. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  5912. Success(0, E) : Error(E);
  5913. }
  5914. }
  5915. }
  5916. static bool HasSameBase(const LValue &A, const LValue &B) {
  5917. if (!A.getLValueBase())
  5918. return !B.getLValueBase();
  5919. if (!B.getLValueBase())
  5920. return false;
  5921. if (A.getLValueBase().getOpaqueValue() !=
  5922. B.getLValueBase().getOpaqueValue()) {
  5923. const Decl *ADecl = GetLValueBaseDecl(A);
  5924. if (!ADecl)
  5925. return false;
  5926. const Decl *BDecl = GetLValueBaseDecl(B);
  5927. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  5928. return false;
  5929. }
  5930. return IsGlobalLValue(A.getLValueBase()) ||
  5931. A.getLValueCallIndex() == B.getLValueCallIndex();
  5932. }
  5933. /// \brief Determine whether this is a pointer past the end of the complete
  5934. /// object referred to by the lvalue.
  5935. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  5936. const LValue &LV) {
  5937. // A null pointer can be viewed as being "past the end" but we don't
  5938. // choose to look at it that way here.
  5939. if (!LV.getLValueBase())
  5940. return false;
  5941. // If the designator is valid and refers to a subobject, we're not pointing
  5942. // past the end.
  5943. if (!LV.getLValueDesignator().Invalid &&
  5944. !LV.getLValueDesignator().isOnePastTheEnd())
  5945. return false;
  5946. // We're a past-the-end pointer if we point to the byte after the object,
  5947. // no matter what our type or path is.
  5948. auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
  5949. return LV.getLValueOffset() == Size;
  5950. }
  5951. namespace {
  5952. /// \brief Data recursive integer evaluator of certain binary operators.
  5953. ///
  5954. /// We use a data recursive algorithm for binary operators so that we are able
  5955. /// to handle extreme cases of chained binary operators without causing stack
  5956. /// overflow.
  5957. class DataRecursiveIntBinOpEvaluator {
  5958. struct EvalResult {
  5959. APValue Val;
  5960. bool Failed;
  5961. EvalResult() : Failed(false) { }
  5962. void swap(EvalResult &RHS) {
  5963. Val.swap(RHS.Val);
  5964. Failed = RHS.Failed;
  5965. RHS.Failed = false;
  5966. }
  5967. };
  5968. struct Job {
  5969. const Expr *E;
  5970. EvalResult LHSResult; // meaningful only for binary operator expression.
  5971. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  5972. Job() : StoredInfo(nullptr) {}
  5973. void startSpeculativeEval(EvalInfo &Info) {
  5974. OldEvalStatus = Info.EvalStatus;
  5975. Info.EvalStatus.Diag = nullptr;
  5976. StoredInfo = &Info;
  5977. }
  5978. ~Job() {
  5979. if (StoredInfo) {
  5980. StoredInfo->EvalStatus = OldEvalStatus;
  5981. }
  5982. }
  5983. private:
  5984. EvalInfo *StoredInfo; // non-null if status changed.
  5985. Expr::EvalStatus OldEvalStatus;
  5986. };
  5987. SmallVector<Job, 16> Queue;
  5988. IntExprEvaluator &IntEval;
  5989. EvalInfo &Info;
  5990. APValue &FinalResult;
  5991. public:
  5992. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  5993. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  5994. /// \brief True if \param E is a binary operator that we are going to handle
  5995. /// data recursively.
  5996. /// We handle binary operators that are comma, logical, or that have operands
  5997. /// with integral or enumeration type.
  5998. static bool shouldEnqueue(const BinaryOperator *E) {
  5999. return E->getOpcode() == BO_Comma ||
  6000. E->isLogicalOp() ||
  6001. (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6002. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6003. }
  6004. bool Traverse(const BinaryOperator *E) {
  6005. enqueue(E);
  6006. EvalResult PrevResult;
  6007. while (!Queue.empty())
  6008. process(PrevResult);
  6009. if (PrevResult.Failed) return false;
  6010. FinalResult.swap(PrevResult.Val);
  6011. return true;
  6012. }
  6013. private:
  6014. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6015. return IntEval.Success(Value, E, Result);
  6016. }
  6017. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  6018. return IntEval.Success(Value, E, Result);
  6019. }
  6020. bool Error(const Expr *E) {
  6021. return IntEval.Error(E);
  6022. }
  6023. bool Error(const Expr *E, diag::kind D) {
  6024. return IntEval.Error(E, D);
  6025. }
  6026. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  6027. return Info.CCEDiag(E, D);
  6028. }
  6029. // \brief Returns true if visiting the RHS is necessary, false otherwise.
  6030. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6031. bool &SuppressRHSDiags);
  6032. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6033. const BinaryOperator *E, APValue &Result);
  6034. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  6035. Result.Failed = !Evaluate(Result.Val, Info, E);
  6036. if (Result.Failed)
  6037. Result.Val = APValue();
  6038. }
  6039. void process(EvalResult &Result);
  6040. void enqueue(const Expr *E) {
  6041. E = E->IgnoreParens();
  6042. Queue.resize(Queue.size()+1);
  6043. Queue.back().E = E;
  6044. Queue.back().Kind = Job::AnyExprKind;
  6045. }
  6046. };
  6047. }
  6048. bool DataRecursiveIntBinOpEvaluator::
  6049. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6050. bool &SuppressRHSDiags) {
  6051. if (E->getOpcode() == BO_Comma) {
  6052. // Ignore LHS but note if we could not evaluate it.
  6053. if (LHSResult.Failed)
  6054. return Info.noteSideEffect();
  6055. return true;
  6056. }
  6057. if (E->isLogicalOp()) {
  6058. bool LHSAsBool;
  6059. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  6060. // We were able to evaluate the LHS, see if we can get away with not
  6061. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  6062. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  6063. Success(LHSAsBool, E, LHSResult.Val);
  6064. return false; // Ignore RHS
  6065. }
  6066. } else {
  6067. LHSResult.Failed = true;
  6068. // Since we weren't able to evaluate the left hand side, it
  6069. // must have had side effects.
  6070. if (!Info.noteSideEffect())
  6071. return false;
  6072. // We can't evaluate the LHS; however, sometimes the result
  6073. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6074. // Don't ignore RHS and suppress diagnostics from this arm.
  6075. SuppressRHSDiags = true;
  6076. }
  6077. return true;
  6078. }
  6079. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6080. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6081. if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
  6082. return false; // Ignore RHS;
  6083. return true;
  6084. }
  6085. bool DataRecursiveIntBinOpEvaluator::
  6086. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6087. const BinaryOperator *E, APValue &Result) {
  6088. if (E->getOpcode() == BO_Comma) {
  6089. if (RHSResult.Failed)
  6090. return false;
  6091. Result = RHSResult.Val;
  6092. return true;
  6093. }
  6094. if (E->isLogicalOp()) {
  6095. bool lhsResult, rhsResult;
  6096. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  6097. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  6098. if (LHSIsOK) {
  6099. if (RHSIsOK) {
  6100. if (E->getOpcode() == BO_LOr)
  6101. return Success(lhsResult || rhsResult, E, Result);
  6102. else
  6103. return Success(lhsResult && rhsResult, E, Result);
  6104. }
  6105. } else {
  6106. if (RHSIsOK) {
  6107. // We can't evaluate the LHS; however, sometimes the result
  6108. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6109. if (rhsResult == (E->getOpcode() == BO_LOr))
  6110. return Success(rhsResult, E, Result);
  6111. }
  6112. }
  6113. return false;
  6114. }
  6115. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6116. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6117. if (LHSResult.Failed || RHSResult.Failed)
  6118. return false;
  6119. const APValue &LHSVal = LHSResult.Val;
  6120. const APValue &RHSVal = RHSResult.Val;
  6121. // Handle cases like (unsigned long)&a + 4.
  6122. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  6123. Result = LHSVal;
  6124. CharUnits AdditionalOffset =
  6125. CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
  6126. if (E->getOpcode() == BO_Add)
  6127. Result.getLValueOffset() += AdditionalOffset;
  6128. else
  6129. Result.getLValueOffset() -= AdditionalOffset;
  6130. return true;
  6131. }
  6132. // Handle cases like 4 + (unsigned long)&a
  6133. if (E->getOpcode() == BO_Add &&
  6134. RHSVal.isLValue() && LHSVal.isInt()) {
  6135. Result = RHSVal;
  6136. Result.getLValueOffset() +=
  6137. CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
  6138. return true;
  6139. }
  6140. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  6141. // Handle (intptr_t)&&A - (intptr_t)&&B.
  6142. if (!LHSVal.getLValueOffset().isZero() ||
  6143. !RHSVal.getLValueOffset().isZero())
  6144. return false;
  6145. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  6146. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  6147. if (!LHSExpr || !RHSExpr)
  6148. return false;
  6149. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6150. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6151. if (!LHSAddrExpr || !RHSAddrExpr)
  6152. return false;
  6153. // Make sure both labels come from the same function.
  6154. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6155. RHSAddrExpr->getLabel()->getDeclContext())
  6156. return false;
  6157. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  6158. return true;
  6159. }
  6160. // All the remaining cases expect both operands to be an integer
  6161. if (!LHSVal.isInt() || !RHSVal.isInt())
  6162. return Error(E);
  6163. // Set up the width and signedness manually, in case it can't be deduced
  6164. // from the operation we're performing.
  6165. // FIXME: Don't do this in the cases where we can deduce it.
  6166. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  6167. E->getType()->isUnsignedIntegerOrEnumerationType());
  6168. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  6169. RHSVal.getInt(), Value))
  6170. return false;
  6171. return Success(Value, E, Result);
  6172. }
  6173. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  6174. Job &job = Queue.back();
  6175. switch (job.Kind) {
  6176. case Job::AnyExprKind: {
  6177. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  6178. if (shouldEnqueue(Bop)) {
  6179. job.Kind = Job::BinOpKind;
  6180. enqueue(Bop->getLHS());
  6181. return;
  6182. }
  6183. }
  6184. EvaluateExpr(job.E, Result);
  6185. Queue.pop_back();
  6186. return;
  6187. }
  6188. case Job::BinOpKind: {
  6189. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6190. bool SuppressRHSDiags = false;
  6191. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  6192. Queue.pop_back();
  6193. return;
  6194. }
  6195. if (SuppressRHSDiags)
  6196. job.startSpeculativeEval(Info);
  6197. job.LHSResult.swap(Result);
  6198. job.Kind = Job::BinOpVisitedLHSKind;
  6199. enqueue(Bop->getRHS());
  6200. return;
  6201. }
  6202. case Job::BinOpVisitedLHSKind: {
  6203. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6204. EvalResult RHS;
  6205. RHS.swap(Result);
  6206. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  6207. Queue.pop_back();
  6208. return;
  6209. }
  6210. }
  6211. llvm_unreachable("Invalid Job::Kind!");
  6212. }
  6213. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6214. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  6215. return Error(E);
  6216. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  6217. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  6218. QualType LHSTy = E->getLHS()->getType();
  6219. QualType RHSTy = E->getRHS()->getType();
  6220. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  6221. ComplexValue LHS, RHS;
  6222. bool LHSOK;
  6223. if (E->isAssignmentOp()) {
  6224. LValue LV;
  6225. EvaluateLValue(E->getLHS(), LV, Info);
  6226. LHSOK = false;
  6227. } else if (LHSTy->isRealFloatingType()) {
  6228. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  6229. if (LHSOK) {
  6230. LHS.makeComplexFloat();
  6231. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  6232. }
  6233. } else {
  6234. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  6235. }
  6236. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  6237. return false;
  6238. if (E->getRHS()->getType()->isRealFloatingType()) {
  6239. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  6240. return false;
  6241. RHS.makeComplexFloat();
  6242. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  6243. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  6244. return false;
  6245. if (LHS.isComplexFloat()) {
  6246. APFloat::cmpResult CR_r =
  6247. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  6248. APFloat::cmpResult CR_i =
  6249. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  6250. if (E->getOpcode() == BO_EQ)
  6251. return Success((CR_r == APFloat::cmpEqual &&
  6252. CR_i == APFloat::cmpEqual), E);
  6253. else {
  6254. assert(E->getOpcode() == BO_NE &&
  6255. "Invalid complex comparison.");
  6256. return Success(((CR_r == APFloat::cmpGreaterThan ||
  6257. CR_r == APFloat::cmpLessThan ||
  6258. CR_r == APFloat::cmpUnordered) ||
  6259. (CR_i == APFloat::cmpGreaterThan ||
  6260. CR_i == APFloat::cmpLessThan ||
  6261. CR_i == APFloat::cmpUnordered)), E);
  6262. }
  6263. } else {
  6264. if (E->getOpcode() == BO_EQ)
  6265. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  6266. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  6267. else {
  6268. assert(E->getOpcode() == BO_NE &&
  6269. "Invalid compex comparison.");
  6270. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  6271. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  6272. }
  6273. }
  6274. }
  6275. if (LHSTy->isRealFloatingType() &&
  6276. RHSTy->isRealFloatingType()) {
  6277. APFloat RHS(0.0), LHS(0.0);
  6278. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  6279. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  6280. return false;
  6281. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  6282. return false;
  6283. APFloat::cmpResult CR = LHS.compare(RHS);
  6284. switch (E->getOpcode()) {
  6285. default:
  6286. llvm_unreachable("Invalid binary operator!");
  6287. case BO_LT:
  6288. return Success(CR == APFloat::cmpLessThan, E);
  6289. case BO_GT:
  6290. return Success(CR == APFloat::cmpGreaterThan, E);
  6291. case BO_LE:
  6292. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  6293. case BO_GE:
  6294. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  6295. E);
  6296. case BO_EQ:
  6297. return Success(CR == APFloat::cmpEqual, E);
  6298. case BO_NE:
  6299. return Success(CR == APFloat::cmpGreaterThan
  6300. || CR == APFloat::cmpLessThan
  6301. || CR == APFloat::cmpUnordered, E);
  6302. }
  6303. }
  6304. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  6305. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  6306. LValue LHSValue, RHSValue;
  6307. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  6308. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  6309. return false;
  6310. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  6311. return false;
  6312. // Reject differing bases from the normal codepath; we special-case
  6313. // comparisons to null.
  6314. if (!HasSameBase(LHSValue, RHSValue)) {
  6315. if (E->getOpcode() == BO_Sub) {
  6316. // Handle &&A - &&B.
  6317. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  6318. return false;
  6319. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  6320. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
  6321. if (!LHSExpr || !RHSExpr)
  6322. return false;
  6323. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6324. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6325. if (!LHSAddrExpr || !RHSAddrExpr)
  6326. return false;
  6327. // Make sure both labels come from the same function.
  6328. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6329. RHSAddrExpr->getLabel()->getDeclContext())
  6330. return false;
  6331. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  6332. return true;
  6333. }
  6334. // Inequalities and subtractions between unrelated pointers have
  6335. // unspecified or undefined behavior.
  6336. if (!E->isEqualityOp())
  6337. return Error(E);
  6338. // A constant address may compare equal to the address of a symbol.
  6339. // The one exception is that address of an object cannot compare equal
  6340. // to a null pointer constant.
  6341. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  6342. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  6343. return Error(E);
  6344. // It's implementation-defined whether distinct literals will have
  6345. // distinct addresses. In clang, the result of such a comparison is
  6346. // unspecified, so it is not a constant expression. However, we do know
  6347. // that the address of a literal will be non-null.
  6348. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  6349. LHSValue.Base && RHSValue.Base)
  6350. return Error(E);
  6351. // We can't tell whether weak symbols will end up pointing to the same
  6352. // object.
  6353. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  6354. return Error(E);
  6355. // We can't compare the address of the start of one object with the
  6356. // past-the-end address of another object, per C++ DR1652.
  6357. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  6358. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  6359. (RHSValue.Base && RHSValue.Offset.isZero() &&
  6360. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  6361. return Error(E);
  6362. // We can't tell whether an object is at the same address as another
  6363. // zero sized object.
  6364. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  6365. (LHSValue.Base && isZeroSized(RHSValue)))
  6366. return Error(E);
  6367. // Pointers with different bases cannot represent the same object.
  6368. // (Note that clang defaults to -fmerge-all-constants, which can
  6369. // lead to inconsistent results for comparisons involving the address
  6370. // of a constant; this generally doesn't matter in practice.)
  6371. return Success(E->getOpcode() == BO_NE, E);
  6372. }
  6373. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  6374. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  6375. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  6376. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  6377. if (E->getOpcode() == BO_Sub) {
  6378. // C++11 [expr.add]p6:
  6379. // Unless both pointers point to elements of the same array object, or
  6380. // one past the last element of the array object, the behavior is
  6381. // undefined.
  6382. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  6383. !AreElementsOfSameArray(getType(LHSValue.Base),
  6384. LHSDesignator, RHSDesignator))
  6385. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  6386. QualType Type = E->getLHS()->getType();
  6387. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  6388. CharUnits ElementSize;
  6389. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  6390. return false;
  6391. // As an extension, a type may have zero size (empty struct or union in
  6392. // C, array of zero length). Pointer subtraction in such cases has
  6393. // undefined behavior, so is not constant.
  6394. if (ElementSize.isZero()) {
  6395. Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  6396. << ElementType;
  6397. return false;
  6398. }
  6399. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  6400. // and produce incorrect results when it overflows. Such behavior
  6401. // appears to be non-conforming, but is common, so perhaps we should
  6402. // assume the standard intended for such cases to be undefined behavior
  6403. // and check for them.
  6404. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  6405. // overflow in the final conversion to ptrdiff_t.
  6406. APSInt LHS(
  6407. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  6408. APSInt RHS(
  6409. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  6410. APSInt ElemSize(
  6411. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  6412. APSInt TrueResult = (LHS - RHS) / ElemSize;
  6413. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  6414. if (Result.extend(65) != TrueResult)
  6415. HandleOverflow(Info, E, TrueResult, E->getType());
  6416. return Success(Result, E);
  6417. }
  6418. // C++11 [expr.rel]p3:
  6419. // Pointers to void (after pointer conversions) can be compared, with a
  6420. // result defined as follows: If both pointers represent the same
  6421. // address or are both the null pointer value, the result is true if the
  6422. // operator is <= or >= and false otherwise; otherwise the result is
  6423. // unspecified.
  6424. // We interpret this as applying to pointers to *cv* void.
  6425. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  6426. E->isRelationalOp())
  6427. CCEDiag(E, diag::note_constexpr_void_comparison);
  6428. // C++11 [expr.rel]p2:
  6429. // - If two pointers point to non-static data members of the same object,
  6430. // or to subobjects or array elements fo such members, recursively, the
  6431. // pointer to the later declared member compares greater provided the
  6432. // two members have the same access control and provided their class is
  6433. // not a union.
  6434. // [...]
  6435. // - Otherwise pointer comparisons are unspecified.
  6436. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  6437. E->isRelationalOp()) {
  6438. bool WasArrayIndex;
  6439. unsigned Mismatch =
  6440. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  6441. RHSDesignator, WasArrayIndex);
  6442. // At the point where the designators diverge, the comparison has a
  6443. // specified value if:
  6444. // - we are comparing array indices
  6445. // - we are comparing fields of a union, or fields with the same access
  6446. // Otherwise, the result is unspecified and thus the comparison is not a
  6447. // constant expression.
  6448. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  6449. Mismatch < RHSDesignator.Entries.size()) {
  6450. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  6451. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  6452. if (!LF && !RF)
  6453. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  6454. else if (!LF)
  6455. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  6456. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  6457. << RF->getParent() << RF;
  6458. else if (!RF)
  6459. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  6460. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  6461. << LF->getParent() << LF;
  6462. else if (!LF->getParent()->isUnion() &&
  6463. LF->getAccess() != RF->getAccess())
  6464. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  6465. << LF << LF->getAccess() << RF << RF->getAccess()
  6466. << LF->getParent();
  6467. }
  6468. }
  6469. // The comparison here must be unsigned, and performed with the same
  6470. // width as the pointer.
  6471. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  6472. uint64_t CompareLHS = LHSOffset.getQuantity();
  6473. uint64_t CompareRHS = RHSOffset.getQuantity();
  6474. assert(PtrSize <= 64 && "Unexpected pointer width");
  6475. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  6476. CompareLHS &= Mask;
  6477. CompareRHS &= Mask;
  6478. // If there is a base and this is a relational operator, we can only
  6479. // compare pointers within the object in question; otherwise, the result
  6480. // depends on where the object is located in memory.
  6481. if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
  6482. QualType BaseTy = getType(LHSValue.Base);
  6483. if (BaseTy->isIncompleteType())
  6484. return Error(E);
  6485. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  6486. uint64_t OffsetLimit = Size.getQuantity();
  6487. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  6488. return Error(E);
  6489. }
  6490. switch (E->getOpcode()) {
  6491. default: llvm_unreachable("missing comparison operator");
  6492. case BO_LT: return Success(CompareLHS < CompareRHS, E);
  6493. case BO_GT: return Success(CompareLHS > CompareRHS, E);
  6494. case BO_LE: return Success(CompareLHS <= CompareRHS, E);
  6495. case BO_GE: return Success(CompareLHS >= CompareRHS, E);
  6496. case BO_EQ: return Success(CompareLHS == CompareRHS, E);
  6497. case BO_NE: return Success(CompareLHS != CompareRHS, E);
  6498. }
  6499. }
  6500. }
  6501. if (LHSTy->isMemberPointerType()) {
  6502. assert(E->isEqualityOp() && "unexpected member pointer operation");
  6503. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  6504. MemberPtr LHSValue, RHSValue;
  6505. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  6506. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  6507. return false;
  6508. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  6509. return false;
  6510. // C++11 [expr.eq]p2:
  6511. // If both operands are null, they compare equal. Otherwise if only one is
  6512. // null, they compare unequal.
  6513. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  6514. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  6515. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  6516. }
  6517. // Otherwise if either is a pointer to a virtual member function, the
  6518. // result is unspecified.
  6519. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  6520. if (MD->isVirtual())
  6521. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  6522. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  6523. if (MD->isVirtual())
  6524. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  6525. // Otherwise they compare equal if and only if they would refer to the
  6526. // same member of the same most derived object or the same subobject if
  6527. // they were dereferenced with a hypothetical object of the associated
  6528. // class type.
  6529. bool Equal = LHSValue == RHSValue;
  6530. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  6531. }
  6532. if (LHSTy->isNullPtrType()) {
  6533. assert(E->isComparisonOp() && "unexpected nullptr operation");
  6534. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  6535. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  6536. // are compared, the result is true of the operator is <=, >= or ==, and
  6537. // false otherwise.
  6538. BinaryOperator::Opcode Opcode = E->getOpcode();
  6539. return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
  6540. }
  6541. assert((!LHSTy->isIntegralOrEnumerationType() ||
  6542. !RHSTy->isIntegralOrEnumerationType()) &&
  6543. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  6544. // We can't continue from here for non-integral types.
  6545. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6546. }
  6547. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  6548. /// a result as the expression's type.
  6549. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  6550. const UnaryExprOrTypeTraitExpr *E) {
  6551. switch(E->getKind()) {
  6552. case UETT_AlignOf: {
  6553. if (E->isArgumentType())
  6554. return Success(GetAlignOfType(Info, E->getArgumentType()), E);
  6555. else
  6556. return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
  6557. }
  6558. case UETT_VecStep: {
  6559. QualType Ty = E->getTypeOfArgument();
  6560. if (Ty->isVectorType()) {
  6561. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  6562. // The vec_step built-in functions that take a 3-component
  6563. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  6564. if (n == 3)
  6565. n = 4;
  6566. return Success(n, E);
  6567. } else
  6568. return Success(1, E);
  6569. }
  6570. case UETT_SizeOf: {
  6571. QualType SrcTy = E->getTypeOfArgument();
  6572. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  6573. // the result is the size of the referenced type."
  6574. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  6575. SrcTy = Ref->getPointeeType();
  6576. CharUnits Sizeof;
  6577. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  6578. return false;
  6579. return Success(Sizeof, E);
  6580. }
  6581. case UETT_OpenMPRequiredSimdAlign:
  6582. assert(E->isArgumentType());
  6583. return Success(
  6584. Info.Ctx.toCharUnitsFromBits(
  6585. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  6586. .getQuantity(),
  6587. E);
  6588. // HLSL Change Begins
  6589. case UETT_ArrayLength: {
  6590. QualType SrcTy = E->getTypeOfArgument();
  6591. assert(isa<ConstantArrayType>(SrcTy));
  6592. const ConstantArrayType *CAT = cast<ConstantArrayType>(SrcTy);
  6593. return Success(CAT->getSize(), E);
  6594. }
  6595. // HLSL Change Ends
  6596. }
  6597. llvm_unreachable("unknown expr/type trait");
  6598. }
  6599. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  6600. CharUnits Result;
  6601. unsigned n = OOE->getNumComponents();
  6602. if (n == 0)
  6603. return Error(OOE);
  6604. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  6605. for (unsigned i = 0; i != n; ++i) {
  6606. OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
  6607. switch (ON.getKind()) {
  6608. case OffsetOfExpr::OffsetOfNode::Array: {
  6609. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  6610. APSInt IdxResult;
  6611. if (!EvaluateInteger(Idx, IdxResult, Info))
  6612. return false;
  6613. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  6614. if (!AT)
  6615. return Error(OOE);
  6616. CurrentType = AT->getElementType();
  6617. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  6618. Result += IdxResult.getSExtValue() * ElementSize;
  6619. break;
  6620. }
  6621. case OffsetOfExpr::OffsetOfNode::Field: {
  6622. FieldDecl *MemberDecl = ON.getField();
  6623. const RecordType *RT = CurrentType->getAs<RecordType>();
  6624. if (!RT)
  6625. return Error(OOE);
  6626. RecordDecl *RD = RT->getDecl();
  6627. if (RD->isInvalidDecl()) return false;
  6628. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  6629. unsigned i = MemberDecl->getFieldIndex();
  6630. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  6631. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  6632. CurrentType = MemberDecl->getType().getNonReferenceType();
  6633. break;
  6634. }
  6635. case OffsetOfExpr::OffsetOfNode::Identifier:
  6636. llvm_unreachable("dependent __builtin_offsetof");
  6637. case OffsetOfExpr::OffsetOfNode::Base: {
  6638. CXXBaseSpecifier *BaseSpec = ON.getBase();
  6639. if (BaseSpec->isVirtual())
  6640. return Error(OOE);
  6641. // Find the layout of the class whose base we are looking into.
  6642. const RecordType *RT = CurrentType->getAs<RecordType>();
  6643. if (!RT)
  6644. return Error(OOE);
  6645. RecordDecl *RD = RT->getDecl();
  6646. if (RD->isInvalidDecl()) return false;
  6647. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  6648. // Find the base class itself.
  6649. CurrentType = BaseSpec->getType();
  6650. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  6651. if (!BaseRT)
  6652. return Error(OOE);
  6653. // Add the offset to the base.
  6654. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  6655. break;
  6656. }
  6657. }
  6658. }
  6659. return Success(Result, OOE);
  6660. }
  6661. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  6662. switch (E->getOpcode()) {
  6663. default:
  6664. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  6665. // See C99 6.6p3.
  6666. return Error(E);
  6667. case UO_Extension:
  6668. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  6669. // If so, we could clear the diagnostic ID.
  6670. return Visit(E->getSubExpr());
  6671. case UO_Plus:
  6672. // The result is just the value.
  6673. return Visit(E->getSubExpr());
  6674. case UO_Minus: {
  6675. if (!Visit(E->getSubExpr()))
  6676. return false;
  6677. if (!Result.isInt()) return Error(E);
  6678. const APSInt &Value = Result.getInt();
  6679. if (Value.isSigned() && Value.isMinSignedValue())
  6680. HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  6681. E->getType());
  6682. return Success(-Value, E);
  6683. }
  6684. case UO_Not: {
  6685. if (!Visit(E->getSubExpr()))
  6686. return false;
  6687. if (!Result.isInt()) return Error(E);
  6688. return Success(~Result.getInt(), E);
  6689. }
  6690. case UO_LNot: {
  6691. bool bres;
  6692. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  6693. return false;
  6694. return Success(!bres, E);
  6695. }
  6696. }
  6697. }
  6698. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  6699. /// result type is integer.
  6700. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6701. const Expr *SubExpr = E->getSubExpr();
  6702. QualType DestType = E->getType();
  6703. QualType SrcType = SubExpr->getType();
  6704. switch (E->getCastKind()) {
  6705. case CK_BaseToDerived:
  6706. case CK_DerivedToBase:
  6707. case CK_UncheckedDerivedToBase:
  6708. case CK_Dynamic:
  6709. case CK_ToUnion:
  6710. case CK_ArrayToPointerDecay:
  6711. case CK_FunctionToPointerDecay:
  6712. case CK_NullToPointer:
  6713. case CK_NullToMemberPointer:
  6714. case CK_BaseToDerivedMemberPointer:
  6715. case CK_DerivedToBaseMemberPointer:
  6716. case CK_ReinterpretMemberPointer:
  6717. case CK_ConstructorConversion:
  6718. case CK_IntegralToPointer:
  6719. case CK_ToVoid:
  6720. case CK_VectorSplat:
  6721. case CK_IntegralToFloating:
  6722. case CK_FloatingCast:
  6723. case CK_CPointerToObjCPointerCast:
  6724. case CK_BlockPointerToObjCPointerCast:
  6725. case CK_AnyPointerToBlockPointerCast:
  6726. case CK_ObjCObjectLValueCast:
  6727. case CK_FloatingRealToComplex:
  6728. case CK_FloatingComplexToReal:
  6729. case CK_FloatingComplexCast:
  6730. case CK_FloatingComplexToIntegralComplex:
  6731. case CK_IntegralRealToComplex:
  6732. case CK_IntegralComplexCast:
  6733. case CK_IntegralComplexToFloatingComplex:
  6734. case CK_BuiltinFnToFnPtr:
  6735. case CK_ZeroToOCLEvent:
  6736. case CK_NonAtomicToAtomic:
  6737. case CK_AddressSpaceConversion:
  6738. llvm_unreachable("invalid cast kind for integral value");
  6739. case CK_BitCast:
  6740. case CK_Dependent:
  6741. case CK_LValueBitCast:
  6742. case CK_ARCProduceObject:
  6743. case CK_ARCConsumeObject:
  6744. case CK_ARCReclaimReturnedObject:
  6745. case CK_ARCExtendBlockObject:
  6746. case CK_CopyAndAutoreleaseBlockObject:
  6747. case CK_HLSLVectorToScalarCast: // HLSL Change
  6748. case CK_HLSLMatrixToScalarCast: // HLSL Change
  6749. return Error(E);
  6750. case CK_UserDefinedConversion:
  6751. case CK_LValueToRValue:
  6752. case CK_AtomicToNonAtomic:
  6753. case CK_NoOp:
  6754. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6755. case CK_MemberPointerToBoolean:
  6756. case CK_PointerToBoolean:
  6757. case CK_IntegralToBoolean:
  6758. case CK_FloatingToBoolean:
  6759. case CK_FloatingComplexToBoolean:
  6760. case CK_IntegralComplexToBoolean: {
  6761. bool BoolResult;
  6762. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  6763. return false;
  6764. return Success(BoolResult, E);
  6765. }
  6766. case CK_IntegralCast: {
  6767. if (!Visit(SubExpr))
  6768. return false;
  6769. if (!Result.isInt()) {
  6770. // Allow casts of address-of-label differences if they are no-ops
  6771. // or narrowing. (The narrowing case isn't actually guaranteed to
  6772. // be constant-evaluatable except in some narrow cases which are hard
  6773. // to detect here. We let it through on the assumption the user knows
  6774. // what they are doing.)
  6775. if (Result.isAddrLabelDiff())
  6776. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  6777. // Only allow casts of lvalues if they are lossless.
  6778. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  6779. }
  6780. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  6781. Result.getInt()), E);
  6782. }
  6783. case CK_PointerToIntegral: {
  6784. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6785. LValue LV;
  6786. if (!EvaluatePointer(SubExpr, LV, Info))
  6787. return false;
  6788. if (LV.getLValueBase()) {
  6789. // Only allow based lvalue casts if they are lossless.
  6790. // FIXME: Allow a larger integer size than the pointer size, and allow
  6791. // narrowing back down to pointer width in subsequent integral casts.
  6792. // FIXME: Check integer type's active bits, not its type size.
  6793. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  6794. return Error(E);
  6795. LV.Designator.setInvalid();
  6796. LV.moveInto(Result);
  6797. return true;
  6798. }
  6799. APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
  6800. SrcType);
  6801. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  6802. }
  6803. case CK_IntegralComplexToReal: {
  6804. ComplexValue C;
  6805. if (!EvaluateComplex(SubExpr, C, Info))
  6806. return false;
  6807. return Success(C.getComplexIntReal(), E);
  6808. }
  6809. case CK_FloatingToIntegral: {
  6810. APFloat F(0.0);
  6811. if (!EvaluateFloat(SubExpr, F, Info))
  6812. return false;
  6813. APSInt Value;
  6814. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  6815. return false;
  6816. return Success(Value, E);
  6817. }
  6818. }
  6819. llvm_unreachable("unknown cast resulting in integral value");
  6820. }
  6821. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6822. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6823. ComplexValue LV;
  6824. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  6825. return false;
  6826. if (!LV.isComplexInt())
  6827. return Error(E);
  6828. return Success(LV.getComplexIntReal(), E);
  6829. }
  6830. return Visit(E->getSubExpr());
  6831. }
  6832. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6833. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  6834. ComplexValue LV;
  6835. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  6836. return false;
  6837. if (!LV.isComplexInt())
  6838. return Error(E);
  6839. return Success(LV.getComplexIntImag(), E);
  6840. }
  6841. VisitIgnoredValue(E->getSubExpr());
  6842. return Success(0, E);
  6843. }
  6844. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  6845. return Success(E->getPackLength(), E);
  6846. }
  6847. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  6848. return Success(E->getValue(), E);
  6849. }
  6850. //===----------------------------------------------------------------------===//
  6851. // Float Evaluation
  6852. //===----------------------------------------------------------------------===//
  6853. namespace {
  6854. class FloatExprEvaluator
  6855. : public ExprEvaluatorBase<FloatExprEvaluator> {
  6856. APFloat &Result;
  6857. public:
  6858. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  6859. : ExprEvaluatorBaseTy(info), Result(result) {}
  6860. bool Success(const APValue &V, const Expr *e) {
  6861. Result = V.getFloat();
  6862. return true;
  6863. }
  6864. bool ZeroInitialization(const Expr *E) {
  6865. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  6866. return true;
  6867. }
  6868. bool VisitCallExpr(const CallExpr *E);
  6869. bool VisitUnaryOperator(const UnaryOperator *E);
  6870. bool VisitBinaryOperator(const BinaryOperator *E);
  6871. bool VisitFloatingLiteral(const FloatingLiteral *E);
  6872. bool VisitCastExpr(const CastExpr *E);
  6873. bool VisitUnaryReal(const UnaryOperator *E);
  6874. bool VisitUnaryImag(const UnaryOperator *E);
  6875. // FIXME: Missing: array subscript of vector, member of vector
  6876. };
  6877. } // end anonymous namespace
  6878. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  6879. assert(E->isRValue() && E->getType()->isRealFloatingType());
  6880. return FloatExprEvaluator(Info, Result).Visit(E);
  6881. }
  6882. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  6883. QualType ResultTy,
  6884. const Expr *Arg,
  6885. bool SNaN,
  6886. llvm::APFloat &Result) {
  6887. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  6888. if (!S) return false;
  6889. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  6890. llvm::APInt fill;
  6891. // Treat empty strings as if they were zero.
  6892. if (S->getString().empty())
  6893. fill = llvm::APInt(32, 0);
  6894. else if (S->getString().getAsInteger(0, fill))
  6895. return false;
  6896. if (Context.getTargetInfo().isNan2008()) {
  6897. if (SNaN)
  6898. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  6899. else
  6900. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  6901. } else {
  6902. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  6903. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  6904. // a different encoding to what became a standard in 2008, and for pre-
  6905. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  6906. // sNaN. This is now known as "legacy NaN" encoding.
  6907. if (SNaN)
  6908. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  6909. else
  6910. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  6911. }
  6912. return true;
  6913. }
  6914. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6915. switch (E->getBuiltinCallee()) {
  6916. default:
  6917. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6918. case Builtin::BI__builtin_huge_val:
  6919. case Builtin::BI__builtin_huge_valf:
  6920. case Builtin::BI__builtin_huge_vall:
  6921. case Builtin::BI__builtin_inf:
  6922. case Builtin::BI__builtin_inff:
  6923. case Builtin::BI__builtin_infl: {
  6924. const llvm::fltSemantics &Sem =
  6925. Info.Ctx.getFloatTypeSemantics(E->getType());
  6926. Result = llvm::APFloat::getInf(Sem);
  6927. return true;
  6928. }
  6929. case Builtin::BI__builtin_nans:
  6930. case Builtin::BI__builtin_nansf:
  6931. case Builtin::BI__builtin_nansl:
  6932. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  6933. true, Result))
  6934. return Error(E);
  6935. return true;
  6936. case Builtin::BI__builtin_nan:
  6937. case Builtin::BI__builtin_nanf:
  6938. case Builtin::BI__builtin_nanl:
  6939. // If this is __builtin_nan() turn this into a nan, otherwise we
  6940. // can't constant fold it.
  6941. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  6942. false, Result))
  6943. return Error(E);
  6944. return true;
  6945. case Builtin::BI__builtin_fabs:
  6946. case Builtin::BI__builtin_fabsf:
  6947. case Builtin::BI__builtin_fabsl:
  6948. if (!EvaluateFloat(E->getArg(0), Result, Info))
  6949. return false;
  6950. if (Result.isNegative())
  6951. Result.changeSign();
  6952. return true;
  6953. // FIXME: Builtin::BI__builtin_powi
  6954. // FIXME: Builtin::BI__builtin_powif
  6955. // FIXME: Builtin::BI__builtin_powil
  6956. case Builtin::BI__builtin_copysign:
  6957. case Builtin::BI__builtin_copysignf:
  6958. case Builtin::BI__builtin_copysignl: {
  6959. APFloat RHS(0.);
  6960. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  6961. !EvaluateFloat(E->getArg(1), RHS, Info))
  6962. return false;
  6963. Result.copySign(RHS);
  6964. return true;
  6965. }
  6966. }
  6967. }
  6968. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6969. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6970. ComplexValue CV;
  6971. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  6972. return false;
  6973. Result = CV.FloatReal;
  6974. return true;
  6975. }
  6976. return Visit(E->getSubExpr());
  6977. }
  6978. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6979. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6980. ComplexValue CV;
  6981. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  6982. return false;
  6983. Result = CV.FloatImag;
  6984. return true;
  6985. }
  6986. VisitIgnoredValue(E->getSubExpr());
  6987. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  6988. Result = llvm::APFloat::getZero(Sem);
  6989. return true;
  6990. }
  6991. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  6992. switch (E->getOpcode()) {
  6993. default: return Error(E);
  6994. case UO_Plus:
  6995. return EvaluateFloat(E->getSubExpr(), Result, Info);
  6996. case UO_Minus:
  6997. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  6998. return false;
  6999. Result.changeSign();
  7000. return true;
  7001. }
  7002. }
  7003. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7004. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  7005. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7006. APFloat RHS(0.0);
  7007. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  7008. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  7009. return false;
  7010. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  7011. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  7012. }
  7013. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  7014. Result = E->getValue();
  7015. return true;
  7016. }
  7017. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7018. const Expr* SubExpr = E->getSubExpr();
  7019. switch (E->getCastKind()) {
  7020. default:
  7021. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7022. case CK_IntegralToFloating: {
  7023. APSInt IntResult;
  7024. return EvaluateInteger(SubExpr, IntResult, Info) &&
  7025. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  7026. E->getType(), Result);
  7027. }
  7028. case CK_FloatingCast: {
  7029. if (!Visit(SubExpr))
  7030. return false;
  7031. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  7032. Result);
  7033. }
  7034. case CK_FloatingComplexToReal: {
  7035. ComplexValue V;
  7036. if (!EvaluateComplex(SubExpr, V, Info))
  7037. return false;
  7038. Result = V.getComplexFloatReal();
  7039. return true;
  7040. }
  7041. }
  7042. }
  7043. //===----------------------------------------------------------------------===//
  7044. // Complex Evaluation (for float and integer)
  7045. //===----------------------------------------------------------------------===//
  7046. namespace {
  7047. class ComplexExprEvaluator
  7048. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  7049. ComplexValue &Result;
  7050. public:
  7051. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  7052. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7053. bool Success(const APValue &V, const Expr *e) {
  7054. Result.setFrom(V);
  7055. return true;
  7056. }
  7057. bool ZeroInitialization(const Expr *E);
  7058. //===--------------------------------------------------------------------===//
  7059. // Visitor Methods
  7060. //===--------------------------------------------------------------------===//
  7061. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  7062. bool VisitCastExpr(const CastExpr *E);
  7063. bool VisitBinaryOperator(const BinaryOperator *E);
  7064. bool VisitUnaryOperator(const UnaryOperator *E);
  7065. bool VisitInitListExpr(const InitListExpr *E);
  7066. };
  7067. } // end anonymous namespace
  7068. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  7069. EvalInfo &Info) {
  7070. assert(E->isRValue() && E->getType()->isAnyComplexType());
  7071. return ComplexExprEvaluator(Info, Result).Visit(E);
  7072. }
  7073. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  7074. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  7075. if (ElemTy->isRealFloatingType()) {
  7076. Result.makeComplexFloat();
  7077. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  7078. Result.FloatReal = Zero;
  7079. Result.FloatImag = Zero;
  7080. } else {
  7081. Result.makeComplexInt();
  7082. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  7083. Result.IntReal = Zero;
  7084. Result.IntImag = Zero;
  7085. }
  7086. return true;
  7087. }
  7088. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  7089. const Expr* SubExpr = E->getSubExpr();
  7090. if (SubExpr->getType()->isRealFloatingType()) {
  7091. Result.makeComplexFloat();
  7092. APFloat &Imag = Result.FloatImag;
  7093. if (!EvaluateFloat(SubExpr, Imag, Info))
  7094. return false;
  7095. Result.FloatReal = APFloat(Imag.getSemantics());
  7096. return true;
  7097. } else {
  7098. assert(SubExpr->getType()->isIntegerType() &&
  7099. "Unexpected imaginary literal.");
  7100. Result.makeComplexInt();
  7101. APSInt &Imag = Result.IntImag;
  7102. if (!EvaluateInteger(SubExpr, Imag, Info))
  7103. return false;
  7104. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  7105. return true;
  7106. }
  7107. }
  7108. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7109. switch (E->getCastKind()) {
  7110. case CK_BitCast:
  7111. case CK_BaseToDerived:
  7112. case CK_DerivedToBase:
  7113. case CK_UncheckedDerivedToBase:
  7114. case CK_Dynamic:
  7115. case CK_ToUnion:
  7116. case CK_ArrayToPointerDecay:
  7117. case CK_FunctionToPointerDecay:
  7118. case CK_NullToPointer:
  7119. case CK_NullToMemberPointer:
  7120. case CK_BaseToDerivedMemberPointer:
  7121. case CK_DerivedToBaseMemberPointer:
  7122. case CK_MemberPointerToBoolean:
  7123. case CK_ReinterpretMemberPointer:
  7124. case CK_ConstructorConversion:
  7125. case CK_IntegralToPointer:
  7126. case CK_PointerToIntegral:
  7127. case CK_PointerToBoolean:
  7128. case CK_ToVoid:
  7129. case CK_VectorSplat:
  7130. case CK_IntegralCast:
  7131. case CK_IntegralToBoolean:
  7132. case CK_IntegralToFloating:
  7133. case CK_FloatingToIntegral:
  7134. case CK_FloatingToBoolean:
  7135. case CK_FloatingCast:
  7136. case CK_CPointerToObjCPointerCast:
  7137. case CK_BlockPointerToObjCPointerCast:
  7138. case CK_AnyPointerToBlockPointerCast:
  7139. case CK_ObjCObjectLValueCast:
  7140. case CK_FloatingComplexToReal:
  7141. case CK_FloatingComplexToBoolean:
  7142. case CK_IntegralComplexToReal:
  7143. case CK_IntegralComplexToBoolean:
  7144. case CK_ARCProduceObject:
  7145. case CK_ARCConsumeObject:
  7146. case CK_ARCReclaimReturnedObject:
  7147. case CK_ARCExtendBlockObject:
  7148. case CK_CopyAndAutoreleaseBlockObject:
  7149. case CK_BuiltinFnToFnPtr:
  7150. case CK_ZeroToOCLEvent:
  7151. case CK_NonAtomicToAtomic:
  7152. case CK_AddressSpaceConversion:
  7153. llvm_unreachable("invalid cast kind for complex value");
  7154. case CK_LValueToRValue:
  7155. case CK_AtomicToNonAtomic:
  7156. case CK_NoOp:
  7157. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7158. case CK_Dependent:
  7159. case CK_LValueBitCast:
  7160. case CK_UserDefinedConversion:
  7161. return Error(E);
  7162. case CK_FloatingRealToComplex: {
  7163. APFloat &Real = Result.FloatReal;
  7164. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  7165. return false;
  7166. Result.makeComplexFloat();
  7167. Result.FloatImag = APFloat(Real.getSemantics());
  7168. return true;
  7169. }
  7170. case CK_FloatingComplexCast: {
  7171. if (!Visit(E->getSubExpr()))
  7172. return false;
  7173. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7174. QualType From
  7175. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7176. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  7177. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  7178. }
  7179. case CK_FloatingComplexToIntegralComplex: {
  7180. if (!Visit(E->getSubExpr()))
  7181. return false;
  7182. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7183. QualType From
  7184. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7185. Result.makeComplexInt();
  7186. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  7187. To, Result.IntReal) &&
  7188. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  7189. To, Result.IntImag);
  7190. }
  7191. case CK_IntegralRealToComplex: {
  7192. APSInt &Real = Result.IntReal;
  7193. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  7194. return false;
  7195. Result.makeComplexInt();
  7196. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  7197. return true;
  7198. }
  7199. case CK_IntegralComplexCast: {
  7200. if (!Visit(E->getSubExpr()))
  7201. return false;
  7202. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7203. QualType From
  7204. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7205. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  7206. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  7207. return true;
  7208. }
  7209. case CK_IntegralComplexToFloatingComplex: {
  7210. if (!Visit(E->getSubExpr()))
  7211. return false;
  7212. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  7213. QualType From
  7214. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  7215. Result.makeComplexFloat();
  7216. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  7217. To, Result.FloatReal) &&
  7218. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  7219. To, Result.FloatImag);
  7220. }
  7221. }
  7222. llvm_unreachable("unknown cast resulting in complex value");
  7223. }
  7224. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7225. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  7226. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7227. // Track whether the LHS or RHS is real at the type system level. When this is
  7228. // the case we can simplify our evaluation strategy.
  7229. bool LHSReal = false, RHSReal = false;
  7230. bool LHSOK;
  7231. if (E->getLHS()->getType()->isRealFloatingType()) {
  7232. LHSReal = true;
  7233. APFloat &Real = Result.FloatReal;
  7234. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  7235. if (LHSOK) {
  7236. Result.makeComplexFloat();
  7237. Result.FloatImag = APFloat(Real.getSemantics());
  7238. }
  7239. } else {
  7240. LHSOK = Visit(E->getLHS());
  7241. }
  7242. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  7243. return false;
  7244. ComplexValue RHS;
  7245. if (E->getRHS()->getType()->isRealFloatingType()) {
  7246. RHSReal = true;
  7247. APFloat &Real = RHS.FloatReal;
  7248. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  7249. return false;
  7250. RHS.makeComplexFloat();
  7251. RHS.FloatImag = APFloat(Real.getSemantics());
  7252. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7253. return false;
  7254. assert(!(LHSReal && RHSReal) &&
  7255. "Cannot have both operands of a complex operation be real.");
  7256. switch (E->getOpcode()) {
  7257. default: return Error(E);
  7258. case BO_Add:
  7259. if (Result.isComplexFloat()) {
  7260. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  7261. APFloat::rmNearestTiesToEven);
  7262. if (LHSReal)
  7263. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7264. else if (!RHSReal)
  7265. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  7266. APFloat::rmNearestTiesToEven);
  7267. } else {
  7268. Result.getComplexIntReal() += RHS.getComplexIntReal();
  7269. Result.getComplexIntImag() += RHS.getComplexIntImag();
  7270. }
  7271. break;
  7272. case BO_Sub:
  7273. if (Result.isComplexFloat()) {
  7274. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  7275. APFloat::rmNearestTiesToEven);
  7276. if (LHSReal) {
  7277. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7278. Result.getComplexFloatImag().changeSign();
  7279. } else if (!RHSReal) {
  7280. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  7281. APFloat::rmNearestTiesToEven);
  7282. }
  7283. } else {
  7284. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  7285. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  7286. }
  7287. break;
  7288. case BO_Mul:
  7289. if (Result.isComplexFloat()) {
  7290. // This is an implementation of complex multiplication according to the
  7291. // constraints laid out in C11 Annex G. The implemantion uses the
  7292. // following naming scheme:
  7293. // (a + ib) * (c + id)
  7294. ComplexValue LHS = Result;
  7295. APFloat &A = LHS.getComplexFloatReal();
  7296. APFloat &B = LHS.getComplexFloatImag();
  7297. APFloat &C = RHS.getComplexFloatReal();
  7298. APFloat &D = RHS.getComplexFloatImag();
  7299. APFloat &ResR = Result.getComplexFloatReal();
  7300. APFloat &ResI = Result.getComplexFloatImag();
  7301. if (LHSReal) {
  7302. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  7303. ResR = A * C;
  7304. ResI = A * D;
  7305. } else if (RHSReal) {
  7306. ResR = C * A;
  7307. ResI = C * B;
  7308. } else {
  7309. // In the fully general case, we need to handle NaNs and infinities
  7310. // robustly.
  7311. APFloat AC = A * C;
  7312. APFloat BD = B * D;
  7313. APFloat AD = A * D;
  7314. APFloat BC = B * C;
  7315. ResR = AC - BD;
  7316. ResI = AD + BC;
  7317. if (ResR.isNaN() && ResI.isNaN()) {
  7318. bool Recalc = false;
  7319. if (A.isInfinity() || B.isInfinity()) {
  7320. A = APFloat::copySign(
  7321. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  7322. B = APFloat::copySign(
  7323. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  7324. if (C.isNaN())
  7325. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7326. if (D.isNaN())
  7327. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7328. Recalc = true;
  7329. }
  7330. if (C.isInfinity() || D.isInfinity()) {
  7331. C = APFloat::copySign(
  7332. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  7333. D = APFloat::copySign(
  7334. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  7335. if (A.isNaN())
  7336. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7337. if (B.isNaN())
  7338. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7339. Recalc = true;
  7340. }
  7341. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  7342. AD.isInfinity() || BC.isInfinity())) {
  7343. if (A.isNaN())
  7344. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7345. if (B.isNaN())
  7346. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7347. if (C.isNaN())
  7348. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7349. if (D.isNaN())
  7350. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7351. Recalc = true;
  7352. }
  7353. if (Recalc) {
  7354. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  7355. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  7356. }
  7357. }
  7358. }
  7359. } else {
  7360. ComplexValue LHS = Result;
  7361. Result.getComplexIntReal() =
  7362. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  7363. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  7364. Result.getComplexIntImag() =
  7365. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  7366. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  7367. }
  7368. break;
  7369. case BO_Div:
  7370. if (Result.isComplexFloat()) {
  7371. // This is an implementation of complex division according to the
  7372. // constraints laid out in C11 Annex G. The implemantion uses the
  7373. // following naming scheme:
  7374. // (a + ib) / (c + id)
  7375. ComplexValue LHS = Result;
  7376. APFloat &A = LHS.getComplexFloatReal();
  7377. APFloat &B = LHS.getComplexFloatImag();
  7378. APFloat &C = RHS.getComplexFloatReal();
  7379. APFloat &D = RHS.getComplexFloatImag();
  7380. APFloat &ResR = Result.getComplexFloatReal();
  7381. APFloat &ResI = Result.getComplexFloatImag();
  7382. if (RHSReal) {
  7383. ResR = A / C;
  7384. ResI = B / C;
  7385. } else {
  7386. if (LHSReal) {
  7387. // No real optimizations we can do here, stub out with zero.
  7388. B = APFloat::getZero(A.getSemantics());
  7389. }
  7390. int DenomLogB = 0;
  7391. APFloat MaxCD = maxnum(abs(C), abs(D));
  7392. if (MaxCD.isFinite()) {
  7393. DenomLogB = ilogb(MaxCD);
  7394. C = scalbn(C, -DenomLogB);
  7395. D = scalbn(D, -DenomLogB);
  7396. }
  7397. APFloat Denom = C * C + D * D;
  7398. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
  7399. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
  7400. if (ResR.isNaN() && ResI.isNaN()) {
  7401. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  7402. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  7403. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  7404. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  7405. D.isFinite()) {
  7406. A = APFloat::copySign(
  7407. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  7408. B = APFloat::copySign(
  7409. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  7410. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  7411. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  7412. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  7413. C = APFloat::copySign(
  7414. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  7415. D = APFloat::copySign(
  7416. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  7417. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  7418. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  7419. }
  7420. }
  7421. }
  7422. } else {
  7423. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  7424. return Error(E, diag::note_expr_divide_by_zero);
  7425. ComplexValue LHS = Result;
  7426. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  7427. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  7428. Result.getComplexIntReal() =
  7429. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  7430. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  7431. Result.getComplexIntImag() =
  7432. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  7433. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  7434. }
  7435. break;
  7436. }
  7437. return true;
  7438. }
  7439. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  7440. // Get the operand value into 'Result'.
  7441. if (!Visit(E->getSubExpr()))
  7442. return false;
  7443. switch (E->getOpcode()) {
  7444. default:
  7445. return Error(E);
  7446. case UO_Extension:
  7447. return true;
  7448. case UO_Plus:
  7449. // The result is always just the subexpr.
  7450. return true;
  7451. case UO_Minus:
  7452. if (Result.isComplexFloat()) {
  7453. Result.getComplexFloatReal().changeSign();
  7454. Result.getComplexFloatImag().changeSign();
  7455. }
  7456. else {
  7457. Result.getComplexIntReal() = -Result.getComplexIntReal();
  7458. Result.getComplexIntImag() = -Result.getComplexIntImag();
  7459. }
  7460. return true;
  7461. case UO_Not:
  7462. if (Result.isComplexFloat())
  7463. Result.getComplexFloatImag().changeSign();
  7464. else
  7465. Result.getComplexIntImag() = -Result.getComplexIntImag();
  7466. return true;
  7467. }
  7468. }
  7469. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7470. if (E->getNumInits() == 2) {
  7471. if (E->getType()->isComplexType()) {
  7472. Result.makeComplexFloat();
  7473. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  7474. return false;
  7475. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  7476. return false;
  7477. } else {
  7478. Result.makeComplexInt();
  7479. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  7480. return false;
  7481. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  7482. return false;
  7483. }
  7484. return true;
  7485. }
  7486. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  7487. }
  7488. //===----------------------------------------------------------------------===//
  7489. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  7490. // implicit conversion.
  7491. //===----------------------------------------------------------------------===//
  7492. namespace {
  7493. class AtomicExprEvaluator :
  7494. public ExprEvaluatorBase<AtomicExprEvaluator> {
  7495. APValue &Result;
  7496. public:
  7497. AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
  7498. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7499. bool Success(const APValue &V, const Expr *E) {
  7500. Result = V;
  7501. return true;
  7502. }
  7503. bool ZeroInitialization(const Expr *E) {
  7504. ImplicitValueInitExpr VIE(
  7505. E->getType()->castAs<AtomicType>()->getValueType());
  7506. return Evaluate(Result, Info, &VIE);
  7507. }
  7508. bool VisitCastExpr(const CastExpr *E) {
  7509. switch (E->getCastKind()) {
  7510. default:
  7511. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7512. case CK_NonAtomicToAtomic:
  7513. return Evaluate(Result, Info, E->getSubExpr());
  7514. }
  7515. }
  7516. };
  7517. } // end anonymous namespace
  7518. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
  7519. assert(E->isRValue() && E->getType()->isAtomicType());
  7520. return AtomicExprEvaluator(Info, Result).Visit(E);
  7521. }
  7522. //===----------------------------------------------------------------------===//
  7523. // Void expression evaluation, primarily for a cast to void on the LHS of a
  7524. // comma operator
  7525. //===----------------------------------------------------------------------===//
  7526. namespace {
  7527. class VoidExprEvaluator
  7528. : public ExprEvaluatorBase<VoidExprEvaluator> {
  7529. public:
  7530. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  7531. bool Success(const APValue &V, const Expr *e) { return true; }
  7532. bool VisitCastExpr(const CastExpr *E) {
  7533. switch (E->getCastKind()) {
  7534. default:
  7535. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7536. case CK_ToVoid:
  7537. VisitIgnoredValue(E->getSubExpr());
  7538. return true;
  7539. }
  7540. }
  7541. bool VisitCallExpr(const CallExpr *E) {
  7542. switch (E->getBuiltinCallee()) {
  7543. default:
  7544. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7545. case Builtin::BI__assume:
  7546. case Builtin::BI__builtin_assume:
  7547. // The argument is not evaluated!
  7548. return true;
  7549. }
  7550. }
  7551. };
  7552. } // end anonymous namespace
  7553. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  7554. assert(E->isRValue() && E->getType()->isVoidType());
  7555. return VoidExprEvaluator(Info).Visit(E);
  7556. }
  7557. //===----------------------------------------------------------------------===//
  7558. // Top level Expr::EvaluateAsRValue method.
  7559. //===----------------------------------------------------------------------===//
  7560. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  7561. // In C, function designators are not lvalues, but we evaluate them as if they
  7562. // are.
  7563. // HLSL Change Begins.
  7564. if (Info.getLangOpts().HLSL) {
  7565. if (E->isRValue() && hlsl::IsHLSLVecType(E->getType()) && EvaluateVector(E, Result, Info))
  7566. return true;
  7567. if (E->getStmtClass() == Stmt::InitListExprClass && !E->getType()->isScalarType())
  7568. return false;
  7569. if (E->getStmtClass() == Stmt::DeclRefExprClass) {
  7570. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  7571. const ValueDecl *VD = DRE->getDecl();
  7572. // External variable is in cbuffer, cannot use as immediate.
  7573. if (VD->hasExternalFormalLinkage() &&
  7574. !isa<EnumConstantDecl>(VD))
  7575. return false;
  7576. }
  7577. }
  7578. // HLSL Change Ends.
  7579. QualType T = E->getType();
  7580. if (E->isGLValue() || T->isFunctionType()) {
  7581. LValue LV;
  7582. if (!EvaluateLValue(E, LV, Info))
  7583. return false;
  7584. LV.moveInto(Result);
  7585. } else if (T->isVectorType()) {
  7586. if (!EvaluateVector(E, Result, Info))
  7587. return false;
  7588. } else if (T->isIntegralOrEnumerationType()) {
  7589. if (!IntExprEvaluator(Info, Result).Visit(E))
  7590. return false;
  7591. } else if (T->hasPointerRepresentation()) {
  7592. LValue LV;
  7593. if (!EvaluatePointer(E, LV, Info))
  7594. return false;
  7595. LV.moveInto(Result);
  7596. } else if (T->isRealFloatingType()) {
  7597. llvm::APFloat F(0.0);
  7598. if (!EvaluateFloat(E, F, Info))
  7599. return false;
  7600. Result = APValue(F);
  7601. } else if (T->isAnyComplexType()) {
  7602. ComplexValue C;
  7603. if (!EvaluateComplex(E, C, Info))
  7604. return false;
  7605. C.moveInto(Result);
  7606. } else if (T->isMemberPointerType()) {
  7607. MemberPtr P;
  7608. if (!EvaluateMemberPointer(E, P, Info))
  7609. return false;
  7610. P.moveInto(Result);
  7611. return true;
  7612. } else if (T->isArrayType()) {
  7613. LValue LV;
  7614. LV.set(E, Info.CurrentCall->Index);
  7615. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  7616. if (!EvaluateArray(E, LV, Value, Info))
  7617. return false;
  7618. Result = Value;
  7619. } else if (T->isRecordType()) {
  7620. LValue LV;
  7621. LV.set(E, Info.CurrentCall->Index);
  7622. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  7623. if (!EvaluateRecord(E, LV, Value, Info))
  7624. return false;
  7625. Result = Value;
  7626. } else if (T->isVoidType()) {
  7627. if (!Info.getLangOpts().CPlusPlus11)
  7628. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  7629. << E->getType();
  7630. if (!EvaluateVoid(E, Info))
  7631. return false;
  7632. } else if (T->isAtomicType()) {
  7633. if (!EvaluateAtomic(E, Result, Info))
  7634. return false;
  7635. } else if (Info.getLangOpts().CPlusPlus11) {
  7636. Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
  7637. return false;
  7638. } else {
  7639. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  7640. return false;
  7641. }
  7642. return true;
  7643. }
  7644. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  7645. /// cases, the in-place evaluation is essential, since later initializers for
  7646. /// an object can indirectly refer to subobjects which were initialized earlier.
  7647. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  7648. const Expr *E, bool AllowNonLiteralTypes) {
  7649. assert(!E->isValueDependent());
  7650. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  7651. return false;
  7652. if (E->isRValue()) {
  7653. // Evaluate arrays and record types in-place, so that later initializers can
  7654. // refer to earlier-initialized members of the object.
  7655. if (E->getType()->isArrayType())
  7656. return EvaluateArray(E, This, Result, Info);
  7657. else if (E->getType()->isRecordType())
  7658. return EvaluateRecord(E, This, Result, Info);
  7659. }
  7660. // For any other type, in-place evaluation is unimportant.
  7661. return Evaluate(Result, Info, E);
  7662. }
  7663. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  7664. /// lvalue-to-rvalue cast if it is an lvalue.
  7665. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  7666. if (E->getType().isNull())
  7667. return false;
  7668. if (!CheckLiteralType(Info, E))
  7669. return false;
  7670. if (!::Evaluate(Result, Info, E))
  7671. return false;
  7672. if (E->isGLValue()) {
  7673. LValue LV;
  7674. LV.setFrom(Info.Ctx, Result);
  7675. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  7676. return false;
  7677. }
  7678. // Check this core constant expression is a constant expression.
  7679. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  7680. }
  7681. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  7682. const ASTContext &Ctx, bool &IsConst) {
  7683. // Fast-path evaluations of integer literals, since we sometimes see files
  7684. // containing vast quantities of these.
  7685. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  7686. Result.Val = APValue(APSInt(L->getValue(),
  7687. L->getType()->isUnsignedIntegerType()));
  7688. IsConst = true;
  7689. return true;
  7690. }
  7691. // This case should be rare, but we need to check it before we check on
  7692. // the type below.
  7693. if (Exp->getType().isNull()) {
  7694. IsConst = false;
  7695. return true;
  7696. }
  7697. // FIXME: Evaluating values of large array and record types can cause
  7698. // performance problems. Only do so in C++11 for now.
  7699. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  7700. Exp->getType()->isRecordType()) &&
  7701. !hlsl::IsHLSLVecMatType(Exp->getType()) && // HLSL Change
  7702. !Ctx.getLangOpts().CPlusPlus11) {
  7703. IsConst = false;
  7704. return true;
  7705. }
  7706. return false;
  7707. }
  7708. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  7709. /// any crazy technique (that has nothing to do with language standards) that
  7710. /// we want to. If this function returns true, it returns the folded constant
  7711. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  7712. /// will be applied to the result.
  7713. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  7714. bool IsConst;
  7715. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  7716. return IsConst;
  7717. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  7718. return ::EvaluateAsRValue(Info, this, Result.Val);
  7719. }
  7720. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  7721. const ASTContext &Ctx) const {
  7722. EvalResult Scratch;
  7723. return EvaluateAsRValue(Scratch, Ctx) &&
  7724. HandleConversionToBool(Scratch.Val, Result);
  7725. }
  7726. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  7727. SideEffectsKind AllowSideEffects) const {
  7728. if (!getType()->isIntegralOrEnumerationType())
  7729. return false;
  7730. EvalResult ExprResult;
  7731. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  7732. (!AllowSideEffects && ExprResult.HasSideEffects))
  7733. return false;
  7734. Result = ExprResult.Val.getInt();
  7735. return true;
  7736. }
  7737. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  7738. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  7739. LValue LV;
  7740. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  7741. !CheckLValueConstantExpression(Info, getExprLoc(),
  7742. Ctx.getLValueReferenceType(getType()), LV))
  7743. return false;
  7744. LV.moveInto(Result.Val);
  7745. return true;
  7746. }
  7747. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  7748. const VarDecl *VD,
  7749. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  7750. // FIXME: Evaluating initializers for large array and record types can cause
  7751. // performance problems. Only do so in C++11 for now.
  7752. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  7753. !Ctx.getLangOpts().CPlusPlus11)
  7754. return false;
  7755. Expr::EvalStatus EStatus;
  7756. EStatus.Diag = &Notes;
  7757. EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
  7758. InitInfo.setEvaluatingDecl(VD, Value);
  7759. LValue LVal;
  7760. LVal.set(VD);
  7761. // C++11 [basic.start.init]p2:
  7762. // Variables with static storage duration or thread storage duration shall be
  7763. // zero-initialized before any other initialization takes place.
  7764. // This behavior is not present in C.
  7765. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  7766. !VD->getType()->isReferenceType()) {
  7767. ImplicitValueInitExpr VIE(VD->getType());
  7768. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  7769. /*AllowNonLiteralTypes=*/true))
  7770. return false;
  7771. }
  7772. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  7773. /*AllowNonLiteralTypes=*/true) ||
  7774. EStatus.HasSideEffects)
  7775. return false;
  7776. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  7777. Value);
  7778. }
  7779. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  7780. /// constant folded, but discard the result.
  7781. bool Expr::isEvaluatable(const ASTContext &Ctx) const {
  7782. EvalResult Result;
  7783. return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
  7784. }
  7785. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  7786. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  7787. EvalResult EvalResult;
  7788. EvalResult.Diag = Diag;
  7789. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  7790. (void)Result;
  7791. assert(Result && "Could not evaluate expression");
  7792. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  7793. return EvalResult.Val.getInt();
  7794. }
  7795. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  7796. bool IsConst;
  7797. EvalResult EvalResult;
  7798. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  7799. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  7800. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  7801. }
  7802. }
  7803. bool Expr::EvalResult::isGlobalLValue() const {
  7804. assert(Val.isLValue());
  7805. return IsGlobalLValue(Val.getLValueBase());
  7806. }
  7807. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  7808. /// an integer constant expression.
  7809. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  7810. /// comma, etc
  7811. // CheckICE - This function does the fundamental ICE checking: the returned
  7812. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  7813. // and a (possibly null) SourceLocation indicating the location of the problem.
  7814. //
  7815. // Note that to reduce code duplication, this helper does no evaluation
  7816. // itself; the caller checks whether the expression is evaluatable, and
  7817. // in the rare cases where CheckICE actually cares about the evaluated
  7818. // value, it calls into Evalute.
  7819. namespace {
  7820. enum ICEKind {
  7821. /// This expression is an ICE.
  7822. IK_ICE,
  7823. /// This expression is not an ICE, but if it isn't evaluated, it's
  7824. /// a legal subexpression for an ICE. This return value is used to handle
  7825. /// the comma operator in C99 mode, and non-constant subexpressions.
  7826. IK_ICEIfUnevaluated,
  7827. /// This expression is not an ICE, and is not a legal subexpression for one.
  7828. IK_NotICE
  7829. };
  7830. struct ICEDiag {
  7831. ICEKind Kind;
  7832. SourceLocation Loc;
  7833. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  7834. };
  7835. }
  7836. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  7837. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  7838. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  7839. Expr::EvalResult EVResult;
  7840. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  7841. !EVResult.Val.isInt())
  7842. return ICEDiag(IK_NotICE, E->getLocStart());
  7843. return NoDiag();
  7844. }
  7845. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  7846. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  7847. if (!E->getType()->isIntegralOrEnumerationType())
  7848. return ICEDiag(IK_NotICE, E->getLocStart());
  7849. switch (E->getStmtClass()) {
  7850. #define ABSTRACT_STMT(Node)
  7851. #define STMT(Node, Base) case Expr::Node##Class:
  7852. #define EXPR(Node, Base)
  7853. #include "clang/AST/StmtNodes.inc"
  7854. case Expr::PredefinedExprClass:
  7855. case Expr::FloatingLiteralClass:
  7856. case Expr::ImaginaryLiteralClass:
  7857. case Expr::StringLiteralClass:
  7858. case Expr::ArraySubscriptExprClass:
  7859. case Expr::MemberExprClass:
  7860. case Expr::CompoundAssignOperatorClass:
  7861. case Expr::CompoundLiteralExprClass:
  7862. case Expr::ExtVectorElementExprClass:
  7863. case Expr::ExtMatrixElementExprClass: // HLSL Change
  7864. case Expr::HLSLVectorElementExprClass: // HLSL Change
  7865. case Expr::DesignatedInitExprClass:
  7866. case Expr::NoInitExprClass:
  7867. case Expr::DesignatedInitUpdateExprClass:
  7868. case Expr::ImplicitValueInitExprClass:
  7869. case Expr::ParenListExprClass:
  7870. case Expr::VAArgExprClass:
  7871. case Expr::AddrLabelExprClass:
  7872. case Expr::StmtExprClass:
  7873. case Expr::CXXMemberCallExprClass:
  7874. case Expr::CUDAKernelCallExprClass:
  7875. case Expr::CXXDynamicCastExprClass:
  7876. case Expr::CXXTypeidExprClass:
  7877. case Expr::CXXUuidofExprClass:
  7878. case Expr::MSPropertyRefExprClass:
  7879. case Expr::CXXNullPtrLiteralExprClass:
  7880. case Expr::UserDefinedLiteralClass:
  7881. case Expr::CXXThisExprClass:
  7882. case Expr::CXXThrowExprClass:
  7883. case Expr::CXXNewExprClass:
  7884. case Expr::CXXDeleteExprClass:
  7885. case Expr::CXXPseudoDestructorExprClass:
  7886. case Expr::UnresolvedLookupExprClass:
  7887. case Expr::TypoExprClass:
  7888. case Expr::DependentScopeDeclRefExprClass:
  7889. case Expr::CXXConstructExprClass:
  7890. case Expr::CXXStdInitializerListExprClass:
  7891. case Expr::CXXBindTemporaryExprClass:
  7892. case Expr::ExprWithCleanupsClass:
  7893. case Expr::CXXTemporaryObjectExprClass:
  7894. case Expr::CXXUnresolvedConstructExprClass:
  7895. case Expr::CXXDependentScopeMemberExprClass:
  7896. case Expr::UnresolvedMemberExprClass:
  7897. case Expr::ObjCStringLiteralClass:
  7898. case Expr::ObjCBoxedExprClass:
  7899. case Expr::ObjCArrayLiteralClass:
  7900. case Expr::ObjCDictionaryLiteralClass:
  7901. case Expr::ObjCEncodeExprClass:
  7902. case Expr::ObjCMessageExprClass:
  7903. case Expr::ObjCSelectorExprClass:
  7904. case Expr::ObjCProtocolExprClass:
  7905. case Expr::ObjCIvarRefExprClass:
  7906. case Expr::ObjCPropertyRefExprClass:
  7907. case Expr::ObjCSubscriptRefExprClass:
  7908. case Expr::ObjCIsaExprClass:
  7909. case Expr::ShuffleVectorExprClass:
  7910. case Expr::ConvertVectorExprClass:
  7911. case Expr::BlockExprClass:
  7912. case Expr::NoStmtClass:
  7913. case Expr::OpaqueValueExprClass:
  7914. case Expr::PackExpansionExprClass:
  7915. case Expr::SubstNonTypeTemplateParmPackExprClass:
  7916. case Expr::FunctionParmPackExprClass:
  7917. case Expr::AsTypeExprClass:
  7918. case Expr::ObjCIndirectCopyRestoreExprClass:
  7919. case Expr::MaterializeTemporaryExprClass:
  7920. case Expr::PseudoObjectExprClass:
  7921. case Expr::AtomicExprClass:
  7922. case Expr::LambdaExprClass:
  7923. case Expr::CXXFoldExprClass:
  7924. return ICEDiag(IK_NotICE, E->getLocStart());
  7925. case Expr::InitListExprClass: {
  7926. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  7927. // form "T x = { a };" is equivalent to "T x = a;".
  7928. // Unless we're initializing a reference, T is a scalar as it is known to be
  7929. // of integral or enumeration type.
  7930. if (E->isRValue() && (!Ctx.getLangOpts().HLSL || E->getType()->isScalarType() || IsHLSLVecInitList(E))) // HLSL Change
  7931. if (cast<InitListExpr>(E)->getNumInits() == 1)
  7932. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  7933. return ICEDiag(IK_NotICE, E->getLocStart());
  7934. }
  7935. case Expr::SizeOfPackExprClass:
  7936. case Expr::GNUNullExprClass:
  7937. // GCC considers the GNU __null value to be an integral constant expression.
  7938. return NoDiag();
  7939. case Expr::SubstNonTypeTemplateParmExprClass:
  7940. return
  7941. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  7942. case Expr::ParenExprClass:
  7943. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  7944. case Expr::GenericSelectionExprClass:
  7945. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  7946. case Expr::IntegerLiteralClass:
  7947. case Expr::CharacterLiteralClass:
  7948. case Expr::ObjCBoolLiteralExprClass:
  7949. case Expr::CXXBoolLiteralExprClass:
  7950. case Expr::CXXScalarValueInitExprClass:
  7951. case Expr::TypeTraitExprClass:
  7952. case Expr::ArrayTypeTraitExprClass:
  7953. case Expr::ExpressionTraitExprClass:
  7954. case Expr::CXXNoexceptExprClass:
  7955. return NoDiag();
  7956. case Expr::CallExprClass:
  7957. case Expr::CXXOperatorCallExprClass: {
  7958. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  7959. // constant expressions, but they can never be ICEs because an ICE cannot
  7960. // contain an operand of (pointer to) function type.
  7961. const CallExpr *CE = cast<CallExpr>(E);
  7962. if (hlsl::IsIntrinsicOp(GetCallExprFunction(CE)) || CE->getBuiltinCallee()) // HLSL Change
  7963. return CheckEvalInICE(E, Ctx);
  7964. return ICEDiag(IK_NotICE, E->getLocStart());
  7965. }
  7966. case Expr::DeclRefExprClass: {
  7967. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  7968. return NoDiag();
  7969. const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
  7970. if (Ctx.getLangOpts().CPlusPlus &&
  7971. D && IsConstNonVolatile(D->getType())) {
  7972. // Parameter variables are never constants. Without this check,
  7973. // getAnyInitializer() can find a default argument, which leads
  7974. // to chaos.
  7975. if (isa<ParmVarDecl>(D))
  7976. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7977. // C++ 7.1.5.1p2
  7978. // A variable of non-volatile const-qualified integral or enumeration
  7979. // type initialized by an ICE can be used in ICEs.
  7980. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  7981. if (!Dcl->getType()->isIntegralOrEnumerationType())
  7982. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7983. // HLSL Change: cbuffer vars with init are not really constant in this way
  7984. if (Ctx.getLangOpts().HLSL &&
  7985. Dcl->hasGlobalStorage() &&
  7986. Dcl->getStorageClass() != SC_Static) {
  7987. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7988. }
  7989. const VarDecl *VD;
  7990. // Look for a declaration of this variable that has an initializer, and
  7991. // check whether it is an ICE.
  7992. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  7993. return NoDiag();
  7994. else
  7995. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7996. }
  7997. }
  7998. return ICEDiag(IK_NotICE, E->getLocStart());
  7999. }
  8000. case Expr::UnaryOperatorClass: {
  8001. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  8002. switch (Exp->getOpcode()) {
  8003. case UO_PostInc:
  8004. case UO_PostDec:
  8005. case UO_PreInc:
  8006. case UO_PreDec:
  8007. case UO_AddrOf:
  8008. case UO_Deref:
  8009. // C99 6.6/3 allows increment and decrement within unevaluated
  8010. // subexpressions of constant expressions, but they can never be ICEs
  8011. // because an ICE cannot contain an lvalue operand.
  8012. return ICEDiag(IK_NotICE, E->getLocStart());
  8013. case UO_Extension:
  8014. case UO_LNot:
  8015. case UO_Plus:
  8016. case UO_Minus:
  8017. case UO_Not:
  8018. case UO_Real:
  8019. case UO_Imag:
  8020. return CheckICE(Exp->getSubExpr(), Ctx);
  8021. }
  8022. // OffsetOf falls through here.
  8023. }
  8024. case Expr::OffsetOfExprClass: {
  8025. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  8026. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  8027. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  8028. // compliance: we should warn earlier for offsetof expressions with
  8029. // array subscripts that aren't ICEs, and if the array subscripts
  8030. // are ICEs, the value of the offsetof must be an integer constant.
  8031. return CheckEvalInICE(E, Ctx);
  8032. }
  8033. case Expr::UnaryExprOrTypeTraitExprClass: {
  8034. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  8035. if ((Exp->getKind() == UETT_SizeOf) &&
  8036. Exp->getTypeOfArgument()->isVariableArrayType())
  8037. return ICEDiag(IK_NotICE, E->getLocStart());
  8038. return NoDiag();
  8039. }
  8040. case Expr::BinaryOperatorClass: {
  8041. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  8042. switch (Exp->getOpcode()) {
  8043. case BO_PtrMemD:
  8044. case BO_PtrMemI:
  8045. case BO_Assign:
  8046. case BO_MulAssign:
  8047. case BO_DivAssign:
  8048. case BO_RemAssign:
  8049. case BO_AddAssign:
  8050. case BO_SubAssign:
  8051. case BO_ShlAssign:
  8052. case BO_ShrAssign:
  8053. case BO_AndAssign:
  8054. case BO_XorAssign:
  8055. case BO_OrAssign:
  8056. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  8057. // constant expressions, but they can never be ICEs because an ICE cannot
  8058. // contain an lvalue operand.
  8059. return ICEDiag(IK_NotICE, E->getLocStart());
  8060. case BO_Mul:
  8061. case BO_Div:
  8062. case BO_Rem:
  8063. case BO_Add:
  8064. case BO_Sub:
  8065. case BO_Shl:
  8066. case BO_Shr:
  8067. case BO_LT:
  8068. case BO_GT:
  8069. case BO_LE:
  8070. case BO_GE:
  8071. case BO_EQ:
  8072. case BO_NE:
  8073. case BO_And:
  8074. case BO_Xor:
  8075. case BO_Or:
  8076. case BO_Comma: {
  8077. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8078. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8079. if (Exp->getOpcode() == BO_Div ||
  8080. Exp->getOpcode() == BO_Rem) {
  8081. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  8082. // we don't evaluate one.
  8083. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  8084. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  8085. if (REval == 0)
  8086. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8087. if (REval.isSigned() && REval.isAllOnesValue()) {
  8088. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  8089. if (LEval.isMinSignedValue())
  8090. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8091. }
  8092. }
  8093. }
  8094. if (Exp->getOpcode() == BO_Comma && !Ctx.getLangOpts().HLSL) { // HLSL Change: comma is allowed in ICE
  8095. if (Ctx.getLangOpts().C99) {
  8096. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  8097. // if it isn't evaluated.
  8098. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  8099. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8100. } else {
  8101. // In both C89 and C++, commas in ICEs are illegal.
  8102. return ICEDiag(IK_NotICE, E->getLocStart());
  8103. }
  8104. }
  8105. return Worst(LHSResult, RHSResult);
  8106. }
  8107. case BO_LAnd:
  8108. case BO_LOr: {
  8109. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8110. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8111. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  8112. // Rare case where the RHS has a comma "side-effect"; we need
  8113. // to actually check the condition to see whether the side
  8114. // with the comma is evaluated.
  8115. if ((Exp->getOpcode() == BO_LAnd) !=
  8116. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  8117. return RHSResult;
  8118. return NoDiag();
  8119. }
  8120. return Worst(LHSResult, RHSResult);
  8121. }
  8122. }
  8123. }
  8124. case Expr::ImplicitCastExprClass:
  8125. case Expr::CStyleCastExprClass:
  8126. case Expr::CXXFunctionalCastExprClass:
  8127. case Expr::CXXStaticCastExprClass:
  8128. case Expr::CXXReinterpretCastExprClass:
  8129. case Expr::CXXConstCastExprClass:
  8130. case Expr::ObjCBridgedCastExprClass: {
  8131. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  8132. if (isa<ExplicitCastExpr>(E)) {
  8133. if (const FloatingLiteral *FL
  8134. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  8135. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  8136. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  8137. APSInt IgnoredVal(DestWidth, !DestSigned);
  8138. bool Ignored;
  8139. // If the value does not fit in the destination type, the behavior is
  8140. // undefined, so we are not required to treat it as a constant
  8141. // expression.
  8142. if (FL->getValue().convertToInteger(IgnoredVal,
  8143. llvm::APFloat::rmTowardZero,
  8144. &Ignored) & APFloat::opInvalidOp)
  8145. return ICEDiag(IK_NotICE, E->getLocStart());
  8146. return NoDiag();
  8147. }
  8148. }
  8149. switch (cast<CastExpr>(E)->getCastKind()) {
  8150. case CK_LValueToRValue:
  8151. case CK_AtomicToNonAtomic:
  8152. case CK_NonAtomicToAtomic:
  8153. case CK_NoOp:
  8154. case CK_IntegralToBoolean:
  8155. case CK_IntegralCast:
  8156. return CheckICE(SubExpr, Ctx);
  8157. default:
  8158. return ICEDiag(IK_NotICE, E->getLocStart());
  8159. }
  8160. }
  8161. case Expr::BinaryConditionalOperatorClass: {
  8162. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  8163. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  8164. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  8165. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8166. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  8167. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  8168. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  8169. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  8170. return FalseResult;
  8171. }
  8172. case Expr::ConditionalOperatorClass: {
  8173. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  8174. // If the condition (ignoring parens) is a __builtin_constant_p call,
  8175. // then only the true side is actually considered in an integer constant
  8176. // expression, and it is fully evaluated. This is an important GNU
  8177. // extension. See GCC PR38377 for discussion.
  8178. if (const CallExpr *CallCE
  8179. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  8180. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  8181. return CheckEvalInICE(E, Ctx);
  8182. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  8183. if (CondResult.Kind == IK_NotICE)
  8184. return CondResult;
  8185. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  8186. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8187. if (TrueResult.Kind == IK_NotICE)
  8188. return TrueResult;
  8189. if (FalseResult.Kind == IK_NotICE)
  8190. return FalseResult;
  8191. if (CondResult.Kind == IK_ICEIfUnevaluated)
  8192. return CondResult;
  8193. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  8194. return NoDiag();
  8195. // Rare case where the diagnostics depend on which side is evaluated
  8196. // Note that if we get here, CondResult is 0, and at least one of
  8197. // TrueResult and FalseResult is non-zero.
  8198. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  8199. return FalseResult;
  8200. return TrueResult;
  8201. }
  8202. case Expr::CXXDefaultArgExprClass:
  8203. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  8204. case Expr::CXXDefaultInitExprClass:
  8205. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  8206. case Expr::ChooseExprClass: {
  8207. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  8208. }
  8209. }
  8210. llvm_unreachable("Invalid StmtClass!");
  8211. }
  8212. /// Evaluate an expression as a C++11 integral constant expression.
  8213. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  8214. const Expr *E,
  8215. llvm::APSInt *Value,
  8216. SourceLocation *Loc) {
  8217. if (!E->getType()->isIntegralOrEnumerationType()) {
  8218. if (Loc) *Loc = E->getExprLoc();
  8219. return false;
  8220. }
  8221. APValue Result;
  8222. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  8223. return false;
  8224. if (!Result.isInt()) {
  8225. if (Loc) *Loc = E->getExprLoc();
  8226. return false;
  8227. }
  8228. if (Value) *Value = Result.getInt();
  8229. return true;
  8230. }
  8231. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  8232. SourceLocation *Loc) const {
  8233. if (Ctx.getLangOpts().CPlusPlus11)
  8234. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  8235. ICEDiag D = CheckICE(this, Ctx);
  8236. if (D.Kind != IK_ICE) {
  8237. if (Loc) *Loc = D.Loc;
  8238. return false;
  8239. }
  8240. return true;
  8241. }
  8242. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  8243. SourceLocation *Loc, bool isEvaluated) const {
  8244. if (Ctx.getLangOpts().CPlusPlus11)
  8245. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  8246. if (!isIntegerConstantExpr(Ctx, Loc))
  8247. return false;
  8248. if (!EvaluateAsInt(Value, Ctx))
  8249. llvm_unreachable("ICE cannot be evaluated!");
  8250. return true;
  8251. }
  8252. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  8253. return CheckICE(this, Ctx).Kind == IK_ICE;
  8254. }
  8255. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  8256. SourceLocation *Loc) const {
  8257. // We support this checking in C++98 mode in order to diagnose compatibility
  8258. // issues.
  8259. assert(Ctx.getLangOpts().CPlusPlus);
  8260. // Build evaluation settings.
  8261. Expr::EvalStatus Status;
  8262. SmallVector<PartialDiagnosticAt, 8> Diags;
  8263. Status.Diag = &Diags;
  8264. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  8265. APValue Scratch;
  8266. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  8267. if (!Diags.empty()) {
  8268. IsConstExpr = false;
  8269. if (Loc) *Loc = Diags[0].first;
  8270. } else if (!IsConstExpr) {
  8271. // FIXME: This shouldn't happen.
  8272. if (Loc) *Loc = getExprLoc();
  8273. }
  8274. return IsConstExpr;
  8275. }
  8276. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  8277. const FunctionDecl *Callee,
  8278. ArrayRef<const Expr*> Args) const {
  8279. Expr::EvalStatus Status;
  8280. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  8281. ArgVector ArgValues(Args.size());
  8282. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  8283. I != E; ++I) {
  8284. if ((*I)->isValueDependent() ||
  8285. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  8286. // If evaluation fails, throw away the argument entirely.
  8287. ArgValues[I - Args.begin()] = APValue();
  8288. if (Info.EvalStatus.HasSideEffects)
  8289. return false;
  8290. }
  8291. // Build fake call to Callee.
  8292. CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
  8293. ArgValues.data());
  8294. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  8295. }
  8296. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  8297. SmallVectorImpl<
  8298. PartialDiagnosticAt> &Diags) {
  8299. // FIXME: It would be useful to check constexpr function templates, but at the
  8300. // moment the constant expression evaluator cannot cope with the non-rigorous
  8301. // ASTs which we build for dependent expressions.
  8302. if (FD->isDependentContext())
  8303. return true;
  8304. Expr::EvalStatus Status;
  8305. Status.Diag = &Diags;
  8306. EvalInfo Info(FD->getASTContext(), Status,
  8307. EvalInfo::EM_PotentialConstantExpression);
  8308. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  8309. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  8310. // Fabricate an arbitrary expression on the stack and pretend that it
  8311. // is a temporary being used as the 'this' pointer.
  8312. LValue This;
  8313. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  8314. This.set(&VIE, Info.CurrentCall->Index);
  8315. ArrayRef<const Expr*> Args;
  8316. SourceLocation Loc = FD->getLocation();
  8317. APValue Scratch;
  8318. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  8319. // Evaluate the call as a constant initializer, to allow the construction
  8320. // of objects of non-literal types.
  8321. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  8322. HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
  8323. } else
  8324. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  8325. Args, FD->getBody(), Info, Scratch);
  8326. return Diags.empty();
  8327. }
  8328. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  8329. const FunctionDecl *FD,
  8330. SmallVectorImpl<
  8331. PartialDiagnosticAt> &Diags) {
  8332. Expr::EvalStatus Status;
  8333. Status.Diag = &Diags;
  8334. EvalInfo Info(FD->getASTContext(), Status,
  8335. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  8336. // Fabricate a call stack frame to give the arguments a plausible cover story.
  8337. ArrayRef<const Expr*> Args;
  8338. ArgVector ArgValues(0);
  8339. bool Success = EvaluateArgs(Args, ArgValues, Info);
  8340. (void)Success;
  8341. assert(Success &&
  8342. "Failed to set up arguments for potential constant evaluation");
  8343. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  8344. APValue ResultScratch;
  8345. Evaluate(ResultScratch, Info, E);
  8346. return Diags.empty();
  8347. }