ExprConstant.cpp 338 KB

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