ExprConstant.cpp 331 KB

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