ExprConstant.cpp 228 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476
  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 rules only, at the moment), or, if folding failed too,
  27. // 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/CharUnits.h"
  38. #include "clang/AST/RecordLayout.h"
  39. #include "clang/AST/StmtVisitor.h"
  40. #include "clang/AST/TypeLoc.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/Expr.h"
  43. #include "clang/Basic/Builtins.h"
  44. #include "clang/Basic/PartialDiagnostic.h"
  45. #include "clang/Basic/TargetInfo.h"
  46. #include "llvm/ADT/SmallString.h"
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using llvm::APSInt;
  51. using llvm::APFloat;
  52. /// EvalInfo - This is a private struct used by the evaluator to capture
  53. /// information about a subexpression as it is folded. It retains information
  54. /// about the AST context, but also maintains information about the folded
  55. /// expression.
  56. ///
  57. /// If an expression could be evaluated, it is still possible it is not a C
  58. /// "integer constant expression" or constant expression. If not, this struct
  59. /// captures information about how and why not.
  60. ///
  61. /// One bit of information passed *into* the request for constant folding
  62. /// indicates whether the subexpression is "evaluated" or not according to C
  63. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  64. /// evaluate the expression regardless of what the RHS is, but C only allows
  65. /// certain things in certain situations.
  66. namespace {
  67. struct LValue;
  68. struct CallStackFrame;
  69. struct EvalInfo;
  70. QualType getType(APValue::LValueBase B) {
  71. if (!B) return QualType();
  72. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  73. return D->getType();
  74. return B.get<const Expr*>()->getType();
  75. }
  76. /// Get an LValue path entry, which is known to not be an array index, as a
  77. /// field or base class.
  78. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  79. APValue::BaseOrMemberType Value;
  80. Value.setFromOpaqueValue(E.BaseOrMember);
  81. return Value;
  82. }
  83. /// Get an LValue path entry, which is known to not be an array index, as a
  84. /// field declaration.
  85. const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  86. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  87. }
  88. /// Get an LValue path entry, which is known to not be an array index, as a
  89. /// base class declaration.
  90. const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  91. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  92. }
  93. /// Determine whether this LValue path entry for a base class names a virtual
  94. /// base class.
  95. bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  96. return getAsBaseOrMember(E).getInt();
  97. }
  98. /// Find the path length and type of the most-derived subobject in the given
  99. /// path, and find the size of the containing array, if any.
  100. static
  101. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  102. ArrayRef<APValue::LValuePathEntry> Path,
  103. uint64_t &ArraySize, QualType &Type) {
  104. unsigned MostDerivedLength = 0;
  105. Type = Base;
  106. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  107. if (Type->isArrayType()) {
  108. const ConstantArrayType *CAT =
  109. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  110. Type = CAT->getElementType();
  111. ArraySize = CAT->getSize().getZExtValue();
  112. MostDerivedLength = I + 1;
  113. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  114. Type = FD->getType();
  115. ArraySize = 0;
  116. MostDerivedLength = I + 1;
  117. } else {
  118. // Path[I] describes a base class.
  119. ArraySize = 0;
  120. }
  121. }
  122. return MostDerivedLength;
  123. }
  124. // The order of this enum is important for diagnostics.
  125. enum CheckSubobjectKind {
  126. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  127. CSK_This
  128. };
  129. /// A path from a glvalue to a subobject of that glvalue.
  130. struct SubobjectDesignator {
  131. /// True if the subobject was named in a manner not supported by C++11. Such
  132. /// lvalues can still be folded, but they are not core constant expressions
  133. /// and we cannot perform lvalue-to-rvalue conversions on them.
  134. bool Invalid : 1;
  135. /// Is this a pointer one past the end of an object?
  136. bool IsOnePastTheEnd : 1;
  137. /// The length of the path to the most-derived object of which this is a
  138. /// subobject.
  139. unsigned MostDerivedPathLength : 30;
  140. /// The size of the array of which the most-derived object is an element, or
  141. /// 0 if the most-derived object is not an array element.
  142. uint64_t MostDerivedArraySize;
  143. /// The type of the most derived object referred to by this address.
  144. QualType MostDerivedType;
  145. typedef APValue::LValuePathEntry PathEntry;
  146. /// The entries on the path from the glvalue to the designated subobject.
  147. SmallVector<PathEntry, 8> Entries;
  148. SubobjectDesignator() : Invalid(true) {}
  149. explicit SubobjectDesignator(QualType T)
  150. : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
  151. MostDerivedArraySize(0), MostDerivedType(T) {}
  152. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  153. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  154. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  155. if (!Invalid) {
  156. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  157. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  158. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  159. if (V.getLValueBase())
  160. MostDerivedPathLength =
  161. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  162. V.getLValuePath(), MostDerivedArraySize,
  163. MostDerivedType);
  164. }
  165. }
  166. void setInvalid() {
  167. Invalid = true;
  168. Entries.clear();
  169. }
  170. /// Determine whether this is a one-past-the-end pointer.
  171. bool isOnePastTheEnd() const {
  172. if (IsOnePastTheEnd)
  173. return true;
  174. if (MostDerivedArraySize &&
  175. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  176. return true;
  177. return false;
  178. }
  179. /// Check that this refers to a valid subobject.
  180. bool isValidSubobject() const {
  181. if (Invalid)
  182. return false;
  183. return !isOnePastTheEnd();
  184. }
  185. /// Check that this refers to a valid subobject, and if not, produce a
  186. /// relevant diagnostic and set the designator as invalid.
  187. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  188. /// Update this designator to refer to the first element within this array.
  189. void addArrayUnchecked(const ConstantArrayType *CAT) {
  190. PathEntry Entry;
  191. Entry.ArrayIndex = 0;
  192. Entries.push_back(Entry);
  193. // This is a most-derived object.
  194. MostDerivedType = CAT->getElementType();
  195. MostDerivedArraySize = CAT->getSize().getZExtValue();
  196. MostDerivedPathLength = Entries.size();
  197. }
  198. /// Update this designator to refer to the given base or member of this
  199. /// object.
  200. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  201. PathEntry Entry;
  202. APValue::BaseOrMemberType Value(D, Virtual);
  203. Entry.BaseOrMember = Value.getOpaqueValue();
  204. Entries.push_back(Entry);
  205. // If this isn't a base class, it's a new most-derived object.
  206. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  207. MostDerivedType = FD->getType();
  208. MostDerivedArraySize = 0;
  209. MostDerivedPathLength = Entries.size();
  210. }
  211. }
  212. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  213. /// Add N to the address of this subobject.
  214. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  215. if (Invalid) return;
  216. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
  217. Entries.back().ArrayIndex += N;
  218. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  219. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  220. setInvalid();
  221. }
  222. return;
  223. }
  224. // [expr.add]p4: For the purposes of these operators, a pointer to a
  225. // nonarray object behaves the same as a pointer to the first element of
  226. // an array of length one with the type of the object as its element type.
  227. if (IsOnePastTheEnd && N == (uint64_t)-1)
  228. IsOnePastTheEnd = false;
  229. else if (!IsOnePastTheEnd && N == 1)
  230. IsOnePastTheEnd = true;
  231. else if (N != 0) {
  232. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  233. setInvalid();
  234. }
  235. }
  236. };
  237. /// A core constant value. This can be the value of any constant expression,
  238. /// or a pointer or reference to a non-static object or function parameter.
  239. ///
  240. /// For an LValue, the base and offset are stored in the APValue subobject,
  241. /// but the other information is stored in the SubobjectDesignator. For all
  242. /// other value kinds, the value is stored directly in the APValue subobject.
  243. class CCValue : public APValue {
  244. typedef llvm::APSInt APSInt;
  245. typedef llvm::APFloat APFloat;
  246. /// If the value is a reference or pointer into a parameter or temporary,
  247. /// this is the corresponding call stack frame.
  248. CallStackFrame *CallFrame;
  249. /// If the value is a reference or pointer, this is a description of how the
  250. /// subobject was specified.
  251. SubobjectDesignator Designator;
  252. public:
  253. struct GlobalValue {};
  254. CCValue() {}
  255. explicit CCValue(const APSInt &I) : APValue(I) {}
  256. explicit CCValue(const APFloat &F) : APValue(F) {}
  257. CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
  258. CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
  259. CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
  260. CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
  261. CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
  262. const SubobjectDesignator &D) :
  263. APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
  264. CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
  265. APValue(V), CallFrame(0), Designator(Ctx, V) {}
  266. CCValue(const ValueDecl *D, bool IsDerivedMember,
  267. ArrayRef<const CXXRecordDecl*> Path) :
  268. APValue(D, IsDerivedMember, Path) {}
  269. CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
  270. APValue(LHSExpr, RHSExpr) {}
  271. CallStackFrame *getLValueFrame() const {
  272. assert(getKind() == LValue);
  273. return CallFrame;
  274. }
  275. SubobjectDesignator &getLValueDesignator() {
  276. assert(getKind() == LValue);
  277. return Designator;
  278. }
  279. const SubobjectDesignator &getLValueDesignator() const {
  280. return const_cast<CCValue*>(this)->getLValueDesignator();
  281. }
  282. };
  283. /// A stack frame in the constexpr call stack.
  284. struct CallStackFrame {
  285. EvalInfo &Info;
  286. /// Parent - The caller of this stack frame.
  287. CallStackFrame *Caller;
  288. /// CallLoc - The location of the call expression for this call.
  289. SourceLocation CallLoc;
  290. /// Callee - The function which was called.
  291. const FunctionDecl *Callee;
  292. /// This - The binding for the this pointer in this call, if any.
  293. const LValue *This;
  294. /// ParmBindings - Parameter bindings for this function call, indexed by
  295. /// parameters' function scope indices.
  296. const CCValue *Arguments;
  297. typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
  298. typedef MapTy::const_iterator temp_iterator;
  299. /// Temporaries - Temporary lvalues materialized within this stack frame.
  300. MapTy Temporaries;
  301. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  302. const FunctionDecl *Callee, const LValue *This,
  303. const CCValue *Arguments);
  304. ~CallStackFrame();
  305. };
  306. /// A partial diagnostic which we might know in advance that we are not going
  307. /// to emit.
  308. class OptionalDiagnostic {
  309. PartialDiagnostic *Diag;
  310. public:
  311. explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
  312. template<typename T>
  313. OptionalDiagnostic &operator<<(const T &v) {
  314. if (Diag)
  315. *Diag << v;
  316. return *this;
  317. }
  318. OptionalDiagnostic &operator<<(const APSInt &I) {
  319. if (Diag) {
  320. llvm::SmallVector<char, 32> Buffer;
  321. I.toString(Buffer);
  322. *Diag << StringRef(Buffer.data(), Buffer.size());
  323. }
  324. return *this;
  325. }
  326. OptionalDiagnostic &operator<<(const APFloat &F) {
  327. if (Diag) {
  328. llvm::SmallVector<char, 32> Buffer;
  329. F.toString(Buffer);
  330. *Diag << StringRef(Buffer.data(), Buffer.size());
  331. }
  332. return *this;
  333. }
  334. };
  335. struct EvalInfo {
  336. ASTContext &Ctx;
  337. /// EvalStatus - Contains information about the evaluation.
  338. Expr::EvalStatus &EvalStatus;
  339. /// CurrentCall - The top of the constexpr call stack.
  340. CallStackFrame *CurrentCall;
  341. /// CallStackDepth - The number of calls in the call stack right now.
  342. unsigned CallStackDepth;
  343. typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
  344. /// OpaqueValues - Values used as the common expression in a
  345. /// BinaryConditionalOperator.
  346. MapTy OpaqueValues;
  347. /// BottomFrame - The frame in which evaluation started. This must be
  348. /// initialized after CurrentCall and CallStackDepth.
  349. CallStackFrame BottomFrame;
  350. /// EvaluatingDecl - This is the declaration whose initializer is being
  351. /// evaluated, if any.
  352. const VarDecl *EvaluatingDecl;
  353. /// EvaluatingDeclValue - This is the value being constructed for the
  354. /// declaration whose initializer is being evaluated, if any.
  355. APValue *EvaluatingDeclValue;
  356. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  357. /// notes attached to it will also be stored, otherwise they will not be.
  358. bool HasActiveDiagnostic;
  359. /// CheckingPotentialConstantExpression - Are we checking whether the
  360. /// expression is a potential constant expression? If so, some diagnostics
  361. /// are suppressed.
  362. bool CheckingPotentialConstantExpression;
  363. EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
  364. : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
  365. CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
  366. EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
  367. CheckingPotentialConstantExpression(false) {}
  368. const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
  369. MapTy::const_iterator i = OpaqueValues.find(e);
  370. if (i == OpaqueValues.end()) return 0;
  371. return &i->second;
  372. }
  373. void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
  374. EvaluatingDecl = VD;
  375. EvaluatingDeclValue = &Value;
  376. }
  377. const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
  378. bool CheckCallLimit(SourceLocation Loc) {
  379. // Don't perform any constexpr calls (other than the call we're checking)
  380. // when checking a potential constant expression.
  381. if (CheckingPotentialConstantExpression && CallStackDepth > 1)
  382. return false;
  383. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  384. return true;
  385. Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
  386. << getLangOpts().ConstexprCallDepth;
  387. return false;
  388. }
  389. private:
  390. /// Add a diagnostic to the diagnostics list.
  391. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  392. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  393. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  394. return EvalStatus.Diag->back().second;
  395. }
  396. /// Add notes containing a call stack to the current point of evaluation.
  397. void addCallStack(unsigned Limit);
  398. public:
  399. /// Diagnose that the evaluation cannot be folded.
  400. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
  401. = diag::note_invalid_subexpr_in_const_expr,
  402. unsigned ExtraNotes = 0) {
  403. // If we have a prior diagnostic, it will be noting that the expression
  404. // isn't a constant expression. This diagnostic is more important.
  405. // FIXME: We might want to show both diagnostics to the user.
  406. if (EvalStatus.Diag) {
  407. unsigned CallStackNotes = CallStackDepth - 1;
  408. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  409. if (Limit)
  410. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  411. if (CheckingPotentialConstantExpression)
  412. CallStackNotes = 0;
  413. HasActiveDiagnostic = true;
  414. EvalStatus.Diag->clear();
  415. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  416. addDiag(Loc, DiagId);
  417. if (!CheckingPotentialConstantExpression)
  418. addCallStack(Limit);
  419. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  420. }
  421. HasActiveDiagnostic = false;
  422. return OptionalDiagnostic();
  423. }
  424. /// Diagnose that the evaluation does not produce a C++11 core constant
  425. /// expression.
  426. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  427. = diag::note_invalid_subexpr_in_const_expr,
  428. unsigned ExtraNotes = 0) {
  429. // Don't override a previous diagnostic.
  430. if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
  431. return OptionalDiagnostic();
  432. return Diag(Loc, DiagId, ExtraNotes);
  433. }
  434. /// Add a note to a prior diagnostic.
  435. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  436. if (!HasActiveDiagnostic)
  437. return OptionalDiagnostic();
  438. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  439. }
  440. /// Add a stack of notes to a prior diagnostic.
  441. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  442. if (HasActiveDiagnostic) {
  443. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  444. Diags.begin(), Diags.end());
  445. }
  446. }
  447. /// Should we continue evaluation as much as possible after encountering a
  448. /// construct which can't be folded?
  449. bool keepEvaluatingAfterFailure() {
  450. return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
  451. }
  452. };
  453. /// Object used to treat all foldable expressions as constant expressions.
  454. struct FoldConstant {
  455. bool Enabled;
  456. explicit FoldConstant(EvalInfo &Info)
  457. : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
  458. !Info.EvalStatus.HasSideEffects) {
  459. }
  460. // Treat the value we've computed since this object was created as constant.
  461. void Fold(EvalInfo &Info) {
  462. if (Enabled && !Info.EvalStatus.Diag->empty() &&
  463. !Info.EvalStatus.HasSideEffects)
  464. Info.EvalStatus.Diag->clear();
  465. }
  466. };
  467. }
  468. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  469. CheckSubobjectKind CSK) {
  470. if (Invalid)
  471. return false;
  472. if (isOnePastTheEnd()) {
  473. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
  474. << CSK;
  475. setInvalid();
  476. return false;
  477. }
  478. return true;
  479. }
  480. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  481. const Expr *E, uint64_t N) {
  482. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
  483. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
  484. << static_cast<int>(N) << /*array*/ 0
  485. << static_cast<unsigned>(MostDerivedArraySize);
  486. else
  487. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
  488. << static_cast<int>(N) << /*non-array*/ 1;
  489. setInvalid();
  490. }
  491. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  492. const FunctionDecl *Callee, const LValue *This,
  493. const CCValue *Arguments)
  494. : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
  495. This(This), Arguments(Arguments) {
  496. Info.CurrentCall = this;
  497. ++Info.CallStackDepth;
  498. }
  499. CallStackFrame::~CallStackFrame() {
  500. assert(Info.CurrentCall == this && "calls retired out of order");
  501. --Info.CallStackDepth;
  502. Info.CurrentCall = Caller;
  503. }
  504. /// Produce a string describing the given constexpr call.
  505. static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
  506. unsigned ArgIndex = 0;
  507. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  508. !isa<CXXConstructorDecl>(Frame->Callee) &&
  509. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  510. if (!IsMemberCall)
  511. Out << *Frame->Callee << '(';
  512. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  513. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  514. if (ArgIndex > (unsigned)IsMemberCall)
  515. Out << ", ";
  516. const ParmVarDecl *Param = *I;
  517. const CCValue &Arg = Frame->Arguments[ArgIndex];
  518. if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
  519. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  520. else {
  521. // Deliberately slice off the frame to form an APValue we can print.
  522. APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
  523. Arg.getLValueDesignator().Entries,
  524. Arg.getLValueDesignator().IsOnePastTheEnd);
  525. Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
  526. }
  527. if (ArgIndex == 0 && IsMemberCall)
  528. Out << "->" << *Frame->Callee << '(';
  529. }
  530. Out << ')';
  531. }
  532. void EvalInfo::addCallStack(unsigned Limit) {
  533. // Determine which calls to skip, if any.
  534. unsigned ActiveCalls = CallStackDepth - 1;
  535. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  536. if (Limit && Limit < ActiveCalls) {
  537. SkipStart = Limit / 2 + Limit % 2;
  538. SkipEnd = ActiveCalls - Limit / 2;
  539. }
  540. // Walk the call stack and add the diagnostics.
  541. unsigned CallIdx = 0;
  542. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  543. Frame = Frame->Caller, ++CallIdx) {
  544. // Skip this call?
  545. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  546. if (CallIdx == SkipStart) {
  547. // Note that we're skipping calls.
  548. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  549. << unsigned(ActiveCalls - Limit);
  550. }
  551. continue;
  552. }
  553. llvm::SmallVector<char, 128> Buffer;
  554. llvm::raw_svector_ostream Out(Buffer);
  555. describeCall(Frame, Out);
  556. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  557. }
  558. }
  559. namespace {
  560. struct ComplexValue {
  561. private:
  562. bool IsInt;
  563. public:
  564. APSInt IntReal, IntImag;
  565. APFloat FloatReal, FloatImag;
  566. ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
  567. void makeComplexFloat() { IsInt = false; }
  568. bool isComplexFloat() const { return !IsInt; }
  569. APFloat &getComplexFloatReal() { return FloatReal; }
  570. APFloat &getComplexFloatImag() { return FloatImag; }
  571. void makeComplexInt() { IsInt = true; }
  572. bool isComplexInt() const { return IsInt; }
  573. APSInt &getComplexIntReal() { return IntReal; }
  574. APSInt &getComplexIntImag() { return IntImag; }
  575. void moveInto(CCValue &v) const {
  576. if (isComplexFloat())
  577. v = CCValue(FloatReal, FloatImag);
  578. else
  579. v = CCValue(IntReal, IntImag);
  580. }
  581. void setFrom(const CCValue &v) {
  582. assert(v.isComplexFloat() || v.isComplexInt());
  583. if (v.isComplexFloat()) {
  584. makeComplexFloat();
  585. FloatReal = v.getComplexFloatReal();
  586. FloatImag = v.getComplexFloatImag();
  587. } else {
  588. makeComplexInt();
  589. IntReal = v.getComplexIntReal();
  590. IntImag = v.getComplexIntImag();
  591. }
  592. }
  593. };
  594. struct LValue {
  595. APValue::LValueBase Base;
  596. CharUnits Offset;
  597. CallStackFrame *Frame;
  598. SubobjectDesignator Designator;
  599. const APValue::LValueBase getLValueBase() const { return Base; }
  600. CharUnits &getLValueOffset() { return Offset; }
  601. const CharUnits &getLValueOffset() const { return Offset; }
  602. CallStackFrame *getLValueFrame() const { return Frame; }
  603. SubobjectDesignator &getLValueDesignator() { return Designator; }
  604. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  605. void moveInto(CCValue &V) const {
  606. V = CCValue(Base, Offset, Frame, Designator);
  607. }
  608. void setFrom(const CCValue &V) {
  609. assert(V.isLValue());
  610. Base = V.getLValueBase();
  611. Offset = V.getLValueOffset();
  612. Frame = V.getLValueFrame();
  613. Designator = V.getLValueDesignator();
  614. }
  615. void set(APValue::LValueBase B, CallStackFrame *F = 0) {
  616. Base = B;
  617. Offset = CharUnits::Zero();
  618. Frame = F;
  619. Designator = SubobjectDesignator(getType(B));
  620. }
  621. // Check that this LValue is not based on a null pointer. If it is, produce
  622. // a diagnostic and mark the designator as invalid.
  623. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  624. CheckSubobjectKind CSK) {
  625. if (Designator.Invalid)
  626. return false;
  627. if (!Base) {
  628. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
  629. << CSK;
  630. Designator.setInvalid();
  631. return false;
  632. }
  633. return true;
  634. }
  635. // Check this LValue refers to an object. If not, set the designator to be
  636. // invalid and emit a diagnostic.
  637. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  638. return checkNullPointer(Info, E, CSK) &&
  639. Designator.checkSubobject(Info, E, CSK);
  640. }
  641. void addDecl(EvalInfo &Info, const Expr *E,
  642. const Decl *D, bool Virtual = false) {
  643. checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
  644. Designator.addDeclUnchecked(D, Virtual);
  645. }
  646. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  647. checkSubobject(Info, E, CSK_ArrayToPointer);
  648. Designator.addArrayUnchecked(CAT);
  649. }
  650. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  651. if (!checkNullPointer(Info, E, CSK_ArrayIndex))
  652. return;
  653. Designator.adjustIndex(Info, E, N);
  654. }
  655. };
  656. struct MemberPtr {
  657. MemberPtr() {}
  658. explicit MemberPtr(const ValueDecl *Decl) :
  659. DeclAndIsDerivedMember(Decl, false), Path() {}
  660. /// The member or (direct or indirect) field referred to by this member
  661. /// pointer, or 0 if this is a null member pointer.
  662. const ValueDecl *getDecl() const {
  663. return DeclAndIsDerivedMember.getPointer();
  664. }
  665. /// Is this actually a member of some type derived from the relevant class?
  666. bool isDerivedMember() const {
  667. return DeclAndIsDerivedMember.getInt();
  668. }
  669. /// Get the class which the declaration actually lives in.
  670. const CXXRecordDecl *getContainingRecord() const {
  671. return cast<CXXRecordDecl>(
  672. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  673. }
  674. void moveInto(CCValue &V) const {
  675. V = CCValue(getDecl(), isDerivedMember(), Path);
  676. }
  677. void setFrom(const CCValue &V) {
  678. assert(V.isMemberPointer());
  679. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  680. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  681. Path.clear();
  682. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  683. Path.insert(Path.end(), P.begin(), P.end());
  684. }
  685. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  686. /// whether the member is a member of some class derived from the class type
  687. /// of the member pointer.
  688. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  689. /// Path - The path of base/derived classes from the member declaration's
  690. /// class (exclusive) to the class type of the member pointer (inclusive).
  691. SmallVector<const CXXRecordDecl*, 4> Path;
  692. /// Perform a cast towards the class of the Decl (either up or down the
  693. /// hierarchy).
  694. bool castBack(const CXXRecordDecl *Class) {
  695. assert(!Path.empty());
  696. const CXXRecordDecl *Expected;
  697. if (Path.size() >= 2)
  698. Expected = Path[Path.size() - 2];
  699. else
  700. Expected = getContainingRecord();
  701. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  702. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  703. // if B does not contain the original member and is not a base or
  704. // derived class of the class containing the original member, the result
  705. // of the cast is undefined.
  706. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  707. // (D::*). We consider that to be a language defect.
  708. return false;
  709. }
  710. Path.pop_back();
  711. return true;
  712. }
  713. /// Perform a base-to-derived member pointer cast.
  714. bool castToDerived(const CXXRecordDecl *Derived) {
  715. if (!getDecl())
  716. return true;
  717. if (!isDerivedMember()) {
  718. Path.push_back(Derived);
  719. return true;
  720. }
  721. if (!castBack(Derived))
  722. return false;
  723. if (Path.empty())
  724. DeclAndIsDerivedMember.setInt(false);
  725. return true;
  726. }
  727. /// Perform a derived-to-base member pointer cast.
  728. bool castToBase(const CXXRecordDecl *Base) {
  729. if (!getDecl())
  730. return true;
  731. if (Path.empty())
  732. DeclAndIsDerivedMember.setInt(true);
  733. if (isDerivedMember()) {
  734. Path.push_back(Base);
  735. return true;
  736. }
  737. return castBack(Base);
  738. }
  739. };
  740. /// Compare two member pointers, which are assumed to be of the same type.
  741. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  742. if (!LHS.getDecl() || !RHS.getDecl())
  743. return !LHS.getDecl() && !RHS.getDecl();
  744. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  745. return false;
  746. return LHS.Path == RHS.Path;
  747. }
  748. /// Kinds of constant expression checking, for diagnostics.
  749. enum CheckConstantExpressionKind {
  750. CCEK_Constant, ///< A normal constant.
  751. CCEK_ReturnValue, ///< A constexpr function return value.
  752. CCEK_MemberInit ///< A constexpr constructor mem-initializer.
  753. };
  754. }
  755. static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
  756. static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
  757. const LValue &This, const Expr *E,
  758. CheckConstantExpressionKind CCEK
  759. = CCEK_Constant);
  760. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  761. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  762. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  763. EvalInfo &Info);
  764. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  765. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  766. static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
  767. EvalInfo &Info);
  768. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  769. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  770. //===----------------------------------------------------------------------===//
  771. // Misc utilities
  772. //===----------------------------------------------------------------------===//
  773. /// Should this call expression be treated as a string literal?
  774. static bool IsStringLiteralCall(const CallExpr *E) {
  775. unsigned Builtin = E->isBuiltinCall();
  776. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  777. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  778. }
  779. static bool IsGlobalLValue(APValue::LValueBase B) {
  780. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  781. // constant expression of pointer type that evaluates to...
  782. // ... a null pointer value, or a prvalue core constant expression of type
  783. // std::nullptr_t.
  784. if (!B) return true;
  785. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  786. // ... the address of an object with static storage duration,
  787. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  788. return VD->hasGlobalStorage();
  789. // ... the address of a function,
  790. return isa<FunctionDecl>(D);
  791. }
  792. const Expr *E = B.get<const Expr*>();
  793. switch (E->getStmtClass()) {
  794. default:
  795. return false;
  796. case Expr::CompoundLiteralExprClass:
  797. return cast<CompoundLiteralExpr>(E)->isFileScope();
  798. // A string literal has static storage duration.
  799. case Expr::StringLiteralClass:
  800. case Expr::PredefinedExprClass:
  801. case Expr::ObjCStringLiteralClass:
  802. case Expr::ObjCEncodeExprClass:
  803. case Expr::CXXTypeidExprClass:
  804. return true;
  805. case Expr::CallExprClass:
  806. return IsStringLiteralCall(cast<CallExpr>(E));
  807. // For GCC compatibility, &&label has static storage duration.
  808. case Expr::AddrLabelExprClass:
  809. return true;
  810. // A Block literal expression may be used as the initialization value for
  811. // Block variables at global or local static scope.
  812. case Expr::BlockExprClass:
  813. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  814. case Expr::ImplicitValueInitExprClass:
  815. // FIXME:
  816. // We can never form an lvalue with an implicit value initialization as its
  817. // base through expression evaluation, so these only appear in one case: the
  818. // implicit variable declaration we invent when checking whether a constexpr
  819. // constructor can produce a constant expression. We must assume that such
  820. // an expression might be a global lvalue.
  821. return true;
  822. }
  823. }
  824. /// Check that this reference or pointer core constant expression is a valid
  825. /// value for an address or reference constant expression. Type T should be
  826. /// either LValue or CCValue. Return true if we can fold this expression,
  827. /// whether or not it's a constant expression.
  828. template<typename T>
  829. static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
  830. const T &LVal, APValue &Value,
  831. CheckConstantExpressionKind CCEK) {
  832. APValue::LValueBase Base = LVal.getLValueBase();
  833. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  834. if (!IsGlobalLValue(Base)) {
  835. if (Info.getLangOpts().CPlusPlus0x) {
  836. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  837. Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
  838. << E->isGLValue() << !Designator.Entries.empty()
  839. << !!VD << CCEK << VD;
  840. if (VD)
  841. Info.Note(VD->getLocation(), diag::note_declared_at);
  842. else
  843. Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
  844. diag::note_constexpr_temporary_here);
  845. } else {
  846. Info.Diag(E->getExprLoc());
  847. }
  848. // Don't allow references to temporaries to escape.
  849. return false;
  850. }
  851. bool IsReferenceType = E->isGLValue();
  852. if (Designator.Invalid) {
  853. // This is not a core constant expression. An appropriate diagnostic will
  854. // have already been produced.
  855. Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
  856. APValue::NoLValuePath());
  857. return true;
  858. }
  859. Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
  860. Designator.Entries, Designator.IsOnePastTheEnd);
  861. // Allow address constant expressions to be past-the-end pointers. This is
  862. // an extension: the standard requires them to point to an object.
  863. if (!IsReferenceType)
  864. return true;
  865. // A reference constant expression must refer to an object.
  866. if (!Base) {
  867. // FIXME: diagnostic
  868. Info.CCEDiag(E->getExprLoc());
  869. return true;
  870. }
  871. // Does this refer one past the end of some object?
  872. if (Designator.isOnePastTheEnd()) {
  873. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  874. Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
  875. << !Designator.Entries.empty() << !!VD << VD;
  876. if (VD)
  877. Info.Note(VD->getLocation(), diag::note_declared_at);
  878. else
  879. Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
  880. diag::note_constexpr_temporary_here);
  881. }
  882. return true;
  883. }
  884. /// Check that this core constant expression is of literal type, and if not,
  885. /// produce an appropriate diagnostic.
  886. static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
  887. if (!E->isRValue() || E->getType()->isLiteralType())
  888. return true;
  889. // Prvalue constant expressions must be of literal types.
  890. if (Info.getLangOpts().CPlusPlus0x)
  891. Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
  892. << E->getType();
  893. else
  894. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  895. return false;
  896. }
  897. /// Check that this core constant expression value is a valid value for a
  898. /// constant expression, and if it is, produce the corresponding constant value.
  899. /// If not, report an appropriate diagnostic. Does not check that the expression
  900. /// is of literal type.
  901. static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
  902. const CCValue &CCValue, APValue &Value,
  903. CheckConstantExpressionKind CCEK
  904. = CCEK_Constant) {
  905. if (!CCValue.isLValue()) {
  906. Value = CCValue;
  907. return true;
  908. }
  909. return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
  910. }
  911. const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  912. return LVal.Base.dyn_cast<const ValueDecl*>();
  913. }
  914. static bool IsLiteralLValue(const LValue &Value) {
  915. return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
  916. }
  917. static bool IsWeakLValue(const LValue &Value) {
  918. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  919. return Decl && Decl->isWeak();
  920. }
  921. static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
  922. // A null base expression indicates a null pointer. These are always
  923. // evaluatable, and they are false unless the offset is zero.
  924. if (!Value.getLValueBase()) {
  925. Result = !Value.getLValueOffset().isZero();
  926. return true;
  927. }
  928. // We have a non-null base. These are generally known to be true, but if it's
  929. // a weak declaration it can be null at runtime.
  930. Result = true;
  931. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  932. return !Decl || !Decl->isWeak();
  933. }
  934. static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
  935. switch (Val.getKind()) {
  936. case APValue::Uninitialized:
  937. return false;
  938. case APValue::Int:
  939. Result = Val.getInt().getBoolValue();
  940. return true;
  941. case APValue::Float:
  942. Result = !Val.getFloat().isZero();
  943. return true;
  944. case APValue::ComplexInt:
  945. Result = Val.getComplexIntReal().getBoolValue() ||
  946. Val.getComplexIntImag().getBoolValue();
  947. return true;
  948. case APValue::ComplexFloat:
  949. Result = !Val.getComplexFloatReal().isZero() ||
  950. !Val.getComplexFloatImag().isZero();
  951. return true;
  952. case APValue::LValue:
  953. return EvalPointerValueAsBool(Val, Result);
  954. case APValue::MemberPointer:
  955. Result = Val.getMemberPointerDecl();
  956. return true;
  957. case APValue::Vector:
  958. case APValue::Array:
  959. case APValue::Struct:
  960. case APValue::Union:
  961. case APValue::AddrLabelDiff:
  962. return false;
  963. }
  964. llvm_unreachable("unknown APValue kind");
  965. }
  966. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  967. EvalInfo &Info) {
  968. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  969. CCValue Val;
  970. if (!Evaluate(Val, Info, E))
  971. return false;
  972. return HandleConversionToBool(Val, Result);
  973. }
  974. template<typename T>
  975. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  976. const T &SrcValue, QualType DestType) {
  977. Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
  978. << SrcValue << DestType;
  979. return false;
  980. }
  981. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  982. QualType SrcType, const APFloat &Value,
  983. QualType DestType, APSInt &Result) {
  984. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  985. // Determine whether we are converting to unsigned or signed.
  986. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  987. Result = APSInt(DestWidth, !DestSigned);
  988. bool ignored;
  989. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  990. & APFloat::opInvalidOp)
  991. return HandleOverflow(Info, E, Value, DestType);
  992. return true;
  993. }
  994. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  995. QualType SrcType, QualType DestType,
  996. APFloat &Result) {
  997. APFloat Value = Result;
  998. bool ignored;
  999. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1000. APFloat::rmNearestTiesToEven, &ignored)
  1001. & APFloat::opOverflow)
  1002. return HandleOverflow(Info, E, Value, DestType);
  1003. return true;
  1004. }
  1005. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1006. QualType DestType, QualType SrcType,
  1007. APSInt &Value) {
  1008. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1009. APSInt Result = Value;
  1010. // Figure out if this is a truncate, extend or noop cast.
  1011. // If the input is signed, do a sign extend, noop, or truncate.
  1012. Result = Result.extOrTrunc(DestWidth);
  1013. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1014. return Result;
  1015. }
  1016. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1017. QualType SrcType, const APSInt &Value,
  1018. QualType DestType, APFloat &Result) {
  1019. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1020. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1021. APFloat::rmNearestTiesToEven)
  1022. & APFloat::opOverflow)
  1023. return HandleOverflow(Info, E, Value, DestType);
  1024. return true;
  1025. }
  1026. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1027. llvm::APInt &Res) {
  1028. CCValue SVal;
  1029. if (!Evaluate(SVal, Info, E))
  1030. return false;
  1031. if (SVal.isInt()) {
  1032. Res = SVal.getInt();
  1033. return true;
  1034. }
  1035. if (SVal.isFloat()) {
  1036. Res = SVal.getFloat().bitcastToAPInt();
  1037. return true;
  1038. }
  1039. if (SVal.isVector()) {
  1040. QualType VecTy = E->getType();
  1041. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1042. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1043. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1044. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1045. Res = llvm::APInt::getNullValue(VecSize);
  1046. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1047. APValue &Elt = SVal.getVectorElt(i);
  1048. llvm::APInt EltAsInt;
  1049. if (Elt.isInt()) {
  1050. EltAsInt = Elt.getInt();
  1051. } else if (Elt.isFloat()) {
  1052. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1053. } else {
  1054. // Don't try to handle vectors of anything other than int or float
  1055. // (not sure if it's possible to hit this case).
  1056. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1057. return false;
  1058. }
  1059. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1060. if (BigEndian)
  1061. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1062. else
  1063. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1064. }
  1065. return true;
  1066. }
  1067. // Give up if the input isn't an int, float, or vector. For example, we
  1068. // reject "(v4i16)(intptr_t)&a".
  1069. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1070. return false;
  1071. }
  1072. /// Cast an lvalue referring to a base subobject to a derived class, by
  1073. /// truncating the lvalue's path to the given length.
  1074. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1075. const RecordDecl *TruncatedType,
  1076. unsigned TruncatedElements) {
  1077. SubobjectDesignator &D = Result.Designator;
  1078. // Check we actually point to a derived class object.
  1079. if (TruncatedElements == D.Entries.size())
  1080. return true;
  1081. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1082. "not casting to a derived class");
  1083. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1084. return false;
  1085. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1086. const RecordDecl *RD = TruncatedType;
  1087. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1088. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1089. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1090. if (isVirtualBaseClass(D.Entries[I]))
  1091. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1092. else
  1093. Result.Offset -= Layout.getBaseClassOffset(Base);
  1094. RD = Base;
  1095. }
  1096. D.Entries.resize(TruncatedElements);
  1097. return true;
  1098. }
  1099. static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1100. const CXXRecordDecl *Derived,
  1101. const CXXRecordDecl *Base,
  1102. const ASTRecordLayout *RL = 0) {
  1103. if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
  1104. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1105. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1106. }
  1107. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1108. const CXXRecordDecl *DerivedDecl,
  1109. const CXXBaseSpecifier *Base) {
  1110. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1111. if (!Base->isVirtual()) {
  1112. HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1113. return true;
  1114. }
  1115. SubobjectDesignator &D = Obj.Designator;
  1116. if (D.Invalid)
  1117. return false;
  1118. // Extract most-derived object and corresponding type.
  1119. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1120. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1121. return false;
  1122. // Find the virtual base class.
  1123. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1124. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1125. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1126. return true;
  1127. }
  1128. /// Update LVal to refer to the given field, which must be a member of the type
  1129. /// currently described by LVal.
  1130. static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1131. const FieldDecl *FD,
  1132. const ASTRecordLayout *RL = 0) {
  1133. if (!RL)
  1134. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1135. unsigned I = FD->getFieldIndex();
  1136. LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
  1137. LVal.addDecl(Info, E, FD);
  1138. }
  1139. /// Update LVal to refer to the given indirect field.
  1140. static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1141. LValue &LVal,
  1142. const IndirectFieldDecl *IFD) {
  1143. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  1144. CE = IFD->chain_end(); C != CE; ++C)
  1145. HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
  1146. }
  1147. /// Get the size of the given type in char units.
  1148. static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
  1149. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1150. // extension.
  1151. if (Type->isVoidType() || Type->isFunctionType()) {
  1152. Size = CharUnits::One();
  1153. return true;
  1154. }
  1155. if (!Type->isConstantSizeType()) {
  1156. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1157. // FIXME: Diagnostic.
  1158. return false;
  1159. }
  1160. Size = Info.Ctx.getTypeSizeInChars(Type);
  1161. return true;
  1162. }
  1163. /// Update a pointer value to model pointer arithmetic.
  1164. /// \param Info - Information about the ongoing evaluation.
  1165. /// \param E - The expression being evaluated, for diagnostic purposes.
  1166. /// \param LVal - The pointer value to be updated.
  1167. /// \param EltTy - The pointee type represented by LVal.
  1168. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1169. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1170. LValue &LVal, QualType EltTy,
  1171. int64_t Adjustment) {
  1172. CharUnits SizeOfPointee;
  1173. if (!HandleSizeof(Info, EltTy, SizeOfPointee))
  1174. return false;
  1175. // Compute the new offset in the appropriate width.
  1176. LVal.Offset += Adjustment * SizeOfPointee;
  1177. LVal.adjustIndex(Info, E, Adjustment);
  1178. return true;
  1179. }
  1180. /// Try to evaluate the initializer for a variable declaration.
  1181. static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1182. const VarDecl *VD,
  1183. CallStackFrame *Frame, CCValue &Result) {
  1184. // If this is a parameter to an active constexpr function call, perform
  1185. // argument substitution.
  1186. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1187. // Assume arguments of a potential constant expression are unknown
  1188. // constant expressions.
  1189. if (Info.CheckingPotentialConstantExpression)
  1190. return false;
  1191. if (!Frame || !Frame->Arguments) {
  1192. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1193. return false;
  1194. }
  1195. Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
  1196. return true;
  1197. }
  1198. // Dig out the initializer, and use the declaration which it's attached to.
  1199. const Expr *Init = VD->getAnyInitializer(VD);
  1200. if (!Init || Init->isValueDependent()) {
  1201. // If we're checking a potential constant expression, the variable could be
  1202. // initialized later.
  1203. if (!Info.CheckingPotentialConstantExpression)
  1204. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1205. return false;
  1206. }
  1207. // If we're currently evaluating the initializer of this declaration, use that
  1208. // in-flight value.
  1209. if (Info.EvaluatingDecl == VD) {
  1210. Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
  1211. CCValue::GlobalValue());
  1212. return !Result.isUninit();
  1213. }
  1214. // Never evaluate the initializer of a weak variable. We can't be sure that
  1215. // this is the definition which will be used.
  1216. if (VD->isWeak()) {
  1217. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1218. return false;
  1219. }
  1220. // Check that we can fold the initializer. In C++, we will have already done
  1221. // this in the cases where it matters for conformance.
  1222. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  1223. if (!VD->evaluateValue(Notes)) {
  1224. Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
  1225. Notes.size() + 1) << VD;
  1226. Info.Note(VD->getLocation(), diag::note_declared_at);
  1227. Info.addNotes(Notes);
  1228. return false;
  1229. } else if (!VD->checkInitIsICE()) {
  1230. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
  1231. Notes.size() + 1) << VD;
  1232. Info.Note(VD->getLocation(), diag::note_declared_at);
  1233. Info.addNotes(Notes);
  1234. }
  1235. Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
  1236. return true;
  1237. }
  1238. static bool IsConstNonVolatile(QualType T) {
  1239. Qualifiers Quals = T.getQualifiers();
  1240. return Quals.hasConst() && !Quals.hasVolatile();
  1241. }
  1242. /// Get the base index of the given base class within an APValue representing
  1243. /// the given derived class.
  1244. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1245. const CXXRecordDecl *Base) {
  1246. Base = Base->getCanonicalDecl();
  1247. unsigned Index = 0;
  1248. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  1249. E = Derived->bases_end(); I != E; ++I, ++Index) {
  1250. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  1251. return Index;
  1252. }
  1253. llvm_unreachable("base class missing from derived class's bases list");
  1254. }
  1255. /// Extract the designated sub-object of an rvalue.
  1256. static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
  1257. CCValue &Obj, QualType ObjType,
  1258. const SubobjectDesignator &Sub, QualType SubType) {
  1259. if (Sub.Invalid)
  1260. // A diagnostic will have already been produced.
  1261. return false;
  1262. if (Sub.isOnePastTheEnd()) {
  1263. Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
  1264. (unsigned)diag::note_constexpr_read_past_end :
  1265. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1266. return false;
  1267. }
  1268. if (Sub.Entries.empty())
  1269. return true;
  1270. if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
  1271. // This object might be initialized later.
  1272. return false;
  1273. assert(!Obj.isLValue() && "extracting subobject of lvalue");
  1274. const APValue *O = &Obj;
  1275. // Walk the designator's path to find the subobject.
  1276. for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
  1277. if (ObjType->isArrayType()) {
  1278. // Next subobject is an array element.
  1279. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  1280. assert(CAT && "vla in literal type?");
  1281. uint64_t Index = Sub.Entries[I].ArrayIndex;
  1282. if (CAT->getSize().ule(Index)) {
  1283. // Note, it should not be possible to form a pointer with a valid
  1284. // designator which points more than one past the end of the array.
  1285. Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
  1286. (unsigned)diag::note_constexpr_read_past_end :
  1287. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1288. return false;
  1289. }
  1290. if (O->getArrayInitializedElts() > Index)
  1291. O = &O->getArrayInitializedElt(Index);
  1292. else
  1293. O = &O->getArrayFiller();
  1294. ObjType = CAT->getElementType();
  1295. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  1296. // Next subobject is a class, struct or union field.
  1297. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  1298. if (RD->isUnion()) {
  1299. const FieldDecl *UnionField = O->getUnionField();
  1300. if (!UnionField ||
  1301. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  1302. Info.Diag(E->getExprLoc(),
  1303. diag::note_constexpr_read_inactive_union_member)
  1304. << Field << !UnionField << UnionField;
  1305. return false;
  1306. }
  1307. O = &O->getUnionValue();
  1308. } else
  1309. O = &O->getStructField(Field->getFieldIndex());
  1310. ObjType = Field->getType();
  1311. if (ObjType.isVolatileQualified()) {
  1312. if (Info.getLangOpts().CPlusPlus) {
  1313. // FIXME: Include a description of the path to the volatile subobject.
  1314. Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
  1315. << 2 << Field;
  1316. Info.Note(Field->getLocation(), diag::note_declared_at);
  1317. } else {
  1318. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1319. }
  1320. return false;
  1321. }
  1322. } else {
  1323. // Next subobject is a base class.
  1324. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  1325. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  1326. O = &O->getStructBase(getBaseIndex(Derived, Base));
  1327. ObjType = Info.Ctx.getRecordType(Base);
  1328. }
  1329. if (O->isUninit()) {
  1330. if (!Info.CheckingPotentialConstantExpression)
  1331. Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
  1332. return false;
  1333. }
  1334. }
  1335. Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
  1336. return true;
  1337. }
  1338. /// Find the position where two subobject designators diverge, or equivalently
  1339. /// the length of the common initial subsequence.
  1340. static unsigned FindDesignatorMismatch(QualType ObjType,
  1341. const SubobjectDesignator &A,
  1342. const SubobjectDesignator &B,
  1343. bool &WasArrayIndex) {
  1344. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  1345. for (/**/; I != N; ++I) {
  1346. if (!ObjType.isNull() && ObjType->isArrayType()) {
  1347. // Next subobject is an array element.
  1348. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  1349. WasArrayIndex = true;
  1350. return I;
  1351. }
  1352. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  1353. } else {
  1354. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  1355. WasArrayIndex = false;
  1356. return I;
  1357. }
  1358. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  1359. // Next subobject is a field.
  1360. ObjType = FD->getType();
  1361. else
  1362. // Next subobject is a base class.
  1363. ObjType = QualType();
  1364. }
  1365. }
  1366. WasArrayIndex = false;
  1367. return I;
  1368. }
  1369. /// Determine whether the given subobject designators refer to elements of the
  1370. /// same array object.
  1371. static bool AreElementsOfSameArray(QualType ObjType,
  1372. const SubobjectDesignator &A,
  1373. const SubobjectDesignator &B) {
  1374. if (A.Entries.size() != B.Entries.size())
  1375. return false;
  1376. bool IsArray = A.MostDerivedArraySize != 0;
  1377. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  1378. // A is a subobject of the array element.
  1379. return false;
  1380. // If A (and B) designates an array element, the last entry will be the array
  1381. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  1382. // of length 1' case, and the entire path must match.
  1383. bool WasArrayIndex;
  1384. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  1385. return CommonLength >= A.Entries.size() - IsArray;
  1386. }
  1387. /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
  1388. /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
  1389. /// for looking up the glvalue referred to by an entity of reference type.
  1390. ///
  1391. /// \param Info - Information about the ongoing evaluation.
  1392. /// \param Conv - The expression for which we are performing the conversion.
  1393. /// Used for diagnostics.
  1394. /// \param Type - The type we expect this conversion to produce.
  1395. /// \param LVal - The glvalue on which we are attempting to perform this action.
  1396. /// \param RVal - The produced value will be placed here.
  1397. static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  1398. QualType Type,
  1399. const LValue &LVal, CCValue &RVal) {
  1400. // In C, an lvalue-to-rvalue conversion is never a constant expression.
  1401. if (!Info.getLangOpts().CPlusPlus)
  1402. Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1403. if (LVal.Designator.Invalid)
  1404. // A diagnostic will have already been produced.
  1405. return false;
  1406. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  1407. CallStackFrame *Frame = LVal.Frame;
  1408. SourceLocation Loc = Conv->getExprLoc();
  1409. if (!LVal.Base) {
  1410. // FIXME: Indirection through a null pointer deserves a specific diagnostic.
  1411. Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
  1412. return false;
  1413. }
  1414. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  1415. // is not a constant expression (even if the object is non-volatile). We also
  1416. // apply this rule to C++98, in order to conform to the expected 'volatile'
  1417. // semantics.
  1418. if (Type.isVolatileQualified()) {
  1419. if (Info.getLangOpts().CPlusPlus)
  1420. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
  1421. else
  1422. Info.Diag(Loc);
  1423. return false;
  1424. }
  1425. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  1426. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  1427. // In C++11, constexpr, non-volatile variables initialized with constant
  1428. // expressions are constant expressions too. Inside constexpr functions,
  1429. // parameters are constant expressions even if they're non-const.
  1430. // In C, such things can also be folded, although they are not ICEs.
  1431. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1432. if (const VarDecl *VDef = VD->getDefinition())
  1433. VD = VDef;
  1434. if (!VD || VD->isInvalidDecl()) {
  1435. Info.Diag(Loc);
  1436. return false;
  1437. }
  1438. // DR1313: If the object is volatile-qualified but the glvalue was not,
  1439. // behavior is undefined so the result is not a constant expression.
  1440. QualType VT = VD->getType();
  1441. if (VT.isVolatileQualified()) {
  1442. if (Info.getLangOpts().CPlusPlus) {
  1443. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
  1444. Info.Note(VD->getLocation(), diag::note_declared_at);
  1445. } else {
  1446. Info.Diag(Loc);
  1447. }
  1448. return false;
  1449. }
  1450. if (!isa<ParmVarDecl>(VD)) {
  1451. if (VD->isConstexpr()) {
  1452. // OK, we can read this variable.
  1453. } else if (VT->isIntegralOrEnumerationType()) {
  1454. if (!VT.isConstQualified()) {
  1455. if (Info.getLangOpts().CPlusPlus) {
  1456. Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  1457. Info.Note(VD->getLocation(), diag::note_declared_at);
  1458. } else {
  1459. Info.Diag(Loc);
  1460. }
  1461. return false;
  1462. }
  1463. } else if (VT->isFloatingType() && VT.isConstQualified()) {
  1464. // We support folding of const floating-point types, in order to make
  1465. // static const data members of such types (supported as an extension)
  1466. // more useful.
  1467. if (Info.getLangOpts().CPlusPlus0x) {
  1468. Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1469. Info.Note(VD->getLocation(), diag::note_declared_at);
  1470. } else {
  1471. Info.CCEDiag(Loc);
  1472. }
  1473. } else {
  1474. // FIXME: Allow folding of values of any literal type in all languages.
  1475. if (Info.getLangOpts().CPlusPlus0x) {
  1476. Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1477. Info.Note(VD->getLocation(), diag::note_declared_at);
  1478. } else {
  1479. Info.Diag(Loc);
  1480. }
  1481. return false;
  1482. }
  1483. }
  1484. if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
  1485. return false;
  1486. if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
  1487. return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
  1488. // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
  1489. // conversion. This happens when the declaration and the lvalue should be
  1490. // considered synonymous, for instance when initializing an array of char
  1491. // from a string literal. Continue as if the initializer lvalue was the
  1492. // value we were originally given.
  1493. assert(RVal.getLValueOffset().isZero() &&
  1494. "offset for lvalue init of non-reference");
  1495. Base = RVal.getLValueBase().get<const Expr*>();
  1496. Frame = RVal.getLValueFrame();
  1497. }
  1498. // Volatile temporary objects cannot be read in constant expressions.
  1499. if (Base->getType().isVolatileQualified()) {
  1500. if (Info.getLangOpts().CPlusPlus) {
  1501. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
  1502. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  1503. } else {
  1504. Info.Diag(Loc);
  1505. }
  1506. return false;
  1507. }
  1508. // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
  1509. if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
  1510. const SubobjectDesignator &Designator = LVal.Designator;
  1511. if (Designator.Invalid || Designator.Entries.size() != 1) {
  1512. Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1513. return false;
  1514. }
  1515. assert(Type->isIntegerType() && "string element not integer type");
  1516. uint64_t Index = Designator.Entries[0].ArrayIndex;
  1517. const ConstantArrayType *CAT =
  1518. Info.Ctx.getAsConstantArrayType(S->getType());
  1519. if (Index >= CAT->getSize().getZExtValue()) {
  1520. // Note, it should not be possible to form a pointer which points more
  1521. // than one past the end of the array without producing a prior const expr
  1522. // diagnostic.
  1523. Info.Diag(Loc, diag::note_constexpr_read_past_end);
  1524. return false;
  1525. }
  1526. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1527. Type->isUnsignedIntegerType());
  1528. if (Index < S->getLength())
  1529. Value = S->getCodeUnit(Index);
  1530. RVal = CCValue(Value);
  1531. return true;
  1532. }
  1533. if (Frame) {
  1534. // If this is a temporary expression with a nontrivial initializer, grab the
  1535. // value from the relevant stack frame.
  1536. RVal = Frame->Temporaries[Base];
  1537. } else if (const CompoundLiteralExpr *CLE
  1538. = dyn_cast<CompoundLiteralExpr>(Base)) {
  1539. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  1540. // initializer until now for such expressions. Such an expression can't be
  1541. // an ICE in C, so this only matters for fold.
  1542. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  1543. if (!Evaluate(RVal, Info, CLE->getInitializer()))
  1544. return false;
  1545. } else {
  1546. Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1547. return false;
  1548. }
  1549. return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
  1550. Type);
  1551. }
  1552. /// Build an lvalue for the object argument of a member function call.
  1553. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  1554. LValue &This) {
  1555. if (Object->getType()->isPointerType())
  1556. return EvaluatePointer(Object, This, Info);
  1557. if (Object->isGLValue())
  1558. return EvaluateLValue(Object, This, Info);
  1559. if (Object->getType()->isLiteralType())
  1560. return EvaluateTemporary(Object, This, Info);
  1561. return false;
  1562. }
  1563. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  1564. /// lvalue referring to the result.
  1565. ///
  1566. /// \param Info - Information about the ongoing evaluation.
  1567. /// \param BO - The member pointer access operation.
  1568. /// \param LV - Filled in with a reference to the resulting object.
  1569. /// \param IncludeMember - Specifies whether the member itself is included in
  1570. /// the resulting LValue subobject designator. This is not possible when
  1571. /// creating a bound member function.
  1572. /// \return The field or method declaration to which the member pointer refers,
  1573. /// or 0 if evaluation fails.
  1574. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  1575. const BinaryOperator *BO,
  1576. LValue &LV,
  1577. bool IncludeMember = true) {
  1578. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  1579. bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
  1580. if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
  1581. return 0;
  1582. MemberPtr MemPtr;
  1583. if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
  1584. return 0;
  1585. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  1586. // member value, the behavior is undefined.
  1587. if (!MemPtr.getDecl())
  1588. return 0;
  1589. if (!EvalObjOK)
  1590. return 0;
  1591. if (MemPtr.isDerivedMember()) {
  1592. // This is a member of some derived class. Truncate LV appropriately.
  1593. // The end of the derived-to-base path for the base object must match the
  1594. // derived-to-base path for the member pointer.
  1595. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  1596. LV.Designator.Entries.size())
  1597. return 0;
  1598. unsigned PathLengthToMember =
  1599. LV.Designator.Entries.size() - MemPtr.Path.size();
  1600. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  1601. const CXXRecordDecl *LVDecl = getAsBaseClass(
  1602. LV.Designator.Entries[PathLengthToMember + I]);
  1603. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  1604. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
  1605. return 0;
  1606. }
  1607. // Truncate the lvalue to the appropriate derived class.
  1608. if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
  1609. PathLengthToMember))
  1610. return 0;
  1611. } else if (!MemPtr.Path.empty()) {
  1612. // Extend the LValue path with the member pointer's path.
  1613. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  1614. MemPtr.Path.size() + IncludeMember);
  1615. // Walk down to the appropriate base class.
  1616. QualType LVType = BO->getLHS()->getType();
  1617. if (const PointerType *PT = LVType->getAs<PointerType>())
  1618. LVType = PT->getPointeeType();
  1619. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  1620. assert(RD && "member pointer access on non-class-type expression");
  1621. // The first class in the path is that of the lvalue.
  1622. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  1623. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  1624. HandleLValueDirectBase(Info, BO, LV, RD, Base);
  1625. RD = Base;
  1626. }
  1627. // Finally cast to the class containing the member.
  1628. HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
  1629. }
  1630. // Add the member. Note that we cannot build bound member functions here.
  1631. if (IncludeMember) {
  1632. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
  1633. HandleLValueMember(Info, BO, LV, FD);
  1634. else if (const IndirectFieldDecl *IFD =
  1635. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
  1636. HandleLValueIndirectMember(Info, BO, LV, IFD);
  1637. else
  1638. llvm_unreachable("can't construct reference to bound member function");
  1639. }
  1640. return MemPtr.getDecl();
  1641. }
  1642. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  1643. /// the provided lvalue, which currently refers to the base object.
  1644. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  1645. LValue &Result) {
  1646. SubobjectDesignator &D = Result.Designator;
  1647. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  1648. return false;
  1649. QualType TargetQT = E->getType();
  1650. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  1651. TargetQT = PT->getPointeeType();
  1652. // Check this cast lands within the final derived-to-base subobject path.
  1653. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  1654. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
  1655. << D.MostDerivedType << TargetQT;
  1656. return false;
  1657. }
  1658. // Check the type of the final cast. We don't need to check the path,
  1659. // since a cast can only be formed if the path is unique.
  1660. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  1661. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  1662. const CXXRecordDecl *FinalType;
  1663. if (NewEntriesSize == D.MostDerivedPathLength)
  1664. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  1665. else
  1666. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  1667. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  1668. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
  1669. << D.MostDerivedType << TargetQT;
  1670. return false;
  1671. }
  1672. // Truncate the lvalue to the appropriate derived class.
  1673. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  1674. }
  1675. namespace {
  1676. enum EvalStmtResult {
  1677. /// Evaluation failed.
  1678. ESR_Failed,
  1679. /// Hit a 'return' statement.
  1680. ESR_Returned,
  1681. /// Evaluation succeeded.
  1682. ESR_Succeeded
  1683. };
  1684. }
  1685. // Evaluate a statement.
  1686. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  1687. const Stmt *S) {
  1688. switch (S->getStmtClass()) {
  1689. default:
  1690. return ESR_Failed;
  1691. case Stmt::NullStmtClass:
  1692. case Stmt::DeclStmtClass:
  1693. return ESR_Succeeded;
  1694. case Stmt::ReturnStmtClass: {
  1695. CCValue CCResult;
  1696. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  1697. if (!Evaluate(CCResult, Info, RetExpr) ||
  1698. !CheckConstantExpression(Info, RetExpr, CCResult, Result,
  1699. CCEK_ReturnValue))
  1700. return ESR_Failed;
  1701. return ESR_Returned;
  1702. }
  1703. case Stmt::CompoundStmtClass: {
  1704. const CompoundStmt *CS = cast<CompoundStmt>(S);
  1705. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  1706. BE = CS->body_end(); BI != BE; ++BI) {
  1707. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  1708. if (ESR != ESR_Succeeded)
  1709. return ESR;
  1710. }
  1711. return ESR_Succeeded;
  1712. }
  1713. }
  1714. }
  1715. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  1716. /// default constructor. If so, we'll fold it whether or not it's marked as
  1717. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  1718. /// so we need special handling.
  1719. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  1720. const CXXConstructorDecl *CD,
  1721. bool IsValueInitialization) {
  1722. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  1723. return false;
  1724. // Value-initialization does not call a trivial default constructor, so such a
  1725. // call is a core constant expression whether or not the constructor is
  1726. // constexpr.
  1727. if (!CD->isConstexpr() && !IsValueInitialization) {
  1728. if (Info.getLangOpts().CPlusPlus0x) {
  1729. // FIXME: If DiagDecl is an implicitly-declared special member function,
  1730. // we should be much more explicit about why it's not constexpr.
  1731. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  1732. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  1733. Info.Note(CD->getLocation(), diag::note_declared_at);
  1734. } else {
  1735. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  1736. }
  1737. }
  1738. return true;
  1739. }
  1740. /// CheckConstexprFunction - Check that a function can be called in a constant
  1741. /// expression.
  1742. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  1743. const FunctionDecl *Declaration,
  1744. const FunctionDecl *Definition) {
  1745. // Potential constant expressions can contain calls to declared, but not yet
  1746. // defined, constexpr functions.
  1747. if (Info.CheckingPotentialConstantExpression && !Definition &&
  1748. Declaration->isConstexpr())
  1749. return false;
  1750. // Can we evaluate this function call?
  1751. if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
  1752. return true;
  1753. if (Info.getLangOpts().CPlusPlus0x) {
  1754. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  1755. // FIXME: If DiagDecl is an implicitly-declared special member function, we
  1756. // should be much more explicit about why it's not constexpr.
  1757. Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
  1758. << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
  1759. << DiagDecl;
  1760. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  1761. } else {
  1762. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  1763. }
  1764. return false;
  1765. }
  1766. namespace {
  1767. typedef SmallVector<CCValue, 8> ArgVector;
  1768. }
  1769. /// EvaluateArgs - Evaluate the arguments to a function call.
  1770. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  1771. EvalInfo &Info) {
  1772. bool Success = true;
  1773. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  1774. I != E; ++I) {
  1775. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  1776. // If we're checking for a potential constant expression, evaluate all
  1777. // initializers even if some of them fail.
  1778. if (!Info.keepEvaluatingAfterFailure())
  1779. return false;
  1780. Success = false;
  1781. }
  1782. }
  1783. return Success;
  1784. }
  1785. /// Evaluate a function call.
  1786. static bool HandleFunctionCall(SourceLocation CallLoc,
  1787. const FunctionDecl *Callee, const LValue *This,
  1788. ArrayRef<const Expr*> Args, const Stmt *Body,
  1789. EvalInfo &Info, APValue &Result) {
  1790. ArgVector ArgValues(Args.size());
  1791. if (!EvaluateArgs(Args, ArgValues, Info))
  1792. return false;
  1793. if (!Info.CheckCallLimit(CallLoc))
  1794. return false;
  1795. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  1796. return EvaluateStmt(Result, Info, Body) == ESR_Returned;
  1797. }
  1798. /// Evaluate a constructor call.
  1799. static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
  1800. ArrayRef<const Expr*> Args,
  1801. const CXXConstructorDecl *Definition,
  1802. EvalInfo &Info, APValue &Result) {
  1803. ArgVector ArgValues(Args.size());
  1804. if (!EvaluateArgs(Args, ArgValues, Info))
  1805. return false;
  1806. if (!Info.CheckCallLimit(CallLoc))
  1807. return false;
  1808. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
  1809. // If it's a delegating constructor, just delegate.
  1810. if (Definition->isDelegatingConstructor()) {
  1811. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  1812. return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
  1813. }
  1814. // For a trivial copy or move constructor, perform an APValue copy. This is
  1815. // essential for unions, where the operations performed by the constructor
  1816. // cannot be represented by ctor-initializers.
  1817. const CXXRecordDecl *RD = Definition->getParent();
  1818. if (Definition->isDefaulted() &&
  1819. ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
  1820. (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
  1821. LValue RHS;
  1822. RHS.setFrom(ArgValues[0]);
  1823. CCValue Value;
  1824. if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  1825. RHS, Value))
  1826. return false;
  1827. assert((Value.isStruct() || Value.isUnion()) &&
  1828. "trivial copy/move from non-class type?");
  1829. // Any CCValue of class type must already be a constant expression.
  1830. Result = Value;
  1831. return true;
  1832. }
  1833. // Reserve space for the struct members.
  1834. if (!RD->isUnion() && Result.isUninit())
  1835. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  1836. std::distance(RD->field_begin(), RD->field_end()));
  1837. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1838. bool Success = true;
  1839. unsigned BasesSeen = 0;
  1840. #ifndef NDEBUG
  1841. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  1842. #endif
  1843. for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
  1844. E = Definition->init_end(); I != E; ++I) {
  1845. LValue Subobject = This;
  1846. APValue *Value = &Result;
  1847. // Determine the subobject to initialize.
  1848. if ((*I)->isBaseInitializer()) {
  1849. QualType BaseType((*I)->getBaseClass(), 0);
  1850. #ifndef NDEBUG
  1851. // Non-virtual base classes are initialized in the order in the class
  1852. // definition. We cannot have a virtual base class for a literal type.
  1853. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  1854. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  1855. "base class initializers not in expected order");
  1856. ++BaseIt;
  1857. #endif
  1858. HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
  1859. BaseType->getAsCXXRecordDecl(), &Layout);
  1860. Value = &Result.getStructBase(BasesSeen++);
  1861. } else if (FieldDecl *FD = (*I)->getMember()) {
  1862. HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
  1863. if (RD->isUnion()) {
  1864. Result = APValue(FD);
  1865. Value = &Result.getUnionValue();
  1866. } else {
  1867. Value = &Result.getStructField(FD->getFieldIndex());
  1868. }
  1869. } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
  1870. // Walk the indirect field decl's chain to find the object to initialize,
  1871. // and make sure we've initialized every step along it.
  1872. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  1873. CE = IFD->chain_end();
  1874. C != CE; ++C) {
  1875. FieldDecl *FD = cast<FieldDecl>(*C);
  1876. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  1877. // Switch the union field if it differs. This happens if we had
  1878. // preceding zero-initialization, and we're now initializing a union
  1879. // subobject other than the first.
  1880. // FIXME: In this case, the values of the other subobjects are
  1881. // specified, since zero-initialization sets all padding bits to zero.
  1882. if (Value->isUninit() ||
  1883. (Value->isUnion() && Value->getUnionField() != FD)) {
  1884. if (CD->isUnion())
  1885. *Value = APValue(FD);
  1886. else
  1887. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  1888. std::distance(CD->field_begin(), CD->field_end()));
  1889. }
  1890. HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
  1891. if (CD->isUnion())
  1892. Value = &Value->getUnionValue();
  1893. else
  1894. Value = &Value->getStructField(FD->getFieldIndex());
  1895. }
  1896. } else {
  1897. llvm_unreachable("unknown base initializer kind");
  1898. }
  1899. if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
  1900. (*I)->isBaseInitializer()
  1901. ? CCEK_Constant : CCEK_MemberInit)) {
  1902. // If we're checking for a potential constant expression, evaluate all
  1903. // initializers even if some of them fail.
  1904. if (!Info.keepEvaluatingAfterFailure())
  1905. return false;
  1906. Success = false;
  1907. }
  1908. }
  1909. return Success;
  1910. }
  1911. namespace {
  1912. class HasSideEffect
  1913. : public ConstStmtVisitor<HasSideEffect, bool> {
  1914. const ASTContext &Ctx;
  1915. public:
  1916. HasSideEffect(const ASTContext &C) : Ctx(C) {}
  1917. // Unhandled nodes conservatively default to having side effects.
  1918. bool VisitStmt(const Stmt *S) {
  1919. return true;
  1920. }
  1921. bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
  1922. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
  1923. return Visit(E->getResultExpr());
  1924. }
  1925. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1926. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  1927. return true;
  1928. return false;
  1929. }
  1930. bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
  1931. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  1932. return true;
  1933. return false;
  1934. }
  1935. bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
  1936. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  1937. return true;
  1938. return false;
  1939. }
  1940. // We don't want to evaluate BlockExprs multiple times, as they generate
  1941. // a ton of code.
  1942. bool VisitBlockExpr(const BlockExpr *E) { return true; }
  1943. bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
  1944. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
  1945. { return Visit(E->getInitializer()); }
  1946. bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
  1947. bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
  1948. bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
  1949. bool VisitStringLiteral(const StringLiteral *E) { return false; }
  1950. bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
  1951. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
  1952. { return false; }
  1953. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
  1954. { return Visit(E->getLHS()) || Visit(E->getRHS()); }
  1955. bool VisitChooseExpr(const ChooseExpr *E)
  1956. { return Visit(E->getChosenSubExpr(Ctx)); }
  1957. bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
  1958. bool VisitBinAssign(const BinaryOperator *E) { return true; }
  1959. bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
  1960. bool VisitBinaryOperator(const BinaryOperator *E)
  1961. { return Visit(E->getLHS()) || Visit(E->getRHS()); }
  1962. bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
  1963. bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
  1964. bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
  1965. bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
  1966. bool VisitUnaryDeref(const UnaryOperator *E) {
  1967. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  1968. return true;
  1969. return Visit(E->getSubExpr());
  1970. }
  1971. bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
  1972. // Has side effects if any element does.
  1973. bool VisitInitListExpr(const InitListExpr *E) {
  1974. for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
  1975. if (Visit(E->getInit(i))) return true;
  1976. if (const Expr *filler = E->getArrayFiller())
  1977. return Visit(filler);
  1978. return false;
  1979. }
  1980. bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
  1981. };
  1982. class OpaqueValueEvaluation {
  1983. EvalInfo &info;
  1984. OpaqueValueExpr *opaqueValue;
  1985. public:
  1986. OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
  1987. Expr *value)
  1988. : info(info), opaqueValue(opaqueValue) {
  1989. // If evaluation fails, fail immediately.
  1990. if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
  1991. this->opaqueValue = 0;
  1992. return;
  1993. }
  1994. }
  1995. bool hasError() const { return opaqueValue == 0; }
  1996. ~OpaqueValueEvaluation() {
  1997. // FIXME: This will not work for recursive constexpr functions using opaque
  1998. // values. Restore the former value.
  1999. if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
  2000. }
  2001. };
  2002. } // end anonymous namespace
  2003. //===----------------------------------------------------------------------===//
  2004. // Generic Evaluation
  2005. //===----------------------------------------------------------------------===//
  2006. namespace {
  2007. // FIXME: RetTy is always bool. Remove it.
  2008. template <class Derived, typename RetTy=bool>
  2009. class ExprEvaluatorBase
  2010. : public ConstStmtVisitor<Derived, RetTy> {
  2011. private:
  2012. RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
  2013. return static_cast<Derived*>(this)->Success(V, E);
  2014. }
  2015. RetTy DerivedZeroInitialization(const Expr *E) {
  2016. return static_cast<Derived*>(this)->ZeroInitialization(E);
  2017. }
  2018. protected:
  2019. EvalInfo &Info;
  2020. typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
  2021. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  2022. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  2023. return Info.CCEDiag(E->getExprLoc(), D);
  2024. }
  2025. /// Report an evaluation error. This should only be called when an error is
  2026. /// first discovered. When propagating an error, just return false.
  2027. bool Error(const Expr *E, diag::kind D) {
  2028. Info.Diag(E->getExprLoc(), D);
  2029. return false;
  2030. }
  2031. bool Error(const Expr *E) {
  2032. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  2033. }
  2034. RetTy ZeroInitialization(const Expr *E) { return Error(E); }
  2035. public:
  2036. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  2037. RetTy VisitStmt(const Stmt *) {
  2038. llvm_unreachable("Expression evaluator should not be called on stmts");
  2039. }
  2040. RetTy VisitExpr(const Expr *E) {
  2041. return Error(E);
  2042. }
  2043. RetTy VisitParenExpr(const ParenExpr *E)
  2044. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2045. RetTy VisitUnaryExtension(const UnaryOperator *E)
  2046. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2047. RetTy VisitUnaryPlus(const UnaryOperator *E)
  2048. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2049. RetTy VisitChooseExpr(const ChooseExpr *E)
  2050. { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
  2051. RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  2052. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  2053. RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  2054. { return StmtVisitorTy::Visit(E->getReplacement()); }
  2055. RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  2056. { return StmtVisitorTy::Visit(E->getExpr()); }
  2057. // We cannot create any objects for which cleanups are required, so there is
  2058. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  2059. RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
  2060. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2061. RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  2062. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  2063. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2064. }
  2065. RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  2066. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  2067. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2068. }
  2069. RetTy VisitBinaryOperator(const BinaryOperator *E) {
  2070. switch (E->getOpcode()) {
  2071. default:
  2072. return Error(E);
  2073. case BO_Comma:
  2074. VisitIgnoredValue(E->getLHS());
  2075. return StmtVisitorTy::Visit(E->getRHS());
  2076. case BO_PtrMemD:
  2077. case BO_PtrMemI: {
  2078. LValue Obj;
  2079. if (!HandleMemberPointerAccess(Info, E, Obj))
  2080. return false;
  2081. CCValue Result;
  2082. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  2083. return false;
  2084. return DerivedSuccess(Result, E);
  2085. }
  2086. }
  2087. }
  2088. RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  2089. OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
  2090. if (opaque.hasError())
  2091. return false;
  2092. bool cond;
  2093. if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
  2094. return false;
  2095. return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
  2096. }
  2097. RetTy VisitConditionalOperator(const ConditionalOperator *E) {
  2098. bool IsBcpCall = false;
  2099. // If the condition (ignoring parens) is a __builtin_constant_p call,
  2100. // the result is a constant expression if it can be folded without
  2101. // side-effects. This is an important GNU extension. See GCC PR38377
  2102. // for discussion.
  2103. if (const CallExpr *CallCE =
  2104. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  2105. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  2106. IsBcpCall = true;
  2107. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  2108. // constant expression; we can't check whether it's potentially foldable.
  2109. if (Info.CheckingPotentialConstantExpression && IsBcpCall)
  2110. return false;
  2111. FoldConstant Fold(Info);
  2112. bool BoolResult;
  2113. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
  2114. return false;
  2115. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  2116. if (!StmtVisitorTy::Visit(EvalExpr))
  2117. return false;
  2118. if (IsBcpCall)
  2119. Fold.Fold(Info);
  2120. return true;
  2121. }
  2122. RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  2123. const CCValue *Value = Info.getOpaqueValue(E);
  2124. if (!Value) {
  2125. const Expr *Source = E->getSourceExpr();
  2126. if (!Source)
  2127. return Error(E);
  2128. if (Source == E) { // sanity checking.
  2129. assert(0 && "OpaqueValueExpr recursively refers to itself");
  2130. return Error(E);
  2131. }
  2132. return StmtVisitorTy::Visit(Source);
  2133. }
  2134. return DerivedSuccess(*Value, E);
  2135. }
  2136. RetTy VisitCallExpr(const CallExpr *E) {
  2137. const Expr *Callee = E->getCallee()->IgnoreParens();
  2138. QualType CalleeType = Callee->getType();
  2139. const FunctionDecl *FD = 0;
  2140. LValue *This = 0, ThisVal;
  2141. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  2142. // Extract function decl and 'this' pointer from the callee.
  2143. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  2144. const ValueDecl *Member = 0;
  2145. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  2146. // Explicit bound member calls, such as x.f() or p->g();
  2147. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  2148. return false;
  2149. Member = ME->getMemberDecl();
  2150. This = &ThisVal;
  2151. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  2152. // Indirect bound member calls ('.*' or '->*').
  2153. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  2154. if (!Member) return false;
  2155. This = &ThisVal;
  2156. } else
  2157. return Error(Callee);
  2158. FD = dyn_cast<FunctionDecl>(Member);
  2159. if (!FD)
  2160. return Error(Callee);
  2161. } else if (CalleeType->isFunctionPointerType()) {
  2162. LValue Call;
  2163. if (!EvaluatePointer(Callee, Call, Info))
  2164. return false;
  2165. if (!Call.getLValueOffset().isZero())
  2166. return Error(Callee);
  2167. FD = dyn_cast_or_null<FunctionDecl>(
  2168. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  2169. if (!FD)
  2170. return Error(Callee);
  2171. // Overloaded operator calls to member functions are represented as normal
  2172. // calls with '*this' as the first argument.
  2173. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  2174. if (MD && !MD->isStatic()) {
  2175. // FIXME: When selecting an implicit conversion for an overloaded
  2176. // operator delete, we sometimes try to evaluate calls to conversion
  2177. // operators without a 'this' parameter!
  2178. if (Args.empty())
  2179. return Error(E);
  2180. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  2181. return false;
  2182. This = &ThisVal;
  2183. Args = Args.slice(1);
  2184. }
  2185. // Don't call function pointers which have been cast to some other type.
  2186. if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
  2187. return Error(E);
  2188. } else
  2189. return Error(E);
  2190. if (This && !This->checkSubobject(Info, E, CSK_This))
  2191. return false;
  2192. const FunctionDecl *Definition = 0;
  2193. Stmt *Body = FD->getBody(Definition);
  2194. APValue Result;
  2195. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
  2196. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
  2197. Info, Result))
  2198. return false;
  2199. return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
  2200. }
  2201. RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2202. return StmtVisitorTy::Visit(E->getInitializer());
  2203. }
  2204. RetTy VisitInitListExpr(const InitListExpr *E) {
  2205. if (E->getNumInits() == 0)
  2206. return DerivedZeroInitialization(E);
  2207. if (E->getNumInits() == 1)
  2208. return StmtVisitorTy::Visit(E->getInit(0));
  2209. return Error(E);
  2210. }
  2211. RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  2212. return DerivedZeroInitialization(E);
  2213. }
  2214. RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  2215. return DerivedZeroInitialization(E);
  2216. }
  2217. RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  2218. return DerivedZeroInitialization(E);
  2219. }
  2220. /// A member expression where the object is a prvalue is itself a prvalue.
  2221. RetTy VisitMemberExpr(const MemberExpr *E) {
  2222. assert(!E->isArrow() && "missing call to bound member function?");
  2223. CCValue Val;
  2224. if (!Evaluate(Val, Info, E->getBase()))
  2225. return false;
  2226. QualType BaseTy = E->getBase()->getType();
  2227. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2228. if (!FD) return Error(E);
  2229. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  2230. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2231. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2232. SubobjectDesignator Designator(BaseTy);
  2233. Designator.addDeclUnchecked(FD);
  2234. return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
  2235. DerivedSuccess(Val, E);
  2236. }
  2237. RetTy VisitCastExpr(const CastExpr *E) {
  2238. switch (E->getCastKind()) {
  2239. default:
  2240. break;
  2241. case CK_AtomicToNonAtomic:
  2242. case CK_NonAtomicToAtomic:
  2243. case CK_NoOp:
  2244. case CK_UserDefinedConversion:
  2245. return StmtVisitorTy::Visit(E->getSubExpr());
  2246. case CK_LValueToRValue: {
  2247. LValue LVal;
  2248. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  2249. return false;
  2250. CCValue RVal;
  2251. if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
  2252. return false;
  2253. return DerivedSuccess(RVal, E);
  2254. }
  2255. }
  2256. return Error(E);
  2257. }
  2258. /// Visit a value which is evaluated, but whose value is ignored.
  2259. void VisitIgnoredValue(const Expr *E) {
  2260. CCValue Scratch;
  2261. if (!Evaluate(Scratch, Info, E))
  2262. Info.EvalStatus.HasSideEffects = true;
  2263. }
  2264. };
  2265. }
  2266. //===----------------------------------------------------------------------===//
  2267. // Common base class for lvalue and temporary evaluation.
  2268. //===----------------------------------------------------------------------===//
  2269. namespace {
  2270. template<class Derived>
  2271. class LValueExprEvaluatorBase
  2272. : public ExprEvaluatorBase<Derived, bool> {
  2273. protected:
  2274. LValue &Result;
  2275. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  2276. typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
  2277. bool Success(APValue::LValueBase B) {
  2278. Result.set(B);
  2279. return true;
  2280. }
  2281. public:
  2282. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  2283. ExprEvaluatorBaseTy(Info), Result(Result) {}
  2284. bool Success(const CCValue &V, const Expr *E) {
  2285. Result.setFrom(V);
  2286. return true;
  2287. }
  2288. bool VisitMemberExpr(const MemberExpr *E) {
  2289. // Handle non-static data members.
  2290. QualType BaseTy;
  2291. if (E->isArrow()) {
  2292. if (!EvaluatePointer(E->getBase(), Result, this->Info))
  2293. return false;
  2294. BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
  2295. } else if (E->getBase()->isRValue()) {
  2296. assert(E->getBase()->getType()->isRecordType());
  2297. if (!EvaluateTemporary(E->getBase(), Result, this->Info))
  2298. return false;
  2299. BaseTy = E->getBase()->getType();
  2300. } else {
  2301. if (!this->Visit(E->getBase()))
  2302. return false;
  2303. BaseTy = E->getBase()->getType();
  2304. }
  2305. const ValueDecl *MD = E->getMemberDecl();
  2306. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  2307. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2308. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2309. (void)BaseTy;
  2310. HandleLValueMember(this->Info, E, Result, FD);
  2311. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  2312. HandleLValueIndirectMember(this->Info, E, Result, IFD);
  2313. } else
  2314. return this->Error(E);
  2315. if (MD->getType()->isReferenceType()) {
  2316. CCValue RefValue;
  2317. if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  2318. RefValue))
  2319. return false;
  2320. return Success(RefValue, E);
  2321. }
  2322. return true;
  2323. }
  2324. bool VisitBinaryOperator(const BinaryOperator *E) {
  2325. switch (E->getOpcode()) {
  2326. default:
  2327. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2328. case BO_PtrMemD:
  2329. case BO_PtrMemI:
  2330. return HandleMemberPointerAccess(this->Info, E, Result);
  2331. }
  2332. }
  2333. bool VisitCastExpr(const CastExpr *E) {
  2334. switch (E->getCastKind()) {
  2335. default:
  2336. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2337. case CK_DerivedToBase:
  2338. case CK_UncheckedDerivedToBase: {
  2339. if (!this->Visit(E->getSubExpr()))
  2340. return false;
  2341. // Now figure out the necessary offset to add to the base LV to get from
  2342. // the derived class to the base class.
  2343. QualType Type = E->getSubExpr()->getType();
  2344. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2345. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2346. if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
  2347. *PathI))
  2348. return false;
  2349. Type = (*PathI)->getType();
  2350. }
  2351. return true;
  2352. }
  2353. }
  2354. }
  2355. };
  2356. }
  2357. //===----------------------------------------------------------------------===//
  2358. // LValue Evaluation
  2359. //
  2360. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  2361. // function designators (in C), decl references to void objects (in C), and
  2362. // temporaries (if building with -Wno-address-of-temporary).
  2363. //
  2364. // LValue evaluation produces values comprising a base expression of one of the
  2365. // following types:
  2366. // - Declarations
  2367. // * VarDecl
  2368. // * FunctionDecl
  2369. // - Literals
  2370. // * CompoundLiteralExpr in C
  2371. // * StringLiteral
  2372. // * CXXTypeidExpr
  2373. // * PredefinedExpr
  2374. // * ObjCStringLiteralExpr
  2375. // * ObjCEncodeExpr
  2376. // * AddrLabelExpr
  2377. // * BlockExpr
  2378. // * CallExpr for a MakeStringConstant builtin
  2379. // - Locals and temporaries
  2380. // * Any Expr, with a Frame indicating the function in which the temporary was
  2381. // evaluated.
  2382. // plus an offset in bytes.
  2383. //===----------------------------------------------------------------------===//
  2384. namespace {
  2385. class LValueExprEvaluator
  2386. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  2387. public:
  2388. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  2389. LValueExprEvaluatorBaseTy(Info, Result) {}
  2390. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  2391. bool VisitDeclRefExpr(const DeclRefExpr *E);
  2392. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  2393. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2394. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  2395. bool VisitMemberExpr(const MemberExpr *E);
  2396. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  2397. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  2398. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  2399. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  2400. bool VisitUnaryDeref(const UnaryOperator *E);
  2401. bool VisitCastExpr(const CastExpr *E) {
  2402. switch (E->getCastKind()) {
  2403. default:
  2404. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  2405. case CK_LValueBitCast:
  2406. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2407. if (!Visit(E->getSubExpr()))
  2408. return false;
  2409. Result.Designator.setInvalid();
  2410. return true;
  2411. case CK_BaseToDerived:
  2412. if (!Visit(E->getSubExpr()))
  2413. return false;
  2414. return HandleBaseToDerivedCast(Info, E, Result);
  2415. }
  2416. }
  2417. // FIXME: Missing: __real__, __imag__
  2418. };
  2419. } // end anonymous namespace
  2420. /// Evaluate an expression as an lvalue. This can be legitimately called on
  2421. /// expressions which are not glvalues, in a few cases:
  2422. /// * function designators in C,
  2423. /// * "extern void" objects,
  2424. /// * temporaries, if building with -Wno-address-of-temporary.
  2425. static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
  2426. assert((E->isGLValue() || E->getType()->isFunctionType() ||
  2427. E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
  2428. "can't evaluate expression as an lvalue");
  2429. return LValueExprEvaluator(Info, Result).Visit(E);
  2430. }
  2431. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  2432. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  2433. return Success(FD);
  2434. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  2435. return VisitVarDecl(E, VD);
  2436. return Error(E);
  2437. }
  2438. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  2439. if (!VD->getType()->isReferenceType()) {
  2440. if (isa<ParmVarDecl>(VD)) {
  2441. Result.set(VD, Info.CurrentCall);
  2442. return true;
  2443. }
  2444. return Success(VD);
  2445. }
  2446. CCValue V;
  2447. if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
  2448. return false;
  2449. return Success(V, E);
  2450. }
  2451. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  2452. const MaterializeTemporaryExpr *E) {
  2453. if (E->GetTemporaryExpr()->isRValue()) {
  2454. if (E->getType()->isRecordType())
  2455. return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
  2456. Result.set(E, Info.CurrentCall);
  2457. return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
  2458. Result, E->GetTemporaryExpr());
  2459. }
  2460. // Materialization of an lvalue temporary occurs when we need to force a copy
  2461. // (for instance, if it's a bitfield).
  2462. // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
  2463. if (!Visit(E->GetTemporaryExpr()))
  2464. return false;
  2465. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
  2466. Info.CurrentCall->Temporaries[E]))
  2467. return false;
  2468. Result.set(E, Info.CurrentCall);
  2469. return true;
  2470. }
  2471. bool
  2472. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2473. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  2474. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  2475. // only see this when folding in C, so there's no standard to follow here.
  2476. return Success(E);
  2477. }
  2478. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  2479. if (E->isTypeOperand())
  2480. return Success(E);
  2481. CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
  2482. if (RD && RD->isPolymorphic()) {
  2483. Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
  2484. << E->getExprOperand()->getType()
  2485. << E->getExprOperand()->getSourceRange();
  2486. return false;
  2487. }
  2488. return Success(E);
  2489. }
  2490. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  2491. // Handle static data members.
  2492. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  2493. VisitIgnoredValue(E->getBase());
  2494. return VisitVarDecl(E, VD);
  2495. }
  2496. // Handle static member functions.
  2497. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  2498. if (MD->isStatic()) {
  2499. VisitIgnoredValue(E->getBase());
  2500. return Success(MD);
  2501. }
  2502. }
  2503. // Handle non-static data members.
  2504. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  2505. }
  2506. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  2507. // FIXME: Deal with vectors as array subscript bases.
  2508. if (E->getBase()->getType()->isVectorType())
  2509. return Error(E);
  2510. if (!EvaluatePointer(E->getBase(), Result, Info))
  2511. return false;
  2512. APSInt Index;
  2513. if (!EvaluateInteger(E->getIdx(), Index, Info))
  2514. return false;
  2515. int64_t IndexValue
  2516. = Index.isSigned() ? Index.getSExtValue()
  2517. : static_cast<int64_t>(Index.getZExtValue());
  2518. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
  2519. }
  2520. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  2521. return EvaluatePointer(E->getSubExpr(), Result, Info);
  2522. }
  2523. //===----------------------------------------------------------------------===//
  2524. // Pointer Evaluation
  2525. //===----------------------------------------------------------------------===//
  2526. namespace {
  2527. class PointerExprEvaluator
  2528. : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
  2529. LValue &Result;
  2530. bool Success(const Expr *E) {
  2531. Result.set(E);
  2532. return true;
  2533. }
  2534. public:
  2535. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  2536. : ExprEvaluatorBaseTy(info), Result(Result) {}
  2537. bool Success(const CCValue &V, const Expr *E) {
  2538. Result.setFrom(V);
  2539. return true;
  2540. }
  2541. bool ZeroInitialization(const Expr *E) {
  2542. return Success((Expr*)0);
  2543. }
  2544. bool VisitBinaryOperator(const BinaryOperator *E);
  2545. bool VisitCastExpr(const CastExpr* E);
  2546. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2547. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  2548. { return Success(E); }
  2549. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  2550. { return Success(E); }
  2551. bool VisitCallExpr(const CallExpr *E);
  2552. bool VisitBlockExpr(const BlockExpr *E) {
  2553. if (!E->getBlockDecl()->hasCaptures())
  2554. return Success(E);
  2555. return Error(E);
  2556. }
  2557. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  2558. if (!Info.CurrentCall->This)
  2559. return Error(E);
  2560. Result = *Info.CurrentCall->This;
  2561. return true;
  2562. }
  2563. // FIXME: Missing: @protocol, @selector
  2564. };
  2565. } // end anonymous namespace
  2566. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  2567. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  2568. return PointerExprEvaluator(Info, Result).Visit(E);
  2569. }
  2570. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  2571. if (E->getOpcode() != BO_Add &&
  2572. E->getOpcode() != BO_Sub)
  2573. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2574. const Expr *PExp = E->getLHS();
  2575. const Expr *IExp = E->getRHS();
  2576. if (IExp->getType()->isPointerType())
  2577. std::swap(PExp, IExp);
  2578. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  2579. if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
  2580. return false;
  2581. llvm::APSInt Offset;
  2582. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  2583. return false;
  2584. int64_t AdditionalOffset
  2585. = Offset.isSigned() ? Offset.getSExtValue()
  2586. : static_cast<int64_t>(Offset.getZExtValue());
  2587. if (E->getOpcode() == BO_Sub)
  2588. AdditionalOffset = -AdditionalOffset;
  2589. QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
  2590. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  2591. AdditionalOffset);
  2592. }
  2593. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2594. return EvaluateLValue(E->getSubExpr(), Result, Info);
  2595. }
  2596. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  2597. const Expr* SubExpr = E->getSubExpr();
  2598. switch (E->getCastKind()) {
  2599. default:
  2600. break;
  2601. case CK_BitCast:
  2602. case CK_CPointerToObjCPointerCast:
  2603. case CK_BlockPointerToObjCPointerCast:
  2604. case CK_AnyPointerToBlockPointerCast:
  2605. if (!Visit(SubExpr))
  2606. return false;
  2607. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  2608. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  2609. // also static_casts, but we disallow them as a resolution to DR1312.
  2610. if (!E->getType()->isVoidPointerType()) {
  2611. Result.Designator.setInvalid();
  2612. if (SubExpr->getType()->isVoidPointerType())
  2613. CCEDiag(E, diag::note_constexpr_invalid_cast)
  2614. << 3 << SubExpr->getType();
  2615. else
  2616. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2617. }
  2618. return true;
  2619. case CK_DerivedToBase:
  2620. case CK_UncheckedDerivedToBase: {
  2621. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  2622. return false;
  2623. if (!Result.Base && Result.Offset.isZero())
  2624. return true;
  2625. // Now figure out the necessary offset to add to the base LV to get from
  2626. // the derived class to the base class.
  2627. QualType Type =
  2628. E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2629. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2630. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2631. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2632. *PathI))
  2633. return false;
  2634. Type = (*PathI)->getType();
  2635. }
  2636. return true;
  2637. }
  2638. case CK_BaseToDerived:
  2639. if (!Visit(E->getSubExpr()))
  2640. return false;
  2641. if (!Result.Base && Result.Offset.isZero())
  2642. return true;
  2643. return HandleBaseToDerivedCast(Info, E, Result);
  2644. case CK_NullToPointer:
  2645. return ZeroInitialization(E);
  2646. case CK_IntegralToPointer: {
  2647. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2648. CCValue Value;
  2649. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  2650. break;
  2651. if (Value.isInt()) {
  2652. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  2653. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  2654. Result.Base = (Expr*)0;
  2655. Result.Offset = CharUnits::fromQuantity(N);
  2656. Result.Frame = 0;
  2657. Result.Designator.setInvalid();
  2658. return true;
  2659. } else {
  2660. // Cast is of an lvalue, no need to change value.
  2661. Result.setFrom(Value);
  2662. return true;
  2663. }
  2664. }
  2665. case CK_ArrayToPointerDecay:
  2666. if (SubExpr->isGLValue()) {
  2667. if (!EvaluateLValue(SubExpr, Result, Info))
  2668. return false;
  2669. } else {
  2670. Result.set(SubExpr, Info.CurrentCall);
  2671. if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
  2672. Info, Result, SubExpr))
  2673. return false;
  2674. }
  2675. // The result is a pointer to the first element of the array.
  2676. if (const ConstantArrayType *CAT
  2677. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  2678. Result.addArray(Info, E, CAT);
  2679. else
  2680. Result.Designator.setInvalid();
  2681. return true;
  2682. case CK_FunctionToPointerDecay:
  2683. return EvaluateLValue(SubExpr, Result, Info);
  2684. }
  2685. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2686. }
  2687. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  2688. if (IsStringLiteralCall(E))
  2689. return Success(E);
  2690. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  2691. }
  2692. //===----------------------------------------------------------------------===//
  2693. // Member Pointer Evaluation
  2694. //===----------------------------------------------------------------------===//
  2695. namespace {
  2696. class MemberPointerExprEvaluator
  2697. : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
  2698. MemberPtr &Result;
  2699. bool Success(const ValueDecl *D) {
  2700. Result = MemberPtr(D);
  2701. return true;
  2702. }
  2703. public:
  2704. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  2705. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  2706. bool Success(const CCValue &V, const Expr *E) {
  2707. Result.setFrom(V);
  2708. return true;
  2709. }
  2710. bool ZeroInitialization(const Expr *E) {
  2711. return Success((const ValueDecl*)0);
  2712. }
  2713. bool VisitCastExpr(const CastExpr *E);
  2714. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2715. };
  2716. } // end anonymous namespace
  2717. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  2718. EvalInfo &Info) {
  2719. assert(E->isRValue() && E->getType()->isMemberPointerType());
  2720. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  2721. }
  2722. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  2723. switch (E->getCastKind()) {
  2724. default:
  2725. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2726. case CK_NullToMemberPointer:
  2727. return ZeroInitialization(E);
  2728. case CK_BaseToDerivedMemberPointer: {
  2729. if (!Visit(E->getSubExpr()))
  2730. return false;
  2731. if (E->path_empty())
  2732. return true;
  2733. // Base-to-derived member pointer casts store the path in derived-to-base
  2734. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  2735. // the wrong end of the derived->base arc, so stagger the path by one class.
  2736. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  2737. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  2738. PathI != PathE; ++PathI) {
  2739. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2740. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  2741. if (!Result.castToDerived(Derived))
  2742. return Error(E);
  2743. }
  2744. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  2745. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  2746. return Error(E);
  2747. return true;
  2748. }
  2749. case CK_DerivedToBaseMemberPointer:
  2750. if (!Visit(E->getSubExpr()))
  2751. return false;
  2752. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2753. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2754. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2755. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  2756. if (!Result.castToBase(Base))
  2757. return Error(E);
  2758. }
  2759. return true;
  2760. }
  2761. }
  2762. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2763. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  2764. // member can be formed.
  2765. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  2766. }
  2767. //===----------------------------------------------------------------------===//
  2768. // Record Evaluation
  2769. //===----------------------------------------------------------------------===//
  2770. namespace {
  2771. class RecordExprEvaluator
  2772. : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
  2773. const LValue &This;
  2774. APValue &Result;
  2775. public:
  2776. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  2777. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  2778. bool Success(const CCValue &V, const Expr *E) {
  2779. return CheckConstantExpression(Info, E, V, Result);
  2780. }
  2781. bool ZeroInitialization(const Expr *E);
  2782. bool VisitCastExpr(const CastExpr *E);
  2783. bool VisitInitListExpr(const InitListExpr *E);
  2784. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  2785. };
  2786. }
  2787. /// Perform zero-initialization on an object of non-union class type.
  2788. /// C++11 [dcl.init]p5:
  2789. /// To zero-initialize an object or reference of type T means:
  2790. /// [...]
  2791. /// -- if T is a (possibly cv-qualified) non-union class type,
  2792. /// each non-static data member and each base-class subobject is
  2793. /// zero-initialized
  2794. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  2795. const RecordDecl *RD,
  2796. const LValue &This, APValue &Result) {
  2797. assert(!RD->isUnion() && "Expected non-union class type");
  2798. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  2799. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  2800. std::distance(RD->field_begin(), RD->field_end()));
  2801. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2802. if (CD) {
  2803. unsigned Index = 0;
  2804. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  2805. End = CD->bases_end(); I != End; ++I, ++Index) {
  2806. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  2807. LValue Subobject = This;
  2808. HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
  2809. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  2810. Result.getStructBase(Index)))
  2811. return false;
  2812. }
  2813. }
  2814. for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
  2815. I != End; ++I) {
  2816. // -- if T is a reference type, no initialization is performed.
  2817. if ((*I)->getType()->isReferenceType())
  2818. continue;
  2819. LValue Subobject = This;
  2820. HandleLValueMember(Info, E, Subobject, *I, &Layout);
  2821. ImplicitValueInitExpr VIE((*I)->getType());
  2822. if (!EvaluateConstantExpression(
  2823. Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
  2824. return false;
  2825. }
  2826. return true;
  2827. }
  2828. bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
  2829. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  2830. if (RD->isUnion()) {
  2831. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  2832. // object's first non-static named data member is zero-initialized
  2833. RecordDecl::field_iterator I = RD->field_begin();
  2834. if (I == RD->field_end()) {
  2835. Result = APValue((const FieldDecl*)0);
  2836. return true;
  2837. }
  2838. LValue Subobject = This;
  2839. HandleLValueMember(Info, E, Subobject, *I);
  2840. Result = APValue(*I);
  2841. ImplicitValueInitExpr VIE((*I)->getType());
  2842. return EvaluateConstantExpression(Result.getUnionValue(), Info,
  2843. Subobject, &VIE);
  2844. }
  2845. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  2846. }
  2847. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  2848. switch (E->getCastKind()) {
  2849. default:
  2850. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2851. case CK_ConstructorConversion:
  2852. return Visit(E->getSubExpr());
  2853. case CK_DerivedToBase:
  2854. case CK_UncheckedDerivedToBase: {
  2855. CCValue DerivedObject;
  2856. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  2857. return false;
  2858. if (!DerivedObject.isStruct())
  2859. return Error(E->getSubExpr());
  2860. // Derived-to-base rvalue conversion: just slice off the derived part.
  2861. APValue *Value = &DerivedObject;
  2862. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  2863. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2864. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2865. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  2866. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  2867. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  2868. RD = Base;
  2869. }
  2870. Result = *Value;
  2871. return true;
  2872. }
  2873. }
  2874. }
  2875. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  2876. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  2877. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2878. if (RD->isUnion()) {
  2879. const FieldDecl *Field = E->getInitializedFieldInUnion();
  2880. Result = APValue(Field);
  2881. if (!Field)
  2882. return true;
  2883. // If the initializer list for a union does not contain any elements, the
  2884. // first element of the union is value-initialized.
  2885. ImplicitValueInitExpr VIE(Field->getType());
  2886. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  2887. LValue Subobject = This;
  2888. HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
  2889. return EvaluateConstantExpression(Result.getUnionValue(), Info,
  2890. Subobject, InitExpr);
  2891. }
  2892. assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
  2893. "initializer list for class with base classes");
  2894. Result = APValue(APValue::UninitStruct(), 0,
  2895. std::distance(RD->field_begin(), RD->field_end()));
  2896. unsigned ElementNo = 0;
  2897. bool Success = true;
  2898. for (RecordDecl::field_iterator Field = RD->field_begin(),
  2899. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
  2900. // Anonymous bit-fields are not considered members of the class for
  2901. // purposes of aggregate initialization.
  2902. if (Field->isUnnamedBitfield())
  2903. continue;
  2904. LValue Subobject = This;
  2905. bool HaveInit = ElementNo < E->getNumInits();
  2906. // FIXME: Diagnostics here should point to the end of the initializer
  2907. // list, not the start.
  2908. HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
  2909. *Field, &Layout);
  2910. // Perform an implicit value-initialization for members beyond the end of
  2911. // the initializer list.
  2912. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  2913. if (!EvaluateConstantExpression(
  2914. Result.getStructField((*Field)->getFieldIndex()),
  2915. Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
  2916. if (!Info.keepEvaluatingAfterFailure())
  2917. return false;
  2918. Success = false;
  2919. }
  2920. }
  2921. return Success;
  2922. }
  2923. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  2924. const CXXConstructorDecl *FD = E->getConstructor();
  2925. bool ZeroInit = E->requiresZeroInitialization();
  2926. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  2927. // If we've already performed zero-initialization, we're already done.
  2928. if (!Result.isUninit())
  2929. return true;
  2930. if (ZeroInit)
  2931. return ZeroInitialization(E);
  2932. const CXXRecordDecl *RD = FD->getParent();
  2933. if (RD->isUnion())
  2934. Result = APValue((FieldDecl*)0);
  2935. else
  2936. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  2937. std::distance(RD->field_begin(), RD->field_end()));
  2938. return true;
  2939. }
  2940. const FunctionDecl *Definition = 0;
  2941. FD->getBody(Definition);
  2942. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  2943. return false;
  2944. // Avoid materializing a temporary for an elidable copy/move constructor.
  2945. if (E->isElidable() && !ZeroInit)
  2946. if (const MaterializeTemporaryExpr *ME
  2947. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  2948. return Visit(ME->GetTemporaryExpr());
  2949. if (ZeroInit && !ZeroInitialization(E))
  2950. return false;
  2951. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  2952. return HandleConstructorCall(E->getExprLoc(), This, Args,
  2953. cast<CXXConstructorDecl>(Definition), Info,
  2954. Result);
  2955. }
  2956. static bool EvaluateRecord(const Expr *E, const LValue &This,
  2957. APValue &Result, EvalInfo &Info) {
  2958. assert(E->isRValue() && E->getType()->isRecordType() &&
  2959. "can't evaluate expression as a record rvalue");
  2960. return RecordExprEvaluator(Info, This, Result).Visit(E);
  2961. }
  2962. //===----------------------------------------------------------------------===//
  2963. // Temporary Evaluation
  2964. //
  2965. // Temporaries are represented in the AST as rvalues, but generally behave like
  2966. // lvalues. The full-object of which the temporary is a subobject is implicitly
  2967. // materialized so that a reference can bind to it.
  2968. //===----------------------------------------------------------------------===//
  2969. namespace {
  2970. class TemporaryExprEvaluator
  2971. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  2972. public:
  2973. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  2974. LValueExprEvaluatorBaseTy(Info, Result) {}
  2975. /// Visit an expression which constructs the value of this temporary.
  2976. bool VisitConstructExpr(const Expr *E) {
  2977. Result.set(E, Info.CurrentCall);
  2978. return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
  2979. Result, E);
  2980. }
  2981. bool VisitCastExpr(const CastExpr *E) {
  2982. switch (E->getCastKind()) {
  2983. default:
  2984. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  2985. case CK_ConstructorConversion:
  2986. return VisitConstructExpr(E->getSubExpr());
  2987. }
  2988. }
  2989. bool VisitInitListExpr(const InitListExpr *E) {
  2990. return VisitConstructExpr(E);
  2991. }
  2992. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  2993. return VisitConstructExpr(E);
  2994. }
  2995. bool VisitCallExpr(const CallExpr *E) {
  2996. return VisitConstructExpr(E);
  2997. }
  2998. };
  2999. } // end anonymous namespace
  3000. /// Evaluate an expression of record type as a temporary.
  3001. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  3002. assert(E->isRValue() && E->getType()->isRecordType());
  3003. return TemporaryExprEvaluator(Info, Result).Visit(E);
  3004. }
  3005. //===----------------------------------------------------------------------===//
  3006. // Vector Evaluation
  3007. //===----------------------------------------------------------------------===//
  3008. namespace {
  3009. class VectorExprEvaluator
  3010. : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
  3011. APValue &Result;
  3012. public:
  3013. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  3014. : ExprEvaluatorBaseTy(info), Result(Result) {}
  3015. bool Success(const ArrayRef<APValue> &V, const Expr *E) {
  3016. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  3017. // FIXME: remove this APValue copy.
  3018. Result = APValue(V.data(), V.size());
  3019. return true;
  3020. }
  3021. bool Success(const CCValue &V, const Expr *E) {
  3022. assert(V.isVector());
  3023. Result = V;
  3024. return true;
  3025. }
  3026. bool ZeroInitialization(const Expr *E);
  3027. bool VisitUnaryReal(const UnaryOperator *E)
  3028. { return Visit(E->getSubExpr()); }
  3029. bool VisitCastExpr(const CastExpr* E);
  3030. bool VisitInitListExpr(const InitListExpr *E);
  3031. bool VisitUnaryImag(const UnaryOperator *E);
  3032. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  3033. // binary comparisons, binary and/or/xor,
  3034. // shufflevector, ExtVectorElementExpr
  3035. };
  3036. } // end anonymous namespace
  3037. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  3038. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  3039. return VectorExprEvaluator(Info, Result).Visit(E);
  3040. }
  3041. bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
  3042. const VectorType *VTy = E->getType()->castAs<VectorType>();
  3043. unsigned NElts = VTy->getNumElements();
  3044. const Expr *SE = E->getSubExpr();
  3045. QualType SETy = SE->getType();
  3046. switch (E->getCastKind()) {
  3047. case CK_VectorSplat: {
  3048. APValue Val = APValue();
  3049. if (SETy->isIntegerType()) {
  3050. APSInt IntResult;
  3051. if (!EvaluateInteger(SE, IntResult, Info))
  3052. return false;
  3053. Val = APValue(IntResult);
  3054. } else if (SETy->isRealFloatingType()) {
  3055. APFloat F(0.0);
  3056. if (!EvaluateFloat(SE, F, Info))
  3057. return false;
  3058. Val = APValue(F);
  3059. } else {
  3060. return Error(E);
  3061. }
  3062. // Splat and create vector APValue.
  3063. SmallVector<APValue, 4> Elts(NElts, Val);
  3064. return Success(Elts, E);
  3065. }
  3066. case CK_BitCast: {
  3067. // Evaluate the operand into an APInt we can extract from.
  3068. llvm::APInt SValInt;
  3069. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  3070. return false;
  3071. // Extract the elements
  3072. QualType EltTy = VTy->getElementType();
  3073. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  3074. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  3075. SmallVector<APValue, 4> Elts;
  3076. if (EltTy->isRealFloatingType()) {
  3077. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  3078. bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
  3079. unsigned FloatEltSize = EltSize;
  3080. if (&Sem == &APFloat::x87DoubleExtended)
  3081. FloatEltSize = 80;
  3082. for (unsigned i = 0; i < NElts; i++) {
  3083. llvm::APInt Elt;
  3084. if (BigEndian)
  3085. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  3086. else
  3087. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  3088. Elts.push_back(APValue(APFloat(Elt, isIEESem)));
  3089. }
  3090. } else if (EltTy->isIntegerType()) {
  3091. for (unsigned i = 0; i < NElts; i++) {
  3092. llvm::APInt Elt;
  3093. if (BigEndian)
  3094. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  3095. else
  3096. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  3097. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  3098. }
  3099. } else {
  3100. return Error(E);
  3101. }
  3102. return Success(Elts, E);
  3103. }
  3104. default:
  3105. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  3106. }
  3107. }
  3108. bool
  3109. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3110. const VectorType *VT = E->getType()->castAs<VectorType>();
  3111. unsigned NumInits = E->getNumInits();
  3112. unsigned NumElements = VT->getNumElements();
  3113. QualType EltTy = VT->getElementType();
  3114. SmallVector<APValue, 4> Elements;
  3115. // The number of initializers can be less than the number of
  3116. // vector elements. For OpenCL, this can be due to nested vector
  3117. // initialization. For GCC compatibility, missing trailing elements
  3118. // should be initialized with zeroes.
  3119. unsigned CountInits = 0, CountElts = 0;
  3120. while (CountElts < NumElements) {
  3121. // Handle nested vector initialization.
  3122. if (CountInits < NumInits
  3123. && E->getInit(CountInits)->getType()->isExtVectorType()) {
  3124. APValue v;
  3125. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  3126. return Error(E);
  3127. unsigned vlen = v.getVectorLength();
  3128. for (unsigned j = 0; j < vlen; j++)
  3129. Elements.push_back(v.getVectorElt(j));
  3130. CountElts += vlen;
  3131. } else if (EltTy->isIntegerType()) {
  3132. llvm::APSInt sInt(32);
  3133. if (CountInits < NumInits) {
  3134. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  3135. return Error(E);
  3136. } else // trailing integer zero.
  3137. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  3138. Elements.push_back(APValue(sInt));
  3139. CountElts++;
  3140. } else {
  3141. llvm::APFloat f(0.0);
  3142. if (CountInits < NumInits) {
  3143. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  3144. return Error(E);
  3145. } else // trailing float zero.
  3146. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  3147. Elements.push_back(APValue(f));
  3148. CountElts++;
  3149. }
  3150. CountInits++;
  3151. }
  3152. return Success(Elements, E);
  3153. }
  3154. bool
  3155. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  3156. const VectorType *VT = E->getType()->getAs<VectorType>();
  3157. QualType EltTy = VT->getElementType();
  3158. APValue ZeroElement;
  3159. if (EltTy->isIntegerType())
  3160. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  3161. else
  3162. ZeroElement =
  3163. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  3164. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  3165. return Success(Elements, E);
  3166. }
  3167. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  3168. VisitIgnoredValue(E->getSubExpr());
  3169. return ZeroInitialization(E);
  3170. }
  3171. //===----------------------------------------------------------------------===//
  3172. // Array Evaluation
  3173. //===----------------------------------------------------------------------===//
  3174. namespace {
  3175. class ArrayExprEvaluator
  3176. : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
  3177. const LValue &This;
  3178. APValue &Result;
  3179. public:
  3180. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  3181. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  3182. bool Success(const APValue &V, const Expr *E) {
  3183. assert(V.isArray() && "Expected array type");
  3184. Result = V;
  3185. return true;
  3186. }
  3187. bool ZeroInitialization(const Expr *E) {
  3188. const ConstantArrayType *CAT =
  3189. Info.Ctx.getAsConstantArrayType(E->getType());
  3190. if (!CAT)
  3191. return Error(E);
  3192. Result = APValue(APValue::UninitArray(), 0,
  3193. CAT->getSize().getZExtValue());
  3194. if (!Result.hasArrayFiller()) return true;
  3195. // Zero-initialize all elements.
  3196. LValue Subobject = This;
  3197. Subobject.addArray(Info, E, CAT);
  3198. ImplicitValueInitExpr VIE(CAT->getElementType());
  3199. return EvaluateConstantExpression(Result.getArrayFiller(), Info,
  3200. Subobject, &VIE);
  3201. }
  3202. bool VisitInitListExpr(const InitListExpr *E);
  3203. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  3204. };
  3205. } // end anonymous namespace
  3206. static bool EvaluateArray(const Expr *E, const LValue &This,
  3207. APValue &Result, EvalInfo &Info) {
  3208. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  3209. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  3210. }
  3211. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3212. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  3213. if (!CAT)
  3214. return Error(E);
  3215. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  3216. // an appropriately-typed string literal enclosed in braces.
  3217. if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
  3218. Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
  3219. LValue LV;
  3220. if (!EvaluateLValue(E->getInit(0), LV, Info))
  3221. return false;
  3222. uint64_t NumElements = CAT->getSize().getZExtValue();
  3223. Result = APValue(APValue::UninitArray(), NumElements, NumElements);
  3224. // Copy the string literal into the array. FIXME: Do this better.
  3225. LV.addArray(Info, E, CAT);
  3226. for (uint64_t I = 0; I < NumElements; ++I) {
  3227. CCValue Char;
  3228. if (!HandleLValueToRValueConversion(Info, E->getInit(0),
  3229. CAT->getElementType(), LV, Char) ||
  3230. !CheckConstantExpression(Info, E->getInit(0), Char,
  3231. Result.getArrayInitializedElt(I)) ||
  3232. !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
  3233. CAT->getElementType(), 1))
  3234. return false;
  3235. }
  3236. return true;
  3237. }
  3238. bool Success = true;
  3239. Result = APValue(APValue::UninitArray(), E->getNumInits(),
  3240. CAT->getSize().getZExtValue());
  3241. LValue Subobject = This;
  3242. Subobject.addArray(Info, E, CAT);
  3243. unsigned Index = 0;
  3244. for (InitListExpr::const_iterator I = E->begin(), End = E->end();
  3245. I != End; ++I, ++Index) {
  3246. if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
  3247. Info, Subobject, cast<Expr>(*I)) ||
  3248. !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
  3249. CAT->getElementType(), 1)) {
  3250. if (!Info.keepEvaluatingAfterFailure())
  3251. return false;
  3252. Success = false;
  3253. }
  3254. }
  3255. if (!Result.hasArrayFiller()) return Success;
  3256. assert(E->hasArrayFiller() && "no array filler for incomplete init list");
  3257. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3258. // but sometimes does:
  3259. // struct S { constexpr S() : p(&p) {} void *p; };
  3260. // S s[10] = {};
  3261. return EvaluateConstantExpression(Result.getArrayFiller(), Info,
  3262. Subobject, E->getArrayFiller()) && Success;
  3263. }
  3264. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3265. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  3266. if (!CAT)
  3267. return Error(E);
  3268. bool HadZeroInit = !Result.isUninit();
  3269. if (!HadZeroInit)
  3270. Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
  3271. if (!Result.hasArrayFiller())
  3272. return true;
  3273. const CXXConstructorDecl *FD = E->getConstructor();
  3274. bool ZeroInit = E->requiresZeroInitialization();
  3275. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  3276. if (HadZeroInit)
  3277. return true;
  3278. if (ZeroInit) {
  3279. LValue Subobject = This;
  3280. Subobject.addArray(Info, E, CAT);
  3281. ImplicitValueInitExpr VIE(CAT->getElementType());
  3282. return EvaluateConstantExpression(Result.getArrayFiller(), Info,
  3283. Subobject, &VIE);
  3284. }
  3285. const CXXRecordDecl *RD = FD->getParent();
  3286. if (RD->isUnion())
  3287. Result.getArrayFiller() = APValue((FieldDecl*)0);
  3288. else
  3289. Result.getArrayFiller() =
  3290. APValue(APValue::UninitStruct(), RD->getNumBases(),
  3291. std::distance(RD->field_begin(), RD->field_end()));
  3292. return true;
  3293. }
  3294. const FunctionDecl *Definition = 0;
  3295. FD->getBody(Definition);
  3296. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  3297. return false;
  3298. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3299. // but sometimes does:
  3300. // struct S { constexpr S() : p(&p) {} void *p; };
  3301. // S s[10];
  3302. LValue Subobject = This;
  3303. Subobject.addArray(Info, E, CAT);
  3304. if (ZeroInit && !HadZeroInit) {
  3305. ImplicitValueInitExpr VIE(CAT->getElementType());
  3306. if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
  3307. &VIE))
  3308. return false;
  3309. }
  3310. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  3311. return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
  3312. cast<CXXConstructorDecl>(Definition),
  3313. Info, Result.getArrayFiller());
  3314. }
  3315. //===----------------------------------------------------------------------===//
  3316. // Integer Evaluation
  3317. //
  3318. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  3319. // types and back in constant folding. Integer values are thus represented
  3320. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  3321. //===----------------------------------------------------------------------===//
  3322. namespace {
  3323. class IntExprEvaluator
  3324. : public ExprEvaluatorBase<IntExprEvaluator, bool> {
  3325. CCValue &Result;
  3326. public:
  3327. IntExprEvaluator(EvalInfo &info, CCValue &result)
  3328. : ExprEvaluatorBaseTy(info), Result(result) {}
  3329. bool Success(const llvm::APSInt &SI, const Expr *E) {
  3330. assert(E->getType()->isIntegralOrEnumerationType() &&
  3331. "Invalid evaluation result.");
  3332. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  3333. "Invalid evaluation result.");
  3334. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3335. "Invalid evaluation result.");
  3336. Result = CCValue(SI);
  3337. return true;
  3338. }
  3339. bool Success(const llvm::APInt &I, const Expr *E) {
  3340. assert(E->getType()->isIntegralOrEnumerationType() &&
  3341. "Invalid evaluation result.");
  3342. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3343. "Invalid evaluation result.");
  3344. Result = CCValue(APSInt(I));
  3345. Result.getInt().setIsUnsigned(
  3346. E->getType()->isUnsignedIntegerOrEnumerationType());
  3347. return true;
  3348. }
  3349. bool Success(uint64_t Value, const Expr *E) {
  3350. assert(E->getType()->isIntegralOrEnumerationType() &&
  3351. "Invalid evaluation result.");
  3352. Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  3353. return true;
  3354. }
  3355. bool Success(CharUnits Size, const Expr *E) {
  3356. return Success(Size.getQuantity(), E);
  3357. }
  3358. bool Success(const CCValue &V, const Expr *E) {
  3359. if (V.isLValue() || V.isAddrLabelDiff()) {
  3360. Result = V;
  3361. return true;
  3362. }
  3363. return Success(V.getInt(), E);
  3364. }
  3365. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  3366. //===--------------------------------------------------------------------===//
  3367. // Visitor Methods
  3368. //===--------------------------------------------------------------------===//
  3369. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  3370. return Success(E->getValue(), E);
  3371. }
  3372. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  3373. return Success(E->getValue(), E);
  3374. }
  3375. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  3376. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  3377. if (CheckReferencedDecl(E, E->getDecl()))
  3378. return true;
  3379. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  3380. }
  3381. bool VisitMemberExpr(const MemberExpr *E) {
  3382. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  3383. VisitIgnoredValue(E->getBase());
  3384. return true;
  3385. }
  3386. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  3387. }
  3388. bool VisitCallExpr(const CallExpr *E);
  3389. bool VisitBinaryOperator(const BinaryOperator *E);
  3390. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  3391. bool VisitUnaryOperator(const UnaryOperator *E);
  3392. bool VisitCastExpr(const CastExpr* E);
  3393. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  3394. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  3395. return Success(E->getValue(), E);
  3396. }
  3397. // Note, GNU defines __null as an integer, not a pointer.
  3398. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  3399. return ZeroInitialization(E);
  3400. }
  3401. bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
  3402. return Success(E->getValue(), E);
  3403. }
  3404. bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
  3405. return Success(E->getValue(), E);
  3406. }
  3407. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  3408. return Success(E->getValue(), E);
  3409. }
  3410. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  3411. return Success(E->getValue(), E);
  3412. }
  3413. bool VisitUnaryReal(const UnaryOperator *E);
  3414. bool VisitUnaryImag(const UnaryOperator *E);
  3415. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  3416. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  3417. private:
  3418. CharUnits GetAlignOfExpr(const Expr *E);
  3419. CharUnits GetAlignOfType(QualType T);
  3420. static QualType GetObjectType(APValue::LValueBase B);
  3421. bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
  3422. // FIXME: Missing: array subscript of vector, member of vector
  3423. };
  3424. } // end anonymous namespace
  3425. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  3426. /// produce either the integer value or a pointer.
  3427. ///
  3428. /// GCC has a heinous extension which folds casts between pointer types and
  3429. /// pointer-sized integral types. We support this by allowing the evaluation of
  3430. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  3431. /// Some simple arithmetic on such values is supported (they are treated much
  3432. /// like char*).
  3433. static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
  3434. EvalInfo &Info) {
  3435. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  3436. return IntExprEvaluator(Info, Result).Visit(E);
  3437. }
  3438. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  3439. CCValue Val;
  3440. if (!EvaluateIntegerOrLValue(E, Val, Info))
  3441. return false;
  3442. if (!Val.isInt()) {
  3443. // FIXME: It would be better to produce the diagnostic for casting
  3444. // a pointer to an integer.
  3445. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  3446. return false;
  3447. }
  3448. Result = Val.getInt();
  3449. return true;
  3450. }
  3451. /// Check whether the given declaration can be directly converted to an integral
  3452. /// rvalue. If not, no diagnostic is produced; there are other things we can
  3453. /// try.
  3454. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  3455. // Enums are integer constant exprs.
  3456. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  3457. // Check for signedness/width mismatches between E type and ECD value.
  3458. bool SameSign = (ECD->getInitVal().isSigned()
  3459. == E->getType()->isSignedIntegerOrEnumerationType());
  3460. bool SameWidth = (ECD->getInitVal().getBitWidth()
  3461. == Info.Ctx.getIntWidth(E->getType()));
  3462. if (SameSign && SameWidth)
  3463. return Success(ECD->getInitVal(), E);
  3464. else {
  3465. // Get rid of mismatch (otherwise Success assertions will fail)
  3466. // by computing a new value matching the type of E.
  3467. llvm::APSInt Val = ECD->getInitVal();
  3468. if (!SameSign)
  3469. Val.setIsSigned(!ECD->getInitVal().isSigned());
  3470. if (!SameWidth)
  3471. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  3472. return Success(Val, E);
  3473. }
  3474. }
  3475. return false;
  3476. }
  3477. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  3478. /// as GCC.
  3479. static int EvaluateBuiltinClassifyType(const CallExpr *E) {
  3480. // The following enum mimics the values returned by GCC.
  3481. // FIXME: Does GCC differ between lvalue and rvalue references here?
  3482. enum gcc_type_class {
  3483. no_type_class = -1,
  3484. void_type_class, integer_type_class, char_type_class,
  3485. enumeral_type_class, boolean_type_class,
  3486. pointer_type_class, reference_type_class, offset_type_class,
  3487. real_type_class, complex_type_class,
  3488. function_type_class, method_type_class,
  3489. record_type_class, union_type_class,
  3490. array_type_class, string_type_class,
  3491. lang_type_class
  3492. };
  3493. // If no argument was supplied, default to "no_type_class". This isn't
  3494. // ideal, however it is what gcc does.
  3495. if (E->getNumArgs() == 0)
  3496. return no_type_class;
  3497. QualType ArgTy = E->getArg(0)->getType();
  3498. if (ArgTy->isVoidType())
  3499. return void_type_class;
  3500. else if (ArgTy->isEnumeralType())
  3501. return enumeral_type_class;
  3502. else if (ArgTy->isBooleanType())
  3503. return boolean_type_class;
  3504. else if (ArgTy->isCharType())
  3505. return string_type_class; // gcc doesn't appear to use char_type_class
  3506. else if (ArgTy->isIntegerType())
  3507. return integer_type_class;
  3508. else if (ArgTy->isPointerType())
  3509. return pointer_type_class;
  3510. else if (ArgTy->isReferenceType())
  3511. return reference_type_class;
  3512. else if (ArgTy->isRealType())
  3513. return real_type_class;
  3514. else if (ArgTy->isComplexType())
  3515. return complex_type_class;
  3516. else if (ArgTy->isFunctionType())
  3517. return function_type_class;
  3518. else if (ArgTy->isStructureOrClassType())
  3519. return record_type_class;
  3520. else if (ArgTy->isUnionType())
  3521. return union_type_class;
  3522. else if (ArgTy->isArrayType())
  3523. return array_type_class;
  3524. else if (ArgTy->isUnionType())
  3525. return union_type_class;
  3526. else // FIXME: offset_type_class, method_type_class, & lang_type_class?
  3527. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  3528. }
  3529. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  3530. /// __builtin_constant_p when applied to the given lvalue.
  3531. ///
  3532. /// An lvalue is only "constant" if it is a pointer or reference to the first
  3533. /// character of a string literal.
  3534. template<typename LValue>
  3535. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  3536. const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
  3537. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  3538. }
  3539. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  3540. /// GCC as we can manage.
  3541. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  3542. QualType ArgType = Arg->getType();
  3543. // __builtin_constant_p always has one operand. The rules which gcc follows
  3544. // are not precisely documented, but are as follows:
  3545. //
  3546. // - If the operand is of integral, floating, complex or enumeration type,
  3547. // and can be folded to a known value of that type, it returns 1.
  3548. // - If the operand and can be folded to a pointer to the first character
  3549. // of a string literal (or such a pointer cast to an integral type), it
  3550. // returns 1.
  3551. //
  3552. // Otherwise, it returns 0.
  3553. //
  3554. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  3555. // its support for this does not currently work.
  3556. if (ArgType->isIntegralOrEnumerationType()) {
  3557. Expr::EvalResult Result;
  3558. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  3559. return false;
  3560. APValue &V = Result.Val;
  3561. if (V.getKind() == APValue::Int)
  3562. return true;
  3563. return EvaluateBuiltinConstantPForLValue(V);
  3564. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  3565. return Arg->isEvaluatable(Ctx);
  3566. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  3567. LValue LV;
  3568. Expr::EvalStatus Status;
  3569. EvalInfo Info(Ctx, Status);
  3570. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  3571. : EvaluatePointer(Arg, LV, Info)) &&
  3572. !Status.HasSideEffects)
  3573. return EvaluateBuiltinConstantPForLValue(LV);
  3574. }
  3575. // Anything else isn't considered to be sufficiently constant.
  3576. return false;
  3577. }
  3578. /// Retrieves the "underlying object type" of the given expression,
  3579. /// as used by __builtin_object_size.
  3580. QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
  3581. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  3582. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3583. return VD->getType();
  3584. } else if (const Expr *E = B.get<const Expr*>()) {
  3585. if (isa<CompoundLiteralExpr>(E))
  3586. return E->getType();
  3587. }
  3588. return QualType();
  3589. }
  3590. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
  3591. // TODO: Perhaps we should let LLVM lower this?
  3592. LValue Base;
  3593. if (!EvaluatePointer(E->getArg(0), Base, Info))
  3594. return false;
  3595. // If we can prove the base is null, lower to zero now.
  3596. if (!Base.getLValueBase()) return Success(0, E);
  3597. QualType T = GetObjectType(Base.getLValueBase());
  3598. if (T.isNull() ||
  3599. T->isIncompleteType() ||
  3600. T->isFunctionType() ||
  3601. T->isVariablyModifiedType() ||
  3602. T->isDependentType())
  3603. return Error(E);
  3604. CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
  3605. CharUnits Offset = Base.getLValueOffset();
  3606. if (!Offset.isNegative() && Offset <= Size)
  3607. Size -= Offset;
  3608. else
  3609. Size = CharUnits::Zero();
  3610. return Success(Size, E);
  3611. }
  3612. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  3613. switch (E->isBuiltinCall()) {
  3614. default:
  3615. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  3616. case Builtin::BI__builtin_object_size: {
  3617. if (TryEvaluateBuiltinObjectSize(E))
  3618. return true;
  3619. // If evaluating the argument has side-effects we can't determine
  3620. // the size of the object and lower it to unknown now.
  3621. if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
  3622. if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
  3623. return Success(-1ULL, E);
  3624. return Success(0, E);
  3625. }
  3626. return Error(E);
  3627. }
  3628. case Builtin::BI__builtin_classify_type:
  3629. return Success(EvaluateBuiltinClassifyType(E), E);
  3630. case Builtin::BI__builtin_constant_p:
  3631. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  3632. case Builtin::BI__builtin_eh_return_data_regno: {
  3633. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  3634. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  3635. return Success(Operand, E);
  3636. }
  3637. case Builtin::BI__builtin_expect:
  3638. return Visit(E->getArg(0));
  3639. case Builtin::BIstrlen:
  3640. // A call to strlen is not a constant expression.
  3641. if (Info.getLangOpts().CPlusPlus0x)
  3642. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
  3643. << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
  3644. else
  3645. Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  3646. // Fall through.
  3647. case Builtin::BI__builtin_strlen:
  3648. // As an extension, we support strlen() and __builtin_strlen() as constant
  3649. // expressions when the argument is a string literal.
  3650. if (const StringLiteral *S
  3651. = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
  3652. // The string literal may have embedded null characters. Find the first
  3653. // one and truncate there.
  3654. StringRef Str = S->getString();
  3655. StringRef::size_type Pos = Str.find(0);
  3656. if (Pos != StringRef::npos)
  3657. Str = Str.substr(0, Pos);
  3658. return Success(Str.size(), E);
  3659. }
  3660. return Error(E);
  3661. case Builtin::BI__atomic_is_lock_free: {
  3662. APSInt SizeVal;
  3663. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  3664. return false;
  3665. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  3666. // of two less than the maximum inline atomic width, we know it is
  3667. // lock-free. If the size isn't a power of two, or greater than the
  3668. // maximum alignment where we promote atomics, we know it is not lock-free
  3669. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  3670. // the answer can only be determined at runtime; for example, 16-byte
  3671. // atomics have lock-free implementations on some, but not all,
  3672. // x86-64 processors.
  3673. // Check power-of-two.
  3674. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  3675. if (!Size.isPowerOfTwo())
  3676. #if 0
  3677. // FIXME: Suppress this folding until the ABI for the promotion width
  3678. // settles.
  3679. return Success(0, E);
  3680. #else
  3681. return Error(E);
  3682. #endif
  3683. #if 0
  3684. // Check against promotion width.
  3685. // FIXME: Suppress this folding until the ABI for the promotion width
  3686. // settles.
  3687. unsigned PromoteWidthBits =
  3688. Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
  3689. if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
  3690. return Success(0, E);
  3691. #endif
  3692. // Check against inlining width.
  3693. unsigned InlineWidthBits =
  3694. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  3695. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
  3696. return Success(1, E);
  3697. return Error(E);
  3698. }
  3699. }
  3700. }
  3701. static bool HasSameBase(const LValue &A, const LValue &B) {
  3702. if (!A.getLValueBase())
  3703. return !B.getLValueBase();
  3704. if (!B.getLValueBase())
  3705. return false;
  3706. if (A.getLValueBase().getOpaqueValue() !=
  3707. B.getLValueBase().getOpaqueValue()) {
  3708. const Decl *ADecl = GetLValueBaseDecl(A);
  3709. if (!ADecl)
  3710. return false;
  3711. const Decl *BDecl = GetLValueBaseDecl(B);
  3712. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  3713. return false;
  3714. }
  3715. return IsGlobalLValue(A.getLValueBase()) ||
  3716. A.getLValueFrame() == B.getLValueFrame();
  3717. }
  3718. /// Perform the given integer operation, which is known to need at most BitWidth
  3719. /// bits, and check for overflow in the original type (if that type was not an
  3720. /// unsigned type).
  3721. template<typename Operation>
  3722. static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  3723. const APSInt &LHS, const APSInt &RHS,
  3724. unsigned BitWidth, Operation Op) {
  3725. if (LHS.isUnsigned())
  3726. return Op(LHS, RHS);
  3727. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  3728. APSInt Result = Value.trunc(LHS.getBitWidth());
  3729. if (Result.extend(BitWidth) != Value)
  3730. HandleOverflow(Info, E, Value, E->getType());
  3731. return Result;
  3732. }
  3733. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  3734. if (E->isAssignmentOp())
  3735. return Error(E);
  3736. if (E->getOpcode() == BO_Comma) {
  3737. VisitIgnoredValue(E->getLHS());
  3738. return Visit(E->getRHS());
  3739. }
  3740. if (E->isLogicalOp()) {
  3741. // These need to be handled specially because the operands aren't
  3742. // necessarily integral
  3743. bool lhsResult, rhsResult;
  3744. if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
  3745. // We were able to evaluate the LHS, see if we can get away with not
  3746. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  3747. if (lhsResult == (E->getOpcode() == BO_LOr))
  3748. return Success(lhsResult, E);
  3749. if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
  3750. if (E->getOpcode() == BO_LOr)
  3751. return Success(lhsResult || rhsResult, E);
  3752. else
  3753. return Success(lhsResult && rhsResult, E);
  3754. }
  3755. } else {
  3756. // FIXME: If both evaluations fail, we should produce the diagnostic from
  3757. // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
  3758. // less clear how to diagnose this.
  3759. if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
  3760. // We can't evaluate the LHS; however, sometimes the result
  3761. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  3762. if (rhsResult == (E->getOpcode() == BO_LOr)) {
  3763. // Since we weren't able to evaluate the left hand side, it
  3764. // must have had side effects.
  3765. Info.EvalStatus.HasSideEffects = true;
  3766. return Success(rhsResult, E);
  3767. }
  3768. }
  3769. }
  3770. return false;
  3771. }
  3772. QualType LHSTy = E->getLHS()->getType();
  3773. QualType RHSTy = E->getRHS()->getType();
  3774. if (LHSTy->isAnyComplexType()) {
  3775. assert(RHSTy->isAnyComplexType() && "Invalid comparison");
  3776. ComplexValue LHS, RHS;
  3777. bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  3778. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  3779. return false;
  3780. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  3781. return false;
  3782. if (LHS.isComplexFloat()) {
  3783. APFloat::cmpResult CR_r =
  3784. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  3785. APFloat::cmpResult CR_i =
  3786. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  3787. if (E->getOpcode() == BO_EQ)
  3788. return Success((CR_r == APFloat::cmpEqual &&
  3789. CR_i == APFloat::cmpEqual), E);
  3790. else {
  3791. assert(E->getOpcode() == BO_NE &&
  3792. "Invalid complex comparison.");
  3793. return Success(((CR_r == APFloat::cmpGreaterThan ||
  3794. CR_r == APFloat::cmpLessThan ||
  3795. CR_r == APFloat::cmpUnordered) ||
  3796. (CR_i == APFloat::cmpGreaterThan ||
  3797. CR_i == APFloat::cmpLessThan ||
  3798. CR_i == APFloat::cmpUnordered)), E);
  3799. }
  3800. } else {
  3801. if (E->getOpcode() == BO_EQ)
  3802. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  3803. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  3804. else {
  3805. assert(E->getOpcode() == BO_NE &&
  3806. "Invalid compex comparison.");
  3807. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  3808. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  3809. }
  3810. }
  3811. }
  3812. if (LHSTy->isRealFloatingType() &&
  3813. RHSTy->isRealFloatingType()) {
  3814. APFloat RHS(0.0), LHS(0.0);
  3815. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  3816. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  3817. return false;
  3818. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  3819. return false;
  3820. APFloat::cmpResult CR = LHS.compare(RHS);
  3821. switch (E->getOpcode()) {
  3822. default:
  3823. llvm_unreachable("Invalid binary operator!");
  3824. case BO_LT:
  3825. return Success(CR == APFloat::cmpLessThan, E);
  3826. case BO_GT:
  3827. return Success(CR == APFloat::cmpGreaterThan, E);
  3828. case BO_LE:
  3829. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  3830. case BO_GE:
  3831. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  3832. E);
  3833. case BO_EQ:
  3834. return Success(CR == APFloat::cmpEqual, E);
  3835. case BO_NE:
  3836. return Success(CR == APFloat::cmpGreaterThan
  3837. || CR == APFloat::cmpLessThan
  3838. || CR == APFloat::cmpUnordered, E);
  3839. }
  3840. }
  3841. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  3842. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  3843. LValue LHSValue, RHSValue;
  3844. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  3845. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  3846. return false;
  3847. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  3848. return false;
  3849. // Reject differing bases from the normal codepath; we special-case
  3850. // comparisons to null.
  3851. if (!HasSameBase(LHSValue, RHSValue)) {
  3852. if (E->getOpcode() == BO_Sub) {
  3853. // Handle &&A - &&B.
  3854. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  3855. return false;
  3856. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  3857. const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  3858. if (!LHSExpr || !RHSExpr)
  3859. return false;
  3860. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  3861. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  3862. if (!LHSAddrExpr || !RHSAddrExpr)
  3863. return false;
  3864. // Make sure both labels come from the same function.
  3865. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  3866. RHSAddrExpr->getLabel()->getDeclContext())
  3867. return false;
  3868. Result = CCValue(LHSAddrExpr, RHSAddrExpr);
  3869. return true;
  3870. }
  3871. // Inequalities and subtractions between unrelated pointers have
  3872. // unspecified or undefined behavior.
  3873. if (!E->isEqualityOp())
  3874. return Error(E);
  3875. // A constant address may compare equal to the address of a symbol.
  3876. // The one exception is that address of an object cannot compare equal
  3877. // to a null pointer constant.
  3878. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  3879. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  3880. return Error(E);
  3881. // It's implementation-defined whether distinct literals will have
  3882. // distinct addresses. In clang, the result of such a comparison is
  3883. // unspecified, so it is not a constant expression. However, we do know
  3884. // that the address of a literal will be non-null.
  3885. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  3886. LHSValue.Base && RHSValue.Base)
  3887. return Error(E);
  3888. // We can't tell whether weak symbols will end up pointing to the same
  3889. // object.
  3890. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  3891. return Error(E);
  3892. // Pointers with different bases cannot represent the same object.
  3893. // (Note that clang defaults to -fmerge-all-constants, which can
  3894. // lead to inconsistent results for comparisons involving the address
  3895. // of a constant; this generally doesn't matter in practice.)
  3896. return Success(E->getOpcode() == BO_NE, E);
  3897. }
  3898. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  3899. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  3900. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  3901. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  3902. if (E->getOpcode() == BO_Sub) {
  3903. // C++11 [expr.add]p6:
  3904. // Unless both pointers point to elements of the same array object, or
  3905. // one past the last element of the array object, the behavior is
  3906. // undefined.
  3907. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  3908. !AreElementsOfSameArray(getType(LHSValue.Base),
  3909. LHSDesignator, RHSDesignator))
  3910. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  3911. QualType Type = E->getLHS()->getType();
  3912. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  3913. CharUnits ElementSize;
  3914. if (!HandleSizeof(Info, ElementType, ElementSize))
  3915. return false;
  3916. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  3917. // and produce incorrect results when it overflows. Such behavior
  3918. // appears to be non-conforming, but is common, so perhaps we should
  3919. // assume the standard intended for such cases to be undefined behavior
  3920. // and check for them.
  3921. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  3922. // overflow in the final conversion to ptrdiff_t.
  3923. APSInt LHS(
  3924. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  3925. APSInt RHS(
  3926. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  3927. APSInt ElemSize(
  3928. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  3929. APSInt TrueResult = (LHS - RHS) / ElemSize;
  3930. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  3931. if (Result.extend(65) != TrueResult)
  3932. HandleOverflow(Info, E, TrueResult, E->getType());
  3933. return Success(Result, E);
  3934. }
  3935. // C++11 [expr.rel]p3:
  3936. // Pointers to void (after pointer conversions) can be compared, with a
  3937. // result defined as follows: If both pointers represent the same
  3938. // address or are both the null pointer value, the result is true if the
  3939. // operator is <= or >= and false otherwise; otherwise the result is
  3940. // unspecified.
  3941. // We interpret this as applying to pointers to *cv* void.
  3942. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  3943. E->isRelationalOp())
  3944. CCEDiag(E, diag::note_constexpr_void_comparison);
  3945. // C++11 [expr.rel]p2:
  3946. // - If two pointers point to non-static data members of the same object,
  3947. // or to subobjects or array elements fo such members, recursively, the
  3948. // pointer to the later declared member compares greater provided the
  3949. // two members have the same access control and provided their class is
  3950. // not a union.
  3951. // [...]
  3952. // - Otherwise pointer comparisons are unspecified.
  3953. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  3954. E->isRelationalOp()) {
  3955. bool WasArrayIndex;
  3956. unsigned Mismatch =
  3957. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  3958. RHSDesignator, WasArrayIndex);
  3959. // At the point where the designators diverge, the comparison has a
  3960. // specified value if:
  3961. // - we are comparing array indices
  3962. // - we are comparing fields of a union, or fields with the same access
  3963. // Otherwise, the result is unspecified and thus the comparison is not a
  3964. // constant expression.
  3965. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  3966. Mismatch < RHSDesignator.Entries.size()) {
  3967. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  3968. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  3969. if (!LF && !RF)
  3970. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  3971. else if (!LF)
  3972. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  3973. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  3974. << RF->getParent() << RF;
  3975. else if (!RF)
  3976. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  3977. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  3978. << LF->getParent() << LF;
  3979. else if (!LF->getParent()->isUnion() &&
  3980. LF->getAccess() != RF->getAccess())
  3981. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  3982. << LF << LF->getAccess() << RF << RF->getAccess()
  3983. << LF->getParent();
  3984. }
  3985. }
  3986. switch (E->getOpcode()) {
  3987. default: llvm_unreachable("missing comparison operator");
  3988. case BO_LT: return Success(LHSOffset < RHSOffset, E);
  3989. case BO_GT: return Success(LHSOffset > RHSOffset, E);
  3990. case BO_LE: return Success(LHSOffset <= RHSOffset, E);
  3991. case BO_GE: return Success(LHSOffset >= RHSOffset, E);
  3992. case BO_EQ: return Success(LHSOffset == RHSOffset, E);
  3993. case BO_NE: return Success(LHSOffset != RHSOffset, E);
  3994. }
  3995. }
  3996. }
  3997. if (LHSTy->isMemberPointerType()) {
  3998. assert(E->isEqualityOp() && "unexpected member pointer operation");
  3999. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  4000. MemberPtr LHSValue, RHSValue;
  4001. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  4002. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  4003. return false;
  4004. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  4005. return false;
  4006. // C++11 [expr.eq]p2:
  4007. // If both operands are null, they compare equal. Otherwise if only one is
  4008. // null, they compare unequal.
  4009. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  4010. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  4011. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4012. }
  4013. // Otherwise if either is a pointer to a virtual member function, the
  4014. // result is unspecified.
  4015. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  4016. if (MD->isVirtual())
  4017. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4018. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  4019. if (MD->isVirtual())
  4020. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4021. // Otherwise they compare equal if and only if they would refer to the
  4022. // same member of the same most derived object or the same subobject if
  4023. // they were dereferenced with a hypothetical object of the associated
  4024. // class type.
  4025. bool Equal = LHSValue == RHSValue;
  4026. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4027. }
  4028. if (!LHSTy->isIntegralOrEnumerationType() ||
  4029. !RHSTy->isIntegralOrEnumerationType()) {
  4030. // We can't continue from here for non-integral types.
  4031. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4032. }
  4033. // The LHS of a constant expr is always evaluated and needed.
  4034. CCValue LHSVal;
  4035. bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
  4036. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4037. return false;
  4038. if (!Visit(E->getRHS()) || !LHSOK)
  4039. return false;
  4040. CCValue &RHSVal = Result;
  4041. // Handle cases like (unsigned long)&a + 4.
  4042. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  4043. CharUnits AdditionalOffset = CharUnits::fromQuantity(
  4044. RHSVal.getInt().getZExtValue());
  4045. if (E->getOpcode() == BO_Add)
  4046. LHSVal.getLValueOffset() += AdditionalOffset;
  4047. else
  4048. LHSVal.getLValueOffset() -= AdditionalOffset;
  4049. Result = LHSVal;
  4050. return true;
  4051. }
  4052. // Handle cases like 4 + (unsigned long)&a
  4053. if (E->getOpcode() == BO_Add &&
  4054. RHSVal.isLValue() && LHSVal.isInt()) {
  4055. RHSVal.getLValueOffset() += CharUnits::fromQuantity(
  4056. LHSVal.getInt().getZExtValue());
  4057. // Note that RHSVal is Result.
  4058. return true;
  4059. }
  4060. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  4061. // Handle (intptr_t)&&A - (intptr_t)&&B.
  4062. if (!LHSVal.getLValueOffset().isZero() ||
  4063. !RHSVal.getLValueOffset().isZero())
  4064. return false;
  4065. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  4066. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  4067. if (!LHSExpr || !RHSExpr)
  4068. return false;
  4069. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  4070. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  4071. if (!LHSAddrExpr || !RHSAddrExpr)
  4072. return false;
  4073. // Make sure both labels come from the same function.
  4074. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  4075. RHSAddrExpr->getLabel()->getDeclContext())
  4076. return false;
  4077. Result = CCValue(LHSAddrExpr, RHSAddrExpr);
  4078. return true;
  4079. }
  4080. // All the following cases expect both operands to be an integer
  4081. if (!LHSVal.isInt() || !RHSVal.isInt())
  4082. return Error(E);
  4083. APSInt &LHS = LHSVal.getInt();
  4084. APSInt &RHS = RHSVal.getInt();
  4085. switch (E->getOpcode()) {
  4086. default:
  4087. return Error(E);
  4088. case BO_Mul:
  4089. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4090. LHS.getBitWidth() * 2,
  4091. std::multiplies<APSInt>()), E);
  4092. case BO_Add:
  4093. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4094. LHS.getBitWidth() + 1,
  4095. std::plus<APSInt>()), E);
  4096. case BO_Sub:
  4097. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4098. LHS.getBitWidth() + 1,
  4099. std::minus<APSInt>()), E);
  4100. case BO_And: return Success(LHS & RHS, E);
  4101. case BO_Xor: return Success(LHS ^ RHS, E);
  4102. case BO_Or: return Success(LHS | RHS, E);
  4103. case BO_Div:
  4104. case BO_Rem:
  4105. if (RHS == 0)
  4106. return Error(E, diag::note_expr_divide_by_zero);
  4107. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
  4108. // actually undefined behavior in C++11 due to a language defect.
  4109. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  4110. LHS.isSigned() && LHS.isMinSignedValue())
  4111. HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  4112. return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
  4113. case BO_Shl: {
  4114. // During constant-folding, a negative shift is an opposite shift. Such a
  4115. // shift is not a constant expression.
  4116. if (RHS.isSigned() && RHS.isNegative()) {
  4117. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4118. RHS = -RHS;
  4119. goto shift_right;
  4120. }
  4121. shift_left:
  4122. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  4123. // shifted type.
  4124. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4125. if (SA != RHS) {
  4126. CCEDiag(E, diag::note_constexpr_large_shift)
  4127. << RHS << E->getType() << LHS.getBitWidth();
  4128. } else if (LHS.isSigned()) {
  4129. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  4130. // operand, and must not overflow.
  4131. if (LHS.isNegative())
  4132. CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  4133. else if (LHS.countLeadingZeros() <= SA)
  4134. HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
  4135. E->getType());
  4136. }
  4137. return Success(LHS << SA, E);
  4138. }
  4139. case BO_Shr: {
  4140. // During constant-folding, a negative shift is an opposite shift. Such a
  4141. // shift is not a constant expression.
  4142. if (RHS.isSigned() && RHS.isNegative()) {
  4143. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4144. RHS = -RHS;
  4145. goto shift_left;
  4146. }
  4147. shift_right:
  4148. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  4149. // shifted type.
  4150. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4151. if (SA != RHS)
  4152. CCEDiag(E, diag::note_constexpr_large_shift)
  4153. << RHS << E->getType() << LHS.getBitWidth();
  4154. return Success(LHS >> SA, E);
  4155. }
  4156. case BO_LT: return Success(LHS < RHS, E);
  4157. case BO_GT: return Success(LHS > RHS, E);
  4158. case BO_LE: return Success(LHS <= RHS, E);
  4159. case BO_GE: return Success(LHS >= RHS, E);
  4160. case BO_EQ: return Success(LHS == RHS, E);
  4161. case BO_NE: return Success(LHS != RHS, E);
  4162. }
  4163. }
  4164. CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
  4165. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  4166. // the result is the size of the referenced type."
  4167. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  4168. // result shall be the alignment of the referenced type."
  4169. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4170. T = Ref->getPointeeType();
  4171. // __alignof is defined to return the preferred alignment.
  4172. return Info.Ctx.toCharUnitsFromBits(
  4173. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4174. }
  4175. CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
  4176. E = E->IgnoreParens();
  4177. // alignof decl is always accepted, even if it doesn't make sense: we default
  4178. // to 1 in those cases.
  4179. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4180. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4181. /*RefAsPointee*/true);
  4182. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4183. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4184. /*RefAsPointee*/true);
  4185. return GetAlignOfType(E->getType());
  4186. }
  4187. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  4188. /// a result as the expression's type.
  4189. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  4190. const UnaryExprOrTypeTraitExpr *E) {
  4191. switch(E->getKind()) {
  4192. case UETT_AlignOf: {
  4193. if (E->isArgumentType())
  4194. return Success(GetAlignOfType(E->getArgumentType()), E);
  4195. else
  4196. return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
  4197. }
  4198. case UETT_VecStep: {
  4199. QualType Ty = E->getTypeOfArgument();
  4200. if (Ty->isVectorType()) {
  4201. unsigned n = Ty->getAs<VectorType>()->getNumElements();
  4202. // The vec_step built-in functions that take a 3-component
  4203. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  4204. if (n == 3)
  4205. n = 4;
  4206. return Success(n, E);
  4207. } else
  4208. return Success(1, E);
  4209. }
  4210. case UETT_SizeOf: {
  4211. QualType SrcTy = E->getTypeOfArgument();
  4212. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  4213. // the result is the size of the referenced type."
  4214. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  4215. // result shall be the alignment of the referenced type."
  4216. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  4217. SrcTy = Ref->getPointeeType();
  4218. CharUnits Sizeof;
  4219. if (!HandleSizeof(Info, SrcTy, Sizeof))
  4220. return false;
  4221. return Success(Sizeof, E);
  4222. }
  4223. }
  4224. llvm_unreachable("unknown expr/type trait");
  4225. }
  4226. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  4227. CharUnits Result;
  4228. unsigned n = OOE->getNumComponents();
  4229. if (n == 0)
  4230. return Error(OOE);
  4231. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  4232. for (unsigned i = 0; i != n; ++i) {
  4233. OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
  4234. switch (ON.getKind()) {
  4235. case OffsetOfExpr::OffsetOfNode::Array: {
  4236. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  4237. APSInt IdxResult;
  4238. if (!EvaluateInteger(Idx, IdxResult, Info))
  4239. return false;
  4240. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  4241. if (!AT)
  4242. return Error(OOE);
  4243. CurrentType = AT->getElementType();
  4244. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  4245. Result += IdxResult.getSExtValue() * ElementSize;
  4246. break;
  4247. }
  4248. case OffsetOfExpr::OffsetOfNode::Field: {
  4249. FieldDecl *MemberDecl = ON.getField();
  4250. const RecordType *RT = CurrentType->getAs<RecordType>();
  4251. if (!RT)
  4252. return Error(OOE);
  4253. RecordDecl *RD = RT->getDecl();
  4254. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4255. unsigned i = MemberDecl->getFieldIndex();
  4256. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  4257. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  4258. CurrentType = MemberDecl->getType().getNonReferenceType();
  4259. break;
  4260. }
  4261. case OffsetOfExpr::OffsetOfNode::Identifier:
  4262. llvm_unreachable("dependent __builtin_offsetof");
  4263. case OffsetOfExpr::OffsetOfNode::Base: {
  4264. CXXBaseSpecifier *BaseSpec = ON.getBase();
  4265. if (BaseSpec->isVirtual())
  4266. return Error(OOE);
  4267. // Find the layout of the class whose base we are looking into.
  4268. const RecordType *RT = CurrentType->getAs<RecordType>();
  4269. if (!RT)
  4270. return Error(OOE);
  4271. RecordDecl *RD = RT->getDecl();
  4272. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4273. // Find the base class itself.
  4274. CurrentType = BaseSpec->getType();
  4275. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  4276. if (!BaseRT)
  4277. return Error(OOE);
  4278. // Add the offset to the base.
  4279. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  4280. break;
  4281. }
  4282. }
  4283. }
  4284. return Success(Result, OOE);
  4285. }
  4286. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4287. switch (E->getOpcode()) {
  4288. default:
  4289. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  4290. // See C99 6.6p3.
  4291. return Error(E);
  4292. case UO_Extension:
  4293. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  4294. // If so, we could clear the diagnostic ID.
  4295. return Visit(E->getSubExpr());
  4296. case UO_Plus:
  4297. // The result is just the value.
  4298. return Visit(E->getSubExpr());
  4299. case UO_Minus: {
  4300. if (!Visit(E->getSubExpr()))
  4301. return false;
  4302. if (!Result.isInt()) return Error(E);
  4303. const APSInt &Value = Result.getInt();
  4304. if (Value.isSigned() && Value.isMinSignedValue())
  4305. HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  4306. E->getType());
  4307. return Success(-Value, E);
  4308. }
  4309. case UO_Not: {
  4310. if (!Visit(E->getSubExpr()))
  4311. return false;
  4312. if (!Result.isInt()) return Error(E);
  4313. return Success(~Result.getInt(), E);
  4314. }
  4315. case UO_LNot: {
  4316. bool bres;
  4317. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  4318. return false;
  4319. return Success(!bres, E);
  4320. }
  4321. }
  4322. }
  4323. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  4324. /// result type is integer.
  4325. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4326. const Expr *SubExpr = E->getSubExpr();
  4327. QualType DestType = E->getType();
  4328. QualType SrcType = SubExpr->getType();
  4329. switch (E->getCastKind()) {
  4330. case CK_BaseToDerived:
  4331. case CK_DerivedToBase:
  4332. case CK_UncheckedDerivedToBase:
  4333. case CK_Dynamic:
  4334. case CK_ToUnion:
  4335. case CK_ArrayToPointerDecay:
  4336. case CK_FunctionToPointerDecay:
  4337. case CK_NullToPointer:
  4338. case CK_NullToMemberPointer:
  4339. case CK_BaseToDerivedMemberPointer:
  4340. case CK_DerivedToBaseMemberPointer:
  4341. case CK_ConstructorConversion:
  4342. case CK_IntegralToPointer:
  4343. case CK_ToVoid:
  4344. case CK_VectorSplat:
  4345. case CK_IntegralToFloating:
  4346. case CK_FloatingCast:
  4347. case CK_CPointerToObjCPointerCast:
  4348. case CK_BlockPointerToObjCPointerCast:
  4349. case CK_AnyPointerToBlockPointerCast:
  4350. case CK_ObjCObjectLValueCast:
  4351. case CK_FloatingRealToComplex:
  4352. case CK_FloatingComplexToReal:
  4353. case CK_FloatingComplexCast:
  4354. case CK_FloatingComplexToIntegralComplex:
  4355. case CK_IntegralRealToComplex:
  4356. case CK_IntegralComplexCast:
  4357. case CK_IntegralComplexToFloatingComplex:
  4358. llvm_unreachable("invalid cast kind for integral value");
  4359. case CK_BitCast:
  4360. case CK_Dependent:
  4361. case CK_LValueBitCast:
  4362. case CK_ARCProduceObject:
  4363. case CK_ARCConsumeObject:
  4364. case CK_ARCReclaimReturnedObject:
  4365. case CK_ARCExtendBlockObject:
  4366. return Error(E);
  4367. case CK_UserDefinedConversion:
  4368. case CK_LValueToRValue:
  4369. case CK_AtomicToNonAtomic:
  4370. case CK_NonAtomicToAtomic:
  4371. case CK_NoOp:
  4372. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4373. case CK_MemberPointerToBoolean:
  4374. case CK_PointerToBoolean:
  4375. case CK_IntegralToBoolean:
  4376. case CK_FloatingToBoolean:
  4377. case CK_FloatingComplexToBoolean:
  4378. case CK_IntegralComplexToBoolean: {
  4379. bool BoolResult;
  4380. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  4381. return false;
  4382. return Success(BoolResult, E);
  4383. }
  4384. case CK_IntegralCast: {
  4385. if (!Visit(SubExpr))
  4386. return false;
  4387. if (!Result.isInt()) {
  4388. // Allow casts of address-of-label differences if they are no-ops
  4389. // or narrowing. (The narrowing case isn't actually guaranteed to
  4390. // be constant-evaluatable except in some narrow cases which are hard
  4391. // to detect here. We let it through on the assumption the user knows
  4392. // what they are doing.)
  4393. if (Result.isAddrLabelDiff())
  4394. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  4395. // Only allow casts of lvalues if they are lossless.
  4396. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  4397. }
  4398. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  4399. Result.getInt()), E);
  4400. }
  4401. case CK_PointerToIntegral: {
  4402. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4403. LValue LV;
  4404. if (!EvaluatePointer(SubExpr, LV, Info))
  4405. return false;
  4406. if (LV.getLValueBase()) {
  4407. // Only allow based lvalue casts if they are lossless.
  4408. // FIXME: Allow a larger integer size than the pointer size, and allow
  4409. // narrowing back down to pointer width in subsequent integral casts.
  4410. // FIXME: Check integer type's active bits, not its type size.
  4411. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  4412. return Error(E);
  4413. LV.Designator.setInvalid();
  4414. LV.moveInto(Result);
  4415. return true;
  4416. }
  4417. APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
  4418. SrcType);
  4419. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  4420. }
  4421. case CK_IntegralComplexToReal: {
  4422. ComplexValue C;
  4423. if (!EvaluateComplex(SubExpr, C, Info))
  4424. return false;
  4425. return Success(C.getComplexIntReal(), E);
  4426. }
  4427. case CK_FloatingToIntegral: {
  4428. APFloat F(0.0);
  4429. if (!EvaluateFloat(SubExpr, F, Info))
  4430. return false;
  4431. APSInt Value;
  4432. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  4433. return false;
  4434. return Success(Value, E);
  4435. }
  4436. }
  4437. llvm_unreachable("unknown cast resulting in integral value");
  4438. }
  4439. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4440. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4441. ComplexValue LV;
  4442. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4443. return false;
  4444. if (!LV.isComplexInt())
  4445. return Error(E);
  4446. return Success(LV.getComplexIntReal(), E);
  4447. }
  4448. return Visit(E->getSubExpr());
  4449. }
  4450. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4451. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  4452. ComplexValue LV;
  4453. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4454. return false;
  4455. if (!LV.isComplexInt())
  4456. return Error(E);
  4457. return Success(LV.getComplexIntImag(), E);
  4458. }
  4459. VisitIgnoredValue(E->getSubExpr());
  4460. return Success(0, E);
  4461. }
  4462. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  4463. return Success(E->getPackLength(), E);
  4464. }
  4465. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  4466. return Success(E->getValue(), E);
  4467. }
  4468. //===----------------------------------------------------------------------===//
  4469. // Float Evaluation
  4470. //===----------------------------------------------------------------------===//
  4471. namespace {
  4472. class FloatExprEvaluator
  4473. : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
  4474. APFloat &Result;
  4475. public:
  4476. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  4477. : ExprEvaluatorBaseTy(info), Result(result) {}
  4478. bool Success(const CCValue &V, const Expr *e) {
  4479. Result = V.getFloat();
  4480. return true;
  4481. }
  4482. bool ZeroInitialization(const Expr *E) {
  4483. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  4484. return true;
  4485. }
  4486. bool VisitCallExpr(const CallExpr *E);
  4487. bool VisitUnaryOperator(const UnaryOperator *E);
  4488. bool VisitBinaryOperator(const BinaryOperator *E);
  4489. bool VisitFloatingLiteral(const FloatingLiteral *E);
  4490. bool VisitCastExpr(const CastExpr *E);
  4491. bool VisitUnaryReal(const UnaryOperator *E);
  4492. bool VisitUnaryImag(const UnaryOperator *E);
  4493. // FIXME: Missing: array subscript of vector, member of vector
  4494. };
  4495. } // end anonymous namespace
  4496. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  4497. assert(E->isRValue() && E->getType()->isRealFloatingType());
  4498. return FloatExprEvaluator(Info, Result).Visit(E);
  4499. }
  4500. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  4501. QualType ResultTy,
  4502. const Expr *Arg,
  4503. bool SNaN,
  4504. llvm::APFloat &Result) {
  4505. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  4506. if (!S) return false;
  4507. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  4508. llvm::APInt fill;
  4509. // Treat empty strings as if they were zero.
  4510. if (S->getString().empty())
  4511. fill = llvm::APInt(32, 0);
  4512. else if (S->getString().getAsInteger(0, fill))
  4513. return false;
  4514. if (SNaN)
  4515. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  4516. else
  4517. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  4518. return true;
  4519. }
  4520. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4521. switch (E->isBuiltinCall()) {
  4522. default:
  4523. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4524. case Builtin::BI__builtin_huge_val:
  4525. case Builtin::BI__builtin_huge_valf:
  4526. case Builtin::BI__builtin_huge_vall:
  4527. case Builtin::BI__builtin_inf:
  4528. case Builtin::BI__builtin_inff:
  4529. case Builtin::BI__builtin_infl: {
  4530. const llvm::fltSemantics &Sem =
  4531. Info.Ctx.getFloatTypeSemantics(E->getType());
  4532. Result = llvm::APFloat::getInf(Sem);
  4533. return true;
  4534. }
  4535. case Builtin::BI__builtin_nans:
  4536. case Builtin::BI__builtin_nansf:
  4537. case Builtin::BI__builtin_nansl:
  4538. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4539. true, Result))
  4540. return Error(E);
  4541. return true;
  4542. case Builtin::BI__builtin_nan:
  4543. case Builtin::BI__builtin_nanf:
  4544. case Builtin::BI__builtin_nanl:
  4545. // If this is __builtin_nan() turn this into a nan, otherwise we
  4546. // can't constant fold it.
  4547. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4548. false, Result))
  4549. return Error(E);
  4550. return true;
  4551. case Builtin::BI__builtin_fabs:
  4552. case Builtin::BI__builtin_fabsf:
  4553. case Builtin::BI__builtin_fabsl:
  4554. if (!EvaluateFloat(E->getArg(0), Result, Info))
  4555. return false;
  4556. if (Result.isNegative())
  4557. Result.changeSign();
  4558. return true;
  4559. case Builtin::BI__builtin_copysign:
  4560. case Builtin::BI__builtin_copysignf:
  4561. case Builtin::BI__builtin_copysignl: {
  4562. APFloat RHS(0.);
  4563. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  4564. !EvaluateFloat(E->getArg(1), RHS, Info))
  4565. return false;
  4566. Result.copySign(RHS);
  4567. return true;
  4568. }
  4569. }
  4570. }
  4571. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4572. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4573. ComplexValue CV;
  4574. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4575. return false;
  4576. Result = CV.FloatReal;
  4577. return true;
  4578. }
  4579. return Visit(E->getSubExpr());
  4580. }
  4581. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4582. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4583. ComplexValue CV;
  4584. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4585. return false;
  4586. Result = CV.FloatImag;
  4587. return true;
  4588. }
  4589. VisitIgnoredValue(E->getSubExpr());
  4590. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  4591. Result = llvm::APFloat::getZero(Sem);
  4592. return true;
  4593. }
  4594. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4595. switch (E->getOpcode()) {
  4596. default: return Error(E);
  4597. case UO_Plus:
  4598. return EvaluateFloat(E->getSubExpr(), Result, Info);
  4599. case UO_Minus:
  4600. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  4601. return false;
  4602. Result.changeSign();
  4603. return true;
  4604. }
  4605. }
  4606. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4607. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  4608. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4609. APFloat RHS(0.0);
  4610. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  4611. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4612. return false;
  4613. if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
  4614. return false;
  4615. switch (E->getOpcode()) {
  4616. default: return Error(E);
  4617. case BO_Mul:
  4618. Result.multiply(RHS, APFloat::rmNearestTiesToEven);
  4619. break;
  4620. case BO_Add:
  4621. Result.add(RHS, APFloat::rmNearestTiesToEven);
  4622. break;
  4623. case BO_Sub:
  4624. Result.subtract(RHS, APFloat::rmNearestTiesToEven);
  4625. break;
  4626. case BO_Div:
  4627. Result.divide(RHS, APFloat::rmNearestTiesToEven);
  4628. break;
  4629. }
  4630. if (Result.isInfinity() || Result.isNaN())
  4631. CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
  4632. return true;
  4633. }
  4634. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  4635. Result = E->getValue();
  4636. return true;
  4637. }
  4638. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4639. const Expr* SubExpr = E->getSubExpr();
  4640. switch (E->getCastKind()) {
  4641. default:
  4642. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4643. case CK_IntegralToFloating: {
  4644. APSInt IntResult;
  4645. return EvaluateInteger(SubExpr, IntResult, Info) &&
  4646. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  4647. E->getType(), Result);
  4648. }
  4649. case CK_FloatingCast: {
  4650. if (!Visit(SubExpr))
  4651. return false;
  4652. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  4653. Result);
  4654. }
  4655. case CK_FloatingComplexToReal: {
  4656. ComplexValue V;
  4657. if (!EvaluateComplex(SubExpr, V, Info))
  4658. return false;
  4659. Result = V.getComplexFloatReal();
  4660. return true;
  4661. }
  4662. }
  4663. }
  4664. //===----------------------------------------------------------------------===//
  4665. // Complex Evaluation (for float and integer)
  4666. //===----------------------------------------------------------------------===//
  4667. namespace {
  4668. class ComplexExprEvaluator
  4669. : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
  4670. ComplexValue &Result;
  4671. public:
  4672. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  4673. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4674. bool Success(const CCValue &V, const Expr *e) {
  4675. Result.setFrom(V);
  4676. return true;
  4677. }
  4678. bool ZeroInitialization(const Expr *E);
  4679. //===--------------------------------------------------------------------===//
  4680. // Visitor Methods
  4681. //===--------------------------------------------------------------------===//
  4682. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  4683. bool VisitCastExpr(const CastExpr *E);
  4684. bool VisitBinaryOperator(const BinaryOperator *E);
  4685. bool VisitUnaryOperator(const UnaryOperator *E);
  4686. bool VisitInitListExpr(const InitListExpr *E);
  4687. };
  4688. } // end anonymous namespace
  4689. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  4690. EvalInfo &Info) {
  4691. assert(E->isRValue() && E->getType()->isAnyComplexType());
  4692. return ComplexExprEvaluator(Info, Result).Visit(E);
  4693. }
  4694. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  4695. QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
  4696. if (ElemTy->isRealFloatingType()) {
  4697. Result.makeComplexFloat();
  4698. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  4699. Result.FloatReal = Zero;
  4700. Result.FloatImag = Zero;
  4701. } else {
  4702. Result.makeComplexInt();
  4703. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  4704. Result.IntReal = Zero;
  4705. Result.IntImag = Zero;
  4706. }
  4707. return true;
  4708. }
  4709. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  4710. const Expr* SubExpr = E->getSubExpr();
  4711. if (SubExpr->getType()->isRealFloatingType()) {
  4712. Result.makeComplexFloat();
  4713. APFloat &Imag = Result.FloatImag;
  4714. if (!EvaluateFloat(SubExpr, Imag, Info))
  4715. return false;
  4716. Result.FloatReal = APFloat(Imag.getSemantics());
  4717. return true;
  4718. } else {
  4719. assert(SubExpr->getType()->isIntegerType() &&
  4720. "Unexpected imaginary literal.");
  4721. Result.makeComplexInt();
  4722. APSInt &Imag = Result.IntImag;
  4723. if (!EvaluateInteger(SubExpr, Imag, Info))
  4724. return false;
  4725. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  4726. return true;
  4727. }
  4728. }
  4729. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4730. switch (E->getCastKind()) {
  4731. case CK_BitCast:
  4732. case CK_BaseToDerived:
  4733. case CK_DerivedToBase:
  4734. case CK_UncheckedDerivedToBase:
  4735. case CK_Dynamic:
  4736. case CK_ToUnion:
  4737. case CK_ArrayToPointerDecay:
  4738. case CK_FunctionToPointerDecay:
  4739. case CK_NullToPointer:
  4740. case CK_NullToMemberPointer:
  4741. case CK_BaseToDerivedMemberPointer:
  4742. case CK_DerivedToBaseMemberPointer:
  4743. case CK_MemberPointerToBoolean:
  4744. case CK_ConstructorConversion:
  4745. case CK_IntegralToPointer:
  4746. case CK_PointerToIntegral:
  4747. case CK_PointerToBoolean:
  4748. case CK_ToVoid:
  4749. case CK_VectorSplat:
  4750. case CK_IntegralCast:
  4751. case CK_IntegralToBoolean:
  4752. case CK_IntegralToFloating:
  4753. case CK_FloatingToIntegral:
  4754. case CK_FloatingToBoolean:
  4755. case CK_FloatingCast:
  4756. case CK_CPointerToObjCPointerCast:
  4757. case CK_BlockPointerToObjCPointerCast:
  4758. case CK_AnyPointerToBlockPointerCast:
  4759. case CK_ObjCObjectLValueCast:
  4760. case CK_FloatingComplexToReal:
  4761. case CK_FloatingComplexToBoolean:
  4762. case CK_IntegralComplexToReal:
  4763. case CK_IntegralComplexToBoolean:
  4764. case CK_ARCProduceObject:
  4765. case CK_ARCConsumeObject:
  4766. case CK_ARCReclaimReturnedObject:
  4767. case CK_ARCExtendBlockObject:
  4768. llvm_unreachable("invalid cast kind for complex value");
  4769. case CK_LValueToRValue:
  4770. case CK_AtomicToNonAtomic:
  4771. case CK_NonAtomicToAtomic:
  4772. case CK_NoOp:
  4773. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4774. case CK_Dependent:
  4775. case CK_LValueBitCast:
  4776. case CK_UserDefinedConversion:
  4777. return Error(E);
  4778. case CK_FloatingRealToComplex: {
  4779. APFloat &Real = Result.FloatReal;
  4780. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  4781. return false;
  4782. Result.makeComplexFloat();
  4783. Result.FloatImag = APFloat(Real.getSemantics());
  4784. return true;
  4785. }
  4786. case CK_FloatingComplexCast: {
  4787. if (!Visit(E->getSubExpr()))
  4788. return false;
  4789. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4790. QualType From
  4791. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4792. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  4793. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  4794. }
  4795. case CK_FloatingComplexToIntegralComplex: {
  4796. if (!Visit(E->getSubExpr()))
  4797. return false;
  4798. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4799. QualType From
  4800. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4801. Result.makeComplexInt();
  4802. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  4803. To, Result.IntReal) &&
  4804. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  4805. To, Result.IntImag);
  4806. }
  4807. case CK_IntegralRealToComplex: {
  4808. APSInt &Real = Result.IntReal;
  4809. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  4810. return false;
  4811. Result.makeComplexInt();
  4812. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  4813. return true;
  4814. }
  4815. case CK_IntegralComplexCast: {
  4816. if (!Visit(E->getSubExpr()))
  4817. return false;
  4818. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4819. QualType From
  4820. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4821. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  4822. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  4823. return true;
  4824. }
  4825. case CK_IntegralComplexToFloatingComplex: {
  4826. if (!Visit(E->getSubExpr()))
  4827. return false;
  4828. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4829. QualType From
  4830. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4831. Result.makeComplexFloat();
  4832. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  4833. To, Result.FloatReal) &&
  4834. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  4835. To, Result.FloatImag);
  4836. }
  4837. }
  4838. llvm_unreachable("unknown cast resulting in complex value");
  4839. }
  4840. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4841. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  4842. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4843. bool LHSOK = Visit(E->getLHS());
  4844. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4845. return false;
  4846. ComplexValue RHS;
  4847. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  4848. return false;
  4849. assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
  4850. "Invalid operands to binary operator.");
  4851. switch (E->getOpcode()) {
  4852. default: return Error(E);
  4853. case BO_Add:
  4854. if (Result.isComplexFloat()) {
  4855. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  4856. APFloat::rmNearestTiesToEven);
  4857. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  4858. APFloat::rmNearestTiesToEven);
  4859. } else {
  4860. Result.getComplexIntReal() += RHS.getComplexIntReal();
  4861. Result.getComplexIntImag() += RHS.getComplexIntImag();
  4862. }
  4863. break;
  4864. case BO_Sub:
  4865. if (Result.isComplexFloat()) {
  4866. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  4867. APFloat::rmNearestTiesToEven);
  4868. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  4869. APFloat::rmNearestTiesToEven);
  4870. } else {
  4871. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  4872. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  4873. }
  4874. break;
  4875. case BO_Mul:
  4876. if (Result.isComplexFloat()) {
  4877. ComplexValue LHS = Result;
  4878. APFloat &LHS_r = LHS.getComplexFloatReal();
  4879. APFloat &LHS_i = LHS.getComplexFloatImag();
  4880. APFloat &RHS_r = RHS.getComplexFloatReal();
  4881. APFloat &RHS_i = RHS.getComplexFloatImag();
  4882. APFloat Tmp = LHS_r;
  4883. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  4884. Result.getComplexFloatReal() = Tmp;
  4885. Tmp = LHS_i;
  4886. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  4887. Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
  4888. Tmp = LHS_r;
  4889. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  4890. Result.getComplexFloatImag() = Tmp;
  4891. Tmp = LHS_i;
  4892. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  4893. Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
  4894. } else {
  4895. ComplexValue LHS = Result;
  4896. Result.getComplexIntReal() =
  4897. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  4898. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  4899. Result.getComplexIntImag() =
  4900. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  4901. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  4902. }
  4903. break;
  4904. case BO_Div:
  4905. if (Result.isComplexFloat()) {
  4906. ComplexValue LHS = Result;
  4907. APFloat &LHS_r = LHS.getComplexFloatReal();
  4908. APFloat &LHS_i = LHS.getComplexFloatImag();
  4909. APFloat &RHS_r = RHS.getComplexFloatReal();
  4910. APFloat &RHS_i = RHS.getComplexFloatImag();
  4911. APFloat &Res_r = Result.getComplexFloatReal();
  4912. APFloat &Res_i = Result.getComplexFloatImag();
  4913. APFloat Den = RHS_r;
  4914. Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  4915. APFloat Tmp = RHS_i;
  4916. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  4917. Den.add(Tmp, APFloat::rmNearestTiesToEven);
  4918. Res_r = LHS_r;
  4919. Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  4920. Tmp = LHS_i;
  4921. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  4922. Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
  4923. Res_r.divide(Den, APFloat::rmNearestTiesToEven);
  4924. Res_i = LHS_i;
  4925. Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  4926. Tmp = LHS_r;
  4927. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  4928. Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
  4929. Res_i.divide(Den, APFloat::rmNearestTiesToEven);
  4930. } else {
  4931. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  4932. return Error(E, diag::note_expr_divide_by_zero);
  4933. ComplexValue LHS = Result;
  4934. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  4935. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  4936. Result.getComplexIntReal() =
  4937. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  4938. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  4939. Result.getComplexIntImag() =
  4940. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  4941. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  4942. }
  4943. break;
  4944. }
  4945. return true;
  4946. }
  4947. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4948. // Get the operand value into 'Result'.
  4949. if (!Visit(E->getSubExpr()))
  4950. return false;
  4951. switch (E->getOpcode()) {
  4952. default:
  4953. return Error(E);
  4954. case UO_Extension:
  4955. return true;
  4956. case UO_Plus:
  4957. // The result is always just the subexpr.
  4958. return true;
  4959. case UO_Minus:
  4960. if (Result.isComplexFloat()) {
  4961. Result.getComplexFloatReal().changeSign();
  4962. Result.getComplexFloatImag().changeSign();
  4963. }
  4964. else {
  4965. Result.getComplexIntReal() = -Result.getComplexIntReal();
  4966. Result.getComplexIntImag() = -Result.getComplexIntImag();
  4967. }
  4968. return true;
  4969. case UO_Not:
  4970. if (Result.isComplexFloat())
  4971. Result.getComplexFloatImag().changeSign();
  4972. else
  4973. Result.getComplexIntImag() = -Result.getComplexIntImag();
  4974. return true;
  4975. }
  4976. }
  4977. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  4978. if (E->getNumInits() == 2) {
  4979. if (E->getType()->isComplexType()) {
  4980. Result.makeComplexFloat();
  4981. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  4982. return false;
  4983. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  4984. return false;
  4985. } else {
  4986. Result.makeComplexInt();
  4987. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  4988. return false;
  4989. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  4990. return false;
  4991. }
  4992. return true;
  4993. }
  4994. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  4995. }
  4996. //===----------------------------------------------------------------------===//
  4997. // Void expression evaluation, primarily for a cast to void on the LHS of a
  4998. // comma operator
  4999. //===----------------------------------------------------------------------===//
  5000. namespace {
  5001. class VoidExprEvaluator
  5002. : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
  5003. public:
  5004. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  5005. bool Success(const CCValue &V, const Expr *e) { return true; }
  5006. bool VisitCastExpr(const CastExpr *E) {
  5007. switch (E->getCastKind()) {
  5008. default:
  5009. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5010. case CK_ToVoid:
  5011. VisitIgnoredValue(E->getSubExpr());
  5012. return true;
  5013. }
  5014. }
  5015. };
  5016. } // end anonymous namespace
  5017. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  5018. assert(E->isRValue() && E->getType()->isVoidType());
  5019. return VoidExprEvaluator(Info).Visit(E);
  5020. }
  5021. //===----------------------------------------------------------------------===//
  5022. // Top level Expr::EvaluateAsRValue method.
  5023. //===----------------------------------------------------------------------===//
  5024. static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
  5025. // In C, function designators are not lvalues, but we evaluate them as if they
  5026. // are.
  5027. if (E->isGLValue() || E->getType()->isFunctionType()) {
  5028. LValue LV;
  5029. if (!EvaluateLValue(E, LV, Info))
  5030. return false;
  5031. LV.moveInto(Result);
  5032. } else if (E->getType()->isVectorType()) {
  5033. if (!EvaluateVector(E, Result, Info))
  5034. return false;
  5035. } else if (E->getType()->isIntegralOrEnumerationType()) {
  5036. if (!IntExprEvaluator(Info, Result).Visit(E))
  5037. return false;
  5038. } else if (E->getType()->hasPointerRepresentation()) {
  5039. LValue LV;
  5040. if (!EvaluatePointer(E, LV, Info))
  5041. return false;
  5042. LV.moveInto(Result);
  5043. } else if (E->getType()->isRealFloatingType()) {
  5044. llvm::APFloat F(0.0);
  5045. if (!EvaluateFloat(E, F, Info))
  5046. return false;
  5047. Result = CCValue(F);
  5048. } else if (E->getType()->isAnyComplexType()) {
  5049. ComplexValue C;
  5050. if (!EvaluateComplex(E, C, Info))
  5051. return false;
  5052. C.moveInto(Result);
  5053. } else if (E->getType()->isMemberPointerType()) {
  5054. MemberPtr P;
  5055. if (!EvaluateMemberPointer(E, P, Info))
  5056. return false;
  5057. P.moveInto(Result);
  5058. return true;
  5059. } else if (E->getType()->isArrayType()) {
  5060. LValue LV;
  5061. LV.set(E, Info.CurrentCall);
  5062. if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5063. return false;
  5064. Result = Info.CurrentCall->Temporaries[E];
  5065. } else if (E->getType()->isRecordType()) {
  5066. LValue LV;
  5067. LV.set(E, Info.CurrentCall);
  5068. if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5069. return false;
  5070. Result = Info.CurrentCall->Temporaries[E];
  5071. } else if (E->getType()->isVoidType()) {
  5072. if (Info.getLangOpts().CPlusPlus0x)
  5073. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
  5074. << E->getType();
  5075. else
  5076. Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  5077. if (!EvaluateVoid(E, Info))
  5078. return false;
  5079. } else if (Info.getLangOpts().CPlusPlus0x) {
  5080. Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
  5081. return false;
  5082. } else {
  5083. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  5084. return false;
  5085. }
  5086. return true;
  5087. }
  5088. /// EvaluateConstantExpression - Evaluate an expression as a constant expression
  5089. /// in-place in an APValue. In some cases, the in-place evaluation is essential,
  5090. /// since later initializers for an object can indirectly refer to subobjects
  5091. /// which were initialized earlier.
  5092. static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
  5093. const LValue &This, const Expr *E,
  5094. CheckConstantExpressionKind CCEK) {
  5095. if (!CheckLiteralType(Info, E))
  5096. return false;
  5097. if (E->isRValue()) {
  5098. // Evaluate arrays and record types in-place, so that later initializers can
  5099. // refer to earlier-initialized members of the object.
  5100. if (E->getType()->isArrayType())
  5101. return EvaluateArray(E, This, Result, Info);
  5102. else if (E->getType()->isRecordType())
  5103. return EvaluateRecord(E, This, Result, Info);
  5104. }
  5105. // For any other type, in-place evaluation is unimportant.
  5106. CCValue CoreConstResult;
  5107. return Evaluate(CoreConstResult, Info, E) &&
  5108. CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
  5109. }
  5110. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  5111. /// lvalue-to-rvalue cast if it is an lvalue.
  5112. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  5113. if (!CheckLiteralType(Info, E))
  5114. return false;
  5115. CCValue Value;
  5116. if (!::Evaluate(Value, Info, E))
  5117. return false;
  5118. if (E->isGLValue()) {
  5119. LValue LV;
  5120. LV.setFrom(Value);
  5121. if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
  5122. return false;
  5123. }
  5124. // Check this core constant expression is a constant expression, and if so,
  5125. // convert it to one.
  5126. return CheckConstantExpression(Info, E, Value, Result);
  5127. }
  5128. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  5129. /// any crazy technique (that has nothing to do with language standards) that
  5130. /// we want to. If this function returns true, it returns the folded constant
  5131. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  5132. /// will be applied to the result.
  5133. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  5134. // Fast-path evaluations of integer literals, since we sometimes see files
  5135. // containing vast quantities of these.
  5136. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
  5137. Result.Val = APValue(APSInt(L->getValue(),
  5138. L->getType()->isUnsignedIntegerType()));
  5139. return true;
  5140. }
  5141. // FIXME: Evaluating values of large array and record types can cause
  5142. // performance problems. Only do so in C++11 for now.
  5143. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5144. !Ctx.getLangOptions().CPlusPlus0x)
  5145. return false;
  5146. EvalInfo Info(Ctx, Result);
  5147. return ::EvaluateAsRValue(Info, this, Result.Val);
  5148. }
  5149. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  5150. const ASTContext &Ctx) const {
  5151. EvalResult Scratch;
  5152. return EvaluateAsRValue(Scratch, Ctx) &&
  5153. HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
  5154. Scratch.Val, CCValue::GlobalValue()),
  5155. Result);
  5156. }
  5157. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  5158. SideEffectsKind AllowSideEffects) const {
  5159. if (!getType()->isIntegralOrEnumerationType())
  5160. return false;
  5161. EvalResult ExprResult;
  5162. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  5163. (!AllowSideEffects && ExprResult.HasSideEffects))
  5164. return false;
  5165. Result = ExprResult.Val.getInt();
  5166. return true;
  5167. }
  5168. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  5169. EvalInfo Info(Ctx, Result);
  5170. LValue LV;
  5171. return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
  5172. CheckLValueConstantExpression(Info, this, LV, Result.Val,
  5173. CCEK_Constant);
  5174. }
  5175. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  5176. const VarDecl *VD,
  5177. llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  5178. // FIXME: Evaluating initializers for large array and record types can cause
  5179. // performance problems. Only do so in C++11 for now.
  5180. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5181. !Ctx.getLangOptions().CPlusPlus0x)
  5182. return false;
  5183. Expr::EvalStatus EStatus;
  5184. EStatus.Diag = &Notes;
  5185. EvalInfo InitInfo(Ctx, EStatus);
  5186. InitInfo.setEvaluatingDecl(VD, Value);
  5187. if (!CheckLiteralType(InitInfo, this))
  5188. return false;
  5189. LValue LVal;
  5190. LVal.set(VD);
  5191. // C++11 [basic.start.init]p2:
  5192. // Variables with static storage duration or thread storage duration shall be
  5193. // zero-initialized before any other initialization takes place.
  5194. // This behavior is not present in C.
  5195. if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
  5196. !VD->getType()->isReferenceType()) {
  5197. ImplicitValueInitExpr VIE(VD->getType());
  5198. if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
  5199. return false;
  5200. }
  5201. return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
  5202. !EStatus.HasSideEffects;
  5203. }
  5204. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  5205. /// constant folded, but discard the result.
  5206. bool Expr::isEvaluatable(const ASTContext &Ctx) const {
  5207. EvalResult Result;
  5208. return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
  5209. }
  5210. bool Expr::HasSideEffects(const ASTContext &Ctx) const {
  5211. return HasSideEffect(Ctx).Visit(this);
  5212. }
  5213. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
  5214. EvalResult EvalResult;
  5215. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  5216. (void)Result;
  5217. assert(Result && "Could not evaluate expression");
  5218. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  5219. return EvalResult.Val.getInt();
  5220. }
  5221. bool Expr::EvalResult::isGlobalLValue() const {
  5222. assert(Val.isLValue());
  5223. return IsGlobalLValue(Val.getLValueBase());
  5224. }
  5225. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  5226. /// an integer constant expression.
  5227. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  5228. /// comma, etc
  5229. ///
  5230. /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
  5231. /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
  5232. /// cast+dereference.
  5233. // CheckICE - This function does the fundamental ICE checking: the returned
  5234. // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
  5235. // Note that to reduce code duplication, this helper does no evaluation
  5236. // itself; the caller checks whether the expression is evaluatable, and
  5237. // in the rare cases where CheckICE actually cares about the evaluated
  5238. // value, it calls into Evalute.
  5239. //
  5240. // Meanings of Val:
  5241. // 0: This expression is an ICE.
  5242. // 1: This expression is not an ICE, but if it isn't evaluated, it's
  5243. // a legal subexpression for an ICE. This return value is used to handle
  5244. // the comma operator in C99 mode.
  5245. // 2: This expression is not an ICE, and is not a legal subexpression for one.
  5246. namespace {
  5247. struct ICEDiag {
  5248. unsigned Val;
  5249. SourceLocation Loc;
  5250. public:
  5251. ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
  5252. ICEDiag() : Val(0) {}
  5253. };
  5254. }
  5255. static ICEDiag NoDiag() { return ICEDiag(); }
  5256. static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
  5257. Expr::EvalResult EVResult;
  5258. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  5259. !EVResult.Val.isInt()) {
  5260. return ICEDiag(2, E->getLocStart());
  5261. }
  5262. return NoDiag();
  5263. }
  5264. static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
  5265. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  5266. if (!E->getType()->isIntegralOrEnumerationType()) {
  5267. return ICEDiag(2, E->getLocStart());
  5268. }
  5269. switch (E->getStmtClass()) {
  5270. #define ABSTRACT_STMT(Node)
  5271. #define STMT(Node, Base) case Expr::Node##Class:
  5272. #define EXPR(Node, Base)
  5273. #include "clang/AST/StmtNodes.inc"
  5274. case Expr::PredefinedExprClass:
  5275. case Expr::FloatingLiteralClass:
  5276. case Expr::ImaginaryLiteralClass:
  5277. case Expr::StringLiteralClass:
  5278. case Expr::ArraySubscriptExprClass:
  5279. case Expr::MemberExprClass:
  5280. case Expr::CompoundAssignOperatorClass:
  5281. case Expr::CompoundLiteralExprClass:
  5282. case Expr::ExtVectorElementExprClass:
  5283. case Expr::DesignatedInitExprClass:
  5284. case Expr::ImplicitValueInitExprClass:
  5285. case Expr::ParenListExprClass:
  5286. case Expr::VAArgExprClass:
  5287. case Expr::AddrLabelExprClass:
  5288. case Expr::StmtExprClass:
  5289. case Expr::CXXMemberCallExprClass:
  5290. case Expr::CUDAKernelCallExprClass:
  5291. case Expr::CXXDynamicCastExprClass:
  5292. case Expr::CXXTypeidExprClass:
  5293. case Expr::CXXUuidofExprClass:
  5294. case Expr::CXXNullPtrLiteralExprClass:
  5295. case Expr::CXXThisExprClass:
  5296. case Expr::CXXThrowExprClass:
  5297. case Expr::CXXNewExprClass:
  5298. case Expr::CXXDeleteExprClass:
  5299. case Expr::CXXPseudoDestructorExprClass:
  5300. case Expr::UnresolvedLookupExprClass:
  5301. case Expr::DependentScopeDeclRefExprClass:
  5302. case Expr::CXXConstructExprClass:
  5303. case Expr::CXXBindTemporaryExprClass:
  5304. case Expr::ExprWithCleanupsClass:
  5305. case Expr::CXXTemporaryObjectExprClass:
  5306. case Expr::CXXUnresolvedConstructExprClass:
  5307. case Expr::CXXDependentScopeMemberExprClass:
  5308. case Expr::UnresolvedMemberExprClass:
  5309. case Expr::ObjCStringLiteralClass:
  5310. case Expr::ObjCEncodeExprClass:
  5311. case Expr::ObjCMessageExprClass:
  5312. case Expr::ObjCSelectorExprClass:
  5313. case Expr::ObjCProtocolExprClass:
  5314. case Expr::ObjCIvarRefExprClass:
  5315. case Expr::ObjCPropertyRefExprClass:
  5316. case Expr::ObjCIsaExprClass:
  5317. case Expr::ShuffleVectorExprClass:
  5318. case Expr::BlockExprClass:
  5319. case Expr::BlockDeclRefExprClass:
  5320. case Expr::NoStmtClass:
  5321. case Expr::OpaqueValueExprClass:
  5322. case Expr::PackExpansionExprClass:
  5323. case Expr::SubstNonTypeTemplateParmPackExprClass:
  5324. case Expr::AsTypeExprClass:
  5325. case Expr::ObjCIndirectCopyRestoreExprClass:
  5326. case Expr::MaterializeTemporaryExprClass:
  5327. case Expr::PseudoObjectExprClass:
  5328. case Expr::AtomicExprClass:
  5329. case Expr::InitListExprClass:
  5330. return ICEDiag(2, E->getLocStart());
  5331. case Expr::SizeOfPackExprClass:
  5332. case Expr::GNUNullExprClass:
  5333. // GCC considers the GNU __null value to be an integral constant expression.
  5334. return NoDiag();
  5335. case Expr::SubstNonTypeTemplateParmExprClass:
  5336. return
  5337. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  5338. case Expr::ParenExprClass:
  5339. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  5340. case Expr::GenericSelectionExprClass:
  5341. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  5342. case Expr::IntegerLiteralClass:
  5343. case Expr::CharacterLiteralClass:
  5344. case Expr::CXXBoolLiteralExprClass:
  5345. case Expr::CXXScalarValueInitExprClass:
  5346. case Expr::UnaryTypeTraitExprClass:
  5347. case Expr::BinaryTypeTraitExprClass:
  5348. case Expr::ArrayTypeTraitExprClass:
  5349. case Expr::ExpressionTraitExprClass:
  5350. case Expr::CXXNoexceptExprClass:
  5351. return NoDiag();
  5352. case Expr::CallExprClass:
  5353. case Expr::CXXOperatorCallExprClass: {
  5354. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  5355. // constant expressions, but they can never be ICEs because an ICE cannot
  5356. // contain an operand of (pointer to) function type.
  5357. const CallExpr *CE = cast<CallExpr>(E);
  5358. if (CE->isBuiltinCall())
  5359. return CheckEvalInICE(E, Ctx);
  5360. return ICEDiag(2, E->getLocStart());
  5361. }
  5362. case Expr::DeclRefExprClass:
  5363. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  5364. return NoDiag();
  5365. if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
  5366. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  5367. // Parameter variables are never constants. Without this check,
  5368. // getAnyInitializer() can find a default argument, which leads
  5369. // to chaos.
  5370. if (isa<ParmVarDecl>(D))
  5371. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5372. // C++ 7.1.5.1p2
  5373. // A variable of non-volatile const-qualified integral or enumeration
  5374. // type initialized by an ICE can be used in ICEs.
  5375. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  5376. if (!Dcl->getType()->isIntegralOrEnumerationType())
  5377. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5378. const VarDecl *VD;
  5379. // Look for a declaration of this variable that has an initializer, and
  5380. // check whether it is an ICE.
  5381. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  5382. return NoDiag();
  5383. else
  5384. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5385. }
  5386. }
  5387. return ICEDiag(2, E->getLocStart());
  5388. case Expr::UnaryOperatorClass: {
  5389. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  5390. switch (Exp->getOpcode()) {
  5391. case UO_PostInc:
  5392. case UO_PostDec:
  5393. case UO_PreInc:
  5394. case UO_PreDec:
  5395. case UO_AddrOf:
  5396. case UO_Deref:
  5397. // C99 6.6/3 allows increment and decrement within unevaluated
  5398. // subexpressions of constant expressions, but they can never be ICEs
  5399. // because an ICE cannot contain an lvalue operand.
  5400. return ICEDiag(2, E->getLocStart());
  5401. case UO_Extension:
  5402. case UO_LNot:
  5403. case UO_Plus:
  5404. case UO_Minus:
  5405. case UO_Not:
  5406. case UO_Real:
  5407. case UO_Imag:
  5408. return CheckICE(Exp->getSubExpr(), Ctx);
  5409. }
  5410. // OffsetOf falls through here.
  5411. }
  5412. case Expr::OffsetOfExprClass: {
  5413. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  5414. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  5415. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  5416. // compliance: we should warn earlier for offsetof expressions with
  5417. // array subscripts that aren't ICEs, and if the array subscripts
  5418. // are ICEs, the value of the offsetof must be an integer constant.
  5419. return CheckEvalInICE(E, Ctx);
  5420. }
  5421. case Expr::UnaryExprOrTypeTraitExprClass: {
  5422. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  5423. if ((Exp->getKind() == UETT_SizeOf) &&
  5424. Exp->getTypeOfArgument()->isVariableArrayType())
  5425. return ICEDiag(2, E->getLocStart());
  5426. return NoDiag();
  5427. }
  5428. case Expr::BinaryOperatorClass: {
  5429. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  5430. switch (Exp->getOpcode()) {
  5431. case BO_PtrMemD:
  5432. case BO_PtrMemI:
  5433. case BO_Assign:
  5434. case BO_MulAssign:
  5435. case BO_DivAssign:
  5436. case BO_RemAssign:
  5437. case BO_AddAssign:
  5438. case BO_SubAssign:
  5439. case BO_ShlAssign:
  5440. case BO_ShrAssign:
  5441. case BO_AndAssign:
  5442. case BO_XorAssign:
  5443. case BO_OrAssign:
  5444. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  5445. // constant expressions, but they can never be ICEs because an ICE cannot
  5446. // contain an lvalue operand.
  5447. return ICEDiag(2, E->getLocStart());
  5448. case BO_Mul:
  5449. case BO_Div:
  5450. case BO_Rem:
  5451. case BO_Add:
  5452. case BO_Sub:
  5453. case BO_Shl:
  5454. case BO_Shr:
  5455. case BO_LT:
  5456. case BO_GT:
  5457. case BO_LE:
  5458. case BO_GE:
  5459. case BO_EQ:
  5460. case BO_NE:
  5461. case BO_And:
  5462. case BO_Xor:
  5463. case BO_Or:
  5464. case BO_Comma: {
  5465. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5466. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5467. if (Exp->getOpcode() == BO_Div ||
  5468. Exp->getOpcode() == BO_Rem) {
  5469. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  5470. // we don't evaluate one.
  5471. if (LHSResult.Val == 0 && RHSResult.Val == 0) {
  5472. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  5473. if (REval == 0)
  5474. return ICEDiag(1, E->getLocStart());
  5475. if (REval.isSigned() && REval.isAllOnesValue()) {
  5476. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  5477. if (LEval.isMinSignedValue())
  5478. return ICEDiag(1, E->getLocStart());
  5479. }
  5480. }
  5481. }
  5482. if (Exp->getOpcode() == BO_Comma) {
  5483. if (Ctx.getLangOptions().C99) {
  5484. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  5485. // if it isn't evaluated.
  5486. if (LHSResult.Val == 0 && RHSResult.Val == 0)
  5487. return ICEDiag(1, E->getLocStart());
  5488. } else {
  5489. // In both C89 and C++, commas in ICEs are illegal.
  5490. return ICEDiag(2, E->getLocStart());
  5491. }
  5492. }
  5493. if (LHSResult.Val >= RHSResult.Val)
  5494. return LHSResult;
  5495. return RHSResult;
  5496. }
  5497. case BO_LAnd:
  5498. case BO_LOr: {
  5499. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5500. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5501. if (LHSResult.Val == 0 && RHSResult.Val == 1) {
  5502. // Rare case where the RHS has a comma "side-effect"; we need
  5503. // to actually check the condition to see whether the side
  5504. // with the comma is evaluated.
  5505. if ((Exp->getOpcode() == BO_LAnd) !=
  5506. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  5507. return RHSResult;
  5508. return NoDiag();
  5509. }
  5510. if (LHSResult.Val >= RHSResult.Val)
  5511. return LHSResult;
  5512. return RHSResult;
  5513. }
  5514. }
  5515. }
  5516. case Expr::ImplicitCastExprClass:
  5517. case Expr::CStyleCastExprClass:
  5518. case Expr::CXXFunctionalCastExprClass:
  5519. case Expr::CXXStaticCastExprClass:
  5520. case Expr::CXXReinterpretCastExprClass:
  5521. case Expr::CXXConstCastExprClass:
  5522. case Expr::ObjCBridgedCastExprClass: {
  5523. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  5524. if (isa<ExplicitCastExpr>(E)) {
  5525. if (const FloatingLiteral *FL
  5526. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  5527. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  5528. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  5529. APSInt IgnoredVal(DestWidth, !DestSigned);
  5530. bool Ignored;
  5531. // If the value does not fit in the destination type, the behavior is
  5532. // undefined, so we are not required to treat it as a constant
  5533. // expression.
  5534. if (FL->getValue().convertToInteger(IgnoredVal,
  5535. llvm::APFloat::rmTowardZero,
  5536. &Ignored) & APFloat::opInvalidOp)
  5537. return ICEDiag(2, E->getLocStart());
  5538. return NoDiag();
  5539. }
  5540. }
  5541. switch (cast<CastExpr>(E)->getCastKind()) {
  5542. case CK_LValueToRValue:
  5543. case CK_AtomicToNonAtomic:
  5544. case CK_NonAtomicToAtomic:
  5545. case CK_NoOp:
  5546. case CK_IntegralToBoolean:
  5547. case CK_IntegralCast:
  5548. return CheckICE(SubExpr, Ctx);
  5549. default:
  5550. return ICEDiag(2, E->getLocStart());
  5551. }
  5552. }
  5553. case Expr::BinaryConditionalOperatorClass: {
  5554. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  5555. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  5556. if (CommonResult.Val == 2) return CommonResult;
  5557. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5558. if (FalseResult.Val == 2) return FalseResult;
  5559. if (CommonResult.Val == 1) return CommonResult;
  5560. if (FalseResult.Val == 1 &&
  5561. Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
  5562. return FalseResult;
  5563. }
  5564. case Expr::ConditionalOperatorClass: {
  5565. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  5566. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5567. // then only the true side is actually considered in an integer constant
  5568. // expression, and it is fully evaluated. This is an important GNU
  5569. // extension. See GCC PR38377 for discussion.
  5570. if (const CallExpr *CallCE
  5571. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  5572. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  5573. return CheckEvalInICE(E, Ctx);
  5574. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  5575. if (CondResult.Val == 2)
  5576. return CondResult;
  5577. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  5578. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5579. if (TrueResult.Val == 2)
  5580. return TrueResult;
  5581. if (FalseResult.Val == 2)
  5582. return FalseResult;
  5583. if (CondResult.Val == 1)
  5584. return CondResult;
  5585. if (TrueResult.Val == 0 && FalseResult.Val == 0)
  5586. return NoDiag();
  5587. // Rare case where the diagnostics depend on which side is evaluated
  5588. // Note that if we get here, CondResult is 0, and at least one of
  5589. // TrueResult and FalseResult is non-zero.
  5590. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
  5591. return FalseResult;
  5592. }
  5593. return TrueResult;
  5594. }
  5595. case Expr::CXXDefaultArgExprClass:
  5596. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  5597. case Expr::ChooseExprClass: {
  5598. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
  5599. }
  5600. }
  5601. llvm_unreachable("Invalid StmtClass!");
  5602. }
  5603. /// Evaluate an expression as a C++11 integral constant expression.
  5604. static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
  5605. const Expr *E,
  5606. llvm::APSInt *Value,
  5607. SourceLocation *Loc) {
  5608. if (!E->getType()->isIntegralOrEnumerationType()) {
  5609. if (Loc) *Loc = E->getExprLoc();
  5610. return false;
  5611. }
  5612. APValue Result;
  5613. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  5614. return false;
  5615. assert(Result.isInt() && "pointer cast to int is not an ICE");
  5616. if (Value) *Value = Result.getInt();
  5617. return true;
  5618. }
  5619. bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
  5620. if (Ctx.getLangOptions().CPlusPlus0x)
  5621. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
  5622. ICEDiag d = CheckICE(this, Ctx);
  5623. if (d.Val != 0) {
  5624. if (Loc) *Loc = d.Loc;
  5625. return false;
  5626. }
  5627. return true;
  5628. }
  5629. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
  5630. SourceLocation *Loc, bool isEvaluated) const {
  5631. if (Ctx.getLangOptions().CPlusPlus0x)
  5632. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  5633. if (!isIntegerConstantExpr(Ctx, Loc))
  5634. return false;
  5635. if (!EvaluateAsInt(Value, Ctx))
  5636. llvm_unreachable("ICE cannot be evaluated!");
  5637. return true;
  5638. }
  5639. bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
  5640. SourceLocation *Loc) const {
  5641. // We support this checking in C++98 mode in order to diagnose compatibility
  5642. // issues.
  5643. assert(Ctx.getLangOptions().CPlusPlus);
  5644. Expr::EvalStatus Status;
  5645. llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
  5646. Status.Diag = &Diags;
  5647. EvalInfo Info(Ctx, Status);
  5648. APValue Scratch;
  5649. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  5650. if (!Diags.empty()) {
  5651. IsConstExpr = false;
  5652. if (Loc) *Loc = Diags[0].first;
  5653. } else if (!IsConstExpr) {
  5654. // FIXME: This shouldn't happen.
  5655. if (Loc) *Loc = getExprLoc();
  5656. }
  5657. return IsConstExpr;
  5658. }
  5659. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  5660. llvm::SmallVectorImpl<
  5661. PartialDiagnosticAt> &Diags) {
  5662. // FIXME: It would be useful to check constexpr function templates, but at the
  5663. // moment the constant expression evaluator cannot cope with the non-rigorous
  5664. // ASTs which we build for dependent expressions.
  5665. if (FD->isDependentContext())
  5666. return true;
  5667. Expr::EvalStatus Status;
  5668. Status.Diag = &Diags;
  5669. EvalInfo Info(FD->getASTContext(), Status);
  5670. Info.CheckingPotentialConstantExpression = true;
  5671. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5672. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
  5673. // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
  5674. // is a temporary being used as the 'this' pointer.
  5675. LValue This;
  5676. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  5677. This.set(&VIE, Info.CurrentCall);
  5678. APValue Scratch;
  5679. ArrayRef<const Expr*> Args;
  5680. SourceLocation Loc = FD->getLocation();
  5681. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  5682. HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
  5683. } else
  5684. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
  5685. Args, FD->getBody(), Info, Scratch);
  5686. return Diags.empty();
  5687. }