ExprConstant.cpp 503 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include <cstring>
  35. #include <functional>
  36. #include "Interp/Context.h"
  37. #include "Interp/Frame.h"
  38. #include "Interp/State.h"
  39. #include "clang/AST/APValue.h"
  40. #include "clang/AST/ASTContext.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/ASTLambda.h"
  43. #include "clang/AST/CXXInheritance.h"
  44. #include "clang/AST/CharUnits.h"
  45. #include "clang/AST/CurrentSourceLocExprScope.h"
  46. #include "clang/AST/Expr.h"
  47. #include "clang/AST/OSLog.h"
  48. #include "clang/AST/OptionalDiagnostic.h"
  49. #include "clang/AST/RecordLayout.h"
  50. #include "clang/AST/StmtVisitor.h"
  51. #include "clang/AST/TypeLoc.h"
  52. #include "clang/Basic/Builtins.h"
  53. #include "clang/Basic/FixedPoint.h"
  54. #include "clang/Basic/TargetInfo.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/SmallBitVector.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #define DEBUG_TYPE "exprconstant"
  60. using namespace clang;
  61. using llvm::APInt;
  62. using llvm::APSInt;
  63. using llvm::APFloat;
  64. using llvm::Optional;
  65. namespace {
  66. struct LValue;
  67. class CallStackFrame;
  68. class EvalInfo;
  69. using SourceLocExprScopeGuard =
  70. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  71. static QualType getType(APValue::LValueBase B) {
  72. if (!B) return QualType();
  73. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  74. // FIXME: It's unclear where we're supposed to take the type from, and
  75. // this actually matters for arrays of unknown bound. Eg:
  76. //
  77. // extern int arr[]; void f() { extern int arr[3]; };
  78. // constexpr int *p = &arr[1]; // valid?
  79. //
  80. // For now, we take the array bound from the most recent declaration.
  81. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  82. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  83. QualType T = Redecl->getType();
  84. if (!T->isIncompleteArrayType())
  85. return T;
  86. }
  87. return D->getType();
  88. }
  89. if (B.is<TypeInfoLValue>())
  90. return B.getTypeInfoType();
  91. if (B.is<DynamicAllocLValue>())
  92. return B.getDynamicAllocType();
  93. const Expr *Base = B.get<const Expr*>();
  94. // For a materialized temporary, the type of the temporary we materialized
  95. // may not be the type of the expression.
  96. if (const MaterializeTemporaryExpr *MTE =
  97. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  98. SmallVector<const Expr *, 2> CommaLHSs;
  99. SmallVector<SubobjectAdjustment, 2> Adjustments;
  100. const Expr *Temp = MTE->GetTemporaryExpr();
  101. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  102. Adjustments);
  103. // Keep any cv-qualifiers from the reference if we generated a temporary
  104. // for it directly. Otherwise use the type after adjustment.
  105. if (!Adjustments.empty())
  106. return Inner->getType();
  107. }
  108. return Base->getType();
  109. }
  110. /// Get an LValue path entry, which is known to not be an array index, as a
  111. /// field declaration.
  112. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  113. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// base class declaration.
  117. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  118. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  119. }
  120. /// Determine whether this LValue path entry for a base class names a virtual
  121. /// base class.
  122. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  123. return E.getAsBaseOrMember().getInt();
  124. }
  125. /// Given an expression, determine the type used to store the result of
  126. /// evaluating that expression.
  127. static QualType getStorageType(ASTContext &Ctx, Expr *E) {
  128. if (E->isRValue())
  129. return E->getType();
  130. return Ctx.getLValueReferenceType(E->getType());
  131. }
  132. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  133. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  134. const FunctionDecl *Callee = CE->getDirectCallee();
  135. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  136. }
  137. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  138. /// This will look through a single cast.
  139. ///
  140. /// Returns null if we couldn't unwrap a function with alloc_size.
  141. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  142. if (!E->getType()->isPointerType())
  143. return nullptr;
  144. E = E->IgnoreParens();
  145. // If we're doing a variable assignment from e.g. malloc(N), there will
  146. // probably be a cast of some kind. In exotic cases, we might also see a
  147. // top-level ExprWithCleanups. Ignore them either way.
  148. if (const auto *FE = dyn_cast<FullExpr>(E))
  149. E = FE->getSubExpr()->IgnoreParens();
  150. if (const auto *Cast = dyn_cast<CastExpr>(E))
  151. E = Cast->getSubExpr()->IgnoreParens();
  152. if (const auto *CE = dyn_cast<CallExpr>(E))
  153. return getAllocSizeAttr(CE) ? CE : nullptr;
  154. return nullptr;
  155. }
  156. /// Determines whether or not the given Base contains a call to a function
  157. /// with the alloc_size attribute.
  158. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  159. const auto *E = Base.dyn_cast<const Expr *>();
  160. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  161. }
  162. /// The bound to claim that an array of unknown bound has.
  163. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  164. /// to an arbitrary value that's likely to loudly break things if it's used.
  165. static const uint64_t AssumedSizeForUnsizedArray =
  166. std::numeric_limits<uint64_t>::max() / 2;
  167. /// Determines if an LValue with the given LValueBase will have an unsized
  168. /// array in its designator.
  169. /// Find the path length and type of the most-derived subobject in the given
  170. /// path, and find the size of the containing array, if any.
  171. static unsigned
  172. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  173. ArrayRef<APValue::LValuePathEntry> Path,
  174. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  175. bool &FirstEntryIsUnsizedArray) {
  176. // This only accepts LValueBases from APValues, and APValues don't support
  177. // arrays that lack size info.
  178. assert(!isBaseAnAllocSizeCall(Base) &&
  179. "Unsized arrays shouldn't appear here");
  180. unsigned MostDerivedLength = 0;
  181. Type = getType(Base);
  182. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  183. if (Type->isArrayType()) {
  184. const ArrayType *AT = Ctx.getAsArrayType(Type);
  185. Type = AT->getElementType();
  186. MostDerivedLength = I + 1;
  187. IsArray = true;
  188. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  189. ArraySize = CAT->getSize().getZExtValue();
  190. } else {
  191. assert(I == 0 && "unexpected unsized array designator");
  192. FirstEntryIsUnsizedArray = true;
  193. ArraySize = AssumedSizeForUnsizedArray;
  194. }
  195. } else if (Type->isAnyComplexType()) {
  196. const ComplexType *CT = Type->castAs<ComplexType>();
  197. Type = CT->getElementType();
  198. ArraySize = 2;
  199. MostDerivedLength = I + 1;
  200. IsArray = true;
  201. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  202. Type = FD->getType();
  203. ArraySize = 0;
  204. MostDerivedLength = I + 1;
  205. IsArray = false;
  206. } else {
  207. // Path[I] describes a base class.
  208. ArraySize = 0;
  209. IsArray = false;
  210. }
  211. }
  212. return MostDerivedLength;
  213. }
  214. /// A path from a glvalue to a subobject of that glvalue.
  215. struct SubobjectDesignator {
  216. /// True if the subobject was named in a manner not supported by C++11. Such
  217. /// lvalues can still be folded, but they are not core constant expressions
  218. /// and we cannot perform lvalue-to-rvalue conversions on them.
  219. unsigned Invalid : 1;
  220. /// Is this a pointer one past the end of an object?
  221. unsigned IsOnePastTheEnd : 1;
  222. /// Indicator of whether the first entry is an unsized array.
  223. unsigned FirstEntryIsAnUnsizedArray : 1;
  224. /// Indicator of whether the most-derived object is an array element.
  225. unsigned MostDerivedIsArrayElement : 1;
  226. /// The length of the path to the most-derived object of which this is a
  227. /// subobject.
  228. unsigned MostDerivedPathLength : 28;
  229. /// The size of the array of which the most-derived object is an element.
  230. /// This will always be 0 if the most-derived object is not an array
  231. /// element. 0 is not an indicator of whether or not the most-derived object
  232. /// is an array, however, because 0-length arrays are allowed.
  233. ///
  234. /// If the current array is an unsized array, the value of this is
  235. /// undefined.
  236. uint64_t MostDerivedArraySize;
  237. /// The type of the most derived object referred to by this address.
  238. QualType MostDerivedType;
  239. typedef APValue::LValuePathEntry PathEntry;
  240. /// The entries on the path from the glvalue to the designated subobject.
  241. SmallVector<PathEntry, 8> Entries;
  242. SubobjectDesignator() : Invalid(true) {}
  243. explicit SubobjectDesignator(QualType T)
  244. : Invalid(false), IsOnePastTheEnd(false),
  245. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  246. MostDerivedPathLength(0), MostDerivedArraySize(0),
  247. MostDerivedType(T) {}
  248. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  249. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  250. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  251. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  252. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  253. if (!Invalid) {
  254. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  255. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  256. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  257. if (V.getLValueBase()) {
  258. bool IsArray = false;
  259. bool FirstIsUnsizedArray = false;
  260. MostDerivedPathLength = findMostDerivedSubobject(
  261. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  262. MostDerivedType, IsArray, FirstIsUnsizedArray);
  263. MostDerivedIsArrayElement = IsArray;
  264. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  265. }
  266. }
  267. }
  268. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  269. unsigned NewLength) {
  270. if (Invalid)
  271. return;
  272. assert(Base && "cannot truncate path for null pointer");
  273. assert(NewLength <= Entries.size() && "not a truncation");
  274. if (NewLength == Entries.size())
  275. return;
  276. Entries.resize(NewLength);
  277. bool IsArray = false;
  278. bool FirstIsUnsizedArray = false;
  279. MostDerivedPathLength = findMostDerivedSubobject(
  280. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  281. FirstIsUnsizedArray);
  282. MostDerivedIsArrayElement = IsArray;
  283. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  284. }
  285. void setInvalid() {
  286. Invalid = true;
  287. Entries.clear();
  288. }
  289. /// Determine whether the most derived subobject is an array without a
  290. /// known bound.
  291. bool isMostDerivedAnUnsizedArray() const {
  292. assert(!Invalid && "Calling this makes no sense on invalid designators");
  293. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  294. }
  295. /// Determine what the most derived array's size is. Results in an assertion
  296. /// failure if the most derived array lacks a size.
  297. uint64_t getMostDerivedArraySize() const {
  298. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  299. return MostDerivedArraySize;
  300. }
  301. /// Determine whether this is a one-past-the-end pointer.
  302. bool isOnePastTheEnd() const {
  303. assert(!Invalid);
  304. if (IsOnePastTheEnd)
  305. return true;
  306. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  307. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  308. MostDerivedArraySize)
  309. return true;
  310. return false;
  311. }
  312. /// Get the range of valid index adjustments in the form
  313. /// {maximum value that can be subtracted from this pointer,
  314. /// maximum value that can be added to this pointer}
  315. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  316. if (Invalid || isMostDerivedAnUnsizedArray())
  317. return {0, 0};
  318. // [expr.add]p4: For the purposes of these operators, a pointer to a
  319. // nonarray object behaves the same as a pointer to the first element of
  320. // an array of length one with the type of the object as its element type.
  321. bool IsArray = MostDerivedPathLength == Entries.size() &&
  322. MostDerivedIsArrayElement;
  323. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  324. : (uint64_t)IsOnePastTheEnd;
  325. uint64_t ArraySize =
  326. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  327. return {ArrayIndex, ArraySize - ArrayIndex};
  328. }
  329. /// Check that this refers to a valid subobject.
  330. bool isValidSubobject() const {
  331. if (Invalid)
  332. return false;
  333. return !isOnePastTheEnd();
  334. }
  335. /// Check that this refers to a valid subobject, and if not, produce a
  336. /// relevant diagnostic and set the designator as invalid.
  337. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  338. /// Get the type of the designated object.
  339. QualType getType(ASTContext &Ctx) const {
  340. assert(!Invalid && "invalid designator has no subobject type");
  341. return MostDerivedPathLength == Entries.size()
  342. ? MostDerivedType
  343. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  344. }
  345. /// Update this designator to refer to the first element within this array.
  346. void addArrayUnchecked(const ConstantArrayType *CAT) {
  347. Entries.push_back(PathEntry::ArrayIndex(0));
  348. // This is a most-derived object.
  349. MostDerivedType = CAT->getElementType();
  350. MostDerivedIsArrayElement = true;
  351. MostDerivedArraySize = CAT->getSize().getZExtValue();
  352. MostDerivedPathLength = Entries.size();
  353. }
  354. /// Update this designator to refer to the first element within the array of
  355. /// elements of type T. This is an array of unknown size.
  356. void addUnsizedArrayUnchecked(QualType ElemTy) {
  357. Entries.push_back(PathEntry::ArrayIndex(0));
  358. MostDerivedType = ElemTy;
  359. MostDerivedIsArrayElement = true;
  360. // The value in MostDerivedArraySize is undefined in this case. So, set it
  361. // to an arbitrary value that's likely to loudly break things if it's
  362. // used.
  363. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  364. MostDerivedPathLength = Entries.size();
  365. }
  366. /// Update this designator to refer to the given base or member of this
  367. /// object.
  368. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  369. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  370. // If this isn't a base class, it's a new most-derived object.
  371. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  372. MostDerivedType = FD->getType();
  373. MostDerivedIsArrayElement = false;
  374. MostDerivedArraySize = 0;
  375. MostDerivedPathLength = Entries.size();
  376. }
  377. }
  378. /// Update this designator to refer to the given complex component.
  379. void addComplexUnchecked(QualType EltTy, bool Imag) {
  380. Entries.push_back(PathEntry::ArrayIndex(Imag));
  381. // This is technically a most-derived object, though in practice this
  382. // is unlikely to matter.
  383. MostDerivedType = EltTy;
  384. MostDerivedIsArrayElement = true;
  385. MostDerivedArraySize = 2;
  386. MostDerivedPathLength = Entries.size();
  387. }
  388. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  389. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  390. const APSInt &N);
  391. /// Add N to the address of this subobject.
  392. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  393. if (Invalid || !N) return;
  394. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  395. if (isMostDerivedAnUnsizedArray()) {
  396. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  397. // Can't verify -- trust that the user is doing the right thing (or if
  398. // not, trust that the caller will catch the bad behavior).
  399. // FIXME: Should we reject if this overflows, at least?
  400. Entries.back() = PathEntry::ArrayIndex(
  401. Entries.back().getAsArrayIndex() + TruncatedN);
  402. return;
  403. }
  404. // [expr.add]p4: For the purposes of these operators, a pointer to a
  405. // nonarray object behaves the same as a pointer to the first element of
  406. // an array of length one with the type of the object as its element type.
  407. bool IsArray = MostDerivedPathLength == Entries.size() &&
  408. MostDerivedIsArrayElement;
  409. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  410. : (uint64_t)IsOnePastTheEnd;
  411. uint64_t ArraySize =
  412. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  413. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  414. // Calculate the actual index in a wide enough type, so we can include
  415. // it in the note.
  416. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  417. (llvm::APInt&)N += ArrayIndex;
  418. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  419. diagnosePointerArithmetic(Info, E, N);
  420. setInvalid();
  421. return;
  422. }
  423. ArrayIndex += TruncatedN;
  424. assert(ArrayIndex <= ArraySize &&
  425. "bounds check succeeded for out-of-bounds index");
  426. if (IsArray)
  427. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  428. else
  429. IsOnePastTheEnd = (ArrayIndex != 0);
  430. }
  431. };
  432. /// A stack frame in the constexpr call stack.
  433. class CallStackFrame : public interp::Frame {
  434. public:
  435. EvalInfo &Info;
  436. /// Parent - The caller of this stack frame.
  437. CallStackFrame *Caller;
  438. /// Callee - The function which was called.
  439. const FunctionDecl *Callee;
  440. /// This - The binding for the this pointer in this call, if any.
  441. const LValue *This;
  442. /// Arguments - Parameter bindings for this function call, indexed by
  443. /// parameters' function scope indices.
  444. APValue *Arguments;
  445. /// Source location information about the default argument or default
  446. /// initializer expression we're evaluating, if any.
  447. CurrentSourceLocExprScope CurSourceLocExprScope;
  448. // Note that we intentionally use std::map here so that references to
  449. // values are stable.
  450. typedef std::pair<const void *, unsigned> MapKeyTy;
  451. typedef std::map<MapKeyTy, APValue> MapTy;
  452. /// Temporaries - Temporary lvalues materialized within this stack frame.
  453. MapTy Temporaries;
  454. /// CallLoc - The location of the call expression for this call.
  455. SourceLocation CallLoc;
  456. /// Index - The call index of this call.
  457. unsigned Index;
  458. /// The stack of integers for tracking version numbers for temporaries.
  459. SmallVector<unsigned, 2> TempVersionStack = {1};
  460. unsigned CurTempVersion = TempVersionStack.back();
  461. unsigned getTempVersion() const { return TempVersionStack.back(); }
  462. void pushTempVersion() {
  463. TempVersionStack.push_back(++CurTempVersion);
  464. }
  465. void popTempVersion() {
  466. TempVersionStack.pop_back();
  467. }
  468. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  469. // on the overall stack usage of deeply-recursing constexpr evaluations.
  470. // (We should cache this map rather than recomputing it repeatedly.)
  471. // But let's try this and see how it goes; we can look into caching the map
  472. // as a later change.
  473. /// LambdaCaptureFields - Mapping from captured variables/this to
  474. /// corresponding data members in the closure class.
  475. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  476. FieldDecl *LambdaThisCaptureField;
  477. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  478. const FunctionDecl *Callee, const LValue *This,
  479. APValue *Arguments);
  480. ~CallStackFrame();
  481. // Return the temporary for Key whose version number is Version.
  482. APValue *getTemporary(const void *Key, unsigned Version) {
  483. MapKeyTy KV(Key, Version);
  484. auto LB = Temporaries.lower_bound(KV);
  485. if (LB != Temporaries.end() && LB->first == KV)
  486. return &LB->second;
  487. // Pair (Key,Version) wasn't found in the map. Check that no elements
  488. // in the map have 'Key' as their key.
  489. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  490. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  491. "Element with key 'Key' found in map");
  492. return nullptr;
  493. }
  494. // Return the current temporary for Key in the map.
  495. APValue *getCurrentTemporary(const void *Key) {
  496. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  497. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  498. return &std::prev(UB)->second;
  499. return nullptr;
  500. }
  501. // Return the version number of the current temporary for Key.
  502. unsigned getCurrentTemporaryVersion(const void *Key) const {
  503. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  504. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  505. return std::prev(UB)->first.second;
  506. return 0;
  507. }
  508. /// Allocate storage for an object of type T in this stack frame.
  509. /// Populates LV with a handle to the created object. Key identifies
  510. /// the temporary within the stack frame, and must not be reused without
  511. /// bumping the temporary version number.
  512. template<typename KeyT>
  513. APValue &createTemporary(const KeyT *Key, QualType T,
  514. bool IsLifetimeExtended, LValue &LV);
  515. void describe(llvm::raw_ostream &OS) override;
  516. Frame *getCaller() const override { return Caller; }
  517. SourceLocation getCallLocation() const override { return CallLoc; }
  518. const FunctionDecl *getCallee() const override { return Callee; }
  519. };
  520. /// Temporarily override 'this'.
  521. class ThisOverrideRAII {
  522. public:
  523. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  524. : Frame(Frame), OldThis(Frame.This) {
  525. if (Enable)
  526. Frame.This = NewThis;
  527. }
  528. ~ThisOverrideRAII() {
  529. Frame.This = OldThis;
  530. }
  531. private:
  532. CallStackFrame &Frame;
  533. const LValue *OldThis;
  534. };
  535. }
  536. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  537. const LValue &This, QualType ThisType);
  538. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  539. APValue::LValueBase LVBase, APValue &Value,
  540. QualType T);
  541. namespace {
  542. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  543. class Cleanup {
  544. llvm::PointerIntPair<APValue*, 1, bool> Value;
  545. APValue::LValueBase Base;
  546. QualType T;
  547. public:
  548. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  549. bool IsLifetimeExtended)
  550. : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
  551. bool isLifetimeExtended() const { return Value.getInt(); }
  552. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  553. if (RunDestructors) {
  554. SourceLocation Loc;
  555. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  556. Loc = VD->getLocation();
  557. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  558. Loc = E->getExprLoc();
  559. return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
  560. }
  561. *Value.getPointer() = APValue();
  562. return true;
  563. }
  564. bool hasSideEffect() {
  565. return T.isDestructedType();
  566. }
  567. };
  568. /// A reference to an object whose construction we are currently evaluating.
  569. struct ObjectUnderConstruction {
  570. APValue::LValueBase Base;
  571. ArrayRef<APValue::LValuePathEntry> Path;
  572. friend bool operator==(const ObjectUnderConstruction &LHS,
  573. const ObjectUnderConstruction &RHS) {
  574. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  575. }
  576. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  577. return llvm::hash_combine(Obj.Base, Obj.Path);
  578. }
  579. };
  580. enum class ConstructionPhase {
  581. None,
  582. Bases,
  583. AfterBases,
  584. Destroying,
  585. DestroyingBases
  586. };
  587. }
  588. namespace llvm {
  589. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  590. using Base = DenseMapInfo<APValue::LValueBase>;
  591. static ObjectUnderConstruction getEmptyKey() {
  592. return {Base::getEmptyKey(), {}}; }
  593. static ObjectUnderConstruction getTombstoneKey() {
  594. return {Base::getTombstoneKey(), {}};
  595. }
  596. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  597. return hash_value(Object);
  598. }
  599. static bool isEqual(const ObjectUnderConstruction &LHS,
  600. const ObjectUnderConstruction &RHS) {
  601. return LHS == RHS;
  602. }
  603. };
  604. }
  605. namespace {
  606. /// EvalInfo - This is a private struct used by the evaluator to capture
  607. /// information about a subexpression as it is folded. It retains information
  608. /// about the AST context, but also maintains information about the folded
  609. /// expression.
  610. ///
  611. /// If an expression could be evaluated, it is still possible it is not a C
  612. /// "integer constant expression" or constant expression. If not, this struct
  613. /// captures information about how and why not.
  614. ///
  615. /// One bit of information passed *into* the request for constant folding
  616. /// indicates whether the subexpression is "evaluated" or not according to C
  617. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  618. /// evaluate the expression regardless of what the RHS is, but C only allows
  619. /// certain things in certain situations.
  620. class EvalInfo : public interp::State {
  621. public:
  622. ASTContext &Ctx;
  623. /// EvalStatus - Contains information about the evaluation.
  624. Expr::EvalStatus &EvalStatus;
  625. /// CurrentCall - The top of the constexpr call stack.
  626. CallStackFrame *CurrentCall;
  627. /// CallStackDepth - The number of calls in the call stack right now.
  628. unsigned CallStackDepth;
  629. /// NextCallIndex - The next call index to assign.
  630. unsigned NextCallIndex;
  631. /// StepsLeft - The remaining number of evaluation steps we're permitted
  632. /// to perform. This is essentially a limit for the number of statements
  633. /// we will evaluate.
  634. unsigned StepsLeft;
  635. /// Force the use of the experimental new constant interpreter, bailing out
  636. /// with an error if a feature is not supported.
  637. bool ForceNewConstInterp;
  638. /// Enable the experimental new constant interpreter.
  639. bool EnableNewConstInterp;
  640. /// BottomFrame - The frame in which evaluation started. This must be
  641. /// initialized after CurrentCall and CallStackDepth.
  642. CallStackFrame BottomFrame;
  643. /// A stack of values whose lifetimes end at the end of some surrounding
  644. /// evaluation frame.
  645. llvm::SmallVector<Cleanup, 16> CleanupStack;
  646. /// EvaluatingDecl - This is the declaration whose initializer is being
  647. /// evaluated, if any.
  648. APValue::LValueBase EvaluatingDecl;
  649. enum class EvaluatingDeclKind {
  650. None,
  651. /// We're evaluating the construction of EvaluatingDecl.
  652. Ctor,
  653. /// We're evaluating the destruction of EvaluatingDecl.
  654. Dtor,
  655. };
  656. EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
  657. /// EvaluatingDeclValue - This is the value being constructed for the
  658. /// declaration whose initializer is being evaluated, if any.
  659. APValue *EvaluatingDeclValue;
  660. /// Set of objects that are currently being constructed.
  661. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  662. ObjectsUnderConstruction;
  663. /// A dynamically-allocated heap object.
  664. struct DynAlloc {
  665. /// The value of this heap-allocated object.
  666. APValue Value;
  667. /// The allocating expression; used for diagnostics.
  668. const Expr *AllocExpr = nullptr;
  669. };
  670. struct DynAllocOrder {
  671. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  672. return L.getIndex() < R.getIndex();
  673. }
  674. };
  675. /// Current heap allocations, along with the location where each was
  676. /// allocated. We use std::map here because we need stable addresses
  677. /// for the stored APValues.
  678. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  679. /// The number of heap allocations performed so far in this evaluation.
  680. unsigned NumHeapAllocs = 0;
  681. struct EvaluatingConstructorRAII {
  682. EvalInfo &EI;
  683. ObjectUnderConstruction Object;
  684. bool DidInsert;
  685. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  686. bool HasBases)
  687. : EI(EI), Object(Object) {
  688. DidInsert =
  689. EI.ObjectsUnderConstruction
  690. .insert({Object, HasBases ? ConstructionPhase::Bases
  691. : ConstructionPhase::AfterBases})
  692. .second;
  693. }
  694. void finishedConstructingBases() {
  695. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  696. }
  697. ~EvaluatingConstructorRAII() {
  698. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  699. }
  700. };
  701. struct EvaluatingDestructorRAII {
  702. EvalInfo &EI;
  703. ObjectUnderConstruction Object;
  704. bool DidInsert;
  705. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  706. : EI(EI), Object(Object) {
  707. DidInsert = EI.ObjectsUnderConstruction
  708. .insert({Object, ConstructionPhase::Destroying})
  709. .second;
  710. }
  711. void startedDestroyingBases() {
  712. EI.ObjectsUnderConstruction[Object] =
  713. ConstructionPhase::DestroyingBases;
  714. }
  715. ~EvaluatingDestructorRAII() {
  716. if (DidInsert)
  717. EI.ObjectsUnderConstruction.erase(Object);
  718. }
  719. };
  720. ConstructionPhase
  721. isEvaluatingCtorDtor(APValue::LValueBase Base,
  722. ArrayRef<APValue::LValuePathEntry> Path) {
  723. return ObjectsUnderConstruction.lookup({Base, Path});
  724. }
  725. /// If we're currently speculatively evaluating, the outermost call stack
  726. /// depth at which we can mutate state, otherwise 0.
  727. unsigned SpeculativeEvaluationDepth = 0;
  728. /// The current array initialization index, if we're performing array
  729. /// initialization.
  730. uint64_t ArrayInitIndex = -1;
  731. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  732. /// notes attached to it will also be stored, otherwise they will not be.
  733. bool HasActiveDiagnostic;
  734. /// Have we emitted a diagnostic explaining why we couldn't constant
  735. /// fold (not just why it's not strictly a constant expression)?
  736. bool HasFoldFailureDiagnostic;
  737. /// Whether or not we're in a context where the front end requires a
  738. /// constant value.
  739. bool InConstantContext;
  740. /// Whether we're checking that an expression is a potential constant
  741. /// expression. If so, do not fail on constructs that could become constant
  742. /// later on (such as a use of an undefined global).
  743. bool CheckingPotentialConstantExpression = false;
  744. /// Whether we're checking for an expression that has undefined behavior.
  745. /// If so, we will produce warnings if we encounter an operation that is
  746. /// always undefined.
  747. bool CheckingForUndefinedBehavior = false;
  748. enum EvaluationMode {
  749. /// Evaluate as a constant expression. Stop if we find that the expression
  750. /// is not a constant expression.
  751. EM_ConstantExpression,
  752. /// Evaluate as a constant expression. Stop if we find that the expression
  753. /// is not a constant expression. Some expressions can be retried in the
  754. /// optimizer if we don't constant fold them here, but in an unevaluated
  755. /// context we try to fold them immediately since the optimizer never
  756. /// gets a chance to look at it.
  757. EM_ConstantExpressionUnevaluated,
  758. /// Fold the expression to a constant. Stop if we hit a side-effect that
  759. /// we can't model.
  760. EM_ConstantFold,
  761. /// Evaluate in any way we know how. Don't worry about side-effects that
  762. /// can't be modeled.
  763. EM_IgnoreSideEffects,
  764. } EvalMode;
  765. /// Are we checking whether the expression is a potential constant
  766. /// expression?
  767. bool checkingPotentialConstantExpression() const override {
  768. return CheckingPotentialConstantExpression;
  769. }
  770. /// Are we checking an expression for overflow?
  771. // FIXME: We should check for any kind of undefined or suspicious behavior
  772. // in such constructs, not just overflow.
  773. bool checkingForUndefinedBehavior() const override {
  774. return CheckingForUndefinedBehavior;
  775. }
  776. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  777. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  778. CallStackDepth(0), NextCallIndex(1),
  779. StepsLeft(getLangOpts().ConstexprStepLimit),
  780. ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
  781. EnableNewConstInterp(ForceNewConstInterp ||
  782. getLangOpts().EnableNewConstInterp),
  783. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  784. EvaluatingDecl((const ValueDecl *)nullptr),
  785. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  786. HasFoldFailureDiagnostic(false), InConstantContext(false),
  787. EvalMode(Mode) {}
  788. ~EvalInfo() {
  789. discardCleanups();
  790. }
  791. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
  792. EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
  793. EvaluatingDecl = Base;
  794. IsEvaluatingDecl = EDK;
  795. EvaluatingDeclValue = &Value;
  796. }
  797. bool CheckCallLimit(SourceLocation Loc) {
  798. // Don't perform any constexpr calls (other than the call we're checking)
  799. // when checking a potential constant expression.
  800. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  801. return false;
  802. if (NextCallIndex == 0) {
  803. // NextCallIndex has wrapped around.
  804. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  805. return false;
  806. }
  807. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  808. return true;
  809. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  810. << getLangOpts().ConstexprCallDepth;
  811. return false;
  812. }
  813. std::pair<CallStackFrame *, unsigned>
  814. getCallFrameAndDepth(unsigned CallIndex) {
  815. assert(CallIndex && "no call index in getCallFrameAndDepth");
  816. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  817. // be null in this loop.
  818. unsigned Depth = CallStackDepth;
  819. CallStackFrame *Frame = CurrentCall;
  820. while (Frame->Index > CallIndex) {
  821. Frame = Frame->Caller;
  822. --Depth;
  823. }
  824. if (Frame->Index == CallIndex)
  825. return {Frame, Depth};
  826. return {nullptr, 0};
  827. }
  828. bool nextStep(const Stmt *S) {
  829. if (!StepsLeft) {
  830. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  831. return false;
  832. }
  833. --StepsLeft;
  834. return true;
  835. }
  836. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  837. Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
  838. Optional<DynAlloc*> Result;
  839. auto It = HeapAllocs.find(DA);
  840. if (It != HeapAllocs.end())
  841. Result = &It->second;
  842. return Result;
  843. }
  844. void performLifetimeExtension() {
  845. // Disable the cleanups for lifetime-extended temporaries.
  846. CleanupStack.erase(
  847. std::remove_if(CleanupStack.begin(), CleanupStack.end(),
  848. [](Cleanup &C) { return C.isLifetimeExtended(); }),
  849. CleanupStack.end());
  850. }
  851. /// Throw away any remaining cleanups at the end of evaluation. If any
  852. /// cleanups would have had a side-effect, note that as an unmodeled
  853. /// side-effect and return false. Otherwise, return true.
  854. bool discardCleanups() {
  855. for (Cleanup &C : CleanupStack)
  856. if (C.hasSideEffect())
  857. if (!noteSideEffect())
  858. return false;
  859. return true;
  860. }
  861. private:
  862. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  863. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  864. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  865. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  866. void setFoldFailureDiagnostic(bool Flag) override {
  867. HasFoldFailureDiagnostic = Flag;
  868. }
  869. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  870. ASTContext &getCtx() const override { return Ctx; }
  871. // If we have a prior diagnostic, it will be noting that the expression
  872. // isn't a constant expression. This diagnostic is more important,
  873. // unless we require this evaluation to produce a constant expression.
  874. //
  875. // FIXME: We might want to show both diagnostics to the user in
  876. // EM_ConstantFold mode.
  877. bool hasPriorDiagnostic() override {
  878. if (!EvalStatus.Diag->empty()) {
  879. switch (EvalMode) {
  880. case EM_ConstantFold:
  881. case EM_IgnoreSideEffects:
  882. if (!HasFoldFailureDiagnostic)
  883. break;
  884. // We've already failed to fold something. Keep that diagnostic.
  885. LLVM_FALLTHROUGH;
  886. case EM_ConstantExpression:
  887. case EM_ConstantExpressionUnevaluated:
  888. setActiveDiagnostic(false);
  889. return true;
  890. }
  891. }
  892. return false;
  893. }
  894. unsigned getCallStackDepth() override { return CallStackDepth; }
  895. public:
  896. /// Should we continue evaluation after encountering a side-effect that we
  897. /// couldn't model?
  898. bool keepEvaluatingAfterSideEffect() {
  899. switch (EvalMode) {
  900. case EM_IgnoreSideEffects:
  901. return true;
  902. case EM_ConstantExpression:
  903. case EM_ConstantExpressionUnevaluated:
  904. case EM_ConstantFold:
  905. // By default, assume any side effect might be valid in some other
  906. // evaluation of this expression from a different context.
  907. return checkingPotentialConstantExpression() ||
  908. checkingForUndefinedBehavior();
  909. }
  910. llvm_unreachable("Missed EvalMode case");
  911. }
  912. /// Note that we have had a side-effect, and determine whether we should
  913. /// keep evaluating.
  914. bool noteSideEffect() {
  915. EvalStatus.HasSideEffects = true;
  916. return keepEvaluatingAfterSideEffect();
  917. }
  918. /// Should we continue evaluation after encountering undefined behavior?
  919. bool keepEvaluatingAfterUndefinedBehavior() {
  920. switch (EvalMode) {
  921. case EM_IgnoreSideEffects:
  922. case EM_ConstantFold:
  923. return true;
  924. case EM_ConstantExpression:
  925. case EM_ConstantExpressionUnevaluated:
  926. return checkingForUndefinedBehavior();
  927. }
  928. llvm_unreachable("Missed EvalMode case");
  929. }
  930. /// Note that we hit something that was technically undefined behavior, but
  931. /// that we can evaluate past it (such as signed overflow or floating-point
  932. /// division by zero.)
  933. bool noteUndefinedBehavior() override {
  934. EvalStatus.HasUndefinedBehavior = true;
  935. return keepEvaluatingAfterUndefinedBehavior();
  936. }
  937. /// Should we continue evaluation as much as possible after encountering a
  938. /// construct which can't be reduced to a value?
  939. bool keepEvaluatingAfterFailure() const override {
  940. if (!StepsLeft)
  941. return false;
  942. switch (EvalMode) {
  943. case EM_ConstantExpression:
  944. case EM_ConstantExpressionUnevaluated:
  945. case EM_ConstantFold:
  946. case EM_IgnoreSideEffects:
  947. return checkingPotentialConstantExpression() ||
  948. checkingForUndefinedBehavior();
  949. }
  950. llvm_unreachable("Missed EvalMode case");
  951. }
  952. /// Notes that we failed to evaluate an expression that other expressions
  953. /// directly depend on, and determine if we should keep evaluating. This
  954. /// should only be called if we actually intend to keep evaluating.
  955. ///
  956. /// Call noteSideEffect() instead if we may be able to ignore the value that
  957. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  958. ///
  959. /// (Foo(), 1) // use noteSideEffect
  960. /// (Foo() || true) // use noteSideEffect
  961. /// Foo() + 1 // use noteFailure
  962. LLVM_NODISCARD bool noteFailure() {
  963. // Failure when evaluating some expression often means there is some
  964. // subexpression whose evaluation was skipped. Therefore, (because we
  965. // don't track whether we skipped an expression when unwinding after an
  966. // evaluation failure) every evaluation failure that bubbles up from a
  967. // subexpression implies that a side-effect has potentially happened. We
  968. // skip setting the HasSideEffects flag to true until we decide to
  969. // continue evaluating after that point, which happens here.
  970. bool KeepGoing = keepEvaluatingAfterFailure();
  971. EvalStatus.HasSideEffects |= KeepGoing;
  972. return KeepGoing;
  973. }
  974. class ArrayInitLoopIndex {
  975. EvalInfo &Info;
  976. uint64_t OuterIndex;
  977. public:
  978. ArrayInitLoopIndex(EvalInfo &Info)
  979. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  980. Info.ArrayInitIndex = 0;
  981. }
  982. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  983. operator uint64_t&() { return Info.ArrayInitIndex; }
  984. };
  985. };
  986. /// Object used to treat all foldable expressions as constant expressions.
  987. struct FoldConstant {
  988. EvalInfo &Info;
  989. bool Enabled;
  990. bool HadNoPriorDiags;
  991. EvalInfo::EvaluationMode OldMode;
  992. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  993. : Info(Info),
  994. Enabled(Enabled),
  995. HadNoPriorDiags(Info.EvalStatus.Diag &&
  996. Info.EvalStatus.Diag->empty() &&
  997. !Info.EvalStatus.HasSideEffects),
  998. OldMode(Info.EvalMode) {
  999. if (Enabled)
  1000. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1001. }
  1002. void keepDiagnostics() { Enabled = false; }
  1003. ~FoldConstant() {
  1004. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1005. !Info.EvalStatus.HasSideEffects)
  1006. Info.EvalStatus.Diag->clear();
  1007. Info.EvalMode = OldMode;
  1008. }
  1009. };
  1010. /// RAII object used to set the current evaluation mode to ignore
  1011. /// side-effects.
  1012. struct IgnoreSideEffectsRAII {
  1013. EvalInfo &Info;
  1014. EvalInfo::EvaluationMode OldMode;
  1015. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1016. : Info(Info), OldMode(Info.EvalMode) {
  1017. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1018. }
  1019. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1020. };
  1021. /// RAII object used to optionally suppress diagnostics and side-effects from
  1022. /// a speculative evaluation.
  1023. class SpeculativeEvaluationRAII {
  1024. EvalInfo *Info = nullptr;
  1025. Expr::EvalStatus OldStatus;
  1026. unsigned OldSpeculativeEvaluationDepth;
  1027. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1028. Info = Other.Info;
  1029. OldStatus = Other.OldStatus;
  1030. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1031. Other.Info = nullptr;
  1032. }
  1033. void maybeRestoreState() {
  1034. if (!Info)
  1035. return;
  1036. Info->EvalStatus = OldStatus;
  1037. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1038. }
  1039. public:
  1040. SpeculativeEvaluationRAII() = default;
  1041. SpeculativeEvaluationRAII(
  1042. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1043. : Info(&Info), OldStatus(Info.EvalStatus),
  1044. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1045. Info.EvalStatus.Diag = NewDiag;
  1046. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1047. }
  1048. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1049. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1050. moveFromAndCancel(std::move(Other));
  1051. }
  1052. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1053. maybeRestoreState();
  1054. moveFromAndCancel(std::move(Other));
  1055. return *this;
  1056. }
  1057. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1058. };
  1059. /// RAII object wrapping a full-expression or block scope, and handling
  1060. /// the ending of the lifetime of temporaries created within it.
  1061. template<bool IsFullExpression>
  1062. class ScopeRAII {
  1063. EvalInfo &Info;
  1064. unsigned OldStackSize;
  1065. public:
  1066. ScopeRAII(EvalInfo &Info)
  1067. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1068. // Push a new temporary version. This is needed to distinguish between
  1069. // temporaries created in different iterations of a loop.
  1070. Info.CurrentCall->pushTempVersion();
  1071. }
  1072. bool destroy(bool RunDestructors = true) {
  1073. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1074. OldStackSize = -1U;
  1075. return OK;
  1076. }
  1077. ~ScopeRAII() {
  1078. if (OldStackSize != -1U)
  1079. destroy(false);
  1080. // Body moved to a static method to encourage the compiler to inline away
  1081. // instances of this class.
  1082. Info.CurrentCall->popTempVersion();
  1083. }
  1084. private:
  1085. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1086. unsigned OldStackSize) {
  1087. assert(OldStackSize <= Info.CleanupStack.size() &&
  1088. "running cleanups out of order?");
  1089. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1090. // for a full-expression scope.
  1091. bool Success = true;
  1092. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1093. if (!(IsFullExpression &&
  1094. Info.CleanupStack[I - 1].isLifetimeExtended())) {
  1095. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
  1096. Success = false;
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. // Compact lifetime-extended cleanups.
  1102. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1103. if (IsFullExpression)
  1104. NewEnd =
  1105. std::remove_if(NewEnd, Info.CleanupStack.end(),
  1106. [](Cleanup &C) { return !C.isLifetimeExtended(); });
  1107. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1108. return Success;
  1109. }
  1110. };
  1111. typedef ScopeRAII<false> BlockScopeRAII;
  1112. typedef ScopeRAII<true> FullExpressionRAII;
  1113. }
  1114. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1115. CheckSubobjectKind CSK) {
  1116. if (Invalid)
  1117. return false;
  1118. if (isOnePastTheEnd()) {
  1119. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1120. << CSK;
  1121. setInvalid();
  1122. return false;
  1123. }
  1124. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1125. // must actually be at least one array element; even a VLA cannot have a
  1126. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1127. return true;
  1128. }
  1129. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1130. const Expr *E) {
  1131. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1132. // Do not set the designator as invalid: we can represent this situation,
  1133. // and correct handling of __builtin_object_size requires us to do so.
  1134. }
  1135. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1136. const Expr *E,
  1137. const APSInt &N) {
  1138. // If we're complaining, we must be able to statically determine the size of
  1139. // the most derived array.
  1140. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1141. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1142. << N << /*array*/ 0
  1143. << static_cast<unsigned>(getMostDerivedArraySize());
  1144. else
  1145. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1146. << N << /*non-array*/ 1;
  1147. setInvalid();
  1148. }
  1149. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1150. const FunctionDecl *Callee, const LValue *This,
  1151. APValue *Arguments)
  1152. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1153. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1154. Info.CurrentCall = this;
  1155. ++Info.CallStackDepth;
  1156. }
  1157. CallStackFrame::~CallStackFrame() {
  1158. assert(Info.CurrentCall == this && "calls retired out of order");
  1159. --Info.CallStackDepth;
  1160. Info.CurrentCall = Caller;
  1161. }
  1162. static bool isRead(AccessKinds AK) {
  1163. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1164. }
  1165. static bool isModification(AccessKinds AK) {
  1166. switch (AK) {
  1167. case AK_Read:
  1168. case AK_ReadObjectRepresentation:
  1169. case AK_MemberCall:
  1170. case AK_DynamicCast:
  1171. case AK_TypeId:
  1172. return false;
  1173. case AK_Assign:
  1174. case AK_Increment:
  1175. case AK_Decrement:
  1176. case AK_Destroy:
  1177. return true;
  1178. }
  1179. llvm_unreachable("unknown access kind");
  1180. }
  1181. static bool isAnyAccess(AccessKinds AK) {
  1182. return isRead(AK) || isModification(AK);
  1183. }
  1184. /// Is this an access per the C++ definition?
  1185. static bool isFormalAccess(AccessKinds AK) {
  1186. return isAnyAccess(AK) && AK != AK_Destroy;
  1187. }
  1188. namespace {
  1189. struct ComplexValue {
  1190. private:
  1191. bool IsInt;
  1192. public:
  1193. APSInt IntReal, IntImag;
  1194. APFloat FloatReal, FloatImag;
  1195. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1196. void makeComplexFloat() { IsInt = false; }
  1197. bool isComplexFloat() const { return !IsInt; }
  1198. APFloat &getComplexFloatReal() { return FloatReal; }
  1199. APFloat &getComplexFloatImag() { return FloatImag; }
  1200. void makeComplexInt() { IsInt = true; }
  1201. bool isComplexInt() const { return IsInt; }
  1202. APSInt &getComplexIntReal() { return IntReal; }
  1203. APSInt &getComplexIntImag() { return IntImag; }
  1204. void moveInto(APValue &v) const {
  1205. if (isComplexFloat())
  1206. v = APValue(FloatReal, FloatImag);
  1207. else
  1208. v = APValue(IntReal, IntImag);
  1209. }
  1210. void setFrom(const APValue &v) {
  1211. assert(v.isComplexFloat() || v.isComplexInt());
  1212. if (v.isComplexFloat()) {
  1213. makeComplexFloat();
  1214. FloatReal = v.getComplexFloatReal();
  1215. FloatImag = v.getComplexFloatImag();
  1216. } else {
  1217. makeComplexInt();
  1218. IntReal = v.getComplexIntReal();
  1219. IntImag = v.getComplexIntImag();
  1220. }
  1221. }
  1222. };
  1223. struct LValue {
  1224. APValue::LValueBase Base;
  1225. CharUnits Offset;
  1226. SubobjectDesignator Designator;
  1227. bool IsNullPtr : 1;
  1228. bool InvalidBase : 1;
  1229. const APValue::LValueBase getLValueBase() const { return Base; }
  1230. CharUnits &getLValueOffset() { return Offset; }
  1231. const CharUnits &getLValueOffset() const { return Offset; }
  1232. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1233. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1234. bool isNullPointer() const { return IsNullPtr;}
  1235. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1236. unsigned getLValueVersion() const { return Base.getVersion(); }
  1237. void moveInto(APValue &V) const {
  1238. if (Designator.Invalid)
  1239. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1240. else {
  1241. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1242. V = APValue(Base, Offset, Designator.Entries,
  1243. Designator.IsOnePastTheEnd, IsNullPtr);
  1244. }
  1245. }
  1246. void setFrom(ASTContext &Ctx, const APValue &V) {
  1247. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1248. Base = V.getLValueBase();
  1249. Offset = V.getLValueOffset();
  1250. InvalidBase = false;
  1251. Designator = SubobjectDesignator(Ctx, V);
  1252. IsNullPtr = V.isNullPointer();
  1253. }
  1254. void set(APValue::LValueBase B, bool BInvalid = false) {
  1255. #ifndef NDEBUG
  1256. // We only allow a few types of invalid bases. Enforce that here.
  1257. if (BInvalid) {
  1258. const auto *E = B.get<const Expr *>();
  1259. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1260. "Unexpected type of invalid base");
  1261. }
  1262. #endif
  1263. Base = B;
  1264. Offset = CharUnits::fromQuantity(0);
  1265. InvalidBase = BInvalid;
  1266. Designator = SubobjectDesignator(getType(B));
  1267. IsNullPtr = false;
  1268. }
  1269. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1270. Base = (Expr *)nullptr;
  1271. Offset = CharUnits::fromQuantity(TargetVal);
  1272. InvalidBase = false;
  1273. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1274. IsNullPtr = true;
  1275. }
  1276. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1277. set(B, true);
  1278. }
  1279. private:
  1280. // Check that this LValue is not based on a null pointer. If it is, produce
  1281. // a diagnostic and mark the designator as invalid.
  1282. template <typename GenDiagType>
  1283. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1284. if (Designator.Invalid)
  1285. return false;
  1286. if (IsNullPtr) {
  1287. GenDiag();
  1288. Designator.setInvalid();
  1289. return false;
  1290. }
  1291. return true;
  1292. }
  1293. public:
  1294. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1295. CheckSubobjectKind CSK) {
  1296. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1297. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1298. });
  1299. }
  1300. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1301. AccessKinds AK) {
  1302. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1303. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1304. });
  1305. }
  1306. // Check this LValue refers to an object. If not, set the designator to be
  1307. // invalid and emit a diagnostic.
  1308. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1309. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1310. Designator.checkSubobject(Info, E, CSK);
  1311. }
  1312. void addDecl(EvalInfo &Info, const Expr *E,
  1313. const Decl *D, bool Virtual = false) {
  1314. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1315. Designator.addDeclUnchecked(D, Virtual);
  1316. }
  1317. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1318. if (!Designator.Entries.empty()) {
  1319. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1320. Designator.setInvalid();
  1321. return;
  1322. }
  1323. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1324. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1325. Designator.FirstEntryIsAnUnsizedArray = true;
  1326. Designator.addUnsizedArrayUnchecked(ElemTy);
  1327. }
  1328. }
  1329. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1330. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1331. Designator.addArrayUnchecked(CAT);
  1332. }
  1333. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1334. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1335. Designator.addComplexUnchecked(EltTy, Imag);
  1336. }
  1337. void clearIsNullPointer() {
  1338. IsNullPtr = false;
  1339. }
  1340. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1341. const APSInt &Index, CharUnits ElementSize) {
  1342. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1343. // but we're not required to diagnose it and it's valid in C++.)
  1344. if (!Index)
  1345. return;
  1346. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1347. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1348. // offsets.
  1349. uint64_t Offset64 = Offset.getQuantity();
  1350. uint64_t ElemSize64 = ElementSize.getQuantity();
  1351. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1352. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1353. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1354. Designator.adjustIndex(Info, E, Index);
  1355. clearIsNullPointer();
  1356. }
  1357. void adjustOffset(CharUnits N) {
  1358. Offset += N;
  1359. if (N.getQuantity())
  1360. clearIsNullPointer();
  1361. }
  1362. };
  1363. struct MemberPtr {
  1364. MemberPtr() {}
  1365. explicit MemberPtr(const ValueDecl *Decl) :
  1366. DeclAndIsDerivedMember(Decl, false), Path() {}
  1367. /// The member or (direct or indirect) field referred to by this member
  1368. /// pointer, or 0 if this is a null member pointer.
  1369. const ValueDecl *getDecl() const {
  1370. return DeclAndIsDerivedMember.getPointer();
  1371. }
  1372. /// Is this actually a member of some type derived from the relevant class?
  1373. bool isDerivedMember() const {
  1374. return DeclAndIsDerivedMember.getInt();
  1375. }
  1376. /// Get the class which the declaration actually lives in.
  1377. const CXXRecordDecl *getContainingRecord() const {
  1378. return cast<CXXRecordDecl>(
  1379. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1380. }
  1381. void moveInto(APValue &V) const {
  1382. V = APValue(getDecl(), isDerivedMember(), Path);
  1383. }
  1384. void setFrom(const APValue &V) {
  1385. assert(V.isMemberPointer());
  1386. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1387. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1388. Path.clear();
  1389. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1390. Path.insert(Path.end(), P.begin(), P.end());
  1391. }
  1392. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1393. /// whether the member is a member of some class derived from the class type
  1394. /// of the member pointer.
  1395. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1396. /// Path - The path of base/derived classes from the member declaration's
  1397. /// class (exclusive) to the class type of the member pointer (inclusive).
  1398. SmallVector<const CXXRecordDecl*, 4> Path;
  1399. /// Perform a cast towards the class of the Decl (either up or down the
  1400. /// hierarchy).
  1401. bool castBack(const CXXRecordDecl *Class) {
  1402. assert(!Path.empty());
  1403. const CXXRecordDecl *Expected;
  1404. if (Path.size() >= 2)
  1405. Expected = Path[Path.size() - 2];
  1406. else
  1407. Expected = getContainingRecord();
  1408. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1409. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1410. // if B does not contain the original member and is not a base or
  1411. // derived class of the class containing the original member, the result
  1412. // of the cast is undefined.
  1413. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1414. // (D::*). We consider that to be a language defect.
  1415. return false;
  1416. }
  1417. Path.pop_back();
  1418. return true;
  1419. }
  1420. /// Perform a base-to-derived member pointer cast.
  1421. bool castToDerived(const CXXRecordDecl *Derived) {
  1422. if (!getDecl())
  1423. return true;
  1424. if (!isDerivedMember()) {
  1425. Path.push_back(Derived);
  1426. return true;
  1427. }
  1428. if (!castBack(Derived))
  1429. return false;
  1430. if (Path.empty())
  1431. DeclAndIsDerivedMember.setInt(false);
  1432. return true;
  1433. }
  1434. /// Perform a derived-to-base member pointer cast.
  1435. bool castToBase(const CXXRecordDecl *Base) {
  1436. if (!getDecl())
  1437. return true;
  1438. if (Path.empty())
  1439. DeclAndIsDerivedMember.setInt(true);
  1440. if (isDerivedMember()) {
  1441. Path.push_back(Base);
  1442. return true;
  1443. }
  1444. return castBack(Base);
  1445. }
  1446. };
  1447. /// Compare two member pointers, which are assumed to be of the same type.
  1448. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1449. if (!LHS.getDecl() || !RHS.getDecl())
  1450. return !LHS.getDecl() && !RHS.getDecl();
  1451. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1452. return false;
  1453. return LHS.Path == RHS.Path;
  1454. }
  1455. }
  1456. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1457. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1458. const LValue &This, const Expr *E,
  1459. bool AllowNonLiteralTypes = false);
  1460. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1461. bool InvalidBaseOK = false);
  1462. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1463. bool InvalidBaseOK = false);
  1464. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1465. EvalInfo &Info);
  1466. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1467. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1468. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1469. EvalInfo &Info);
  1470. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1471. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1472. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1473. EvalInfo &Info);
  1474. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1475. /// Evaluate an integer or fixed point expression into an APResult.
  1476. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1477. EvalInfo &Info);
  1478. /// Evaluate only a fixed point expression into an APResult.
  1479. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1480. EvalInfo &Info);
  1481. //===----------------------------------------------------------------------===//
  1482. // Misc utilities
  1483. //===----------------------------------------------------------------------===//
  1484. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1485. /// preserving its value (by extending by up to one bit as needed).
  1486. static void negateAsSigned(APSInt &Int) {
  1487. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1488. Int = Int.extend(Int.getBitWidth() + 1);
  1489. Int.setIsSigned(true);
  1490. }
  1491. Int = -Int;
  1492. }
  1493. template<typename KeyT>
  1494. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1495. bool IsLifetimeExtended, LValue &LV) {
  1496. unsigned Version = getTempVersion();
  1497. APValue::LValueBase Base(Key, Index, Version);
  1498. LV.set(Base);
  1499. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1500. assert(Result.isAbsent() && "temporary created multiple times");
  1501. // If we're creating a temporary immediately in the operand of a speculative
  1502. // evaluation, don't register a cleanup to be run outside the speculative
  1503. // evaluation context, since we won't actually be able to initialize this
  1504. // object.
  1505. if (Index <= Info.SpeculativeEvaluationDepth) {
  1506. if (T.isDestructedType())
  1507. Info.noteSideEffect();
  1508. } else {
  1509. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
  1510. }
  1511. return Result;
  1512. }
  1513. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1514. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1515. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1516. return nullptr;
  1517. }
  1518. DynamicAllocLValue DA(NumHeapAllocs++);
  1519. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1520. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1521. std::forward_as_tuple(DA), std::tuple<>());
  1522. assert(Result.second && "reused a heap alloc index?");
  1523. Result.first->second.AllocExpr = E;
  1524. return &Result.first->second.Value;
  1525. }
  1526. /// Produce a string describing the given constexpr call.
  1527. void CallStackFrame::describe(raw_ostream &Out) {
  1528. unsigned ArgIndex = 0;
  1529. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1530. !isa<CXXConstructorDecl>(Callee) &&
  1531. cast<CXXMethodDecl>(Callee)->isInstance();
  1532. if (!IsMemberCall)
  1533. Out << *Callee << '(';
  1534. if (This && IsMemberCall) {
  1535. APValue Val;
  1536. This->moveInto(Val);
  1537. Val.printPretty(Out, Info.Ctx,
  1538. This->Designator.MostDerivedType);
  1539. // FIXME: Add parens around Val if needed.
  1540. Out << "->" << *Callee << '(';
  1541. IsMemberCall = false;
  1542. }
  1543. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1544. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1545. if (ArgIndex > (unsigned)IsMemberCall)
  1546. Out << ", ";
  1547. const ParmVarDecl *Param = *I;
  1548. const APValue &Arg = Arguments[ArgIndex];
  1549. Arg.printPretty(Out, Info.Ctx, Param->getType());
  1550. if (ArgIndex == 0 && IsMemberCall)
  1551. Out << "->" << *Callee << '(';
  1552. }
  1553. Out << ')';
  1554. }
  1555. /// Evaluate an expression to see if it had side-effects, and discard its
  1556. /// result.
  1557. /// \return \c true if the caller should keep evaluating.
  1558. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1559. APValue Scratch;
  1560. if (!Evaluate(Scratch, Info, E))
  1561. // We don't need the value, but we might have skipped a side effect here.
  1562. return Info.noteSideEffect();
  1563. return true;
  1564. }
  1565. /// Should this call expression be treated as a string literal?
  1566. static bool IsStringLiteralCall(const CallExpr *E) {
  1567. unsigned Builtin = E->getBuiltinCallee();
  1568. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1569. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1570. }
  1571. static bool IsGlobalLValue(APValue::LValueBase B) {
  1572. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1573. // constant expression of pointer type that evaluates to...
  1574. // ... a null pointer value, or a prvalue core constant expression of type
  1575. // std::nullptr_t.
  1576. if (!B) return true;
  1577. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1578. // ... the address of an object with static storage duration,
  1579. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1580. return VD->hasGlobalStorage();
  1581. // ... the address of a function,
  1582. return isa<FunctionDecl>(D);
  1583. }
  1584. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1585. return true;
  1586. const Expr *E = B.get<const Expr*>();
  1587. switch (E->getStmtClass()) {
  1588. default:
  1589. return false;
  1590. case Expr::CompoundLiteralExprClass: {
  1591. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1592. return CLE->isFileScope() && CLE->isLValue();
  1593. }
  1594. case Expr::MaterializeTemporaryExprClass:
  1595. // A materialized temporary might have been lifetime-extended to static
  1596. // storage duration.
  1597. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1598. // A string literal has static storage duration.
  1599. case Expr::StringLiteralClass:
  1600. case Expr::PredefinedExprClass:
  1601. case Expr::ObjCStringLiteralClass:
  1602. case Expr::ObjCEncodeExprClass:
  1603. case Expr::CXXUuidofExprClass:
  1604. return true;
  1605. case Expr::ObjCBoxedExprClass:
  1606. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1607. case Expr::CallExprClass:
  1608. return IsStringLiteralCall(cast<CallExpr>(E));
  1609. // For GCC compatibility, &&label has static storage duration.
  1610. case Expr::AddrLabelExprClass:
  1611. return true;
  1612. // A Block literal expression may be used as the initialization value for
  1613. // Block variables at global or local static scope.
  1614. case Expr::BlockExprClass:
  1615. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1616. case Expr::ImplicitValueInitExprClass:
  1617. // FIXME:
  1618. // We can never form an lvalue with an implicit value initialization as its
  1619. // base through expression evaluation, so these only appear in one case: the
  1620. // implicit variable declaration we invent when checking whether a constexpr
  1621. // constructor can produce a constant expression. We must assume that such
  1622. // an expression might be a global lvalue.
  1623. return true;
  1624. }
  1625. }
  1626. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1627. return LVal.Base.dyn_cast<const ValueDecl*>();
  1628. }
  1629. static bool IsLiteralLValue(const LValue &Value) {
  1630. if (Value.getLValueCallIndex())
  1631. return false;
  1632. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1633. return E && !isa<MaterializeTemporaryExpr>(E);
  1634. }
  1635. static bool IsWeakLValue(const LValue &Value) {
  1636. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1637. return Decl && Decl->isWeak();
  1638. }
  1639. static bool isZeroSized(const LValue &Value) {
  1640. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1641. if (Decl && isa<VarDecl>(Decl)) {
  1642. QualType Ty = Decl->getType();
  1643. if (Ty->isArrayType())
  1644. return Ty->isIncompleteType() ||
  1645. Decl->getASTContext().getTypeSize(Ty) == 0;
  1646. }
  1647. return false;
  1648. }
  1649. static bool HasSameBase(const LValue &A, const LValue &B) {
  1650. if (!A.getLValueBase())
  1651. return !B.getLValueBase();
  1652. if (!B.getLValueBase())
  1653. return false;
  1654. if (A.getLValueBase().getOpaqueValue() !=
  1655. B.getLValueBase().getOpaqueValue()) {
  1656. const Decl *ADecl = GetLValueBaseDecl(A);
  1657. if (!ADecl)
  1658. return false;
  1659. const Decl *BDecl = GetLValueBaseDecl(B);
  1660. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1661. return false;
  1662. }
  1663. return IsGlobalLValue(A.getLValueBase()) ||
  1664. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1665. A.getLValueVersion() == B.getLValueVersion());
  1666. }
  1667. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1668. assert(Base && "no location for a null lvalue");
  1669. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1670. if (VD)
  1671. Info.Note(VD->getLocation(), diag::note_declared_at);
  1672. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1673. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1674. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1675. // FIXME: Produce a note for dangling pointers too.
  1676. if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
  1677. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1678. diag::note_constexpr_dynamic_alloc_here);
  1679. }
  1680. // We have no information to show for a typeid(T) object.
  1681. }
  1682. enum class CheckEvaluationResultKind {
  1683. ConstantExpression,
  1684. FullyInitialized,
  1685. };
  1686. /// Materialized temporaries that we've already checked to determine if they're
  1687. /// initializsed by a constant expression.
  1688. using CheckedTemporaries =
  1689. llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
  1690. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1691. EvalInfo &Info, SourceLocation DiagLoc,
  1692. QualType Type, const APValue &Value,
  1693. Expr::ConstExprUsage Usage,
  1694. SourceLocation SubobjectLoc,
  1695. CheckedTemporaries &CheckedTemps);
  1696. /// Check that this reference or pointer core constant expression is a valid
  1697. /// value for an address or reference constant expression. Return true if we
  1698. /// can fold this expression, whether or not it's a constant expression.
  1699. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1700. QualType Type, const LValue &LVal,
  1701. Expr::ConstExprUsage Usage,
  1702. CheckedTemporaries &CheckedTemps) {
  1703. bool IsReferenceType = Type->isReferenceType();
  1704. APValue::LValueBase Base = LVal.getLValueBase();
  1705. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1706. // Check that the object is a global. Note that the fake 'this' object we
  1707. // manufacture when checking potential constant expressions is conservatively
  1708. // assumed to be global here.
  1709. if (!IsGlobalLValue(Base)) {
  1710. if (Info.getLangOpts().CPlusPlus11) {
  1711. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1712. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1713. << IsReferenceType << !Designator.Entries.empty()
  1714. << !!VD << VD;
  1715. NoteLValueLocation(Info, Base);
  1716. } else {
  1717. Info.FFDiag(Loc);
  1718. }
  1719. // Don't allow references to temporaries to escape.
  1720. return false;
  1721. }
  1722. assert((Info.checkingPotentialConstantExpression() ||
  1723. LVal.getLValueCallIndex() == 0) &&
  1724. "have call index for global lvalue");
  1725. if (Base.is<DynamicAllocLValue>()) {
  1726. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1727. << IsReferenceType << !Designator.Entries.empty();
  1728. NoteLValueLocation(Info, Base);
  1729. return false;
  1730. }
  1731. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1732. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1733. // Check if this is a thread-local variable.
  1734. if (Var->getTLSKind())
  1735. // FIXME: Diagnostic!
  1736. return false;
  1737. // A dllimport variable never acts like a constant.
  1738. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1739. // FIXME: Diagnostic!
  1740. return false;
  1741. }
  1742. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1743. // __declspec(dllimport) must be handled very carefully:
  1744. // We must never initialize an expression with the thunk in C++.
  1745. // Doing otherwise would allow the same id-expression to yield
  1746. // different addresses for the same function in different translation
  1747. // units. However, this means that we must dynamically initialize the
  1748. // expression with the contents of the import address table at runtime.
  1749. //
  1750. // The C language has no notion of ODR; furthermore, it has no notion of
  1751. // dynamic initialization. This means that we are permitted to
  1752. // perform initialization with the address of the thunk.
  1753. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1754. FD->hasAttr<DLLImportAttr>())
  1755. // FIXME: Diagnostic!
  1756. return false;
  1757. }
  1758. } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
  1759. Base.dyn_cast<const Expr *>())) {
  1760. if (CheckedTemps.insert(MTE).second) {
  1761. QualType TempType = getType(Base);
  1762. if (TempType.isDestructedType()) {
  1763. Info.FFDiag(MTE->getExprLoc(),
  1764. diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
  1765. << TempType;
  1766. return false;
  1767. }
  1768. APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  1769. assert(V && "evasluation result refers to uninitialised temporary");
  1770. if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1771. Info, MTE->getExprLoc(), TempType, *V,
  1772. Usage, SourceLocation(), CheckedTemps))
  1773. return false;
  1774. }
  1775. }
  1776. // Allow address constant expressions to be past-the-end pointers. This is
  1777. // an extension: the standard requires them to point to an object.
  1778. if (!IsReferenceType)
  1779. return true;
  1780. // A reference constant expression must refer to an object.
  1781. if (!Base) {
  1782. // FIXME: diagnostic
  1783. Info.CCEDiag(Loc);
  1784. return true;
  1785. }
  1786. // Does this refer one past the end of some object?
  1787. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1788. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1789. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1790. << !Designator.Entries.empty() << !!VD << VD;
  1791. NoteLValueLocation(Info, Base);
  1792. }
  1793. return true;
  1794. }
  1795. /// Member pointers are constant expressions unless they point to a
  1796. /// non-virtual dllimport member function.
  1797. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1798. SourceLocation Loc,
  1799. QualType Type,
  1800. const APValue &Value,
  1801. Expr::ConstExprUsage Usage) {
  1802. const ValueDecl *Member = Value.getMemberPointerDecl();
  1803. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1804. if (!FD)
  1805. return true;
  1806. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1807. !FD->hasAttr<DLLImportAttr>();
  1808. }
  1809. /// Check that this core constant expression is of literal type, and if not,
  1810. /// produce an appropriate diagnostic.
  1811. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1812. const LValue *This = nullptr) {
  1813. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1814. return true;
  1815. // C++1y: A constant initializer for an object o [...] may also invoke
  1816. // constexpr constructors for o and its subobjects even if those objects
  1817. // are of non-literal class types.
  1818. //
  1819. // C++11 missed this detail for aggregates, so classes like this:
  1820. // struct foo_t { union { int i; volatile int j; } u; };
  1821. // are not (obviously) initializable like so:
  1822. // __attribute__((__require_constant_initialization__))
  1823. // static const foo_t x = {{0}};
  1824. // because "i" is a subobject with non-literal initialization (due to the
  1825. // volatile member of the union). See:
  1826. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1827. // Therefore, we use the C++1y behavior.
  1828. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1829. return true;
  1830. // Prvalue constant expressions must be of literal types.
  1831. if (Info.getLangOpts().CPlusPlus11)
  1832. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1833. << E->getType();
  1834. else
  1835. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1836. return false;
  1837. }
  1838. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1839. EvalInfo &Info, SourceLocation DiagLoc,
  1840. QualType Type, const APValue &Value,
  1841. Expr::ConstExprUsage Usage,
  1842. SourceLocation SubobjectLoc,
  1843. CheckedTemporaries &CheckedTemps) {
  1844. if (!Value.hasValue()) {
  1845. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1846. << true << Type;
  1847. if (SubobjectLoc.isValid())
  1848. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1849. return false;
  1850. }
  1851. // We allow _Atomic(T) to be initialized from anything that T can be
  1852. // initialized from.
  1853. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1854. Type = AT->getValueType();
  1855. // Core issue 1454: For a literal constant expression of array or class type,
  1856. // each subobject of its value shall have been initialized by a constant
  1857. // expression.
  1858. if (Value.isArray()) {
  1859. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1860. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1861. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1862. Value.getArrayInitializedElt(I), Usage,
  1863. SubobjectLoc, CheckedTemps))
  1864. return false;
  1865. }
  1866. if (!Value.hasArrayFiller())
  1867. return true;
  1868. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1869. Value.getArrayFiller(), Usage, SubobjectLoc,
  1870. CheckedTemps);
  1871. }
  1872. if (Value.isUnion() && Value.getUnionField()) {
  1873. return CheckEvaluationResult(
  1874. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  1875. Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
  1876. CheckedTemps);
  1877. }
  1878. if (Value.isStruct()) {
  1879. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1880. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1881. unsigned BaseIndex = 0;
  1882. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1883. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  1884. Value.getStructBase(BaseIndex), Usage,
  1885. BS.getBeginLoc(), CheckedTemps))
  1886. return false;
  1887. ++BaseIndex;
  1888. }
  1889. }
  1890. for (const auto *I : RD->fields()) {
  1891. if (I->isUnnamedBitfield())
  1892. continue;
  1893. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  1894. Value.getStructField(I->getFieldIndex()),
  1895. Usage, I->getLocation(), CheckedTemps))
  1896. return false;
  1897. }
  1898. }
  1899. if (Value.isLValue() &&
  1900. CERK == CheckEvaluationResultKind::ConstantExpression) {
  1901. LValue LVal;
  1902. LVal.setFrom(Info.Ctx, Value);
  1903. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
  1904. CheckedTemps);
  1905. }
  1906. if (Value.isMemberPointer() &&
  1907. CERK == CheckEvaluationResultKind::ConstantExpression)
  1908. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1909. // Everything else is fine.
  1910. return true;
  1911. }
  1912. /// Check that this core constant expression value is a valid value for a
  1913. /// constant expression. If not, report an appropriate diagnostic. Does not
  1914. /// check that the expression is of literal type.
  1915. static bool
  1916. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1917. const APValue &Value,
  1918. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1919. CheckedTemporaries CheckedTemps;
  1920. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1921. Info, DiagLoc, Type, Value, Usage,
  1922. SourceLocation(), CheckedTemps);
  1923. }
  1924. /// Check that this evaluated value is fully-initialized and can be loaded by
  1925. /// an lvalue-to-rvalue conversion.
  1926. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  1927. QualType Type, const APValue &Value) {
  1928. CheckedTemporaries CheckedTemps;
  1929. return CheckEvaluationResult(
  1930. CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
  1931. Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
  1932. }
  1933. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  1934. /// "the allocated storage is deallocated within the evaluation".
  1935. static bool CheckMemoryLeaks(EvalInfo &Info) {
  1936. if (!Info.HeapAllocs.empty()) {
  1937. // We can still fold to a constant despite a compile-time memory leak,
  1938. // so long as the heap allocation isn't referenced in the result (we check
  1939. // that in CheckConstantExpression).
  1940. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  1941. diag::note_constexpr_memory_leak)
  1942. << unsigned(Info.HeapAllocs.size() - 1);
  1943. }
  1944. return true;
  1945. }
  1946. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1947. // A null base expression indicates a null pointer. These are always
  1948. // evaluatable, and they are false unless the offset is zero.
  1949. if (!Value.getLValueBase()) {
  1950. Result = !Value.getLValueOffset().isZero();
  1951. return true;
  1952. }
  1953. // We have a non-null base. These are generally known to be true, but if it's
  1954. // a weak declaration it can be null at runtime.
  1955. Result = true;
  1956. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1957. return !Decl || !Decl->isWeak();
  1958. }
  1959. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1960. switch (Val.getKind()) {
  1961. case APValue::None:
  1962. case APValue::Indeterminate:
  1963. return false;
  1964. case APValue::Int:
  1965. Result = Val.getInt().getBoolValue();
  1966. return true;
  1967. case APValue::FixedPoint:
  1968. Result = Val.getFixedPoint().getBoolValue();
  1969. return true;
  1970. case APValue::Float:
  1971. Result = !Val.getFloat().isZero();
  1972. return true;
  1973. case APValue::ComplexInt:
  1974. Result = Val.getComplexIntReal().getBoolValue() ||
  1975. Val.getComplexIntImag().getBoolValue();
  1976. return true;
  1977. case APValue::ComplexFloat:
  1978. Result = !Val.getComplexFloatReal().isZero() ||
  1979. !Val.getComplexFloatImag().isZero();
  1980. return true;
  1981. case APValue::LValue:
  1982. return EvalPointerValueAsBool(Val, Result);
  1983. case APValue::MemberPointer:
  1984. Result = Val.getMemberPointerDecl();
  1985. return true;
  1986. case APValue::Vector:
  1987. case APValue::Array:
  1988. case APValue::Struct:
  1989. case APValue::Union:
  1990. case APValue::AddrLabelDiff:
  1991. return false;
  1992. }
  1993. llvm_unreachable("unknown APValue kind");
  1994. }
  1995. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1996. EvalInfo &Info) {
  1997. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1998. APValue Val;
  1999. if (!Evaluate(Val, Info, E))
  2000. return false;
  2001. return HandleConversionToBool(Val, Result);
  2002. }
  2003. template<typename T>
  2004. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  2005. const T &SrcValue, QualType DestType) {
  2006. Info.CCEDiag(E, diag::note_constexpr_overflow)
  2007. << SrcValue << DestType;
  2008. return Info.noteUndefinedBehavior();
  2009. }
  2010. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  2011. QualType SrcType, const APFloat &Value,
  2012. QualType DestType, APSInt &Result) {
  2013. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2014. // Determine whether we are converting to unsigned or signed.
  2015. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  2016. Result = APSInt(DestWidth, !DestSigned);
  2017. bool ignored;
  2018. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  2019. & APFloat::opInvalidOp)
  2020. return HandleOverflow(Info, E, Value, DestType);
  2021. return true;
  2022. }
  2023. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  2024. QualType SrcType, QualType DestType,
  2025. APFloat &Result) {
  2026. APFloat Value = Result;
  2027. bool ignored;
  2028. Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  2029. APFloat::rmNearestTiesToEven, &ignored);
  2030. return true;
  2031. }
  2032. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  2033. QualType DestType, QualType SrcType,
  2034. const APSInt &Value) {
  2035. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2036. // Figure out if this is a truncate, extend or noop cast.
  2037. // If the input is signed, do a sign extend, noop, or truncate.
  2038. APSInt Result = Value.extOrTrunc(DestWidth);
  2039. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  2040. if (DestType->isBooleanType())
  2041. Result = Value.getBoolValue();
  2042. return Result;
  2043. }
  2044. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  2045. QualType SrcType, const APSInt &Value,
  2046. QualType DestType, APFloat &Result) {
  2047. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  2048. Result.convertFromAPInt(Value, Value.isSigned(),
  2049. APFloat::rmNearestTiesToEven);
  2050. return true;
  2051. }
  2052. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  2053. APValue &Value, const FieldDecl *FD) {
  2054. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2055. if (!Value.isInt()) {
  2056. // Trying to store a pointer-cast-to-integer into a bitfield.
  2057. // FIXME: In this case, we should provide the diagnostic for casting
  2058. // a pointer to an integer.
  2059. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2060. Info.FFDiag(E);
  2061. return false;
  2062. }
  2063. APSInt &Int = Value.getInt();
  2064. unsigned OldBitWidth = Int.getBitWidth();
  2065. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2066. if (NewBitWidth < OldBitWidth)
  2067. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2068. return true;
  2069. }
  2070. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2071. llvm::APInt &Res) {
  2072. APValue SVal;
  2073. if (!Evaluate(SVal, Info, E))
  2074. return false;
  2075. if (SVal.isInt()) {
  2076. Res = SVal.getInt();
  2077. return true;
  2078. }
  2079. if (SVal.isFloat()) {
  2080. Res = SVal.getFloat().bitcastToAPInt();
  2081. return true;
  2082. }
  2083. if (SVal.isVector()) {
  2084. QualType VecTy = E->getType();
  2085. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2086. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2087. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2088. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2089. Res = llvm::APInt::getNullValue(VecSize);
  2090. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2091. APValue &Elt = SVal.getVectorElt(i);
  2092. llvm::APInt EltAsInt;
  2093. if (Elt.isInt()) {
  2094. EltAsInt = Elt.getInt();
  2095. } else if (Elt.isFloat()) {
  2096. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2097. } else {
  2098. // Don't try to handle vectors of anything other than int or float
  2099. // (not sure if it's possible to hit this case).
  2100. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2101. return false;
  2102. }
  2103. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2104. if (BigEndian)
  2105. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2106. else
  2107. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2108. }
  2109. return true;
  2110. }
  2111. // Give up if the input isn't an int, float, or vector. For example, we
  2112. // reject "(v4i16)(intptr_t)&a".
  2113. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2114. return false;
  2115. }
  2116. /// Perform the given integer operation, which is known to need at most BitWidth
  2117. /// bits, and check for overflow in the original type (if that type was not an
  2118. /// unsigned type).
  2119. template<typename Operation>
  2120. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2121. const APSInt &LHS, const APSInt &RHS,
  2122. unsigned BitWidth, Operation Op,
  2123. APSInt &Result) {
  2124. if (LHS.isUnsigned()) {
  2125. Result = Op(LHS, RHS);
  2126. return true;
  2127. }
  2128. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2129. Result = Value.trunc(LHS.getBitWidth());
  2130. if (Result.extend(BitWidth) != Value) {
  2131. if (Info.checkingForUndefinedBehavior())
  2132. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2133. diag::warn_integer_constant_overflow)
  2134. << Result.toString(10) << E->getType();
  2135. else
  2136. return HandleOverflow(Info, E, Value, E->getType());
  2137. }
  2138. return true;
  2139. }
  2140. /// Perform the given binary integer operation.
  2141. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2142. BinaryOperatorKind Opcode, APSInt RHS,
  2143. APSInt &Result) {
  2144. switch (Opcode) {
  2145. default:
  2146. Info.FFDiag(E);
  2147. return false;
  2148. case BO_Mul:
  2149. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2150. std::multiplies<APSInt>(), Result);
  2151. case BO_Add:
  2152. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2153. std::plus<APSInt>(), Result);
  2154. case BO_Sub:
  2155. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2156. std::minus<APSInt>(), Result);
  2157. case BO_And: Result = LHS & RHS; return true;
  2158. case BO_Xor: Result = LHS ^ RHS; return true;
  2159. case BO_Or: Result = LHS | RHS; return true;
  2160. case BO_Div:
  2161. case BO_Rem:
  2162. if (RHS == 0) {
  2163. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2164. return false;
  2165. }
  2166. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2167. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2168. // this operation and gives the two's complement result.
  2169. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2170. LHS.isSigned() && LHS.isMinSignedValue())
  2171. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2172. E->getType());
  2173. return true;
  2174. case BO_Shl: {
  2175. if (Info.getLangOpts().OpenCL)
  2176. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2177. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2178. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2179. RHS.isUnsigned());
  2180. else if (RHS.isSigned() && RHS.isNegative()) {
  2181. // During constant-folding, a negative shift is an opposite shift. Such
  2182. // a shift is not a constant expression.
  2183. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2184. RHS = -RHS;
  2185. goto shift_right;
  2186. }
  2187. shift_left:
  2188. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2189. // the shifted type.
  2190. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2191. if (SA != RHS) {
  2192. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2193. << RHS << E->getType() << LHS.getBitWidth();
  2194. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  2195. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2196. // operand, and must not overflow the corresponding unsigned type.
  2197. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2198. // E1 x 2^E2 module 2^N.
  2199. if (LHS.isNegative())
  2200. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2201. else if (LHS.countLeadingZeros() < SA)
  2202. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2203. }
  2204. Result = LHS << SA;
  2205. return true;
  2206. }
  2207. case BO_Shr: {
  2208. if (Info.getLangOpts().OpenCL)
  2209. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2210. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2211. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2212. RHS.isUnsigned());
  2213. else if (RHS.isSigned() && RHS.isNegative()) {
  2214. // During constant-folding, a negative shift is an opposite shift. Such a
  2215. // shift is not a constant expression.
  2216. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2217. RHS = -RHS;
  2218. goto shift_left;
  2219. }
  2220. shift_right:
  2221. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2222. // shifted type.
  2223. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2224. if (SA != RHS)
  2225. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2226. << RHS << E->getType() << LHS.getBitWidth();
  2227. Result = LHS >> SA;
  2228. return true;
  2229. }
  2230. case BO_LT: Result = LHS < RHS; return true;
  2231. case BO_GT: Result = LHS > RHS; return true;
  2232. case BO_LE: Result = LHS <= RHS; return true;
  2233. case BO_GE: Result = LHS >= RHS; return true;
  2234. case BO_EQ: Result = LHS == RHS; return true;
  2235. case BO_NE: Result = LHS != RHS; return true;
  2236. case BO_Cmp:
  2237. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2238. }
  2239. }
  2240. /// Perform the given binary floating-point operation, in-place, on LHS.
  2241. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2242. APFloat &LHS, BinaryOperatorKind Opcode,
  2243. const APFloat &RHS) {
  2244. switch (Opcode) {
  2245. default:
  2246. Info.FFDiag(E);
  2247. return false;
  2248. case BO_Mul:
  2249. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2250. break;
  2251. case BO_Add:
  2252. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2253. break;
  2254. case BO_Sub:
  2255. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2256. break;
  2257. case BO_Div:
  2258. // [expr.mul]p4:
  2259. // If the second operand of / or % is zero the behavior is undefined.
  2260. if (RHS.isZero())
  2261. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2262. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2263. break;
  2264. }
  2265. // [expr.pre]p4:
  2266. // If during the evaluation of an expression, the result is not
  2267. // mathematically defined [...], the behavior is undefined.
  2268. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2269. if (LHS.isNaN()) {
  2270. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2271. return Info.noteUndefinedBehavior();
  2272. }
  2273. return true;
  2274. }
  2275. /// Cast an lvalue referring to a base subobject to a derived class, by
  2276. /// truncating the lvalue's path to the given length.
  2277. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2278. const RecordDecl *TruncatedType,
  2279. unsigned TruncatedElements) {
  2280. SubobjectDesignator &D = Result.Designator;
  2281. // Check we actually point to a derived class object.
  2282. if (TruncatedElements == D.Entries.size())
  2283. return true;
  2284. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2285. "not casting to a derived class");
  2286. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2287. return false;
  2288. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2289. const RecordDecl *RD = TruncatedType;
  2290. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2291. if (RD->isInvalidDecl()) return false;
  2292. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2293. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2294. if (isVirtualBaseClass(D.Entries[I]))
  2295. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2296. else
  2297. Result.Offset -= Layout.getBaseClassOffset(Base);
  2298. RD = Base;
  2299. }
  2300. D.Entries.resize(TruncatedElements);
  2301. return true;
  2302. }
  2303. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2304. const CXXRecordDecl *Derived,
  2305. const CXXRecordDecl *Base,
  2306. const ASTRecordLayout *RL = nullptr) {
  2307. if (!RL) {
  2308. if (Derived->isInvalidDecl()) return false;
  2309. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2310. }
  2311. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2312. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2313. return true;
  2314. }
  2315. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2316. const CXXRecordDecl *DerivedDecl,
  2317. const CXXBaseSpecifier *Base) {
  2318. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2319. if (!Base->isVirtual())
  2320. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2321. SubobjectDesignator &D = Obj.Designator;
  2322. if (D.Invalid)
  2323. return false;
  2324. // Extract most-derived object and corresponding type.
  2325. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2326. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2327. return false;
  2328. // Find the virtual base class.
  2329. if (DerivedDecl->isInvalidDecl()) return false;
  2330. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2331. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2332. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2333. return true;
  2334. }
  2335. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2336. QualType Type, LValue &Result) {
  2337. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2338. PathE = E->path_end();
  2339. PathI != PathE; ++PathI) {
  2340. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2341. *PathI))
  2342. return false;
  2343. Type = (*PathI)->getType();
  2344. }
  2345. return true;
  2346. }
  2347. /// Cast an lvalue referring to a derived class to a known base subobject.
  2348. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2349. const CXXRecordDecl *DerivedRD,
  2350. const CXXRecordDecl *BaseRD) {
  2351. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2352. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2353. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2354. llvm_unreachable("Class must be derived from the passed in base class!");
  2355. for (CXXBasePathElement &Elem : Paths.front())
  2356. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2357. return false;
  2358. return true;
  2359. }
  2360. /// Update LVal to refer to the given field, which must be a member of the type
  2361. /// currently described by LVal.
  2362. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2363. const FieldDecl *FD,
  2364. const ASTRecordLayout *RL = nullptr) {
  2365. if (!RL) {
  2366. if (FD->getParent()->isInvalidDecl()) return false;
  2367. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2368. }
  2369. unsigned I = FD->getFieldIndex();
  2370. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2371. LVal.addDecl(Info, E, FD);
  2372. return true;
  2373. }
  2374. /// Update LVal to refer to the given indirect field.
  2375. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2376. LValue &LVal,
  2377. const IndirectFieldDecl *IFD) {
  2378. for (const auto *C : IFD->chain())
  2379. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2380. return false;
  2381. return true;
  2382. }
  2383. /// Get the size of the given type in char units.
  2384. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2385. QualType Type, CharUnits &Size) {
  2386. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2387. // extension.
  2388. if (Type->isVoidType() || Type->isFunctionType()) {
  2389. Size = CharUnits::One();
  2390. return true;
  2391. }
  2392. if (Type->isDependentType()) {
  2393. Info.FFDiag(Loc);
  2394. return false;
  2395. }
  2396. if (!Type->isConstantSizeType()) {
  2397. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2398. // FIXME: Better diagnostic.
  2399. Info.FFDiag(Loc);
  2400. return false;
  2401. }
  2402. Size = Info.Ctx.getTypeSizeInChars(Type);
  2403. return true;
  2404. }
  2405. /// Update a pointer value to model pointer arithmetic.
  2406. /// \param Info - Information about the ongoing evaluation.
  2407. /// \param E - The expression being evaluated, for diagnostic purposes.
  2408. /// \param LVal - The pointer value to be updated.
  2409. /// \param EltTy - The pointee type represented by LVal.
  2410. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2411. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2412. LValue &LVal, QualType EltTy,
  2413. APSInt Adjustment) {
  2414. CharUnits SizeOfPointee;
  2415. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2416. return false;
  2417. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2418. return true;
  2419. }
  2420. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2421. LValue &LVal, QualType EltTy,
  2422. int64_t Adjustment) {
  2423. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2424. APSInt::get(Adjustment));
  2425. }
  2426. /// Update an lvalue to refer to a component of a complex number.
  2427. /// \param Info - Information about the ongoing evaluation.
  2428. /// \param LVal - The lvalue to be updated.
  2429. /// \param EltTy - The complex number's component type.
  2430. /// \param Imag - False for the real component, true for the imaginary.
  2431. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2432. LValue &LVal, QualType EltTy,
  2433. bool Imag) {
  2434. if (Imag) {
  2435. CharUnits SizeOfComponent;
  2436. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2437. return false;
  2438. LVal.Offset += SizeOfComponent;
  2439. }
  2440. LVal.addComplex(Info, E, EltTy, Imag);
  2441. return true;
  2442. }
  2443. /// Try to evaluate the initializer for a variable declaration.
  2444. ///
  2445. /// \param Info Information about the ongoing evaluation.
  2446. /// \param E An expression to be used when printing diagnostics.
  2447. /// \param VD The variable whose initializer should be obtained.
  2448. /// \param Frame The frame in which the variable was created. Must be null
  2449. /// if this variable is not local to the evaluation.
  2450. /// \param Result Filled in with a pointer to the value of the variable.
  2451. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2452. const VarDecl *VD, CallStackFrame *Frame,
  2453. APValue *&Result, const LValue *LVal) {
  2454. // If this is a parameter to an active constexpr function call, perform
  2455. // argument substitution.
  2456. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2457. // Assume arguments of a potential constant expression are unknown
  2458. // constant expressions.
  2459. if (Info.checkingPotentialConstantExpression())
  2460. return false;
  2461. if (!Frame || !Frame->Arguments) {
  2462. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2463. return false;
  2464. }
  2465. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2466. return true;
  2467. }
  2468. // If this is a local variable, dig out its value.
  2469. if (Frame) {
  2470. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2471. : Frame->getCurrentTemporary(VD);
  2472. if (!Result) {
  2473. // Assume variables referenced within a lambda's call operator that were
  2474. // not declared within the call operator are captures and during checking
  2475. // of a potential constant expression, assume they are unknown constant
  2476. // expressions.
  2477. assert(isLambdaCallOperator(Frame->Callee) &&
  2478. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2479. "missing value for local variable");
  2480. if (Info.checkingPotentialConstantExpression())
  2481. return false;
  2482. // FIXME: implement capture evaluation during constant expr evaluation.
  2483. Info.FFDiag(E->getBeginLoc(),
  2484. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2485. << "captures not currently allowed";
  2486. return false;
  2487. }
  2488. return true;
  2489. }
  2490. // Dig out the initializer, and use the declaration which it's attached to.
  2491. const Expr *Init = VD->getAnyInitializer(VD);
  2492. if (!Init || Init->isValueDependent()) {
  2493. // If we're checking a potential constant expression, the variable could be
  2494. // initialized later.
  2495. if (!Info.checkingPotentialConstantExpression())
  2496. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2497. return false;
  2498. }
  2499. // If we're currently evaluating the initializer of this declaration, use that
  2500. // in-flight value.
  2501. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2502. Result = Info.EvaluatingDeclValue;
  2503. return true;
  2504. }
  2505. // Never evaluate the initializer of a weak variable. We can't be sure that
  2506. // this is the definition which will be used.
  2507. if (VD->isWeak()) {
  2508. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2509. return false;
  2510. }
  2511. // Check that we can fold the initializer. In C++, we will have already done
  2512. // this in the cases where it matters for conformance.
  2513. SmallVector<PartialDiagnosticAt, 8> Notes;
  2514. if (!VD->evaluateValue(Notes)) {
  2515. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2516. Notes.size() + 1) << VD;
  2517. Info.Note(VD->getLocation(), diag::note_declared_at);
  2518. Info.addNotes(Notes);
  2519. return false;
  2520. } else if (!VD->checkInitIsICE()) {
  2521. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2522. Notes.size() + 1) << VD;
  2523. Info.Note(VD->getLocation(), diag::note_declared_at);
  2524. Info.addNotes(Notes);
  2525. }
  2526. Result = VD->getEvaluatedValue();
  2527. return true;
  2528. }
  2529. static bool IsConstNonVolatile(QualType T) {
  2530. Qualifiers Quals = T.getQualifiers();
  2531. return Quals.hasConst() && !Quals.hasVolatile();
  2532. }
  2533. /// Get the base index of the given base class within an APValue representing
  2534. /// the given derived class.
  2535. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2536. const CXXRecordDecl *Base) {
  2537. Base = Base->getCanonicalDecl();
  2538. unsigned Index = 0;
  2539. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2540. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2541. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2542. return Index;
  2543. }
  2544. llvm_unreachable("base class missing from derived class's bases list");
  2545. }
  2546. /// Extract the value of a character from a string literal.
  2547. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2548. uint64_t Index) {
  2549. assert(!isa<SourceLocExpr>(Lit) &&
  2550. "SourceLocExpr should have already been converted to a StringLiteral");
  2551. // FIXME: Support MakeStringConstant
  2552. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2553. std::string Str;
  2554. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2555. assert(Index <= Str.size() && "Index too large");
  2556. return APSInt::getUnsigned(Str.c_str()[Index]);
  2557. }
  2558. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2559. Lit = PE->getFunctionName();
  2560. const StringLiteral *S = cast<StringLiteral>(Lit);
  2561. const ConstantArrayType *CAT =
  2562. Info.Ctx.getAsConstantArrayType(S->getType());
  2563. assert(CAT && "string literal isn't an array");
  2564. QualType CharType = CAT->getElementType();
  2565. assert(CharType->isIntegerType() && "unexpected character type");
  2566. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2567. CharType->isUnsignedIntegerType());
  2568. if (Index < S->getLength())
  2569. Value = S->getCodeUnit(Index);
  2570. return Value;
  2571. }
  2572. // Expand a string literal into an array of characters.
  2573. //
  2574. // FIXME: This is inefficient; we should probably introduce something similar
  2575. // to the LLVM ConstantDataArray to make this cheaper.
  2576. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2577. APValue &Result,
  2578. QualType AllocType = QualType()) {
  2579. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  2580. AllocType.isNull() ? S->getType() : AllocType);
  2581. assert(CAT && "string literal isn't an array");
  2582. QualType CharType = CAT->getElementType();
  2583. assert(CharType->isIntegerType() && "unexpected character type");
  2584. unsigned Elts = CAT->getSize().getZExtValue();
  2585. Result = APValue(APValue::UninitArray(),
  2586. std::min(S->getLength(), Elts), Elts);
  2587. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2588. CharType->isUnsignedIntegerType());
  2589. if (Result.hasArrayFiller())
  2590. Result.getArrayFiller() = APValue(Value);
  2591. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2592. Value = S->getCodeUnit(I);
  2593. Result.getArrayInitializedElt(I) = APValue(Value);
  2594. }
  2595. }
  2596. // Expand an array so that it has more than Index filled elements.
  2597. static void expandArray(APValue &Array, unsigned Index) {
  2598. unsigned Size = Array.getArraySize();
  2599. assert(Index < Size);
  2600. // Always at least double the number of elements for which we store a value.
  2601. unsigned OldElts = Array.getArrayInitializedElts();
  2602. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2603. NewElts = std::min(Size, std::max(NewElts, 8u));
  2604. // Copy the data across.
  2605. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2606. for (unsigned I = 0; I != OldElts; ++I)
  2607. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2608. for (unsigned I = OldElts; I != NewElts; ++I)
  2609. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2610. if (NewValue.hasArrayFiller())
  2611. NewValue.getArrayFiller() = Array.getArrayFiller();
  2612. Array.swap(NewValue);
  2613. }
  2614. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2615. /// conversion. If it's of class type, we may assume that the copy operation
  2616. /// is trivial. Note that this is never true for a union type with fields
  2617. /// (because the copy always "reads" the active member) and always true for
  2618. /// a non-class type.
  2619. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2620. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2621. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2622. return true;
  2623. if (RD->isEmpty())
  2624. return false;
  2625. for (auto *Field : RD->fields())
  2626. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2627. return true;
  2628. for (auto &BaseSpec : RD->bases())
  2629. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2630. return true;
  2631. return false;
  2632. }
  2633. /// Diagnose an attempt to read from any unreadable field within the specified
  2634. /// type, which might be a class type.
  2635. static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
  2636. QualType T) {
  2637. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2638. if (!RD)
  2639. return false;
  2640. if (!RD->hasMutableFields())
  2641. return false;
  2642. for (auto *Field : RD->fields()) {
  2643. // If we're actually going to read this field in some way, then it can't
  2644. // be mutable. If we're in a union, then assigning to a mutable field
  2645. // (even an empty one) can change the active member, so that's not OK.
  2646. // FIXME: Add core issue number for the union case.
  2647. if (Field->isMutable() &&
  2648. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2649. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
  2650. Info.Note(Field->getLocation(), diag::note_declared_at);
  2651. return true;
  2652. }
  2653. if (diagnoseMutableFields(Info, E, AK, Field->getType()))
  2654. return true;
  2655. }
  2656. for (auto &BaseSpec : RD->bases())
  2657. if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
  2658. return true;
  2659. // All mutable fields were empty, and thus not actually read.
  2660. return false;
  2661. }
  2662. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2663. APValue::LValueBase Base,
  2664. bool MutableSubobject = false) {
  2665. // A temporary we created.
  2666. if (Base.getCallIndex())
  2667. return true;
  2668. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2669. if (!Evaluating)
  2670. return false;
  2671. auto *BaseD = Base.dyn_cast<const ValueDecl*>();
  2672. switch (Info.IsEvaluatingDecl) {
  2673. case EvalInfo::EvaluatingDeclKind::None:
  2674. return false;
  2675. case EvalInfo::EvaluatingDeclKind::Ctor:
  2676. // The variable whose initializer we're evaluating.
  2677. if (BaseD)
  2678. return declaresSameEntity(Evaluating, BaseD);
  2679. // A temporary lifetime-extended by the variable whose initializer we're
  2680. // evaluating.
  2681. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2682. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2683. return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
  2684. return false;
  2685. case EvalInfo::EvaluatingDeclKind::Dtor:
  2686. // C++2a [expr.const]p6:
  2687. // [during constant destruction] the lifetime of a and its non-mutable
  2688. // subobjects (but not its mutable subobjects) [are] considered to start
  2689. // within e.
  2690. //
  2691. // FIXME: We can meaningfully extend this to cover non-const objects, but
  2692. // we will need special handling: we should be able to access only
  2693. // subobjects of such objects that are themselves declared const.
  2694. if (!BaseD ||
  2695. !(BaseD->getType().isConstQualified() ||
  2696. BaseD->getType()->isReferenceType()) ||
  2697. MutableSubobject)
  2698. return false;
  2699. return declaresSameEntity(Evaluating, BaseD);
  2700. }
  2701. llvm_unreachable("unknown evaluating decl kind");
  2702. }
  2703. namespace {
  2704. /// A handle to a complete object (an object that is not a subobject of
  2705. /// another object).
  2706. struct CompleteObject {
  2707. /// The identity of the object.
  2708. APValue::LValueBase Base;
  2709. /// The value of the complete object.
  2710. APValue *Value;
  2711. /// The type of the complete object.
  2712. QualType Type;
  2713. CompleteObject() : Value(nullptr) {}
  2714. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2715. : Base(Base), Value(Value), Type(Type) {}
  2716. bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
  2717. // In C++14 onwards, it is permitted to read a mutable member whose
  2718. // lifetime began within the evaluation.
  2719. // FIXME: Should we also allow this in C++11?
  2720. if (!Info.getLangOpts().CPlusPlus14)
  2721. return false;
  2722. return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
  2723. }
  2724. explicit operator bool() const { return !Type.isNull(); }
  2725. };
  2726. } // end anonymous namespace
  2727. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2728. bool IsMutable = false) {
  2729. // C++ [basic.type.qualifier]p1:
  2730. // - A const object is an object of type const T or a non-mutable subobject
  2731. // of a const object.
  2732. if (ObjType.isConstQualified() && !IsMutable)
  2733. SubobjType.addConst();
  2734. // - A volatile object is an object of type const T or a subobject of a
  2735. // volatile object.
  2736. if (ObjType.isVolatileQualified())
  2737. SubobjType.addVolatile();
  2738. return SubobjType;
  2739. }
  2740. /// Find the designated sub-object of an rvalue.
  2741. template<typename SubobjectHandler>
  2742. typename SubobjectHandler::result_type
  2743. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2744. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2745. if (Sub.Invalid)
  2746. // A diagnostic will have already been produced.
  2747. return handler.failed();
  2748. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2749. if (Info.getLangOpts().CPlusPlus11)
  2750. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2751. ? diag::note_constexpr_access_past_end
  2752. : diag::note_constexpr_access_unsized_array)
  2753. << handler.AccessKind;
  2754. else
  2755. Info.FFDiag(E);
  2756. return handler.failed();
  2757. }
  2758. APValue *O = Obj.Value;
  2759. QualType ObjType = Obj.Type;
  2760. const FieldDecl *LastField = nullptr;
  2761. const FieldDecl *VolatileField = nullptr;
  2762. // Walk the designator's path to find the subobject.
  2763. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2764. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2765. if (O->isAbsent() ||
  2766. (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
  2767. handler.AccessKind != AK_ReadObjectRepresentation)) {
  2768. if (!Info.checkingPotentialConstantExpression())
  2769. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2770. << handler.AccessKind << O->isIndeterminate();
  2771. return handler.failed();
  2772. }
  2773. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  2774. // const and volatile semantics are not applied on an object under
  2775. // {con,de}struction.
  2776. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2777. ObjType->isRecordType() &&
  2778. Info.isEvaluatingCtorDtor(
  2779. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2780. Sub.Entries.begin() + I)) !=
  2781. ConstructionPhase::None) {
  2782. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2783. ObjType.removeLocalConst();
  2784. ObjType.removeLocalVolatile();
  2785. }
  2786. // If this is our last pass, check that the final object type is OK.
  2787. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2788. // Accesses to volatile objects are prohibited.
  2789. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2790. if (Info.getLangOpts().CPlusPlus) {
  2791. int DiagKind;
  2792. SourceLocation Loc;
  2793. const NamedDecl *Decl = nullptr;
  2794. if (VolatileField) {
  2795. DiagKind = 2;
  2796. Loc = VolatileField->getLocation();
  2797. Decl = VolatileField;
  2798. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2799. DiagKind = 1;
  2800. Loc = VD->getLocation();
  2801. Decl = VD;
  2802. } else {
  2803. DiagKind = 0;
  2804. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2805. Loc = E->getExprLoc();
  2806. }
  2807. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2808. << handler.AccessKind << DiagKind << Decl;
  2809. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2810. } else {
  2811. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2812. }
  2813. return handler.failed();
  2814. }
  2815. // If we are reading an object of class type, there may still be more
  2816. // things we need to check: if there are any mutable subobjects, we
  2817. // cannot perform this read. (This only happens when performing a trivial
  2818. // copy or assignment.)
  2819. if (ObjType->isRecordType() &&
  2820. !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
  2821. diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
  2822. return handler.failed();
  2823. }
  2824. if (I == N) {
  2825. if (!handler.found(*O, ObjType))
  2826. return false;
  2827. // If we modified a bit-field, truncate it to the right width.
  2828. if (isModification(handler.AccessKind) &&
  2829. LastField && LastField->isBitField() &&
  2830. !truncateBitfieldValue(Info, E, *O, LastField))
  2831. return false;
  2832. return true;
  2833. }
  2834. LastField = nullptr;
  2835. if (ObjType->isArrayType()) {
  2836. // Next subobject is an array element.
  2837. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2838. assert(CAT && "vla in literal type?");
  2839. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2840. if (CAT->getSize().ule(Index)) {
  2841. // Note, it should not be possible to form a pointer with a valid
  2842. // designator which points more than one past the end of the array.
  2843. if (Info.getLangOpts().CPlusPlus11)
  2844. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2845. << handler.AccessKind;
  2846. else
  2847. Info.FFDiag(E);
  2848. return handler.failed();
  2849. }
  2850. ObjType = CAT->getElementType();
  2851. if (O->getArrayInitializedElts() > Index)
  2852. O = &O->getArrayInitializedElt(Index);
  2853. else if (!isRead(handler.AccessKind)) {
  2854. expandArray(*O, Index);
  2855. O = &O->getArrayInitializedElt(Index);
  2856. } else
  2857. O = &O->getArrayFiller();
  2858. } else if (ObjType->isAnyComplexType()) {
  2859. // Next subobject is a complex number.
  2860. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2861. if (Index > 1) {
  2862. if (Info.getLangOpts().CPlusPlus11)
  2863. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2864. << handler.AccessKind;
  2865. else
  2866. Info.FFDiag(E);
  2867. return handler.failed();
  2868. }
  2869. ObjType = getSubobjectType(
  2870. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2871. assert(I == N - 1 && "extracting subobject of scalar?");
  2872. if (O->isComplexInt()) {
  2873. return handler.found(Index ? O->getComplexIntImag()
  2874. : O->getComplexIntReal(), ObjType);
  2875. } else {
  2876. assert(O->isComplexFloat());
  2877. return handler.found(Index ? O->getComplexFloatImag()
  2878. : O->getComplexFloatReal(), ObjType);
  2879. }
  2880. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2881. if (Field->isMutable() &&
  2882. !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
  2883. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
  2884. << handler.AccessKind << Field;
  2885. Info.Note(Field->getLocation(), diag::note_declared_at);
  2886. return handler.failed();
  2887. }
  2888. // Next subobject is a class, struct or union field.
  2889. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2890. if (RD->isUnion()) {
  2891. const FieldDecl *UnionField = O->getUnionField();
  2892. if (!UnionField ||
  2893. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2894. // FIXME: If O->getUnionValue() is absent, report that there's no
  2895. // active union member rather than reporting the prior active union
  2896. // member. We'll need to fix nullptr_t to not use APValue() as its
  2897. // representation first.
  2898. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2899. << handler.AccessKind << Field << !UnionField << UnionField;
  2900. return handler.failed();
  2901. }
  2902. O = &O->getUnionValue();
  2903. } else
  2904. O = &O->getStructField(Field->getFieldIndex());
  2905. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2906. LastField = Field;
  2907. if (Field->getType().isVolatileQualified())
  2908. VolatileField = Field;
  2909. } else {
  2910. // Next subobject is a base class.
  2911. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2912. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2913. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2914. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2915. }
  2916. }
  2917. }
  2918. namespace {
  2919. struct ExtractSubobjectHandler {
  2920. EvalInfo &Info;
  2921. const Expr *E;
  2922. APValue &Result;
  2923. const AccessKinds AccessKind;
  2924. typedef bool result_type;
  2925. bool failed() { return false; }
  2926. bool found(APValue &Subobj, QualType SubobjType) {
  2927. Result = Subobj;
  2928. if (AccessKind == AK_ReadObjectRepresentation)
  2929. return true;
  2930. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  2931. }
  2932. bool found(APSInt &Value, QualType SubobjType) {
  2933. Result = APValue(Value);
  2934. return true;
  2935. }
  2936. bool found(APFloat &Value, QualType SubobjType) {
  2937. Result = APValue(Value);
  2938. return true;
  2939. }
  2940. };
  2941. } // end anonymous namespace
  2942. /// Extract the designated sub-object of an rvalue.
  2943. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2944. const CompleteObject &Obj,
  2945. const SubobjectDesignator &Sub, APValue &Result,
  2946. AccessKinds AK = AK_Read) {
  2947. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  2948. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  2949. return findSubobject(Info, E, Obj, Sub, Handler);
  2950. }
  2951. namespace {
  2952. struct ModifySubobjectHandler {
  2953. EvalInfo &Info;
  2954. APValue &NewVal;
  2955. const Expr *E;
  2956. typedef bool result_type;
  2957. static const AccessKinds AccessKind = AK_Assign;
  2958. bool checkConst(QualType QT) {
  2959. // Assigning to a const object has undefined behavior.
  2960. if (QT.isConstQualified()) {
  2961. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2962. return false;
  2963. }
  2964. return true;
  2965. }
  2966. bool failed() { return false; }
  2967. bool found(APValue &Subobj, QualType SubobjType) {
  2968. if (!checkConst(SubobjType))
  2969. return false;
  2970. // We've been given ownership of NewVal, so just swap it in.
  2971. Subobj.swap(NewVal);
  2972. return true;
  2973. }
  2974. bool found(APSInt &Value, QualType SubobjType) {
  2975. if (!checkConst(SubobjType))
  2976. return false;
  2977. if (!NewVal.isInt()) {
  2978. // Maybe trying to write a cast pointer value into a complex?
  2979. Info.FFDiag(E);
  2980. return false;
  2981. }
  2982. Value = NewVal.getInt();
  2983. return true;
  2984. }
  2985. bool found(APFloat &Value, QualType SubobjType) {
  2986. if (!checkConst(SubobjType))
  2987. return false;
  2988. Value = NewVal.getFloat();
  2989. return true;
  2990. }
  2991. };
  2992. } // end anonymous namespace
  2993. const AccessKinds ModifySubobjectHandler::AccessKind;
  2994. /// Update the designated sub-object of an rvalue to the given value.
  2995. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2996. const CompleteObject &Obj,
  2997. const SubobjectDesignator &Sub,
  2998. APValue &NewVal) {
  2999. ModifySubobjectHandler Handler = { Info, NewVal, E };
  3000. return findSubobject(Info, E, Obj, Sub, Handler);
  3001. }
  3002. /// Find the position where two subobject designators diverge, or equivalently
  3003. /// the length of the common initial subsequence.
  3004. static unsigned FindDesignatorMismatch(QualType ObjType,
  3005. const SubobjectDesignator &A,
  3006. const SubobjectDesignator &B,
  3007. bool &WasArrayIndex) {
  3008. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  3009. for (/**/; I != N; ++I) {
  3010. if (!ObjType.isNull() &&
  3011. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  3012. // Next subobject is an array element.
  3013. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  3014. WasArrayIndex = true;
  3015. return I;
  3016. }
  3017. if (ObjType->isAnyComplexType())
  3018. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  3019. else
  3020. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  3021. } else {
  3022. if (A.Entries[I].getAsBaseOrMember() !=
  3023. B.Entries[I].getAsBaseOrMember()) {
  3024. WasArrayIndex = false;
  3025. return I;
  3026. }
  3027. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  3028. // Next subobject is a field.
  3029. ObjType = FD->getType();
  3030. else
  3031. // Next subobject is a base class.
  3032. ObjType = QualType();
  3033. }
  3034. }
  3035. WasArrayIndex = false;
  3036. return I;
  3037. }
  3038. /// Determine whether the given subobject designators refer to elements of the
  3039. /// same array object.
  3040. static bool AreElementsOfSameArray(QualType ObjType,
  3041. const SubobjectDesignator &A,
  3042. const SubobjectDesignator &B) {
  3043. if (A.Entries.size() != B.Entries.size())
  3044. return false;
  3045. bool IsArray = A.MostDerivedIsArrayElement;
  3046. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  3047. // A is a subobject of the array element.
  3048. return false;
  3049. // If A (and B) designates an array element, the last entry will be the array
  3050. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  3051. // of length 1' case, and the entire path must match.
  3052. bool WasArrayIndex;
  3053. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  3054. return CommonLength >= A.Entries.size() - IsArray;
  3055. }
  3056. /// Find the complete object to which an LValue refers.
  3057. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  3058. AccessKinds AK, const LValue &LVal,
  3059. QualType LValType) {
  3060. if (LVal.InvalidBase) {
  3061. Info.FFDiag(E);
  3062. return CompleteObject();
  3063. }
  3064. if (!LVal.Base) {
  3065. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  3066. return CompleteObject();
  3067. }
  3068. CallStackFrame *Frame = nullptr;
  3069. unsigned Depth = 0;
  3070. if (LVal.getLValueCallIndex()) {
  3071. std::tie(Frame, Depth) =
  3072. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  3073. if (!Frame) {
  3074. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  3075. << AK << LVal.Base.is<const ValueDecl*>();
  3076. NoteLValueLocation(Info, LVal.Base);
  3077. return CompleteObject();
  3078. }
  3079. }
  3080. bool IsAccess = isAnyAccess(AK);
  3081. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3082. // is not a constant expression (even if the object is non-volatile). We also
  3083. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3084. // semantics.
  3085. if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
  3086. if (Info.getLangOpts().CPlusPlus)
  3087. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3088. << AK << LValType;
  3089. else
  3090. Info.FFDiag(E);
  3091. return CompleteObject();
  3092. }
  3093. // Compute value storage location and type of base object.
  3094. APValue *BaseVal = nullptr;
  3095. QualType BaseType = getType(LVal.Base);
  3096. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  3097. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3098. // In C++11, constexpr, non-volatile variables initialized with constant
  3099. // expressions are constant expressions too. Inside constexpr functions,
  3100. // parameters are constant expressions even if they're non-const.
  3101. // In C++1y, objects local to a constant expression (those with a Frame) are
  3102. // both readable and writable inside constant expressions.
  3103. // In C, such things can also be folded, although they are not ICEs.
  3104. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3105. if (VD) {
  3106. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3107. VD = VDef;
  3108. }
  3109. if (!VD || VD->isInvalidDecl()) {
  3110. Info.FFDiag(E);
  3111. return CompleteObject();
  3112. }
  3113. // Unless we're looking at a local variable or argument in a constexpr call,
  3114. // the variable we're reading must be const.
  3115. if (!Frame) {
  3116. if (Info.getLangOpts().CPlusPlus14 &&
  3117. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3118. // OK, we can read and modify an object if we're in the process of
  3119. // evaluating its initializer, because its lifetime began in this
  3120. // evaluation.
  3121. } else if (isModification(AK)) {
  3122. // All the remaining cases do not permit modification of the object.
  3123. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3124. return CompleteObject();
  3125. } else if (VD->isConstexpr()) {
  3126. // OK, we can read this variable.
  3127. } else if (BaseType->isIntegralOrEnumerationType()) {
  3128. // In OpenCL if a variable is in constant address space it is a const
  3129. // value.
  3130. if (!(BaseType.isConstQualified() ||
  3131. (Info.getLangOpts().OpenCL &&
  3132. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3133. if (!IsAccess)
  3134. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3135. if (Info.getLangOpts().CPlusPlus) {
  3136. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3137. Info.Note(VD->getLocation(), diag::note_declared_at);
  3138. } else {
  3139. Info.FFDiag(E);
  3140. }
  3141. return CompleteObject();
  3142. }
  3143. } else if (!IsAccess) {
  3144. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3145. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3146. // We support folding of const floating-point types, in order to make
  3147. // static const data members of such types (supported as an extension)
  3148. // more useful.
  3149. if (Info.getLangOpts().CPlusPlus11) {
  3150. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3151. Info.Note(VD->getLocation(), diag::note_declared_at);
  3152. } else {
  3153. Info.CCEDiag(E);
  3154. }
  3155. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3156. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3157. // Keep evaluating to see what we can do.
  3158. } else {
  3159. // FIXME: Allow folding of values of any literal type in all languages.
  3160. if (Info.checkingPotentialConstantExpression() &&
  3161. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3162. // The definition of this variable could be constexpr. We can't
  3163. // access it right now, but may be able to in future.
  3164. } else if (Info.getLangOpts().CPlusPlus11) {
  3165. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3166. Info.Note(VD->getLocation(), diag::note_declared_at);
  3167. } else {
  3168. Info.FFDiag(E);
  3169. }
  3170. return CompleteObject();
  3171. }
  3172. }
  3173. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3174. return CompleteObject();
  3175. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3176. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  3177. if (!Alloc) {
  3178. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3179. return CompleteObject();
  3180. }
  3181. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3182. LVal.Base.getDynamicAllocType());
  3183. } else {
  3184. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3185. if (!Frame) {
  3186. if (const MaterializeTemporaryExpr *MTE =
  3187. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3188. assert(MTE->getStorageDuration() == SD_Static &&
  3189. "should have a frame for a non-global materialized temporary");
  3190. // Per C++1y [expr.const]p2:
  3191. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3192. // - a [...] glvalue of integral or enumeration type that refers to
  3193. // a non-volatile const object [...]
  3194. // [...]
  3195. // - a [...] glvalue of literal type that refers to a non-volatile
  3196. // object whose lifetime began within the evaluation of e.
  3197. //
  3198. // C++11 misses the 'began within the evaluation of e' check and
  3199. // instead allows all temporaries, including things like:
  3200. // int &&r = 1;
  3201. // int x = ++r;
  3202. // constexpr int k = r;
  3203. // Therefore we use the C++14 rules in C++11 too.
  3204. //
  3205. // Note that temporaries whose lifetimes began while evaluating a
  3206. // variable's constructor are not usable while evaluating the
  3207. // corresponding destructor, not even if they're of const-qualified
  3208. // types.
  3209. if (!(BaseType.isConstQualified() &&
  3210. BaseType->isIntegralOrEnumerationType()) &&
  3211. !lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3212. if (!IsAccess)
  3213. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3214. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3215. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3216. return CompleteObject();
  3217. }
  3218. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3219. assert(BaseVal && "got reference to unevaluated temporary");
  3220. } else {
  3221. if (!IsAccess)
  3222. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3223. APValue Val;
  3224. LVal.moveInto(Val);
  3225. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3226. << AK
  3227. << Val.getAsString(Info.Ctx,
  3228. Info.Ctx.getLValueReferenceType(LValType));
  3229. NoteLValueLocation(Info, LVal.Base);
  3230. return CompleteObject();
  3231. }
  3232. } else {
  3233. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3234. assert(BaseVal && "missing value for temporary");
  3235. }
  3236. }
  3237. // In C++14, we can't safely access any mutable state when we might be
  3238. // evaluating after an unmodeled side effect.
  3239. //
  3240. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3241. // to be read here (but take care with 'mutable' fields).
  3242. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3243. Info.EvalStatus.HasSideEffects) ||
  3244. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3245. return CompleteObject();
  3246. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3247. }
  3248. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3249. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3250. /// glvalue referred to by an entity of reference type.
  3251. ///
  3252. /// \param Info - Information about the ongoing evaluation.
  3253. /// \param Conv - The expression for which we are performing the conversion.
  3254. /// Used for diagnostics.
  3255. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3256. /// case of a non-class type).
  3257. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3258. /// \param RVal - The produced value will be placed here.
  3259. /// \param WantObjectRepresentation - If true, we're looking for the object
  3260. /// representation rather than the value, and in particular,
  3261. /// there is no requirement that the result be fully initialized.
  3262. static bool
  3263. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3264. const LValue &LVal, APValue &RVal,
  3265. bool WantObjectRepresentation = false) {
  3266. if (LVal.Designator.Invalid)
  3267. return false;
  3268. // Check for special cases where there is no existing APValue to look at.
  3269. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3270. AccessKinds AK =
  3271. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3272. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3273. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3274. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3275. // initializer until now for such expressions. Such an expression can't be
  3276. // an ICE in C, so this only matters for fold.
  3277. if (Type.isVolatileQualified()) {
  3278. Info.FFDiag(Conv);
  3279. return false;
  3280. }
  3281. APValue Lit;
  3282. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3283. return false;
  3284. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3285. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3286. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3287. // Special-case character extraction so we don't have to construct an
  3288. // APValue for the whole string.
  3289. assert(LVal.Designator.Entries.size() <= 1 &&
  3290. "Can only read characters from string literals");
  3291. if (LVal.Designator.Entries.empty()) {
  3292. // Fail for now for LValue to RValue conversion of an array.
  3293. // (This shouldn't show up in C/C++, but it could be triggered by a
  3294. // weird EvaluateAsRValue call from a tool.)
  3295. Info.FFDiag(Conv);
  3296. return false;
  3297. }
  3298. if (LVal.Designator.isOnePastTheEnd()) {
  3299. if (Info.getLangOpts().CPlusPlus11)
  3300. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3301. else
  3302. Info.FFDiag(Conv);
  3303. return false;
  3304. }
  3305. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3306. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3307. return true;
  3308. }
  3309. }
  3310. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3311. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3312. }
  3313. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3314. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3315. QualType LValType, APValue &Val) {
  3316. if (LVal.Designator.Invalid)
  3317. return false;
  3318. if (!Info.getLangOpts().CPlusPlus14) {
  3319. Info.FFDiag(E);
  3320. return false;
  3321. }
  3322. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3323. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3324. }
  3325. namespace {
  3326. struct CompoundAssignSubobjectHandler {
  3327. EvalInfo &Info;
  3328. const Expr *E;
  3329. QualType PromotedLHSType;
  3330. BinaryOperatorKind Opcode;
  3331. const APValue &RHS;
  3332. static const AccessKinds AccessKind = AK_Assign;
  3333. typedef bool result_type;
  3334. bool checkConst(QualType QT) {
  3335. // Assigning to a const object has undefined behavior.
  3336. if (QT.isConstQualified()) {
  3337. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3338. return false;
  3339. }
  3340. return true;
  3341. }
  3342. bool failed() { return false; }
  3343. bool found(APValue &Subobj, QualType SubobjType) {
  3344. switch (Subobj.getKind()) {
  3345. case APValue::Int:
  3346. return found(Subobj.getInt(), SubobjType);
  3347. case APValue::Float:
  3348. return found(Subobj.getFloat(), SubobjType);
  3349. case APValue::ComplexInt:
  3350. case APValue::ComplexFloat:
  3351. // FIXME: Implement complex compound assignment.
  3352. Info.FFDiag(E);
  3353. return false;
  3354. case APValue::LValue:
  3355. return foundPointer(Subobj, SubobjType);
  3356. default:
  3357. // FIXME: can this happen?
  3358. Info.FFDiag(E);
  3359. return false;
  3360. }
  3361. }
  3362. bool found(APSInt &Value, QualType SubobjType) {
  3363. if (!checkConst(SubobjType))
  3364. return false;
  3365. if (!SubobjType->isIntegerType()) {
  3366. // We don't support compound assignment on integer-cast-to-pointer
  3367. // values.
  3368. Info.FFDiag(E);
  3369. return false;
  3370. }
  3371. if (RHS.isInt()) {
  3372. APSInt LHS =
  3373. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3374. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3375. return false;
  3376. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3377. return true;
  3378. } else if (RHS.isFloat()) {
  3379. APFloat FValue(0.0);
  3380. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3381. FValue) &&
  3382. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3383. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3384. Value);
  3385. }
  3386. Info.FFDiag(E);
  3387. return false;
  3388. }
  3389. bool found(APFloat &Value, QualType SubobjType) {
  3390. return checkConst(SubobjType) &&
  3391. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3392. Value) &&
  3393. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3394. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3395. }
  3396. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3397. if (!checkConst(SubobjType))
  3398. return false;
  3399. QualType PointeeType;
  3400. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3401. PointeeType = PT->getPointeeType();
  3402. if (PointeeType.isNull() || !RHS.isInt() ||
  3403. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3404. Info.FFDiag(E);
  3405. return false;
  3406. }
  3407. APSInt Offset = RHS.getInt();
  3408. if (Opcode == BO_Sub)
  3409. negateAsSigned(Offset);
  3410. LValue LVal;
  3411. LVal.setFrom(Info.Ctx, Subobj);
  3412. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3413. return false;
  3414. LVal.moveInto(Subobj);
  3415. return true;
  3416. }
  3417. };
  3418. } // end anonymous namespace
  3419. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3420. /// Perform a compound assignment of LVal <op>= RVal.
  3421. static bool handleCompoundAssignment(
  3422. EvalInfo &Info, const Expr *E,
  3423. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3424. BinaryOperatorKind Opcode, const APValue &RVal) {
  3425. if (LVal.Designator.Invalid)
  3426. return false;
  3427. if (!Info.getLangOpts().CPlusPlus14) {
  3428. Info.FFDiag(E);
  3429. return false;
  3430. }
  3431. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3432. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3433. RVal };
  3434. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3435. }
  3436. namespace {
  3437. struct IncDecSubobjectHandler {
  3438. EvalInfo &Info;
  3439. const UnaryOperator *E;
  3440. AccessKinds AccessKind;
  3441. APValue *Old;
  3442. typedef bool result_type;
  3443. bool checkConst(QualType QT) {
  3444. // Assigning to a const object has undefined behavior.
  3445. if (QT.isConstQualified()) {
  3446. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3447. return false;
  3448. }
  3449. return true;
  3450. }
  3451. bool failed() { return false; }
  3452. bool found(APValue &Subobj, QualType SubobjType) {
  3453. // Stash the old value. Also clear Old, so we don't clobber it later
  3454. // if we're post-incrementing a complex.
  3455. if (Old) {
  3456. *Old = Subobj;
  3457. Old = nullptr;
  3458. }
  3459. switch (Subobj.getKind()) {
  3460. case APValue::Int:
  3461. return found(Subobj.getInt(), SubobjType);
  3462. case APValue::Float:
  3463. return found(Subobj.getFloat(), SubobjType);
  3464. case APValue::ComplexInt:
  3465. return found(Subobj.getComplexIntReal(),
  3466. SubobjType->castAs<ComplexType>()->getElementType()
  3467. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3468. case APValue::ComplexFloat:
  3469. return found(Subobj.getComplexFloatReal(),
  3470. SubobjType->castAs<ComplexType>()->getElementType()
  3471. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3472. case APValue::LValue:
  3473. return foundPointer(Subobj, SubobjType);
  3474. default:
  3475. // FIXME: can this happen?
  3476. Info.FFDiag(E);
  3477. return false;
  3478. }
  3479. }
  3480. bool found(APSInt &Value, QualType SubobjType) {
  3481. if (!checkConst(SubobjType))
  3482. return false;
  3483. if (!SubobjType->isIntegerType()) {
  3484. // We don't support increment / decrement on integer-cast-to-pointer
  3485. // values.
  3486. Info.FFDiag(E);
  3487. return false;
  3488. }
  3489. if (Old) *Old = APValue(Value);
  3490. // bool arithmetic promotes to int, and the conversion back to bool
  3491. // doesn't reduce mod 2^n, so special-case it.
  3492. if (SubobjType->isBooleanType()) {
  3493. if (AccessKind == AK_Increment)
  3494. Value = 1;
  3495. else
  3496. Value = !Value;
  3497. return true;
  3498. }
  3499. bool WasNegative = Value.isNegative();
  3500. if (AccessKind == AK_Increment) {
  3501. ++Value;
  3502. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3503. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3504. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3505. }
  3506. } else {
  3507. --Value;
  3508. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3509. unsigned BitWidth = Value.getBitWidth();
  3510. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3511. ActualValue.setBit(BitWidth);
  3512. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3513. }
  3514. }
  3515. return true;
  3516. }
  3517. bool found(APFloat &Value, QualType SubobjType) {
  3518. if (!checkConst(SubobjType))
  3519. return false;
  3520. if (Old) *Old = APValue(Value);
  3521. APFloat One(Value.getSemantics(), 1);
  3522. if (AccessKind == AK_Increment)
  3523. Value.add(One, APFloat::rmNearestTiesToEven);
  3524. else
  3525. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3526. return true;
  3527. }
  3528. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3529. if (!checkConst(SubobjType))
  3530. return false;
  3531. QualType PointeeType;
  3532. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3533. PointeeType = PT->getPointeeType();
  3534. else {
  3535. Info.FFDiag(E);
  3536. return false;
  3537. }
  3538. LValue LVal;
  3539. LVal.setFrom(Info.Ctx, Subobj);
  3540. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3541. AccessKind == AK_Increment ? 1 : -1))
  3542. return false;
  3543. LVal.moveInto(Subobj);
  3544. return true;
  3545. }
  3546. };
  3547. } // end anonymous namespace
  3548. /// Perform an increment or decrement on LVal.
  3549. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3550. QualType LValType, bool IsIncrement, APValue *Old) {
  3551. if (LVal.Designator.Invalid)
  3552. return false;
  3553. if (!Info.getLangOpts().CPlusPlus14) {
  3554. Info.FFDiag(E);
  3555. return false;
  3556. }
  3557. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3558. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3559. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3560. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3561. }
  3562. /// Build an lvalue for the object argument of a member function call.
  3563. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3564. LValue &This) {
  3565. if (Object->getType()->isPointerType() && Object->isRValue())
  3566. return EvaluatePointer(Object, This, Info);
  3567. if (Object->isGLValue())
  3568. return EvaluateLValue(Object, This, Info);
  3569. if (Object->getType()->isLiteralType(Info.Ctx))
  3570. return EvaluateTemporary(Object, This, Info);
  3571. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3572. return false;
  3573. }
  3574. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3575. /// lvalue referring to the result.
  3576. ///
  3577. /// \param Info - Information about the ongoing evaluation.
  3578. /// \param LV - An lvalue referring to the base of the member pointer.
  3579. /// \param RHS - The member pointer expression.
  3580. /// \param IncludeMember - Specifies whether the member itself is included in
  3581. /// the resulting LValue subobject designator. This is not possible when
  3582. /// creating a bound member function.
  3583. /// \return The field or method declaration to which the member pointer refers,
  3584. /// or 0 if evaluation fails.
  3585. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3586. QualType LVType,
  3587. LValue &LV,
  3588. const Expr *RHS,
  3589. bool IncludeMember = true) {
  3590. MemberPtr MemPtr;
  3591. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3592. return nullptr;
  3593. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3594. // member value, the behavior is undefined.
  3595. if (!MemPtr.getDecl()) {
  3596. // FIXME: Specific diagnostic.
  3597. Info.FFDiag(RHS);
  3598. return nullptr;
  3599. }
  3600. if (MemPtr.isDerivedMember()) {
  3601. // This is a member of some derived class. Truncate LV appropriately.
  3602. // The end of the derived-to-base path for the base object must match the
  3603. // derived-to-base path for the member pointer.
  3604. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3605. LV.Designator.Entries.size()) {
  3606. Info.FFDiag(RHS);
  3607. return nullptr;
  3608. }
  3609. unsigned PathLengthToMember =
  3610. LV.Designator.Entries.size() - MemPtr.Path.size();
  3611. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3612. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3613. LV.Designator.Entries[PathLengthToMember + I]);
  3614. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3615. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3616. Info.FFDiag(RHS);
  3617. return nullptr;
  3618. }
  3619. }
  3620. // Truncate the lvalue to the appropriate derived class.
  3621. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3622. PathLengthToMember))
  3623. return nullptr;
  3624. } else if (!MemPtr.Path.empty()) {
  3625. // Extend the LValue path with the member pointer's path.
  3626. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3627. MemPtr.Path.size() + IncludeMember);
  3628. // Walk down to the appropriate base class.
  3629. if (const PointerType *PT = LVType->getAs<PointerType>())
  3630. LVType = PT->getPointeeType();
  3631. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3632. assert(RD && "member pointer access on non-class-type expression");
  3633. // The first class in the path is that of the lvalue.
  3634. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3635. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3636. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3637. return nullptr;
  3638. RD = Base;
  3639. }
  3640. // Finally cast to the class containing the member.
  3641. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3642. MemPtr.getContainingRecord()))
  3643. return nullptr;
  3644. }
  3645. // Add the member. Note that we cannot build bound member functions here.
  3646. if (IncludeMember) {
  3647. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3648. if (!HandleLValueMember(Info, RHS, LV, FD))
  3649. return nullptr;
  3650. } else if (const IndirectFieldDecl *IFD =
  3651. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3652. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3653. return nullptr;
  3654. } else {
  3655. llvm_unreachable("can't construct reference to bound member function");
  3656. }
  3657. }
  3658. return MemPtr.getDecl();
  3659. }
  3660. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3661. const BinaryOperator *BO,
  3662. LValue &LV,
  3663. bool IncludeMember = true) {
  3664. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3665. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3666. if (Info.noteFailure()) {
  3667. MemberPtr MemPtr;
  3668. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3669. }
  3670. return nullptr;
  3671. }
  3672. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3673. BO->getRHS(), IncludeMember);
  3674. }
  3675. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3676. /// the provided lvalue, which currently refers to the base object.
  3677. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3678. LValue &Result) {
  3679. SubobjectDesignator &D = Result.Designator;
  3680. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3681. return false;
  3682. QualType TargetQT = E->getType();
  3683. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3684. TargetQT = PT->getPointeeType();
  3685. // Check this cast lands within the final derived-to-base subobject path.
  3686. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3687. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3688. << D.MostDerivedType << TargetQT;
  3689. return false;
  3690. }
  3691. // Check the type of the final cast. We don't need to check the path,
  3692. // since a cast can only be formed if the path is unique.
  3693. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3694. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3695. const CXXRecordDecl *FinalType;
  3696. if (NewEntriesSize == D.MostDerivedPathLength)
  3697. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3698. else
  3699. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3700. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3701. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3702. << D.MostDerivedType << TargetQT;
  3703. return false;
  3704. }
  3705. // Truncate the lvalue to the appropriate derived class.
  3706. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3707. }
  3708. /// Get the value to use for a default-initialized object of type T.
  3709. static APValue getDefaultInitValue(QualType T) {
  3710. if (auto *RD = T->getAsCXXRecordDecl()) {
  3711. if (RD->isUnion())
  3712. return APValue((const FieldDecl*)nullptr);
  3713. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  3714. std::distance(RD->field_begin(), RD->field_end()));
  3715. unsigned Index = 0;
  3716. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3717. End = RD->bases_end(); I != End; ++I, ++Index)
  3718. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  3719. for (const auto *I : RD->fields()) {
  3720. if (I->isUnnamedBitfield())
  3721. continue;
  3722. Struct.getStructField(I->getFieldIndex()) =
  3723. getDefaultInitValue(I->getType());
  3724. }
  3725. return Struct;
  3726. }
  3727. if (auto *AT =
  3728. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  3729. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  3730. if (Array.hasArrayFiller())
  3731. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  3732. return Array;
  3733. }
  3734. return APValue::IndeterminateValue();
  3735. }
  3736. namespace {
  3737. enum EvalStmtResult {
  3738. /// Evaluation failed.
  3739. ESR_Failed,
  3740. /// Hit a 'return' statement.
  3741. ESR_Returned,
  3742. /// Evaluation succeeded.
  3743. ESR_Succeeded,
  3744. /// Hit a 'continue' statement.
  3745. ESR_Continue,
  3746. /// Hit a 'break' statement.
  3747. ESR_Break,
  3748. /// Still scanning for 'case' or 'default' statement.
  3749. ESR_CaseNotFound
  3750. };
  3751. }
  3752. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3753. // We don't need to evaluate the initializer for a static local.
  3754. if (!VD->hasLocalStorage())
  3755. return true;
  3756. LValue Result;
  3757. APValue &Val =
  3758. Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
  3759. const Expr *InitE = VD->getInit();
  3760. if (!InitE) {
  3761. Val = getDefaultInitValue(VD->getType());
  3762. return true;
  3763. }
  3764. if (InitE->isValueDependent())
  3765. return false;
  3766. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3767. // Wipe out any partially-computed value, to allow tracking that this
  3768. // evaluation failed.
  3769. Val = APValue();
  3770. return false;
  3771. }
  3772. return true;
  3773. }
  3774. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3775. bool OK = true;
  3776. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3777. OK &= EvaluateVarDecl(Info, VD);
  3778. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3779. for (auto *BD : DD->bindings())
  3780. if (auto *VD = BD->getHoldingVar())
  3781. OK &= EvaluateDecl(Info, VD);
  3782. return OK;
  3783. }
  3784. /// Evaluate a condition (either a variable declaration or an expression).
  3785. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3786. const Expr *Cond, bool &Result) {
  3787. FullExpressionRAII Scope(Info);
  3788. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3789. return false;
  3790. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  3791. return false;
  3792. return Scope.destroy();
  3793. }
  3794. namespace {
  3795. /// A location where the result (returned value) of evaluating a
  3796. /// statement should be stored.
  3797. struct StmtResult {
  3798. /// The APValue that should be filled in with the returned value.
  3799. APValue &Value;
  3800. /// The location containing the result, if any (used to support RVO).
  3801. const LValue *Slot;
  3802. };
  3803. struct TempVersionRAII {
  3804. CallStackFrame &Frame;
  3805. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3806. Frame.pushTempVersion();
  3807. }
  3808. ~TempVersionRAII() {
  3809. Frame.popTempVersion();
  3810. }
  3811. };
  3812. }
  3813. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3814. const Stmt *S,
  3815. const SwitchCase *SC = nullptr);
  3816. /// Evaluate the body of a loop, and translate the result as appropriate.
  3817. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3818. const Stmt *Body,
  3819. const SwitchCase *Case = nullptr) {
  3820. BlockScopeRAII Scope(Info);
  3821. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  3822. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3823. ESR = ESR_Failed;
  3824. switch (ESR) {
  3825. case ESR_Break:
  3826. return ESR_Succeeded;
  3827. case ESR_Succeeded:
  3828. case ESR_Continue:
  3829. return ESR_Continue;
  3830. case ESR_Failed:
  3831. case ESR_Returned:
  3832. case ESR_CaseNotFound:
  3833. return ESR;
  3834. }
  3835. llvm_unreachable("Invalid EvalStmtResult!");
  3836. }
  3837. /// Evaluate a switch statement.
  3838. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3839. const SwitchStmt *SS) {
  3840. BlockScopeRAII Scope(Info);
  3841. // Evaluate the switch condition.
  3842. APSInt Value;
  3843. {
  3844. if (const Stmt *Init = SS->getInit()) {
  3845. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3846. if (ESR != ESR_Succeeded) {
  3847. if (ESR != ESR_Failed && !Scope.destroy())
  3848. ESR = ESR_Failed;
  3849. return ESR;
  3850. }
  3851. }
  3852. FullExpressionRAII CondScope(Info);
  3853. if (SS->getConditionVariable() &&
  3854. !EvaluateDecl(Info, SS->getConditionVariable()))
  3855. return ESR_Failed;
  3856. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3857. return ESR_Failed;
  3858. if (!CondScope.destroy())
  3859. return ESR_Failed;
  3860. }
  3861. // Find the switch case corresponding to the value of the condition.
  3862. // FIXME: Cache this lookup.
  3863. const SwitchCase *Found = nullptr;
  3864. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3865. SC = SC->getNextSwitchCase()) {
  3866. if (isa<DefaultStmt>(SC)) {
  3867. Found = SC;
  3868. continue;
  3869. }
  3870. const CaseStmt *CS = cast<CaseStmt>(SC);
  3871. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3872. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3873. : LHS;
  3874. if (LHS <= Value && Value <= RHS) {
  3875. Found = SC;
  3876. break;
  3877. }
  3878. }
  3879. if (!Found)
  3880. return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
  3881. // Search the switch body for the switch case and evaluate it from there.
  3882. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  3883. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3884. return ESR_Failed;
  3885. switch (ESR) {
  3886. case ESR_Break:
  3887. return ESR_Succeeded;
  3888. case ESR_Succeeded:
  3889. case ESR_Continue:
  3890. case ESR_Failed:
  3891. case ESR_Returned:
  3892. return ESR;
  3893. case ESR_CaseNotFound:
  3894. // This can only happen if the switch case is nested within a statement
  3895. // expression. We have no intention of supporting that.
  3896. Info.FFDiag(Found->getBeginLoc(),
  3897. diag::note_constexpr_stmt_expr_unsupported);
  3898. return ESR_Failed;
  3899. }
  3900. llvm_unreachable("Invalid EvalStmtResult!");
  3901. }
  3902. // Evaluate a statement.
  3903. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3904. const Stmt *S, const SwitchCase *Case) {
  3905. if (!Info.nextStep(S))
  3906. return ESR_Failed;
  3907. // If we're hunting down a 'case' or 'default' label, recurse through
  3908. // substatements until we hit the label.
  3909. if (Case) {
  3910. switch (S->getStmtClass()) {
  3911. case Stmt::CompoundStmtClass:
  3912. // FIXME: Precompute which substatement of a compound statement we
  3913. // would jump to, and go straight there rather than performing a
  3914. // linear scan each time.
  3915. case Stmt::LabelStmtClass:
  3916. case Stmt::AttributedStmtClass:
  3917. case Stmt::DoStmtClass:
  3918. break;
  3919. case Stmt::CaseStmtClass:
  3920. case Stmt::DefaultStmtClass:
  3921. if (Case == S)
  3922. Case = nullptr;
  3923. break;
  3924. case Stmt::IfStmtClass: {
  3925. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3926. // straight there rather than scanning both sides.
  3927. const IfStmt *IS = cast<IfStmt>(S);
  3928. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3929. // preceded by our switch label.
  3930. BlockScopeRAII Scope(Info);
  3931. // Step into the init statement in case it brings an (uninitialized)
  3932. // variable into scope.
  3933. if (const Stmt *Init = IS->getInit()) {
  3934. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3935. if (ESR != ESR_CaseNotFound) {
  3936. assert(ESR != ESR_Succeeded);
  3937. return ESR;
  3938. }
  3939. }
  3940. // Condition variable must be initialized if it exists.
  3941. // FIXME: We can skip evaluating the body if there's a condition
  3942. // variable, as there can't be any case labels within it.
  3943. // (The same is true for 'for' statements.)
  3944. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3945. if (ESR == ESR_Failed)
  3946. return ESR;
  3947. if (ESR != ESR_CaseNotFound)
  3948. return Scope.destroy() ? ESR : ESR_Failed;
  3949. if (!IS->getElse())
  3950. return ESR_CaseNotFound;
  3951. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  3952. if (ESR == ESR_Failed)
  3953. return ESR;
  3954. if (ESR != ESR_CaseNotFound)
  3955. return Scope.destroy() ? ESR : ESR_Failed;
  3956. return ESR_CaseNotFound;
  3957. }
  3958. case Stmt::WhileStmtClass: {
  3959. EvalStmtResult ESR =
  3960. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3961. if (ESR != ESR_Continue)
  3962. return ESR;
  3963. break;
  3964. }
  3965. case Stmt::ForStmtClass: {
  3966. const ForStmt *FS = cast<ForStmt>(S);
  3967. BlockScopeRAII Scope(Info);
  3968. // Step into the init statement in case it brings an (uninitialized)
  3969. // variable into scope.
  3970. if (const Stmt *Init = FS->getInit()) {
  3971. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3972. if (ESR != ESR_CaseNotFound) {
  3973. assert(ESR != ESR_Succeeded);
  3974. return ESR;
  3975. }
  3976. }
  3977. EvalStmtResult ESR =
  3978. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3979. if (ESR != ESR_Continue)
  3980. return ESR;
  3981. if (FS->getInc()) {
  3982. FullExpressionRAII IncScope(Info);
  3983. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  3984. return ESR_Failed;
  3985. }
  3986. break;
  3987. }
  3988. case Stmt::DeclStmtClass: {
  3989. // Start the lifetime of any uninitialized variables we encounter. They
  3990. // might be used by the selected branch of the switch.
  3991. const DeclStmt *DS = cast<DeclStmt>(S);
  3992. for (const auto *D : DS->decls()) {
  3993. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3994. if (VD->hasLocalStorage() && !VD->getInit())
  3995. if (!EvaluateVarDecl(Info, VD))
  3996. return ESR_Failed;
  3997. // FIXME: If the variable has initialization that can't be jumped
  3998. // over, bail out of any immediately-surrounding compound-statement
  3999. // too. There can't be any case labels here.
  4000. }
  4001. }
  4002. return ESR_CaseNotFound;
  4003. }
  4004. default:
  4005. return ESR_CaseNotFound;
  4006. }
  4007. }
  4008. switch (S->getStmtClass()) {
  4009. default:
  4010. if (const Expr *E = dyn_cast<Expr>(S)) {
  4011. // Don't bother evaluating beyond an expression-statement which couldn't
  4012. // be evaluated.
  4013. // FIXME: Do we need the FullExpressionRAII object here?
  4014. // VisitExprWithCleanups should create one when necessary.
  4015. FullExpressionRAII Scope(Info);
  4016. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  4017. return ESR_Failed;
  4018. return ESR_Succeeded;
  4019. }
  4020. Info.FFDiag(S->getBeginLoc());
  4021. return ESR_Failed;
  4022. case Stmt::NullStmtClass:
  4023. return ESR_Succeeded;
  4024. case Stmt::DeclStmtClass: {
  4025. const DeclStmt *DS = cast<DeclStmt>(S);
  4026. for (const auto *D : DS->decls()) {
  4027. // Each declaration initialization is its own full-expression.
  4028. FullExpressionRAII Scope(Info);
  4029. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  4030. return ESR_Failed;
  4031. if (!Scope.destroy())
  4032. return ESR_Failed;
  4033. }
  4034. return ESR_Succeeded;
  4035. }
  4036. case Stmt::ReturnStmtClass: {
  4037. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  4038. FullExpressionRAII Scope(Info);
  4039. if (RetExpr &&
  4040. !(Result.Slot
  4041. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  4042. : Evaluate(Result.Value, Info, RetExpr)))
  4043. return ESR_Failed;
  4044. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  4045. }
  4046. case Stmt::CompoundStmtClass: {
  4047. BlockScopeRAII Scope(Info);
  4048. const CompoundStmt *CS = cast<CompoundStmt>(S);
  4049. for (const auto *BI : CS->body()) {
  4050. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  4051. if (ESR == ESR_Succeeded)
  4052. Case = nullptr;
  4053. else if (ESR != ESR_CaseNotFound) {
  4054. if (ESR != ESR_Failed && !Scope.destroy())
  4055. return ESR_Failed;
  4056. return ESR;
  4057. }
  4058. }
  4059. if (Case)
  4060. return ESR_CaseNotFound;
  4061. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4062. }
  4063. case Stmt::IfStmtClass: {
  4064. const IfStmt *IS = cast<IfStmt>(S);
  4065. // Evaluate the condition, as either a var decl or as an expression.
  4066. BlockScopeRAII Scope(Info);
  4067. if (const Stmt *Init = IS->getInit()) {
  4068. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4069. if (ESR != ESR_Succeeded) {
  4070. if (ESR != ESR_Failed && !Scope.destroy())
  4071. return ESR_Failed;
  4072. return ESR;
  4073. }
  4074. }
  4075. bool Cond;
  4076. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  4077. return ESR_Failed;
  4078. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  4079. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  4080. if (ESR != ESR_Succeeded) {
  4081. if (ESR != ESR_Failed && !Scope.destroy())
  4082. return ESR_Failed;
  4083. return ESR;
  4084. }
  4085. }
  4086. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4087. }
  4088. case Stmt::WhileStmtClass: {
  4089. const WhileStmt *WS = cast<WhileStmt>(S);
  4090. while (true) {
  4091. BlockScopeRAII Scope(Info);
  4092. bool Continue;
  4093. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4094. Continue))
  4095. return ESR_Failed;
  4096. if (!Continue)
  4097. break;
  4098. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4099. if (ESR != ESR_Continue) {
  4100. if (ESR != ESR_Failed && !Scope.destroy())
  4101. return ESR_Failed;
  4102. return ESR;
  4103. }
  4104. if (!Scope.destroy())
  4105. return ESR_Failed;
  4106. }
  4107. return ESR_Succeeded;
  4108. }
  4109. case Stmt::DoStmtClass: {
  4110. const DoStmt *DS = cast<DoStmt>(S);
  4111. bool Continue;
  4112. do {
  4113. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4114. if (ESR != ESR_Continue)
  4115. return ESR;
  4116. Case = nullptr;
  4117. FullExpressionRAII CondScope(Info);
  4118. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4119. !CondScope.destroy())
  4120. return ESR_Failed;
  4121. } while (Continue);
  4122. return ESR_Succeeded;
  4123. }
  4124. case Stmt::ForStmtClass: {
  4125. const ForStmt *FS = cast<ForStmt>(S);
  4126. BlockScopeRAII ForScope(Info);
  4127. if (FS->getInit()) {
  4128. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4129. if (ESR != ESR_Succeeded) {
  4130. if (ESR != ESR_Failed && !ForScope.destroy())
  4131. return ESR_Failed;
  4132. return ESR;
  4133. }
  4134. }
  4135. while (true) {
  4136. BlockScopeRAII IterScope(Info);
  4137. bool Continue = true;
  4138. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4139. FS->getCond(), Continue))
  4140. return ESR_Failed;
  4141. if (!Continue)
  4142. break;
  4143. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4144. if (ESR != ESR_Continue) {
  4145. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4146. return ESR_Failed;
  4147. return ESR;
  4148. }
  4149. if (FS->getInc()) {
  4150. FullExpressionRAII IncScope(Info);
  4151. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  4152. return ESR_Failed;
  4153. }
  4154. if (!IterScope.destroy())
  4155. return ESR_Failed;
  4156. }
  4157. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4158. }
  4159. case Stmt::CXXForRangeStmtClass: {
  4160. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4161. BlockScopeRAII Scope(Info);
  4162. // Evaluate the init-statement if present.
  4163. if (FS->getInit()) {
  4164. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4165. if (ESR != ESR_Succeeded) {
  4166. if (ESR != ESR_Failed && !Scope.destroy())
  4167. return ESR_Failed;
  4168. return ESR;
  4169. }
  4170. }
  4171. // Initialize the __range variable.
  4172. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4173. if (ESR != ESR_Succeeded) {
  4174. if (ESR != ESR_Failed && !Scope.destroy())
  4175. return ESR_Failed;
  4176. return ESR;
  4177. }
  4178. // Create the __begin and __end iterators.
  4179. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4180. if (ESR != ESR_Succeeded) {
  4181. if (ESR != ESR_Failed && !Scope.destroy())
  4182. return ESR_Failed;
  4183. return ESR;
  4184. }
  4185. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4186. if (ESR != ESR_Succeeded) {
  4187. if (ESR != ESR_Failed && !Scope.destroy())
  4188. return ESR_Failed;
  4189. return ESR;
  4190. }
  4191. while (true) {
  4192. // Condition: __begin != __end.
  4193. {
  4194. bool Continue = true;
  4195. FullExpressionRAII CondExpr(Info);
  4196. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4197. return ESR_Failed;
  4198. if (!Continue)
  4199. break;
  4200. }
  4201. // User's variable declaration, initialized by *__begin.
  4202. BlockScopeRAII InnerScope(Info);
  4203. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4204. if (ESR != ESR_Succeeded) {
  4205. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4206. return ESR_Failed;
  4207. return ESR;
  4208. }
  4209. // Loop body.
  4210. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4211. if (ESR != ESR_Continue) {
  4212. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4213. return ESR_Failed;
  4214. return ESR;
  4215. }
  4216. // Increment: ++__begin
  4217. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4218. return ESR_Failed;
  4219. if (!InnerScope.destroy())
  4220. return ESR_Failed;
  4221. }
  4222. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4223. }
  4224. case Stmt::SwitchStmtClass:
  4225. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4226. case Stmt::ContinueStmtClass:
  4227. return ESR_Continue;
  4228. case Stmt::BreakStmtClass:
  4229. return ESR_Break;
  4230. case Stmt::LabelStmtClass:
  4231. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4232. case Stmt::AttributedStmtClass:
  4233. // As a general principle, C++11 attributes can be ignored without
  4234. // any semantic impact.
  4235. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4236. Case);
  4237. case Stmt::CaseStmtClass:
  4238. case Stmt::DefaultStmtClass:
  4239. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4240. case Stmt::CXXTryStmtClass:
  4241. // Evaluate try blocks by evaluating all sub statements.
  4242. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4243. }
  4244. }
  4245. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4246. /// default constructor. If so, we'll fold it whether or not it's marked as
  4247. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4248. /// so we need special handling.
  4249. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4250. const CXXConstructorDecl *CD,
  4251. bool IsValueInitialization) {
  4252. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4253. return false;
  4254. // Value-initialization does not call a trivial default constructor, so such a
  4255. // call is a core constant expression whether or not the constructor is
  4256. // constexpr.
  4257. if (!CD->isConstexpr() && !IsValueInitialization) {
  4258. if (Info.getLangOpts().CPlusPlus11) {
  4259. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4260. // we should be much more explicit about why it's not constexpr.
  4261. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4262. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4263. Info.Note(CD->getLocation(), diag::note_declared_at);
  4264. } else {
  4265. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4266. }
  4267. }
  4268. return true;
  4269. }
  4270. /// CheckConstexprFunction - Check that a function can be called in a constant
  4271. /// expression.
  4272. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4273. const FunctionDecl *Declaration,
  4274. const FunctionDecl *Definition,
  4275. const Stmt *Body) {
  4276. // Potential constant expressions can contain calls to declared, but not yet
  4277. // defined, constexpr functions.
  4278. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4279. Declaration->isConstexpr())
  4280. return false;
  4281. // Bail out if the function declaration itself is invalid. We will
  4282. // have produced a relevant diagnostic while parsing it, so just
  4283. // note the problematic sub-expression.
  4284. if (Declaration->isInvalidDecl()) {
  4285. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4286. return false;
  4287. }
  4288. // DR1872: An instantiated virtual constexpr function can't be called in a
  4289. // constant expression (prior to C++20). We can still constant-fold such a
  4290. // call.
  4291. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4292. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4293. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4294. if (Definition && Definition->isInvalidDecl()) {
  4295. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4296. return false;
  4297. }
  4298. // Can we evaluate this function call?
  4299. if (Definition && Definition->isConstexpr() && Body)
  4300. return true;
  4301. if (Info.getLangOpts().CPlusPlus11) {
  4302. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4303. // If this function is not constexpr because it is an inherited
  4304. // non-constexpr constructor, diagnose that directly.
  4305. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4306. if (CD && CD->isInheritingConstructor()) {
  4307. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4308. if (!Inherited->isConstexpr())
  4309. DiagDecl = CD = Inherited;
  4310. }
  4311. // FIXME: If DiagDecl is an implicitly-declared special member function
  4312. // or an inheriting constructor, we should be much more explicit about why
  4313. // it's not constexpr.
  4314. if (CD && CD->isInheritingConstructor())
  4315. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4316. << CD->getInheritedConstructor().getConstructor()->getParent();
  4317. else
  4318. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4319. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4320. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4321. } else {
  4322. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4323. }
  4324. return false;
  4325. }
  4326. namespace {
  4327. struct CheckDynamicTypeHandler {
  4328. AccessKinds AccessKind;
  4329. typedef bool result_type;
  4330. bool failed() { return false; }
  4331. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4332. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4333. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4334. };
  4335. } // end anonymous namespace
  4336. /// Check that we can access the notional vptr of an object / determine its
  4337. /// dynamic type.
  4338. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4339. AccessKinds AK, bool Polymorphic) {
  4340. if (This.Designator.Invalid)
  4341. return false;
  4342. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4343. if (!Obj)
  4344. return false;
  4345. if (!Obj.Value) {
  4346. // The object is not usable in constant expressions, so we can't inspect
  4347. // its value to see if it's in-lifetime or what the active union members
  4348. // are. We can still check for a one-past-the-end lvalue.
  4349. if (This.Designator.isOnePastTheEnd() ||
  4350. This.Designator.isMostDerivedAnUnsizedArray()) {
  4351. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4352. ? diag::note_constexpr_access_past_end
  4353. : diag::note_constexpr_access_unsized_array)
  4354. << AK;
  4355. return false;
  4356. } else if (Polymorphic) {
  4357. // Conservatively refuse to perform a polymorphic operation if we would
  4358. // not be able to read a notional 'vptr' value.
  4359. APValue Val;
  4360. This.moveInto(Val);
  4361. QualType StarThisType =
  4362. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4363. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4364. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4365. return false;
  4366. }
  4367. return true;
  4368. }
  4369. CheckDynamicTypeHandler Handler{AK};
  4370. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4371. }
  4372. /// Check that the pointee of the 'this' pointer in a member function call is
  4373. /// either within its lifetime or in its period of construction or destruction.
  4374. static bool
  4375. checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4376. const LValue &This,
  4377. const CXXMethodDecl *NamedMember) {
  4378. return checkDynamicType(
  4379. Info, E, This,
  4380. isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
  4381. }
  4382. struct DynamicType {
  4383. /// The dynamic class type of the object.
  4384. const CXXRecordDecl *Type;
  4385. /// The corresponding path length in the lvalue.
  4386. unsigned PathLength;
  4387. };
  4388. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4389. unsigned PathLength) {
  4390. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4391. Designator.Entries.size() && "invalid path length");
  4392. return (PathLength == Designator.MostDerivedPathLength)
  4393. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4394. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4395. }
  4396. /// Determine the dynamic type of an object.
  4397. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4398. LValue &This, AccessKinds AK) {
  4399. // If we don't have an lvalue denoting an object of class type, there is no
  4400. // meaningful dynamic type. (We consider objects of non-class type to have no
  4401. // dynamic type.)
  4402. if (!checkDynamicType(Info, E, This, AK, true))
  4403. return None;
  4404. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4405. // shouldn't happen other than in constant-folding situations, since literal
  4406. // types can't have virtual bases.
  4407. //
  4408. // Note that consumers of DynamicType assume that the type has no virtual
  4409. // bases, and will need modifications if this restriction is relaxed.
  4410. const CXXRecordDecl *Class =
  4411. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4412. if (!Class || Class->getNumVBases()) {
  4413. Info.FFDiag(E);
  4414. return None;
  4415. }
  4416. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4417. // binary search here instead. But the overwhelmingly common case is that
  4418. // we're not in the middle of a constructor, so it probably doesn't matter
  4419. // in practice.
  4420. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4421. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4422. PathLength <= Path.size(); ++PathLength) {
  4423. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  4424. Path.slice(0, PathLength))) {
  4425. case ConstructionPhase::Bases:
  4426. case ConstructionPhase::DestroyingBases:
  4427. // We're constructing or destroying a base class. This is not the dynamic
  4428. // type.
  4429. break;
  4430. case ConstructionPhase::None:
  4431. case ConstructionPhase::AfterBases:
  4432. case ConstructionPhase::Destroying:
  4433. // We've finished constructing the base classes and not yet started
  4434. // destroying them again, so this is the dynamic type.
  4435. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4436. PathLength};
  4437. }
  4438. }
  4439. // CWG issue 1517: we're constructing a base class of the object described by
  4440. // 'This', so that object has not yet begun its period of construction and
  4441. // any polymorphic operation on it results in undefined behavior.
  4442. Info.FFDiag(E);
  4443. return None;
  4444. }
  4445. /// Perform virtual dispatch.
  4446. static const CXXMethodDecl *HandleVirtualDispatch(
  4447. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4448. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4449. Optional<DynamicType> DynType = ComputeDynamicType(
  4450. Info, E, This,
  4451. isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
  4452. if (!DynType)
  4453. return nullptr;
  4454. // Find the final overrider. It must be declared in one of the classes on the
  4455. // path from the dynamic type to the static type.
  4456. // FIXME: If we ever allow literal types to have virtual base classes, that
  4457. // won't be true.
  4458. const CXXMethodDecl *Callee = Found;
  4459. unsigned PathLength = DynType->PathLength;
  4460. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4461. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4462. const CXXMethodDecl *Overrider =
  4463. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4464. if (Overrider) {
  4465. Callee = Overrider;
  4466. break;
  4467. }
  4468. }
  4469. // C++2a [class.abstract]p6:
  4470. // the effect of making a virtual call to a pure virtual function [...] is
  4471. // undefined
  4472. if (Callee->isPure()) {
  4473. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4474. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4475. return nullptr;
  4476. }
  4477. // If necessary, walk the rest of the path to determine the sequence of
  4478. // covariant adjustment steps to apply.
  4479. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4480. Found->getReturnType())) {
  4481. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4482. for (unsigned CovariantPathLength = PathLength + 1;
  4483. CovariantPathLength != This.Designator.Entries.size();
  4484. ++CovariantPathLength) {
  4485. const CXXRecordDecl *NextClass =
  4486. getBaseClassType(This.Designator, CovariantPathLength);
  4487. const CXXMethodDecl *Next =
  4488. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4489. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4490. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4491. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4492. }
  4493. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4494. CovariantAdjustmentPath.back()))
  4495. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4496. }
  4497. // Perform 'this' adjustment.
  4498. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4499. return nullptr;
  4500. return Callee;
  4501. }
  4502. /// Perform the adjustment from a value returned by a virtual function to
  4503. /// a value of the statically expected type, which may be a pointer or
  4504. /// reference to a base class of the returned type.
  4505. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4506. APValue &Result,
  4507. ArrayRef<QualType> Path) {
  4508. assert(Result.isLValue() &&
  4509. "unexpected kind of APValue for covariant return");
  4510. if (Result.isNullPointer())
  4511. return true;
  4512. LValue LVal;
  4513. LVal.setFrom(Info.Ctx, Result);
  4514. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4515. for (unsigned I = 1; I != Path.size(); ++I) {
  4516. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4517. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4518. if (OldClass != NewClass &&
  4519. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4520. return false;
  4521. OldClass = NewClass;
  4522. }
  4523. LVal.moveInto(Result);
  4524. return true;
  4525. }
  4526. /// Determine whether \p Base, which is known to be a direct base class of
  4527. /// \p Derived, is a public base class.
  4528. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4529. const CXXRecordDecl *Base) {
  4530. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4531. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4532. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4533. return BaseSpec.getAccessSpecifier() == AS_public;
  4534. }
  4535. llvm_unreachable("Base is not a direct base of Derived");
  4536. }
  4537. /// Apply the given dynamic cast operation on the provided lvalue.
  4538. ///
  4539. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4540. /// to find a suitable target subobject.
  4541. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4542. LValue &Ptr) {
  4543. // We can't do anything with a non-symbolic pointer value.
  4544. SubobjectDesignator &D = Ptr.Designator;
  4545. if (D.Invalid)
  4546. return false;
  4547. // C++ [expr.dynamic.cast]p6:
  4548. // If v is a null pointer value, the result is a null pointer value.
  4549. if (Ptr.isNullPointer() && !E->isGLValue())
  4550. return true;
  4551. // For all the other cases, we need the pointer to point to an object within
  4552. // its lifetime / period of construction / destruction, and we need to know
  4553. // its dynamic type.
  4554. Optional<DynamicType> DynType =
  4555. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4556. if (!DynType)
  4557. return false;
  4558. // C++ [expr.dynamic.cast]p7:
  4559. // If T is "pointer to cv void", then the result is a pointer to the most
  4560. // derived object
  4561. if (E->getType()->isVoidPointerType())
  4562. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4563. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4564. assert(C && "dynamic_cast target is not void pointer nor class");
  4565. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4566. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4567. // C++ [expr.dynamic.cast]p9:
  4568. if (!E->isGLValue()) {
  4569. // The value of a failed cast to pointer type is the null pointer value
  4570. // of the required result type.
  4571. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4572. Ptr.setNull(E->getType(), TargetVal);
  4573. return true;
  4574. }
  4575. // A failed cast to reference type throws [...] std::bad_cast.
  4576. unsigned DiagKind;
  4577. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4578. DynType->Type->isDerivedFrom(C)))
  4579. DiagKind = 0;
  4580. else if (!Paths || Paths->begin() == Paths->end())
  4581. DiagKind = 1;
  4582. else if (Paths->isAmbiguous(CQT))
  4583. DiagKind = 2;
  4584. else {
  4585. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4586. DiagKind = 3;
  4587. }
  4588. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4589. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4590. << Info.Ctx.getRecordType(DynType->Type)
  4591. << E->getType().getUnqualifiedType();
  4592. return false;
  4593. };
  4594. // Runtime check, phase 1:
  4595. // Walk from the base subobject towards the derived object looking for the
  4596. // target type.
  4597. for (int PathLength = Ptr.Designator.Entries.size();
  4598. PathLength >= (int)DynType->PathLength; --PathLength) {
  4599. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4600. if (declaresSameEntity(Class, C))
  4601. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4602. // We can only walk across public inheritance edges.
  4603. if (PathLength > (int)DynType->PathLength &&
  4604. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4605. Class))
  4606. return RuntimeCheckFailed(nullptr);
  4607. }
  4608. // Runtime check, phase 2:
  4609. // Search the dynamic type for an unambiguous public base of type C.
  4610. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4611. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4612. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4613. Paths.front().Access == AS_public) {
  4614. // Downcast to the dynamic type...
  4615. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4616. return false;
  4617. // ... then upcast to the chosen base class subobject.
  4618. for (CXXBasePathElement &Elem : Paths.front())
  4619. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4620. return false;
  4621. return true;
  4622. }
  4623. // Otherwise, the runtime check fails.
  4624. return RuntimeCheckFailed(&Paths);
  4625. }
  4626. namespace {
  4627. struct StartLifetimeOfUnionMemberHandler {
  4628. const FieldDecl *Field;
  4629. static const AccessKinds AccessKind = AK_Assign;
  4630. typedef bool result_type;
  4631. bool failed() { return false; }
  4632. bool found(APValue &Subobj, QualType SubobjType) {
  4633. // We are supposed to perform no initialization but begin the lifetime of
  4634. // the object. We interpret that as meaning to do what default
  4635. // initialization of the object would do if all constructors involved were
  4636. // trivial:
  4637. // * All base, non-variant member, and array element subobjects' lifetimes
  4638. // begin
  4639. // * No variant members' lifetimes begin
  4640. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4641. assert(SubobjType->isUnionType());
  4642. if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
  4643. !Subobj.getUnionValue().hasValue())
  4644. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4645. return true;
  4646. }
  4647. bool found(APSInt &Value, QualType SubobjType) {
  4648. llvm_unreachable("wrong value kind for union object");
  4649. }
  4650. bool found(APFloat &Value, QualType SubobjType) {
  4651. llvm_unreachable("wrong value kind for union object");
  4652. }
  4653. };
  4654. } // end anonymous namespace
  4655. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4656. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4657. /// operator whose left-hand side might involve a union member access. If it
  4658. /// does, implicitly start the lifetime of any accessed union elements per
  4659. /// C++20 [class.union]5.
  4660. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4661. const LValue &LHS) {
  4662. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4663. return false;
  4664. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4665. // C++ [class.union]p5:
  4666. // define the set S(E) of subexpressions of E as follows:
  4667. unsigned PathLength = LHS.Designator.Entries.size();
  4668. for (const Expr *E = LHSExpr; E != nullptr;) {
  4669. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4670. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4671. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4672. // Note that we can't implicitly start the lifetime of a reference,
  4673. // so we don't need to proceed any further if we reach one.
  4674. if (!FD || FD->getType()->isReferenceType())
  4675. break;
  4676. // ... and also contains A.B if B names a union member
  4677. if (FD->getParent()->isUnion())
  4678. UnionPathLengths.push_back({PathLength - 1, FD});
  4679. E = ME->getBase();
  4680. --PathLength;
  4681. assert(declaresSameEntity(FD,
  4682. LHS.Designator.Entries[PathLength]
  4683. .getAsBaseOrMember().getPointer()));
  4684. // -- If E is of the form A[B] and is interpreted as a built-in array
  4685. // subscripting operator, S(E) is [S(the array operand, if any)].
  4686. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4687. // Step over an ArrayToPointerDecay implicit cast.
  4688. auto *Base = ASE->getBase()->IgnoreImplicit();
  4689. if (!Base->getType()->isArrayType())
  4690. break;
  4691. E = Base;
  4692. --PathLength;
  4693. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4694. // Step over a derived-to-base conversion.
  4695. E = ICE->getSubExpr();
  4696. if (ICE->getCastKind() == CK_NoOp)
  4697. continue;
  4698. if (ICE->getCastKind() != CK_DerivedToBase &&
  4699. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4700. break;
  4701. // Walk path backwards as we walk up from the base to the derived class.
  4702. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4703. --PathLength;
  4704. (void)Elt;
  4705. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4706. LHS.Designator.Entries[PathLength]
  4707. .getAsBaseOrMember().getPointer()));
  4708. }
  4709. // -- Otherwise, S(E) is empty.
  4710. } else {
  4711. break;
  4712. }
  4713. }
  4714. // Common case: no unions' lifetimes are started.
  4715. if (UnionPathLengths.empty())
  4716. return true;
  4717. // if modification of X [would access an inactive union member], an object
  4718. // of the type of X is implicitly created
  4719. CompleteObject Obj =
  4720. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4721. if (!Obj)
  4722. return false;
  4723. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4724. llvm::reverse(UnionPathLengths)) {
  4725. // Form a designator for the union object.
  4726. SubobjectDesignator D = LHS.Designator;
  4727. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4728. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4729. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4730. return false;
  4731. }
  4732. return true;
  4733. }
  4734. /// Determine if a class has any fields that might need to be copied by a
  4735. /// trivial copy or move operation.
  4736. static bool hasFields(const CXXRecordDecl *RD) {
  4737. if (!RD || RD->isEmpty())
  4738. return false;
  4739. for (auto *FD : RD->fields()) {
  4740. if (FD->isUnnamedBitfield())
  4741. continue;
  4742. return true;
  4743. }
  4744. for (auto &Base : RD->bases())
  4745. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4746. return true;
  4747. return false;
  4748. }
  4749. namespace {
  4750. typedef SmallVector<APValue, 8> ArgVector;
  4751. }
  4752. /// EvaluateArgs - Evaluate the arguments to a function call.
  4753. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4754. EvalInfo &Info, const FunctionDecl *Callee) {
  4755. bool Success = true;
  4756. llvm::SmallBitVector ForbiddenNullArgs;
  4757. if (Callee->hasAttr<NonNullAttr>()) {
  4758. ForbiddenNullArgs.resize(Args.size());
  4759. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4760. if (!Attr->args_size()) {
  4761. ForbiddenNullArgs.set();
  4762. break;
  4763. } else
  4764. for (auto Idx : Attr->args()) {
  4765. unsigned ASTIdx = Idx.getASTIndex();
  4766. if (ASTIdx >= Args.size())
  4767. continue;
  4768. ForbiddenNullArgs[ASTIdx] = 1;
  4769. }
  4770. }
  4771. }
  4772. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4773. I != E; ++I) {
  4774. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4775. // If we're checking for a potential constant expression, evaluate all
  4776. // initializers even if some of them fail.
  4777. if (!Info.noteFailure())
  4778. return false;
  4779. Success = false;
  4780. } else if (!ForbiddenNullArgs.empty() &&
  4781. ForbiddenNullArgs[I - Args.begin()] &&
  4782. ArgValues[I - Args.begin()].isNullPointer()) {
  4783. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4784. if (!Info.noteFailure())
  4785. return false;
  4786. Success = false;
  4787. }
  4788. }
  4789. return Success;
  4790. }
  4791. /// Evaluate a function call.
  4792. static bool HandleFunctionCall(SourceLocation CallLoc,
  4793. const FunctionDecl *Callee, const LValue *This,
  4794. ArrayRef<const Expr*> Args, const Stmt *Body,
  4795. EvalInfo &Info, APValue &Result,
  4796. const LValue *ResultSlot) {
  4797. ArgVector ArgValues(Args.size());
  4798. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4799. return false;
  4800. if (!Info.CheckCallLimit(CallLoc))
  4801. return false;
  4802. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4803. // For a trivial copy or move assignment, perform an APValue copy. This is
  4804. // essential for unions, where the operations performed by the assignment
  4805. // operator cannot be represented as statements.
  4806. //
  4807. // Skip this for non-union classes with no fields; in that case, the defaulted
  4808. // copy/move does not actually read the object.
  4809. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4810. if (MD && MD->isDefaulted() &&
  4811. (MD->getParent()->isUnion() ||
  4812. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4813. assert(This &&
  4814. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4815. LValue RHS;
  4816. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4817. APValue RHSValue;
  4818. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
  4819. RHSValue, MD->getParent()->isUnion()))
  4820. return false;
  4821. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4822. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4823. return false;
  4824. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4825. RHSValue))
  4826. return false;
  4827. This->moveInto(Result);
  4828. return true;
  4829. } else if (MD && isLambdaCallOperator(MD)) {
  4830. // We're in a lambda; determine the lambda capture field maps unless we're
  4831. // just constexpr checking a lambda's call operator. constexpr checking is
  4832. // done before the captures have been added to the closure object (unless
  4833. // we're inferring constexpr-ness), so we don't have access to them in this
  4834. // case. But since we don't need the captures to constexpr check, we can
  4835. // just ignore them.
  4836. if (!Info.checkingPotentialConstantExpression())
  4837. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4838. Frame.LambdaThisCaptureField);
  4839. }
  4840. StmtResult Ret = {Result, ResultSlot};
  4841. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4842. if (ESR == ESR_Succeeded) {
  4843. if (Callee->getReturnType()->isVoidType())
  4844. return true;
  4845. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4846. }
  4847. return ESR == ESR_Returned;
  4848. }
  4849. /// Evaluate a constructor call.
  4850. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4851. APValue *ArgValues,
  4852. const CXXConstructorDecl *Definition,
  4853. EvalInfo &Info, APValue &Result) {
  4854. SourceLocation CallLoc = E->getExprLoc();
  4855. if (!Info.CheckCallLimit(CallLoc))
  4856. return false;
  4857. const CXXRecordDecl *RD = Definition->getParent();
  4858. if (RD->getNumVBases()) {
  4859. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4860. return false;
  4861. }
  4862. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4863. Info,
  4864. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4865. RD->getNumBases());
  4866. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4867. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4868. // wasteful.
  4869. APValue RetVal;
  4870. StmtResult Ret = {RetVal, nullptr};
  4871. // If it's a delegating constructor, delegate.
  4872. if (Definition->isDelegatingConstructor()) {
  4873. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4874. {
  4875. FullExpressionRAII InitScope(Info);
  4876. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  4877. !InitScope.destroy())
  4878. return false;
  4879. }
  4880. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4881. }
  4882. // For a trivial copy or move constructor, perform an APValue copy. This is
  4883. // essential for unions (or classes with anonymous union members), where the
  4884. // operations performed by the constructor cannot be represented by
  4885. // ctor-initializers.
  4886. //
  4887. // Skip this for empty non-union classes; we should not perform an
  4888. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4889. // actually read them.
  4890. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4891. (Definition->getParent()->isUnion() ||
  4892. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4893. LValue RHS;
  4894. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4895. return handleLValueToRValueConversion(
  4896. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4897. RHS, Result, Definition->getParent()->isUnion());
  4898. }
  4899. // Reserve space for the struct members.
  4900. if (!RD->isUnion() && !Result.hasValue())
  4901. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4902. std::distance(RD->field_begin(), RD->field_end()));
  4903. if (RD->isInvalidDecl()) return false;
  4904. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4905. // A scope for temporaries lifetime-extended by reference members.
  4906. BlockScopeRAII LifetimeExtendedScope(Info);
  4907. bool Success = true;
  4908. unsigned BasesSeen = 0;
  4909. #ifndef NDEBUG
  4910. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4911. #endif
  4912. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  4913. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  4914. // We might be initializing the same field again if this is an indirect
  4915. // field initialization.
  4916. if (FieldIt == RD->field_end() ||
  4917. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  4918. assert(Indirect && "fields out of order?");
  4919. return;
  4920. }
  4921. // Default-initialize any fields with no explicit initializer.
  4922. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  4923. assert(FieldIt != RD->field_end() && "missing field?");
  4924. if (!FieldIt->isUnnamedBitfield())
  4925. Result.getStructField(FieldIt->getFieldIndex()) =
  4926. getDefaultInitValue(FieldIt->getType());
  4927. }
  4928. ++FieldIt;
  4929. };
  4930. for (const auto *I : Definition->inits()) {
  4931. LValue Subobject = This;
  4932. LValue SubobjectParent = This;
  4933. APValue *Value = &Result;
  4934. // Determine the subobject to initialize.
  4935. FieldDecl *FD = nullptr;
  4936. if (I->isBaseInitializer()) {
  4937. QualType BaseType(I->getBaseClass(), 0);
  4938. #ifndef NDEBUG
  4939. // Non-virtual base classes are initialized in the order in the class
  4940. // definition. We have already checked for virtual base classes.
  4941. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4942. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4943. "base class initializers not in expected order");
  4944. ++BaseIt;
  4945. #endif
  4946. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4947. BaseType->getAsCXXRecordDecl(), &Layout))
  4948. return false;
  4949. Value = &Result.getStructBase(BasesSeen++);
  4950. } else if ((FD = I->getMember())) {
  4951. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4952. return false;
  4953. if (RD->isUnion()) {
  4954. Result = APValue(FD);
  4955. Value = &Result.getUnionValue();
  4956. } else {
  4957. SkipToField(FD, false);
  4958. Value = &Result.getStructField(FD->getFieldIndex());
  4959. }
  4960. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4961. // Walk the indirect field decl's chain to find the object to initialize,
  4962. // and make sure we've initialized every step along it.
  4963. auto IndirectFieldChain = IFD->chain();
  4964. for (auto *C : IndirectFieldChain) {
  4965. FD = cast<FieldDecl>(C);
  4966. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4967. // Switch the union field if it differs. This happens if we had
  4968. // preceding zero-initialization, and we're now initializing a union
  4969. // subobject other than the first.
  4970. // FIXME: In this case, the values of the other subobjects are
  4971. // specified, since zero-initialization sets all padding bits to zero.
  4972. if (!Value->hasValue() ||
  4973. (Value->isUnion() && Value->getUnionField() != FD)) {
  4974. if (CD->isUnion())
  4975. *Value = APValue(FD);
  4976. else
  4977. // FIXME: This immediately starts the lifetime of all members of an
  4978. // anonymous struct. It would be preferable to strictly start member
  4979. // lifetime in initialization order.
  4980. *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
  4981. }
  4982. // Store Subobject as its parent before updating it for the last element
  4983. // in the chain.
  4984. if (C == IndirectFieldChain.back())
  4985. SubobjectParent = Subobject;
  4986. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4987. return false;
  4988. if (CD->isUnion())
  4989. Value = &Value->getUnionValue();
  4990. else {
  4991. if (C == IndirectFieldChain.front() && !RD->isUnion())
  4992. SkipToField(FD, true);
  4993. Value = &Value->getStructField(FD->getFieldIndex());
  4994. }
  4995. }
  4996. } else {
  4997. llvm_unreachable("unknown base initializer kind");
  4998. }
  4999. // Need to override This for implicit field initializers as in this case
  5000. // This refers to innermost anonymous struct/union containing initializer,
  5001. // not to currently constructed class.
  5002. const Expr *Init = I->getInit();
  5003. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  5004. isa<CXXDefaultInitExpr>(Init));
  5005. FullExpressionRAII InitScope(Info);
  5006. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  5007. (FD && FD->isBitField() &&
  5008. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  5009. // If we're checking for a potential constant expression, evaluate all
  5010. // initializers even if some of them fail.
  5011. if (!Info.noteFailure())
  5012. return false;
  5013. Success = false;
  5014. }
  5015. // This is the point at which the dynamic type of the object becomes this
  5016. // class type.
  5017. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  5018. EvalObj.finishedConstructingBases();
  5019. }
  5020. // Default-initialize any remaining fields.
  5021. if (!RD->isUnion()) {
  5022. for (; FieldIt != RD->field_end(); ++FieldIt) {
  5023. if (!FieldIt->isUnnamedBitfield())
  5024. Result.getStructField(FieldIt->getFieldIndex()) =
  5025. getDefaultInitValue(FieldIt->getType());
  5026. }
  5027. }
  5028. return Success &&
  5029. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  5030. LifetimeExtendedScope.destroy();
  5031. }
  5032. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5033. ArrayRef<const Expr*> Args,
  5034. const CXXConstructorDecl *Definition,
  5035. EvalInfo &Info, APValue &Result) {
  5036. ArgVector ArgValues(Args.size());
  5037. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  5038. return false;
  5039. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  5040. Info, Result);
  5041. }
  5042. static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
  5043. const LValue &This, APValue &Value,
  5044. QualType T) {
  5045. // Objects can only be destroyed while they're within their lifetimes.
  5046. // FIXME: We have no representation for whether an object of type nullptr_t
  5047. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  5048. // as indeterminate instead?
  5049. if (Value.isAbsent() && !T->isNullPtrType()) {
  5050. APValue Printable;
  5051. This.moveInto(Printable);
  5052. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  5053. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  5054. return false;
  5055. }
  5056. // Invent an expression for location purposes.
  5057. // FIXME: We shouldn't need to do this.
  5058. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
  5059. // For arrays, destroy elements right-to-left.
  5060. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  5061. uint64_t Size = CAT->getSize().getZExtValue();
  5062. QualType ElemT = CAT->getElementType();
  5063. LValue ElemLV = This;
  5064. ElemLV.addArray(Info, &LocE, CAT);
  5065. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  5066. return false;
  5067. // Ensure that we have actual array elements available to destroy; the
  5068. // destructors might mutate the value, so we can't run them on the array
  5069. // filler.
  5070. if (Size && Size > Value.getArrayInitializedElts())
  5071. expandArray(Value, Value.getArraySize() - 1);
  5072. for (; Size != 0; --Size) {
  5073. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  5074. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  5075. !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  5076. return false;
  5077. }
  5078. // End the lifetime of this array now.
  5079. Value = APValue();
  5080. return true;
  5081. }
  5082. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5083. if (!RD) {
  5084. if (T.isDestructedType()) {
  5085. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  5086. return false;
  5087. }
  5088. Value = APValue();
  5089. return true;
  5090. }
  5091. if (RD->getNumVBases()) {
  5092. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5093. return false;
  5094. }
  5095. const CXXDestructorDecl *DD = RD->getDestructor();
  5096. if (!DD && !RD->hasTrivialDestructor()) {
  5097. Info.FFDiag(CallLoc);
  5098. return false;
  5099. }
  5100. if (!DD || DD->isTrivial() ||
  5101. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5102. // A trivial destructor just ends the lifetime of the object. Check for
  5103. // this case before checking for a body, because we might not bother
  5104. // building a body for a trivial destructor. Note that it doesn't matter
  5105. // whether the destructor is constexpr in this case; all trivial
  5106. // destructors are constexpr.
  5107. //
  5108. // If an anonymous union would be destroyed, some enclosing destructor must
  5109. // have been explicitly defined, and the anonymous union destruction should
  5110. // have no effect.
  5111. Value = APValue();
  5112. return true;
  5113. }
  5114. if (!Info.CheckCallLimit(CallLoc))
  5115. return false;
  5116. const FunctionDecl *Definition = nullptr;
  5117. const Stmt *Body = DD->getBody(Definition);
  5118. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5119. return false;
  5120. CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
  5121. // We're now in the period of destruction of this object.
  5122. unsigned BasesLeft = RD->getNumBases();
  5123. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5124. Info,
  5125. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5126. if (!EvalObj.DidInsert) {
  5127. // C++2a [class.dtor]p19:
  5128. // the behavior is undefined if the destructor is invoked for an object
  5129. // whose lifetime has ended
  5130. // (Note that formally the lifetime ends when the period of destruction
  5131. // begins, even though certain uses of the object remain valid until the
  5132. // period of destruction ends.)
  5133. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5134. return false;
  5135. }
  5136. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5137. // wasteful.
  5138. APValue RetVal;
  5139. StmtResult Ret = {RetVal, nullptr};
  5140. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5141. return false;
  5142. // A union destructor does not implicitly destroy its members.
  5143. if (RD->isUnion())
  5144. return true;
  5145. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5146. // We don't have a good way to iterate fields in reverse, so collect all the
  5147. // fields first and then walk them backwards.
  5148. SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  5149. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5150. if (FD->isUnnamedBitfield())
  5151. continue;
  5152. LValue Subobject = This;
  5153. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5154. return false;
  5155. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5156. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5157. FD->getType()))
  5158. return false;
  5159. }
  5160. if (BasesLeft != 0)
  5161. EvalObj.startedDestroyingBases();
  5162. // Destroy base classes in reverse order.
  5163. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5164. --BasesLeft;
  5165. QualType BaseType = Base.getType();
  5166. LValue Subobject = This;
  5167. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5168. BaseType->getAsCXXRecordDecl(), &Layout))
  5169. return false;
  5170. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5171. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5172. BaseType))
  5173. return false;
  5174. }
  5175. assert(BasesLeft == 0 && "NumBases was wrong?");
  5176. // The period of destruction ends now. The object is gone.
  5177. Value = APValue();
  5178. return true;
  5179. }
  5180. namespace {
  5181. struct DestroyObjectHandler {
  5182. EvalInfo &Info;
  5183. const Expr *E;
  5184. const LValue &This;
  5185. const AccessKinds AccessKind;
  5186. typedef bool result_type;
  5187. bool failed() { return false; }
  5188. bool found(APValue &Subobj, QualType SubobjType) {
  5189. return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
  5190. SubobjType);
  5191. }
  5192. bool found(APSInt &Value, QualType SubobjType) {
  5193. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5194. return false;
  5195. }
  5196. bool found(APFloat &Value, QualType SubobjType) {
  5197. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5198. return false;
  5199. }
  5200. };
  5201. }
  5202. /// Perform a destructor or pseudo-destructor call on the given object, which
  5203. /// might in general not be a complete object.
  5204. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  5205. const LValue &This, QualType ThisType) {
  5206. CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
  5207. DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
  5208. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5209. }
  5210. /// Destroy and end the lifetime of the given complete object.
  5211. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  5212. APValue::LValueBase LVBase, APValue &Value,
  5213. QualType T) {
  5214. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5215. // (such as the object we're about to destroy) being correct.
  5216. if (Info.EvalStatus.HasSideEffects)
  5217. return false;
  5218. LValue LV;
  5219. LV.set({LVBase});
  5220. return HandleDestructionImpl(Info, Loc, LV, Value, T);
  5221. }
  5222. //===----------------------------------------------------------------------===//
  5223. // Generic Evaluation
  5224. //===----------------------------------------------------------------------===//
  5225. namespace {
  5226. class BitCastBuffer {
  5227. // FIXME: We're going to need bit-level granularity when we support
  5228. // bit-fields.
  5229. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  5230. // we don't support a host or target where that is the case. Still, we should
  5231. // use a more generic type in case we ever do.
  5232. SmallVector<Optional<unsigned char>, 32> Bytes;
  5233. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  5234. "Need at least 8 bit unsigned char");
  5235. bool TargetIsLittleEndian;
  5236. public:
  5237. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  5238. : Bytes(Width.getQuantity()),
  5239. TargetIsLittleEndian(TargetIsLittleEndian) {}
  5240. LLVM_NODISCARD
  5241. bool readObject(CharUnits Offset, CharUnits Width,
  5242. SmallVectorImpl<unsigned char> &Output) const {
  5243. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  5244. // If a byte of an integer is uninitialized, then the whole integer is
  5245. // uninitalized.
  5246. if (!Bytes[I.getQuantity()])
  5247. return false;
  5248. Output.push_back(*Bytes[I.getQuantity()]);
  5249. }
  5250. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5251. std::reverse(Output.begin(), Output.end());
  5252. return true;
  5253. }
  5254. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  5255. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5256. std::reverse(Input.begin(), Input.end());
  5257. size_t Index = 0;
  5258. for (unsigned char Byte : Input) {
  5259. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  5260. Bytes[Offset.getQuantity() + Index] = Byte;
  5261. ++Index;
  5262. }
  5263. }
  5264. size_t size() { return Bytes.size(); }
  5265. };
  5266. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  5267. /// target would represent the value at runtime.
  5268. class APValueToBufferConverter {
  5269. EvalInfo &Info;
  5270. BitCastBuffer Buffer;
  5271. const CastExpr *BCE;
  5272. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  5273. const CastExpr *BCE)
  5274. : Info(Info),
  5275. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  5276. BCE(BCE) {}
  5277. bool visit(const APValue &Val, QualType Ty) {
  5278. return visit(Val, Ty, CharUnits::fromQuantity(0));
  5279. }
  5280. // Write out Val with type Ty into Buffer starting at Offset.
  5281. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  5282. assert((size_t)Offset.getQuantity() <= Buffer.size());
  5283. // As a special case, nullptr_t has an indeterminate value.
  5284. if (Ty->isNullPtrType())
  5285. return true;
  5286. // Dig through Src to find the byte at SrcOffset.
  5287. switch (Val.getKind()) {
  5288. case APValue::Indeterminate:
  5289. case APValue::None:
  5290. return true;
  5291. case APValue::Int:
  5292. return visitInt(Val.getInt(), Ty, Offset);
  5293. case APValue::Float:
  5294. return visitFloat(Val.getFloat(), Ty, Offset);
  5295. case APValue::Array:
  5296. return visitArray(Val, Ty, Offset);
  5297. case APValue::Struct:
  5298. return visitRecord(Val, Ty, Offset);
  5299. case APValue::ComplexInt:
  5300. case APValue::ComplexFloat:
  5301. case APValue::Vector:
  5302. case APValue::FixedPoint:
  5303. // FIXME: We should support these.
  5304. case APValue::Union:
  5305. case APValue::MemberPointer:
  5306. case APValue::AddrLabelDiff: {
  5307. Info.FFDiag(BCE->getBeginLoc(),
  5308. diag::note_constexpr_bit_cast_unsupported_type)
  5309. << Ty;
  5310. return false;
  5311. }
  5312. case APValue::LValue:
  5313. llvm_unreachable("LValue subobject in bit_cast?");
  5314. }
  5315. llvm_unreachable("Unhandled APValue::ValueKind");
  5316. }
  5317. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  5318. const RecordDecl *RD = Ty->getAsRecordDecl();
  5319. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5320. // Visit the base classes.
  5321. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5322. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5323. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5324. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5325. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  5326. Layout.getBaseClassOffset(BaseDecl) + Offset))
  5327. return false;
  5328. }
  5329. }
  5330. // Visit the fields.
  5331. unsigned FieldIdx = 0;
  5332. for (FieldDecl *FD : RD->fields()) {
  5333. if (FD->isBitField()) {
  5334. Info.FFDiag(BCE->getBeginLoc(),
  5335. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5336. return false;
  5337. }
  5338. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5339. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  5340. "only bit-fields can have sub-char alignment");
  5341. CharUnits FieldOffset =
  5342. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  5343. QualType FieldTy = FD->getType();
  5344. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  5345. return false;
  5346. ++FieldIdx;
  5347. }
  5348. return true;
  5349. }
  5350. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  5351. const auto *CAT =
  5352. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  5353. if (!CAT)
  5354. return false;
  5355. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  5356. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  5357. unsigned ArraySize = Val.getArraySize();
  5358. // First, initialize the initialized elements.
  5359. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  5360. const APValue &SubObj = Val.getArrayInitializedElt(I);
  5361. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  5362. return false;
  5363. }
  5364. // Next, initialize the rest of the array using the filler.
  5365. if (Val.hasArrayFiller()) {
  5366. const APValue &Filler = Val.getArrayFiller();
  5367. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  5368. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  5369. return false;
  5370. }
  5371. }
  5372. return true;
  5373. }
  5374. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  5375. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  5376. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  5377. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  5378. Buffer.writeObject(Offset, Bytes);
  5379. return true;
  5380. }
  5381. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  5382. APSInt AsInt(Val.bitcastToAPInt());
  5383. return visitInt(AsInt, Ty, Offset);
  5384. }
  5385. public:
  5386. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  5387. const CastExpr *BCE) {
  5388. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  5389. APValueToBufferConverter Converter(Info, DstSize, BCE);
  5390. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  5391. return None;
  5392. return Converter.Buffer;
  5393. }
  5394. };
  5395. /// Write an BitCastBuffer into an APValue.
  5396. class BufferToAPValueConverter {
  5397. EvalInfo &Info;
  5398. const BitCastBuffer &Buffer;
  5399. const CastExpr *BCE;
  5400. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  5401. const CastExpr *BCE)
  5402. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  5403. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  5404. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  5405. // Ideally this will be unreachable.
  5406. llvm::NoneType unsupportedType(QualType Ty) {
  5407. Info.FFDiag(BCE->getBeginLoc(),
  5408. diag::note_constexpr_bit_cast_unsupported_type)
  5409. << Ty;
  5410. return None;
  5411. }
  5412. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  5413. const EnumType *EnumSugar = nullptr) {
  5414. if (T->isNullPtrType()) {
  5415. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  5416. return APValue((Expr *)nullptr,
  5417. /*Offset=*/CharUnits::fromQuantity(NullValue),
  5418. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  5419. }
  5420. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  5421. SmallVector<uint8_t, 8> Bytes;
  5422. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  5423. // If this is std::byte or unsigned char, then its okay to store an
  5424. // indeterminate value.
  5425. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  5426. bool IsUChar =
  5427. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  5428. T->isSpecificBuiltinType(BuiltinType::Char_U));
  5429. if (!IsStdByte && !IsUChar) {
  5430. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  5431. Info.FFDiag(BCE->getExprLoc(),
  5432. diag::note_constexpr_bit_cast_indet_dest)
  5433. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  5434. return None;
  5435. }
  5436. return APValue::IndeterminateValue();
  5437. }
  5438. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  5439. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  5440. if (T->isIntegralOrEnumerationType()) {
  5441. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  5442. return APValue(Val);
  5443. }
  5444. if (T->isRealFloatingType()) {
  5445. const llvm::fltSemantics &Semantics =
  5446. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5447. return APValue(APFloat(Semantics, Val));
  5448. }
  5449. return unsupportedType(QualType(T, 0));
  5450. }
  5451. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5452. const RecordDecl *RD = RTy->getAsRecordDecl();
  5453. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5454. unsigned NumBases = 0;
  5455. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5456. NumBases = CXXRD->getNumBases();
  5457. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5458. std::distance(RD->field_begin(), RD->field_end()));
  5459. // Visit the base classes.
  5460. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5461. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5462. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5463. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5464. if (BaseDecl->isEmpty() ||
  5465. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5466. continue;
  5467. Optional<APValue> SubObj = visitType(
  5468. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5469. if (!SubObj)
  5470. return None;
  5471. ResultVal.getStructBase(I) = *SubObj;
  5472. }
  5473. }
  5474. // Visit the fields.
  5475. unsigned FieldIdx = 0;
  5476. for (FieldDecl *FD : RD->fields()) {
  5477. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5478. // this is in CodeGen, so we need to factor it around.
  5479. if (FD->isBitField()) {
  5480. Info.FFDiag(BCE->getBeginLoc(),
  5481. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5482. return None;
  5483. }
  5484. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5485. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5486. CharUnits FieldOffset =
  5487. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5488. Offset;
  5489. QualType FieldTy = FD->getType();
  5490. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5491. if (!SubObj)
  5492. return None;
  5493. ResultVal.getStructField(FieldIdx) = *SubObj;
  5494. ++FieldIdx;
  5495. }
  5496. return ResultVal;
  5497. }
  5498. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5499. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5500. assert(!RepresentationType.isNull() &&
  5501. "enum forward decl should be caught by Sema");
  5502. const BuiltinType *AsBuiltin =
  5503. RepresentationType.getCanonicalType()->getAs<BuiltinType>();
  5504. assert(AsBuiltin && "non-integral enum underlying type?");
  5505. // Recurse into the underlying type. Treat std::byte transparently as
  5506. // unsigned char.
  5507. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5508. }
  5509. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5510. size_t Size = Ty->getSize().getLimitedValue();
  5511. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5512. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5513. for (size_t I = 0; I != Size; ++I) {
  5514. Optional<APValue> ElementValue =
  5515. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5516. if (!ElementValue)
  5517. return None;
  5518. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5519. }
  5520. return ArrayValue;
  5521. }
  5522. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5523. return unsupportedType(QualType(Ty, 0));
  5524. }
  5525. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5526. QualType Can = Ty.getCanonicalType();
  5527. switch (Can->getTypeClass()) {
  5528. #define TYPE(Class, Base) \
  5529. case Type::Class: \
  5530. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5531. #define ABSTRACT_TYPE(Class, Base)
  5532. #define NON_CANONICAL_TYPE(Class, Base) \
  5533. case Type::Class: \
  5534. llvm_unreachable("non-canonical type should be impossible!");
  5535. #define DEPENDENT_TYPE(Class, Base) \
  5536. case Type::Class: \
  5537. llvm_unreachable( \
  5538. "dependent types aren't supported in the constant evaluator!");
  5539. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5540. case Type::Class: \
  5541. llvm_unreachable("either dependent or not canonical!");
  5542. #include "clang/AST/TypeNodes.inc"
  5543. }
  5544. llvm_unreachable("Unhandled Type::TypeClass");
  5545. }
  5546. public:
  5547. // Pull out a full value of type DstType.
  5548. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5549. const CastExpr *BCE) {
  5550. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5551. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5552. }
  5553. };
  5554. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5555. QualType Ty, EvalInfo *Info,
  5556. const ASTContext &Ctx,
  5557. bool CheckingDest) {
  5558. Ty = Ty.getCanonicalType();
  5559. auto diag = [&](int Reason) {
  5560. if (Info)
  5561. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5562. << CheckingDest << (Reason == 4) << Reason;
  5563. return false;
  5564. };
  5565. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5566. if (Info)
  5567. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5568. << NoteTy << Construct << Ty;
  5569. return false;
  5570. };
  5571. if (Ty->isUnionType())
  5572. return diag(0);
  5573. if (Ty->isPointerType())
  5574. return diag(1);
  5575. if (Ty->isMemberPointerType())
  5576. return diag(2);
  5577. if (Ty.isVolatileQualified())
  5578. return diag(3);
  5579. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5580. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5581. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5582. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5583. CheckingDest))
  5584. return note(1, BS.getType(), BS.getBeginLoc());
  5585. }
  5586. for (FieldDecl *FD : Record->fields()) {
  5587. if (FD->getType()->isReferenceType())
  5588. return diag(4);
  5589. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5590. CheckingDest))
  5591. return note(0, FD->getType(), FD->getBeginLoc());
  5592. }
  5593. }
  5594. if (Ty->isArrayType() &&
  5595. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5596. Info, Ctx, CheckingDest))
  5597. return false;
  5598. return true;
  5599. }
  5600. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5601. const ASTContext &Ctx,
  5602. const CastExpr *BCE) {
  5603. bool DestOK = checkBitCastConstexprEligibilityType(
  5604. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5605. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5606. BCE->getBeginLoc(),
  5607. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5608. return SourceOK;
  5609. }
  5610. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5611. APValue &SourceValue,
  5612. const CastExpr *BCE) {
  5613. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5614. "no host or target supports non 8-bit chars");
  5615. assert(SourceValue.isLValue() &&
  5616. "LValueToRValueBitcast requires an lvalue operand!");
  5617. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5618. return false;
  5619. LValue SourceLValue;
  5620. APValue SourceRValue;
  5621. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5622. if (!handleLValueToRValueConversion(
  5623. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  5624. SourceRValue, /*WantObjectRepresentation=*/true))
  5625. return false;
  5626. // Read out SourceValue into a char buffer.
  5627. Optional<BitCastBuffer> Buffer =
  5628. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5629. if (!Buffer)
  5630. return false;
  5631. // Write out the buffer into a new APValue.
  5632. Optional<APValue> MaybeDestValue =
  5633. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5634. if (!MaybeDestValue)
  5635. return false;
  5636. DestValue = std::move(*MaybeDestValue);
  5637. return true;
  5638. }
  5639. template <class Derived>
  5640. class ExprEvaluatorBase
  5641. : public ConstStmtVisitor<Derived, bool> {
  5642. private:
  5643. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5644. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5645. return getDerived().Success(V, E);
  5646. }
  5647. bool DerivedZeroInitialization(const Expr *E) {
  5648. return getDerived().ZeroInitialization(E);
  5649. }
  5650. // Check whether a conditional operator with a non-constant condition is a
  5651. // potential constant expression. If neither arm is a potential constant
  5652. // expression, then the conditional operator is not either.
  5653. template<typename ConditionalOperator>
  5654. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5655. assert(Info.checkingPotentialConstantExpression());
  5656. // Speculatively evaluate both arms.
  5657. SmallVector<PartialDiagnosticAt, 8> Diag;
  5658. {
  5659. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5660. StmtVisitorTy::Visit(E->getFalseExpr());
  5661. if (Diag.empty())
  5662. return;
  5663. }
  5664. {
  5665. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5666. Diag.clear();
  5667. StmtVisitorTy::Visit(E->getTrueExpr());
  5668. if (Diag.empty())
  5669. return;
  5670. }
  5671. Error(E, diag::note_constexpr_conditional_never_const);
  5672. }
  5673. template<typename ConditionalOperator>
  5674. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5675. bool BoolResult;
  5676. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5677. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5678. CheckPotentialConstantConditional(E);
  5679. return false;
  5680. }
  5681. if (Info.noteFailure()) {
  5682. StmtVisitorTy::Visit(E->getTrueExpr());
  5683. StmtVisitorTy::Visit(E->getFalseExpr());
  5684. }
  5685. return false;
  5686. }
  5687. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5688. return StmtVisitorTy::Visit(EvalExpr);
  5689. }
  5690. protected:
  5691. EvalInfo &Info;
  5692. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5693. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5694. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5695. return Info.CCEDiag(E, D);
  5696. }
  5697. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5698. public:
  5699. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5700. EvalInfo &getEvalInfo() { return Info; }
  5701. /// Report an evaluation error. This should only be called when an error is
  5702. /// first discovered. When propagating an error, just return false.
  5703. bool Error(const Expr *E, diag::kind D) {
  5704. Info.FFDiag(E, D);
  5705. return false;
  5706. }
  5707. bool Error(const Expr *E) {
  5708. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5709. }
  5710. bool VisitStmt(const Stmt *) {
  5711. llvm_unreachable("Expression evaluator should not be called on stmts");
  5712. }
  5713. bool VisitExpr(const Expr *E) {
  5714. return Error(E);
  5715. }
  5716. bool VisitConstantExpr(const ConstantExpr *E)
  5717. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5718. bool VisitParenExpr(const ParenExpr *E)
  5719. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5720. bool VisitUnaryExtension(const UnaryOperator *E)
  5721. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5722. bool VisitUnaryPlus(const UnaryOperator *E)
  5723. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5724. bool VisitChooseExpr(const ChooseExpr *E)
  5725. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5726. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5727. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5728. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5729. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5730. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5731. TempVersionRAII RAII(*Info.CurrentCall);
  5732. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5733. return StmtVisitorTy::Visit(E->getExpr());
  5734. }
  5735. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5736. TempVersionRAII RAII(*Info.CurrentCall);
  5737. // The initializer may not have been parsed yet, or might be erroneous.
  5738. if (!E->getExpr())
  5739. return Error(E);
  5740. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5741. return StmtVisitorTy::Visit(E->getExpr());
  5742. }
  5743. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  5744. FullExpressionRAII Scope(Info);
  5745. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  5746. }
  5747. // Temporaries are registered when created, so we don't care about
  5748. // CXXBindTemporaryExpr.
  5749. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  5750. return StmtVisitorTy::Visit(E->getSubExpr());
  5751. }
  5752. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5753. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5754. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5755. }
  5756. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5757. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5758. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5759. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5760. }
  5761. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5762. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5763. }
  5764. bool VisitBinaryOperator(const BinaryOperator *E) {
  5765. switch (E->getOpcode()) {
  5766. default:
  5767. return Error(E);
  5768. case BO_Comma:
  5769. VisitIgnoredValue(E->getLHS());
  5770. return StmtVisitorTy::Visit(E->getRHS());
  5771. case BO_PtrMemD:
  5772. case BO_PtrMemI: {
  5773. LValue Obj;
  5774. if (!HandleMemberPointerAccess(Info, E, Obj))
  5775. return false;
  5776. APValue Result;
  5777. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5778. return false;
  5779. return DerivedSuccess(Result, E);
  5780. }
  5781. }
  5782. }
  5783. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5784. // Evaluate and cache the common expression. We treat it as a temporary,
  5785. // even though it's not quite the same thing.
  5786. LValue CommonLV;
  5787. if (!Evaluate(Info.CurrentCall->createTemporary(
  5788. E->getOpaqueValue(),
  5789. getStorageType(Info.Ctx, E->getOpaqueValue()), false,
  5790. CommonLV),
  5791. Info, E->getCommon()))
  5792. return false;
  5793. return HandleConditionalOperator(E);
  5794. }
  5795. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5796. bool IsBcpCall = false;
  5797. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5798. // the result is a constant expression if it can be folded without
  5799. // side-effects. This is an important GNU extension. See GCC PR38377
  5800. // for discussion.
  5801. if (const CallExpr *CallCE =
  5802. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5803. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5804. IsBcpCall = true;
  5805. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5806. // constant expression; we can't check whether it's potentially foldable.
  5807. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  5808. // it would return 'false' in this mode.
  5809. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  5810. return false;
  5811. FoldConstant Fold(Info, IsBcpCall);
  5812. if (!HandleConditionalOperator(E)) {
  5813. Fold.keepDiagnostics();
  5814. return false;
  5815. }
  5816. return true;
  5817. }
  5818. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  5819. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  5820. return DerivedSuccess(*Value, E);
  5821. const Expr *Source = E->getSourceExpr();
  5822. if (!Source)
  5823. return Error(E);
  5824. if (Source == E) { // sanity checking.
  5825. assert(0 && "OpaqueValueExpr recursively refers to itself");
  5826. return Error(E);
  5827. }
  5828. return StmtVisitorTy::Visit(Source);
  5829. }
  5830. bool VisitCallExpr(const CallExpr *E) {
  5831. APValue Result;
  5832. if (!handleCallExpr(E, Result, nullptr))
  5833. return false;
  5834. return DerivedSuccess(Result, E);
  5835. }
  5836. bool handleCallExpr(const CallExpr *E, APValue &Result,
  5837. const LValue *ResultSlot) {
  5838. const Expr *Callee = E->getCallee()->IgnoreParens();
  5839. QualType CalleeType = Callee->getType();
  5840. const FunctionDecl *FD = nullptr;
  5841. LValue *This = nullptr, ThisVal;
  5842. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5843. bool HasQualifier = false;
  5844. // Extract function decl and 'this' pointer from the callee.
  5845. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  5846. const CXXMethodDecl *Member = nullptr;
  5847. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  5848. // Explicit bound member calls, such as x.f() or p->g();
  5849. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  5850. return false;
  5851. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  5852. if (!Member)
  5853. return Error(Callee);
  5854. This = &ThisVal;
  5855. HasQualifier = ME->hasQualifier();
  5856. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  5857. // Indirect bound member calls ('.*' or '->*').
  5858. Member = dyn_cast_or_null<CXXMethodDecl>(
  5859. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  5860. if (!Member)
  5861. return Error(Callee);
  5862. This = &ThisVal;
  5863. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  5864. if (!Info.getLangOpts().CPlusPlus2a)
  5865. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  5866. // FIXME: If pseudo-destructor calls ever start ending the lifetime of
  5867. // their callee, we should start calling HandleDestruction here.
  5868. // For now, we just evaluate the object argument and discard it.
  5869. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
  5870. } else
  5871. return Error(Callee);
  5872. FD = Member;
  5873. } else if (CalleeType->isFunctionPointerType()) {
  5874. LValue Call;
  5875. if (!EvaluatePointer(Callee, Call, Info))
  5876. return false;
  5877. if (!Call.getLValueOffset().isZero())
  5878. return Error(Callee);
  5879. FD = dyn_cast_or_null<FunctionDecl>(
  5880. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  5881. if (!FD)
  5882. return Error(Callee);
  5883. // Don't call function pointers which have been cast to some other type.
  5884. // Per DR (no number yet), the caller and callee can differ in noexcept.
  5885. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  5886. CalleeType->getPointeeType(), FD->getType())) {
  5887. return Error(E);
  5888. }
  5889. // Overloaded operator calls to member functions are represented as normal
  5890. // calls with '*this' as the first argument.
  5891. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5892. if (MD && !MD->isStatic()) {
  5893. // FIXME: When selecting an implicit conversion for an overloaded
  5894. // operator delete, we sometimes try to evaluate calls to conversion
  5895. // operators without a 'this' parameter!
  5896. if (Args.empty())
  5897. return Error(E);
  5898. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  5899. return false;
  5900. This = &ThisVal;
  5901. Args = Args.slice(1);
  5902. } else if (MD && MD->isLambdaStaticInvoker()) {
  5903. // Map the static invoker for the lambda back to the call operator.
  5904. // Conveniently, we don't have to slice out the 'this' argument (as is
  5905. // being done for the non-static case), since a static member function
  5906. // doesn't have an implicit argument passed in.
  5907. const CXXRecordDecl *ClosureClass = MD->getParent();
  5908. assert(
  5909. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5910. "Number of captures must be zero for conversion to function-ptr");
  5911. const CXXMethodDecl *LambdaCallOp =
  5912. ClosureClass->getLambdaCallOperator();
  5913. // Set 'FD', the function that will be called below, to the call
  5914. // operator. If the closure object represents a generic lambda, find
  5915. // the corresponding specialization of the call operator.
  5916. if (ClosureClass->isGenericLambda()) {
  5917. assert(MD->isFunctionTemplateSpecialization() &&
  5918. "A generic lambda's static-invoker function must be a "
  5919. "template specialization");
  5920. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5921. FunctionTemplateDecl *CallOpTemplate =
  5922. LambdaCallOp->getDescribedFunctionTemplate();
  5923. void *InsertPos = nullptr;
  5924. FunctionDecl *CorrespondingCallOpSpecialization =
  5925. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5926. assert(CorrespondingCallOpSpecialization &&
  5927. "We must always have a function call operator specialization "
  5928. "that corresponds to our static invoker specialization");
  5929. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5930. } else
  5931. FD = LambdaCallOp;
  5932. }
  5933. } else
  5934. return Error(E);
  5935. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5936. if (This) {
  5937. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5938. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5939. // Perform virtual dispatch, if necessary.
  5940. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5941. CovariantAdjustmentPath);
  5942. if (!FD)
  5943. return false;
  5944. } else {
  5945. // Check that the 'this' pointer points to an object of the right type.
  5946. // FIXME: If this is an assignment operator call, we may need to change
  5947. // the active union member before we check this.
  5948. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  5949. return false;
  5950. }
  5951. }
  5952. // Destructor calls are different enough that they have their own codepath.
  5953. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  5954. assert(This && "no 'this' pointer for destructor call");
  5955. return HandleDestruction(Info, E, *This,
  5956. Info.Ctx.getRecordType(DD->getParent()));
  5957. }
  5958. const FunctionDecl *Definition = nullptr;
  5959. Stmt *Body = FD->getBody(Definition);
  5960. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5961. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5962. Result, ResultSlot))
  5963. return false;
  5964. if (!CovariantAdjustmentPath.empty() &&
  5965. !HandleCovariantReturnAdjustment(Info, E, Result,
  5966. CovariantAdjustmentPath))
  5967. return false;
  5968. return true;
  5969. }
  5970. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5971. return StmtVisitorTy::Visit(E->getInitializer());
  5972. }
  5973. bool VisitInitListExpr(const InitListExpr *E) {
  5974. if (E->getNumInits() == 0)
  5975. return DerivedZeroInitialization(E);
  5976. if (E->getNumInits() == 1)
  5977. return StmtVisitorTy::Visit(E->getInit(0));
  5978. return Error(E);
  5979. }
  5980. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5981. return DerivedZeroInitialization(E);
  5982. }
  5983. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5984. return DerivedZeroInitialization(E);
  5985. }
  5986. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5987. return DerivedZeroInitialization(E);
  5988. }
  5989. /// A member expression where the object is a prvalue is itself a prvalue.
  5990. bool VisitMemberExpr(const MemberExpr *E) {
  5991. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5992. "missing temporary materialization conversion");
  5993. assert(!E->isArrow() && "missing call to bound member function?");
  5994. APValue Val;
  5995. if (!Evaluate(Val, Info, E->getBase()))
  5996. return false;
  5997. QualType BaseTy = E->getBase()->getType();
  5998. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5999. if (!FD) return Error(E);
  6000. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  6001. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6002. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6003. // Note: there is no lvalue base here. But this case should only ever
  6004. // happen in C or in C++98, where we cannot be evaluating a constexpr
  6005. // constructor, which is the only case the base matters.
  6006. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  6007. SubobjectDesignator Designator(BaseTy);
  6008. Designator.addDeclUnchecked(FD);
  6009. APValue Result;
  6010. return extractSubobject(Info, E, Obj, Designator, Result) &&
  6011. DerivedSuccess(Result, E);
  6012. }
  6013. bool VisitCastExpr(const CastExpr *E) {
  6014. switch (E->getCastKind()) {
  6015. default:
  6016. break;
  6017. case CK_AtomicToNonAtomic: {
  6018. APValue AtomicVal;
  6019. // This does not need to be done in place even for class/array types:
  6020. // atomic-to-non-atomic conversion implies copying the object
  6021. // representation.
  6022. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  6023. return false;
  6024. return DerivedSuccess(AtomicVal, E);
  6025. }
  6026. case CK_NoOp:
  6027. case CK_UserDefinedConversion:
  6028. return StmtVisitorTy::Visit(E->getSubExpr());
  6029. case CK_LValueToRValue: {
  6030. LValue LVal;
  6031. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  6032. return false;
  6033. APValue RVal;
  6034. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6035. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6036. LVal, RVal))
  6037. return false;
  6038. return DerivedSuccess(RVal, E);
  6039. }
  6040. case CK_LValueToRValueBitCast: {
  6041. APValue DestValue, SourceValue;
  6042. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  6043. return false;
  6044. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  6045. return false;
  6046. return DerivedSuccess(DestValue, E);
  6047. }
  6048. }
  6049. return Error(E);
  6050. }
  6051. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  6052. return VisitUnaryPostIncDec(UO);
  6053. }
  6054. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  6055. return VisitUnaryPostIncDec(UO);
  6056. }
  6057. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  6058. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6059. return Error(UO);
  6060. LValue LVal;
  6061. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  6062. return false;
  6063. APValue RVal;
  6064. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  6065. UO->isIncrementOp(), &RVal))
  6066. return false;
  6067. return DerivedSuccess(RVal, UO);
  6068. }
  6069. bool VisitStmtExpr(const StmtExpr *E) {
  6070. // We will have checked the full-expressions inside the statement expression
  6071. // when they were completed, and don't need to check them again now.
  6072. if (Info.checkingForUndefinedBehavior())
  6073. return Error(E);
  6074. const CompoundStmt *CS = E->getSubStmt();
  6075. if (CS->body_empty())
  6076. return true;
  6077. BlockScopeRAII Scope(Info);
  6078. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  6079. BE = CS->body_end();
  6080. /**/; ++BI) {
  6081. if (BI + 1 == BE) {
  6082. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  6083. if (!FinalExpr) {
  6084. Info.FFDiag((*BI)->getBeginLoc(),
  6085. diag::note_constexpr_stmt_expr_unsupported);
  6086. return false;
  6087. }
  6088. return this->Visit(FinalExpr) && Scope.destroy();
  6089. }
  6090. APValue ReturnValue;
  6091. StmtResult Result = { ReturnValue, nullptr };
  6092. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  6093. if (ESR != ESR_Succeeded) {
  6094. // FIXME: If the statement-expression terminated due to 'return',
  6095. // 'break', or 'continue', it would be nice to propagate that to
  6096. // the outer statement evaluation rather than bailing out.
  6097. if (ESR != ESR_Failed)
  6098. Info.FFDiag((*BI)->getBeginLoc(),
  6099. diag::note_constexpr_stmt_expr_unsupported);
  6100. return false;
  6101. }
  6102. }
  6103. llvm_unreachable("Return from function from the loop above.");
  6104. }
  6105. /// Visit a value which is evaluated, but whose value is ignored.
  6106. void VisitIgnoredValue(const Expr *E) {
  6107. EvaluateIgnoredValue(Info, E);
  6108. }
  6109. /// Potentially visit a MemberExpr's base expression.
  6110. void VisitIgnoredBaseExpression(const Expr *E) {
  6111. // While MSVC doesn't evaluate the base expression, it does diagnose the
  6112. // presence of side-effecting behavior.
  6113. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  6114. return;
  6115. VisitIgnoredValue(E);
  6116. }
  6117. };
  6118. } // namespace
  6119. //===----------------------------------------------------------------------===//
  6120. // Common base class for lvalue and temporary evaluation.
  6121. //===----------------------------------------------------------------------===//
  6122. namespace {
  6123. template<class Derived>
  6124. class LValueExprEvaluatorBase
  6125. : public ExprEvaluatorBase<Derived> {
  6126. protected:
  6127. LValue &Result;
  6128. bool InvalidBaseOK;
  6129. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  6130. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  6131. bool Success(APValue::LValueBase B) {
  6132. Result.set(B);
  6133. return true;
  6134. }
  6135. bool evaluatePointer(const Expr *E, LValue &Result) {
  6136. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  6137. }
  6138. public:
  6139. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  6140. : ExprEvaluatorBaseTy(Info), Result(Result),
  6141. InvalidBaseOK(InvalidBaseOK) {}
  6142. bool Success(const APValue &V, const Expr *E) {
  6143. Result.setFrom(this->Info.Ctx, V);
  6144. return true;
  6145. }
  6146. bool VisitMemberExpr(const MemberExpr *E) {
  6147. // Handle non-static data members.
  6148. QualType BaseTy;
  6149. bool EvalOK;
  6150. if (E->isArrow()) {
  6151. EvalOK = evaluatePointer(E->getBase(), Result);
  6152. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  6153. } else if (E->getBase()->isRValue()) {
  6154. assert(E->getBase()->getType()->isRecordType());
  6155. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  6156. BaseTy = E->getBase()->getType();
  6157. } else {
  6158. EvalOK = this->Visit(E->getBase());
  6159. BaseTy = E->getBase()->getType();
  6160. }
  6161. if (!EvalOK) {
  6162. if (!InvalidBaseOK)
  6163. return false;
  6164. Result.setInvalid(E);
  6165. return true;
  6166. }
  6167. const ValueDecl *MD = E->getMemberDecl();
  6168. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  6169. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6170. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6171. (void)BaseTy;
  6172. if (!HandleLValueMember(this->Info, E, Result, FD))
  6173. return false;
  6174. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  6175. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  6176. return false;
  6177. } else
  6178. return this->Error(E);
  6179. if (MD->getType()->isReferenceType()) {
  6180. APValue RefValue;
  6181. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  6182. RefValue))
  6183. return false;
  6184. return Success(RefValue, E);
  6185. }
  6186. return true;
  6187. }
  6188. bool VisitBinaryOperator(const BinaryOperator *E) {
  6189. switch (E->getOpcode()) {
  6190. default:
  6191. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6192. case BO_PtrMemD:
  6193. case BO_PtrMemI:
  6194. return HandleMemberPointerAccess(this->Info, E, Result);
  6195. }
  6196. }
  6197. bool VisitCastExpr(const CastExpr *E) {
  6198. switch (E->getCastKind()) {
  6199. default:
  6200. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6201. case CK_DerivedToBase:
  6202. case CK_UncheckedDerivedToBase:
  6203. if (!this->Visit(E->getSubExpr()))
  6204. return false;
  6205. // Now figure out the necessary offset to add to the base LV to get from
  6206. // the derived class to the base class.
  6207. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  6208. Result);
  6209. }
  6210. }
  6211. };
  6212. }
  6213. //===----------------------------------------------------------------------===//
  6214. // LValue Evaluation
  6215. //
  6216. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  6217. // function designators (in C), decl references to void objects (in C), and
  6218. // temporaries (if building with -Wno-address-of-temporary).
  6219. //
  6220. // LValue evaluation produces values comprising a base expression of one of the
  6221. // following types:
  6222. // - Declarations
  6223. // * VarDecl
  6224. // * FunctionDecl
  6225. // - Literals
  6226. // * CompoundLiteralExpr in C (and in global scope in C++)
  6227. // * StringLiteral
  6228. // * PredefinedExpr
  6229. // * ObjCStringLiteralExpr
  6230. // * ObjCEncodeExpr
  6231. // * AddrLabelExpr
  6232. // * BlockExpr
  6233. // * CallExpr for a MakeStringConstant builtin
  6234. // - typeid(T) expressions, as TypeInfoLValues
  6235. // - Locals and temporaries
  6236. // * MaterializeTemporaryExpr
  6237. // * Any Expr, with a CallIndex indicating the function in which the temporary
  6238. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  6239. // from the AST (FIXME).
  6240. // * A MaterializeTemporaryExpr that has static storage duration, with no
  6241. // CallIndex, for a lifetime-extended temporary.
  6242. // plus an offset in bytes.
  6243. //===----------------------------------------------------------------------===//
  6244. namespace {
  6245. class LValueExprEvaluator
  6246. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  6247. public:
  6248. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  6249. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  6250. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  6251. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  6252. bool VisitDeclRefExpr(const DeclRefExpr *E);
  6253. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  6254. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  6255. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  6256. bool VisitMemberExpr(const MemberExpr *E);
  6257. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  6258. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  6259. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  6260. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  6261. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  6262. bool VisitUnaryDeref(const UnaryOperator *E);
  6263. bool VisitUnaryReal(const UnaryOperator *E);
  6264. bool VisitUnaryImag(const UnaryOperator *E);
  6265. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  6266. return VisitUnaryPreIncDec(UO);
  6267. }
  6268. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  6269. return VisitUnaryPreIncDec(UO);
  6270. }
  6271. bool VisitBinAssign(const BinaryOperator *BO);
  6272. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  6273. bool VisitCastExpr(const CastExpr *E) {
  6274. switch (E->getCastKind()) {
  6275. default:
  6276. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6277. case CK_LValueBitCast:
  6278. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6279. if (!Visit(E->getSubExpr()))
  6280. return false;
  6281. Result.Designator.setInvalid();
  6282. return true;
  6283. case CK_BaseToDerived:
  6284. if (!Visit(E->getSubExpr()))
  6285. return false;
  6286. return HandleBaseToDerivedCast(Info, E, Result);
  6287. case CK_Dynamic:
  6288. if (!Visit(E->getSubExpr()))
  6289. return false;
  6290. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6291. }
  6292. }
  6293. };
  6294. } // end anonymous namespace
  6295. /// Evaluate an expression as an lvalue. This can be legitimately called on
  6296. /// expressions which are not glvalues, in three cases:
  6297. /// * function designators in C, and
  6298. /// * "extern void" objects
  6299. /// * @selector() expressions in Objective-C
  6300. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  6301. bool InvalidBaseOK) {
  6302. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  6303. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  6304. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6305. }
  6306. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  6307. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  6308. return Success(FD);
  6309. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  6310. return VisitVarDecl(E, VD);
  6311. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  6312. return Visit(BD->getBinding());
  6313. return Error(E);
  6314. }
  6315. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  6316. // If we are within a lambda's call operator, check whether the 'VD' referred
  6317. // to within 'E' actually represents a lambda-capture that maps to a
  6318. // data-member/field within the closure object, and if so, evaluate to the
  6319. // field or what the field refers to.
  6320. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  6321. isa<DeclRefExpr>(E) &&
  6322. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  6323. // We don't always have a complete capture-map when checking or inferring if
  6324. // the function call operator meets the requirements of a constexpr function
  6325. // - but we don't need to evaluate the captures to determine constexprness
  6326. // (dcl.constexpr C++17).
  6327. if (Info.checkingPotentialConstantExpression())
  6328. return false;
  6329. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  6330. // Start with 'Result' referring to the complete closure object...
  6331. Result = *Info.CurrentCall->This;
  6332. // ... then update it to refer to the field of the closure object
  6333. // that represents the capture.
  6334. if (!HandleLValueMember(Info, E, Result, FD))
  6335. return false;
  6336. // And if the field is of reference type, update 'Result' to refer to what
  6337. // the field refers to.
  6338. if (FD->getType()->isReferenceType()) {
  6339. APValue RVal;
  6340. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  6341. RVal))
  6342. return false;
  6343. Result.setFrom(Info.Ctx, RVal);
  6344. }
  6345. return true;
  6346. }
  6347. }
  6348. CallStackFrame *Frame = nullptr;
  6349. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  6350. // Only if a local variable was declared in the function currently being
  6351. // evaluated, do we expect to be able to find its value in the current
  6352. // frame. (Otherwise it was likely declared in an enclosing context and
  6353. // could either have a valid evaluatable value (for e.g. a constexpr
  6354. // variable) or be ill-formed (and trigger an appropriate evaluation
  6355. // diagnostic)).
  6356. if (Info.CurrentCall->Callee &&
  6357. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  6358. Frame = Info.CurrentCall;
  6359. }
  6360. }
  6361. if (!VD->getType()->isReferenceType()) {
  6362. if (Frame) {
  6363. Result.set({VD, Frame->Index,
  6364. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  6365. return true;
  6366. }
  6367. return Success(VD);
  6368. }
  6369. APValue *V;
  6370. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  6371. return false;
  6372. if (!V->hasValue()) {
  6373. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  6374. // adjust the diagnostic to say that.
  6375. if (!Info.checkingPotentialConstantExpression())
  6376. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  6377. return false;
  6378. }
  6379. return Success(*V, E);
  6380. }
  6381. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  6382. const MaterializeTemporaryExpr *E) {
  6383. // Walk through the expression to find the materialized temporary itself.
  6384. SmallVector<const Expr *, 2> CommaLHSs;
  6385. SmallVector<SubobjectAdjustment, 2> Adjustments;
  6386. const Expr *Inner = E->GetTemporaryExpr()->
  6387. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  6388. // If we passed any comma operators, evaluate their LHSs.
  6389. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  6390. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  6391. return false;
  6392. // A materialized temporary with static storage duration can appear within the
  6393. // result of a constant expression evaluation, so we need to preserve its
  6394. // value for use outside this evaluation.
  6395. APValue *Value;
  6396. if (E->getStorageDuration() == SD_Static) {
  6397. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  6398. *Value = APValue();
  6399. Result.set(E);
  6400. } else {
  6401. Value = &Info.CurrentCall->createTemporary(
  6402. E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
  6403. }
  6404. QualType Type = Inner->getType();
  6405. // Materialize the temporary itself.
  6406. if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
  6407. *Value = APValue();
  6408. return false;
  6409. }
  6410. // Adjust our lvalue to refer to the desired subobject.
  6411. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  6412. --I;
  6413. switch (Adjustments[I].Kind) {
  6414. case SubobjectAdjustment::DerivedToBaseAdjustment:
  6415. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  6416. Type, Result))
  6417. return false;
  6418. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  6419. break;
  6420. case SubobjectAdjustment::FieldAdjustment:
  6421. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  6422. return false;
  6423. Type = Adjustments[I].Field->getType();
  6424. break;
  6425. case SubobjectAdjustment::MemberPointerAdjustment:
  6426. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  6427. Adjustments[I].Ptr.RHS))
  6428. return false;
  6429. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  6430. break;
  6431. }
  6432. }
  6433. return true;
  6434. }
  6435. bool
  6436. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6437. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  6438. "lvalue compound literal in c++?");
  6439. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  6440. // only see this when folding in C, so there's no standard to follow here.
  6441. return Success(E);
  6442. }
  6443. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  6444. TypeInfoLValue TypeInfo;
  6445. if (!E->isPotentiallyEvaluated()) {
  6446. if (E->isTypeOperand())
  6447. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  6448. else
  6449. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  6450. } else {
  6451. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  6452. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  6453. << E->getExprOperand()->getType()
  6454. << E->getExprOperand()->getSourceRange();
  6455. }
  6456. if (!Visit(E->getExprOperand()))
  6457. return false;
  6458. Optional<DynamicType> DynType =
  6459. ComputeDynamicType(Info, E, Result, AK_TypeId);
  6460. if (!DynType)
  6461. return false;
  6462. TypeInfo =
  6463. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  6464. }
  6465. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  6466. }
  6467. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  6468. return Success(E);
  6469. }
  6470. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6471. // Handle static data members.
  6472. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6473. VisitIgnoredBaseExpression(E->getBase());
  6474. return VisitVarDecl(E, VD);
  6475. }
  6476. // Handle static member functions.
  6477. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6478. if (MD->isStatic()) {
  6479. VisitIgnoredBaseExpression(E->getBase());
  6480. return Success(MD);
  6481. }
  6482. }
  6483. // Handle non-static data members.
  6484. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6485. }
  6486. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6487. // FIXME: Deal with vectors as array subscript bases.
  6488. if (E->getBase()->getType()->isVectorType())
  6489. return Error(E);
  6490. bool Success = true;
  6491. if (!evaluatePointer(E->getBase(), Result)) {
  6492. if (!Info.noteFailure())
  6493. return false;
  6494. Success = false;
  6495. }
  6496. APSInt Index;
  6497. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6498. return false;
  6499. return Success &&
  6500. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6501. }
  6502. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6503. return evaluatePointer(E->getSubExpr(), Result);
  6504. }
  6505. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6506. if (!Visit(E->getSubExpr()))
  6507. return false;
  6508. // __real is a no-op on scalar lvalues.
  6509. if (E->getSubExpr()->getType()->isAnyComplexType())
  6510. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6511. return true;
  6512. }
  6513. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6514. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6515. "lvalue __imag__ on scalar?");
  6516. if (!Visit(E->getSubExpr()))
  6517. return false;
  6518. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6519. return true;
  6520. }
  6521. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6522. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6523. return Error(UO);
  6524. if (!this->Visit(UO->getSubExpr()))
  6525. return false;
  6526. return handleIncDec(
  6527. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6528. UO->isIncrementOp(), nullptr);
  6529. }
  6530. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6531. const CompoundAssignOperator *CAO) {
  6532. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6533. return Error(CAO);
  6534. APValue RHS;
  6535. // The overall lvalue result is the result of evaluating the LHS.
  6536. if (!this->Visit(CAO->getLHS())) {
  6537. if (Info.noteFailure())
  6538. Evaluate(RHS, this->Info, CAO->getRHS());
  6539. return false;
  6540. }
  6541. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6542. return false;
  6543. return handleCompoundAssignment(
  6544. this->Info, CAO,
  6545. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6546. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6547. }
  6548. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6549. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6550. return Error(E);
  6551. APValue NewVal;
  6552. if (!this->Visit(E->getLHS())) {
  6553. if (Info.noteFailure())
  6554. Evaluate(NewVal, this->Info, E->getRHS());
  6555. return false;
  6556. }
  6557. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6558. return false;
  6559. if (Info.getLangOpts().CPlusPlus2a &&
  6560. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6561. return false;
  6562. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6563. NewVal);
  6564. }
  6565. //===----------------------------------------------------------------------===//
  6566. // Pointer Evaluation
  6567. //===----------------------------------------------------------------------===//
  6568. /// Attempts to compute the number of bytes available at the pointer
  6569. /// returned by a function with the alloc_size attribute. Returns true if we
  6570. /// were successful. Places an unsigned number into `Result`.
  6571. ///
  6572. /// This expects the given CallExpr to be a call to a function with an
  6573. /// alloc_size attribute.
  6574. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6575. const CallExpr *Call,
  6576. llvm::APInt &Result) {
  6577. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6578. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6579. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6580. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6581. if (Call->getNumArgs() <= SizeArgNo)
  6582. return false;
  6583. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6584. Expr::EvalResult ExprResult;
  6585. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6586. return false;
  6587. Into = ExprResult.Val.getInt();
  6588. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6589. return false;
  6590. Into = Into.zextOrSelf(BitsInSizeT);
  6591. return true;
  6592. };
  6593. APSInt SizeOfElem;
  6594. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6595. return false;
  6596. if (!AllocSize->getNumElemsParam().isValid()) {
  6597. Result = std::move(SizeOfElem);
  6598. return true;
  6599. }
  6600. APSInt NumberOfElems;
  6601. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6602. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6603. return false;
  6604. bool Overflow;
  6605. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6606. if (Overflow)
  6607. return false;
  6608. Result = std::move(BytesAvailable);
  6609. return true;
  6610. }
  6611. /// Convenience function. LVal's base must be a call to an alloc_size
  6612. /// function.
  6613. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6614. const LValue &LVal,
  6615. llvm::APInt &Result) {
  6616. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6617. "Can't get the size of a non alloc_size function");
  6618. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6619. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6620. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6621. }
  6622. /// Attempts to evaluate the given LValueBase as the result of a call to
  6623. /// a function with the alloc_size attribute. If it was possible to do so, this
  6624. /// function will return true, make Result's Base point to said function call,
  6625. /// and mark Result's Base as invalid.
  6626. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6627. LValue &Result) {
  6628. if (Base.isNull())
  6629. return false;
  6630. // Because we do no form of static analysis, we only support const variables.
  6631. //
  6632. // Additionally, we can't support parameters, nor can we support static
  6633. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6634. // we have no clue what they'll be assigned to).
  6635. const auto *VD =
  6636. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6637. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6638. return false;
  6639. const Expr *Init = VD->getAnyInitializer();
  6640. if (!Init)
  6641. return false;
  6642. const Expr *E = Init->IgnoreParens();
  6643. if (!tryUnwrapAllocSizeCall(E))
  6644. return false;
  6645. // Store E instead of E unwrapped so that the type of the LValue's base is
  6646. // what the user wanted.
  6647. Result.setInvalid(E);
  6648. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6649. Result.addUnsizedArray(Info, E, Pointee);
  6650. return true;
  6651. }
  6652. namespace {
  6653. class PointerExprEvaluator
  6654. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6655. LValue &Result;
  6656. bool InvalidBaseOK;
  6657. bool Success(const Expr *E) {
  6658. Result.set(E);
  6659. return true;
  6660. }
  6661. bool evaluateLValue(const Expr *E, LValue &Result) {
  6662. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6663. }
  6664. bool evaluatePointer(const Expr *E, LValue &Result) {
  6665. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6666. }
  6667. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6668. public:
  6669. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6670. : ExprEvaluatorBaseTy(info), Result(Result),
  6671. InvalidBaseOK(InvalidBaseOK) {}
  6672. bool Success(const APValue &V, const Expr *E) {
  6673. Result.setFrom(Info.Ctx, V);
  6674. return true;
  6675. }
  6676. bool ZeroInitialization(const Expr *E) {
  6677. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  6678. Result.setNull(E->getType(), TargetVal);
  6679. return true;
  6680. }
  6681. bool VisitBinaryOperator(const BinaryOperator *E);
  6682. bool VisitCastExpr(const CastExpr* E);
  6683. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6684. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6685. { return Success(E); }
  6686. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6687. if (E->isExpressibleAsConstantInitializer())
  6688. return Success(E);
  6689. if (Info.noteFailure())
  6690. EvaluateIgnoredValue(Info, E->getSubExpr());
  6691. return Error(E);
  6692. }
  6693. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6694. { return Success(E); }
  6695. bool VisitCallExpr(const CallExpr *E);
  6696. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6697. bool VisitBlockExpr(const BlockExpr *E) {
  6698. if (!E->getBlockDecl()->hasCaptures())
  6699. return Success(E);
  6700. return Error(E);
  6701. }
  6702. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6703. // Can't look at 'this' when checking a potential constant expression.
  6704. if (Info.checkingPotentialConstantExpression())
  6705. return false;
  6706. if (!Info.CurrentCall->This) {
  6707. if (Info.getLangOpts().CPlusPlus11)
  6708. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6709. else
  6710. Info.FFDiag(E);
  6711. return false;
  6712. }
  6713. Result = *Info.CurrentCall->This;
  6714. // If we are inside a lambda's call operator, the 'this' expression refers
  6715. // to the enclosing '*this' object (either by value or reference) which is
  6716. // either copied into the closure object's field that represents the '*this'
  6717. // or refers to '*this'.
  6718. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6719. // Update 'Result' to refer to the data member/field of the closure object
  6720. // that represents the '*this' capture.
  6721. if (!HandleLValueMember(Info, E, Result,
  6722. Info.CurrentCall->LambdaThisCaptureField))
  6723. return false;
  6724. // If we captured '*this' by reference, replace the field with its referent.
  6725. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6726. ->isPointerType()) {
  6727. APValue RVal;
  6728. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6729. RVal))
  6730. return false;
  6731. Result.setFrom(Info.Ctx, RVal);
  6732. }
  6733. }
  6734. return true;
  6735. }
  6736. bool VisitCXXNewExpr(const CXXNewExpr *E);
  6737. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6738. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6739. APValue LValResult = E->EvaluateInContext(
  6740. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6741. Result.setFrom(Info.Ctx, LValResult);
  6742. return true;
  6743. }
  6744. // FIXME: Missing: @protocol, @selector
  6745. };
  6746. } // end anonymous namespace
  6747. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6748. bool InvalidBaseOK) {
  6749. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6750. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6751. }
  6752. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6753. if (E->getOpcode() != BO_Add &&
  6754. E->getOpcode() != BO_Sub)
  6755. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6756. const Expr *PExp = E->getLHS();
  6757. const Expr *IExp = E->getRHS();
  6758. if (IExp->getType()->isPointerType())
  6759. std::swap(PExp, IExp);
  6760. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6761. if (!EvalPtrOK && !Info.noteFailure())
  6762. return false;
  6763. llvm::APSInt Offset;
  6764. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6765. return false;
  6766. if (E->getOpcode() == BO_Sub)
  6767. negateAsSigned(Offset);
  6768. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6769. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6770. }
  6771. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6772. return evaluateLValue(E->getSubExpr(), Result);
  6773. }
  6774. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6775. const Expr *SubExpr = E->getSubExpr();
  6776. switch (E->getCastKind()) {
  6777. default:
  6778. break;
  6779. case CK_BitCast:
  6780. case CK_CPointerToObjCPointerCast:
  6781. case CK_BlockPointerToObjCPointerCast:
  6782. case CK_AnyPointerToBlockPointerCast:
  6783. case CK_AddressSpaceConversion:
  6784. if (!Visit(SubExpr))
  6785. return false;
  6786. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6787. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6788. // also static_casts, but we disallow them as a resolution to DR1312.
  6789. if (!E->getType()->isVoidPointerType()) {
  6790. Result.Designator.setInvalid();
  6791. if (SubExpr->getType()->isVoidPointerType())
  6792. CCEDiag(E, diag::note_constexpr_invalid_cast)
  6793. << 3 << SubExpr->getType();
  6794. else
  6795. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6796. }
  6797. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  6798. ZeroInitialization(E);
  6799. return true;
  6800. case CK_DerivedToBase:
  6801. case CK_UncheckedDerivedToBase:
  6802. if (!evaluatePointer(E->getSubExpr(), Result))
  6803. return false;
  6804. if (!Result.Base && Result.Offset.isZero())
  6805. return true;
  6806. // Now figure out the necessary offset to add to the base LV to get from
  6807. // the derived class to the base class.
  6808. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  6809. castAs<PointerType>()->getPointeeType(),
  6810. Result);
  6811. case CK_BaseToDerived:
  6812. if (!Visit(E->getSubExpr()))
  6813. return false;
  6814. if (!Result.Base && Result.Offset.isZero())
  6815. return true;
  6816. return HandleBaseToDerivedCast(Info, E, Result);
  6817. case CK_Dynamic:
  6818. if (!Visit(E->getSubExpr()))
  6819. return false;
  6820. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6821. case CK_NullToPointer:
  6822. VisitIgnoredValue(E->getSubExpr());
  6823. return ZeroInitialization(E);
  6824. case CK_IntegralToPointer: {
  6825. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6826. APValue Value;
  6827. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  6828. break;
  6829. if (Value.isInt()) {
  6830. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  6831. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  6832. Result.Base = (Expr*)nullptr;
  6833. Result.InvalidBase = false;
  6834. Result.Offset = CharUnits::fromQuantity(N);
  6835. Result.Designator.setInvalid();
  6836. Result.IsNullPtr = false;
  6837. return true;
  6838. } else {
  6839. // Cast is of an lvalue, no need to change value.
  6840. Result.setFrom(Info.Ctx, Value);
  6841. return true;
  6842. }
  6843. }
  6844. case CK_ArrayToPointerDecay: {
  6845. if (SubExpr->isGLValue()) {
  6846. if (!evaluateLValue(SubExpr, Result))
  6847. return false;
  6848. } else {
  6849. APValue &Value = Info.CurrentCall->createTemporary(
  6850. SubExpr, SubExpr->getType(), false, Result);
  6851. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  6852. return false;
  6853. }
  6854. // The result is a pointer to the first element of the array.
  6855. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  6856. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6857. Result.addArray(Info, E, CAT);
  6858. else
  6859. Result.addUnsizedArray(Info, E, AT->getElementType());
  6860. return true;
  6861. }
  6862. case CK_FunctionToPointerDecay:
  6863. return evaluateLValue(SubExpr, Result);
  6864. case CK_LValueToRValue: {
  6865. LValue LVal;
  6866. if (!evaluateLValue(E->getSubExpr(), LVal))
  6867. return false;
  6868. APValue RVal;
  6869. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6870. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6871. LVal, RVal))
  6872. return InvalidBaseOK &&
  6873. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  6874. return Success(RVal, E);
  6875. }
  6876. }
  6877. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6878. }
  6879. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  6880. UnaryExprOrTypeTrait ExprKind) {
  6881. // C++ [expr.alignof]p3:
  6882. // When alignof is applied to a reference type, the result is the
  6883. // alignment of the referenced type.
  6884. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  6885. T = Ref->getPointeeType();
  6886. if (T.getQualifiers().hasUnaligned())
  6887. return CharUnits::One();
  6888. const bool AlignOfReturnsPreferred =
  6889. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  6890. // __alignof is defined to return the preferred alignment.
  6891. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  6892. // as well.
  6893. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  6894. return Info.Ctx.toCharUnitsFromBits(
  6895. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  6896. // alignof and _Alignof are defined to return the ABI alignment.
  6897. else if (ExprKind == UETT_AlignOf)
  6898. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  6899. else
  6900. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  6901. }
  6902. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  6903. UnaryExprOrTypeTrait ExprKind) {
  6904. E = E->IgnoreParens();
  6905. // The kinds of expressions that we have special-case logic here for
  6906. // should be kept up to date with the special checks for those
  6907. // expressions in Sema.
  6908. // alignof decl is always accepted, even if it doesn't make sense: we default
  6909. // to 1 in those cases.
  6910. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6911. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  6912. /*RefAsPointee*/true);
  6913. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  6914. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  6915. /*RefAsPointee*/true);
  6916. return GetAlignOfType(Info, E->getType(), ExprKind);
  6917. }
  6918. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  6919. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6920. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6921. return true;
  6922. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6923. return false;
  6924. Result.setInvalid(E);
  6925. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6926. Result.addUnsizedArray(Info, E, PointeeTy);
  6927. return true;
  6928. }
  6929. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6930. if (IsStringLiteralCall(E))
  6931. return Success(E);
  6932. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6933. return VisitBuiltinCallExpr(E, BuiltinOp);
  6934. return visitNonBuiltinCallExpr(E);
  6935. }
  6936. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6937. unsigned BuiltinOp) {
  6938. switch (BuiltinOp) {
  6939. case Builtin::BI__builtin_addressof:
  6940. return evaluateLValue(E->getArg(0), Result);
  6941. case Builtin::BI__builtin_assume_aligned: {
  6942. // We need to be very careful here because: if the pointer does not have the
  6943. // asserted alignment, then the behavior is undefined, and undefined
  6944. // behavior is non-constant.
  6945. if (!evaluatePointer(E->getArg(0), Result))
  6946. return false;
  6947. LValue OffsetResult(Result);
  6948. APSInt Alignment;
  6949. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6950. return false;
  6951. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6952. if (E->getNumArgs() > 2) {
  6953. APSInt Offset;
  6954. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6955. return false;
  6956. int64_t AdditionalOffset = -Offset.getZExtValue();
  6957. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6958. }
  6959. // If there is a base object, then it must have the correct alignment.
  6960. if (OffsetResult.Base) {
  6961. CharUnits BaseAlignment;
  6962. if (const ValueDecl *VD =
  6963. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6964. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6965. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6966. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6967. } else {
  6968. BaseAlignment = GetAlignOfType(
  6969. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6970. }
  6971. if (BaseAlignment < Align) {
  6972. Result.Designator.setInvalid();
  6973. // FIXME: Add support to Diagnostic for long / long long.
  6974. CCEDiag(E->getArg(0),
  6975. diag::note_constexpr_baa_insufficient_alignment) << 0
  6976. << (unsigned)BaseAlignment.getQuantity()
  6977. << (unsigned)Align.getQuantity();
  6978. return false;
  6979. }
  6980. }
  6981. // The offset must also have the correct alignment.
  6982. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6983. Result.Designator.setInvalid();
  6984. (OffsetResult.Base
  6985. ? CCEDiag(E->getArg(0),
  6986. diag::note_constexpr_baa_insufficient_alignment) << 1
  6987. : CCEDiag(E->getArg(0),
  6988. diag::note_constexpr_baa_value_insufficient_alignment))
  6989. << (int)OffsetResult.Offset.getQuantity()
  6990. << (unsigned)Align.getQuantity();
  6991. return false;
  6992. }
  6993. return true;
  6994. }
  6995. case Builtin::BI__builtin_launder:
  6996. return evaluatePointer(E->getArg(0), Result);
  6997. case Builtin::BIstrchr:
  6998. case Builtin::BIwcschr:
  6999. case Builtin::BImemchr:
  7000. case Builtin::BIwmemchr:
  7001. if (Info.getLangOpts().CPlusPlus11)
  7002. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7003. << /*isConstexpr*/0 << /*isConstructor*/0
  7004. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7005. else
  7006. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7007. LLVM_FALLTHROUGH;
  7008. case Builtin::BI__builtin_strchr:
  7009. case Builtin::BI__builtin_wcschr:
  7010. case Builtin::BI__builtin_memchr:
  7011. case Builtin::BI__builtin_char_memchr:
  7012. case Builtin::BI__builtin_wmemchr: {
  7013. if (!Visit(E->getArg(0)))
  7014. return false;
  7015. APSInt Desired;
  7016. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  7017. return false;
  7018. uint64_t MaxLength = uint64_t(-1);
  7019. if (BuiltinOp != Builtin::BIstrchr &&
  7020. BuiltinOp != Builtin::BIwcschr &&
  7021. BuiltinOp != Builtin::BI__builtin_strchr &&
  7022. BuiltinOp != Builtin::BI__builtin_wcschr) {
  7023. APSInt N;
  7024. if (!EvaluateInteger(E->getArg(2), N, Info))
  7025. return false;
  7026. MaxLength = N.getExtValue();
  7027. }
  7028. // We cannot find the value if there are no candidates to match against.
  7029. if (MaxLength == 0u)
  7030. return ZeroInitialization(E);
  7031. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  7032. Result.Designator.Invalid)
  7033. return false;
  7034. QualType CharTy = Result.Designator.getType(Info.Ctx);
  7035. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  7036. BuiltinOp == Builtin::BI__builtin_memchr;
  7037. assert(IsRawByte ||
  7038. Info.Ctx.hasSameUnqualifiedType(
  7039. CharTy, E->getArg(0)->getType()->getPointeeType()));
  7040. // Pointers to const void may point to objects of incomplete type.
  7041. if (IsRawByte && CharTy->isIncompleteType()) {
  7042. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  7043. return false;
  7044. }
  7045. // Give up on byte-oriented matching against multibyte elements.
  7046. // FIXME: We can compare the bytes in the correct order.
  7047. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  7048. return false;
  7049. // Figure out what value we're actually looking for (after converting to
  7050. // the corresponding unsigned type if necessary).
  7051. uint64_t DesiredVal;
  7052. bool StopAtNull = false;
  7053. switch (BuiltinOp) {
  7054. case Builtin::BIstrchr:
  7055. case Builtin::BI__builtin_strchr:
  7056. // strchr compares directly to the passed integer, and therefore
  7057. // always fails if given an int that is not a char.
  7058. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  7059. E->getArg(1)->getType(),
  7060. Desired),
  7061. Desired))
  7062. return ZeroInitialization(E);
  7063. StopAtNull = true;
  7064. LLVM_FALLTHROUGH;
  7065. case Builtin::BImemchr:
  7066. case Builtin::BI__builtin_memchr:
  7067. case Builtin::BI__builtin_char_memchr:
  7068. // memchr compares by converting both sides to unsigned char. That's also
  7069. // correct for strchr if we get this far (to cope with plain char being
  7070. // unsigned in the strchr case).
  7071. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  7072. break;
  7073. case Builtin::BIwcschr:
  7074. case Builtin::BI__builtin_wcschr:
  7075. StopAtNull = true;
  7076. LLVM_FALLTHROUGH;
  7077. case Builtin::BIwmemchr:
  7078. case Builtin::BI__builtin_wmemchr:
  7079. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  7080. DesiredVal = Desired.getZExtValue();
  7081. break;
  7082. }
  7083. for (; MaxLength; --MaxLength) {
  7084. APValue Char;
  7085. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  7086. !Char.isInt())
  7087. return false;
  7088. if (Char.getInt().getZExtValue() == DesiredVal)
  7089. return true;
  7090. if (StopAtNull && !Char.getInt())
  7091. break;
  7092. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  7093. return false;
  7094. }
  7095. // Not found: return nullptr.
  7096. return ZeroInitialization(E);
  7097. }
  7098. case Builtin::BImemcpy:
  7099. case Builtin::BImemmove:
  7100. case Builtin::BIwmemcpy:
  7101. case Builtin::BIwmemmove:
  7102. if (Info.getLangOpts().CPlusPlus11)
  7103. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7104. << /*isConstexpr*/0 << /*isConstructor*/0
  7105. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7106. else
  7107. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7108. LLVM_FALLTHROUGH;
  7109. case Builtin::BI__builtin_memcpy:
  7110. case Builtin::BI__builtin_memmove:
  7111. case Builtin::BI__builtin_wmemcpy:
  7112. case Builtin::BI__builtin_wmemmove: {
  7113. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  7114. BuiltinOp == Builtin::BIwmemmove ||
  7115. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  7116. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7117. bool Move = BuiltinOp == Builtin::BImemmove ||
  7118. BuiltinOp == Builtin::BIwmemmove ||
  7119. BuiltinOp == Builtin::BI__builtin_memmove ||
  7120. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7121. // The result of mem* is the first argument.
  7122. if (!Visit(E->getArg(0)))
  7123. return false;
  7124. LValue Dest = Result;
  7125. LValue Src;
  7126. if (!EvaluatePointer(E->getArg(1), Src, Info))
  7127. return false;
  7128. APSInt N;
  7129. if (!EvaluateInteger(E->getArg(2), N, Info))
  7130. return false;
  7131. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  7132. // If the size is zero, we treat this as always being a valid no-op.
  7133. // (Even if one of the src and dest pointers is null.)
  7134. if (!N)
  7135. return true;
  7136. // Otherwise, if either of the operands is null, we can't proceed. Don't
  7137. // try to determine the type of the copied objects, because there aren't
  7138. // any.
  7139. if (!Src.Base || !Dest.Base) {
  7140. APValue Val;
  7141. (!Src.Base ? Src : Dest).moveInto(Val);
  7142. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  7143. << Move << WChar << !!Src.Base
  7144. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  7145. return false;
  7146. }
  7147. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  7148. return false;
  7149. // We require that Src and Dest are both pointers to arrays of
  7150. // trivially-copyable type. (For the wide version, the designator will be
  7151. // invalid if the designated object is not a wchar_t.)
  7152. QualType T = Dest.Designator.getType(Info.Ctx);
  7153. QualType SrcT = Src.Designator.getType(Info.Ctx);
  7154. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  7155. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  7156. return false;
  7157. }
  7158. if (T->isIncompleteType()) {
  7159. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  7160. return false;
  7161. }
  7162. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  7163. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  7164. return false;
  7165. }
  7166. // Figure out how many T's we're copying.
  7167. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  7168. if (!WChar) {
  7169. uint64_t Remainder;
  7170. llvm::APInt OrigN = N;
  7171. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  7172. if (Remainder) {
  7173. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7174. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  7175. << (unsigned)TSize;
  7176. return false;
  7177. }
  7178. }
  7179. // Check that the copying will remain within the arrays, just so that we
  7180. // can give a more meaningful diagnostic. This implicitly also checks that
  7181. // N fits into 64 bits.
  7182. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  7183. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  7184. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  7185. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7186. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  7187. << N.toString(10, /*Signed*/false);
  7188. return false;
  7189. }
  7190. uint64_t NElems = N.getZExtValue();
  7191. uint64_t NBytes = NElems * TSize;
  7192. // Check for overlap.
  7193. int Direction = 1;
  7194. if (HasSameBase(Src, Dest)) {
  7195. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  7196. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  7197. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  7198. // Dest is inside the source region.
  7199. if (!Move) {
  7200. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7201. return false;
  7202. }
  7203. // For memmove and friends, copy backwards.
  7204. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  7205. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  7206. return false;
  7207. Direction = -1;
  7208. } else if (!Move && SrcOffset >= DestOffset &&
  7209. SrcOffset - DestOffset < NBytes) {
  7210. // Src is inside the destination region for memcpy: invalid.
  7211. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7212. return false;
  7213. }
  7214. }
  7215. while (true) {
  7216. APValue Val;
  7217. // FIXME: Set WantObjectRepresentation to true if we're copying a
  7218. // char-like type?
  7219. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  7220. !handleAssignment(Info, E, Dest, T, Val))
  7221. return false;
  7222. // Do not iterate past the last element; if we're copying backwards, that
  7223. // might take us off the start of the array.
  7224. if (--NElems == 0)
  7225. return true;
  7226. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  7227. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  7228. return false;
  7229. }
  7230. }
  7231. default:
  7232. return visitNonBuiltinCallExpr(E);
  7233. }
  7234. }
  7235. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7236. APValue &Result, const InitListExpr *ILE,
  7237. QualType AllocType);
  7238. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  7239. if (!Info.getLangOpts().CPlusPlus2a)
  7240. Info.CCEDiag(E, diag::note_constexpr_new);
  7241. // We cannot speculatively evaluate a delete expression.
  7242. if (Info.SpeculativeEvaluationDepth)
  7243. return false;
  7244. FunctionDecl *OperatorNew = E->getOperatorNew();
  7245. if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  7246. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  7247. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  7248. return false;
  7249. }
  7250. bool IsNothrow = false;
  7251. if (E->getNumPlacementArgs()) {
  7252. // The only new-placement list we support is of the form (std::nothrow).
  7253. //
  7254. // FIXME: There is no restriction on this, but it's not clear that any
  7255. // other form makes any sense. We get here for cases such as:
  7256. //
  7257. // new (std::align_val_t{N}) X(int)
  7258. //
  7259. // (which should presumably be valid only if N is a multiple of
  7260. // alignof(int), and in any case can't be deallocated unless N is
  7261. // alignof(X) and X has new-extended alignment).
  7262. if (E->getNumPlacementArgs() != 1 ||
  7263. !E->getPlacementArg(0)->getType()->isNothrowT())
  7264. return Error(E, diag::note_constexpr_new_placement);
  7265. LValue Nothrow;
  7266. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  7267. return false;
  7268. IsNothrow = true;
  7269. }
  7270. const Expr *Init = E->getInitializer();
  7271. const InitListExpr *ResizedArrayILE = nullptr;
  7272. QualType AllocType = E->getAllocatedType();
  7273. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  7274. const Expr *Stripped = *ArraySize;
  7275. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  7276. Stripped = ICE->getSubExpr())
  7277. if (ICE->getCastKind() != CK_NoOp &&
  7278. ICE->getCastKind() != CK_IntegralCast)
  7279. break;
  7280. llvm::APSInt ArrayBound;
  7281. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  7282. return false;
  7283. // C++ [expr.new]p9:
  7284. // The expression is erroneous if:
  7285. // -- [...] its value before converting to size_t [or] applying the
  7286. // second standard conversion sequence is less than zero
  7287. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  7288. if (IsNothrow)
  7289. return ZeroInitialization(E);
  7290. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  7291. << ArrayBound << (*ArraySize)->getSourceRange();
  7292. return false;
  7293. }
  7294. // -- its value is such that the size of the allocated object would
  7295. // exceed the implementation-defined limit
  7296. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  7297. ArrayBound) >
  7298. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  7299. if (IsNothrow)
  7300. return ZeroInitialization(E);
  7301. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  7302. << ArrayBound << (*ArraySize)->getSourceRange();
  7303. return false;
  7304. }
  7305. // -- the new-initializer is a braced-init-list and the number of
  7306. // array elements for which initializers are provided [...]
  7307. // exceeds the number of elements to initialize
  7308. if (Init) {
  7309. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  7310. assert(CAT && "unexpected type for array initializer");
  7311. unsigned Bits =
  7312. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  7313. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  7314. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  7315. if (InitBound.ugt(AllocBound)) {
  7316. if (IsNothrow)
  7317. return ZeroInitialization(E);
  7318. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  7319. << AllocBound.toString(10, /*Signed=*/false)
  7320. << InitBound.toString(10, /*Signed=*/false)
  7321. << (*ArraySize)->getSourceRange();
  7322. return false;
  7323. }
  7324. // If the sizes differ, we must have an initializer list, and we need
  7325. // special handling for this case when we initialize.
  7326. if (InitBound != AllocBound)
  7327. ResizedArrayILE = cast<InitListExpr>(Init);
  7328. }
  7329. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
  7330. ArrayType::Normal, 0);
  7331. } else {
  7332. assert(!AllocType->isArrayType() &&
  7333. "array allocation with non-array new");
  7334. }
  7335. // Perform the allocation and obtain a pointer to the resulting object.
  7336. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  7337. if (!Val)
  7338. return false;
  7339. if (ResizedArrayILE) {
  7340. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  7341. AllocType))
  7342. return false;
  7343. } else if (Init) {
  7344. if (!EvaluateInPlace(*Val, Info, Result, Init))
  7345. return false;
  7346. } else {
  7347. *Val = getDefaultInitValue(AllocType);
  7348. }
  7349. // Array new returns a pointer to the first element, not a pointer to the
  7350. // array.
  7351. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  7352. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  7353. return true;
  7354. }
  7355. //===----------------------------------------------------------------------===//
  7356. // Member Pointer Evaluation
  7357. //===----------------------------------------------------------------------===//
  7358. namespace {
  7359. class MemberPointerExprEvaluator
  7360. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  7361. MemberPtr &Result;
  7362. bool Success(const ValueDecl *D) {
  7363. Result = MemberPtr(D);
  7364. return true;
  7365. }
  7366. public:
  7367. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  7368. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7369. bool Success(const APValue &V, const Expr *E) {
  7370. Result.setFrom(V);
  7371. return true;
  7372. }
  7373. bool ZeroInitialization(const Expr *E) {
  7374. return Success((const ValueDecl*)nullptr);
  7375. }
  7376. bool VisitCastExpr(const CastExpr *E);
  7377. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7378. };
  7379. } // end anonymous namespace
  7380. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  7381. EvalInfo &Info) {
  7382. assert(E->isRValue() && E->getType()->isMemberPointerType());
  7383. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  7384. }
  7385. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7386. switch (E->getCastKind()) {
  7387. default:
  7388. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7389. case CK_NullToMemberPointer:
  7390. VisitIgnoredValue(E->getSubExpr());
  7391. return ZeroInitialization(E);
  7392. case CK_BaseToDerivedMemberPointer: {
  7393. if (!Visit(E->getSubExpr()))
  7394. return false;
  7395. if (E->path_empty())
  7396. return true;
  7397. // Base-to-derived member pointer casts store the path in derived-to-base
  7398. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  7399. // the wrong end of the derived->base arc, so stagger the path by one class.
  7400. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  7401. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  7402. PathI != PathE; ++PathI) {
  7403. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7404. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  7405. if (!Result.castToDerived(Derived))
  7406. return Error(E);
  7407. }
  7408. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  7409. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  7410. return Error(E);
  7411. return true;
  7412. }
  7413. case CK_DerivedToBaseMemberPointer:
  7414. if (!Visit(E->getSubExpr()))
  7415. return false;
  7416. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7417. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7418. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7419. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7420. if (!Result.castToBase(Base))
  7421. return Error(E);
  7422. }
  7423. return true;
  7424. }
  7425. }
  7426. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7427. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  7428. // member can be formed.
  7429. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  7430. }
  7431. //===----------------------------------------------------------------------===//
  7432. // Record Evaluation
  7433. //===----------------------------------------------------------------------===//
  7434. namespace {
  7435. class RecordExprEvaluator
  7436. : public ExprEvaluatorBase<RecordExprEvaluator> {
  7437. const LValue &This;
  7438. APValue &Result;
  7439. public:
  7440. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  7441. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  7442. bool Success(const APValue &V, const Expr *E) {
  7443. Result = V;
  7444. return true;
  7445. }
  7446. bool ZeroInitialization(const Expr *E) {
  7447. return ZeroInitialization(E, E->getType());
  7448. }
  7449. bool ZeroInitialization(const Expr *E, QualType T);
  7450. bool VisitCallExpr(const CallExpr *E) {
  7451. return handleCallExpr(E, Result, &This);
  7452. }
  7453. bool VisitCastExpr(const CastExpr *E);
  7454. bool VisitInitListExpr(const InitListExpr *E);
  7455. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7456. return VisitCXXConstructExpr(E, E->getType());
  7457. }
  7458. bool VisitLambdaExpr(const LambdaExpr *E);
  7459. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  7460. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  7461. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  7462. bool VisitBinCmp(const BinaryOperator *E);
  7463. };
  7464. }
  7465. /// Perform zero-initialization on an object of non-union class type.
  7466. /// C++11 [dcl.init]p5:
  7467. /// To zero-initialize an object or reference of type T means:
  7468. /// [...]
  7469. /// -- if T is a (possibly cv-qualified) non-union class type,
  7470. /// each non-static data member and each base-class subobject is
  7471. /// zero-initialized
  7472. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  7473. const RecordDecl *RD,
  7474. const LValue &This, APValue &Result) {
  7475. assert(!RD->isUnion() && "Expected non-union class type");
  7476. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  7477. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  7478. std::distance(RD->field_begin(), RD->field_end()));
  7479. if (RD->isInvalidDecl()) return false;
  7480. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7481. if (CD) {
  7482. unsigned Index = 0;
  7483. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  7484. End = CD->bases_end(); I != End; ++I, ++Index) {
  7485. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  7486. LValue Subobject = This;
  7487. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  7488. return false;
  7489. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  7490. Result.getStructBase(Index)))
  7491. return false;
  7492. }
  7493. }
  7494. for (const auto *I : RD->fields()) {
  7495. // -- if T is a reference type, no initialization is performed.
  7496. if (I->getType()->isReferenceType())
  7497. continue;
  7498. LValue Subobject = This;
  7499. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  7500. return false;
  7501. ImplicitValueInitExpr VIE(I->getType());
  7502. if (!EvaluateInPlace(
  7503. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  7504. return false;
  7505. }
  7506. return true;
  7507. }
  7508. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  7509. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  7510. if (RD->isInvalidDecl()) return false;
  7511. if (RD->isUnion()) {
  7512. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  7513. // object's first non-static named data member is zero-initialized
  7514. RecordDecl::field_iterator I = RD->field_begin();
  7515. if (I == RD->field_end()) {
  7516. Result = APValue((const FieldDecl*)nullptr);
  7517. return true;
  7518. }
  7519. LValue Subobject = This;
  7520. if (!HandleLValueMember(Info, E, Subobject, *I))
  7521. return false;
  7522. Result = APValue(*I);
  7523. ImplicitValueInitExpr VIE(I->getType());
  7524. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  7525. }
  7526. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  7527. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  7528. return false;
  7529. }
  7530. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  7531. }
  7532. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7533. switch (E->getCastKind()) {
  7534. default:
  7535. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7536. case CK_ConstructorConversion:
  7537. return Visit(E->getSubExpr());
  7538. case CK_DerivedToBase:
  7539. case CK_UncheckedDerivedToBase: {
  7540. APValue DerivedObject;
  7541. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  7542. return false;
  7543. if (!DerivedObject.isStruct())
  7544. return Error(E->getSubExpr());
  7545. // Derived-to-base rvalue conversion: just slice off the derived part.
  7546. APValue *Value = &DerivedObject;
  7547. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  7548. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7549. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7550. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  7551. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7552. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  7553. RD = Base;
  7554. }
  7555. Result = *Value;
  7556. return true;
  7557. }
  7558. }
  7559. }
  7560. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7561. if (E->isTransparent())
  7562. return Visit(E->getInit(0));
  7563. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  7564. if (RD->isInvalidDecl()) return false;
  7565. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7566. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  7567. EvalInfo::EvaluatingConstructorRAII EvalObj(
  7568. Info,
  7569. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  7570. CXXRD && CXXRD->getNumBases());
  7571. if (RD->isUnion()) {
  7572. const FieldDecl *Field = E->getInitializedFieldInUnion();
  7573. Result = APValue(Field);
  7574. if (!Field)
  7575. return true;
  7576. // If the initializer list for a union does not contain any elements, the
  7577. // first element of the union is value-initialized.
  7578. // FIXME: The element should be initialized from an initializer list.
  7579. // Is this difference ever observable for initializer lists which
  7580. // we don't build?
  7581. ImplicitValueInitExpr VIE(Field->getType());
  7582. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  7583. LValue Subobject = This;
  7584. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  7585. return false;
  7586. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7587. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7588. isa<CXXDefaultInitExpr>(InitExpr));
  7589. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  7590. }
  7591. if (!Result.hasValue())
  7592. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  7593. std::distance(RD->field_begin(), RD->field_end()));
  7594. unsigned ElementNo = 0;
  7595. bool Success = true;
  7596. // Initialize base classes.
  7597. if (CXXRD && CXXRD->getNumBases()) {
  7598. for (const auto &Base : CXXRD->bases()) {
  7599. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7600. const Expr *Init = E->getInit(ElementNo);
  7601. LValue Subobject = This;
  7602. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7603. return false;
  7604. APValue &FieldVal = Result.getStructBase(ElementNo);
  7605. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7606. if (!Info.noteFailure())
  7607. return false;
  7608. Success = false;
  7609. }
  7610. ++ElementNo;
  7611. }
  7612. EvalObj.finishedConstructingBases();
  7613. }
  7614. // Initialize members.
  7615. for (const auto *Field : RD->fields()) {
  7616. // Anonymous bit-fields are not considered members of the class for
  7617. // purposes of aggregate initialization.
  7618. if (Field->isUnnamedBitfield())
  7619. continue;
  7620. LValue Subobject = This;
  7621. bool HaveInit = ElementNo < E->getNumInits();
  7622. // FIXME: Diagnostics here should point to the end of the initializer
  7623. // list, not the start.
  7624. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7625. Subobject, Field, &Layout))
  7626. return false;
  7627. // Perform an implicit value-initialization for members beyond the end of
  7628. // the initializer list.
  7629. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7630. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7631. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7632. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7633. isa<CXXDefaultInitExpr>(Init));
  7634. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7635. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7636. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7637. FieldVal, Field))) {
  7638. if (!Info.noteFailure())
  7639. return false;
  7640. Success = false;
  7641. }
  7642. }
  7643. return Success;
  7644. }
  7645. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7646. QualType T) {
  7647. // Note that E's type is not necessarily the type of our class here; we might
  7648. // be initializing an array element instead.
  7649. const CXXConstructorDecl *FD = E->getConstructor();
  7650. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7651. bool ZeroInit = E->requiresZeroInitialization();
  7652. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7653. // If we've already performed zero-initialization, we're already done.
  7654. if (Result.hasValue())
  7655. return true;
  7656. if (ZeroInit)
  7657. return ZeroInitialization(E, T);
  7658. Result = getDefaultInitValue(T);
  7659. return true;
  7660. }
  7661. const FunctionDecl *Definition = nullptr;
  7662. auto Body = FD->getBody(Definition);
  7663. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7664. return false;
  7665. // Avoid materializing a temporary for an elidable copy/move constructor.
  7666. if (E->isElidable() && !ZeroInit)
  7667. if (const MaterializeTemporaryExpr *ME
  7668. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7669. return Visit(ME->GetTemporaryExpr());
  7670. if (ZeroInit && !ZeroInitialization(E, T))
  7671. return false;
  7672. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7673. return HandleConstructorCall(E, This, Args,
  7674. cast<CXXConstructorDecl>(Definition), Info,
  7675. Result);
  7676. }
  7677. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7678. const CXXInheritedCtorInitExpr *E) {
  7679. if (!Info.CurrentCall) {
  7680. assert(Info.checkingPotentialConstantExpression());
  7681. return false;
  7682. }
  7683. const CXXConstructorDecl *FD = E->getConstructor();
  7684. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7685. return false;
  7686. const FunctionDecl *Definition = nullptr;
  7687. auto Body = FD->getBody(Definition);
  7688. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7689. return false;
  7690. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7691. cast<CXXConstructorDecl>(Definition), Info,
  7692. Result);
  7693. }
  7694. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7695. const CXXStdInitializerListExpr *E) {
  7696. const ConstantArrayType *ArrayType =
  7697. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7698. LValue Array;
  7699. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7700. return false;
  7701. // Get a pointer to the first element of the array.
  7702. Array.addArray(Info, E, ArrayType);
  7703. // FIXME: Perform the checks on the field types in SemaInit.
  7704. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7705. RecordDecl::field_iterator Field = Record->field_begin();
  7706. if (Field == Record->field_end())
  7707. return Error(E);
  7708. // Start pointer.
  7709. if (!Field->getType()->isPointerType() ||
  7710. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7711. ArrayType->getElementType()))
  7712. return Error(E);
  7713. // FIXME: What if the initializer_list type has base classes, etc?
  7714. Result = APValue(APValue::UninitStruct(), 0, 2);
  7715. Array.moveInto(Result.getStructField(0));
  7716. if (++Field == Record->field_end())
  7717. return Error(E);
  7718. if (Field->getType()->isPointerType() &&
  7719. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7720. ArrayType->getElementType())) {
  7721. // End pointer.
  7722. if (!HandleLValueArrayAdjustment(Info, E, Array,
  7723. ArrayType->getElementType(),
  7724. ArrayType->getSize().getZExtValue()))
  7725. return false;
  7726. Array.moveInto(Result.getStructField(1));
  7727. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  7728. // Length.
  7729. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  7730. else
  7731. return Error(E);
  7732. if (++Field != Record->field_end())
  7733. return Error(E);
  7734. return true;
  7735. }
  7736. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  7737. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  7738. if (ClosureClass->isInvalidDecl())
  7739. return false;
  7740. const size_t NumFields =
  7741. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  7742. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  7743. E->capture_init_end()) &&
  7744. "The number of lambda capture initializers should equal the number of "
  7745. "fields within the closure type");
  7746. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  7747. // Iterate through all the lambda's closure object's fields and initialize
  7748. // them.
  7749. auto *CaptureInitIt = E->capture_init_begin();
  7750. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  7751. bool Success = true;
  7752. for (const auto *Field : ClosureClass->fields()) {
  7753. assert(CaptureInitIt != E->capture_init_end());
  7754. // Get the initializer for this field
  7755. Expr *const CurFieldInit = *CaptureInitIt++;
  7756. // If there is no initializer, either this is a VLA or an error has
  7757. // occurred.
  7758. if (!CurFieldInit)
  7759. return Error(E);
  7760. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7761. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  7762. if (!Info.keepEvaluatingAfterFailure())
  7763. return false;
  7764. Success = false;
  7765. }
  7766. ++CaptureIt;
  7767. }
  7768. return Success;
  7769. }
  7770. static bool EvaluateRecord(const Expr *E, const LValue &This,
  7771. APValue &Result, EvalInfo &Info) {
  7772. assert(E->isRValue() && E->getType()->isRecordType() &&
  7773. "can't evaluate expression as a record rvalue");
  7774. return RecordExprEvaluator(Info, This, Result).Visit(E);
  7775. }
  7776. //===----------------------------------------------------------------------===//
  7777. // Temporary Evaluation
  7778. //
  7779. // Temporaries are represented in the AST as rvalues, but generally behave like
  7780. // lvalues. The full-object of which the temporary is a subobject is implicitly
  7781. // materialized so that a reference can bind to it.
  7782. //===----------------------------------------------------------------------===//
  7783. namespace {
  7784. class TemporaryExprEvaluator
  7785. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  7786. public:
  7787. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  7788. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  7789. /// Visit an expression which constructs the value of this temporary.
  7790. bool VisitConstructExpr(const Expr *E) {
  7791. APValue &Value =
  7792. Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
  7793. return EvaluateInPlace(Value, Info, Result, E);
  7794. }
  7795. bool VisitCastExpr(const CastExpr *E) {
  7796. switch (E->getCastKind()) {
  7797. default:
  7798. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7799. case CK_ConstructorConversion:
  7800. return VisitConstructExpr(E->getSubExpr());
  7801. }
  7802. }
  7803. bool VisitInitListExpr(const InitListExpr *E) {
  7804. return VisitConstructExpr(E);
  7805. }
  7806. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7807. return VisitConstructExpr(E);
  7808. }
  7809. bool VisitCallExpr(const CallExpr *E) {
  7810. return VisitConstructExpr(E);
  7811. }
  7812. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  7813. return VisitConstructExpr(E);
  7814. }
  7815. bool VisitLambdaExpr(const LambdaExpr *E) {
  7816. return VisitConstructExpr(E);
  7817. }
  7818. };
  7819. } // end anonymous namespace
  7820. /// Evaluate an expression of record type as a temporary.
  7821. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  7822. assert(E->isRValue() && E->getType()->isRecordType());
  7823. return TemporaryExprEvaluator(Info, Result).Visit(E);
  7824. }
  7825. //===----------------------------------------------------------------------===//
  7826. // Vector Evaluation
  7827. //===----------------------------------------------------------------------===//
  7828. namespace {
  7829. class VectorExprEvaluator
  7830. : public ExprEvaluatorBase<VectorExprEvaluator> {
  7831. APValue &Result;
  7832. public:
  7833. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  7834. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7835. bool Success(ArrayRef<APValue> V, const Expr *E) {
  7836. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  7837. // FIXME: remove this APValue copy.
  7838. Result = APValue(V.data(), V.size());
  7839. return true;
  7840. }
  7841. bool Success(const APValue &V, const Expr *E) {
  7842. assert(V.isVector());
  7843. Result = V;
  7844. return true;
  7845. }
  7846. bool ZeroInitialization(const Expr *E);
  7847. bool VisitUnaryReal(const UnaryOperator *E)
  7848. { return Visit(E->getSubExpr()); }
  7849. bool VisitCastExpr(const CastExpr* E);
  7850. bool VisitInitListExpr(const InitListExpr *E);
  7851. bool VisitUnaryImag(const UnaryOperator *E);
  7852. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  7853. // binary comparisons, binary and/or/xor,
  7854. // shufflevector, ExtVectorElementExpr
  7855. };
  7856. } // end anonymous namespace
  7857. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  7858. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  7859. return VectorExprEvaluator(Info, Result).Visit(E);
  7860. }
  7861. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7862. const VectorType *VTy = E->getType()->castAs<VectorType>();
  7863. unsigned NElts = VTy->getNumElements();
  7864. const Expr *SE = E->getSubExpr();
  7865. QualType SETy = SE->getType();
  7866. switch (E->getCastKind()) {
  7867. case CK_VectorSplat: {
  7868. APValue Val = APValue();
  7869. if (SETy->isIntegerType()) {
  7870. APSInt IntResult;
  7871. if (!EvaluateInteger(SE, IntResult, Info))
  7872. return false;
  7873. Val = APValue(std::move(IntResult));
  7874. } else if (SETy->isRealFloatingType()) {
  7875. APFloat FloatResult(0.0);
  7876. if (!EvaluateFloat(SE, FloatResult, Info))
  7877. return false;
  7878. Val = APValue(std::move(FloatResult));
  7879. } else {
  7880. return Error(E);
  7881. }
  7882. // Splat and create vector APValue.
  7883. SmallVector<APValue, 4> Elts(NElts, Val);
  7884. return Success(Elts, E);
  7885. }
  7886. case CK_BitCast: {
  7887. // Evaluate the operand into an APInt we can extract from.
  7888. llvm::APInt SValInt;
  7889. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  7890. return false;
  7891. // Extract the elements
  7892. QualType EltTy = VTy->getElementType();
  7893. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  7894. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  7895. SmallVector<APValue, 4> Elts;
  7896. if (EltTy->isRealFloatingType()) {
  7897. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  7898. unsigned FloatEltSize = EltSize;
  7899. if (&Sem == &APFloat::x87DoubleExtended())
  7900. FloatEltSize = 80;
  7901. for (unsigned i = 0; i < NElts; i++) {
  7902. llvm::APInt Elt;
  7903. if (BigEndian)
  7904. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  7905. else
  7906. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  7907. Elts.push_back(APValue(APFloat(Sem, Elt)));
  7908. }
  7909. } else if (EltTy->isIntegerType()) {
  7910. for (unsigned i = 0; i < NElts; i++) {
  7911. llvm::APInt Elt;
  7912. if (BigEndian)
  7913. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  7914. else
  7915. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  7916. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  7917. }
  7918. } else {
  7919. return Error(E);
  7920. }
  7921. return Success(Elts, E);
  7922. }
  7923. default:
  7924. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7925. }
  7926. }
  7927. bool
  7928. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7929. const VectorType *VT = E->getType()->castAs<VectorType>();
  7930. unsigned NumInits = E->getNumInits();
  7931. unsigned NumElements = VT->getNumElements();
  7932. QualType EltTy = VT->getElementType();
  7933. SmallVector<APValue, 4> Elements;
  7934. // The number of initializers can be less than the number of
  7935. // vector elements. For OpenCL, this can be due to nested vector
  7936. // initialization. For GCC compatibility, missing trailing elements
  7937. // should be initialized with zeroes.
  7938. unsigned CountInits = 0, CountElts = 0;
  7939. while (CountElts < NumElements) {
  7940. // Handle nested vector initialization.
  7941. if (CountInits < NumInits
  7942. && E->getInit(CountInits)->getType()->isVectorType()) {
  7943. APValue v;
  7944. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  7945. return Error(E);
  7946. unsigned vlen = v.getVectorLength();
  7947. for (unsigned j = 0; j < vlen; j++)
  7948. Elements.push_back(v.getVectorElt(j));
  7949. CountElts += vlen;
  7950. } else if (EltTy->isIntegerType()) {
  7951. llvm::APSInt sInt(32);
  7952. if (CountInits < NumInits) {
  7953. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  7954. return false;
  7955. } else // trailing integer zero.
  7956. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  7957. Elements.push_back(APValue(sInt));
  7958. CountElts++;
  7959. } else {
  7960. llvm::APFloat f(0.0);
  7961. if (CountInits < NumInits) {
  7962. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  7963. return false;
  7964. } else // trailing float zero.
  7965. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  7966. Elements.push_back(APValue(f));
  7967. CountElts++;
  7968. }
  7969. CountInits++;
  7970. }
  7971. return Success(Elements, E);
  7972. }
  7973. bool
  7974. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  7975. const VectorType *VT = E->getType()->getAs<VectorType>();
  7976. QualType EltTy = VT->getElementType();
  7977. APValue ZeroElement;
  7978. if (EltTy->isIntegerType())
  7979. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  7980. else
  7981. ZeroElement =
  7982. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  7983. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  7984. return Success(Elements, E);
  7985. }
  7986. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7987. VisitIgnoredValue(E->getSubExpr());
  7988. return ZeroInitialization(E);
  7989. }
  7990. //===----------------------------------------------------------------------===//
  7991. // Array Evaluation
  7992. //===----------------------------------------------------------------------===//
  7993. namespace {
  7994. class ArrayExprEvaluator
  7995. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  7996. const LValue &This;
  7997. APValue &Result;
  7998. public:
  7999. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  8000. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  8001. bool Success(const APValue &V, const Expr *E) {
  8002. assert(V.isArray() && "expected array");
  8003. Result = V;
  8004. return true;
  8005. }
  8006. bool ZeroInitialization(const Expr *E) {
  8007. const ConstantArrayType *CAT =
  8008. Info.Ctx.getAsConstantArrayType(E->getType());
  8009. if (!CAT)
  8010. return Error(E);
  8011. Result = APValue(APValue::UninitArray(), 0,
  8012. CAT->getSize().getZExtValue());
  8013. if (!Result.hasArrayFiller()) return true;
  8014. // Zero-initialize all elements.
  8015. LValue Subobject = This;
  8016. Subobject.addArray(Info, E, CAT);
  8017. ImplicitValueInitExpr VIE(CAT->getElementType());
  8018. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  8019. }
  8020. bool VisitCallExpr(const CallExpr *E) {
  8021. return handleCallExpr(E, Result, &This);
  8022. }
  8023. bool VisitInitListExpr(const InitListExpr *E,
  8024. QualType AllocType = QualType());
  8025. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  8026. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  8027. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  8028. const LValue &Subobject,
  8029. APValue *Value, QualType Type);
  8030. bool VisitStringLiteral(const StringLiteral *E,
  8031. QualType AllocType = QualType()) {
  8032. expandStringLiteral(Info, E, Result, AllocType);
  8033. return true;
  8034. }
  8035. };
  8036. } // end anonymous namespace
  8037. static bool EvaluateArray(const Expr *E, const LValue &This,
  8038. APValue &Result, EvalInfo &Info) {
  8039. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  8040. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  8041. }
  8042. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8043. APValue &Result, const InitListExpr *ILE,
  8044. QualType AllocType) {
  8045. assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
  8046. "not an array rvalue");
  8047. return ArrayExprEvaluator(Info, This, Result)
  8048. .VisitInitListExpr(ILE, AllocType);
  8049. }
  8050. // Return true iff the given array filler may depend on the element index.
  8051. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  8052. // For now, just whitelist non-class value-initialization and initialization
  8053. // lists comprised of them.
  8054. if (isa<ImplicitValueInitExpr>(FillerExpr))
  8055. return false;
  8056. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  8057. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  8058. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  8059. return true;
  8060. }
  8061. return false;
  8062. }
  8063. return true;
  8064. }
  8065. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  8066. QualType AllocType) {
  8067. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  8068. AllocType.isNull() ? E->getType() : AllocType);
  8069. if (!CAT)
  8070. return Error(E);
  8071. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  8072. // an appropriately-typed string literal enclosed in braces.
  8073. if (E->isStringLiteralInit()) {
  8074. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
  8075. // FIXME: Support ObjCEncodeExpr here once we support it in
  8076. // ArrayExprEvaluator generally.
  8077. if (!SL)
  8078. return Error(E);
  8079. return VisitStringLiteral(SL, AllocType);
  8080. }
  8081. bool Success = true;
  8082. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  8083. "zero-initialized array shouldn't have any initialized elts");
  8084. APValue Filler;
  8085. if (Result.isArray() && Result.hasArrayFiller())
  8086. Filler = Result.getArrayFiller();
  8087. unsigned NumEltsToInit = E->getNumInits();
  8088. unsigned NumElts = CAT->getSize().getZExtValue();
  8089. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  8090. // If the initializer might depend on the array index, run it for each
  8091. // array element.
  8092. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  8093. NumEltsToInit = NumElts;
  8094. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  8095. << NumEltsToInit << ".\n");
  8096. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  8097. // If the array was previously zero-initialized, preserve the
  8098. // zero-initialized values.
  8099. if (Filler.hasValue()) {
  8100. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  8101. Result.getArrayInitializedElt(I) = Filler;
  8102. if (Result.hasArrayFiller())
  8103. Result.getArrayFiller() = Filler;
  8104. }
  8105. LValue Subobject = This;
  8106. Subobject.addArray(Info, E, CAT);
  8107. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  8108. const Expr *Init =
  8109. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  8110. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8111. Info, Subobject, Init) ||
  8112. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  8113. CAT->getElementType(), 1)) {
  8114. if (!Info.noteFailure())
  8115. return false;
  8116. Success = false;
  8117. }
  8118. }
  8119. if (!Result.hasArrayFiller())
  8120. return Success;
  8121. // If we get here, we have a trivial filler, which we can just evaluate
  8122. // once and splat over the rest of the array elements.
  8123. assert(FillerExpr && "no array filler for incomplete init list");
  8124. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  8125. FillerExpr) && Success;
  8126. }
  8127. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  8128. LValue CommonLV;
  8129. if (E->getCommonExpr() &&
  8130. !Evaluate(Info.CurrentCall->createTemporary(
  8131. E->getCommonExpr(),
  8132. getStorageType(Info.Ctx, E->getCommonExpr()), false,
  8133. CommonLV),
  8134. Info, E->getCommonExpr()->getSourceExpr()))
  8135. return false;
  8136. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  8137. uint64_t Elements = CAT->getSize().getZExtValue();
  8138. Result = APValue(APValue::UninitArray(), Elements, Elements);
  8139. LValue Subobject = This;
  8140. Subobject.addArray(Info, E, CAT);
  8141. bool Success = true;
  8142. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  8143. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8144. Info, Subobject, E->getSubExpr()) ||
  8145. !HandleLValueArrayAdjustment(Info, E, Subobject,
  8146. CAT->getElementType(), 1)) {
  8147. if (!Info.noteFailure())
  8148. return false;
  8149. Success = false;
  8150. }
  8151. }
  8152. return Success;
  8153. }
  8154. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8155. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  8156. }
  8157. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8158. const LValue &Subobject,
  8159. APValue *Value,
  8160. QualType Type) {
  8161. bool HadZeroInit = Value->hasValue();
  8162. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  8163. unsigned N = CAT->getSize().getZExtValue();
  8164. // Preserve the array filler if we had prior zero-initialization.
  8165. APValue Filler =
  8166. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  8167. : APValue();
  8168. *Value = APValue(APValue::UninitArray(), N, N);
  8169. if (HadZeroInit)
  8170. for (unsigned I = 0; I != N; ++I)
  8171. Value->getArrayInitializedElt(I) = Filler;
  8172. // Initialize the elements.
  8173. LValue ArrayElt = Subobject;
  8174. ArrayElt.addArray(Info, E, CAT);
  8175. for (unsigned I = 0; I != N; ++I)
  8176. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  8177. CAT->getElementType()) ||
  8178. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  8179. CAT->getElementType(), 1))
  8180. return false;
  8181. return true;
  8182. }
  8183. if (!Type->isRecordType())
  8184. return Error(E);
  8185. return RecordExprEvaluator(Info, Subobject, *Value)
  8186. .VisitCXXConstructExpr(E, Type);
  8187. }
  8188. //===----------------------------------------------------------------------===//
  8189. // Integer Evaluation
  8190. //
  8191. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  8192. // types and back in constant folding. Integer values are thus represented
  8193. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  8194. //===----------------------------------------------------------------------===//
  8195. namespace {
  8196. class IntExprEvaluator
  8197. : public ExprEvaluatorBase<IntExprEvaluator> {
  8198. APValue &Result;
  8199. public:
  8200. IntExprEvaluator(EvalInfo &info, APValue &result)
  8201. : ExprEvaluatorBaseTy(info), Result(result) {}
  8202. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  8203. assert(E->getType()->isIntegralOrEnumerationType() &&
  8204. "Invalid evaluation result.");
  8205. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  8206. "Invalid evaluation result.");
  8207. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8208. "Invalid evaluation result.");
  8209. Result = APValue(SI);
  8210. return true;
  8211. }
  8212. bool Success(const llvm::APSInt &SI, const Expr *E) {
  8213. return Success(SI, E, Result);
  8214. }
  8215. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  8216. assert(E->getType()->isIntegralOrEnumerationType() &&
  8217. "Invalid evaluation result.");
  8218. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8219. "Invalid evaluation result.");
  8220. Result = APValue(APSInt(I));
  8221. Result.getInt().setIsUnsigned(
  8222. E->getType()->isUnsignedIntegerOrEnumerationType());
  8223. return true;
  8224. }
  8225. bool Success(const llvm::APInt &I, const Expr *E) {
  8226. return Success(I, E, Result);
  8227. }
  8228. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8229. assert(E->getType()->isIntegralOrEnumerationType() &&
  8230. "Invalid evaluation result.");
  8231. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  8232. return true;
  8233. }
  8234. bool Success(uint64_t Value, const Expr *E) {
  8235. return Success(Value, E, Result);
  8236. }
  8237. bool Success(CharUnits Size, const Expr *E) {
  8238. return Success(Size.getQuantity(), E);
  8239. }
  8240. bool Success(const APValue &V, const Expr *E) {
  8241. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  8242. Result = V;
  8243. return true;
  8244. }
  8245. return Success(V.getInt(), E);
  8246. }
  8247. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  8248. //===--------------------------------------------------------------------===//
  8249. // Visitor Methods
  8250. //===--------------------------------------------------------------------===//
  8251. bool VisitConstantExpr(const ConstantExpr *E);
  8252. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  8253. return Success(E->getValue(), E);
  8254. }
  8255. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  8256. return Success(E->getValue(), E);
  8257. }
  8258. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  8259. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  8260. if (CheckReferencedDecl(E, E->getDecl()))
  8261. return true;
  8262. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  8263. }
  8264. bool VisitMemberExpr(const MemberExpr *E) {
  8265. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  8266. VisitIgnoredBaseExpression(E->getBase());
  8267. return true;
  8268. }
  8269. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  8270. }
  8271. bool VisitCallExpr(const CallExpr *E);
  8272. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  8273. bool VisitBinaryOperator(const BinaryOperator *E);
  8274. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  8275. bool VisitUnaryOperator(const UnaryOperator *E);
  8276. bool VisitCastExpr(const CastExpr* E);
  8277. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  8278. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  8279. return Success(E->getValue(), E);
  8280. }
  8281. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  8282. return Success(E->getValue(), E);
  8283. }
  8284. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  8285. if (Info.ArrayInitIndex == uint64_t(-1)) {
  8286. // We were asked to evaluate this subexpression independent of the
  8287. // enclosing ArrayInitLoopExpr. We can't do that.
  8288. Info.FFDiag(E);
  8289. return false;
  8290. }
  8291. return Success(Info.ArrayInitIndex, E);
  8292. }
  8293. // Note, GNU defines __null as an integer, not a pointer.
  8294. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  8295. return ZeroInitialization(E);
  8296. }
  8297. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  8298. return Success(E->getValue(), E);
  8299. }
  8300. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  8301. return Success(E->getValue(), E);
  8302. }
  8303. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  8304. return Success(E->getValue(), E);
  8305. }
  8306. bool VisitUnaryReal(const UnaryOperator *E);
  8307. bool VisitUnaryImag(const UnaryOperator *E);
  8308. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  8309. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  8310. bool VisitSourceLocExpr(const SourceLocExpr *E);
  8311. // FIXME: Missing: array subscript of vector, member of vector
  8312. };
  8313. class FixedPointExprEvaluator
  8314. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  8315. APValue &Result;
  8316. public:
  8317. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  8318. : ExprEvaluatorBaseTy(info), Result(result) {}
  8319. bool Success(const llvm::APInt &I, const Expr *E) {
  8320. return Success(
  8321. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8322. }
  8323. bool Success(uint64_t Value, const Expr *E) {
  8324. return Success(
  8325. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8326. }
  8327. bool Success(const APValue &V, const Expr *E) {
  8328. return Success(V.getFixedPoint(), E);
  8329. }
  8330. bool Success(const APFixedPoint &V, const Expr *E) {
  8331. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  8332. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8333. "Invalid evaluation result.");
  8334. Result = APValue(V);
  8335. return true;
  8336. }
  8337. //===--------------------------------------------------------------------===//
  8338. // Visitor Methods
  8339. //===--------------------------------------------------------------------===//
  8340. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  8341. return Success(E->getValue(), E);
  8342. }
  8343. bool VisitCastExpr(const CastExpr *E);
  8344. bool VisitUnaryOperator(const UnaryOperator *E);
  8345. bool VisitBinaryOperator(const BinaryOperator *E);
  8346. };
  8347. } // end anonymous namespace
  8348. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  8349. /// produce either the integer value or a pointer.
  8350. ///
  8351. /// GCC has a heinous extension which folds casts between pointer types and
  8352. /// pointer-sized integral types. We support this by allowing the evaluation of
  8353. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  8354. /// Some simple arithmetic on such values is supported (they are treated much
  8355. /// like char*).
  8356. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  8357. EvalInfo &Info) {
  8358. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  8359. return IntExprEvaluator(Info, Result).Visit(E);
  8360. }
  8361. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  8362. APValue Val;
  8363. if (!EvaluateIntegerOrLValue(E, Val, Info))
  8364. return false;
  8365. if (!Val.isInt()) {
  8366. // FIXME: It would be better to produce the diagnostic for casting
  8367. // a pointer to an integer.
  8368. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8369. return false;
  8370. }
  8371. Result = Val.getInt();
  8372. return true;
  8373. }
  8374. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  8375. APValue Evaluated = E->EvaluateInContext(
  8376. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  8377. return Success(Evaluated, E);
  8378. }
  8379. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  8380. EvalInfo &Info) {
  8381. if (E->getType()->isFixedPointType()) {
  8382. APValue Val;
  8383. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  8384. return false;
  8385. if (!Val.isFixedPoint())
  8386. return false;
  8387. Result = Val.getFixedPoint();
  8388. return true;
  8389. }
  8390. return false;
  8391. }
  8392. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  8393. EvalInfo &Info) {
  8394. if (E->getType()->isIntegerType()) {
  8395. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  8396. APSInt Val;
  8397. if (!EvaluateInteger(E, Val, Info))
  8398. return false;
  8399. Result = APFixedPoint(Val, FXSema);
  8400. return true;
  8401. } else if (E->getType()->isFixedPointType()) {
  8402. return EvaluateFixedPoint(E, Result, Info);
  8403. }
  8404. return false;
  8405. }
  8406. /// Check whether the given declaration can be directly converted to an integral
  8407. /// rvalue. If not, no diagnostic is produced; there are other things we can
  8408. /// try.
  8409. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  8410. // Enums are integer constant exprs.
  8411. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  8412. // Check for signedness/width mismatches between E type and ECD value.
  8413. bool SameSign = (ECD->getInitVal().isSigned()
  8414. == E->getType()->isSignedIntegerOrEnumerationType());
  8415. bool SameWidth = (ECD->getInitVal().getBitWidth()
  8416. == Info.Ctx.getIntWidth(E->getType()));
  8417. if (SameSign && SameWidth)
  8418. return Success(ECD->getInitVal(), E);
  8419. else {
  8420. // Get rid of mismatch (otherwise Success assertions will fail)
  8421. // by computing a new value matching the type of E.
  8422. llvm::APSInt Val = ECD->getInitVal();
  8423. if (!SameSign)
  8424. Val.setIsSigned(!ECD->getInitVal().isSigned());
  8425. if (!SameWidth)
  8426. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  8427. return Success(Val, E);
  8428. }
  8429. }
  8430. return false;
  8431. }
  8432. /// Values returned by __builtin_classify_type, chosen to match the values
  8433. /// produced by GCC's builtin.
  8434. enum class GCCTypeClass {
  8435. None = -1,
  8436. Void = 0,
  8437. Integer = 1,
  8438. // GCC reserves 2 for character types, but instead classifies them as
  8439. // integers.
  8440. Enum = 3,
  8441. Bool = 4,
  8442. Pointer = 5,
  8443. // GCC reserves 6 for references, but appears to never use it (because
  8444. // expressions never have reference type, presumably).
  8445. PointerToDataMember = 7,
  8446. RealFloat = 8,
  8447. Complex = 9,
  8448. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  8449. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8450. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  8451. // uses 12 for that purpose, same as for a class or struct. Maybe it
  8452. // internally implements a pointer to member as a struct? Who knows.
  8453. PointerToMemberFunction = 12, // Not a bug, see above.
  8454. ClassOrStruct = 12,
  8455. Union = 13,
  8456. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  8457. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8458. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  8459. // literals.
  8460. };
  8461. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8462. /// as GCC.
  8463. static GCCTypeClass
  8464. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  8465. assert(!T->isDependentType() && "unexpected dependent type");
  8466. QualType CanTy = T.getCanonicalType();
  8467. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  8468. switch (CanTy->getTypeClass()) {
  8469. #define TYPE(ID, BASE)
  8470. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8471. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  8472. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8473. #include "clang/AST/TypeNodes.inc"
  8474. case Type::Auto:
  8475. case Type::DeducedTemplateSpecialization:
  8476. llvm_unreachable("unexpected non-canonical or dependent type");
  8477. case Type::Builtin:
  8478. switch (BT->getKind()) {
  8479. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  8480. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  8481. case BuiltinType::ID: return GCCTypeClass::Integer;
  8482. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  8483. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  8484. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  8485. case BuiltinType::ID: break;
  8486. #include "clang/AST/BuiltinTypes.def"
  8487. case BuiltinType::Void:
  8488. return GCCTypeClass::Void;
  8489. case BuiltinType::Bool:
  8490. return GCCTypeClass::Bool;
  8491. case BuiltinType::Char_U:
  8492. case BuiltinType::UChar:
  8493. case BuiltinType::WChar_U:
  8494. case BuiltinType::Char8:
  8495. case BuiltinType::Char16:
  8496. case BuiltinType::Char32:
  8497. case BuiltinType::UShort:
  8498. case BuiltinType::UInt:
  8499. case BuiltinType::ULong:
  8500. case BuiltinType::ULongLong:
  8501. case BuiltinType::UInt128:
  8502. return GCCTypeClass::Integer;
  8503. case BuiltinType::UShortAccum:
  8504. case BuiltinType::UAccum:
  8505. case BuiltinType::ULongAccum:
  8506. case BuiltinType::UShortFract:
  8507. case BuiltinType::UFract:
  8508. case BuiltinType::ULongFract:
  8509. case BuiltinType::SatUShortAccum:
  8510. case BuiltinType::SatUAccum:
  8511. case BuiltinType::SatULongAccum:
  8512. case BuiltinType::SatUShortFract:
  8513. case BuiltinType::SatUFract:
  8514. case BuiltinType::SatULongFract:
  8515. return GCCTypeClass::None;
  8516. case BuiltinType::NullPtr:
  8517. case BuiltinType::ObjCId:
  8518. case BuiltinType::ObjCClass:
  8519. case BuiltinType::ObjCSel:
  8520. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  8521. case BuiltinType::Id:
  8522. #include "clang/Basic/OpenCLImageTypes.def"
  8523. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  8524. case BuiltinType::Id:
  8525. #include "clang/Basic/OpenCLExtensionTypes.def"
  8526. case BuiltinType::OCLSampler:
  8527. case BuiltinType::OCLEvent:
  8528. case BuiltinType::OCLClkEvent:
  8529. case BuiltinType::OCLQueue:
  8530. case BuiltinType::OCLReserveID:
  8531. #define SVE_TYPE(Name, Id, SingletonId) \
  8532. case BuiltinType::Id:
  8533. #include "clang/Basic/AArch64SVEACLETypes.def"
  8534. return GCCTypeClass::None;
  8535. case BuiltinType::Dependent:
  8536. llvm_unreachable("unexpected dependent type");
  8537. };
  8538. llvm_unreachable("unexpected placeholder type");
  8539. case Type::Enum:
  8540. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  8541. case Type::Pointer:
  8542. case Type::ConstantArray:
  8543. case Type::VariableArray:
  8544. case Type::IncompleteArray:
  8545. case Type::FunctionNoProto:
  8546. case Type::FunctionProto:
  8547. return GCCTypeClass::Pointer;
  8548. case Type::MemberPointer:
  8549. return CanTy->isMemberDataPointerType()
  8550. ? GCCTypeClass::PointerToDataMember
  8551. : GCCTypeClass::PointerToMemberFunction;
  8552. case Type::Complex:
  8553. return GCCTypeClass::Complex;
  8554. case Type::Record:
  8555. return CanTy->isUnionType() ? GCCTypeClass::Union
  8556. : GCCTypeClass::ClassOrStruct;
  8557. case Type::Atomic:
  8558. // GCC classifies _Atomic T the same as T.
  8559. return EvaluateBuiltinClassifyType(
  8560. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  8561. case Type::BlockPointer:
  8562. case Type::Vector:
  8563. case Type::ExtVector:
  8564. case Type::ObjCObject:
  8565. case Type::ObjCInterface:
  8566. case Type::ObjCObjectPointer:
  8567. case Type::Pipe:
  8568. // GCC classifies vectors as None. We follow its lead and classify all
  8569. // other types that don't fit into the regular classification the same way.
  8570. return GCCTypeClass::None;
  8571. case Type::LValueReference:
  8572. case Type::RValueReference:
  8573. llvm_unreachable("invalid type for expression");
  8574. }
  8575. llvm_unreachable("unexpected type class");
  8576. }
  8577. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8578. /// as GCC.
  8579. static GCCTypeClass
  8580. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  8581. // If no argument was supplied, default to None. This isn't
  8582. // ideal, however it is what gcc does.
  8583. if (E->getNumArgs() == 0)
  8584. return GCCTypeClass::None;
  8585. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  8586. // being an ICE, but still folds it to a constant using the type of the first
  8587. // argument.
  8588. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  8589. }
  8590. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  8591. /// __builtin_constant_p when applied to the given pointer.
  8592. ///
  8593. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  8594. /// or it points to the first character of a string literal.
  8595. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  8596. APValue::LValueBase Base = LV.getLValueBase();
  8597. if (Base.isNull()) {
  8598. // A null base is acceptable.
  8599. return true;
  8600. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  8601. if (!isa<StringLiteral>(E))
  8602. return false;
  8603. return LV.getLValueOffset().isZero();
  8604. } else if (Base.is<TypeInfoLValue>()) {
  8605. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  8606. // evaluate to true.
  8607. return true;
  8608. } else {
  8609. // Any other base is not constant enough for GCC.
  8610. return false;
  8611. }
  8612. }
  8613. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  8614. /// GCC as we can manage.
  8615. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8616. // This evaluation is not permitted to have side-effects, so evaluate it in
  8617. // a speculative evaluation context.
  8618. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8619. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8620. // (even when the enclosing evaluation context otherwise requires a strict
  8621. // language-specific constant expression).
  8622. FoldConstant Fold(Info, true);
  8623. QualType ArgType = Arg->getType();
  8624. // __builtin_constant_p always has one operand. The rules which gcc follows
  8625. // are not precisely documented, but are as follows:
  8626. //
  8627. // - If the operand is of integral, floating, complex or enumeration type,
  8628. // and can be folded to a known value of that type, it returns 1.
  8629. // - If the operand can be folded to a pointer to the first character
  8630. // of a string literal (or such a pointer cast to an integral type)
  8631. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8632. //
  8633. // Otherwise, it returns 0.
  8634. //
  8635. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8636. // its support for this did not work prior to GCC 9 and is not yet well
  8637. // understood.
  8638. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8639. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8640. ArgType->isNullPtrType()) {
  8641. APValue V;
  8642. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8643. Fold.keepDiagnostics();
  8644. return false;
  8645. }
  8646. // For a pointer (possibly cast to integer), there are special rules.
  8647. if (V.getKind() == APValue::LValue)
  8648. return EvaluateBuiltinConstantPForLValue(V);
  8649. // Otherwise, any constant value is good enough.
  8650. return V.hasValue();
  8651. }
  8652. // Anything else isn't considered to be sufficiently constant.
  8653. return false;
  8654. }
  8655. /// Retrieves the "underlying object type" of the given expression,
  8656. /// as used by __builtin_object_size.
  8657. static QualType getObjectType(APValue::LValueBase B) {
  8658. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8659. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8660. return VD->getType();
  8661. } else if (const Expr *E = B.get<const Expr*>()) {
  8662. if (isa<CompoundLiteralExpr>(E))
  8663. return E->getType();
  8664. } else if (B.is<TypeInfoLValue>()) {
  8665. return B.getTypeInfoType();
  8666. } else if (B.is<DynamicAllocLValue>()) {
  8667. return B.getDynamicAllocType();
  8668. }
  8669. return QualType();
  8670. }
  8671. /// A more selective version of E->IgnoreParenCasts for
  8672. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8673. /// to change the type of E.
  8674. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8675. ///
  8676. /// Always returns an RValue with a pointer representation.
  8677. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8678. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8679. auto *NoParens = E->IgnoreParens();
  8680. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8681. if (Cast == nullptr)
  8682. return NoParens;
  8683. // We only conservatively allow a few kinds of casts, because this code is
  8684. // inherently a simple solution that seeks to support the common case.
  8685. auto CastKind = Cast->getCastKind();
  8686. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8687. CastKind != CK_AddressSpaceConversion)
  8688. return NoParens;
  8689. auto *SubExpr = Cast->getSubExpr();
  8690. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8691. return NoParens;
  8692. return ignorePointerCastsAndParens(SubExpr);
  8693. }
  8694. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8695. /// record layout. e.g.
  8696. /// struct { struct { int a, b; } fst, snd; } obj;
  8697. /// obj.fst // no
  8698. /// obj.snd // yes
  8699. /// obj.fst.a // no
  8700. /// obj.fst.b // no
  8701. /// obj.snd.a // no
  8702. /// obj.snd.b // yes
  8703. ///
  8704. /// Please note: this function is specialized for how __builtin_object_size
  8705. /// views "objects".
  8706. ///
  8707. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8708. /// correct result, it will always return true.
  8709. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8710. assert(!LVal.Designator.Invalid);
  8711. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8712. const RecordDecl *Parent = FD->getParent();
  8713. Invalid = Parent->isInvalidDecl();
  8714. if (Invalid || Parent->isUnion())
  8715. return true;
  8716. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8717. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8718. };
  8719. auto &Base = LVal.getLValueBase();
  8720. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  8721. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  8722. bool Invalid;
  8723. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8724. return Invalid;
  8725. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  8726. for (auto *FD : IFD->chain()) {
  8727. bool Invalid;
  8728. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  8729. return Invalid;
  8730. }
  8731. }
  8732. }
  8733. unsigned I = 0;
  8734. QualType BaseType = getType(Base);
  8735. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  8736. // If we don't know the array bound, conservatively assume we're looking at
  8737. // the final array element.
  8738. ++I;
  8739. if (BaseType->isIncompleteArrayType())
  8740. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  8741. else
  8742. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  8743. }
  8744. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  8745. const auto &Entry = LVal.Designator.Entries[I];
  8746. if (BaseType->isArrayType()) {
  8747. // Because __builtin_object_size treats arrays as objects, we can ignore
  8748. // the index iff this is the last array in the Designator.
  8749. if (I + 1 == E)
  8750. return true;
  8751. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  8752. uint64_t Index = Entry.getAsArrayIndex();
  8753. if (Index + 1 != CAT->getSize())
  8754. return false;
  8755. BaseType = CAT->getElementType();
  8756. } else if (BaseType->isAnyComplexType()) {
  8757. const auto *CT = BaseType->castAs<ComplexType>();
  8758. uint64_t Index = Entry.getAsArrayIndex();
  8759. if (Index != 1)
  8760. return false;
  8761. BaseType = CT->getElementType();
  8762. } else if (auto *FD = getAsField(Entry)) {
  8763. bool Invalid;
  8764. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8765. return Invalid;
  8766. BaseType = FD->getType();
  8767. } else {
  8768. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  8769. return false;
  8770. }
  8771. }
  8772. return true;
  8773. }
  8774. /// Tests to see if the LValue has a user-specified designator (that isn't
  8775. /// necessarily valid). Note that this always returns 'true' if the LValue has
  8776. /// an unsized array as its first designator entry, because there's currently no
  8777. /// way to tell if the user typed *foo or foo[0].
  8778. static bool refersToCompleteObject(const LValue &LVal) {
  8779. if (LVal.Designator.Invalid)
  8780. return false;
  8781. if (!LVal.Designator.Entries.empty())
  8782. return LVal.Designator.isMostDerivedAnUnsizedArray();
  8783. if (!LVal.InvalidBase)
  8784. return true;
  8785. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  8786. // the LValueBase.
  8787. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  8788. return !E || !isa<MemberExpr>(E);
  8789. }
  8790. /// Attempts to detect a user writing into a piece of memory that's impossible
  8791. /// to figure out the size of by just using types.
  8792. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  8793. const SubobjectDesignator &Designator = LVal.Designator;
  8794. // Notes:
  8795. // - Users can only write off of the end when we have an invalid base. Invalid
  8796. // bases imply we don't know where the memory came from.
  8797. // - We used to be a bit more aggressive here; we'd only be conservative if
  8798. // the array at the end was flexible, or if it had 0 or 1 elements. This
  8799. // broke some common standard library extensions (PR30346), but was
  8800. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  8801. // with some sort of whitelist. OTOH, it seems that GCC is always
  8802. // conservative with the last element in structs (if it's an array), so our
  8803. // current behavior is more compatible than a whitelisting approach would
  8804. // be.
  8805. return LVal.InvalidBase &&
  8806. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  8807. Designator.MostDerivedIsArrayElement &&
  8808. isDesignatorAtObjectEnd(Ctx, LVal);
  8809. }
  8810. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  8811. /// Fails if the conversion would cause loss of precision.
  8812. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  8813. CharUnits &Result) {
  8814. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  8815. if (Int.ugt(CharUnitsMax))
  8816. return false;
  8817. Result = CharUnits::fromQuantity(Int.getZExtValue());
  8818. return true;
  8819. }
  8820. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  8821. /// determine how many bytes exist from the beginning of the object to either
  8822. /// the end of the current subobject, or the end of the object itself, depending
  8823. /// on what the LValue looks like + the value of Type.
  8824. ///
  8825. /// If this returns false, the value of Result is undefined.
  8826. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  8827. unsigned Type, const LValue &LVal,
  8828. CharUnits &EndOffset) {
  8829. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  8830. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  8831. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  8832. return false;
  8833. return HandleSizeof(Info, ExprLoc, Ty, Result);
  8834. };
  8835. // We want to evaluate the size of the entire object. This is a valid fallback
  8836. // for when Type=1 and the designator is invalid, because we're asked for an
  8837. // upper-bound.
  8838. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  8839. // Type=3 wants a lower bound, so we can't fall back to this.
  8840. if (Type == 3 && !DetermineForCompleteObject)
  8841. return false;
  8842. llvm::APInt APEndOffset;
  8843. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8844. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8845. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8846. if (LVal.InvalidBase)
  8847. return false;
  8848. QualType BaseTy = getObjectType(LVal.getLValueBase());
  8849. return CheckedHandleSizeof(BaseTy, EndOffset);
  8850. }
  8851. // We want to evaluate the size of a subobject.
  8852. const SubobjectDesignator &Designator = LVal.Designator;
  8853. // The following is a moderately common idiom in C:
  8854. //
  8855. // struct Foo { int a; char c[1]; };
  8856. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  8857. // strcpy(&F->c[0], Bar);
  8858. //
  8859. // In order to not break too much legacy code, we need to support it.
  8860. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  8861. // If we can resolve this to an alloc_size call, we can hand that back,
  8862. // because we know for certain how many bytes there are to write to.
  8863. llvm::APInt APEndOffset;
  8864. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8865. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8866. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8867. // If we cannot determine the size of the initial allocation, then we can't
  8868. // given an accurate upper-bound. However, we are still able to give
  8869. // conservative lower-bounds for Type=3.
  8870. if (Type == 1)
  8871. return false;
  8872. }
  8873. CharUnits BytesPerElem;
  8874. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  8875. return false;
  8876. // According to the GCC documentation, we want the size of the subobject
  8877. // denoted by the pointer. But that's not quite right -- what we actually
  8878. // want is the size of the immediately-enclosing array, if there is one.
  8879. int64_t ElemsRemaining;
  8880. if (Designator.MostDerivedIsArrayElement &&
  8881. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  8882. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  8883. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  8884. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  8885. } else {
  8886. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  8887. }
  8888. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  8889. return true;
  8890. }
  8891. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  8892. /// returns true and stores the result in @p Size.
  8893. ///
  8894. /// If @p WasError is non-null, this will report whether the failure to evaluate
  8895. /// is to be treated as an Error in IntExprEvaluator.
  8896. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  8897. EvalInfo &Info, uint64_t &Size) {
  8898. // Determine the denoted object.
  8899. LValue LVal;
  8900. {
  8901. // The operand of __builtin_object_size is never evaluated for side-effects.
  8902. // If there are any, but we can determine the pointed-to object anyway, then
  8903. // ignore the side-effects.
  8904. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8905. IgnoreSideEffectsRAII Fold(Info);
  8906. if (E->isGLValue()) {
  8907. // It's possible for us to be given GLValues if we're called via
  8908. // Expr::tryEvaluateObjectSize.
  8909. APValue RVal;
  8910. if (!EvaluateAsRValue(Info, E, RVal))
  8911. return false;
  8912. LVal.setFrom(Info.Ctx, RVal);
  8913. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  8914. /*InvalidBaseOK=*/true))
  8915. return false;
  8916. }
  8917. // If we point to before the start of the object, there are no accessible
  8918. // bytes.
  8919. if (LVal.getLValueOffset().isNegative()) {
  8920. Size = 0;
  8921. return true;
  8922. }
  8923. CharUnits EndOffset;
  8924. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  8925. return false;
  8926. // If we've fallen outside of the end offset, just pretend there's nothing to
  8927. // write to/read from.
  8928. if (EndOffset <= LVal.getLValueOffset())
  8929. Size = 0;
  8930. else
  8931. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  8932. return true;
  8933. }
  8934. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  8935. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  8936. if (E->getResultAPValueKind() != APValue::None)
  8937. return Success(E->getAPValueResult(), E);
  8938. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  8939. }
  8940. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8941. if (unsigned BuiltinOp = E->getBuiltinCallee())
  8942. return VisitBuiltinCallExpr(E, BuiltinOp);
  8943. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8944. }
  8945. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8946. unsigned BuiltinOp) {
  8947. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  8948. default:
  8949. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8950. case Builtin::BI__builtin_dynamic_object_size:
  8951. case Builtin::BI__builtin_object_size: {
  8952. // The type was checked when we built the expression.
  8953. unsigned Type =
  8954. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8955. assert(Type <= 3 && "unexpected type");
  8956. uint64_t Size;
  8957. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  8958. return Success(Size, E);
  8959. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  8960. return Success((Type & 2) ? 0 : -1, E);
  8961. // Expression had no side effects, but we couldn't statically determine the
  8962. // size of the referenced object.
  8963. switch (Info.EvalMode) {
  8964. case EvalInfo::EM_ConstantExpression:
  8965. case EvalInfo::EM_ConstantFold:
  8966. case EvalInfo::EM_IgnoreSideEffects:
  8967. // Leave it to IR generation.
  8968. return Error(E);
  8969. case EvalInfo::EM_ConstantExpressionUnevaluated:
  8970. // Reduce it to a constant now.
  8971. return Success((Type & 2) ? 0 : -1, E);
  8972. }
  8973. llvm_unreachable("unexpected EvalMode");
  8974. }
  8975. case Builtin::BI__builtin_os_log_format_buffer_size: {
  8976. analyze_os_log::OSLogBufferLayout Layout;
  8977. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  8978. return Success(Layout.size().getQuantity(), E);
  8979. }
  8980. case Builtin::BI__builtin_bswap16:
  8981. case Builtin::BI__builtin_bswap32:
  8982. case Builtin::BI__builtin_bswap64: {
  8983. APSInt Val;
  8984. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8985. return false;
  8986. return Success(Val.byteSwap(), E);
  8987. }
  8988. case Builtin::BI__builtin_classify_type:
  8989. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  8990. case Builtin::BI__builtin_clrsb:
  8991. case Builtin::BI__builtin_clrsbl:
  8992. case Builtin::BI__builtin_clrsbll: {
  8993. APSInt Val;
  8994. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8995. return false;
  8996. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  8997. }
  8998. case Builtin::BI__builtin_clz:
  8999. case Builtin::BI__builtin_clzl:
  9000. case Builtin::BI__builtin_clzll:
  9001. case Builtin::BI__builtin_clzs: {
  9002. APSInt Val;
  9003. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9004. return false;
  9005. if (!Val)
  9006. return Error(E);
  9007. return Success(Val.countLeadingZeros(), E);
  9008. }
  9009. case Builtin::BI__builtin_constant_p: {
  9010. const Expr *Arg = E->getArg(0);
  9011. if (EvaluateBuiltinConstantP(Info, Arg))
  9012. return Success(true, E);
  9013. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  9014. // Outside a constant context, eagerly evaluate to false in the presence
  9015. // of side-effects in order to avoid -Wunsequenced false-positives in
  9016. // a branch on __builtin_constant_p(expr).
  9017. return Success(false, E);
  9018. }
  9019. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9020. return false;
  9021. }
  9022. case Builtin::BI__builtin_is_constant_evaluated:
  9023. return Success(Info.InConstantContext, E);
  9024. case Builtin::BI__builtin_ctz:
  9025. case Builtin::BI__builtin_ctzl:
  9026. case Builtin::BI__builtin_ctzll:
  9027. case Builtin::BI__builtin_ctzs: {
  9028. APSInt Val;
  9029. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9030. return false;
  9031. if (!Val)
  9032. return Error(E);
  9033. return Success(Val.countTrailingZeros(), E);
  9034. }
  9035. case Builtin::BI__builtin_eh_return_data_regno: {
  9036. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9037. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  9038. return Success(Operand, E);
  9039. }
  9040. case Builtin::BI__builtin_expect:
  9041. return Visit(E->getArg(0));
  9042. case Builtin::BI__builtin_ffs:
  9043. case Builtin::BI__builtin_ffsl:
  9044. case Builtin::BI__builtin_ffsll: {
  9045. APSInt Val;
  9046. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9047. return false;
  9048. unsigned N = Val.countTrailingZeros();
  9049. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  9050. }
  9051. case Builtin::BI__builtin_fpclassify: {
  9052. APFloat Val(0.0);
  9053. if (!EvaluateFloat(E->getArg(5), Val, Info))
  9054. return false;
  9055. unsigned Arg;
  9056. switch (Val.getCategory()) {
  9057. case APFloat::fcNaN: Arg = 0; break;
  9058. case APFloat::fcInfinity: Arg = 1; break;
  9059. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  9060. case APFloat::fcZero: Arg = 4; break;
  9061. }
  9062. return Visit(E->getArg(Arg));
  9063. }
  9064. case Builtin::BI__builtin_isinf_sign: {
  9065. APFloat Val(0.0);
  9066. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9067. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  9068. }
  9069. case Builtin::BI__builtin_isinf: {
  9070. APFloat Val(0.0);
  9071. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9072. Success(Val.isInfinity() ? 1 : 0, E);
  9073. }
  9074. case Builtin::BI__builtin_isfinite: {
  9075. APFloat Val(0.0);
  9076. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9077. Success(Val.isFinite() ? 1 : 0, E);
  9078. }
  9079. case Builtin::BI__builtin_isnan: {
  9080. APFloat Val(0.0);
  9081. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9082. Success(Val.isNaN() ? 1 : 0, E);
  9083. }
  9084. case Builtin::BI__builtin_isnormal: {
  9085. APFloat Val(0.0);
  9086. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9087. Success(Val.isNormal() ? 1 : 0, E);
  9088. }
  9089. case Builtin::BI__builtin_parity:
  9090. case Builtin::BI__builtin_parityl:
  9091. case Builtin::BI__builtin_parityll: {
  9092. APSInt Val;
  9093. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9094. return false;
  9095. return Success(Val.countPopulation() % 2, E);
  9096. }
  9097. case Builtin::BI__builtin_popcount:
  9098. case Builtin::BI__builtin_popcountl:
  9099. case Builtin::BI__builtin_popcountll: {
  9100. APSInt Val;
  9101. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9102. return false;
  9103. return Success(Val.countPopulation(), E);
  9104. }
  9105. case Builtin::BIstrlen:
  9106. case Builtin::BIwcslen:
  9107. // A call to strlen is not a constant expression.
  9108. if (Info.getLangOpts().CPlusPlus11)
  9109. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9110. << /*isConstexpr*/0 << /*isConstructor*/0
  9111. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9112. else
  9113. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9114. LLVM_FALLTHROUGH;
  9115. case Builtin::BI__builtin_strlen:
  9116. case Builtin::BI__builtin_wcslen: {
  9117. // As an extension, we support __builtin_strlen() as a constant expression,
  9118. // and support folding strlen() to a constant.
  9119. LValue String;
  9120. if (!EvaluatePointer(E->getArg(0), String, Info))
  9121. return false;
  9122. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  9123. // Fast path: if it's a string literal, search the string value.
  9124. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  9125. String.getLValueBase().dyn_cast<const Expr *>())) {
  9126. // The string literal may have embedded null characters. Find the first
  9127. // one and truncate there.
  9128. StringRef Str = S->getBytes();
  9129. int64_t Off = String.Offset.getQuantity();
  9130. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  9131. S->getCharByteWidth() == 1 &&
  9132. // FIXME: Add fast-path for wchar_t too.
  9133. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  9134. Str = Str.substr(Off);
  9135. StringRef::size_type Pos = Str.find(0);
  9136. if (Pos != StringRef::npos)
  9137. Str = Str.substr(0, Pos);
  9138. return Success(Str.size(), E);
  9139. }
  9140. // Fall through to slow path to issue appropriate diagnostic.
  9141. }
  9142. // Slow path: scan the bytes of the string looking for the terminating 0.
  9143. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  9144. APValue Char;
  9145. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  9146. !Char.isInt())
  9147. return false;
  9148. if (!Char.getInt())
  9149. return Success(Strlen, E);
  9150. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  9151. return false;
  9152. }
  9153. }
  9154. case Builtin::BIstrcmp:
  9155. case Builtin::BIwcscmp:
  9156. case Builtin::BIstrncmp:
  9157. case Builtin::BIwcsncmp:
  9158. case Builtin::BImemcmp:
  9159. case Builtin::BIbcmp:
  9160. case Builtin::BIwmemcmp:
  9161. // A call to strlen is not a constant expression.
  9162. if (Info.getLangOpts().CPlusPlus11)
  9163. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9164. << /*isConstexpr*/0 << /*isConstructor*/0
  9165. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9166. else
  9167. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9168. LLVM_FALLTHROUGH;
  9169. case Builtin::BI__builtin_strcmp:
  9170. case Builtin::BI__builtin_wcscmp:
  9171. case Builtin::BI__builtin_strncmp:
  9172. case Builtin::BI__builtin_wcsncmp:
  9173. case Builtin::BI__builtin_memcmp:
  9174. case Builtin::BI__builtin_bcmp:
  9175. case Builtin::BI__builtin_wmemcmp: {
  9176. LValue String1, String2;
  9177. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  9178. !EvaluatePointer(E->getArg(1), String2, Info))
  9179. return false;
  9180. uint64_t MaxLength = uint64_t(-1);
  9181. if (BuiltinOp != Builtin::BIstrcmp &&
  9182. BuiltinOp != Builtin::BIwcscmp &&
  9183. BuiltinOp != Builtin::BI__builtin_strcmp &&
  9184. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  9185. APSInt N;
  9186. if (!EvaluateInteger(E->getArg(2), N, Info))
  9187. return false;
  9188. MaxLength = N.getExtValue();
  9189. }
  9190. // Empty substrings compare equal by definition.
  9191. if (MaxLength == 0u)
  9192. return Success(0, E);
  9193. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9194. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9195. String1.Designator.Invalid || String2.Designator.Invalid)
  9196. return false;
  9197. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  9198. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  9199. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  9200. BuiltinOp == Builtin::BIbcmp ||
  9201. BuiltinOp == Builtin::BI__builtin_memcmp ||
  9202. BuiltinOp == Builtin::BI__builtin_bcmp;
  9203. assert(IsRawByte ||
  9204. (Info.Ctx.hasSameUnqualifiedType(
  9205. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  9206. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  9207. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  9208. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  9209. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  9210. Char1.isInt() && Char2.isInt();
  9211. };
  9212. const auto &AdvanceElems = [&] {
  9213. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  9214. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  9215. };
  9216. if (IsRawByte) {
  9217. uint64_t BytesRemaining = MaxLength;
  9218. // Pointers to const void may point to objects of incomplete type.
  9219. if (CharTy1->isIncompleteType()) {
  9220. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  9221. return false;
  9222. }
  9223. if (CharTy2->isIncompleteType()) {
  9224. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  9225. return false;
  9226. }
  9227. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  9228. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  9229. // Give up on comparing between elements with disparate widths.
  9230. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  9231. return false;
  9232. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  9233. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  9234. "following loop considers at least one element");
  9235. while (true) {
  9236. APValue Char1, Char2;
  9237. if (!ReadCurElems(Char1, Char2))
  9238. return false;
  9239. // We have compatible in-memory widths, but a possible type and
  9240. // (for `bool`) internal representation mismatch.
  9241. // Assuming two's complement representation, including 0 for `false` and
  9242. // 1 for `true`, we can check an appropriate number of elements for
  9243. // equality even if they are not byte-sized.
  9244. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  9245. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  9246. if (Char1InMem.ne(Char2InMem)) {
  9247. // If the elements are byte-sized, then we can produce a three-way
  9248. // comparison result in a straightforward manner.
  9249. if (BytesPerElement == 1u) {
  9250. // memcmp always compares unsigned chars.
  9251. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  9252. }
  9253. // The result is byte-order sensitive, and we have multibyte elements.
  9254. // FIXME: We can compare the remaining bytes in the correct order.
  9255. return false;
  9256. }
  9257. if (!AdvanceElems())
  9258. return false;
  9259. if (BytesRemaining <= BytesPerElement)
  9260. break;
  9261. BytesRemaining -= BytesPerElement;
  9262. }
  9263. // Enough elements are equal to account for the memcmp limit.
  9264. return Success(0, E);
  9265. }
  9266. bool StopAtNull =
  9267. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  9268. BuiltinOp != Builtin::BIwmemcmp &&
  9269. BuiltinOp != Builtin::BI__builtin_memcmp &&
  9270. BuiltinOp != Builtin::BI__builtin_bcmp &&
  9271. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  9272. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  9273. BuiltinOp == Builtin::BIwcsncmp ||
  9274. BuiltinOp == Builtin::BIwmemcmp ||
  9275. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  9276. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  9277. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  9278. for (; MaxLength; --MaxLength) {
  9279. APValue Char1, Char2;
  9280. if (!ReadCurElems(Char1, Char2))
  9281. return false;
  9282. if (Char1.getInt() != Char2.getInt()) {
  9283. if (IsWide) // wmemcmp compares with wchar_t signedness.
  9284. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  9285. // memcmp always compares unsigned chars.
  9286. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  9287. }
  9288. if (StopAtNull && !Char1.getInt())
  9289. return Success(0, E);
  9290. assert(!(StopAtNull && !Char2.getInt()));
  9291. if (!AdvanceElems())
  9292. return false;
  9293. }
  9294. // We hit the strncmp / memcmp limit.
  9295. return Success(0, E);
  9296. }
  9297. case Builtin::BI__atomic_always_lock_free:
  9298. case Builtin::BI__atomic_is_lock_free:
  9299. case Builtin::BI__c11_atomic_is_lock_free: {
  9300. APSInt SizeVal;
  9301. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  9302. return false;
  9303. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  9304. // of two less than the maximum inline atomic width, we know it is
  9305. // lock-free. If the size isn't a power of two, or greater than the
  9306. // maximum alignment where we promote atomics, we know it is not lock-free
  9307. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  9308. // the answer can only be determined at runtime; for example, 16-byte
  9309. // atomics have lock-free implementations on some, but not all,
  9310. // x86-64 processors.
  9311. // Check power-of-two.
  9312. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  9313. if (Size.isPowerOfTwo()) {
  9314. // Check against inlining width.
  9315. unsigned InlineWidthBits =
  9316. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  9317. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  9318. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  9319. Size == CharUnits::One() ||
  9320. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  9321. Expr::NPC_NeverValueDependent))
  9322. // OK, we will inline appropriately-aligned operations of this size,
  9323. // and _Atomic(T) is appropriately-aligned.
  9324. return Success(1, E);
  9325. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  9326. castAs<PointerType>()->getPointeeType();
  9327. if (!PointeeType->isIncompleteType() &&
  9328. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  9329. // OK, we will inline operations on this object.
  9330. return Success(1, E);
  9331. }
  9332. }
  9333. }
  9334. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  9335. Success(0, E) : Error(E);
  9336. }
  9337. case Builtin::BIomp_is_initial_device:
  9338. // We can decide statically which value the runtime would return if called.
  9339. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  9340. case Builtin::BI__builtin_add_overflow:
  9341. case Builtin::BI__builtin_sub_overflow:
  9342. case Builtin::BI__builtin_mul_overflow:
  9343. case Builtin::BI__builtin_sadd_overflow:
  9344. case Builtin::BI__builtin_uadd_overflow:
  9345. case Builtin::BI__builtin_uaddl_overflow:
  9346. case Builtin::BI__builtin_uaddll_overflow:
  9347. case Builtin::BI__builtin_usub_overflow:
  9348. case Builtin::BI__builtin_usubl_overflow:
  9349. case Builtin::BI__builtin_usubll_overflow:
  9350. case Builtin::BI__builtin_umul_overflow:
  9351. case Builtin::BI__builtin_umull_overflow:
  9352. case Builtin::BI__builtin_umulll_overflow:
  9353. case Builtin::BI__builtin_saddl_overflow:
  9354. case Builtin::BI__builtin_saddll_overflow:
  9355. case Builtin::BI__builtin_ssub_overflow:
  9356. case Builtin::BI__builtin_ssubl_overflow:
  9357. case Builtin::BI__builtin_ssubll_overflow:
  9358. case Builtin::BI__builtin_smul_overflow:
  9359. case Builtin::BI__builtin_smull_overflow:
  9360. case Builtin::BI__builtin_smulll_overflow: {
  9361. LValue ResultLValue;
  9362. APSInt LHS, RHS;
  9363. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  9364. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  9365. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  9366. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  9367. return false;
  9368. APSInt Result;
  9369. bool DidOverflow = false;
  9370. // If the types don't have to match, enlarge all 3 to the largest of them.
  9371. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9372. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9373. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9374. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  9375. ResultType->isSignedIntegerOrEnumerationType();
  9376. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  9377. ResultType->isSignedIntegerOrEnumerationType();
  9378. uint64_t LHSSize = LHS.getBitWidth();
  9379. uint64_t RHSSize = RHS.getBitWidth();
  9380. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  9381. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  9382. // Add an additional bit if the signedness isn't uniformly agreed to. We
  9383. // could do this ONLY if there is a signed and an unsigned that both have
  9384. // MaxBits, but the code to check that is pretty nasty. The issue will be
  9385. // caught in the shrink-to-result later anyway.
  9386. if (IsSigned && !AllSigned)
  9387. ++MaxBits;
  9388. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  9389. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  9390. Result = APSInt(MaxBits, !IsSigned);
  9391. }
  9392. // Find largest int.
  9393. switch (BuiltinOp) {
  9394. default:
  9395. llvm_unreachable("Invalid value for BuiltinOp");
  9396. case Builtin::BI__builtin_add_overflow:
  9397. case Builtin::BI__builtin_sadd_overflow:
  9398. case Builtin::BI__builtin_saddl_overflow:
  9399. case Builtin::BI__builtin_saddll_overflow:
  9400. case Builtin::BI__builtin_uadd_overflow:
  9401. case Builtin::BI__builtin_uaddl_overflow:
  9402. case Builtin::BI__builtin_uaddll_overflow:
  9403. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  9404. : LHS.uadd_ov(RHS, DidOverflow);
  9405. break;
  9406. case Builtin::BI__builtin_sub_overflow:
  9407. case Builtin::BI__builtin_ssub_overflow:
  9408. case Builtin::BI__builtin_ssubl_overflow:
  9409. case Builtin::BI__builtin_ssubll_overflow:
  9410. case Builtin::BI__builtin_usub_overflow:
  9411. case Builtin::BI__builtin_usubl_overflow:
  9412. case Builtin::BI__builtin_usubll_overflow:
  9413. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  9414. : LHS.usub_ov(RHS, DidOverflow);
  9415. break;
  9416. case Builtin::BI__builtin_mul_overflow:
  9417. case Builtin::BI__builtin_smul_overflow:
  9418. case Builtin::BI__builtin_smull_overflow:
  9419. case Builtin::BI__builtin_smulll_overflow:
  9420. case Builtin::BI__builtin_umul_overflow:
  9421. case Builtin::BI__builtin_umull_overflow:
  9422. case Builtin::BI__builtin_umulll_overflow:
  9423. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  9424. : LHS.umul_ov(RHS, DidOverflow);
  9425. break;
  9426. }
  9427. // In the case where multiple sizes are allowed, truncate and see if
  9428. // the values are the same.
  9429. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9430. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9431. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9432. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  9433. // since it will give us the behavior of a TruncOrSelf in the case where
  9434. // its parameter <= its size. We previously set Result to be at least the
  9435. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  9436. // will work exactly like TruncOrSelf.
  9437. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  9438. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  9439. if (!APSInt::isSameValue(Temp, Result))
  9440. DidOverflow = true;
  9441. Result = Temp;
  9442. }
  9443. APValue APV{Result};
  9444. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  9445. return false;
  9446. return Success(DidOverflow, E);
  9447. }
  9448. }
  9449. }
  9450. /// Determine whether this is a pointer past the end of the complete
  9451. /// object referred to by the lvalue.
  9452. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  9453. const LValue &LV) {
  9454. // A null pointer can be viewed as being "past the end" but we don't
  9455. // choose to look at it that way here.
  9456. if (!LV.getLValueBase())
  9457. return false;
  9458. // If the designator is valid and refers to a subobject, we're not pointing
  9459. // past the end.
  9460. if (!LV.getLValueDesignator().Invalid &&
  9461. !LV.getLValueDesignator().isOnePastTheEnd())
  9462. return false;
  9463. // A pointer to an incomplete type might be past-the-end if the type's size is
  9464. // zero. We cannot tell because the type is incomplete.
  9465. QualType Ty = getType(LV.getLValueBase());
  9466. if (Ty->isIncompleteType())
  9467. return true;
  9468. // We're a past-the-end pointer if we point to the byte after the object,
  9469. // no matter what our type or path is.
  9470. auto Size = Ctx.getTypeSizeInChars(Ty);
  9471. return LV.getLValueOffset() == Size;
  9472. }
  9473. namespace {
  9474. /// Data recursive integer evaluator of certain binary operators.
  9475. ///
  9476. /// We use a data recursive algorithm for binary operators so that we are able
  9477. /// to handle extreme cases of chained binary operators without causing stack
  9478. /// overflow.
  9479. class DataRecursiveIntBinOpEvaluator {
  9480. struct EvalResult {
  9481. APValue Val;
  9482. bool Failed;
  9483. EvalResult() : Failed(false) { }
  9484. void swap(EvalResult &RHS) {
  9485. Val.swap(RHS.Val);
  9486. Failed = RHS.Failed;
  9487. RHS.Failed = false;
  9488. }
  9489. };
  9490. struct Job {
  9491. const Expr *E;
  9492. EvalResult LHSResult; // meaningful only for binary operator expression.
  9493. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  9494. Job() = default;
  9495. Job(Job &&) = default;
  9496. void startSpeculativeEval(EvalInfo &Info) {
  9497. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  9498. }
  9499. private:
  9500. SpeculativeEvaluationRAII SpecEvalRAII;
  9501. };
  9502. SmallVector<Job, 16> Queue;
  9503. IntExprEvaluator &IntEval;
  9504. EvalInfo &Info;
  9505. APValue &FinalResult;
  9506. public:
  9507. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  9508. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  9509. /// True if \param E is a binary operator that we are going to handle
  9510. /// data recursively.
  9511. /// We handle binary operators that are comma, logical, or that have operands
  9512. /// with integral or enumeration type.
  9513. static bool shouldEnqueue(const BinaryOperator *E) {
  9514. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  9515. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  9516. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9517. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9518. }
  9519. bool Traverse(const BinaryOperator *E) {
  9520. enqueue(E);
  9521. EvalResult PrevResult;
  9522. while (!Queue.empty())
  9523. process(PrevResult);
  9524. if (PrevResult.Failed) return false;
  9525. FinalResult.swap(PrevResult.Val);
  9526. return true;
  9527. }
  9528. private:
  9529. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9530. return IntEval.Success(Value, E, Result);
  9531. }
  9532. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  9533. return IntEval.Success(Value, E, Result);
  9534. }
  9535. bool Error(const Expr *E) {
  9536. return IntEval.Error(E);
  9537. }
  9538. bool Error(const Expr *E, diag::kind D) {
  9539. return IntEval.Error(E, D);
  9540. }
  9541. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  9542. return Info.CCEDiag(E, D);
  9543. }
  9544. // Returns true if visiting the RHS is necessary, false otherwise.
  9545. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9546. bool &SuppressRHSDiags);
  9547. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9548. const BinaryOperator *E, APValue &Result);
  9549. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  9550. Result.Failed = !Evaluate(Result.Val, Info, E);
  9551. if (Result.Failed)
  9552. Result.Val = APValue();
  9553. }
  9554. void process(EvalResult &Result);
  9555. void enqueue(const Expr *E) {
  9556. E = E->IgnoreParens();
  9557. Queue.resize(Queue.size()+1);
  9558. Queue.back().E = E;
  9559. Queue.back().Kind = Job::AnyExprKind;
  9560. }
  9561. };
  9562. }
  9563. bool DataRecursiveIntBinOpEvaluator::
  9564. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9565. bool &SuppressRHSDiags) {
  9566. if (E->getOpcode() == BO_Comma) {
  9567. // Ignore LHS but note if we could not evaluate it.
  9568. if (LHSResult.Failed)
  9569. return Info.noteSideEffect();
  9570. return true;
  9571. }
  9572. if (E->isLogicalOp()) {
  9573. bool LHSAsBool;
  9574. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  9575. // We were able to evaluate the LHS, see if we can get away with not
  9576. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  9577. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  9578. Success(LHSAsBool, E, LHSResult.Val);
  9579. return false; // Ignore RHS
  9580. }
  9581. } else {
  9582. LHSResult.Failed = true;
  9583. // Since we weren't able to evaluate the left hand side, it
  9584. // might have had side effects.
  9585. if (!Info.noteSideEffect())
  9586. return false;
  9587. // We can't evaluate the LHS; however, sometimes the result
  9588. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9589. // Don't ignore RHS and suppress diagnostics from this arm.
  9590. SuppressRHSDiags = true;
  9591. }
  9592. return true;
  9593. }
  9594. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9595. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9596. if (LHSResult.Failed && !Info.noteFailure())
  9597. return false; // Ignore RHS;
  9598. return true;
  9599. }
  9600. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  9601. bool IsSub) {
  9602. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  9603. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  9604. // offsets.
  9605. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  9606. CharUnits &Offset = LVal.getLValueOffset();
  9607. uint64_t Offset64 = Offset.getQuantity();
  9608. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  9609. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  9610. : Offset64 + Index64);
  9611. }
  9612. bool DataRecursiveIntBinOpEvaluator::
  9613. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9614. const BinaryOperator *E, APValue &Result) {
  9615. if (E->getOpcode() == BO_Comma) {
  9616. if (RHSResult.Failed)
  9617. return false;
  9618. Result = RHSResult.Val;
  9619. return true;
  9620. }
  9621. if (E->isLogicalOp()) {
  9622. bool lhsResult, rhsResult;
  9623. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9624. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9625. if (LHSIsOK) {
  9626. if (RHSIsOK) {
  9627. if (E->getOpcode() == BO_LOr)
  9628. return Success(lhsResult || rhsResult, E, Result);
  9629. else
  9630. return Success(lhsResult && rhsResult, E, Result);
  9631. }
  9632. } else {
  9633. if (RHSIsOK) {
  9634. // We can't evaluate the LHS; however, sometimes the result
  9635. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9636. if (rhsResult == (E->getOpcode() == BO_LOr))
  9637. return Success(rhsResult, E, Result);
  9638. }
  9639. }
  9640. return false;
  9641. }
  9642. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9643. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9644. if (LHSResult.Failed || RHSResult.Failed)
  9645. return false;
  9646. const APValue &LHSVal = LHSResult.Val;
  9647. const APValue &RHSVal = RHSResult.Val;
  9648. // Handle cases like (unsigned long)&a + 4.
  9649. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9650. Result = LHSVal;
  9651. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9652. return true;
  9653. }
  9654. // Handle cases like 4 + (unsigned long)&a
  9655. if (E->getOpcode() == BO_Add &&
  9656. RHSVal.isLValue() && LHSVal.isInt()) {
  9657. Result = RHSVal;
  9658. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9659. return true;
  9660. }
  9661. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9662. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9663. if (!LHSVal.getLValueOffset().isZero() ||
  9664. !RHSVal.getLValueOffset().isZero())
  9665. return false;
  9666. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9667. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9668. if (!LHSExpr || !RHSExpr)
  9669. return false;
  9670. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9671. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9672. if (!LHSAddrExpr || !RHSAddrExpr)
  9673. return false;
  9674. // Make sure both labels come from the same function.
  9675. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9676. RHSAddrExpr->getLabel()->getDeclContext())
  9677. return false;
  9678. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9679. return true;
  9680. }
  9681. // All the remaining cases expect both operands to be an integer
  9682. if (!LHSVal.isInt() || !RHSVal.isInt())
  9683. return Error(E);
  9684. // Set up the width and signedness manually, in case it can't be deduced
  9685. // from the operation we're performing.
  9686. // FIXME: Don't do this in the cases where we can deduce it.
  9687. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9688. E->getType()->isUnsignedIntegerOrEnumerationType());
  9689. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9690. RHSVal.getInt(), Value))
  9691. return false;
  9692. return Success(Value, E, Result);
  9693. }
  9694. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9695. Job &job = Queue.back();
  9696. switch (job.Kind) {
  9697. case Job::AnyExprKind: {
  9698. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9699. if (shouldEnqueue(Bop)) {
  9700. job.Kind = Job::BinOpKind;
  9701. enqueue(Bop->getLHS());
  9702. return;
  9703. }
  9704. }
  9705. EvaluateExpr(job.E, Result);
  9706. Queue.pop_back();
  9707. return;
  9708. }
  9709. case Job::BinOpKind: {
  9710. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9711. bool SuppressRHSDiags = false;
  9712. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9713. Queue.pop_back();
  9714. return;
  9715. }
  9716. if (SuppressRHSDiags)
  9717. job.startSpeculativeEval(Info);
  9718. job.LHSResult.swap(Result);
  9719. job.Kind = Job::BinOpVisitedLHSKind;
  9720. enqueue(Bop->getRHS());
  9721. return;
  9722. }
  9723. case Job::BinOpVisitedLHSKind: {
  9724. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9725. EvalResult RHS;
  9726. RHS.swap(Result);
  9727. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  9728. Queue.pop_back();
  9729. return;
  9730. }
  9731. }
  9732. llvm_unreachable("Invalid Job::Kind!");
  9733. }
  9734. namespace {
  9735. /// Used when we determine that we should fail, but can keep evaluating prior to
  9736. /// noting that we had a failure.
  9737. class DelayedNoteFailureRAII {
  9738. EvalInfo &Info;
  9739. bool NoteFailure;
  9740. public:
  9741. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  9742. : Info(Info), NoteFailure(NoteFailure) {}
  9743. ~DelayedNoteFailureRAII() {
  9744. if (NoteFailure) {
  9745. bool ContinueAfterFailure = Info.noteFailure();
  9746. (void)ContinueAfterFailure;
  9747. assert(ContinueAfterFailure &&
  9748. "Shouldn't have kept evaluating on failure.");
  9749. }
  9750. }
  9751. };
  9752. }
  9753. template <class SuccessCB, class AfterCB>
  9754. static bool
  9755. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  9756. SuccessCB &&Success, AfterCB &&DoAfter) {
  9757. assert(E->isComparisonOp() && "expected comparison operator");
  9758. assert((E->getOpcode() == BO_Cmp ||
  9759. E->getType()->isIntegralOrEnumerationType()) &&
  9760. "unsupported binary expression evaluation");
  9761. auto Error = [&](const Expr *E) {
  9762. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9763. return false;
  9764. };
  9765. using CCR = ComparisonCategoryResult;
  9766. bool IsRelational = E->isRelationalOp();
  9767. bool IsEquality = E->isEqualityOp();
  9768. if (E->getOpcode() == BO_Cmp) {
  9769. const ComparisonCategoryInfo &CmpInfo =
  9770. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9771. IsRelational = CmpInfo.isOrdered();
  9772. IsEquality = CmpInfo.isEquality();
  9773. }
  9774. QualType LHSTy = E->getLHS()->getType();
  9775. QualType RHSTy = E->getRHS()->getType();
  9776. if (LHSTy->isIntegralOrEnumerationType() &&
  9777. RHSTy->isIntegralOrEnumerationType()) {
  9778. APSInt LHS, RHS;
  9779. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  9780. if (!LHSOK && !Info.noteFailure())
  9781. return false;
  9782. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  9783. return false;
  9784. if (LHS < RHS)
  9785. return Success(CCR::Less, E);
  9786. if (LHS > RHS)
  9787. return Success(CCR::Greater, E);
  9788. return Success(CCR::Equal, E);
  9789. }
  9790. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  9791. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  9792. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  9793. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  9794. if (!LHSOK && !Info.noteFailure())
  9795. return false;
  9796. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  9797. return false;
  9798. if (LHSFX < RHSFX)
  9799. return Success(CCR::Less, E);
  9800. if (LHSFX > RHSFX)
  9801. return Success(CCR::Greater, E);
  9802. return Success(CCR::Equal, E);
  9803. }
  9804. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  9805. ComplexValue LHS, RHS;
  9806. bool LHSOK;
  9807. if (E->isAssignmentOp()) {
  9808. LValue LV;
  9809. EvaluateLValue(E->getLHS(), LV, Info);
  9810. LHSOK = false;
  9811. } else if (LHSTy->isRealFloatingType()) {
  9812. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  9813. if (LHSOK) {
  9814. LHS.makeComplexFloat();
  9815. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  9816. }
  9817. } else {
  9818. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  9819. }
  9820. if (!LHSOK && !Info.noteFailure())
  9821. return false;
  9822. if (E->getRHS()->getType()->isRealFloatingType()) {
  9823. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  9824. return false;
  9825. RHS.makeComplexFloat();
  9826. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  9827. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9828. return false;
  9829. if (LHS.isComplexFloat()) {
  9830. APFloat::cmpResult CR_r =
  9831. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  9832. APFloat::cmpResult CR_i =
  9833. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  9834. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  9835. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9836. } else {
  9837. assert(IsEquality && "invalid complex comparison");
  9838. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  9839. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  9840. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9841. }
  9842. }
  9843. if (LHSTy->isRealFloatingType() &&
  9844. RHSTy->isRealFloatingType()) {
  9845. APFloat RHS(0.0), LHS(0.0);
  9846. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  9847. if (!LHSOK && !Info.noteFailure())
  9848. return false;
  9849. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  9850. return false;
  9851. assert(E->isComparisonOp() && "Invalid binary operator!");
  9852. auto GetCmpRes = [&]() {
  9853. switch (LHS.compare(RHS)) {
  9854. case APFloat::cmpEqual:
  9855. return CCR::Equal;
  9856. case APFloat::cmpLessThan:
  9857. return CCR::Less;
  9858. case APFloat::cmpGreaterThan:
  9859. return CCR::Greater;
  9860. case APFloat::cmpUnordered:
  9861. return CCR::Unordered;
  9862. }
  9863. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  9864. };
  9865. return Success(GetCmpRes(), E);
  9866. }
  9867. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  9868. LValue LHSValue, RHSValue;
  9869. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9870. if (!LHSOK && !Info.noteFailure())
  9871. return false;
  9872. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9873. return false;
  9874. // Reject differing bases from the normal codepath; we special-case
  9875. // comparisons to null.
  9876. if (!HasSameBase(LHSValue, RHSValue)) {
  9877. // Inequalities and subtractions between unrelated pointers have
  9878. // unspecified or undefined behavior.
  9879. if (!IsEquality)
  9880. return Error(E);
  9881. // A constant address may compare equal to the address of a symbol.
  9882. // The one exception is that address of an object cannot compare equal
  9883. // to a null pointer constant.
  9884. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  9885. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  9886. return Error(E);
  9887. // It's implementation-defined whether distinct literals will have
  9888. // distinct addresses. In clang, the result of such a comparison is
  9889. // unspecified, so it is not a constant expression. However, we do know
  9890. // that the address of a literal will be non-null.
  9891. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  9892. LHSValue.Base && RHSValue.Base)
  9893. return Error(E);
  9894. // We can't tell whether weak symbols will end up pointing to the same
  9895. // object.
  9896. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  9897. return Error(E);
  9898. // We can't compare the address of the start of one object with the
  9899. // past-the-end address of another object, per C++ DR1652.
  9900. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  9901. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  9902. (RHSValue.Base && RHSValue.Offset.isZero() &&
  9903. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  9904. return Error(E);
  9905. // We can't tell whether an object is at the same address as another
  9906. // zero sized object.
  9907. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  9908. (LHSValue.Base && isZeroSized(RHSValue)))
  9909. return Error(E);
  9910. return Success(CCR::Nonequal, E);
  9911. }
  9912. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9913. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9914. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9915. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9916. // C++11 [expr.rel]p3:
  9917. // Pointers to void (after pointer conversions) can be compared, with a
  9918. // result defined as follows: If both pointers represent the same
  9919. // address or are both the null pointer value, the result is true if the
  9920. // operator is <= or >= and false otherwise; otherwise the result is
  9921. // unspecified.
  9922. // We interpret this as applying to pointers to *cv* void.
  9923. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  9924. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  9925. // C++11 [expr.rel]p2:
  9926. // - If two pointers point to non-static data members of the same object,
  9927. // or to subobjects or array elements fo such members, recursively, the
  9928. // pointer to the later declared member compares greater provided the
  9929. // two members have the same access control and provided their class is
  9930. // not a union.
  9931. // [...]
  9932. // - Otherwise pointer comparisons are unspecified.
  9933. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  9934. bool WasArrayIndex;
  9935. unsigned Mismatch = FindDesignatorMismatch(
  9936. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  9937. // At the point where the designators diverge, the comparison has a
  9938. // specified value if:
  9939. // - we are comparing array indices
  9940. // - we are comparing fields of a union, or fields with the same access
  9941. // Otherwise, the result is unspecified and thus the comparison is not a
  9942. // constant expression.
  9943. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  9944. Mismatch < RHSDesignator.Entries.size()) {
  9945. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  9946. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  9947. if (!LF && !RF)
  9948. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  9949. else if (!LF)
  9950. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9951. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  9952. << RF->getParent() << RF;
  9953. else if (!RF)
  9954. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9955. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  9956. << LF->getParent() << LF;
  9957. else if (!LF->getParent()->isUnion() &&
  9958. LF->getAccess() != RF->getAccess())
  9959. Info.CCEDiag(E,
  9960. diag::note_constexpr_pointer_comparison_differing_access)
  9961. << LF << LF->getAccess() << RF << RF->getAccess()
  9962. << LF->getParent();
  9963. }
  9964. }
  9965. // The comparison here must be unsigned, and performed with the same
  9966. // width as the pointer.
  9967. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  9968. uint64_t CompareLHS = LHSOffset.getQuantity();
  9969. uint64_t CompareRHS = RHSOffset.getQuantity();
  9970. assert(PtrSize <= 64 && "Unexpected pointer width");
  9971. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  9972. CompareLHS &= Mask;
  9973. CompareRHS &= Mask;
  9974. // If there is a base and this is a relational operator, we can only
  9975. // compare pointers within the object in question; otherwise, the result
  9976. // depends on where the object is located in memory.
  9977. if (!LHSValue.Base.isNull() && IsRelational) {
  9978. QualType BaseTy = getType(LHSValue.Base);
  9979. if (BaseTy->isIncompleteType())
  9980. return Error(E);
  9981. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  9982. uint64_t OffsetLimit = Size.getQuantity();
  9983. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  9984. return Error(E);
  9985. }
  9986. if (CompareLHS < CompareRHS)
  9987. return Success(CCR::Less, E);
  9988. if (CompareLHS > CompareRHS)
  9989. return Success(CCR::Greater, E);
  9990. return Success(CCR::Equal, E);
  9991. }
  9992. if (LHSTy->isMemberPointerType()) {
  9993. assert(IsEquality && "unexpected member pointer operation");
  9994. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  9995. MemberPtr LHSValue, RHSValue;
  9996. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  9997. if (!LHSOK && !Info.noteFailure())
  9998. return false;
  9999. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10000. return false;
  10001. // C++11 [expr.eq]p2:
  10002. // If both operands are null, they compare equal. Otherwise if only one is
  10003. // null, they compare unequal.
  10004. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  10005. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  10006. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10007. }
  10008. // Otherwise if either is a pointer to a virtual member function, the
  10009. // result is unspecified.
  10010. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  10011. if (MD->isVirtual())
  10012. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10013. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  10014. if (MD->isVirtual())
  10015. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10016. // Otherwise they compare equal if and only if they would refer to the
  10017. // same member of the same most derived object or the same subobject if
  10018. // they were dereferenced with a hypothetical object of the associated
  10019. // class type.
  10020. bool Equal = LHSValue == RHSValue;
  10021. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10022. }
  10023. if (LHSTy->isNullPtrType()) {
  10024. assert(E->isComparisonOp() && "unexpected nullptr operation");
  10025. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  10026. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  10027. // are compared, the result is true of the operator is <=, >= or ==, and
  10028. // false otherwise.
  10029. return Success(CCR::Equal, E);
  10030. }
  10031. return DoAfter();
  10032. }
  10033. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  10034. if (!CheckLiteralType(Info, E))
  10035. return false;
  10036. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10037. const BinaryOperator *E) {
  10038. // Evaluation succeeded. Lookup the information for the comparison category
  10039. // type and fetch the VarDecl for the result.
  10040. const ComparisonCategoryInfo &CmpInfo =
  10041. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10042. const VarDecl *VD =
  10043. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  10044. // Check and evaluate the result as a constant expression.
  10045. LValue LV;
  10046. LV.set(VD);
  10047. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10048. return false;
  10049. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10050. };
  10051. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10052. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  10053. });
  10054. }
  10055. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10056. // We don't call noteFailure immediately because the assignment happens after
  10057. // we evaluate LHS and RHS.
  10058. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  10059. return Error(E);
  10060. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  10061. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  10062. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  10063. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  10064. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  10065. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  10066. if (E->isComparisonOp()) {
  10067. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  10068. // comparisons and then translating the result.
  10069. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10070. const BinaryOperator *E) {
  10071. using CCR = ComparisonCategoryResult;
  10072. bool IsEqual = ResKind == CCR::Equal,
  10073. IsLess = ResKind == CCR::Less,
  10074. IsGreater = ResKind == CCR::Greater;
  10075. auto Op = E->getOpcode();
  10076. switch (Op) {
  10077. default:
  10078. llvm_unreachable("unsupported binary operator");
  10079. case BO_EQ:
  10080. case BO_NE:
  10081. return Success(IsEqual == (Op == BO_EQ), E);
  10082. case BO_LT: return Success(IsLess, E);
  10083. case BO_GT: return Success(IsGreater, E);
  10084. case BO_LE: return Success(IsEqual || IsLess, E);
  10085. case BO_GE: return Success(IsEqual || IsGreater, E);
  10086. }
  10087. };
  10088. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10089. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10090. });
  10091. }
  10092. QualType LHSTy = E->getLHS()->getType();
  10093. QualType RHSTy = E->getRHS()->getType();
  10094. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  10095. E->getOpcode() == BO_Sub) {
  10096. LValue LHSValue, RHSValue;
  10097. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10098. if (!LHSOK && !Info.noteFailure())
  10099. return false;
  10100. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10101. return false;
  10102. // Reject differing bases from the normal codepath; we special-case
  10103. // comparisons to null.
  10104. if (!HasSameBase(LHSValue, RHSValue)) {
  10105. // Handle &&A - &&B.
  10106. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  10107. return Error(E);
  10108. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  10109. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  10110. if (!LHSExpr || !RHSExpr)
  10111. return Error(E);
  10112. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  10113. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  10114. if (!LHSAddrExpr || !RHSAddrExpr)
  10115. return Error(E);
  10116. // Make sure both labels come from the same function.
  10117. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  10118. RHSAddrExpr->getLabel()->getDeclContext())
  10119. return Error(E);
  10120. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  10121. }
  10122. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10123. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10124. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10125. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10126. // C++11 [expr.add]p6:
  10127. // Unless both pointers point to elements of the same array object, or
  10128. // one past the last element of the array object, the behavior is
  10129. // undefined.
  10130. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  10131. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  10132. RHSDesignator))
  10133. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  10134. QualType Type = E->getLHS()->getType();
  10135. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  10136. CharUnits ElementSize;
  10137. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  10138. return false;
  10139. // As an extension, a type may have zero size (empty struct or union in
  10140. // C, array of zero length). Pointer subtraction in such cases has
  10141. // undefined behavior, so is not constant.
  10142. if (ElementSize.isZero()) {
  10143. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  10144. << ElementType;
  10145. return false;
  10146. }
  10147. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  10148. // and produce incorrect results when it overflows. Such behavior
  10149. // appears to be non-conforming, but is common, so perhaps we should
  10150. // assume the standard intended for such cases to be undefined behavior
  10151. // and check for them.
  10152. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  10153. // overflow in the final conversion to ptrdiff_t.
  10154. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  10155. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  10156. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  10157. false);
  10158. APSInt TrueResult = (LHS - RHS) / ElemSize;
  10159. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  10160. if (Result.extend(65) != TrueResult &&
  10161. !HandleOverflow(Info, E, TrueResult, E->getType()))
  10162. return false;
  10163. return Success(Result, E);
  10164. }
  10165. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10166. }
  10167. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  10168. /// a result as the expression's type.
  10169. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  10170. const UnaryExprOrTypeTraitExpr *E) {
  10171. switch(E->getKind()) {
  10172. case UETT_PreferredAlignOf:
  10173. case UETT_AlignOf: {
  10174. if (E->isArgumentType())
  10175. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  10176. E);
  10177. else
  10178. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  10179. E);
  10180. }
  10181. case UETT_VecStep: {
  10182. QualType Ty = E->getTypeOfArgument();
  10183. if (Ty->isVectorType()) {
  10184. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  10185. // The vec_step built-in functions that take a 3-component
  10186. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  10187. if (n == 3)
  10188. n = 4;
  10189. return Success(n, E);
  10190. } else
  10191. return Success(1, E);
  10192. }
  10193. case UETT_SizeOf: {
  10194. QualType SrcTy = E->getTypeOfArgument();
  10195. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  10196. // the result is the size of the referenced type."
  10197. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  10198. SrcTy = Ref->getPointeeType();
  10199. CharUnits Sizeof;
  10200. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  10201. return false;
  10202. return Success(Sizeof, E);
  10203. }
  10204. case UETT_OpenMPRequiredSimdAlign:
  10205. assert(E->isArgumentType());
  10206. return Success(
  10207. Info.Ctx.toCharUnitsFromBits(
  10208. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  10209. .getQuantity(),
  10210. E);
  10211. }
  10212. llvm_unreachable("unknown expr/type trait");
  10213. }
  10214. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  10215. CharUnits Result;
  10216. unsigned n = OOE->getNumComponents();
  10217. if (n == 0)
  10218. return Error(OOE);
  10219. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  10220. for (unsigned i = 0; i != n; ++i) {
  10221. OffsetOfNode ON = OOE->getComponent(i);
  10222. switch (ON.getKind()) {
  10223. case OffsetOfNode::Array: {
  10224. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  10225. APSInt IdxResult;
  10226. if (!EvaluateInteger(Idx, IdxResult, Info))
  10227. return false;
  10228. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  10229. if (!AT)
  10230. return Error(OOE);
  10231. CurrentType = AT->getElementType();
  10232. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  10233. Result += IdxResult.getSExtValue() * ElementSize;
  10234. break;
  10235. }
  10236. case OffsetOfNode::Field: {
  10237. FieldDecl *MemberDecl = ON.getField();
  10238. const RecordType *RT = CurrentType->getAs<RecordType>();
  10239. if (!RT)
  10240. return Error(OOE);
  10241. RecordDecl *RD = RT->getDecl();
  10242. if (RD->isInvalidDecl()) return false;
  10243. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10244. unsigned i = MemberDecl->getFieldIndex();
  10245. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  10246. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  10247. CurrentType = MemberDecl->getType().getNonReferenceType();
  10248. break;
  10249. }
  10250. case OffsetOfNode::Identifier:
  10251. llvm_unreachable("dependent __builtin_offsetof");
  10252. case OffsetOfNode::Base: {
  10253. CXXBaseSpecifier *BaseSpec = ON.getBase();
  10254. if (BaseSpec->isVirtual())
  10255. return Error(OOE);
  10256. // Find the layout of the class whose base we are looking into.
  10257. const RecordType *RT = CurrentType->getAs<RecordType>();
  10258. if (!RT)
  10259. return Error(OOE);
  10260. RecordDecl *RD = RT->getDecl();
  10261. if (RD->isInvalidDecl()) return false;
  10262. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10263. // Find the base class itself.
  10264. CurrentType = BaseSpec->getType();
  10265. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  10266. if (!BaseRT)
  10267. return Error(OOE);
  10268. // Add the offset to the base.
  10269. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  10270. break;
  10271. }
  10272. }
  10273. }
  10274. return Success(Result, OOE);
  10275. }
  10276. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10277. switch (E->getOpcode()) {
  10278. default:
  10279. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  10280. // See C99 6.6p3.
  10281. return Error(E);
  10282. case UO_Extension:
  10283. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  10284. // If so, we could clear the diagnostic ID.
  10285. return Visit(E->getSubExpr());
  10286. case UO_Plus:
  10287. // The result is just the value.
  10288. return Visit(E->getSubExpr());
  10289. case UO_Minus: {
  10290. if (!Visit(E->getSubExpr()))
  10291. return false;
  10292. if (!Result.isInt()) return Error(E);
  10293. const APSInt &Value = Result.getInt();
  10294. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  10295. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  10296. E->getType()))
  10297. return false;
  10298. return Success(-Value, E);
  10299. }
  10300. case UO_Not: {
  10301. if (!Visit(E->getSubExpr()))
  10302. return false;
  10303. if (!Result.isInt()) return Error(E);
  10304. return Success(~Result.getInt(), E);
  10305. }
  10306. case UO_LNot: {
  10307. bool bres;
  10308. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10309. return false;
  10310. return Success(!bres, E);
  10311. }
  10312. }
  10313. }
  10314. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  10315. /// result type is integer.
  10316. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10317. const Expr *SubExpr = E->getSubExpr();
  10318. QualType DestType = E->getType();
  10319. QualType SrcType = SubExpr->getType();
  10320. switch (E->getCastKind()) {
  10321. case CK_BaseToDerived:
  10322. case CK_DerivedToBase:
  10323. case CK_UncheckedDerivedToBase:
  10324. case CK_Dynamic:
  10325. case CK_ToUnion:
  10326. case CK_ArrayToPointerDecay:
  10327. case CK_FunctionToPointerDecay:
  10328. case CK_NullToPointer:
  10329. case CK_NullToMemberPointer:
  10330. case CK_BaseToDerivedMemberPointer:
  10331. case CK_DerivedToBaseMemberPointer:
  10332. case CK_ReinterpretMemberPointer:
  10333. case CK_ConstructorConversion:
  10334. case CK_IntegralToPointer:
  10335. case CK_ToVoid:
  10336. case CK_VectorSplat:
  10337. case CK_IntegralToFloating:
  10338. case CK_FloatingCast:
  10339. case CK_CPointerToObjCPointerCast:
  10340. case CK_BlockPointerToObjCPointerCast:
  10341. case CK_AnyPointerToBlockPointerCast:
  10342. case CK_ObjCObjectLValueCast:
  10343. case CK_FloatingRealToComplex:
  10344. case CK_FloatingComplexToReal:
  10345. case CK_FloatingComplexCast:
  10346. case CK_FloatingComplexToIntegralComplex:
  10347. case CK_IntegralRealToComplex:
  10348. case CK_IntegralComplexCast:
  10349. case CK_IntegralComplexToFloatingComplex:
  10350. case CK_BuiltinFnToFnPtr:
  10351. case CK_ZeroToOCLOpaqueType:
  10352. case CK_NonAtomicToAtomic:
  10353. case CK_AddressSpaceConversion:
  10354. case CK_IntToOCLSampler:
  10355. case CK_FixedPointCast:
  10356. case CK_IntegralToFixedPoint:
  10357. llvm_unreachable("invalid cast kind for integral value");
  10358. case CK_BitCast:
  10359. case CK_Dependent:
  10360. case CK_LValueBitCast:
  10361. case CK_ARCProduceObject:
  10362. case CK_ARCConsumeObject:
  10363. case CK_ARCReclaimReturnedObject:
  10364. case CK_ARCExtendBlockObject:
  10365. case CK_CopyAndAutoreleaseBlockObject:
  10366. return Error(E);
  10367. case CK_UserDefinedConversion:
  10368. case CK_LValueToRValue:
  10369. case CK_AtomicToNonAtomic:
  10370. case CK_NoOp:
  10371. case CK_LValueToRValueBitCast:
  10372. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10373. case CK_MemberPointerToBoolean:
  10374. case CK_PointerToBoolean:
  10375. case CK_IntegralToBoolean:
  10376. case CK_FloatingToBoolean:
  10377. case CK_BooleanToSignedIntegral:
  10378. case CK_FloatingComplexToBoolean:
  10379. case CK_IntegralComplexToBoolean: {
  10380. bool BoolResult;
  10381. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  10382. return false;
  10383. uint64_t IntResult = BoolResult;
  10384. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  10385. IntResult = (uint64_t)-1;
  10386. return Success(IntResult, E);
  10387. }
  10388. case CK_FixedPointToIntegral: {
  10389. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  10390. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10391. return false;
  10392. bool Overflowed;
  10393. llvm::APSInt Result = Src.convertToInt(
  10394. Info.Ctx.getIntWidth(DestType),
  10395. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  10396. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10397. return false;
  10398. return Success(Result, E);
  10399. }
  10400. case CK_FixedPointToBoolean: {
  10401. // Unsigned padding does not affect this.
  10402. APValue Val;
  10403. if (!Evaluate(Val, Info, SubExpr))
  10404. return false;
  10405. return Success(Val.getFixedPoint().getBoolValue(), E);
  10406. }
  10407. case CK_IntegralCast: {
  10408. if (!Visit(SubExpr))
  10409. return false;
  10410. if (!Result.isInt()) {
  10411. // Allow casts of address-of-label differences if they are no-ops
  10412. // or narrowing. (The narrowing case isn't actually guaranteed to
  10413. // be constant-evaluatable except in some narrow cases which are hard
  10414. // to detect here. We let it through on the assumption the user knows
  10415. // what they are doing.)
  10416. if (Result.isAddrLabelDiff())
  10417. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  10418. // Only allow casts of lvalues if they are lossless.
  10419. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  10420. }
  10421. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  10422. Result.getInt()), E);
  10423. }
  10424. case CK_PointerToIntegral: {
  10425. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  10426. LValue LV;
  10427. if (!EvaluatePointer(SubExpr, LV, Info))
  10428. return false;
  10429. if (LV.getLValueBase()) {
  10430. // Only allow based lvalue casts if they are lossless.
  10431. // FIXME: Allow a larger integer size than the pointer size, and allow
  10432. // narrowing back down to pointer width in subsequent integral casts.
  10433. // FIXME: Check integer type's active bits, not its type size.
  10434. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  10435. return Error(E);
  10436. LV.Designator.setInvalid();
  10437. LV.moveInto(Result);
  10438. return true;
  10439. }
  10440. APSInt AsInt;
  10441. APValue V;
  10442. LV.moveInto(V);
  10443. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  10444. llvm_unreachable("Can't cast this!");
  10445. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  10446. }
  10447. case CK_IntegralComplexToReal: {
  10448. ComplexValue C;
  10449. if (!EvaluateComplex(SubExpr, C, Info))
  10450. return false;
  10451. return Success(C.getComplexIntReal(), E);
  10452. }
  10453. case CK_FloatingToIntegral: {
  10454. APFloat F(0.0);
  10455. if (!EvaluateFloat(SubExpr, F, Info))
  10456. return false;
  10457. APSInt Value;
  10458. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  10459. return false;
  10460. return Success(Value, E);
  10461. }
  10462. }
  10463. llvm_unreachable("unknown cast resulting in integral value");
  10464. }
  10465. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10466. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10467. ComplexValue LV;
  10468. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10469. return false;
  10470. if (!LV.isComplexInt())
  10471. return Error(E);
  10472. return Success(LV.getComplexIntReal(), E);
  10473. }
  10474. return Visit(E->getSubExpr());
  10475. }
  10476. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10477. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  10478. ComplexValue LV;
  10479. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10480. return false;
  10481. if (!LV.isComplexInt())
  10482. return Error(E);
  10483. return Success(LV.getComplexIntImag(), E);
  10484. }
  10485. VisitIgnoredValue(E->getSubExpr());
  10486. return Success(0, E);
  10487. }
  10488. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  10489. return Success(E->getPackLength(), E);
  10490. }
  10491. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  10492. return Success(E->getValue(), E);
  10493. }
  10494. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10495. switch (E->getOpcode()) {
  10496. default:
  10497. // Invalid unary operators
  10498. return Error(E);
  10499. case UO_Plus:
  10500. // The result is just the value.
  10501. return Visit(E->getSubExpr());
  10502. case UO_Minus: {
  10503. if (!Visit(E->getSubExpr())) return false;
  10504. if (!Result.isFixedPoint())
  10505. return Error(E);
  10506. bool Overflowed;
  10507. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  10508. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  10509. return false;
  10510. return Success(Negated, E);
  10511. }
  10512. case UO_LNot: {
  10513. bool bres;
  10514. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10515. return false;
  10516. return Success(!bres, E);
  10517. }
  10518. }
  10519. }
  10520. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10521. const Expr *SubExpr = E->getSubExpr();
  10522. QualType DestType = E->getType();
  10523. assert(DestType->isFixedPointType() &&
  10524. "Expected destination type to be a fixed point type");
  10525. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  10526. switch (E->getCastKind()) {
  10527. case CK_FixedPointCast: {
  10528. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  10529. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10530. return false;
  10531. bool Overflowed;
  10532. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  10533. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10534. return false;
  10535. return Success(Result, E);
  10536. }
  10537. case CK_IntegralToFixedPoint: {
  10538. APSInt Src;
  10539. if (!EvaluateInteger(SubExpr, Src, Info))
  10540. return false;
  10541. bool Overflowed;
  10542. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10543. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  10544. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  10545. return false;
  10546. return Success(IntResult, E);
  10547. }
  10548. case CK_NoOp:
  10549. case CK_LValueToRValue:
  10550. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10551. default:
  10552. return Error(E);
  10553. }
  10554. }
  10555. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10556. const Expr *LHS = E->getLHS();
  10557. const Expr *RHS = E->getRHS();
  10558. FixedPointSemantics ResultFXSema =
  10559. Info.Ctx.getFixedPointSemantics(E->getType());
  10560. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  10561. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  10562. return false;
  10563. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  10564. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  10565. return false;
  10566. switch (E->getOpcode()) {
  10567. case BO_Add: {
  10568. bool AddOverflow, ConversionOverflow;
  10569. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  10570. .convert(ResultFXSema, &ConversionOverflow);
  10571. if ((AddOverflow || ConversionOverflow) &&
  10572. !HandleOverflow(Info, E, Result, E->getType()))
  10573. return false;
  10574. return Success(Result, E);
  10575. }
  10576. default:
  10577. return false;
  10578. }
  10579. llvm_unreachable("Should've exited before this");
  10580. }
  10581. //===----------------------------------------------------------------------===//
  10582. // Float Evaluation
  10583. //===----------------------------------------------------------------------===//
  10584. namespace {
  10585. class FloatExprEvaluator
  10586. : public ExprEvaluatorBase<FloatExprEvaluator> {
  10587. APFloat &Result;
  10588. public:
  10589. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  10590. : ExprEvaluatorBaseTy(info), Result(result) {}
  10591. bool Success(const APValue &V, const Expr *e) {
  10592. Result = V.getFloat();
  10593. return true;
  10594. }
  10595. bool ZeroInitialization(const Expr *E) {
  10596. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  10597. return true;
  10598. }
  10599. bool VisitCallExpr(const CallExpr *E);
  10600. bool VisitUnaryOperator(const UnaryOperator *E);
  10601. bool VisitBinaryOperator(const BinaryOperator *E);
  10602. bool VisitFloatingLiteral(const FloatingLiteral *E);
  10603. bool VisitCastExpr(const CastExpr *E);
  10604. bool VisitUnaryReal(const UnaryOperator *E);
  10605. bool VisitUnaryImag(const UnaryOperator *E);
  10606. // FIXME: Missing: array subscript of vector, member of vector
  10607. };
  10608. } // end anonymous namespace
  10609. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  10610. assert(E->isRValue() && E->getType()->isRealFloatingType());
  10611. return FloatExprEvaluator(Info, Result).Visit(E);
  10612. }
  10613. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10614. QualType ResultTy,
  10615. const Expr *Arg,
  10616. bool SNaN,
  10617. llvm::APFloat &Result) {
  10618. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10619. if (!S) return false;
  10620. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10621. llvm::APInt fill;
  10622. // Treat empty strings as if they were zero.
  10623. if (S->getString().empty())
  10624. fill = llvm::APInt(32, 0);
  10625. else if (S->getString().getAsInteger(0, fill))
  10626. return false;
  10627. if (Context.getTargetInfo().isNan2008()) {
  10628. if (SNaN)
  10629. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10630. else
  10631. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10632. } else {
  10633. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10634. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10635. // a different encoding to what became a standard in 2008, and for pre-
  10636. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10637. // sNaN. This is now known as "legacy NaN" encoding.
  10638. if (SNaN)
  10639. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10640. else
  10641. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10642. }
  10643. return true;
  10644. }
  10645. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10646. switch (E->getBuiltinCallee()) {
  10647. default:
  10648. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10649. case Builtin::BI__builtin_huge_val:
  10650. case Builtin::BI__builtin_huge_valf:
  10651. case Builtin::BI__builtin_huge_vall:
  10652. case Builtin::BI__builtin_huge_valf128:
  10653. case Builtin::BI__builtin_inf:
  10654. case Builtin::BI__builtin_inff:
  10655. case Builtin::BI__builtin_infl:
  10656. case Builtin::BI__builtin_inff128: {
  10657. const llvm::fltSemantics &Sem =
  10658. Info.Ctx.getFloatTypeSemantics(E->getType());
  10659. Result = llvm::APFloat::getInf(Sem);
  10660. return true;
  10661. }
  10662. case Builtin::BI__builtin_nans:
  10663. case Builtin::BI__builtin_nansf:
  10664. case Builtin::BI__builtin_nansl:
  10665. case Builtin::BI__builtin_nansf128:
  10666. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10667. true, Result))
  10668. return Error(E);
  10669. return true;
  10670. case Builtin::BI__builtin_nan:
  10671. case Builtin::BI__builtin_nanf:
  10672. case Builtin::BI__builtin_nanl:
  10673. case Builtin::BI__builtin_nanf128:
  10674. // If this is __builtin_nan() turn this into a nan, otherwise we
  10675. // can't constant fold it.
  10676. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10677. false, Result))
  10678. return Error(E);
  10679. return true;
  10680. case Builtin::BI__builtin_fabs:
  10681. case Builtin::BI__builtin_fabsf:
  10682. case Builtin::BI__builtin_fabsl:
  10683. case Builtin::BI__builtin_fabsf128:
  10684. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10685. return false;
  10686. if (Result.isNegative())
  10687. Result.changeSign();
  10688. return true;
  10689. // FIXME: Builtin::BI__builtin_powi
  10690. // FIXME: Builtin::BI__builtin_powif
  10691. // FIXME: Builtin::BI__builtin_powil
  10692. case Builtin::BI__builtin_copysign:
  10693. case Builtin::BI__builtin_copysignf:
  10694. case Builtin::BI__builtin_copysignl:
  10695. case Builtin::BI__builtin_copysignf128: {
  10696. APFloat RHS(0.);
  10697. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10698. !EvaluateFloat(E->getArg(1), RHS, Info))
  10699. return false;
  10700. Result.copySign(RHS);
  10701. return true;
  10702. }
  10703. }
  10704. }
  10705. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10706. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10707. ComplexValue CV;
  10708. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10709. return false;
  10710. Result = CV.FloatReal;
  10711. return true;
  10712. }
  10713. return Visit(E->getSubExpr());
  10714. }
  10715. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10716. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10717. ComplexValue CV;
  10718. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10719. return false;
  10720. Result = CV.FloatImag;
  10721. return true;
  10722. }
  10723. VisitIgnoredValue(E->getSubExpr());
  10724. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  10725. Result = llvm::APFloat::getZero(Sem);
  10726. return true;
  10727. }
  10728. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10729. switch (E->getOpcode()) {
  10730. default: return Error(E);
  10731. case UO_Plus:
  10732. return EvaluateFloat(E->getSubExpr(), Result, Info);
  10733. case UO_Minus:
  10734. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  10735. return false;
  10736. Result.changeSign();
  10737. return true;
  10738. }
  10739. }
  10740. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10741. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10742. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10743. APFloat RHS(0.0);
  10744. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  10745. if (!LHSOK && !Info.noteFailure())
  10746. return false;
  10747. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  10748. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  10749. }
  10750. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  10751. Result = E->getValue();
  10752. return true;
  10753. }
  10754. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10755. const Expr* SubExpr = E->getSubExpr();
  10756. switch (E->getCastKind()) {
  10757. default:
  10758. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10759. case CK_IntegralToFloating: {
  10760. APSInt IntResult;
  10761. return EvaluateInteger(SubExpr, IntResult, Info) &&
  10762. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  10763. E->getType(), Result);
  10764. }
  10765. case CK_FloatingCast: {
  10766. if (!Visit(SubExpr))
  10767. return false;
  10768. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  10769. Result);
  10770. }
  10771. case CK_FloatingComplexToReal: {
  10772. ComplexValue V;
  10773. if (!EvaluateComplex(SubExpr, V, Info))
  10774. return false;
  10775. Result = V.getComplexFloatReal();
  10776. return true;
  10777. }
  10778. }
  10779. }
  10780. //===----------------------------------------------------------------------===//
  10781. // Complex Evaluation (for float and integer)
  10782. //===----------------------------------------------------------------------===//
  10783. namespace {
  10784. class ComplexExprEvaluator
  10785. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  10786. ComplexValue &Result;
  10787. public:
  10788. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  10789. : ExprEvaluatorBaseTy(info), Result(Result) {}
  10790. bool Success(const APValue &V, const Expr *e) {
  10791. Result.setFrom(V);
  10792. return true;
  10793. }
  10794. bool ZeroInitialization(const Expr *E);
  10795. //===--------------------------------------------------------------------===//
  10796. // Visitor Methods
  10797. //===--------------------------------------------------------------------===//
  10798. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  10799. bool VisitCastExpr(const CastExpr *E);
  10800. bool VisitBinaryOperator(const BinaryOperator *E);
  10801. bool VisitUnaryOperator(const UnaryOperator *E);
  10802. bool VisitInitListExpr(const InitListExpr *E);
  10803. };
  10804. } // end anonymous namespace
  10805. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  10806. EvalInfo &Info) {
  10807. assert(E->isRValue() && E->getType()->isAnyComplexType());
  10808. return ComplexExprEvaluator(Info, Result).Visit(E);
  10809. }
  10810. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  10811. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  10812. if (ElemTy->isRealFloatingType()) {
  10813. Result.makeComplexFloat();
  10814. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  10815. Result.FloatReal = Zero;
  10816. Result.FloatImag = Zero;
  10817. } else {
  10818. Result.makeComplexInt();
  10819. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  10820. Result.IntReal = Zero;
  10821. Result.IntImag = Zero;
  10822. }
  10823. return true;
  10824. }
  10825. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  10826. const Expr* SubExpr = E->getSubExpr();
  10827. if (SubExpr->getType()->isRealFloatingType()) {
  10828. Result.makeComplexFloat();
  10829. APFloat &Imag = Result.FloatImag;
  10830. if (!EvaluateFloat(SubExpr, Imag, Info))
  10831. return false;
  10832. Result.FloatReal = APFloat(Imag.getSemantics());
  10833. return true;
  10834. } else {
  10835. assert(SubExpr->getType()->isIntegerType() &&
  10836. "Unexpected imaginary literal.");
  10837. Result.makeComplexInt();
  10838. APSInt &Imag = Result.IntImag;
  10839. if (!EvaluateInteger(SubExpr, Imag, Info))
  10840. return false;
  10841. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  10842. return true;
  10843. }
  10844. }
  10845. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10846. switch (E->getCastKind()) {
  10847. case CK_BitCast:
  10848. case CK_BaseToDerived:
  10849. case CK_DerivedToBase:
  10850. case CK_UncheckedDerivedToBase:
  10851. case CK_Dynamic:
  10852. case CK_ToUnion:
  10853. case CK_ArrayToPointerDecay:
  10854. case CK_FunctionToPointerDecay:
  10855. case CK_NullToPointer:
  10856. case CK_NullToMemberPointer:
  10857. case CK_BaseToDerivedMemberPointer:
  10858. case CK_DerivedToBaseMemberPointer:
  10859. case CK_MemberPointerToBoolean:
  10860. case CK_ReinterpretMemberPointer:
  10861. case CK_ConstructorConversion:
  10862. case CK_IntegralToPointer:
  10863. case CK_PointerToIntegral:
  10864. case CK_PointerToBoolean:
  10865. case CK_ToVoid:
  10866. case CK_VectorSplat:
  10867. case CK_IntegralCast:
  10868. case CK_BooleanToSignedIntegral:
  10869. case CK_IntegralToBoolean:
  10870. case CK_IntegralToFloating:
  10871. case CK_FloatingToIntegral:
  10872. case CK_FloatingToBoolean:
  10873. case CK_FloatingCast:
  10874. case CK_CPointerToObjCPointerCast:
  10875. case CK_BlockPointerToObjCPointerCast:
  10876. case CK_AnyPointerToBlockPointerCast:
  10877. case CK_ObjCObjectLValueCast:
  10878. case CK_FloatingComplexToReal:
  10879. case CK_FloatingComplexToBoolean:
  10880. case CK_IntegralComplexToReal:
  10881. case CK_IntegralComplexToBoolean:
  10882. case CK_ARCProduceObject:
  10883. case CK_ARCConsumeObject:
  10884. case CK_ARCReclaimReturnedObject:
  10885. case CK_ARCExtendBlockObject:
  10886. case CK_CopyAndAutoreleaseBlockObject:
  10887. case CK_BuiltinFnToFnPtr:
  10888. case CK_ZeroToOCLOpaqueType:
  10889. case CK_NonAtomicToAtomic:
  10890. case CK_AddressSpaceConversion:
  10891. case CK_IntToOCLSampler:
  10892. case CK_FixedPointCast:
  10893. case CK_FixedPointToBoolean:
  10894. case CK_FixedPointToIntegral:
  10895. case CK_IntegralToFixedPoint:
  10896. llvm_unreachable("invalid cast kind for complex value");
  10897. case CK_LValueToRValue:
  10898. case CK_AtomicToNonAtomic:
  10899. case CK_NoOp:
  10900. case CK_LValueToRValueBitCast:
  10901. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10902. case CK_Dependent:
  10903. case CK_LValueBitCast:
  10904. case CK_UserDefinedConversion:
  10905. return Error(E);
  10906. case CK_FloatingRealToComplex: {
  10907. APFloat &Real = Result.FloatReal;
  10908. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  10909. return false;
  10910. Result.makeComplexFloat();
  10911. Result.FloatImag = APFloat(Real.getSemantics());
  10912. return true;
  10913. }
  10914. case CK_FloatingComplexCast: {
  10915. if (!Visit(E->getSubExpr()))
  10916. return false;
  10917. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10918. QualType From
  10919. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10920. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  10921. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  10922. }
  10923. case CK_FloatingComplexToIntegralComplex: {
  10924. if (!Visit(E->getSubExpr()))
  10925. return false;
  10926. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10927. QualType From
  10928. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10929. Result.makeComplexInt();
  10930. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  10931. To, Result.IntReal) &&
  10932. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  10933. To, Result.IntImag);
  10934. }
  10935. case CK_IntegralRealToComplex: {
  10936. APSInt &Real = Result.IntReal;
  10937. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  10938. return false;
  10939. Result.makeComplexInt();
  10940. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  10941. return true;
  10942. }
  10943. case CK_IntegralComplexCast: {
  10944. if (!Visit(E->getSubExpr()))
  10945. return false;
  10946. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10947. QualType From
  10948. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10949. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  10950. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  10951. return true;
  10952. }
  10953. case CK_IntegralComplexToFloatingComplex: {
  10954. if (!Visit(E->getSubExpr()))
  10955. return false;
  10956. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  10957. QualType From
  10958. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  10959. Result.makeComplexFloat();
  10960. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  10961. To, Result.FloatReal) &&
  10962. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  10963. To, Result.FloatImag);
  10964. }
  10965. }
  10966. llvm_unreachable("unknown cast resulting in complex value");
  10967. }
  10968. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10969. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10970. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10971. // Track whether the LHS or RHS is real at the type system level. When this is
  10972. // the case we can simplify our evaluation strategy.
  10973. bool LHSReal = false, RHSReal = false;
  10974. bool LHSOK;
  10975. if (E->getLHS()->getType()->isRealFloatingType()) {
  10976. LHSReal = true;
  10977. APFloat &Real = Result.FloatReal;
  10978. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  10979. if (LHSOK) {
  10980. Result.makeComplexFloat();
  10981. Result.FloatImag = APFloat(Real.getSemantics());
  10982. }
  10983. } else {
  10984. LHSOK = Visit(E->getLHS());
  10985. }
  10986. if (!LHSOK && !Info.noteFailure())
  10987. return false;
  10988. ComplexValue RHS;
  10989. if (E->getRHS()->getType()->isRealFloatingType()) {
  10990. RHSReal = true;
  10991. APFloat &Real = RHS.FloatReal;
  10992. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  10993. return false;
  10994. RHS.makeComplexFloat();
  10995. RHS.FloatImag = APFloat(Real.getSemantics());
  10996. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10997. return false;
  10998. assert(!(LHSReal && RHSReal) &&
  10999. "Cannot have both operands of a complex operation be real.");
  11000. switch (E->getOpcode()) {
  11001. default: return Error(E);
  11002. case BO_Add:
  11003. if (Result.isComplexFloat()) {
  11004. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  11005. APFloat::rmNearestTiesToEven);
  11006. if (LHSReal)
  11007. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11008. else if (!RHSReal)
  11009. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  11010. APFloat::rmNearestTiesToEven);
  11011. } else {
  11012. Result.getComplexIntReal() += RHS.getComplexIntReal();
  11013. Result.getComplexIntImag() += RHS.getComplexIntImag();
  11014. }
  11015. break;
  11016. case BO_Sub:
  11017. if (Result.isComplexFloat()) {
  11018. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  11019. APFloat::rmNearestTiesToEven);
  11020. if (LHSReal) {
  11021. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11022. Result.getComplexFloatImag().changeSign();
  11023. } else if (!RHSReal) {
  11024. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  11025. APFloat::rmNearestTiesToEven);
  11026. }
  11027. } else {
  11028. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  11029. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  11030. }
  11031. break;
  11032. case BO_Mul:
  11033. if (Result.isComplexFloat()) {
  11034. // This is an implementation of complex multiplication according to the
  11035. // constraints laid out in C11 Annex G. The implementation uses the
  11036. // following naming scheme:
  11037. // (a + ib) * (c + id)
  11038. ComplexValue LHS = Result;
  11039. APFloat &A = LHS.getComplexFloatReal();
  11040. APFloat &B = LHS.getComplexFloatImag();
  11041. APFloat &C = RHS.getComplexFloatReal();
  11042. APFloat &D = RHS.getComplexFloatImag();
  11043. APFloat &ResR = Result.getComplexFloatReal();
  11044. APFloat &ResI = Result.getComplexFloatImag();
  11045. if (LHSReal) {
  11046. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  11047. ResR = A * C;
  11048. ResI = A * D;
  11049. } else if (RHSReal) {
  11050. ResR = C * A;
  11051. ResI = C * B;
  11052. } else {
  11053. // In the fully general case, we need to handle NaNs and infinities
  11054. // robustly.
  11055. APFloat AC = A * C;
  11056. APFloat BD = B * D;
  11057. APFloat AD = A * D;
  11058. APFloat BC = B * C;
  11059. ResR = AC - BD;
  11060. ResI = AD + BC;
  11061. if (ResR.isNaN() && ResI.isNaN()) {
  11062. bool Recalc = false;
  11063. if (A.isInfinity() || B.isInfinity()) {
  11064. A = APFloat::copySign(
  11065. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11066. B = APFloat::copySign(
  11067. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11068. if (C.isNaN())
  11069. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11070. if (D.isNaN())
  11071. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11072. Recalc = true;
  11073. }
  11074. if (C.isInfinity() || D.isInfinity()) {
  11075. C = APFloat::copySign(
  11076. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11077. D = APFloat::copySign(
  11078. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11079. if (A.isNaN())
  11080. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11081. if (B.isNaN())
  11082. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11083. Recalc = true;
  11084. }
  11085. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  11086. AD.isInfinity() || BC.isInfinity())) {
  11087. if (A.isNaN())
  11088. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11089. if (B.isNaN())
  11090. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11091. if (C.isNaN())
  11092. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11093. if (D.isNaN())
  11094. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11095. Recalc = true;
  11096. }
  11097. if (Recalc) {
  11098. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  11099. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  11100. }
  11101. }
  11102. }
  11103. } else {
  11104. ComplexValue LHS = Result;
  11105. Result.getComplexIntReal() =
  11106. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  11107. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  11108. Result.getComplexIntImag() =
  11109. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  11110. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  11111. }
  11112. break;
  11113. case BO_Div:
  11114. if (Result.isComplexFloat()) {
  11115. // This is an implementation of complex division according to the
  11116. // constraints laid out in C11 Annex G. The implementation uses the
  11117. // following naming scheme:
  11118. // (a + ib) / (c + id)
  11119. ComplexValue LHS = Result;
  11120. APFloat &A = LHS.getComplexFloatReal();
  11121. APFloat &B = LHS.getComplexFloatImag();
  11122. APFloat &C = RHS.getComplexFloatReal();
  11123. APFloat &D = RHS.getComplexFloatImag();
  11124. APFloat &ResR = Result.getComplexFloatReal();
  11125. APFloat &ResI = Result.getComplexFloatImag();
  11126. if (RHSReal) {
  11127. ResR = A / C;
  11128. ResI = B / C;
  11129. } else {
  11130. if (LHSReal) {
  11131. // No real optimizations we can do here, stub out with zero.
  11132. B = APFloat::getZero(A.getSemantics());
  11133. }
  11134. int DenomLogB = 0;
  11135. APFloat MaxCD = maxnum(abs(C), abs(D));
  11136. if (MaxCD.isFinite()) {
  11137. DenomLogB = ilogb(MaxCD);
  11138. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  11139. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  11140. }
  11141. APFloat Denom = C * C + D * D;
  11142. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  11143. APFloat::rmNearestTiesToEven);
  11144. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  11145. APFloat::rmNearestTiesToEven);
  11146. if (ResR.isNaN() && ResI.isNaN()) {
  11147. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  11148. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  11149. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  11150. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  11151. D.isFinite()) {
  11152. A = APFloat::copySign(
  11153. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11154. B = APFloat::copySign(
  11155. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11156. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  11157. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  11158. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  11159. C = APFloat::copySign(
  11160. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11161. D = APFloat::copySign(
  11162. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11163. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  11164. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  11165. }
  11166. }
  11167. }
  11168. } else {
  11169. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  11170. return Error(E, diag::note_expr_divide_by_zero);
  11171. ComplexValue LHS = Result;
  11172. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11173. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  11174. Result.getComplexIntReal() =
  11175. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11176. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  11177. Result.getComplexIntImag() =
  11178. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  11179. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  11180. }
  11181. break;
  11182. }
  11183. return true;
  11184. }
  11185. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11186. // Get the operand value into 'Result'.
  11187. if (!Visit(E->getSubExpr()))
  11188. return false;
  11189. switch (E->getOpcode()) {
  11190. default:
  11191. return Error(E);
  11192. case UO_Extension:
  11193. return true;
  11194. case UO_Plus:
  11195. // The result is always just the subexpr.
  11196. return true;
  11197. case UO_Minus:
  11198. if (Result.isComplexFloat()) {
  11199. Result.getComplexFloatReal().changeSign();
  11200. Result.getComplexFloatImag().changeSign();
  11201. }
  11202. else {
  11203. Result.getComplexIntReal() = -Result.getComplexIntReal();
  11204. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11205. }
  11206. return true;
  11207. case UO_Not:
  11208. if (Result.isComplexFloat())
  11209. Result.getComplexFloatImag().changeSign();
  11210. else
  11211. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11212. return true;
  11213. }
  11214. }
  11215. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  11216. if (E->getNumInits() == 2) {
  11217. if (E->getType()->isComplexType()) {
  11218. Result.makeComplexFloat();
  11219. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  11220. return false;
  11221. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  11222. return false;
  11223. } else {
  11224. Result.makeComplexInt();
  11225. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  11226. return false;
  11227. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  11228. return false;
  11229. }
  11230. return true;
  11231. }
  11232. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  11233. }
  11234. //===----------------------------------------------------------------------===//
  11235. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  11236. // implicit conversion.
  11237. //===----------------------------------------------------------------------===//
  11238. namespace {
  11239. class AtomicExprEvaluator :
  11240. public ExprEvaluatorBase<AtomicExprEvaluator> {
  11241. const LValue *This;
  11242. APValue &Result;
  11243. public:
  11244. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  11245. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  11246. bool Success(const APValue &V, const Expr *E) {
  11247. Result = V;
  11248. return true;
  11249. }
  11250. bool ZeroInitialization(const Expr *E) {
  11251. ImplicitValueInitExpr VIE(
  11252. E->getType()->castAs<AtomicType>()->getValueType());
  11253. // For atomic-qualified class (and array) types in C++, initialize the
  11254. // _Atomic-wrapped subobject directly, in-place.
  11255. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  11256. : Evaluate(Result, Info, &VIE);
  11257. }
  11258. bool VisitCastExpr(const CastExpr *E) {
  11259. switch (E->getCastKind()) {
  11260. default:
  11261. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11262. case CK_NonAtomicToAtomic:
  11263. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  11264. : Evaluate(Result, Info, E->getSubExpr());
  11265. }
  11266. }
  11267. };
  11268. } // end anonymous namespace
  11269. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  11270. EvalInfo &Info) {
  11271. assert(E->isRValue() && E->getType()->isAtomicType());
  11272. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  11273. }
  11274. //===----------------------------------------------------------------------===//
  11275. // Void expression evaluation, primarily for a cast to void on the LHS of a
  11276. // comma operator
  11277. //===----------------------------------------------------------------------===//
  11278. namespace {
  11279. class VoidExprEvaluator
  11280. : public ExprEvaluatorBase<VoidExprEvaluator> {
  11281. public:
  11282. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  11283. bool Success(const APValue &V, const Expr *e) { return true; }
  11284. bool ZeroInitialization(const Expr *E) { return true; }
  11285. bool VisitCastExpr(const CastExpr *E) {
  11286. switch (E->getCastKind()) {
  11287. default:
  11288. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11289. case CK_ToVoid:
  11290. VisitIgnoredValue(E->getSubExpr());
  11291. return true;
  11292. }
  11293. }
  11294. bool VisitCallExpr(const CallExpr *E) {
  11295. switch (E->getBuiltinCallee()) {
  11296. default:
  11297. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  11298. case Builtin::BI__assume:
  11299. case Builtin::BI__builtin_assume:
  11300. // The argument is not evaluated!
  11301. return true;
  11302. }
  11303. }
  11304. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  11305. };
  11306. } // end anonymous namespace
  11307. static bool hasVirtualDestructor(QualType T) {
  11308. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  11309. if (CXXDestructorDecl *DD = RD->getDestructor())
  11310. return DD->isVirtual();
  11311. return false;
  11312. }
  11313. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  11314. // We cannot speculatively evaluate a delete expression.
  11315. if (Info.SpeculativeEvaluationDepth)
  11316. return false;
  11317. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  11318. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  11319. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11320. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  11321. return false;
  11322. }
  11323. const Expr *Arg = E->getArgument();
  11324. LValue Pointer;
  11325. if (!EvaluatePointer(Arg, Pointer, Info))
  11326. return false;
  11327. if (Pointer.Designator.Invalid)
  11328. return false;
  11329. // Deleting a null pointer has no effect.
  11330. if (Pointer.isNullPointer()) {
  11331. // This is the only case where we need to produce an extension warning:
  11332. // the only other way we can succeed is if we find a dynamic allocation,
  11333. // and we will have warned when we allocated it in that case.
  11334. if (!Info.getLangOpts().CPlusPlus2a)
  11335. Info.CCEDiag(E, diag::note_constexpr_new);
  11336. return true;
  11337. }
  11338. auto PointerAsString = [&] {
  11339. APValue Printable;
  11340. Pointer.moveInto(Printable);
  11341. return Printable.getAsString(Info.Ctx, Arg->getType());
  11342. };
  11343. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  11344. if (!DA) {
  11345. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  11346. << PointerAsString();
  11347. if (Pointer.Base)
  11348. NoteLValueLocation(Info, Pointer.Base);
  11349. return false;
  11350. }
  11351. QualType AllocType = Pointer.Base.getDynamicAllocType();
  11352. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  11353. if (!Alloc) {
  11354. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11355. return false;
  11356. }
  11357. if (E->isArrayForm() != AllocType->isConstantArrayType()) {
  11358. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  11359. << E->isArrayForm() << AllocType;
  11360. NoteLValueLocation(Info, Pointer.Base);
  11361. return false;
  11362. }
  11363. bool Subobject = false;
  11364. if (E->isArrayForm()) {
  11365. Subobject = Pointer.Designator.Entries.size() != 1 ||
  11366. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  11367. } else {
  11368. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  11369. Pointer.Designator.isOnePastTheEnd();
  11370. }
  11371. if (Subobject) {
  11372. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  11373. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  11374. return false;
  11375. }
  11376. // For the non-array case, the designator must be empty if the static type
  11377. // does not have a virtual destructor.
  11378. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  11379. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  11380. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  11381. << Arg->getType()->getPointeeType() << AllocType;
  11382. return false;
  11383. }
  11384. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  11385. (*Alloc)->Value, AllocType))
  11386. return false;
  11387. if (!Info.HeapAllocs.erase(DA)) {
  11388. // The element was already erased. This means the destructor call also
  11389. // deleted the object.
  11390. // FIXME: This probably results in undefined behavior before we get this
  11391. // far, and should be diagnosed elsewhere first.
  11392. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11393. return false;
  11394. }
  11395. return true;
  11396. }
  11397. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  11398. assert(E->isRValue() && E->getType()->isVoidType());
  11399. return VoidExprEvaluator(Info).Visit(E);
  11400. }
  11401. //===----------------------------------------------------------------------===//
  11402. // Top level Expr::EvaluateAsRValue method.
  11403. //===----------------------------------------------------------------------===//
  11404. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  11405. // In C, function designators are not lvalues, but we evaluate them as if they
  11406. // are.
  11407. QualType T = E->getType();
  11408. if (E->isGLValue() || T->isFunctionType()) {
  11409. LValue LV;
  11410. if (!EvaluateLValue(E, LV, Info))
  11411. return false;
  11412. LV.moveInto(Result);
  11413. } else if (T->isVectorType()) {
  11414. if (!EvaluateVector(E, Result, Info))
  11415. return false;
  11416. } else if (T->isIntegralOrEnumerationType()) {
  11417. if (!IntExprEvaluator(Info, Result).Visit(E))
  11418. return false;
  11419. } else if (T->hasPointerRepresentation()) {
  11420. LValue LV;
  11421. if (!EvaluatePointer(E, LV, Info))
  11422. return false;
  11423. LV.moveInto(Result);
  11424. } else if (T->isRealFloatingType()) {
  11425. llvm::APFloat F(0.0);
  11426. if (!EvaluateFloat(E, F, Info))
  11427. return false;
  11428. Result = APValue(F);
  11429. } else if (T->isAnyComplexType()) {
  11430. ComplexValue C;
  11431. if (!EvaluateComplex(E, C, Info))
  11432. return false;
  11433. C.moveInto(Result);
  11434. } else if (T->isFixedPointType()) {
  11435. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  11436. } else if (T->isMemberPointerType()) {
  11437. MemberPtr P;
  11438. if (!EvaluateMemberPointer(E, P, Info))
  11439. return false;
  11440. P.moveInto(Result);
  11441. return true;
  11442. } else if (T->isArrayType()) {
  11443. LValue LV;
  11444. APValue &Value =
  11445. Info.CurrentCall->createTemporary(E, T, false, LV);
  11446. if (!EvaluateArray(E, LV, Value, Info))
  11447. return false;
  11448. Result = Value;
  11449. } else if (T->isRecordType()) {
  11450. LValue LV;
  11451. APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
  11452. if (!EvaluateRecord(E, LV, Value, Info))
  11453. return false;
  11454. Result = Value;
  11455. } else if (T->isVoidType()) {
  11456. if (!Info.getLangOpts().CPlusPlus11)
  11457. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  11458. << E->getType();
  11459. if (!EvaluateVoid(E, Info))
  11460. return false;
  11461. } else if (T->isAtomicType()) {
  11462. QualType Unqual = T.getAtomicUnqualifiedType();
  11463. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  11464. LValue LV;
  11465. APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
  11466. if (!EvaluateAtomic(E, &LV, Value, Info))
  11467. return false;
  11468. } else {
  11469. if (!EvaluateAtomic(E, nullptr, Result, Info))
  11470. return false;
  11471. }
  11472. } else if (Info.getLangOpts().CPlusPlus11) {
  11473. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  11474. return false;
  11475. } else {
  11476. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11477. return false;
  11478. }
  11479. return true;
  11480. }
  11481. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  11482. /// cases, the in-place evaluation is essential, since later initializers for
  11483. /// an object can indirectly refer to subobjects which were initialized earlier.
  11484. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  11485. const Expr *E, bool AllowNonLiteralTypes) {
  11486. assert(!E->isValueDependent());
  11487. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  11488. return false;
  11489. if (E->isRValue()) {
  11490. // Evaluate arrays and record types in-place, so that later initializers can
  11491. // refer to earlier-initialized members of the object.
  11492. QualType T = E->getType();
  11493. if (T->isArrayType())
  11494. return EvaluateArray(E, This, Result, Info);
  11495. else if (T->isRecordType())
  11496. return EvaluateRecord(E, This, Result, Info);
  11497. else if (T->isAtomicType()) {
  11498. QualType Unqual = T.getAtomicUnqualifiedType();
  11499. if (Unqual->isArrayType() || Unqual->isRecordType())
  11500. return EvaluateAtomic(E, &This, Result, Info);
  11501. }
  11502. }
  11503. // For any other type, in-place evaluation is unimportant.
  11504. return Evaluate(Result, Info, E);
  11505. }
  11506. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  11507. /// lvalue-to-rvalue cast if it is an lvalue.
  11508. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  11509. if (Info.EnableNewConstInterp) {
  11510. auto &InterpCtx = Info.Ctx.getInterpContext();
  11511. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  11512. case interp::InterpResult::Success:
  11513. return true;
  11514. case interp::InterpResult::Fail:
  11515. return false;
  11516. case interp::InterpResult::Bail:
  11517. break;
  11518. }
  11519. }
  11520. if (E->getType().isNull())
  11521. return false;
  11522. if (!CheckLiteralType(Info, E))
  11523. return false;
  11524. if (!::Evaluate(Result, Info, E))
  11525. return false;
  11526. if (E->isGLValue()) {
  11527. LValue LV;
  11528. LV.setFrom(Info.Ctx, Result);
  11529. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11530. return false;
  11531. }
  11532. // Check this core constant expression is a constant expression.
  11533. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
  11534. CheckMemoryLeaks(Info);
  11535. }
  11536. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  11537. const ASTContext &Ctx, bool &IsConst) {
  11538. // Fast-path evaluations of integer literals, since we sometimes see files
  11539. // containing vast quantities of these.
  11540. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  11541. Result.Val = APValue(APSInt(L->getValue(),
  11542. L->getType()->isUnsignedIntegerType()));
  11543. IsConst = true;
  11544. return true;
  11545. }
  11546. // This case should be rare, but we need to check it before we check on
  11547. // the type below.
  11548. if (Exp->getType().isNull()) {
  11549. IsConst = false;
  11550. return true;
  11551. }
  11552. // FIXME: Evaluating values of large array and record types can cause
  11553. // performance problems. Only do so in C++11 for now.
  11554. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  11555. Exp->getType()->isRecordType()) &&
  11556. !Ctx.getLangOpts().CPlusPlus11) {
  11557. IsConst = false;
  11558. return true;
  11559. }
  11560. return false;
  11561. }
  11562. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  11563. Expr::SideEffectsKind SEK) {
  11564. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  11565. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  11566. }
  11567. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  11568. const ASTContext &Ctx, EvalInfo &Info) {
  11569. bool IsConst;
  11570. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  11571. return IsConst;
  11572. return EvaluateAsRValue(Info, E, Result.Val);
  11573. }
  11574. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  11575. const ASTContext &Ctx,
  11576. Expr::SideEffectsKind AllowSideEffects,
  11577. EvalInfo &Info) {
  11578. if (!E->getType()->isIntegralOrEnumerationType())
  11579. return false;
  11580. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  11581. !ExprResult.Val.isInt() ||
  11582. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11583. return false;
  11584. return true;
  11585. }
  11586. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  11587. const ASTContext &Ctx,
  11588. Expr::SideEffectsKind AllowSideEffects,
  11589. EvalInfo &Info) {
  11590. if (!E->getType()->isFixedPointType())
  11591. return false;
  11592. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  11593. return false;
  11594. if (!ExprResult.Val.isFixedPoint() ||
  11595. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11596. return false;
  11597. return true;
  11598. }
  11599. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  11600. /// any crazy technique (that has nothing to do with language standards) that
  11601. /// we want to. If this function returns true, it returns the folded constant
  11602. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  11603. /// will be applied to the result.
  11604. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  11605. bool InConstantContext) const {
  11606. assert(!isValueDependent() &&
  11607. "Expression evaluator can't be called on a dependent expression.");
  11608. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11609. Info.InConstantContext = InConstantContext;
  11610. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  11611. }
  11612. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  11613. bool InConstantContext) const {
  11614. assert(!isValueDependent() &&
  11615. "Expression evaluator can't be called on a dependent expression.");
  11616. EvalResult Scratch;
  11617. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  11618. HandleConversionToBool(Scratch.Val, Result);
  11619. }
  11620. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  11621. SideEffectsKind AllowSideEffects,
  11622. bool InConstantContext) const {
  11623. assert(!isValueDependent() &&
  11624. "Expression evaluator can't be called on a dependent expression.");
  11625. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11626. Info.InConstantContext = InConstantContext;
  11627. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  11628. }
  11629. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  11630. SideEffectsKind AllowSideEffects,
  11631. bool InConstantContext) const {
  11632. assert(!isValueDependent() &&
  11633. "Expression evaluator can't be called on a dependent expression.");
  11634. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11635. Info.InConstantContext = InConstantContext;
  11636. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  11637. }
  11638. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  11639. SideEffectsKind AllowSideEffects,
  11640. bool InConstantContext) const {
  11641. assert(!isValueDependent() &&
  11642. "Expression evaluator can't be called on a dependent expression.");
  11643. if (!getType()->isRealFloatingType())
  11644. return false;
  11645. EvalResult ExprResult;
  11646. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  11647. !ExprResult.Val.isFloat() ||
  11648. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11649. return false;
  11650. Result = ExprResult.Val.getFloat();
  11651. return true;
  11652. }
  11653. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  11654. bool InConstantContext) const {
  11655. assert(!isValueDependent() &&
  11656. "Expression evaluator can't be called on a dependent expression.");
  11657. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  11658. Info.InConstantContext = InConstantContext;
  11659. LValue LV;
  11660. CheckedTemporaries CheckedTemps;
  11661. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  11662. Result.HasSideEffects ||
  11663. !CheckLValueConstantExpression(Info, getExprLoc(),
  11664. Ctx.getLValueReferenceType(getType()), LV,
  11665. Expr::EvaluateForCodeGen, CheckedTemps))
  11666. return false;
  11667. LV.moveInto(Result.Val);
  11668. return true;
  11669. }
  11670. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  11671. const ASTContext &Ctx) const {
  11672. assert(!isValueDependent() &&
  11673. "Expression evaluator can't be called on a dependent expression.");
  11674. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  11675. EvalInfo Info(Ctx, Result, EM);
  11676. Info.InConstantContext = true;
  11677. if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
  11678. return false;
  11679. if (!Info.discardCleanups())
  11680. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11681. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  11682. Usage) &&
  11683. CheckMemoryLeaks(Info);
  11684. }
  11685. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  11686. const VarDecl *VD,
  11687. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11688. assert(!isValueDependent() &&
  11689. "Expression evaluator can't be called on a dependent expression.");
  11690. // FIXME: Evaluating initializers for large array and record types can cause
  11691. // performance problems. Only do so in C++11 for now.
  11692. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  11693. !Ctx.getLangOpts().CPlusPlus11)
  11694. return false;
  11695. Expr::EvalStatus EStatus;
  11696. EStatus.Diag = &Notes;
  11697. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  11698. ? EvalInfo::EM_ConstantExpression
  11699. : EvalInfo::EM_ConstantFold);
  11700. Info.setEvaluatingDecl(VD, Value);
  11701. Info.InConstantContext = true;
  11702. SourceLocation DeclLoc = VD->getLocation();
  11703. QualType DeclTy = VD->getType();
  11704. if (Info.EnableNewConstInterp) {
  11705. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  11706. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  11707. case interp::InterpResult::Fail:
  11708. // Bail out if an error was encountered.
  11709. return false;
  11710. case interp::InterpResult::Success:
  11711. // Evaluation succeeded and value was set.
  11712. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  11713. case interp::InterpResult::Bail:
  11714. // Evaluate the value again for the tree evaluator to use.
  11715. break;
  11716. }
  11717. }
  11718. LValue LVal;
  11719. LVal.set(VD);
  11720. // C++11 [basic.start.init]p2:
  11721. // Variables with static storage duration or thread storage duration shall be
  11722. // zero-initialized before any other initialization takes place.
  11723. // This behavior is not present in C.
  11724. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  11725. !DeclTy->isReferenceType()) {
  11726. ImplicitValueInitExpr VIE(DeclTy);
  11727. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  11728. /*AllowNonLiteralTypes=*/true))
  11729. return false;
  11730. }
  11731. if (!EvaluateInPlace(Value, Info, LVal, this,
  11732. /*AllowNonLiteralTypes=*/true) ||
  11733. EStatus.HasSideEffects)
  11734. return false;
  11735. // At this point, any lifetime-extended temporaries are completely
  11736. // initialized.
  11737. Info.performLifetimeExtension();
  11738. if (!Info.discardCleanups())
  11739. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11740. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
  11741. CheckMemoryLeaks(Info);
  11742. }
  11743. bool VarDecl::evaluateDestruction(
  11744. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11745. assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
  11746. "cannot evaluate destruction of non-constant-initialized variable");
  11747. Expr::EvalStatus EStatus;
  11748. EStatus.Diag = &Notes;
  11749. // Make a copy of the value for the destructor to mutate.
  11750. APValue DestroyedValue = *getEvaluatedValue();
  11751. EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
  11752. Info.setEvaluatingDecl(this, DestroyedValue,
  11753. EvalInfo::EvaluatingDeclKind::Dtor);
  11754. Info.InConstantContext = true;
  11755. SourceLocation DeclLoc = getLocation();
  11756. QualType DeclTy = getType();
  11757. LValue LVal;
  11758. LVal.set(this);
  11759. // FIXME: Consider storing whether this variable has constant destruction in
  11760. // the EvaluatedStmt so that CodeGen can query it.
  11761. if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
  11762. EStatus.HasSideEffects)
  11763. return false;
  11764. if (!Info.discardCleanups())
  11765. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11766. ensureEvaluatedStmt()->HasConstantDestruction = true;
  11767. return true;
  11768. }
  11769. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  11770. /// constant folded, but discard the result.
  11771. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  11772. assert(!isValueDependent() &&
  11773. "Expression evaluator can't be called on a dependent expression.");
  11774. EvalResult Result;
  11775. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  11776. !hasUnacceptableSideEffect(Result, SEK);
  11777. }
  11778. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  11779. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11780. assert(!isValueDependent() &&
  11781. "Expression evaluator can't be called on a dependent expression.");
  11782. EvalResult EVResult;
  11783. EVResult.Diag = Diag;
  11784. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11785. Info.InConstantContext = true;
  11786. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  11787. (void)Result;
  11788. assert(Result && "Could not evaluate expression");
  11789. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11790. return EVResult.Val.getInt();
  11791. }
  11792. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  11793. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11794. assert(!isValueDependent() &&
  11795. "Expression evaluator can't be called on a dependent expression.");
  11796. EvalResult EVResult;
  11797. EVResult.Diag = Diag;
  11798. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11799. Info.InConstantContext = true;
  11800. Info.CheckingForUndefinedBehavior = true;
  11801. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  11802. (void)Result;
  11803. assert(Result && "Could not evaluate expression");
  11804. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11805. return EVResult.Val.getInt();
  11806. }
  11807. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  11808. assert(!isValueDependent() &&
  11809. "Expression evaluator can't be called on a dependent expression.");
  11810. bool IsConst;
  11811. EvalResult EVResult;
  11812. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  11813. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11814. Info.CheckingForUndefinedBehavior = true;
  11815. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  11816. }
  11817. }
  11818. bool Expr::EvalResult::isGlobalLValue() const {
  11819. assert(Val.isLValue());
  11820. return IsGlobalLValue(Val.getLValueBase());
  11821. }
  11822. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  11823. /// an integer constant expression.
  11824. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  11825. /// comma, etc
  11826. // CheckICE - This function does the fundamental ICE checking: the returned
  11827. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  11828. // and a (possibly null) SourceLocation indicating the location of the problem.
  11829. //
  11830. // Note that to reduce code duplication, this helper does no evaluation
  11831. // itself; the caller checks whether the expression is evaluatable, and
  11832. // in the rare cases where CheckICE actually cares about the evaluated
  11833. // value, it calls into Evaluate.
  11834. namespace {
  11835. enum ICEKind {
  11836. /// This expression is an ICE.
  11837. IK_ICE,
  11838. /// This expression is not an ICE, but if it isn't evaluated, it's
  11839. /// a legal subexpression for an ICE. This return value is used to handle
  11840. /// the comma operator in C99 mode, and non-constant subexpressions.
  11841. IK_ICEIfUnevaluated,
  11842. /// This expression is not an ICE, and is not a legal subexpression for one.
  11843. IK_NotICE
  11844. };
  11845. struct ICEDiag {
  11846. ICEKind Kind;
  11847. SourceLocation Loc;
  11848. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  11849. };
  11850. }
  11851. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  11852. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  11853. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  11854. Expr::EvalResult EVResult;
  11855. Expr::EvalStatus Status;
  11856. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11857. Info.InConstantContext = true;
  11858. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  11859. !EVResult.Val.isInt())
  11860. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11861. return NoDiag();
  11862. }
  11863. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  11864. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  11865. if (!E->getType()->isIntegralOrEnumerationType())
  11866. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11867. switch (E->getStmtClass()) {
  11868. #define ABSTRACT_STMT(Node)
  11869. #define STMT(Node, Base) case Expr::Node##Class:
  11870. #define EXPR(Node, Base)
  11871. #include "clang/AST/StmtNodes.inc"
  11872. case Expr::PredefinedExprClass:
  11873. case Expr::FloatingLiteralClass:
  11874. case Expr::ImaginaryLiteralClass:
  11875. case Expr::StringLiteralClass:
  11876. case Expr::ArraySubscriptExprClass:
  11877. case Expr::OMPArraySectionExprClass:
  11878. case Expr::MemberExprClass:
  11879. case Expr::CompoundAssignOperatorClass:
  11880. case Expr::CompoundLiteralExprClass:
  11881. case Expr::ExtVectorElementExprClass:
  11882. case Expr::DesignatedInitExprClass:
  11883. case Expr::ArrayInitLoopExprClass:
  11884. case Expr::ArrayInitIndexExprClass:
  11885. case Expr::NoInitExprClass:
  11886. case Expr::DesignatedInitUpdateExprClass:
  11887. case Expr::ImplicitValueInitExprClass:
  11888. case Expr::ParenListExprClass:
  11889. case Expr::VAArgExprClass:
  11890. case Expr::AddrLabelExprClass:
  11891. case Expr::StmtExprClass:
  11892. case Expr::CXXMemberCallExprClass:
  11893. case Expr::CUDAKernelCallExprClass:
  11894. case Expr::CXXDynamicCastExprClass:
  11895. case Expr::CXXTypeidExprClass:
  11896. case Expr::CXXUuidofExprClass:
  11897. case Expr::MSPropertyRefExprClass:
  11898. case Expr::MSPropertySubscriptExprClass:
  11899. case Expr::CXXNullPtrLiteralExprClass:
  11900. case Expr::UserDefinedLiteralClass:
  11901. case Expr::CXXThisExprClass:
  11902. case Expr::CXXThrowExprClass:
  11903. case Expr::CXXNewExprClass:
  11904. case Expr::CXXDeleteExprClass:
  11905. case Expr::CXXPseudoDestructorExprClass:
  11906. case Expr::UnresolvedLookupExprClass:
  11907. case Expr::TypoExprClass:
  11908. case Expr::DependentScopeDeclRefExprClass:
  11909. case Expr::CXXConstructExprClass:
  11910. case Expr::CXXInheritedCtorInitExprClass:
  11911. case Expr::CXXStdInitializerListExprClass:
  11912. case Expr::CXXBindTemporaryExprClass:
  11913. case Expr::ExprWithCleanupsClass:
  11914. case Expr::CXXTemporaryObjectExprClass:
  11915. case Expr::CXXUnresolvedConstructExprClass:
  11916. case Expr::CXXDependentScopeMemberExprClass:
  11917. case Expr::UnresolvedMemberExprClass:
  11918. case Expr::ObjCStringLiteralClass:
  11919. case Expr::ObjCBoxedExprClass:
  11920. case Expr::ObjCArrayLiteralClass:
  11921. case Expr::ObjCDictionaryLiteralClass:
  11922. case Expr::ObjCEncodeExprClass:
  11923. case Expr::ObjCMessageExprClass:
  11924. case Expr::ObjCSelectorExprClass:
  11925. case Expr::ObjCProtocolExprClass:
  11926. case Expr::ObjCIvarRefExprClass:
  11927. case Expr::ObjCPropertyRefExprClass:
  11928. case Expr::ObjCSubscriptRefExprClass:
  11929. case Expr::ObjCIsaExprClass:
  11930. case Expr::ObjCAvailabilityCheckExprClass:
  11931. case Expr::ShuffleVectorExprClass:
  11932. case Expr::ConvertVectorExprClass:
  11933. case Expr::BlockExprClass:
  11934. case Expr::NoStmtClass:
  11935. case Expr::OpaqueValueExprClass:
  11936. case Expr::PackExpansionExprClass:
  11937. case Expr::SubstNonTypeTemplateParmPackExprClass:
  11938. case Expr::FunctionParmPackExprClass:
  11939. case Expr::AsTypeExprClass:
  11940. case Expr::ObjCIndirectCopyRestoreExprClass:
  11941. case Expr::MaterializeTemporaryExprClass:
  11942. case Expr::PseudoObjectExprClass:
  11943. case Expr::AtomicExprClass:
  11944. case Expr::LambdaExprClass:
  11945. case Expr::CXXFoldExprClass:
  11946. case Expr::CoawaitExprClass:
  11947. case Expr::DependentCoawaitExprClass:
  11948. case Expr::CoyieldExprClass:
  11949. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11950. case Expr::InitListExprClass: {
  11951. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  11952. // form "T x = { a };" is equivalent to "T x = a;".
  11953. // Unless we're initializing a reference, T is a scalar as it is known to be
  11954. // of integral or enumeration type.
  11955. if (E->isRValue())
  11956. if (cast<InitListExpr>(E)->getNumInits() == 1)
  11957. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  11958. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11959. }
  11960. case Expr::SizeOfPackExprClass:
  11961. case Expr::GNUNullExprClass:
  11962. case Expr::SourceLocExprClass:
  11963. return NoDiag();
  11964. case Expr::SubstNonTypeTemplateParmExprClass:
  11965. return
  11966. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  11967. case Expr::ConstantExprClass:
  11968. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  11969. case Expr::ParenExprClass:
  11970. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  11971. case Expr::GenericSelectionExprClass:
  11972. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  11973. case Expr::IntegerLiteralClass:
  11974. case Expr::FixedPointLiteralClass:
  11975. case Expr::CharacterLiteralClass:
  11976. case Expr::ObjCBoolLiteralExprClass:
  11977. case Expr::CXXBoolLiteralExprClass:
  11978. case Expr::CXXScalarValueInitExprClass:
  11979. case Expr::TypeTraitExprClass:
  11980. case Expr::ArrayTypeTraitExprClass:
  11981. case Expr::ExpressionTraitExprClass:
  11982. case Expr::CXXNoexceptExprClass:
  11983. return NoDiag();
  11984. case Expr::CallExprClass:
  11985. case Expr::CXXOperatorCallExprClass: {
  11986. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  11987. // constant expressions, but they can never be ICEs because an ICE cannot
  11988. // contain an operand of (pointer to) function type.
  11989. const CallExpr *CE = cast<CallExpr>(E);
  11990. if (CE->getBuiltinCallee())
  11991. return CheckEvalInICE(E, Ctx);
  11992. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11993. }
  11994. case Expr::DeclRefExprClass: {
  11995. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  11996. return NoDiag();
  11997. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  11998. if (Ctx.getLangOpts().CPlusPlus &&
  11999. D && IsConstNonVolatile(D->getType())) {
  12000. // Parameter variables are never constants. Without this check,
  12001. // getAnyInitializer() can find a default argument, which leads
  12002. // to chaos.
  12003. if (isa<ParmVarDecl>(D))
  12004. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12005. // C++ 7.1.5.1p2
  12006. // A variable of non-volatile const-qualified integral or enumeration
  12007. // type initialized by an ICE can be used in ICEs.
  12008. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  12009. if (!Dcl->getType()->isIntegralOrEnumerationType())
  12010. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12011. const VarDecl *VD;
  12012. // Look for a declaration of this variable that has an initializer, and
  12013. // check whether it is an ICE.
  12014. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  12015. return NoDiag();
  12016. else
  12017. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12018. }
  12019. }
  12020. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12021. }
  12022. case Expr::UnaryOperatorClass: {
  12023. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  12024. switch (Exp->getOpcode()) {
  12025. case UO_PostInc:
  12026. case UO_PostDec:
  12027. case UO_PreInc:
  12028. case UO_PreDec:
  12029. case UO_AddrOf:
  12030. case UO_Deref:
  12031. case UO_Coawait:
  12032. // C99 6.6/3 allows increment and decrement within unevaluated
  12033. // subexpressions of constant expressions, but they can never be ICEs
  12034. // because an ICE cannot contain an lvalue operand.
  12035. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12036. case UO_Extension:
  12037. case UO_LNot:
  12038. case UO_Plus:
  12039. case UO_Minus:
  12040. case UO_Not:
  12041. case UO_Real:
  12042. case UO_Imag:
  12043. return CheckICE(Exp->getSubExpr(), Ctx);
  12044. }
  12045. llvm_unreachable("invalid unary operator class");
  12046. }
  12047. case Expr::OffsetOfExprClass: {
  12048. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  12049. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  12050. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  12051. // compliance: we should warn earlier for offsetof expressions with
  12052. // array subscripts that aren't ICEs, and if the array subscripts
  12053. // are ICEs, the value of the offsetof must be an integer constant.
  12054. return CheckEvalInICE(E, Ctx);
  12055. }
  12056. case Expr::UnaryExprOrTypeTraitExprClass: {
  12057. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  12058. if ((Exp->getKind() == UETT_SizeOf) &&
  12059. Exp->getTypeOfArgument()->isVariableArrayType())
  12060. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12061. return NoDiag();
  12062. }
  12063. case Expr::BinaryOperatorClass: {
  12064. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  12065. switch (Exp->getOpcode()) {
  12066. case BO_PtrMemD:
  12067. case BO_PtrMemI:
  12068. case BO_Assign:
  12069. case BO_MulAssign:
  12070. case BO_DivAssign:
  12071. case BO_RemAssign:
  12072. case BO_AddAssign:
  12073. case BO_SubAssign:
  12074. case BO_ShlAssign:
  12075. case BO_ShrAssign:
  12076. case BO_AndAssign:
  12077. case BO_XorAssign:
  12078. case BO_OrAssign:
  12079. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  12080. // constant expressions, but they can never be ICEs because an ICE cannot
  12081. // contain an lvalue operand.
  12082. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12083. case BO_Mul:
  12084. case BO_Div:
  12085. case BO_Rem:
  12086. case BO_Add:
  12087. case BO_Sub:
  12088. case BO_Shl:
  12089. case BO_Shr:
  12090. case BO_LT:
  12091. case BO_GT:
  12092. case BO_LE:
  12093. case BO_GE:
  12094. case BO_EQ:
  12095. case BO_NE:
  12096. case BO_And:
  12097. case BO_Xor:
  12098. case BO_Or:
  12099. case BO_Comma:
  12100. case BO_Cmp: {
  12101. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12102. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12103. if (Exp->getOpcode() == BO_Div ||
  12104. Exp->getOpcode() == BO_Rem) {
  12105. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  12106. // we don't evaluate one.
  12107. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  12108. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  12109. if (REval == 0)
  12110. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12111. if (REval.isSigned() && REval.isAllOnesValue()) {
  12112. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  12113. if (LEval.isMinSignedValue())
  12114. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12115. }
  12116. }
  12117. }
  12118. if (Exp->getOpcode() == BO_Comma) {
  12119. if (Ctx.getLangOpts().C99) {
  12120. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  12121. // if it isn't evaluated.
  12122. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  12123. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12124. } else {
  12125. // In both C89 and C++, commas in ICEs are illegal.
  12126. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12127. }
  12128. }
  12129. return Worst(LHSResult, RHSResult);
  12130. }
  12131. case BO_LAnd:
  12132. case BO_LOr: {
  12133. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12134. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12135. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  12136. // Rare case where the RHS has a comma "side-effect"; we need
  12137. // to actually check the condition to see whether the side
  12138. // with the comma is evaluated.
  12139. if ((Exp->getOpcode() == BO_LAnd) !=
  12140. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  12141. return RHSResult;
  12142. return NoDiag();
  12143. }
  12144. return Worst(LHSResult, RHSResult);
  12145. }
  12146. }
  12147. llvm_unreachable("invalid binary operator kind");
  12148. }
  12149. case Expr::ImplicitCastExprClass:
  12150. case Expr::CStyleCastExprClass:
  12151. case Expr::CXXFunctionalCastExprClass:
  12152. case Expr::CXXStaticCastExprClass:
  12153. case Expr::CXXReinterpretCastExprClass:
  12154. case Expr::CXXConstCastExprClass:
  12155. case Expr::ObjCBridgedCastExprClass: {
  12156. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  12157. if (isa<ExplicitCastExpr>(E)) {
  12158. if (const FloatingLiteral *FL
  12159. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  12160. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  12161. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  12162. APSInt IgnoredVal(DestWidth, !DestSigned);
  12163. bool Ignored;
  12164. // If the value does not fit in the destination type, the behavior is
  12165. // undefined, so we are not required to treat it as a constant
  12166. // expression.
  12167. if (FL->getValue().convertToInteger(IgnoredVal,
  12168. llvm::APFloat::rmTowardZero,
  12169. &Ignored) & APFloat::opInvalidOp)
  12170. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12171. return NoDiag();
  12172. }
  12173. }
  12174. switch (cast<CastExpr>(E)->getCastKind()) {
  12175. case CK_LValueToRValue:
  12176. case CK_AtomicToNonAtomic:
  12177. case CK_NonAtomicToAtomic:
  12178. case CK_NoOp:
  12179. case CK_IntegralToBoolean:
  12180. case CK_IntegralCast:
  12181. return CheckICE(SubExpr, Ctx);
  12182. default:
  12183. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12184. }
  12185. }
  12186. case Expr::BinaryConditionalOperatorClass: {
  12187. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  12188. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  12189. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  12190. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12191. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  12192. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  12193. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  12194. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  12195. return FalseResult;
  12196. }
  12197. case Expr::ConditionalOperatorClass: {
  12198. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  12199. // If the condition (ignoring parens) is a __builtin_constant_p call,
  12200. // then only the true side is actually considered in an integer constant
  12201. // expression, and it is fully evaluated. This is an important GNU
  12202. // extension. See GCC PR38377 for discussion.
  12203. if (const CallExpr *CallCE
  12204. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  12205. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  12206. return CheckEvalInICE(E, Ctx);
  12207. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  12208. if (CondResult.Kind == IK_NotICE)
  12209. return CondResult;
  12210. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  12211. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12212. if (TrueResult.Kind == IK_NotICE)
  12213. return TrueResult;
  12214. if (FalseResult.Kind == IK_NotICE)
  12215. return FalseResult;
  12216. if (CondResult.Kind == IK_ICEIfUnevaluated)
  12217. return CondResult;
  12218. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  12219. return NoDiag();
  12220. // Rare case where the diagnostics depend on which side is evaluated
  12221. // Note that if we get here, CondResult is 0, and at least one of
  12222. // TrueResult and FalseResult is non-zero.
  12223. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  12224. return FalseResult;
  12225. return TrueResult;
  12226. }
  12227. case Expr::CXXDefaultArgExprClass:
  12228. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  12229. case Expr::CXXDefaultInitExprClass:
  12230. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  12231. case Expr::ChooseExprClass: {
  12232. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  12233. }
  12234. case Expr::BuiltinBitCastExprClass: {
  12235. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  12236. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12237. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  12238. }
  12239. }
  12240. llvm_unreachable("Invalid StmtClass!");
  12241. }
  12242. /// Evaluate an expression as a C++11 integral constant expression.
  12243. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  12244. const Expr *E,
  12245. llvm::APSInt *Value,
  12246. SourceLocation *Loc) {
  12247. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12248. if (Loc) *Loc = E->getExprLoc();
  12249. return false;
  12250. }
  12251. APValue Result;
  12252. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  12253. return false;
  12254. if (!Result.isInt()) {
  12255. if (Loc) *Loc = E->getExprLoc();
  12256. return false;
  12257. }
  12258. if (Value) *Value = Result.getInt();
  12259. return true;
  12260. }
  12261. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  12262. SourceLocation *Loc) const {
  12263. assert(!isValueDependent() &&
  12264. "Expression evaluator can't be called on a dependent expression.");
  12265. if (Ctx.getLangOpts().CPlusPlus11)
  12266. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  12267. ICEDiag D = CheckICE(this, Ctx);
  12268. if (D.Kind != IK_ICE) {
  12269. if (Loc) *Loc = D.Loc;
  12270. return false;
  12271. }
  12272. return true;
  12273. }
  12274. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  12275. SourceLocation *Loc, bool isEvaluated) const {
  12276. assert(!isValueDependent() &&
  12277. "Expression evaluator can't be called on a dependent expression.");
  12278. if (Ctx.getLangOpts().CPlusPlus11)
  12279. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  12280. if (!isIntegerConstantExpr(Ctx, Loc))
  12281. return false;
  12282. // The only possible side-effects here are due to UB discovered in the
  12283. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  12284. // required to treat the expression as an ICE, so we produce the folded
  12285. // value.
  12286. EvalResult ExprResult;
  12287. Expr::EvalStatus Status;
  12288. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  12289. Info.InConstantContext = true;
  12290. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  12291. llvm_unreachable("ICE cannot be evaluated!");
  12292. Value = ExprResult.Val.getInt();
  12293. return true;
  12294. }
  12295. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  12296. assert(!isValueDependent() &&
  12297. "Expression evaluator can't be called on a dependent expression.");
  12298. return CheckICE(this, Ctx).Kind == IK_ICE;
  12299. }
  12300. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  12301. SourceLocation *Loc) const {
  12302. assert(!isValueDependent() &&
  12303. "Expression evaluator can't be called on a dependent expression.");
  12304. // We support this checking in C++98 mode in order to diagnose compatibility
  12305. // issues.
  12306. assert(Ctx.getLangOpts().CPlusPlus);
  12307. // Build evaluation settings.
  12308. Expr::EvalStatus Status;
  12309. SmallVector<PartialDiagnosticAt, 8> Diags;
  12310. Status.Diag = &Diags;
  12311. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12312. APValue Scratch;
  12313. bool IsConstExpr =
  12314. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  12315. // FIXME: We don't produce a diagnostic for this, but the callers that
  12316. // call us on arbitrary full-expressions should generally not care.
  12317. Info.discardCleanups() && !Status.HasSideEffects;
  12318. if (!Diags.empty()) {
  12319. IsConstExpr = false;
  12320. if (Loc) *Loc = Diags[0].first;
  12321. } else if (!IsConstExpr) {
  12322. // FIXME: This shouldn't happen.
  12323. if (Loc) *Loc = getExprLoc();
  12324. }
  12325. return IsConstExpr;
  12326. }
  12327. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  12328. const FunctionDecl *Callee,
  12329. ArrayRef<const Expr*> Args,
  12330. const Expr *This) const {
  12331. assert(!isValueDependent() &&
  12332. "Expression evaluator can't be called on a dependent expression.");
  12333. Expr::EvalStatus Status;
  12334. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  12335. Info.InConstantContext = true;
  12336. LValue ThisVal;
  12337. const LValue *ThisPtr = nullptr;
  12338. if (This) {
  12339. #ifndef NDEBUG
  12340. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  12341. assert(MD && "Don't provide `this` for non-methods.");
  12342. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  12343. #endif
  12344. if (EvaluateObjectArgument(Info, This, ThisVal))
  12345. ThisPtr = &ThisVal;
  12346. if (Info.EvalStatus.HasSideEffects)
  12347. return false;
  12348. }
  12349. ArgVector ArgValues(Args.size());
  12350. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  12351. I != E; ++I) {
  12352. if ((*I)->isValueDependent() ||
  12353. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  12354. // If evaluation fails, throw away the argument entirely.
  12355. ArgValues[I - Args.begin()] = APValue();
  12356. if (Info.EvalStatus.HasSideEffects)
  12357. return false;
  12358. }
  12359. // Build fake call to Callee.
  12360. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  12361. ArgValues.data());
  12362. return Evaluate(Value, Info, this) && Info.discardCleanups() &&
  12363. !Info.EvalStatus.HasSideEffects;
  12364. }
  12365. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  12366. SmallVectorImpl<
  12367. PartialDiagnosticAt> &Diags) {
  12368. // FIXME: It would be useful to check constexpr function templates, but at the
  12369. // moment the constant expression evaluator cannot cope with the non-rigorous
  12370. // ASTs which we build for dependent expressions.
  12371. if (FD->isDependentContext())
  12372. return true;
  12373. Expr::EvalStatus Status;
  12374. Status.Diag = &Diags;
  12375. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  12376. Info.InConstantContext = true;
  12377. Info.CheckingPotentialConstantExpression = true;
  12378. // The constexpr VM attempts to compile all methods to bytecode here.
  12379. if (Info.EnableNewConstInterp) {
  12380. auto &InterpCtx = Info.Ctx.getInterpContext();
  12381. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  12382. case interp::InterpResult::Success:
  12383. case interp::InterpResult::Fail:
  12384. return Diags.empty();
  12385. case interp::InterpResult::Bail:
  12386. break;
  12387. }
  12388. }
  12389. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  12390. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  12391. // Fabricate an arbitrary expression on the stack and pretend that it
  12392. // is a temporary being used as the 'this' pointer.
  12393. LValue This;
  12394. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  12395. This.set({&VIE, Info.CurrentCall->Index});
  12396. ArrayRef<const Expr*> Args;
  12397. APValue Scratch;
  12398. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  12399. // Evaluate the call as a constant initializer, to allow the construction
  12400. // of objects of non-literal types.
  12401. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  12402. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  12403. } else {
  12404. SourceLocation Loc = FD->getLocation();
  12405. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  12406. Args, FD->getBody(), Info, Scratch, nullptr);
  12407. }
  12408. return Diags.empty();
  12409. }
  12410. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  12411. const FunctionDecl *FD,
  12412. SmallVectorImpl<
  12413. PartialDiagnosticAt> &Diags) {
  12414. assert(!E->isValueDependent() &&
  12415. "Expression evaluator can't be called on a dependent expression.");
  12416. Expr::EvalStatus Status;
  12417. Status.Diag = &Diags;
  12418. EvalInfo Info(FD->getASTContext(), Status,
  12419. EvalInfo::EM_ConstantExpressionUnevaluated);
  12420. Info.InConstantContext = true;
  12421. Info.CheckingPotentialConstantExpression = true;
  12422. // Fabricate a call stack frame to give the arguments a plausible cover story.
  12423. ArrayRef<const Expr*> Args;
  12424. ArgVector ArgValues(0);
  12425. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  12426. (void)Success;
  12427. assert(Success &&
  12428. "Failed to set up arguments for potential constant evaluation");
  12429. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  12430. APValue ResultScratch;
  12431. Evaluate(ResultScratch, Info, E);
  12432. return Diags.empty();
  12433. }
  12434. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  12435. unsigned Type) const {
  12436. if (!getType()->isPointerType())
  12437. return false;
  12438. Expr::EvalStatus Status;
  12439. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  12440. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  12441. }