SemaExpr.cpp 562 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  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 semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/ASTMutationListener.h"
  19. #include "clang/AST/CXXInheritance.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/RecursiveASTVisitor.h"
  27. #include "clang/AST/TypeLoc.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaFixItUtils.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/Support/ConvertUTF.h"
  45. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  46. using namespace clang;
  47. using namespace sema;
  48. /// \brief Determine whether the use of this declaration is valid, without
  49. /// emitting diagnostics.
  50. bool Sema::CanUseDecl(NamedDecl *D) {
  51. // See if this is an auto-typed variable whose initializer we are parsing.
  52. if (ParsingInitForAutoVars.count(D))
  53. return false;
  54. // See if this is a deleted function.
  55. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  56. if (FD->isDeleted())
  57. return false;
  58. // If the function has a deduced return type, and we can't deduce it,
  59. // then we can't use it either.
  60. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  61. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  62. return false;
  63. }
  64. // See if this function is unavailable.
  65. if (D->getAvailability() == AR_Unavailable &&
  66. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  67. return false;
  68. return true;
  69. }
  70. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  71. // Warn if this is used but marked unused.
  72. if (D->hasAttr<UnusedAttr>()) {
  73. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  74. if (DC && !DC->hasAttr<UnusedAttr>())
  75. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  76. }
  77. }
  78. static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
  79. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  80. if (!OMD)
  81. return false;
  82. const ObjCInterfaceDecl *OID = OMD->getClassInterface();
  83. if (!OID)
  84. return false;
  85. for (const ObjCCategoryDecl *Cat : OID->visible_categories())
  86. if (ObjCMethodDecl *CatMeth =
  87. Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
  88. if (!CatMeth->hasAttr<AvailabilityAttr>())
  89. return true;
  90. return false;
  91. }
  92. static AvailabilityResult
  93. DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
  94. const ObjCInterfaceDecl *UnknownObjCClass,
  95. bool ObjCPropertyAccess) {
  96. // See if this declaration is unavailable or deprecated.
  97. std::string Message;
  98. AvailabilityResult Result = D->getAvailability(&Message);
  99. // For typedefs, if the typedef declaration appears available look
  100. // to the underlying type to see if it is more restrictive.
  101. while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  102. if (Result == AR_Available) {
  103. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  104. D = TT->getDecl();
  105. Result = D->getAvailability(&Message);
  106. continue;
  107. }
  108. }
  109. break;
  110. }
  111. // Forward class declarations get their attributes from their definition.
  112. if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  113. if (IDecl->getDefinition()) {
  114. D = IDecl->getDefinition();
  115. Result = D->getAvailability(&Message);
  116. }
  117. }
  118. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  119. if (Result == AR_Available) {
  120. const DeclContext *DC = ECD->getDeclContext();
  121. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  122. Result = TheEnumDecl->getAvailability(&Message);
  123. }
  124. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  125. if (Result == AR_Deprecated || Result == AR_Unavailable ||
  126. AR_NotYetIntroduced) {
  127. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  128. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  129. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  130. if (PDeclResult == Result)
  131. ObjCPDecl = PD;
  132. }
  133. }
  134. }
  135. switch (Result) {
  136. case AR_Available:
  137. break;
  138. case AR_Deprecated:
  139. if (S.getCurContextAvailability() != AR_Deprecated)
  140. S.EmitAvailabilityWarning(Sema::AD_Deprecation,
  141. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  142. ObjCPropertyAccess);
  143. break;
  144. case AR_NotYetIntroduced: {
  145. // Don't do this for enums, they can't be redeclared.
  146. if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
  147. break;
  148. bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
  149. // Objective-C method declarations in categories are not modelled as
  150. // redeclarations, so manually look for a redeclaration in a category
  151. // if necessary.
  152. if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
  153. Warn = false;
  154. // In general, D will point to the most recent redeclaration. However,
  155. // for `@class A;` decls, this isn't true -- manually go through the
  156. // redecl chain in that case.
  157. if (Warn && isa<ObjCInterfaceDecl>(D))
  158. for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
  159. Redecl = Redecl->getPreviousDecl())
  160. if (!Redecl->hasAttr<AvailabilityAttr>() ||
  161. Redecl->getAttr<AvailabilityAttr>()->isInherited())
  162. Warn = false;
  163. if (Warn)
  164. S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
  165. UnknownObjCClass, ObjCPDecl,
  166. ObjCPropertyAccess);
  167. break;
  168. }
  169. case AR_Unavailable:
  170. if (S.getCurContextAvailability() != AR_Unavailable)
  171. S.EmitAvailabilityWarning(Sema::AD_Unavailable,
  172. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  173. ObjCPropertyAccess);
  174. break;
  175. }
  176. return Result;
  177. }
  178. /// \brief Emit a note explaining that this function is deleted.
  179. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  180. assert(Decl->isDeleted());
  181. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  182. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  183. // If the method was explicitly defaulted, point at that declaration.
  184. if (!Method->isImplicit())
  185. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  186. // Try to diagnose why this special member function was implicitly
  187. // deleted. This might fail, if that reason no longer applies.
  188. CXXSpecialMember CSM = getSpecialMember(Method);
  189. if (CSM != CXXInvalid)
  190. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  191. return;
  192. }
  193. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
  194. if (CXXConstructorDecl *BaseCD =
  195. const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
  196. Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
  197. if (BaseCD->isDeleted()) {
  198. NoteDeletedFunction(BaseCD);
  199. } else {
  200. // FIXME: An explanation of why exactly it can't be inherited
  201. // would be nice.
  202. Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
  203. }
  204. return;
  205. }
  206. }
  207. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  208. << Decl << true;
  209. }
  210. /// \brief Determine whether a FunctionDecl was ever declared with an
  211. /// explicit storage class.
  212. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  213. for (auto I : D->redecls()) {
  214. if (I->getStorageClass() != SC_None)
  215. return true;
  216. }
  217. return false;
  218. }
  219. /// \brief Check whether we're in an extern inline function and referring to a
  220. /// variable or function with internal linkage (C11 6.7.4p3).
  221. ///
  222. /// This is only a warning because we used to silently accept this code, but
  223. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  224. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  225. /// and so while there may still be user mistakes, most of the time we can't
  226. /// prove that there are errors.
  227. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  228. const NamedDecl *D,
  229. SourceLocation Loc) {
  230. // This is disabled under C++; there are too many ways for this to fire in
  231. // contexts where the warning is a false positive, or where it is technically
  232. // correct but benign.
  233. if (S.getLangOpts().CPlusPlus)
  234. return;
  235. // Check if this is an inlined function or method.
  236. FunctionDecl *Current = S.getCurFunctionDecl();
  237. if (!Current)
  238. return;
  239. if (!Current->isInlined())
  240. return;
  241. if (!Current->isExternallyVisible())
  242. return;
  243. // Check if the decl has internal linkage.
  244. if (D->getFormalLinkage() != InternalLinkage)
  245. return;
  246. // Downgrade from ExtWarn to Extension if
  247. // (1) the supposedly external inline function is in the main file,
  248. // and probably won't be included anywhere else.
  249. // (2) the thing we're referencing is a pure function.
  250. // (3) the thing we're referencing is another inline function.
  251. // This last can give us false negatives, but it's better than warning on
  252. // wrappers for simple C library functions.
  253. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  254. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  255. if (!DowngradeWarning && UsedFn)
  256. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  257. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  258. : diag::ext_internal_in_extern_inline)
  259. << /*IsVar=*/!UsedFn << D;
  260. S.MaybeSuggestAddingStaticToDecl(Current);
  261. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  262. << D;
  263. }
  264. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  265. const FunctionDecl *First = Cur->getFirstDecl();
  266. // Suggest "static" on the function, if possible.
  267. if (!hasAnyExplicitStorageClass(First)) {
  268. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  269. Diag(DeclBegin, diag::note_convert_inline_to_static)
  270. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  271. }
  272. }
  273. /// \brief Determine whether the use of this declaration is valid, and
  274. /// emit any corresponding diagnostics.
  275. ///
  276. /// This routine diagnoses various problems with referencing
  277. /// declarations that can occur when using a declaration. For example,
  278. /// it might warn if a deprecated or unavailable declaration is being
  279. /// used, or produce an error (and return true) if a C++0x deleted
  280. /// function is being used.
  281. ///
  282. /// \returns true if there was an error (this declaration cannot be
  283. /// referenced), false otherwise.
  284. ///
  285. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  286. const ObjCInterfaceDecl *UnknownObjCClass,
  287. bool ObjCPropertyAccess) {
  288. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  289. // If there were any diagnostics suppressed by template argument deduction,
  290. // emit them now.
  291. SuppressedDiagnosticsMap::iterator
  292. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  293. if (Pos != SuppressedDiagnostics.end()) {
  294. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  295. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  296. Diag(Suppressed[I].first, Suppressed[I].second);
  297. // Clear out the list of suppressed diagnostics, so that we don't emit
  298. // them again for this specialization. However, we don't obsolete this
  299. // entry from the table, because we want to avoid ever emitting these
  300. // diagnostics again.
  301. Suppressed.clear();
  302. }
  303. // C++ [basic.start.main]p3:
  304. // The function 'main' shall not be used within a program.
  305. if (cast<FunctionDecl>(D)->isMain())
  306. Diag(Loc, diag::ext_main_used);
  307. }
  308. // See if this is an auto-typed variable whose initializer we are parsing.
  309. if (ParsingInitForAutoVars.count(D)) {
  310. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  311. << D->getDeclName();
  312. return true;
  313. }
  314. // See if this is a deleted function.
  315. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  316. if (FD->isDeleted()) {
  317. Diag(Loc, diag::err_deleted_function_use);
  318. NoteDeletedFunction(FD);
  319. return true;
  320. }
  321. // If the function has a deduced return type, and we can't deduce it,
  322. // then we can't use it either.
  323. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  324. DeduceReturnType(FD, Loc))
  325. return true;
  326. }
  327. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
  328. ObjCPropertyAccess);
  329. DiagnoseUnusedOfDecl(*this, D, Loc);
  330. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  331. return false;
  332. }
  333. /// \brief Retrieve the message suffix that should be added to a
  334. /// diagnostic complaining about the given function being deleted or
  335. /// unavailable.
  336. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  337. std::string Message;
  338. if (FD->getAvailability(&Message))
  339. return ": " + Message;
  340. return std::string();
  341. }
  342. /// DiagnoseSentinelCalls - This routine checks whether a call or
  343. /// message-send is to a declaration with the sentinel attribute, and
  344. /// if so, it checks that the requirements of the sentinel are
  345. /// satisfied.
  346. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  347. ArrayRef<Expr *> Args) {
  348. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  349. if (!attr)
  350. return;
  351. // The number of formal parameters of the declaration.
  352. unsigned numFormalParams;
  353. // The kind of declaration. This is also an index into a %select in
  354. // the diagnostic.
  355. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  356. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  357. numFormalParams = MD->param_size();
  358. calleeType = CT_Method;
  359. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  360. numFormalParams = FD->param_size();
  361. calleeType = CT_Function;
  362. } else if (isa<VarDecl>(D)) {
  363. QualType type = cast<ValueDecl>(D)->getType();
  364. const FunctionType *fn = nullptr;
  365. if (const PointerType *ptr = type->getAs<PointerType>()) {
  366. fn = ptr->getPointeeType()->getAs<FunctionType>();
  367. if (!fn) return;
  368. calleeType = CT_Function;
  369. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  370. fn = ptr->getPointeeType()->castAs<FunctionType>();
  371. calleeType = CT_Block;
  372. } else {
  373. return;
  374. }
  375. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  376. numFormalParams = proto->getNumParams();
  377. } else {
  378. numFormalParams = 0;
  379. }
  380. } else {
  381. return;
  382. }
  383. // "nullPos" is the number of formal parameters at the end which
  384. // effectively count as part of the variadic arguments. This is
  385. // useful if you would prefer to not have *any* formal parameters,
  386. // but the language forces you to have at least one.
  387. unsigned nullPos = attr->getNullPos();
  388. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  389. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  390. // The number of arguments which should follow the sentinel.
  391. unsigned numArgsAfterSentinel = attr->getSentinel();
  392. // If there aren't enough arguments for all the formal parameters,
  393. // the sentinel, and the args after the sentinel, complain.
  394. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  395. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  396. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  397. return;
  398. }
  399. // Otherwise, find the sentinel expression.
  400. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  401. if (!sentinelExpr) return;
  402. if (sentinelExpr->isValueDependent()) return;
  403. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  404. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  405. // or 'NULL' if those are actually defined in the context. Only use
  406. // 'nil' for ObjC methods, where it's much more likely that the
  407. // variadic arguments form a list of object pointers.
  408. SourceLocation MissingNilLoc
  409. = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
  410. std::string NullValue;
  411. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  412. NullValue = "nil";
  413. else if (getLangOpts().CPlusPlus11)
  414. NullValue = "nullptr";
  415. else if (PP.isMacroDefined("NULL"))
  416. NullValue = "NULL";
  417. else
  418. NullValue = "(void*) 0";
  419. if (MissingNilLoc.isInvalid())
  420. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  421. else
  422. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  423. << int(calleeType)
  424. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  425. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  426. }
  427. SourceRange Sema::getExprRange(Expr *E) const {
  428. return E ? E->getSourceRange() : SourceRange();
  429. }
  430. //===----------------------------------------------------------------------===//
  431. // Standard Promotions and Conversions
  432. //===----------------------------------------------------------------------===//
  433. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  434. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
  435. // Handle any placeholder expressions which made it here.
  436. if (E->getType()->isPlaceholderType()) {
  437. ExprResult result = CheckPlaceholderExpr(E);
  438. if (result.isInvalid()) return ExprError();
  439. E = result.get();
  440. }
  441. QualType Ty = E->getType();
  442. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  443. if (Ty->isFunctionType()) {
  444. // If we are here, we are not calling a function but taking
  445. // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
  446. if (getLangOpts().OpenCL) {
  447. Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
  448. return ExprError();
  449. }
  450. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  451. CK_FunctionToPointerDecay).get();
  452. } else if (Ty->isArrayType() && !getLangOpts().HLSL) { // HLSL Change - HLSL does not have pointers; do not decay arrays
  453. // In C90 mode, arrays only promote to pointers if the array expression is
  454. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  455. // type 'array of type' is converted to an expression that has type 'pointer
  456. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  457. // that has type 'array of type' ...". The relevant change is "an lvalue"
  458. // (C90) to "an expression" (C99).
  459. //
  460. // C++ 4.2p1:
  461. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  462. // T" can be converted to an rvalue of type "pointer to T".
  463. //
  464. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  465. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  466. CK_ArrayToPointerDecay).get();
  467. }
  468. return E;
  469. }
  470. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  471. // Check to see if we are dereferencing a null pointer. If so,
  472. // and if not volatile-qualified, this is undefined behavior that the
  473. // optimizer will delete, so warn about it. People sometimes try to use this
  474. // to get a deterministic trap and are surprised by clang's behavior. This
  475. // only handles the pattern "*null", which is a very syntactic check.
  476. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  477. if (UO->getOpcode() == UO_Deref &&
  478. UO->getSubExpr()->IgnoreParenCasts()->
  479. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  480. !UO->getType().isVolatileQualified()) {
  481. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  482. S.PDiag(diag::warn_indirection_through_null)
  483. << UO->getSubExpr()->getSourceRange());
  484. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  485. S.PDiag(diag::note_indirection_through_null));
  486. }
  487. }
  488. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  489. SourceLocation AssignLoc,
  490. const Expr* RHS) {
  491. const ObjCIvarDecl *IV = OIRE->getDecl();
  492. if (!IV)
  493. return;
  494. DeclarationName MemberName = IV->getDeclName();
  495. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  496. if (!Member || !Member->isStr("isa"))
  497. return;
  498. const Expr *Base = OIRE->getBase();
  499. QualType BaseType = Base->getType();
  500. if (OIRE->isArrow())
  501. BaseType = BaseType->getPointeeType();
  502. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  503. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  504. ObjCInterfaceDecl *ClassDeclared = nullptr;
  505. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  506. if (!ClassDeclared->getSuperClass()
  507. && (*ClassDeclared->ivar_begin()) == IV) {
  508. if (RHS) {
  509. NamedDecl *ObjectSetClass =
  510. S.LookupSingleName(S.TUScope,
  511. &S.Context.Idents.get("object_setClass"),
  512. SourceLocation(), S.LookupOrdinaryName);
  513. if (ObjectSetClass) {
  514. SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
  515. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  516. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  517. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  518. AssignLoc), ",") <<
  519. FixItHint::CreateInsertion(RHSLocEnd, ")");
  520. }
  521. else
  522. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  523. } else {
  524. NamedDecl *ObjectGetClass =
  525. S.LookupSingleName(S.TUScope,
  526. &S.Context.Idents.get("object_getClass"),
  527. SourceLocation(), S.LookupOrdinaryName);
  528. if (ObjectGetClass)
  529. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  530. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  531. FixItHint::CreateReplacement(
  532. SourceRange(OIRE->getOpLoc(),
  533. OIRE->getLocEnd()), ")");
  534. else
  535. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  536. }
  537. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  538. }
  539. }
  540. }
  541. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  542. // Handle any placeholder expressions which made it here.
  543. if (E->getType()->isPlaceholderType()) {
  544. ExprResult result = CheckPlaceholderExpr(E);
  545. if (result.isInvalid()) return ExprError();
  546. E = result.get();
  547. }
  548. // C++ [conv.lval]p1:
  549. // A glvalue of a non-function, non-array type T can be
  550. // converted to a prvalue.
  551. if (!E->isGLValue()) return E;
  552. QualType T = E->getType();
  553. assert(!T.isNull() && "r-value conversion on typeless expression?");
  554. // We don't want to throw lvalue-to-rvalue casts on top of
  555. // expressions of certain types in C++.
  556. if (getLangOpts().CPlusPlus &&
  557. !getLangOpts().HLSL && // HLSL Change - matrices and object types should turn into lvalues
  558. (E->getType() == Context.OverloadTy ||
  559. T->isDependentType() ||
  560. T->isRecordType()))
  561. return E;
  562. // The C standard is actually really unclear on this point, and
  563. // DR106 tells us what the result should be but not why. It's
  564. // generally best to say that void types just doesn't undergo
  565. // lvalue-to-rvalue at all. Note that expressions of unqualified
  566. // 'void' type are never l-values, but qualified void can be.
  567. if (T->isVoidType())
  568. return E;
  569. // OpenCL usually rejects direct accesses to values of 'half' type.
  570. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  571. T->isHalfType()) {
  572. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  573. << 0 << T;
  574. return ExprError();
  575. }
  576. CheckForNullPointerDereference(*this, E);
  577. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  578. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  579. &Context.Idents.get("object_getClass"),
  580. SourceLocation(), LookupOrdinaryName);
  581. if (ObjectGetClass)
  582. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  583. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  584. FixItHint::CreateReplacement(
  585. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  586. else
  587. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  588. }
  589. else if (const ObjCIvarRefExpr *OIRE =
  590. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  591. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  592. // C++ [conv.lval]p1:
  593. // [...] If T is a non-class type, the type of the prvalue is the
  594. // cv-unqualified version of T. Otherwise, the type of the
  595. // rvalue is T.
  596. //
  597. // C99 6.3.2.1p2:
  598. // If the lvalue has qualified type, the value has the unqualified
  599. // version of the type of the lvalue; otherwise, the value has the
  600. // type of the lvalue.
  601. if (T.hasQualifiers())
  602. T = T.getUnqualifiedType();
  603. UpdateMarkingForLValueToRValue(E);
  604. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  605. // balance that.
  606. if (getLangOpts().ObjCAutoRefCount &&
  607. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  608. ExprNeedsCleanups = true;
  609. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  610. nullptr, VK_RValue);
  611. // C11 6.3.2.1p2:
  612. // ... if the lvalue has atomic type, the value has the non-atomic version
  613. // of the type of the lvalue ...
  614. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  615. T = Atomic->getValueType().getUnqualifiedType();
  616. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  617. nullptr, VK_RValue);
  618. }
  619. return Res;
  620. }
  621. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  622. ExprResult Res = DefaultFunctionArrayConversion(E);
  623. if (Res.isInvalid())
  624. return ExprError();
  625. Res = DefaultLvalueConversion(Res.get());
  626. if (Res.isInvalid())
  627. return ExprError();
  628. return Res;
  629. }
  630. /// CallExprUnaryConversions - a special case of an unary conversion
  631. /// performed on a function designator of a call expression.
  632. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  633. QualType Ty = E->getType();
  634. ExprResult Res = E;
  635. // Only do implicit cast for a function type, but not for a pointer
  636. // to function type.
  637. if (Ty->isFunctionType()) {
  638. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  639. CK_FunctionToPointerDecay).get();
  640. if (Res.isInvalid())
  641. return ExprError();
  642. }
  643. Res = DefaultLvalueConversion(Res.get());
  644. if (Res.isInvalid())
  645. return ExprError();
  646. return Res.get();
  647. }
  648. /// UsualUnaryConversions - Performs various conversions that are common to most
  649. /// operators (C99 6.3). The conversions of array and function types are
  650. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  651. /// apply if the array is an argument to the sizeof or address (&) operators.
  652. /// In these instances, this routine should *not* be called.
  653. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  654. // First, convert to an r-value.
  655. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  656. if (Res.isInvalid())
  657. return ExprError();
  658. E = Res.get();
  659. QualType Ty = E->getType();
  660. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  661. // Half FP have to be promoted to float unless it is natively supported
  662. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  663. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  664. // Try to perform integral promotions if the object has a theoretically
  665. // promotable type.
  666. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  667. // C99 6.3.1.1p2:
  668. //
  669. // The following may be used in an expression wherever an int or
  670. // unsigned int may be used:
  671. // - an object or expression with an integer type whose integer
  672. // conversion rank is less than or equal to the rank of int
  673. // and unsigned int.
  674. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  675. //
  676. // If an int can represent all values of the original type, the
  677. // value is converted to an int; otherwise, it is converted to an
  678. // unsigned int. These are called the integer promotions. All
  679. // other types are unchanged by the integer promotions.
  680. QualType PTy = Context.isPromotableBitField(E);
  681. if (!PTy.isNull()) {
  682. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  683. return E;
  684. }
  685. if (Ty->isPromotableIntegerType() && !getLangOpts().HLSL) { // HLSL Change: leave low-precision integrals as such for intermediate operations
  686. QualType PT = Context.getPromotedIntegerType(Ty);
  687. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  688. return E;
  689. }
  690. }
  691. return E;
  692. }
  693. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  694. /// do not have a prototype. Arguments that have type float or __fp16
  695. /// are promoted to double. All other argument types are converted by
  696. /// UsualUnaryConversions().
  697. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  698. QualType Ty = E->getType();
  699. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  700. ExprResult Res = UsualUnaryConversions(E);
  701. if (Res.isInvalid())
  702. return ExprError();
  703. E = Res.get();
  704. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  705. // double.
  706. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  707. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  708. BTy->getKind() == BuiltinType::Float))
  709. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  710. // C++ performs lvalue-to-rvalue conversion as a default argument
  711. // promotion, even on class types, but note:
  712. // C++11 [conv.lval]p2:
  713. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  714. // operand or a subexpression thereof the value contained in the
  715. // referenced object is not accessed. Otherwise, if the glvalue
  716. // has a class type, the conversion copy-initializes a temporary
  717. // of type T from the glvalue and the result of the conversion
  718. // is a prvalue for the temporary.
  719. // FIXME: add some way to gate this entire thing for correctness in
  720. // potentially potentially evaluated contexts.
  721. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  722. ExprResult Temp = PerformCopyInitialization(
  723. InitializedEntity::InitializeTemporary(E->getType()),
  724. E->getExprLoc(), E);
  725. if (Temp.isInvalid())
  726. return ExprError();
  727. E = Temp.get();
  728. }
  729. return E;
  730. }
  731. /// Determine the degree of POD-ness for an expression.
  732. /// Incomplete types are considered POD, since this check can be performed
  733. /// when we're in an unevaluated context.
  734. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  735. if (Ty->isIncompleteType()) {
  736. // C++11 [expr.call]p7:
  737. // After these conversions, if the argument does not have arithmetic,
  738. // enumeration, pointer, pointer to member, or class type, the program
  739. // is ill-formed.
  740. //
  741. // Since we've already performed array-to-pointer and function-to-pointer
  742. // decay, the only such type in C++ is cv void. This also handles
  743. // initializer lists as variadic arguments.
  744. if (Ty->isVoidType())
  745. return VAK_Invalid;
  746. if (Ty->isObjCObjectType())
  747. return VAK_Invalid;
  748. return VAK_Valid;
  749. }
  750. if (Ty.isCXX98PODType(Context))
  751. return VAK_Valid;
  752. // C++11 [expr.call]p7:
  753. // Passing a potentially-evaluated argument of class type (Clause 9)
  754. // having a non-trivial copy constructor, a non-trivial move constructor,
  755. // or a non-trivial destructor, with no corresponding parameter,
  756. // is conditionally-supported with implementation-defined semantics.
  757. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  758. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  759. if (!Record->hasNonTrivialCopyConstructor() &&
  760. !Record->hasNonTrivialMoveConstructor() &&
  761. !Record->hasNonTrivialDestructor())
  762. return VAK_ValidInCXX11;
  763. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  764. return VAK_Valid;
  765. if (Ty->isObjCObjectType())
  766. return VAK_Invalid;
  767. if (getLangOpts().MSVCCompat)
  768. return VAK_MSVCUndefined;
  769. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  770. // permitted to reject them. We should consider doing so.
  771. return VAK_Undefined;
  772. }
  773. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  774. // Don't allow one to pass an Objective-C interface to a vararg.
  775. const QualType &Ty = E->getType();
  776. VarArgKind VAK = isValidVarArgType(Ty);
  777. // Complain about passing non-POD types through varargs.
  778. switch (VAK) {
  779. case VAK_ValidInCXX11:
  780. DiagRuntimeBehavior(
  781. E->getLocStart(), nullptr,
  782. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  783. << Ty << CT);
  784. // Fall through.
  785. case VAK_Valid:
  786. if (Ty->isRecordType()) {
  787. // This is unlikely to be what the user intended. If the class has a
  788. // 'c_str' member function, the user probably meant to call that.
  789. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  790. PDiag(diag::warn_pass_class_arg_to_vararg)
  791. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  792. }
  793. break;
  794. case VAK_Undefined:
  795. case VAK_MSVCUndefined:
  796. DiagRuntimeBehavior(
  797. E->getLocStart(), nullptr,
  798. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  799. << getLangOpts().CPlusPlus11 << Ty << CT);
  800. break;
  801. case VAK_Invalid:
  802. if (Ty->isObjCObjectType())
  803. DiagRuntimeBehavior(
  804. E->getLocStart(), nullptr,
  805. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  806. << Ty << CT);
  807. else
  808. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  809. << isa<InitListExpr>(E) << Ty << CT;
  810. break;
  811. }
  812. }
  813. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  814. /// will create a trap if the resulting type is not a POD type.
  815. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  816. FunctionDecl *FDecl) {
  817. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  818. // Strip the unbridged-cast placeholder expression off, if applicable.
  819. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  820. (CT == VariadicMethod ||
  821. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  822. E = stripARCUnbridgedCast(E);
  823. // Otherwise, do normal placeholder checking.
  824. } else {
  825. ExprResult ExprRes = CheckPlaceholderExpr(E);
  826. if (ExprRes.isInvalid())
  827. return ExprError();
  828. E = ExprRes.get();
  829. }
  830. }
  831. ExprResult ExprRes = DefaultArgumentPromotion(E);
  832. if (ExprRes.isInvalid())
  833. return ExprError();
  834. E = ExprRes.get();
  835. // Diagnostics regarding non-POD argument types are
  836. // emitted along with format string checking in Sema::CheckFunctionCall().
  837. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  838. // Turn this into a trap.
  839. CXXScopeSpec SS;
  840. SourceLocation TemplateKWLoc;
  841. UnqualifiedId Name;
  842. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  843. E->getLocStart());
  844. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  845. Name, true, false);
  846. if (TrapFn.isInvalid())
  847. return ExprError();
  848. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  849. E->getLocStart(), None,
  850. E->getLocEnd());
  851. if (Call.isInvalid())
  852. return ExprError();
  853. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  854. Call.get(), E);
  855. if (Comma.isInvalid())
  856. return ExprError();
  857. return Comma.get();
  858. }
  859. if (!getLangOpts().CPlusPlus &&
  860. RequireCompleteType(E->getExprLoc(), E->getType(),
  861. diag::err_call_incomplete_argument))
  862. return ExprError();
  863. return E;
  864. }
  865. /// \brief Converts an integer to complex float type. Helper function of
  866. /// UsualArithmeticConversions()
  867. ///
  868. /// \return false if the integer expression is an integer type and is
  869. /// successfully converted to the complex type.
  870. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  871. ExprResult &ComplexExpr,
  872. QualType IntTy,
  873. QualType ComplexTy,
  874. bool SkipCast) {
  875. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  876. if (SkipCast) return false;
  877. if (IntTy->isIntegerType()) {
  878. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  879. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  880. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  881. CK_FloatingRealToComplex);
  882. } else {
  883. assert(IntTy->isComplexIntegerType());
  884. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  885. CK_IntegralComplexToFloatingComplex);
  886. }
  887. return false;
  888. }
  889. /// \brief Handle arithmetic conversion with complex types. Helper function of
  890. /// UsualArithmeticConversions()
  891. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  892. ExprResult &RHS, QualType LHSType,
  893. QualType RHSType,
  894. bool IsCompAssign) {
  895. // if we have an integer operand, the result is the complex type.
  896. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  897. /*skipCast*/false))
  898. return LHSType;
  899. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  900. /*skipCast*/IsCompAssign))
  901. return RHSType;
  902. // This handles complex/complex, complex/float, or float/complex.
  903. // When both operands are complex, the shorter operand is converted to the
  904. // type of the longer, and that is the type of the result. This corresponds
  905. // to what is done when combining two real floating-point operands.
  906. // The fun begins when size promotion occur across type domains.
  907. // From H&S 6.3.4: When one operand is complex and the other is a real
  908. // floating-point type, the less precise type is converted, within it's
  909. // real or complex domain, to the precision of the other type. For example,
  910. // when combining a "long double" with a "double _Complex", the
  911. // "double _Complex" is promoted to "long double _Complex".
  912. // Compute the rank of the two types, regardless of whether they are complex.
  913. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  914. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  915. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  916. QualType LHSElementType =
  917. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  918. QualType RHSElementType =
  919. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  920. QualType ResultType = S.Context.getComplexType(LHSElementType);
  921. if (Order < 0) {
  922. // Promote the precision of the LHS if not an assignment.
  923. ResultType = S.Context.getComplexType(RHSElementType);
  924. if (!IsCompAssign) {
  925. if (LHSComplexType)
  926. LHS =
  927. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  928. else
  929. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  930. }
  931. } else if (Order > 0) {
  932. // Promote the precision of the RHS.
  933. if (RHSComplexType)
  934. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  935. else
  936. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  937. }
  938. return ResultType;
  939. }
  940. /// \brief Hande arithmetic conversion from integer to float. Helper function
  941. /// of UsualArithmeticConversions()
  942. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  943. ExprResult &IntExpr,
  944. QualType FloatTy, QualType IntTy,
  945. bool ConvertFloat, bool ConvertInt) {
  946. if (IntTy->isIntegerType()) {
  947. if (ConvertInt)
  948. // Convert intExpr to the lhs floating point type.
  949. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  950. CK_IntegralToFloating);
  951. return FloatTy;
  952. }
  953. // Convert both sides to the appropriate complex float.
  954. assert(IntTy->isComplexIntegerType());
  955. QualType result = S.Context.getComplexType(FloatTy);
  956. // _Complex int -> _Complex float
  957. if (ConvertInt)
  958. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  959. CK_IntegralComplexToFloatingComplex);
  960. // float -> _Complex float
  961. if (ConvertFloat)
  962. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  963. CK_FloatingRealToComplex);
  964. return result;
  965. }
  966. /// \brief Handle arithmethic conversion with floating point types. Helper
  967. /// function of UsualArithmeticConversions()
  968. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  969. ExprResult &RHS, QualType LHSType,
  970. QualType RHSType, bool IsCompAssign) {
  971. bool LHSFloat = LHSType->isRealFloatingType();
  972. bool RHSFloat = RHSType->isRealFloatingType();
  973. // If we have two real floating types, convert the smaller operand
  974. // to the bigger result.
  975. if (LHSFloat && RHSFloat) {
  976. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  977. if (order > 0) {
  978. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  979. return LHSType;
  980. }
  981. assert(order < 0 && "illegal float comparison");
  982. if (!IsCompAssign)
  983. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  984. return RHSType;
  985. }
  986. if (LHSFloat) {
  987. // Half FP has to be promoted to float unless it is natively supported
  988. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  989. LHSType = S.Context.FloatTy;
  990. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  991. /*convertFloat=*/!IsCompAssign,
  992. /*convertInt=*/ true);
  993. }
  994. assert(RHSFloat);
  995. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  996. /*convertInt=*/ true,
  997. /*convertFloat=*/!IsCompAssign);
  998. }
  999. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1000. namespace {
  1001. /// These helper callbacks are placed in an anonymous namespace to
  1002. /// permit their use as function template parameters.
  1003. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1004. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1005. }
  1006. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1007. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1008. CK_IntegralComplexCast);
  1009. }
  1010. }
  1011. /// \brief Handle integer arithmetic conversions. Helper function of
  1012. /// UsualArithmeticConversions()
  1013. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1014. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1015. ExprResult &RHS, QualType LHSType,
  1016. QualType RHSType, bool IsCompAssign) {
  1017. // The rules for this case are in C99 6.3.1.8
  1018. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1019. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1020. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1021. if (LHSSigned == RHSSigned) {
  1022. // Same signedness; use the higher-ranked type
  1023. if (order >= 0) {
  1024. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1025. return LHSType;
  1026. } else if (!IsCompAssign)
  1027. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1028. return RHSType;
  1029. } else if (order != (LHSSigned ? 1 : -1)) {
  1030. // The unsigned type has greater than or equal rank to the
  1031. // signed type, so use the unsigned type
  1032. if (RHSSigned) {
  1033. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1034. return LHSType;
  1035. } else if (!IsCompAssign)
  1036. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1037. return RHSType;
  1038. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1039. // The two types are different widths; if we are here, that
  1040. // means the signed type is larger than the unsigned type, so
  1041. // use the signed type.
  1042. if (LHSSigned) {
  1043. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1044. return LHSType;
  1045. } else if (!IsCompAssign)
  1046. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1047. return RHSType;
  1048. } else {
  1049. // The signed type is higher-ranked than the unsigned type,
  1050. // but isn't actually any bigger (like unsigned int and long
  1051. // on most 32-bit systems). Use the unsigned type corresponding
  1052. // to the signed type.
  1053. QualType result =
  1054. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1055. RHS = (*doRHSCast)(S, RHS.get(), result);
  1056. if (!IsCompAssign)
  1057. LHS = (*doLHSCast)(S, LHS.get(), result);
  1058. return result;
  1059. }
  1060. }
  1061. /// \brief Handle conversions with GCC complex int extension. Helper function
  1062. /// of UsualArithmeticConversions()
  1063. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1064. ExprResult &RHS, QualType LHSType,
  1065. QualType RHSType,
  1066. bool IsCompAssign) {
  1067. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1068. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1069. if (LHSComplexInt && RHSComplexInt) {
  1070. QualType LHSEltType = LHSComplexInt->getElementType();
  1071. QualType RHSEltType = RHSComplexInt->getElementType();
  1072. QualType ScalarType =
  1073. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1074. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1075. return S.Context.getComplexType(ScalarType);
  1076. }
  1077. if (LHSComplexInt) {
  1078. QualType LHSEltType = LHSComplexInt->getElementType();
  1079. QualType ScalarType =
  1080. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1081. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1082. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1083. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1084. CK_IntegralRealToComplex);
  1085. return ComplexType;
  1086. }
  1087. assert(RHSComplexInt);
  1088. QualType RHSEltType = RHSComplexInt->getElementType();
  1089. QualType ScalarType =
  1090. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1091. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1092. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1093. if (!IsCompAssign)
  1094. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1095. CK_IntegralRealToComplex);
  1096. return ComplexType;
  1097. }
  1098. /// UsualArithmeticConversions - Performs various conversions that are common to
  1099. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1100. /// routine returns the first non-arithmetic type found. The client is
  1101. /// responsible for emitting appropriate error diagnostics.
  1102. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1103. bool IsCompAssign) {
  1104. if (!IsCompAssign) {
  1105. LHS = UsualUnaryConversions(LHS.get());
  1106. if (LHS.isInvalid())
  1107. return QualType();
  1108. }
  1109. RHS = UsualUnaryConversions(RHS.get());
  1110. if (RHS.isInvalid())
  1111. return QualType();
  1112. // For conversion purposes, we ignore any qualifiers.
  1113. // For example, "const float" and "float" are equivalent.
  1114. QualType LHSType =
  1115. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1116. QualType RHSType =
  1117. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1118. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1119. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1120. LHSType = AtomicLHS->getValueType();
  1121. // If both types are identical, no conversion is needed.
  1122. if (LHSType == RHSType)
  1123. return LHSType;
  1124. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1125. // The caller can deal with this (e.g. pointer + int).
  1126. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1127. return QualType();
  1128. // Apply unary and bitfield promotions to the LHS's type.
  1129. QualType LHSUnpromotedType = LHSType;
  1130. if (LHSType->isPromotableIntegerType())
  1131. LHSType = Context.getPromotedIntegerType(LHSType);
  1132. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1133. if (!LHSBitfieldPromoteTy.isNull())
  1134. LHSType = LHSBitfieldPromoteTy;
  1135. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1136. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1137. // If both types are identical, no conversion is needed.
  1138. if (LHSType == RHSType)
  1139. return LHSType;
  1140. // At this point, we have two different arithmetic types.
  1141. // Handle complex types first (C99 6.3.1.8p1).
  1142. if (LHSType->isComplexType() || RHSType->isComplexType())
  1143. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1144. IsCompAssign);
  1145. // Now handle "real" floating types (i.e. float, double, long double).
  1146. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1147. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1148. IsCompAssign);
  1149. // Handle GCC complex int extension.
  1150. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1151. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1152. IsCompAssign);
  1153. // Finally, we have two differing integer types.
  1154. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1155. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1156. }
  1157. //===----------------------------------------------------------------------===//
  1158. // Semantic Analysis for various Expression Types
  1159. //===----------------------------------------------------------------------===//
  1160. ExprResult
  1161. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1162. SourceLocation DefaultLoc,
  1163. SourceLocation RParenLoc,
  1164. Expr *ControllingExpr,
  1165. ArrayRef<ParsedType> ArgTypes,
  1166. ArrayRef<Expr *> ArgExprs) {
  1167. unsigned NumAssocs = ArgTypes.size();
  1168. assert(NumAssocs == ArgExprs.size());
  1169. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1170. for (unsigned i = 0; i < NumAssocs; ++i) {
  1171. if (ArgTypes[i])
  1172. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1173. else
  1174. Types[i] = nullptr;
  1175. }
  1176. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1177. ControllingExpr,
  1178. llvm::makeArrayRef(Types, NumAssocs),
  1179. ArgExprs);
  1180. delete [] Types;
  1181. return ER;
  1182. }
  1183. ExprResult
  1184. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1185. SourceLocation DefaultLoc,
  1186. SourceLocation RParenLoc,
  1187. Expr *ControllingExpr,
  1188. ArrayRef<TypeSourceInfo *> Types,
  1189. ArrayRef<Expr *> Exprs) {
  1190. unsigned NumAssocs = Types.size();
  1191. assert(NumAssocs == Exprs.size());
  1192. if (ControllingExpr->getType()->isPlaceholderType()) {
  1193. ExprResult result = CheckPlaceholderExpr(ControllingExpr);
  1194. if (result.isInvalid()) return ExprError();
  1195. ControllingExpr = result.get();
  1196. }
  1197. // The controlling expression is an unevaluated operand, so side effects are
  1198. // likely unintended.
  1199. if (ActiveTemplateInstantiations.empty() &&
  1200. ControllingExpr->HasSideEffects(Context, false))
  1201. Diag(ControllingExpr->getExprLoc(),
  1202. diag::warn_side_effects_unevaluated_context);
  1203. bool TypeErrorFound = false,
  1204. IsResultDependent = ControllingExpr->isTypeDependent(),
  1205. ContainsUnexpandedParameterPack
  1206. = ControllingExpr->containsUnexpandedParameterPack();
  1207. for (unsigned i = 0; i < NumAssocs; ++i) {
  1208. if (Exprs[i]->containsUnexpandedParameterPack())
  1209. ContainsUnexpandedParameterPack = true;
  1210. if (Types[i]) {
  1211. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1212. ContainsUnexpandedParameterPack = true;
  1213. if (Types[i]->getType()->isDependentType()) {
  1214. IsResultDependent = true;
  1215. } else {
  1216. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1217. // complete object type other than a variably modified type."
  1218. unsigned D = 0;
  1219. if (Types[i]->getType()->isIncompleteType())
  1220. D = diag::err_assoc_type_incomplete;
  1221. else if (!Types[i]->getType()->isObjectType())
  1222. D = diag::err_assoc_type_nonobject;
  1223. else if (Types[i]->getType()->isVariablyModifiedType())
  1224. D = diag::err_assoc_type_variably_modified;
  1225. if (D != 0) {
  1226. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1227. << Types[i]->getTypeLoc().getSourceRange()
  1228. << Types[i]->getType();
  1229. TypeErrorFound = true;
  1230. }
  1231. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1232. // selection shall specify compatible types."
  1233. for (unsigned j = i+1; j < NumAssocs; ++j)
  1234. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1235. Context.typesAreCompatible(Types[i]->getType(),
  1236. Types[j]->getType())) {
  1237. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1238. diag::err_assoc_compatible_types)
  1239. << Types[j]->getTypeLoc().getSourceRange()
  1240. << Types[j]->getType()
  1241. << Types[i]->getType();
  1242. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1243. diag::note_compat_assoc)
  1244. << Types[i]->getTypeLoc().getSourceRange()
  1245. << Types[i]->getType();
  1246. TypeErrorFound = true;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. if (TypeErrorFound)
  1252. return ExprError();
  1253. // If we determined that the generic selection is result-dependent, don't
  1254. // try to compute the result expression.
  1255. if (IsResultDependent)
  1256. return new (Context) GenericSelectionExpr(
  1257. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1258. ContainsUnexpandedParameterPack);
  1259. SmallVector<unsigned, 1> CompatIndices;
  1260. unsigned DefaultIndex = -1U;
  1261. for (unsigned i = 0; i < NumAssocs; ++i) {
  1262. if (!Types[i])
  1263. DefaultIndex = i;
  1264. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1265. Types[i]->getType()))
  1266. CompatIndices.push_back(i);
  1267. }
  1268. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1269. // type compatible with at most one of the types named in its generic
  1270. // association list."
  1271. if (CompatIndices.size() > 1) {
  1272. // We strip parens here because the controlling expression is typically
  1273. // parenthesized in macro definitions.
  1274. ControllingExpr = ControllingExpr->IgnoreParens();
  1275. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1276. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1277. << (unsigned) CompatIndices.size();
  1278. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1279. E = CompatIndices.end(); I != E; ++I) {
  1280. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1281. diag::note_compat_assoc)
  1282. << Types[*I]->getTypeLoc().getSourceRange()
  1283. << Types[*I]->getType();
  1284. }
  1285. return ExprError();
  1286. }
  1287. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1288. // its controlling expression shall have type compatible with exactly one of
  1289. // the types named in its generic association list."
  1290. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1291. // We strip parens here because the controlling expression is typically
  1292. // parenthesized in macro definitions.
  1293. ControllingExpr = ControllingExpr->IgnoreParens();
  1294. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1295. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1296. return ExprError();
  1297. }
  1298. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1299. // type name that is compatible with the type of the controlling expression,
  1300. // then the result expression of the generic selection is the expression
  1301. // in that generic association. Otherwise, the result expression of the
  1302. // generic selection is the expression in the default generic association."
  1303. unsigned ResultIndex =
  1304. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1305. return new (Context) GenericSelectionExpr(
  1306. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1307. ContainsUnexpandedParameterPack, ResultIndex);
  1308. }
  1309. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1310. /// location of the token and the offset of the ud-suffix within it.
  1311. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1312. unsigned Offset) {
  1313. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1314. S.getLangOpts());
  1315. }
  1316. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1317. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1318. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1319. IdentifierInfo *UDSuffix,
  1320. SourceLocation UDSuffixLoc,
  1321. ArrayRef<Expr*> Args,
  1322. SourceLocation LitEndLoc) {
  1323. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1324. QualType ArgTy[2];
  1325. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1326. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1327. if (ArgTy[ArgIdx]->isArrayType())
  1328. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1329. }
  1330. DeclarationName OpName =
  1331. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1332. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1333. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1334. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1335. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1336. /*AllowRaw*/false, /*AllowTemplate*/false,
  1337. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1338. return ExprError();
  1339. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1340. }
  1341. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1342. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1343. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1344. /// multiple tokens. However, the common case is that StringToks points to one
  1345. /// string.
  1346. ///
  1347. ExprResult
  1348. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1349. assert(!StringToks.empty() && "Must have at least one string!");
  1350. StringLiteralParser Literal(StringToks, PP);
  1351. if (Literal.hadError)
  1352. return ExprError();
  1353. SmallVector<SourceLocation, 4> StringTokLocs;
  1354. for (unsigned i = 0; i != StringToks.size(); ++i)
  1355. StringTokLocs.push_back(StringToks[i].getLocation());
  1356. // HLSL Change Starts
  1357. if (getLangOpts().HLSL) {
  1358. assert(!Literal.isWide() && !Literal.isUTF16() && !Literal.isUTF32() && !Literal.isPascal()
  1359. && "HLSL parser always produces simple string literals");
  1360. QualType CharTyConst = Context.CharTy;
  1361. CharTyConst.addConst();
  1362. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1363. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1364. ArrayType::Normal, 0);
  1365. StringLiteral *Result = StringLiteral::Create(Context, Literal.GetString(), StringLiteral::StringKind::Ascii,
  1366. false, StrTy, &StringTokLocs[0], StringTokLocs.size());
  1367. return Result;
  1368. }
  1369. // HLSL Change Ends
  1370. QualType CharTy = Context.CharTy;
  1371. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1372. if (Literal.isWide()) {
  1373. CharTy = Context.getWideCharType();
  1374. Kind = StringLiteral::Wide;
  1375. } else if (Literal.isUTF8()) {
  1376. Kind = StringLiteral::UTF8;
  1377. } else if (Literal.isUTF16()) {
  1378. CharTy = Context.Char16Ty;
  1379. Kind = StringLiteral::UTF16;
  1380. } else if (Literal.isUTF32()) {
  1381. CharTy = Context.Char32Ty;
  1382. Kind = StringLiteral::UTF32;
  1383. } else if (Literal.isPascal()) {
  1384. CharTy = Context.UnsignedCharTy;
  1385. }
  1386. QualType CharTyConst = CharTy;
  1387. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1388. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1389. CharTyConst.addConst();
  1390. // Get an array type for the string, according to C99 6.4.5. This includes
  1391. // the nul terminator character as well as the string length for pascal
  1392. // strings.
  1393. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1394. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1395. ArrayType::Normal, 0);
  1396. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1397. if (getLangOpts().OpenCL) {
  1398. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1399. }
  1400. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1401. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1402. Kind, Literal.Pascal, StrTy,
  1403. &StringTokLocs[0],
  1404. StringTokLocs.size());
  1405. if (Literal.getUDSuffix().empty())
  1406. return Lit;
  1407. // We're building a user-defined literal.
  1408. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1409. SourceLocation UDSuffixLoc =
  1410. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1411. Literal.getUDSuffixOffset());
  1412. // Make sure we're allowed user-defined literals here.
  1413. if (!UDLScope)
  1414. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1415. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1416. // operator "" X (str, len)
  1417. QualType SizeType = Context.getSizeType();
  1418. DeclarationName OpName =
  1419. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1420. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1421. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1422. QualType ArgTy[] = {
  1423. Context.getArrayDecayedType(StrTy), SizeType
  1424. };
  1425. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1426. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1427. /*AllowRaw*/false, /*AllowTemplate*/false,
  1428. /*AllowStringTemplate*/true)) {
  1429. case LOLR_Cooked: {
  1430. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1431. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1432. StringTokLocs[0]);
  1433. Expr *Args[] = { Lit, LenArg };
  1434. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1435. }
  1436. case LOLR_StringTemplate: {
  1437. TemplateArgumentListInfo ExplicitArgs;
  1438. unsigned CharBits = Context.getIntWidth(CharTy);
  1439. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1440. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1441. TemplateArgument TypeArg(CharTy);
  1442. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1443. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1444. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1445. Value = Lit->getCodeUnit(I);
  1446. TemplateArgument Arg(Context, Value, CharTy);
  1447. TemplateArgumentLocInfo ArgInfo;
  1448. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1449. }
  1450. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1451. &ExplicitArgs);
  1452. }
  1453. case LOLR_Raw:
  1454. case LOLR_Template:
  1455. llvm_unreachable("unexpected literal operator lookup result");
  1456. case LOLR_Error:
  1457. return ExprError();
  1458. }
  1459. llvm_unreachable("unexpected literal operator lookup result");
  1460. }
  1461. ExprResult
  1462. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1463. SourceLocation Loc,
  1464. const CXXScopeSpec *SS) {
  1465. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1466. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1467. }
  1468. /// BuildDeclRefExpr - Build an expression that references a
  1469. /// declaration that does not require a closure capture.
  1470. ExprResult
  1471. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1472. const DeclarationNameInfo &NameInfo,
  1473. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1474. const TemplateArgumentListInfo *TemplateArgs) {
  1475. if (getLangOpts().CUDA)
  1476. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1477. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1478. if (CheckCUDATarget(Caller, Callee)) {
  1479. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1480. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1481. << IdentifyCUDATarget(Caller);
  1482. Diag(D->getLocation(), diag::note_previous_decl)
  1483. << D->getIdentifier();
  1484. return ExprError();
  1485. }
  1486. }
  1487. bool RefersToCapturedVariable =
  1488. isa<VarDecl>(D) &&
  1489. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1490. DeclRefExpr *E;
  1491. if (isa<VarTemplateSpecializationDecl>(D)) {
  1492. VarTemplateSpecializationDecl *VarSpec =
  1493. cast<VarTemplateSpecializationDecl>(D);
  1494. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1495. : NestedNameSpecifierLoc(),
  1496. VarSpec->getTemplateKeywordLoc(), D,
  1497. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1498. FoundD, TemplateArgs);
  1499. } else {
  1500. assert(!TemplateArgs && "No template arguments for non-variable"
  1501. " template specialization references");
  1502. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1503. : NestedNameSpecifierLoc(),
  1504. SourceLocation(), D, RefersToCapturedVariable,
  1505. NameInfo, Ty, VK, FoundD);
  1506. }
  1507. MarkDeclRefReferenced(E);
  1508. if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
  1509. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1510. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1511. recordUseOfEvaluatedWeak(E);
  1512. // Just in case we're building an illegal pointer-to-member.
  1513. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1514. if (FD && FD->isBitField())
  1515. E->setObjectKind(OK_BitField);
  1516. return E;
  1517. }
  1518. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1519. /// possibly a list of template arguments.
  1520. ///
  1521. /// If this produces template arguments, it is permitted to call
  1522. /// DecomposeTemplateName.
  1523. ///
  1524. /// This actually loses a lot of source location information for
  1525. /// non-standard name kinds; we should consider preserving that in
  1526. /// some way.
  1527. void
  1528. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1529. TemplateArgumentListInfo &Buffer,
  1530. DeclarationNameInfo &NameInfo,
  1531. const TemplateArgumentListInfo *&TemplateArgs) {
  1532. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1533. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1534. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1535. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1536. Id.TemplateId->NumArgs);
  1537. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1538. TemplateName TName = Id.TemplateId->Template.get();
  1539. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1540. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1541. TemplateArgs = &Buffer;
  1542. } else {
  1543. NameInfo = GetNameFromUnqualifiedId(Id);
  1544. TemplateArgs = nullptr;
  1545. }
  1546. }
  1547. static void emitEmptyLookupTypoDiagnostic(
  1548. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1549. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1550. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1551. DeclContext *Ctx =
  1552. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1553. if (!TC) {
  1554. // Emit a special diagnostic for failed member lookups.
  1555. // FIXME: computing the declaration context might fail here (?)
  1556. if (Ctx)
  1557. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1558. << SS.getRange();
  1559. else
  1560. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1561. return;
  1562. }
  1563. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1564. bool DroppedSpecifier =
  1565. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1566. unsigned NoteID =
  1567. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1568. ? diag::note_implicit_param_decl
  1569. : diag::note_previous_decl;
  1570. if (!Ctx)
  1571. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1572. SemaRef.PDiag(NoteID));
  1573. else
  1574. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1575. << Typo << Ctx << DroppedSpecifier
  1576. << SS.getRange(),
  1577. SemaRef.PDiag(NoteID));
  1578. }
  1579. /// Diagnose an empty lookup.
  1580. ///
  1581. /// \return false if new lookup candidates were found
  1582. bool
  1583. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1584. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1585. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1586. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1587. DeclarationName Name = R.getLookupName();
  1588. unsigned diagnostic = diag::err_undeclared_var_use;
  1589. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1590. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1591. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1592. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1593. diagnostic = diag::err_undeclared_use;
  1594. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1595. }
  1596. // If the original lookup was an unqualified lookup, fake an
  1597. // unqualified lookup. This is useful when (for example) the
  1598. // original lookup would not have found something because it was a
  1599. // dependent name.
  1600. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1601. ? CurContext : nullptr;
  1602. while (DC) {
  1603. if (isa<CXXRecordDecl>(DC)) {
  1604. LookupQualifiedName(R, DC);
  1605. if (!R.empty()) {
  1606. // Don't give errors about ambiguities in this lookup.
  1607. R.suppressDiagnostics();
  1608. // During a default argument instantiation the CurContext points
  1609. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1610. // function parameter list, hence add an explicit check.
  1611. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1612. ActiveTemplateInstantiations.back().Kind ==
  1613. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1614. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1615. bool isInstance = CurMethod &&
  1616. CurMethod->isInstance() &&
  1617. DC == CurMethod->getParent() && !isDefaultArgument;
  1618. // Give a code modification hint to insert 'this->'.
  1619. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1620. // Actually quite difficult!
  1621. if (getLangOpts().MSVCCompat)
  1622. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1623. if (isInstance) {
  1624. Diag(R.getNameLoc(), diagnostic) << Name
  1625. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1626. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1627. CallsUndergoingInstantiation.back()->getCallee());
  1628. CXXMethodDecl *DepMethod;
  1629. if (CurMethod->isDependentContext())
  1630. DepMethod = CurMethod;
  1631. else if (CurMethod->getTemplatedKind() ==
  1632. FunctionDecl::TK_FunctionTemplateSpecialization)
  1633. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1634. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1635. else
  1636. DepMethod = cast<CXXMethodDecl>(
  1637. CurMethod->getInstantiatedFromMemberFunction());
  1638. assert(DepMethod && "No template pattern found");
  1639. QualType DepThisType = DepMethod->getThisType(Context);
  1640. CheckCXXThisCapture(R.getNameLoc());
  1641. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1642. R.getNameLoc(), DepThisType, false);
  1643. TemplateArgumentListInfo TList;
  1644. if (ULE->hasExplicitTemplateArgs())
  1645. ULE->copyTemplateArgumentsInto(TList);
  1646. CXXScopeSpec SS;
  1647. SS.Adopt(ULE->getQualifierLoc());
  1648. CXXDependentScopeMemberExpr *DepExpr =
  1649. CXXDependentScopeMemberExpr::Create(
  1650. Context, DepThis, DepThisType, true, SourceLocation(),
  1651. SS.getWithLocInContext(Context),
  1652. ULE->getTemplateKeywordLoc(), nullptr,
  1653. R.getLookupNameInfo(),
  1654. ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
  1655. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1656. } else {
  1657. Diag(R.getNameLoc(), diagnostic) << Name;
  1658. }
  1659. // Do we really want to note all of these?
  1660. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1661. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1662. // Return true if we are inside a default argument instantiation
  1663. // and the found name refers to an instance member function, otherwise
  1664. // the function calling DiagnoseEmptyLookup will try to create an
  1665. // implicit member call and this is wrong for default argument.
  1666. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1667. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1668. return true;
  1669. }
  1670. // Tell the callee to try to recover.
  1671. return false;
  1672. }
  1673. R.clear();
  1674. }
  1675. // In Microsoft mode, if we are performing lookup from within a friend
  1676. // function definition declared at class scope then we must set
  1677. // DC to the lexical parent to be able to search into the parent
  1678. // class.
  1679. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1680. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1681. DC->getLexicalParent()->isRecord())
  1682. DC = DC->getLexicalParent();
  1683. else
  1684. DC = DC->getParent();
  1685. }
  1686. // We didn't find anything, so try to correct for a typo.
  1687. TypoCorrection Corrected;
  1688. if (S && Out) {
  1689. SourceLocation TypoLoc = R.getNameLoc();
  1690. assert(!ExplicitTemplateArgs &&
  1691. "Diagnosing an empty lookup with explicit template args!");
  1692. *Out = CorrectTypoDelayed(
  1693. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1694. [=](const TypoCorrection &TC) {
  1695. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1696. diagnostic, diagnostic_suggest);
  1697. },
  1698. nullptr, CTK_ErrorRecovery);
  1699. if (*Out)
  1700. return true;
  1701. } else if (S && (Corrected =
  1702. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1703. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1704. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1705. bool DroppedSpecifier =
  1706. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1707. R.setLookupName(Corrected.getCorrection());
  1708. bool AcceptableWithRecovery = false;
  1709. bool AcceptableWithoutRecovery = false;
  1710. NamedDecl *ND = Corrected.getCorrectionDecl();
  1711. if (ND) {
  1712. if (Corrected.isOverloaded()) {
  1713. OverloadCandidateSet OCS(R.getNameLoc(),
  1714. OverloadCandidateSet::CSK_Normal);
  1715. OverloadCandidateSet::iterator Best;
  1716. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1717. CDEnd = Corrected.end();
  1718. CD != CDEnd; ++CD) {
  1719. if (FunctionTemplateDecl *FTD =
  1720. dyn_cast<FunctionTemplateDecl>(*CD))
  1721. AddTemplateOverloadCandidate(
  1722. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1723. Args, OCS);
  1724. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1725. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1726. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1727. Args, OCS);
  1728. }
  1729. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1730. case OR_Success:
  1731. ND = Best->Function;
  1732. Corrected.setCorrectionDecl(ND);
  1733. break;
  1734. default:
  1735. // FIXME: Arbitrarily pick the first declaration for the note.
  1736. Corrected.setCorrectionDecl(ND);
  1737. break;
  1738. }
  1739. }
  1740. R.addDecl(ND);
  1741. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1742. CXXRecordDecl *Record = nullptr;
  1743. if (Corrected.getCorrectionSpecifier()) {
  1744. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1745. Record = Ty->getAsCXXRecordDecl();
  1746. }
  1747. if (!Record)
  1748. Record = cast<CXXRecordDecl>(
  1749. ND->getDeclContext()->getRedeclContext());
  1750. R.setNamingClass(Record);
  1751. }
  1752. AcceptableWithRecovery =
  1753. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1754. // FIXME: If we ended up with a typo for a type name or
  1755. // Objective-C class name, we're in trouble because the parser
  1756. // is in the wrong place to recover. Suggest the typo
  1757. // correction, but don't make it a fix-it since we're not going
  1758. // to recover well anyway.
  1759. AcceptableWithoutRecovery =
  1760. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1761. } else {
  1762. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1763. // because we aren't able to recover.
  1764. AcceptableWithoutRecovery = true;
  1765. }
  1766. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1767. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1768. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1769. ? diag::note_implicit_param_decl
  1770. : diag::note_previous_decl;
  1771. if (SS.isEmpty())
  1772. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1773. PDiag(NoteID), AcceptableWithRecovery);
  1774. else
  1775. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1776. << Name << computeDeclContext(SS, false)
  1777. << DroppedSpecifier << SS.getRange(),
  1778. PDiag(NoteID), AcceptableWithRecovery);
  1779. // Tell the callee whether to try to recover.
  1780. return !AcceptableWithRecovery;
  1781. }
  1782. }
  1783. R.clear();
  1784. // Emit a special diagnostic for failed member lookups.
  1785. // FIXME: computing the declaration context might fail here (?)
  1786. if (!SS.isEmpty()) {
  1787. Diag(R.getNameLoc(), diag::err_no_member)
  1788. << Name << computeDeclContext(SS, false)
  1789. << SS.getRange();
  1790. return true;
  1791. }
  1792. // Give up, we can't recover.
  1793. Diag(R.getNameLoc(), diagnostic) << Name;
  1794. return true;
  1795. }
  1796. /// In Microsoft mode, if we are inside a template class whose parent class has
  1797. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1798. /// assume the identifier is a member of a dependent base class. We can only
  1799. /// recover successfully in static methods, instance methods, and other contexts
  1800. /// where 'this' is available. This doesn't precisely match MSVC's
  1801. /// instantiation model, but it's close enough.
  1802. static Expr *
  1803. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1804. DeclarationNameInfo &NameInfo,
  1805. SourceLocation TemplateKWLoc,
  1806. const TemplateArgumentListInfo *TemplateArgs) {
  1807. // Only try to recover from lookup into dependent bases in static methods or
  1808. // contexts where 'this' is available.
  1809. QualType ThisType = S.getCurrentThisType();
  1810. const CXXRecordDecl *RD = nullptr;
  1811. if (!ThisType.isNull())
  1812. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1813. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1814. RD = MD->getParent();
  1815. if (!RD || !RD->hasAnyDependentBases())
  1816. return nullptr;
  1817. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1818. // is available, suggest inserting 'this->' as a fixit.
  1819. SourceLocation Loc = NameInfo.getLoc();
  1820. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1821. DB << NameInfo.getName() << RD;
  1822. if (!ThisType.isNull()) {
  1823. DB << FixItHint::CreateInsertion(Loc, "this->");
  1824. return CXXDependentScopeMemberExpr::Create(
  1825. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1826. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1827. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1828. }
  1829. // Synthesize a fake NNS that points to the derived class. This will
  1830. // perform name lookup during template instantiation.
  1831. CXXScopeSpec SS;
  1832. auto *NNS =
  1833. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1834. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1835. return DependentScopeDeclRefExpr::Create(
  1836. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1837. TemplateArgs);
  1838. }
  1839. ExprResult
  1840. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1841. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1842. bool HasTrailingLParen, bool IsAddressOfOperand,
  1843. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1844. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1845. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1846. "cannot be direct & operand and have a trailing lparen");
  1847. if (SS.isInvalid())
  1848. return ExprError();
  1849. TemplateArgumentListInfo TemplateArgsBuffer;
  1850. // Decompose the UnqualifiedId into the following data.
  1851. DeclarationNameInfo NameInfo;
  1852. const TemplateArgumentListInfo *TemplateArgs;
  1853. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1854. DeclarationName Name = NameInfo.getName();
  1855. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1856. SourceLocation NameLoc = NameInfo.getLoc();
  1857. // C++ [temp.dep.expr]p3:
  1858. // An id-expression is type-dependent if it contains:
  1859. // -- an identifier that was declared with a dependent type,
  1860. // (note: handled after lookup)
  1861. // -- a template-id that is dependent,
  1862. // (note: handled in BuildTemplateIdExpr)
  1863. // -- a conversion-function-id that specifies a dependent type,
  1864. // -- a nested-name-specifier that contains a class-name that
  1865. // names a dependent type.
  1866. // Determine whether this is a member of an unknown specialization;
  1867. // we need to handle these differently.
  1868. bool DependentID = false;
  1869. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1870. Name.getCXXNameType()->isDependentType()) {
  1871. DependentID = true;
  1872. } else if (SS.isSet()) {
  1873. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1874. if (RequireCompleteDeclContext(SS, DC))
  1875. return ExprError();
  1876. } else {
  1877. DependentID = true;
  1878. }
  1879. }
  1880. if (DependentID)
  1881. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1882. IsAddressOfOperand, TemplateArgs);
  1883. // Perform the required lookup.
  1884. LookupResult R(*this, NameInfo,
  1885. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1886. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1887. if (TemplateArgs) {
  1888. // Lookup the template name again to correctly establish the context in
  1889. // which it was found. This is really unfortunate as we already did the
  1890. // lookup to determine that it was a template name in the first place. If
  1891. // this becomes a performance hit, we can work harder to preserve those
  1892. // results until we get here but it's likely not worth it.
  1893. bool MemberOfUnknownSpecialization;
  1894. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1895. MemberOfUnknownSpecialization);
  1896. if (MemberOfUnknownSpecialization ||
  1897. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1898. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1899. IsAddressOfOperand, TemplateArgs);
  1900. } else {
  1901. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1902. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1903. // If the result might be in a dependent base class, this is a dependent
  1904. // id-expression.
  1905. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1906. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1907. IsAddressOfOperand, TemplateArgs);
  1908. // If this reference is in an Objective-C method, then we need to do
  1909. // some special Objective-C lookup, too.
  1910. if (IvarLookupFollowUp) {
  1911. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1912. if (E.isInvalid())
  1913. return ExprError();
  1914. if (Expr *Ex = E.getAs<Expr>())
  1915. return Ex;
  1916. }
  1917. }
  1918. if (R.isAmbiguous())
  1919. return ExprError();
  1920. // This could be an implicitly declared function reference (legal in C90,
  1921. // extension in C99, forbidden in C++).
  1922. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1923. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1924. if (D) R.addDecl(D);
  1925. }
  1926. // Determine whether this name might be a candidate for
  1927. // argument-dependent lookup.
  1928. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1929. if (R.empty() && !ADL) {
  1930. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1931. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1932. TemplateKWLoc, TemplateArgs))
  1933. return E;
  1934. }
  1935. // Don't diagnose an empty lookup for inline assembly.
  1936. if (IsInlineAsmIdentifier)
  1937. return ExprError();
  1938. // If this name wasn't predeclared and if this is not a function
  1939. // call, diagnose the problem.
  1940. TypoExpr *TE = nullptr;
  1941. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1942. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1943. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1944. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1945. "Typo correction callback misconfigured");
  1946. if (CCC) {
  1947. // Make sure the callback knows what the typo being diagnosed is.
  1948. CCC->setTypoName(II);
  1949. if (SS.isValid())
  1950. CCC->setTypoNNS(SS.getScopeRep());
  1951. }
  1952. if (DiagnoseEmptyLookup(S, SS, R,
  1953. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1954. nullptr, None, &TE)) {
  1955. if (TE && KeywordReplacement) {
  1956. auto &State = getTypoExprState(TE);
  1957. auto BestTC = State.Consumer->getNextCorrection();
  1958. if (BestTC.isKeyword()) {
  1959. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1960. if (State.DiagHandler)
  1961. State.DiagHandler(BestTC);
  1962. KeywordReplacement->startToken();
  1963. KeywordReplacement->setKind(II->getTokenID());
  1964. KeywordReplacement->setIdentifierInfo(II);
  1965. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1966. // Clean up the state associated with the TypoExpr, since it has
  1967. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1968. clearDelayedTypo(TE);
  1969. // Signal that a correction to a keyword was performed by returning a
  1970. // valid-but-null ExprResult.
  1971. return (Expr*)nullptr;
  1972. }
  1973. State.Consumer->resetCorrectionStream();
  1974. }
  1975. return TE ? TE : ExprError();
  1976. }
  1977. assert(!R.empty() &&
  1978. "DiagnoseEmptyLookup returned false but added no results");
  1979. // If we found an Objective-C instance variable, let
  1980. // LookupInObjCMethod build the appropriate expression to
  1981. // reference the ivar.
  1982. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1983. R.clear();
  1984. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1985. // In a hopelessly buggy code, Objective-C instance variable
  1986. // lookup fails and no expression will be built to reference it.
  1987. if (!E.isInvalid() && !E.get())
  1988. return ExprError();
  1989. return E;
  1990. }
  1991. }
  1992. // This is guaranteed from this point on.
  1993. assert(!R.empty() || ADL);
  1994. // Check whether this might be a C++ implicit instance member access.
  1995. // C++ [class.mfct.non-static]p3:
  1996. // When an id-expression that is not part of a class member access
  1997. // syntax and not used to form a pointer to member is used in the
  1998. // body of a non-static member function of class X, if name lookup
  1999. // resolves the name in the id-expression to a non-static non-type
  2000. // member of some class C, the id-expression is transformed into a
  2001. // class member access expression using (*this) as the
  2002. // postfix-expression to the left of the . operator.
  2003. //
  2004. // But we don't actually need to do this for '&' operands if R
  2005. // resolved to a function or overloaded function set, because the
  2006. // expression is ill-formed if it actually works out to be a
  2007. // non-static member function:
  2008. //
  2009. // C++ [expr.ref]p4:
  2010. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2011. // [t]he expression can be used only as the left-hand operand of a
  2012. // member function call.
  2013. //
  2014. // There are other safeguards against such uses, but it's important
  2015. // to get this right here so that we don't end up making a
  2016. // spuriously dependent expression if we're inside a dependent
  2017. // instance method.
  2018. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2019. bool MightBeImplicitMember;
  2020. if (!IsAddressOfOperand)
  2021. MightBeImplicitMember = true;
  2022. else if (!SS.isEmpty())
  2023. MightBeImplicitMember = false;
  2024. else if (R.isOverloadedResult())
  2025. MightBeImplicitMember = false;
  2026. else if (R.isUnresolvableResult())
  2027. MightBeImplicitMember = true;
  2028. else
  2029. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2030. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2031. isa<MSPropertyDecl>(R.getFoundDecl());
  2032. if (MightBeImplicitMember)
  2033. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2034. R, TemplateArgs);
  2035. }
  2036. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2037. // In C++1y, if this is a variable template id, then check it
  2038. // in BuildTemplateIdExpr().
  2039. // The single lookup result must be a variable template declaration.
  2040. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  2041. Id.TemplateId->Kind == TNK_Var_template) {
  2042. assert(R.getAsSingle<VarTemplateDecl>() &&
  2043. "There should only be one declaration found.");
  2044. }
  2045. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2046. }
  2047. return BuildDeclarationNameExpr(SS, R, ADL);
  2048. }
  2049. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2050. /// declaration name, generally during template instantiation.
  2051. /// There's a large number of things which don't need to be done along
  2052. /// this path.
  2053. ExprResult
  2054. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  2055. const DeclarationNameInfo &NameInfo,
  2056. bool IsAddressOfOperand,
  2057. TypeSourceInfo **RecoveryTSI) {
  2058. DeclContext *DC = computeDeclContext(SS, false);
  2059. if (!DC)
  2060. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2061. NameInfo, /*TemplateArgs=*/nullptr);
  2062. if (RequireCompleteDeclContext(SS, DC))
  2063. return ExprError();
  2064. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2065. LookupQualifiedName(R, DC);
  2066. if (R.isAmbiguous())
  2067. return ExprError();
  2068. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2069. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2070. NameInfo, /*TemplateArgs=*/nullptr);
  2071. if (R.empty()) {
  2072. Diag(NameInfo.getLoc(), diag::err_no_member)
  2073. << NameInfo.getName() << DC << SS.getRange();
  2074. return ExprError();
  2075. }
  2076. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2077. // Diagnose a missing typename if this resolved unambiguously to a type in
  2078. // a dependent context. If we can recover with a type, downgrade this to
  2079. // a warning in Microsoft compatibility mode.
  2080. unsigned DiagID = diag::err_typename_missing;
  2081. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2082. DiagID = diag::ext_typename_missing;
  2083. SourceLocation Loc = SS.getBeginLoc();
  2084. auto D = Diag(Loc, DiagID);
  2085. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2086. << SourceRange(Loc, NameInfo.getEndLoc());
  2087. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2088. // context.
  2089. if (!RecoveryTSI)
  2090. return ExprError();
  2091. // Only issue the fixit if we're prepared to recover.
  2092. D << FixItHint::CreateInsertion(Loc, "typename ");
  2093. // Recover by pretending this was an elaborated type.
  2094. QualType Ty = Context.getTypeDeclType(TD);
  2095. TypeLocBuilder TLB;
  2096. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2097. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2098. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2099. QTL.setElaboratedKeywordLoc(SourceLocation());
  2100. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2101. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2102. return ExprEmpty();
  2103. }
  2104. // Defend against this resolving to an implicit member access. We usually
  2105. // won't get here if this might be a legitimate a class member (we end up in
  2106. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2107. // a pointer-to-member or in an unevaluated context in C++11.
  2108. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2109. return BuildPossibleImplicitMemberExpr(SS,
  2110. /*TemplateKWLoc=*/SourceLocation(),
  2111. R, /*TemplateArgs=*/nullptr);
  2112. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2113. }
  2114. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2115. /// detected that we're currently inside an ObjC method. Perform some
  2116. /// additional lookup.
  2117. ///
  2118. /// Ideally, most of this would be done by lookup, but there's
  2119. /// actually quite a lot of extra work involved.
  2120. ///
  2121. /// Returns a null sentinel to indicate trivial success.
  2122. ExprResult
  2123. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2124. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2125. SourceLocation Loc = Lookup.getNameLoc();
  2126. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2127. // Check for error condition which is already reported.
  2128. if (!CurMethod)
  2129. return ExprError();
  2130. // There are two cases to handle here. 1) scoped lookup could have failed,
  2131. // in which case we should look for an ivar. 2) scoped lookup could have
  2132. // found a decl, but that decl is outside the current instance method (i.e.
  2133. // a global variable). In these two cases, we do a lookup for an ivar with
  2134. // this name, if the lookup sucedes, we replace it our current decl.
  2135. // If we're in a class method, we don't normally want to look for
  2136. // ivars. But if we don't find anything else, and there's an
  2137. // ivar, that's an error.
  2138. bool IsClassMethod = CurMethod->isClassMethod();
  2139. bool LookForIvars;
  2140. if (Lookup.empty())
  2141. LookForIvars = true;
  2142. else if (IsClassMethod)
  2143. LookForIvars = false;
  2144. else
  2145. LookForIvars = (Lookup.isSingleResult() &&
  2146. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2147. ObjCInterfaceDecl *IFace = nullptr;
  2148. if (LookForIvars) {
  2149. IFace = CurMethod->getClassInterface();
  2150. ObjCInterfaceDecl *ClassDeclared;
  2151. ObjCIvarDecl *IV = nullptr;
  2152. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2153. // Diagnose using an ivar in a class method.
  2154. if (IsClassMethod)
  2155. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2156. << IV->getDeclName());
  2157. // If we're referencing an invalid decl, just return this as a silent
  2158. // error node. The error diagnostic was already emitted on the decl.
  2159. if (IV->isInvalidDecl())
  2160. return ExprError();
  2161. // Check if referencing a field with __attribute__((deprecated)).
  2162. if (DiagnoseUseOfDecl(IV, Loc))
  2163. return ExprError();
  2164. // Diagnose the use of an ivar outside of the declaring class.
  2165. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2166. !declaresSameEntity(ClassDeclared, IFace) &&
  2167. !getLangOpts().DebuggerSupport)
  2168. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2169. // FIXME: This should use a new expr for a direct reference, don't
  2170. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2171. IdentifierInfo &II = Context.Idents.get("self");
  2172. UnqualifiedId SelfName;
  2173. SelfName.setIdentifier(&II, SourceLocation());
  2174. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2175. CXXScopeSpec SelfScopeSpec;
  2176. SourceLocation TemplateKWLoc;
  2177. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2178. SelfName, false, false);
  2179. if (SelfExpr.isInvalid())
  2180. return ExprError();
  2181. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2182. if (SelfExpr.isInvalid())
  2183. return ExprError();
  2184. MarkAnyDeclReferenced(Loc, IV, true);
  2185. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2186. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2187. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2188. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2189. ObjCIvarRefExpr *Result = new (Context)
  2190. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2191. IV->getLocation(), SelfExpr.get(), true, true);
  2192. if (getLangOpts().ObjCAutoRefCount) {
  2193. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2194. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2195. recordUseOfEvaluatedWeak(Result);
  2196. }
  2197. if (CurContext->isClosure())
  2198. Diag(Loc, diag::warn_implicitly_retains_self)
  2199. << FixItHint::CreateInsertion(Loc, "self->");
  2200. }
  2201. return Result;
  2202. }
  2203. } else if (CurMethod->isInstanceMethod()) {
  2204. // We should warn if a local variable hides an ivar.
  2205. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2206. ObjCInterfaceDecl *ClassDeclared;
  2207. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2208. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2209. declaresSameEntity(IFace, ClassDeclared))
  2210. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2211. }
  2212. }
  2213. } else if (Lookup.isSingleResult() &&
  2214. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2215. // If accessing a stand-alone ivar in a class method, this is an error.
  2216. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2217. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2218. << IV->getDeclName());
  2219. }
  2220. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2221. // FIXME. Consolidate this with similar code in LookupName.
  2222. if (unsigned BuiltinID = II->getBuiltinID()) {
  2223. if (!(getLangOpts().CPlusPlus &&
  2224. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2225. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2226. S, Lookup.isForRedeclaration(),
  2227. Lookup.getNameLoc());
  2228. if (D) Lookup.addDecl(D);
  2229. }
  2230. }
  2231. }
  2232. // Sentinel value saying that we didn't do anything special.
  2233. return ExprResult((Expr *)nullptr);
  2234. }
  2235. /// \brief Cast a base object to a member's actual type.
  2236. ///
  2237. /// Logically this happens in three phases:
  2238. ///
  2239. /// * First we cast from the base type to the naming class.
  2240. /// The naming class is the class into which we were looking
  2241. /// when we found the member; it's the qualifier type if a
  2242. /// qualifier was provided, and otherwise it's the base type.
  2243. ///
  2244. /// * Next we cast from the naming class to the declaring class.
  2245. /// If the member we found was brought into a class's scope by
  2246. /// a using declaration, this is that class; otherwise it's
  2247. /// the class declaring the member.
  2248. ///
  2249. /// * Finally we cast from the declaring class to the "true"
  2250. /// declaring class of the member. This conversion does not
  2251. /// obey access control.
  2252. ExprResult
  2253. Sema::PerformObjectMemberConversion(Expr *From,
  2254. NestedNameSpecifier *Qualifier,
  2255. NamedDecl *FoundDecl,
  2256. NamedDecl *Member) {
  2257. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2258. if (!RD)
  2259. return From;
  2260. QualType DestRecordType;
  2261. QualType DestType;
  2262. QualType FromRecordType;
  2263. QualType FromType = From->getType();
  2264. bool PointerConversions = false;
  2265. if (isa<FieldDecl>(Member)) {
  2266. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2267. if (FromType->getAs<PointerType>()) {
  2268. DestType = Context.getPointerType(DestRecordType);
  2269. FromRecordType = FromType->getPointeeType();
  2270. PointerConversions = true;
  2271. } else {
  2272. DestType = DestRecordType;
  2273. FromRecordType = FromType;
  2274. }
  2275. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2276. if (Method->isStatic())
  2277. return From;
  2278. DestType = Method->getThisType(Context);
  2279. DestRecordType = DestType->getPointeeType();
  2280. if (FromType->getAs<PointerType>()) {
  2281. FromRecordType = FromType->getPointeeType();
  2282. PointerConversions = true;
  2283. } else {
  2284. FromRecordType = FromType;
  2285. DestType = DestRecordType;
  2286. }
  2287. } else {
  2288. // No conversion necessary.
  2289. return From;
  2290. }
  2291. if (DestType->isDependentType() || FromType->isDependentType())
  2292. return From;
  2293. // If the unqualified types are the same, no conversion is necessary.
  2294. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2295. return From;
  2296. SourceRange FromRange = From->getSourceRange();
  2297. SourceLocation FromLoc = FromRange.getBegin();
  2298. ExprValueKind VK = From->getValueKind();
  2299. // C++ [class.member.lookup]p8:
  2300. // [...] Ambiguities can often be resolved by qualifying a name with its
  2301. // class name.
  2302. //
  2303. // If the member was a qualified name and the qualified referred to a
  2304. // specific base subobject type, we'll cast to that intermediate type
  2305. // first and then to the object in which the member is declared. That allows
  2306. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2307. //
  2308. // class Base { public: int x; };
  2309. // class Derived1 : public Base { };
  2310. // class Derived2 : public Base { };
  2311. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2312. //
  2313. // void VeryDerived::f() {
  2314. // x = 17; // error: ambiguous base subobjects
  2315. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2316. // }
  2317. if (Qualifier && Qualifier->getAsType()) {
  2318. QualType QType = QualType(Qualifier->getAsType(), 0);
  2319. assert(QType->isRecordType() && "lookup done with non-record type");
  2320. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2321. // In C++98, the qualifier type doesn't actually have to be a base
  2322. // type of the object type, in which case we just ignore it.
  2323. // Otherwise build the appropriate casts.
  2324. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2325. CXXCastPath BasePath;
  2326. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2327. FromLoc, FromRange, &BasePath))
  2328. return ExprError();
  2329. if (PointerConversions)
  2330. QType = Context.getPointerType(QType);
  2331. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2332. VK, &BasePath).get();
  2333. FromType = QType;
  2334. FromRecordType = QRecordType;
  2335. // If the qualifier type was the same as the destination type,
  2336. // we're done.
  2337. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2338. return From;
  2339. }
  2340. }
  2341. bool IgnoreAccess = false;
  2342. // If we actually found the member through a using declaration, cast
  2343. // down to the using declaration's type.
  2344. //
  2345. // Pointer equality is fine here because only one declaration of a
  2346. // class ever has member declarations.
  2347. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2348. assert(isa<UsingShadowDecl>(FoundDecl));
  2349. QualType URecordType = Context.getTypeDeclType(
  2350. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2351. // We only need to do this if the naming-class to declaring-class
  2352. // conversion is non-trivial.
  2353. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2354. assert(IsDerivedFrom(FromRecordType, URecordType));
  2355. CXXCastPath BasePath;
  2356. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2357. FromLoc, FromRange, &BasePath))
  2358. return ExprError();
  2359. QualType UType = URecordType;
  2360. if (PointerConversions)
  2361. UType = Context.getPointerType(UType);
  2362. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2363. VK, &BasePath).get();
  2364. FromType = UType;
  2365. FromRecordType = URecordType;
  2366. }
  2367. // We don't do access control for the conversion from the
  2368. // declaring class to the true declaring class.
  2369. IgnoreAccess = true;
  2370. }
  2371. CXXCastPath BasePath;
  2372. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2373. FromLoc, FromRange, &BasePath,
  2374. IgnoreAccess))
  2375. return ExprError();
  2376. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2377. VK, &BasePath);
  2378. }
  2379. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2380. const LookupResult &R,
  2381. bool HasTrailingLParen) {
  2382. // Only when used directly as the postfix-expression of a call.
  2383. if (!HasTrailingLParen)
  2384. return false;
  2385. // Never if a scope specifier was provided.
  2386. if (SS.isSet())
  2387. return false;
  2388. // Only in C++ or ObjC++.
  2389. if (!getLangOpts().CPlusPlus)
  2390. return false;
  2391. // Turn off ADL when we find certain kinds of declarations during
  2392. // normal lookup:
  2393. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2394. NamedDecl *D = *I;
  2395. // C++0x [basic.lookup.argdep]p3:
  2396. // -- a declaration of a class member
  2397. // Since using decls preserve this property, we check this on the
  2398. // original decl.
  2399. if (D->isCXXClassMember())
  2400. return false;
  2401. // C++0x [basic.lookup.argdep]p3:
  2402. // -- a block-scope function declaration that is not a
  2403. // using-declaration
  2404. // NOTE: we also trigger this for function templates (in fact, we
  2405. // don't check the decl type at all, since all other decl types
  2406. // turn off ADL anyway).
  2407. if (isa<UsingShadowDecl>(D))
  2408. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2409. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2410. return false;
  2411. // C++0x [basic.lookup.argdep]p3:
  2412. // -- a declaration that is neither a function or a function
  2413. // template
  2414. // And also for builtin functions.
  2415. if (isa<FunctionDecl>(D)) {
  2416. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2417. // But also builtin functions.
  2418. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2419. return false;
  2420. } else if (!isa<FunctionTemplateDecl>(D))
  2421. return false;
  2422. }
  2423. return true;
  2424. }
  2425. /// Diagnoses obvious problems with the use of the given declaration
  2426. /// as an expression. This is only actually called for lookups that
  2427. /// were not overloaded, and it doesn't promise that the declaration
  2428. /// will in fact be used.
  2429. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2430. if (isa<TypedefNameDecl>(D)) {
  2431. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2432. return true;
  2433. }
  2434. if (isa<ObjCInterfaceDecl>(D)) {
  2435. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2436. return true;
  2437. }
  2438. if (isa<NamespaceDecl>(D)) {
  2439. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2440. return true;
  2441. }
  2442. return false;
  2443. }
  2444. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2445. LookupResult &R, bool NeedsADL,
  2446. bool AcceptInvalidDecl) {
  2447. // If this is a single, fully-resolved result and we don't need ADL,
  2448. // just build an ordinary singleton decl ref.
  2449. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2450. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2451. R.getRepresentativeDecl(), nullptr,
  2452. AcceptInvalidDecl);
  2453. // We only need to check the declaration if there's exactly one
  2454. // result, because in the overloaded case the results can only be
  2455. // functions and function templates.
  2456. if (R.isSingleResult() &&
  2457. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2458. return ExprError();
  2459. // Otherwise, just build an unresolved lookup expression. Suppress
  2460. // any lookup-related diagnostics; we'll hash these out later, when
  2461. // we've picked a target.
  2462. R.suppressDiagnostics();
  2463. UnresolvedLookupExpr *ULE
  2464. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2465. SS.getWithLocInContext(Context),
  2466. R.getLookupNameInfo(),
  2467. NeedsADL, R.isOverloadedResult(),
  2468. R.begin(), R.end());
  2469. return ULE;
  2470. }
  2471. /// \brief Complete semantic analysis for a reference to the given declaration.
  2472. ExprResult Sema::BuildDeclarationNameExpr(
  2473. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2474. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2475. bool AcceptInvalidDecl) {
  2476. assert(D && "Cannot refer to a NULL declaration");
  2477. assert(!isa<FunctionTemplateDecl>(D) &&
  2478. "Cannot refer unambiguously to a function template");
  2479. SourceLocation Loc = NameInfo.getLoc();
  2480. if (CheckDeclInExpr(*this, Loc, D))
  2481. return ExprError();
  2482. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2483. // Specifically diagnose references to class templates that are missing
  2484. // a template argument list.
  2485. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2486. << Template << SS.getRange();
  2487. if (Template->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  2488. Diag(Template->getLocation(), diag::note_template_decl_here);
  2489. }
  2490. return ExprError();
  2491. }
  2492. // Make sure that we're referring to a value.
  2493. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2494. if (!VD) {
  2495. Diag(Loc, diag::err_ref_non_value)
  2496. << D << SS.getRange();
  2497. Diag(D->getLocation(), diag::note_declared_at);
  2498. return ExprError();
  2499. }
  2500. // Check whether this declaration can be used. Note that we suppress
  2501. // this check when we're going to perform argument-dependent lookup
  2502. // on this function name, because this might not be the function
  2503. // that overload resolution actually selects.
  2504. if (DiagnoseUseOfDecl(VD, Loc))
  2505. return ExprError();
  2506. // Only create DeclRefExpr's for valid Decl's.
  2507. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2508. return ExprError();
  2509. // Handle members of anonymous structs and unions. If we got here,
  2510. // and the reference is to a class member indirect field, then this
  2511. // must be the subject of a pointer-to-member expression.
  2512. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2513. if (!indirectField->isCXXClassMember())
  2514. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2515. indirectField);
  2516. {
  2517. QualType type = VD->getType();
  2518. ExprValueKind valueKind = VK_RValue;
  2519. switch (D->getKind()) {
  2520. // Ignore all the non-ValueDecl kinds.
  2521. #define ABSTRACT_DECL(kind)
  2522. #define VALUE(type, base)
  2523. #define DECL(type, base) \
  2524. case Decl::type:
  2525. #include "clang/AST/DeclNodes.inc"
  2526. llvm_unreachable("invalid value decl kind");
  2527. // These shouldn't make it here.
  2528. case Decl::ObjCAtDefsField:
  2529. case Decl::ObjCIvar:
  2530. llvm_unreachable("forming non-member reference to ivar?");
  2531. // Enum constants are always r-values and never references.
  2532. // Unresolved using declarations are dependent.
  2533. case Decl::EnumConstant:
  2534. case Decl::UnresolvedUsingValue:
  2535. valueKind = VK_RValue;
  2536. break;
  2537. // Fields and indirect fields that got here must be for
  2538. // pointer-to-member expressions; we just call them l-values for
  2539. // internal consistency, because this subexpression doesn't really
  2540. // exist in the high-level semantics.
  2541. case Decl::Field:
  2542. case Decl::IndirectField:
  2543. assert(getLangOpts().CPlusPlus &&
  2544. "building reference to field in C?");
  2545. // These can't have reference type in well-formed programs, but
  2546. // for internal consistency we do this anyway.
  2547. type = type.getNonReferenceType();
  2548. valueKind = VK_LValue;
  2549. break;
  2550. // Non-type template parameters are either l-values or r-values
  2551. // depending on the type.
  2552. case Decl::NonTypeTemplateParm: {
  2553. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2554. type = reftype->getPointeeType();
  2555. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2556. break;
  2557. }
  2558. // For non-references, we need to strip qualifiers just in case
  2559. // the template parameter was declared as 'const int' or whatever.
  2560. valueKind = VK_RValue;
  2561. type = type.getUnqualifiedType();
  2562. break;
  2563. }
  2564. case Decl::Var:
  2565. case Decl::VarTemplateSpecialization:
  2566. case Decl::VarTemplatePartialSpecialization:
  2567. // In C, "extern void blah;" is valid and is an r-value.
  2568. if (!getLangOpts().CPlusPlus &&
  2569. !type.hasQualifiers() &&
  2570. type->isVoidType()) {
  2571. valueKind = VK_RValue;
  2572. break;
  2573. }
  2574. // fallthrough
  2575. case Decl::ImplicitParam:
  2576. case Decl::ParmVar: {
  2577. // These are always l-values.
  2578. valueKind = VK_LValue;
  2579. type = type.getNonReferenceType();
  2580. // FIXME: Does the addition of const really only apply in
  2581. // potentially-evaluated contexts? Since the variable isn't actually
  2582. // captured in an unevaluated context, it seems that the answer is no.
  2583. if (!isUnevaluatedContext()) {
  2584. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2585. if (!CapturedType.isNull())
  2586. type = CapturedType;
  2587. }
  2588. break;
  2589. }
  2590. case Decl::Function: {
  2591. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2592. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2593. type = Context.BuiltinFnTy;
  2594. valueKind = VK_RValue;
  2595. break;
  2596. }
  2597. }
  2598. const FunctionType *fty = type->castAs<FunctionType>();
  2599. // If we're referring to a function with an __unknown_anytype
  2600. // result type, make the entire expression __unknown_anytype.
  2601. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2602. type = Context.UnknownAnyTy;
  2603. valueKind = VK_RValue;
  2604. break;
  2605. }
  2606. // Functions are l-values in C++.
  2607. if (getLangOpts().CPlusPlus) {
  2608. valueKind = VK_LValue;
  2609. break;
  2610. }
  2611. // C99 DR 316 says that, if a function type comes from a
  2612. // function definition (without a prototype), that type is only
  2613. // used for checking compatibility. Therefore, when referencing
  2614. // the function, we pretend that we don't have the full function
  2615. // type.
  2616. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2617. isa<FunctionProtoType>(fty))
  2618. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2619. fty->getExtInfo());
  2620. // Functions are r-values in C.
  2621. valueKind = VK_RValue;
  2622. break;
  2623. }
  2624. case Decl::MSProperty:
  2625. valueKind = VK_LValue;
  2626. break;
  2627. case Decl::CXXMethod:
  2628. // If we're referring to a method with an __unknown_anytype
  2629. // result type, make the entire expression __unknown_anytype.
  2630. // This should only be possible with a type written directly.
  2631. if (const FunctionProtoType *proto
  2632. = dyn_cast<FunctionProtoType>(VD->getType()))
  2633. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2634. type = Context.UnknownAnyTy;
  2635. valueKind = VK_RValue;
  2636. break;
  2637. }
  2638. // C++ methods are l-values if static, r-values if non-static.
  2639. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2640. valueKind = VK_LValue;
  2641. break;
  2642. }
  2643. // fallthrough
  2644. case Decl::CXXConversion:
  2645. case Decl::CXXDestructor:
  2646. case Decl::CXXConstructor:
  2647. valueKind = VK_RValue;
  2648. break;
  2649. }
  2650. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2651. TemplateArgs);
  2652. }
  2653. }
  2654. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2655. SmallString<32> &Target) {
  2656. Target.resize(CharByteWidth * (Source.size() + 1));
  2657. char *ResultPtr = &Target[0];
  2658. const UTF8 *ErrorPtr;
  2659. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2660. (void)success;
  2661. assert(success);
  2662. Target.resize(ResultPtr - &Target[0]);
  2663. }
  2664. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2665. PredefinedExpr::IdentType IT) {
  2666. // Pick the current block, lambda, captured statement or function.
  2667. Decl *currentDecl = nullptr;
  2668. if (const BlockScopeInfo *BSI = getCurBlock())
  2669. currentDecl = BSI->TheDecl;
  2670. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2671. currentDecl = LSI->CallOperator;
  2672. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2673. currentDecl = CSI->TheCapturedDecl;
  2674. else
  2675. currentDecl = getCurFunctionOrMethodDecl();
  2676. if (!currentDecl) {
  2677. Diag(Loc, diag::ext_predef_outside_function);
  2678. currentDecl = Context.getTranslationUnitDecl();
  2679. }
  2680. QualType ResTy;
  2681. StringLiteral *SL = nullptr;
  2682. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2683. ResTy = Context.DependentTy;
  2684. else {
  2685. // Pre-defined identifiers are of type char[x], where x is the length of
  2686. // the string.
  2687. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2688. unsigned Length = Str.length();
  2689. llvm::APInt LengthI(32, Length + 1);
  2690. if (IT == PredefinedExpr::LFunction) {
  2691. ResTy = Context.WideCharTy.withConst();
  2692. SmallString<32> RawChars;
  2693. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2694. Str, RawChars);
  2695. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2696. /*IndexTypeQuals*/ 0);
  2697. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2698. /*Pascal*/ false, ResTy, Loc);
  2699. } else {
  2700. ResTy = Context.CharTy.withConst();
  2701. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2702. /*IndexTypeQuals*/ 0);
  2703. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2704. /*Pascal*/ false, ResTy, Loc);
  2705. }
  2706. }
  2707. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2708. }
  2709. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2710. PredefinedExpr::IdentType IT;
  2711. switch (Kind) {
  2712. default: llvm_unreachable("Unknown simple primary expr!");
  2713. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2714. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2715. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2716. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2717. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2718. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2719. }
  2720. return BuildPredefinedExpr(Loc, IT);
  2721. }
  2722. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2723. SmallString<16> CharBuffer;
  2724. bool Invalid = false;
  2725. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2726. if (Invalid)
  2727. return ExprError();
  2728. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2729. PP, Tok.getKind());
  2730. if (Literal.hadError())
  2731. return ExprError();
  2732. // HLSL Change Starts
  2733. if (getLangOpts().HLSL) {
  2734. if (Literal.isWide() || Literal.isUTF16() || Literal.isUTF32() || Literal.isMultiChar()) {
  2735. Diag(Tok.getLocation(), diag::err_hlsl_unsupported_char_literal);
  2736. return ExprError();
  2737. }
  2738. Expr *CharLit = new (Context)CharacterLiteral(Literal.getValue(), CharacterLiteral::Ascii, Context.CharTy,
  2739. Tok.getLocation());
  2740. Expr* Result = ImplicitCastExpr::Create(Context,
  2741. Context.UnsignedIntTy, CK_IntegralCast, CharLit, nullptr, VK_RValue);
  2742. return Result;
  2743. }
  2744. // HLSL Change Ends
  2745. QualType Ty;
  2746. if (Literal.isWide())
  2747. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2748. else if (Literal.isUTF16())
  2749. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2750. else if (Literal.isUTF32())
  2751. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2752. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2753. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2754. else
  2755. Ty = Context.CharTy; // 'x' -> char in C++
  2756. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2757. if (Literal.isWide())
  2758. Kind = CharacterLiteral::Wide;
  2759. else if (Literal.isUTF16())
  2760. Kind = CharacterLiteral::UTF16;
  2761. else if (Literal.isUTF32())
  2762. Kind = CharacterLiteral::UTF32;
  2763. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2764. Tok.getLocation());
  2765. if (Literal.getUDSuffix().empty())
  2766. return Lit;
  2767. // We're building a user-defined literal.
  2768. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2769. SourceLocation UDSuffixLoc =
  2770. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2771. // Make sure we're allowed user-defined literals here.
  2772. if (!UDLScope)
  2773. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2774. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2775. // operator "" X (ch)
  2776. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2777. Lit, Tok.getLocation());
  2778. }
  2779. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2780. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2781. // HLSL Change Starts - HLSL literal int
  2782. QualType Ty;
  2783. if (getLangOpts().HLSL) {
  2784. IntSize = 64;
  2785. Ty = Context.LitIntTy;
  2786. } else
  2787. Ty = Context.IntTy;
  2788. // HLSL Change Ends
  2789. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2790. Ty, Loc); // HLSL Change
  2791. }
  2792. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2793. QualType Ty, SourceLocation Loc) {
  2794. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2795. using llvm::APFloat;
  2796. APFloat Val(Format);
  2797. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2798. // Overflow is always an error, but underflow is only an error if
  2799. // we underflowed to zero (APFloat reports denormals as underflow).
  2800. if ((result & APFloat::opOverflow) ||
  2801. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2802. unsigned diagnostic;
  2803. SmallString<20> buffer;
  2804. if (result & APFloat::opOverflow) {
  2805. diagnostic = diag::warn_float_overflow;
  2806. APFloat::getLargest(Format).toString(buffer);
  2807. } else {
  2808. diagnostic = diag::warn_float_underflow;
  2809. APFloat::getSmallest(Format).toString(buffer);
  2810. }
  2811. S.Diag(Loc, diagnostic)
  2812. << Ty
  2813. << StringRef(buffer.data(), buffer.size());
  2814. }
  2815. bool isExact = (result == APFloat::opOK);
  2816. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2817. }
  2818. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2819. assert(E && "Invalid expression");
  2820. if (E->isValueDependent())
  2821. return false;
  2822. QualType QT = E->getType();
  2823. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2824. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2825. return true;
  2826. }
  2827. llvm::APSInt ValueAPS;
  2828. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2829. if (R.isInvalid())
  2830. return true;
  2831. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2832. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2833. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2834. << ValueAPS.toString(10) << ValueIsPositive;
  2835. return true;
  2836. }
  2837. return false;
  2838. }
  2839. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2840. // Fast path for a single digit (which is quite common). A single digit
  2841. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2842. if (Tok.getLength() == 1) {
  2843. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2844. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2845. }
  2846. SmallString<128> SpellingBuffer;
  2847. // NumericLiteralParser wants to overread by one character. Add padding to
  2848. // the buffer in case the token is copied to the buffer. If getSpelling()
  2849. // returns a StringRef to the memory buffer, it should have a null char at
  2850. // the EOF, so it is also safe.
  2851. SpellingBuffer.resize(Tok.getLength() + 1);
  2852. // Get the spelling of the token, which eliminates trigraphs, etc.
  2853. bool Invalid = false;
  2854. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2855. if (Invalid)
  2856. return ExprError();
  2857. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2858. if (Literal.hadError)
  2859. return ExprError();
  2860. if (Literal.hasUDSuffix()) {
  2861. // We're building a user-defined literal.
  2862. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2863. SourceLocation UDSuffixLoc =
  2864. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2865. // Make sure we're allowed user-defined literals here.
  2866. if (!UDLScope)
  2867. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2868. QualType CookedTy;
  2869. if (Literal.isFloatingLiteral()) {
  2870. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2871. // long double, the literal is treated as a call of the form
  2872. // operator "" X (f L)
  2873. CookedTy = Context.LongDoubleTy;
  2874. } else {
  2875. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2876. // unsigned long long, the literal is treated as a call of the form
  2877. // operator "" X (n ULL)
  2878. CookedTy = Context.UnsignedLongLongTy;
  2879. }
  2880. DeclarationName OpName =
  2881. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2882. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2883. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2884. SourceLocation TokLoc = Tok.getLocation();
  2885. // Perform literal operator lookup to determine if we're building a raw
  2886. // literal or a cooked one.
  2887. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2888. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2889. /*AllowRaw*/true, /*AllowTemplate*/true,
  2890. /*AllowStringTemplate*/false)) {
  2891. case LOLR_Error:
  2892. return ExprError();
  2893. case LOLR_Cooked: {
  2894. Expr *Lit;
  2895. if (Literal.isFloatingLiteral()) {
  2896. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2897. } else {
  2898. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2899. if (Literal.GetIntegerValue(ResultVal))
  2900. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2901. << /* Unsigned */ 1;
  2902. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2903. Tok.getLocation());
  2904. }
  2905. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2906. }
  2907. case LOLR_Raw: {
  2908. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2909. // literal is treated as a call of the form
  2910. // operator "" X ("n")
  2911. unsigned Length = Literal.getUDSuffixOffset();
  2912. QualType StrTy = Context.getConstantArrayType(
  2913. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2914. ArrayType::Normal, 0);
  2915. Expr *Lit = StringLiteral::Create(
  2916. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2917. /*Pascal*/false, StrTy, &TokLoc, 1);
  2918. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2919. }
  2920. case LOLR_Template: {
  2921. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2922. // template), L is treated as a call fo the form
  2923. // operator "" X <'c1', 'c2', ... 'ck'>()
  2924. // where n is the source character sequence c1 c2 ... ck.
  2925. TemplateArgumentListInfo ExplicitArgs;
  2926. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2927. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2928. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2929. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2930. Value = TokSpelling[I];
  2931. TemplateArgument Arg(Context, Value, Context.CharTy);
  2932. TemplateArgumentLocInfo ArgInfo;
  2933. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2934. }
  2935. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2936. &ExplicitArgs);
  2937. }
  2938. case LOLR_StringTemplate:
  2939. llvm_unreachable("unexpected literal operator lookup result");
  2940. }
  2941. }
  2942. Expr *Res;
  2943. if (Literal.isFloatingLiteral()) {
  2944. QualType Ty;
  2945. if (Literal.isFloat)
  2946. Ty = Context.FloatTy;
  2947. // HLSL Change Starts
  2948. else if (getLangOpts().HLSL && !Literal.isLong && !Literal.isHalf)
  2949. Ty = Context.LitFloatTy;
  2950. else if (getLangOpts().HLSL && Literal.isLong)
  2951. Ty = Context.DoubleTy;
  2952. else if (getLangOpts().HLSL && Literal.isHalf) {
  2953. Ty = getLangOpts().UseMinPrecision ? Context.FloatTy : Context.HalfTy;
  2954. }
  2955. // HLSL Change Ends
  2956. else if (!Literal.isLong)
  2957. Ty = Context.DoubleTy;
  2958. else
  2959. Ty = Context.LongDoubleTy;
  2960. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2961. if (Ty == Context.DoubleTy) {
  2962. if (getLangOpts().SinglePrecisionConstants) {
  2963. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2964. } else if (getLangOpts().OpenCL &&
  2965. !((getLangOpts().OpenCLVersion >= 120) ||
  2966. getOpenCLOptions().cl_khr_fp64)) {
  2967. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2968. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2969. }
  2970. }
  2971. } else if (!Literal.isIntegerLiteral()) {
  2972. return ExprError();
  2973. // HLSL Change Starts
  2974. } else if (getLangOpts().HLSL) {
  2975. QualType Ty;
  2976. unsigned Width = 64;
  2977. llvm::APInt ResultVal(Width, 0);
  2978. if (!Literal.isLong && !Literal.isLongLong &&
  2979. !Literal.isUnsigned && Literal.getRadix() == 10) {
  2980. // in HLSL, unspecific literal ints are LitIntTy, using 64-bit
  2981. Ty = Context.LitIntTy;
  2982. if (Literal.GetIntegerValue(ResultVal)) {
  2983. // If this value didn't fit into 64-bit literal int, report error.
  2984. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  2985. }
  2986. } else {
  2987. if (Literal.GetIntegerValue(ResultVal)) {
  2988. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  2989. }
  2990. if (Literal.isLongLong) {
  2991. if (Literal.isUnsigned)
  2992. Ty = Context.UnsignedLongLongTy;
  2993. else
  2994. Ty = Context.LongLongTy;
  2995. }
  2996. else {
  2997. // long is the same as int for HLSL, so ignore isLong here
  2998. Width = 32;
  2999. ResultVal = ResultVal.trunc(Width);
  3000. if (Literal.isUnsigned || Literal.getRadix() != 10)
  3001. Ty = Context.UnsignedIntTy;
  3002. else
  3003. Ty = Context.IntTy;
  3004. }
  3005. }
  3006. return IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3007. // HLSL Change Ends
  3008. } else {
  3009. QualType Ty;
  3010. // 'long long' is a C99 or C++11 feature.
  3011. if (!getLangOpts().C99 && Literal.isLongLong) {
  3012. if (getLangOpts().CPlusPlus)
  3013. Diag(Tok.getLocation(),
  3014. getLangOpts().CPlusPlus11 ?
  3015. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3016. else
  3017. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3018. }
  3019. // Get the value in the widest-possible width.
  3020. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3021. // The microsoft literal suffix extensions support 128-bit literals, which
  3022. // may be wider than [u]intmax_t.
  3023. // FIXME: Actually, they don't. We seem to have accidentally invented the
  3024. // i128 suffix.
  3025. if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
  3026. Context.getTargetInfo().hasInt128Type())
  3027. MaxWidth = 128;
  3028. llvm::APInt ResultVal(MaxWidth, 0);
  3029. if (Literal.GetIntegerValue(ResultVal)) {
  3030. // If this value didn't fit into uintmax_t, error and force to ull.
  3031. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3032. << /* Unsigned */ 1;
  3033. Ty = Context.UnsignedLongLongTy;
  3034. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3035. "long long is not intmax_t?");
  3036. } else {
  3037. // If this value fits into a ULL, try to figure out what else it fits into
  3038. // according to the rules of C99 6.4.4.1p5.
  3039. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3040. // be an unsigned int.
  3041. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3042. // Check from smallest to largest, picking the smallest type we can.
  3043. unsigned Width = 0;
  3044. // Microsoft specific integer suffixes are explicitly sized.
  3045. if (Literal.MicrosoftInteger) {
  3046. if (Literal.MicrosoftInteger > MaxWidth) {
  3047. // If this target doesn't support __int128, error and force to ull.
  3048. Diag(Tok.getLocation(), diag::err_int128_unsupported);
  3049. Width = MaxWidth;
  3050. Ty = Context.getIntMaxType();
  3051. } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3052. Width = 8;
  3053. Ty = Context.CharTy;
  3054. } else {
  3055. Width = Literal.MicrosoftInteger;
  3056. Ty = Context.getIntTypeForBitwidth(Width,
  3057. /*Signed=*/!Literal.isUnsigned);
  3058. }
  3059. }
  3060. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3061. // Are int/unsigned possibilities?
  3062. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3063. // Does it fit in a unsigned int?
  3064. if (ResultVal.isIntN(IntSize)) {
  3065. // Does it fit in a signed int?
  3066. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3067. Ty = Context.IntTy;
  3068. else if (AllowUnsigned)
  3069. Ty = Context.UnsignedIntTy;
  3070. Width = IntSize;
  3071. }
  3072. }
  3073. // Are long/unsigned long possibilities?
  3074. if (Ty.isNull() && !Literal.isLongLong) {
  3075. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3076. // Does it fit in a unsigned long?
  3077. if (ResultVal.isIntN(LongSize)) {
  3078. // Does it fit in a signed long?
  3079. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3080. Ty = Context.LongTy;
  3081. else if (AllowUnsigned)
  3082. Ty = Context.UnsignedLongTy;
  3083. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3084. // is compatible.
  3085. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3086. const unsigned LongLongSize =
  3087. Context.getTargetInfo().getLongLongWidth();
  3088. Diag(Tok.getLocation(),
  3089. getLangOpts().CPlusPlus
  3090. ? Literal.isLong
  3091. ? diag::warn_old_implicitly_unsigned_long_cxx
  3092. : /*C++98 UB*/ diag::
  3093. ext_old_implicitly_unsigned_long_cxx
  3094. : diag::warn_old_implicitly_unsigned_long)
  3095. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3096. : /*will be ill-formed*/ 1);
  3097. Ty = Context.UnsignedLongTy;
  3098. }
  3099. Width = LongSize;
  3100. }
  3101. }
  3102. // Check long long if needed.
  3103. if (Ty.isNull()) {
  3104. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3105. // Does it fit in a unsigned long long?
  3106. if (ResultVal.isIntN(LongLongSize)) {
  3107. // Does it fit in a signed long long?
  3108. // To be compatible with MSVC, hex integer literals ending with the
  3109. // LL or i64 suffix are always signed in Microsoft mode.
  3110. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3111. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  3112. Ty = Context.LongLongTy;
  3113. else if (AllowUnsigned)
  3114. Ty = Context.UnsignedLongLongTy;
  3115. Width = LongLongSize;
  3116. }
  3117. }
  3118. // If we still couldn't decide a type, we probably have something that
  3119. // does not fit in a signed long long, but has no U suffix.
  3120. if (Ty.isNull()) {
  3121. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3122. Ty = Context.UnsignedLongLongTy;
  3123. Width = Context.getTargetInfo().getLongLongWidth();
  3124. }
  3125. if (ResultVal.getBitWidth() != Width)
  3126. ResultVal = ResultVal.trunc(Width);
  3127. }
  3128. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3129. }
  3130. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3131. if (Literal.isImaginary)
  3132. Res = new (Context) ImaginaryLiteral(Res,
  3133. Context.getComplexType(Res->getType()));
  3134. return Res;
  3135. }
  3136. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3137. assert(E && "ActOnParenExpr() missing expr");
  3138. return new (Context) ParenExpr(L, R, E);
  3139. }
  3140. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3141. SourceLocation Loc,
  3142. SourceRange ArgRange) {
  3143. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3144. // scalar or vector data type argument..."
  3145. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3146. // type (C99 6.2.5p18) or void.
  3147. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3148. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3149. << T << ArgRange;
  3150. return true;
  3151. }
  3152. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3153. "Scalar types should always be complete");
  3154. return false;
  3155. }
  3156. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3157. SourceLocation Loc,
  3158. SourceRange ArgRange,
  3159. UnaryExprOrTypeTrait TraitKind) {
  3160. // Invalid types must be hard errors for SFINAE in C++.
  3161. if (S.LangOpts.CPlusPlus)
  3162. return true;
  3163. // C99 6.5.3.4p1:
  3164. if (T->isFunctionType() &&
  3165. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3166. // sizeof(function)/alignof(function) is allowed as an extension.
  3167. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3168. << TraitKind << ArgRange;
  3169. return false;
  3170. }
  3171. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3172. // this is an error (OpenCL v1.1 s6.3.k)
  3173. if (T->isVoidType()) {
  3174. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3175. : diag::ext_sizeof_alignof_void_type;
  3176. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3177. return false;
  3178. }
  3179. return true;
  3180. }
  3181. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3182. SourceLocation Loc,
  3183. SourceRange ArgRange,
  3184. UnaryExprOrTypeTrait TraitKind) {
  3185. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3186. // runtime doesn't allow it.
  3187. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3188. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3189. << T << (TraitKind == UETT_SizeOf)
  3190. << ArgRange;
  3191. return true;
  3192. }
  3193. return false;
  3194. }
  3195. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3196. /// pointer type is equal to T) and emit a warning if it is.
  3197. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3198. Expr *E) {
  3199. // Don't warn if the operation changed the type.
  3200. if (T != E->getType())
  3201. return;
  3202. // Now look for array decays.
  3203. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3204. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3205. return;
  3206. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3207. << ICE->getType()
  3208. << ICE->getSubExpr()->getType();
  3209. }
  3210. /// \brief Check the constraints on expression operands to unary type expression
  3211. /// and type traits.
  3212. ///
  3213. /// Completes any types necessary and validates the constraints on the operand
  3214. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3215. /// the expression as it completes the type for that expression through template
  3216. /// instantiation, etc.
  3217. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3218. UnaryExprOrTypeTrait ExprKind) {
  3219. QualType ExprTy = E->getType();
  3220. assert(!ExprTy->isReferenceType());
  3221. if (ExprKind == UETT_VecStep)
  3222. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3223. E->getSourceRange());
  3224. // Whitelist some types as extensions
  3225. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3226. E->getSourceRange(), ExprKind))
  3227. return false;
  3228. // 'alignof' applied to an expression only requires the base element type of
  3229. // the expression to be complete. 'sizeof' requires the expression's type to
  3230. // be complete (and will attempt to complete it if it's an array of unknown
  3231. // bound).
  3232. if (ExprKind == UETT_AlignOf) {
  3233. if (RequireCompleteType(E->getExprLoc(),
  3234. Context.getBaseElementType(E->getType()),
  3235. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3236. E->getSourceRange()))
  3237. return true;
  3238. } else {
  3239. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3240. ExprKind, E->getSourceRange()))
  3241. return true;
  3242. }
  3243. // Completing the expression's type may have changed it.
  3244. ExprTy = E->getType();
  3245. assert(!ExprTy->isReferenceType());
  3246. if (ExprTy->isFunctionType()) {
  3247. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3248. << ExprKind << E->getSourceRange();
  3249. return true;
  3250. }
  3251. // The operand for sizeof and alignof is in an unevaluated expression context,
  3252. // so side effects could result in unintended consequences.
  3253. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3254. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3255. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3256. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3257. E->getSourceRange(), ExprKind))
  3258. return true;
  3259. if (ExprKind == UETT_SizeOf) {
  3260. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3261. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3262. QualType OType = PVD->getOriginalType();
  3263. QualType Type = PVD->getType();
  3264. if (Type->isPointerType() && OType->isArrayType()) {
  3265. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3266. << Type << OType;
  3267. Diag(PVD->getLocation(), diag::note_declared_at);
  3268. }
  3269. }
  3270. }
  3271. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3272. // decays into a pointer and returns an unintended result. This is most
  3273. // likely a typo for "sizeof(array) op x".
  3274. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3275. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3276. BO->getLHS());
  3277. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3278. BO->getRHS());
  3279. }
  3280. }
  3281. return false;
  3282. }
  3283. /// \brief Check the constraints on operands to unary expression and type
  3284. /// traits.
  3285. ///
  3286. /// This will complete any types necessary, and validate the various constraints
  3287. /// on those operands.
  3288. ///
  3289. /// The UsualUnaryConversions() function is *not* called by this routine.
  3290. /// C99 6.3.2.1p[2-4] all state:
  3291. /// Except when it is the operand of the sizeof operator ...
  3292. ///
  3293. /// C++ [expr.sizeof]p4
  3294. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3295. /// standard conversions are not applied to the operand of sizeof.
  3296. ///
  3297. /// This policy is followed for all of the unary trait expressions.
  3298. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3299. SourceLocation OpLoc,
  3300. SourceRange ExprRange,
  3301. UnaryExprOrTypeTrait ExprKind) {
  3302. if (ExprType->isDependentType())
  3303. return false;
  3304. // C++ [expr.sizeof]p2:
  3305. // When applied to a reference or a reference type, the result
  3306. // is the size of the referenced type.
  3307. // C++11 [expr.alignof]p3:
  3308. // When alignof is applied to a reference type, the result
  3309. // shall be the alignment of the referenced type.
  3310. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3311. ExprType = Ref->getPointeeType();
  3312. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3313. // When alignof or _Alignof is applied to an array type, the result
  3314. // is the alignment of the element type.
  3315. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3316. ExprType = Context.getBaseElementType(ExprType);
  3317. if (ExprKind == UETT_VecStep)
  3318. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3319. // Whitelist some types as extensions
  3320. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3321. ExprKind))
  3322. return false;
  3323. if (RequireCompleteType(OpLoc, ExprType,
  3324. diag::err_sizeof_alignof_incomplete_type,
  3325. ExprKind, ExprRange))
  3326. return true;
  3327. if (ExprType->isFunctionType()) {
  3328. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3329. << ExprKind << ExprRange;
  3330. return true;
  3331. }
  3332. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3333. ExprKind))
  3334. return true;
  3335. return false;
  3336. }
  3337. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3338. E = E->IgnoreParens();
  3339. // Cannot know anything else if the expression is dependent.
  3340. if (E->isTypeDependent())
  3341. return false;
  3342. if (E->getObjectKind() == OK_BitField) {
  3343. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3344. << 1 << E->getSourceRange();
  3345. return true;
  3346. }
  3347. ValueDecl *D = nullptr;
  3348. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3349. D = DRE->getDecl();
  3350. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3351. D = ME->getMemberDecl();
  3352. }
  3353. // If it's a field, require the containing struct to have a
  3354. // complete definition so that we can compute the layout.
  3355. //
  3356. // This can happen in C++11 onwards, either by naming the member
  3357. // in a way that is not transformed into a member access expression
  3358. // (in an unevaluated operand, for instance), or by naming the member
  3359. // in a trailing-return-type.
  3360. //
  3361. // For the record, since __alignof__ on expressions is a GCC
  3362. // extension, GCC seems to permit this but always gives the
  3363. // nonsensical answer 0.
  3364. //
  3365. // We don't really need the layout here --- we could instead just
  3366. // directly check for all the appropriate alignment-lowing
  3367. // attributes --- but that would require duplicating a lot of
  3368. // logic that just isn't worth duplicating for such a marginal
  3369. // use-case.
  3370. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3371. // Fast path this check, since we at least know the record has a
  3372. // definition if we can find a member of it.
  3373. if (!FD->getParent()->isCompleteDefinition()) {
  3374. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3375. << E->getSourceRange();
  3376. return true;
  3377. }
  3378. // Otherwise, if it's a field, and the field doesn't have
  3379. // reference type, then it must have a complete type (or be a
  3380. // flexible array member, which we explicitly want to
  3381. // white-list anyway), which makes the following checks trivial.
  3382. if (!FD->getType()->isReferenceType())
  3383. return false;
  3384. }
  3385. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3386. }
  3387. bool Sema::CheckVecStepExpr(Expr *E) {
  3388. E = E->IgnoreParens();
  3389. // Cannot know anything else if the expression is dependent.
  3390. if (E->isTypeDependent())
  3391. return false;
  3392. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3393. }
  3394. /// \brief Build a sizeof or alignof expression given a type operand.
  3395. ExprResult
  3396. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3397. SourceLocation OpLoc,
  3398. UnaryExprOrTypeTrait ExprKind,
  3399. SourceRange R) {
  3400. if (!TInfo)
  3401. return ExprError();
  3402. QualType T = TInfo->getType();
  3403. if (!T->isDependentType() &&
  3404. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3405. return ExprError();
  3406. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3407. return new (Context) UnaryExprOrTypeTraitExpr(
  3408. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3409. }
  3410. /// \brief Build a sizeof or alignof expression given an expression
  3411. /// operand.
  3412. ExprResult
  3413. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3414. UnaryExprOrTypeTrait ExprKind) {
  3415. ExprResult PE = CheckPlaceholderExpr(E);
  3416. if (PE.isInvalid())
  3417. return ExprError();
  3418. E = PE.get();
  3419. // Verify that the operand is valid.
  3420. bool isInvalid = false;
  3421. if (E->isTypeDependent()) {
  3422. // Delay type-checking for type-dependent expressions.
  3423. } else if (ExprKind == UETT_AlignOf) {
  3424. isInvalid = CheckAlignOfExpr(*this, E);
  3425. } else if (ExprKind == UETT_VecStep) {
  3426. isInvalid = CheckVecStepExpr(E);
  3427. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3428. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3429. isInvalid = true;
  3430. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3431. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3432. isInvalid = true;
  3433. } else {
  3434. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3435. }
  3436. if (isInvalid)
  3437. return ExprError();
  3438. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3439. PE = TransformToPotentiallyEvaluated(E);
  3440. if (PE.isInvalid()) return ExprError();
  3441. E = PE.get();
  3442. }
  3443. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3444. return new (Context) UnaryExprOrTypeTraitExpr(
  3445. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3446. }
  3447. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3448. /// expr and the same for @c alignof and @c __alignof
  3449. /// Note that the ArgRange is invalid if isType is false.
  3450. ExprResult
  3451. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3452. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3453. void *TyOrEx, const SourceRange &ArgRange) {
  3454. // If error parsing type, ignore.
  3455. if (!TyOrEx) return ExprError();
  3456. if (IsType) {
  3457. TypeSourceInfo *TInfo;
  3458. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3459. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3460. }
  3461. Expr *ArgEx = (Expr *)TyOrEx;
  3462. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3463. return Result;
  3464. }
  3465. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3466. bool IsReal) {
  3467. if (V.get()->isTypeDependent())
  3468. return S.Context.DependentTy;
  3469. // _Real and _Imag are only l-values for normal l-values.
  3470. if (V.get()->getObjectKind() != OK_Ordinary) {
  3471. V = S.DefaultLvalueConversion(V.get());
  3472. if (V.isInvalid())
  3473. return QualType();
  3474. }
  3475. // These operators return the element type of a complex type.
  3476. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3477. return CT->getElementType();
  3478. // Otherwise they pass through real integer and floating point types here.
  3479. if (V.get()->getType()->isArithmeticType())
  3480. return V.get()->getType();
  3481. // Test for placeholders.
  3482. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3483. if (PR.isInvalid()) return QualType();
  3484. if (PR.get() != V.get()) {
  3485. V = PR;
  3486. return CheckRealImagOperand(S, V, Loc, IsReal);
  3487. }
  3488. // Reject anything else.
  3489. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3490. << (IsReal ? "__real" : "__imag");
  3491. return QualType();
  3492. }
  3493. ExprResult
  3494. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3495. tok::TokenKind Kind, Expr *Input) {
  3496. UnaryOperatorKind Opc;
  3497. switch (Kind) {
  3498. default: llvm_unreachable("Unknown unary op!");
  3499. case tok::plusplus: Opc = UO_PostInc; break;
  3500. case tok::minusminus: Opc = UO_PostDec; break;
  3501. }
  3502. // Since this might is a postfix expression, get rid of ParenListExprs.
  3503. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3504. if (Result.isInvalid()) return ExprError();
  3505. Input = Result.get();
  3506. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3507. }
  3508. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3509. ///
  3510. /// \return true on error
  3511. static bool checkArithmeticOnObjCPointer(Sema &S,
  3512. SourceLocation opLoc,
  3513. Expr *op) {
  3514. assert(op->getType()->isObjCObjectPointerType());
  3515. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3516. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3517. return false;
  3518. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3519. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3520. << op->getSourceRange();
  3521. return true;
  3522. }
  3523. ExprResult
  3524. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3525. Expr *idx, SourceLocation rbLoc) {
  3526. // Since this might be a postfix expression, get rid of ParenListExprs.
  3527. if (isa<ParenListExpr>(base)) {
  3528. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3529. if (result.isInvalid()) return ExprError();
  3530. base = result.get();
  3531. }
  3532. // Handle any non-overload placeholder types in the base and index
  3533. // expressions. We can't handle overloads here because the other
  3534. // operand might be an overloadable type, in which case the overload
  3535. // resolution for the operator overload should get the first crack
  3536. // at the overload.
  3537. if (base->getType()->isNonOverloadPlaceholderType()) {
  3538. ExprResult result = CheckPlaceholderExpr(base);
  3539. if (result.isInvalid()) return ExprError();
  3540. base = result.get();
  3541. }
  3542. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3543. ExprResult result = CheckPlaceholderExpr(idx);
  3544. if (result.isInvalid()) return ExprError();
  3545. idx = result.get();
  3546. }
  3547. // Build an unanalyzed expression if either operand is type-dependent.
  3548. if (getLangOpts().CPlusPlus &&
  3549. (base->isTypeDependent() || idx->isTypeDependent())) {
  3550. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3551. VK_LValue, OK_Ordinary, rbLoc);
  3552. }
  3553. // Use C++ overloaded-operator rules if either operand has record
  3554. // type. The spec says to do this if either type is *overloadable*,
  3555. // but enum types can't declare subscript operators or conversion
  3556. // operators, so there's nothing interesting for overload resolution
  3557. // to do if there aren't any record types involved.
  3558. //
  3559. // ObjC pointers have their own subscripting logic that is not tied
  3560. // to overload resolution and so should not take this path.
  3561. if (getLangOpts().CPlusPlus &&
  3562. (base->getType()->isRecordType() ||
  3563. (!base->getType()->isObjCObjectPointerType() &&
  3564. idx->getType()->isRecordType()))) {
  3565. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3566. }
  3567. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3568. }
  3569. ExprResult
  3570. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3571. Expr *Idx, SourceLocation RLoc) {
  3572. Expr *LHSExp = Base;
  3573. Expr *RHSExp = Idx;
  3574. // Perform default conversions.
  3575. if (!LHSExp->getType()->getAs<VectorType>()) {
  3576. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3577. if (Result.isInvalid())
  3578. return ExprError();
  3579. LHSExp = Result.get();
  3580. }
  3581. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3582. if (Result.isInvalid())
  3583. return ExprError();
  3584. RHSExp = Result.get();
  3585. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3586. ExprValueKind VK = VK_LValue;
  3587. ExprObjectKind OK = OK_Ordinary;
  3588. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3589. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3590. // in the subscript position. As a result, we need to derive the array base
  3591. // and index from the expression types.
  3592. Expr *BaseExpr, *IndexExpr;
  3593. QualType ResultType;
  3594. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3595. BaseExpr = LHSExp;
  3596. IndexExpr = RHSExp;
  3597. ResultType = Context.DependentTy;
  3598. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3599. BaseExpr = LHSExp;
  3600. IndexExpr = RHSExp;
  3601. ResultType = PTy->getPointeeType();
  3602. } else if (const ObjCObjectPointerType *PTy =
  3603. LHSTy->getAs<ObjCObjectPointerType>()) {
  3604. BaseExpr = LHSExp;
  3605. IndexExpr = RHSExp;
  3606. // Use custom logic if this should be the pseudo-object subscript
  3607. // expression.
  3608. if (!LangOpts.isSubscriptPointerArithmetic())
  3609. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3610. nullptr);
  3611. ResultType = PTy->getPointeeType();
  3612. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3613. // Handle the uncommon case of "123[Ptr]".
  3614. BaseExpr = RHSExp;
  3615. IndexExpr = LHSExp;
  3616. ResultType = PTy->getPointeeType();
  3617. } else if (const ObjCObjectPointerType *PTy =
  3618. RHSTy->getAs<ObjCObjectPointerType>()) {
  3619. // Handle the uncommon case of "123[Ptr]".
  3620. BaseExpr = RHSExp;
  3621. IndexExpr = LHSExp;
  3622. ResultType = PTy->getPointeeType();
  3623. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3624. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3625. << ResultType << BaseExpr->getSourceRange();
  3626. return ExprError();
  3627. }
  3628. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3629. BaseExpr = LHSExp; // vectors: V[123]
  3630. IndexExpr = RHSExp;
  3631. VK = LHSExp->getValueKind();
  3632. if (VK != VK_RValue)
  3633. OK = OK_VectorComponent;
  3634. // FIXME: need to deal with const...
  3635. ResultType = VTy->getElementType();
  3636. } else if (LHSTy->isArrayType()) {
  3637. // If we see an array that wasn't promoted by
  3638. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3639. // wasn't promoted because of the C90 rule that doesn't
  3640. // allow promoting non-lvalue arrays. Warn, then
  3641. // force the promotion here.
  3642. // HLSL Change Starts - arrays won't decay
  3643. if (getLangOpts().HLSL) {
  3644. BaseExpr = LHSExp;
  3645. IndexExpr = RHSExp;
  3646. ResultType = LHSTy->getAsArrayTypeUnsafe()->getElementType();
  3647. } else {
  3648. // HLSL Change Ends
  3649. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3650. LHSExp->getSourceRange();
  3651. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3652. CK_ArrayToPointerDecay).get();
  3653. LHSTy = LHSExp->getType();
  3654. BaseExpr = LHSExp;
  3655. IndexExpr = RHSExp;
  3656. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3657. } // HLSL Change - end else block
  3658. } else if (RHSTy->isArrayType()) {
  3659. // Same as previous, except for 123[f().a] case
  3660. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3661. RHSExp->getSourceRange();
  3662. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3663. CK_ArrayToPointerDecay).get();
  3664. RHSTy = RHSExp->getType();
  3665. BaseExpr = RHSExp;
  3666. IndexExpr = LHSExp;
  3667. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3668. } else {
  3669. // HLSL Change: use HLSL variation of error message
  3670. return ExprError(Diag(LLoc, getLangOpts().HLSL ? diag::err_hlsl_typecheck_subscript_value : diag::err_typecheck_subscript_value)
  3671. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3672. }
  3673. // HLSL Change Starts
  3674. if (getLangOpts().HLSL && BaseExpr != LHSExp) {
  3675. Diag(RHSExp->getLocStart(), diag::err_hlsl_unsupported_subscript_base_rhs);
  3676. }
  3677. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent() &&
  3678. IndexExpr->getType()->isFloatingType()) {
  3679. IndexExpr = ImpCastExprToType(IndexExpr, Context.UnsignedIntTy,
  3680. CK_FloatingToIntegral).get();
  3681. }
  3682. // HLSL Change Ends
  3683. // C99 6.5.2.1p1
  3684. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3685. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3686. << IndexExpr->getSourceRange());
  3687. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3688. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3689. && !IndexExpr->isTypeDependent())
  3690. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3691. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3692. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3693. // type. Note that Functions are not objects, and that (in C99 parlance)
  3694. // incomplete types are not object types.
  3695. if (ResultType->isFunctionType()) {
  3696. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3697. << ResultType << BaseExpr->getSourceRange();
  3698. return ExprError();
  3699. }
  3700. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3701. // GNU extension: subscripting on pointer to void
  3702. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3703. << BaseExpr->getSourceRange();
  3704. // C forbids expressions of unqualified void type from being l-values.
  3705. // See IsCForbiddenLValueType.
  3706. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3707. } else if (!ResultType->isDependentType() &&
  3708. RequireCompleteType(LLoc, ResultType,
  3709. diag::err_subscript_incomplete_type, BaseExpr))
  3710. return ExprError();
  3711. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3712. !ResultType.isCForbiddenLValueType());
  3713. if (getLangOpts().HLSL) RHSExp = IndexExpr; // HLSL Change - refer to right-hands side as indexer
  3714. return new (Context)
  3715. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3716. }
  3717. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3718. FunctionDecl *FD,
  3719. ParmVarDecl *Param) {
  3720. if (Param->hasUnparsedDefaultArg()) {
  3721. Diag(CallLoc,
  3722. diag::err_use_of_default_argument_to_function_declared_later) <<
  3723. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3724. Diag(UnparsedDefaultArgLocs[Param],
  3725. diag::note_default_argument_declared_here);
  3726. return ExprError();
  3727. }
  3728. if (Param->hasUninstantiatedDefaultArg()) {
  3729. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3730. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3731. Param);
  3732. // Instantiate the expression.
  3733. MultiLevelTemplateArgumentList MutiLevelArgList
  3734. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3735. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3736. MutiLevelArgList.getInnermost());
  3737. if (Inst.isInvalid())
  3738. return ExprError();
  3739. ExprResult Result;
  3740. {
  3741. // C++ [dcl.fct.default]p5:
  3742. // The names in the [default argument] expression are bound, and
  3743. // the semantic constraints are checked, at the point where the
  3744. // default argument expression appears.
  3745. ContextRAII SavedContext(*this, FD);
  3746. LocalInstantiationScope Local(*this);
  3747. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3748. }
  3749. if (Result.isInvalid())
  3750. return ExprError();
  3751. // Check the expression as an initializer for the parameter.
  3752. InitializedEntity Entity
  3753. = InitializedEntity::InitializeParameter(Context, Param);
  3754. InitializationKind Kind
  3755. = InitializationKind::CreateCopy(Param->getLocation(),
  3756. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3757. Expr *ResultE = Result.getAs<Expr>();
  3758. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3759. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3760. if (Result.isInvalid())
  3761. return ExprError();
  3762. Expr *Arg = Result.getAs<Expr>();
  3763. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3764. // Build the default argument expression.
  3765. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3766. }
  3767. // If the default expression creates temporaries, we need to
  3768. // push them to the current stack of expression temporaries so they'll
  3769. // be properly destroyed.
  3770. // FIXME: We should really be rebuilding the default argument with new
  3771. // bound temporaries; see the comment in PR5810.
  3772. // We don't need to do that with block decls, though, because
  3773. // blocks in default argument expression can never capture anything.
  3774. if (isa<ExprWithCleanups>(Param->getInit())) {
  3775. // Set the "needs cleanups" bit regardless of whether there are
  3776. // any explicit objects.
  3777. ExprNeedsCleanups = true;
  3778. // Append all the objects to the cleanup list. Right now, this
  3779. // should always be a no-op, because blocks in default argument
  3780. // expressions should never be able to capture anything.
  3781. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3782. "default argument expression has capturing blocks?");
  3783. }
  3784. // We already type-checked the argument, so we know it works.
  3785. // Just mark all of the declarations in this potentially-evaluated expression
  3786. // as being "referenced".
  3787. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3788. /*SkipLocalVariables=*/true);
  3789. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3790. }
  3791. Sema::VariadicCallType
  3792. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3793. Expr *Fn) {
  3794. if (Proto && Proto->isVariadic()) {
  3795. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3796. return VariadicConstructor;
  3797. else if (Fn && Fn->getType()->isBlockPointerType())
  3798. return VariadicBlock;
  3799. else if (FDecl) {
  3800. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3801. if (Method->isInstance())
  3802. return VariadicMethod;
  3803. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3804. return VariadicMethod;
  3805. return VariadicFunction;
  3806. }
  3807. return VariadicDoesNotApply;
  3808. }
  3809. namespace {
  3810. class FunctionCallCCC : public FunctionCallFilterCCC {
  3811. public:
  3812. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3813. unsigned NumArgs, MemberExpr *ME)
  3814. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3815. FunctionName(FuncName) {}
  3816. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3817. if (!candidate.getCorrectionSpecifier() ||
  3818. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3819. return false;
  3820. }
  3821. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3822. }
  3823. private:
  3824. const IdentifierInfo *const FunctionName;
  3825. };
  3826. }
  3827. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3828. FunctionDecl *FDecl,
  3829. ArrayRef<Expr *> Args) {
  3830. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3831. DeclarationName FuncName = FDecl->getDeclName();
  3832. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3833. if (TypoCorrection Corrected = S.CorrectTypo(
  3834. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3835. S.getScopeForContext(S.CurContext), nullptr,
  3836. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3837. Args.size(), ME),
  3838. Sema::CTK_ErrorRecovery)) {
  3839. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3840. if (Corrected.isOverloaded()) {
  3841. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3842. OverloadCandidateSet::iterator Best;
  3843. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3844. CDEnd = Corrected.end();
  3845. CD != CDEnd; ++CD) {
  3846. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3847. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3848. OCS);
  3849. }
  3850. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3851. case OR_Success:
  3852. ND = Best->Function;
  3853. Corrected.setCorrectionDecl(ND);
  3854. break;
  3855. default:
  3856. break;
  3857. }
  3858. }
  3859. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3860. return Corrected;
  3861. }
  3862. }
  3863. }
  3864. return TypoCorrection();
  3865. }
  3866. /// ConvertArgumentsForCall - Converts the arguments specified in
  3867. /// Args/NumArgs to the parameter types of the function FDecl with
  3868. /// function prototype Proto. Call is the call expression itself, and
  3869. /// Fn is the function expression. For a C++ member function, this
  3870. /// routine does not attempt to convert the object argument. Returns
  3871. /// true if the call is ill-formed.
  3872. bool
  3873. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3874. FunctionDecl *FDecl,
  3875. const FunctionProtoType *Proto,
  3876. ArrayRef<Expr *> Args,
  3877. SourceLocation RParenLoc,
  3878. bool IsExecConfig) {
  3879. // Bail out early if calling a builtin with custom typechecking.
  3880. if (FDecl)
  3881. if (unsigned ID = FDecl->getBuiltinID())
  3882. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3883. return false;
  3884. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3885. // assignment, to the types of the corresponding parameter, ...
  3886. unsigned NumParams = Proto->getNumParams();
  3887. bool Invalid = false;
  3888. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3889. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3890. ? 1 /* block */
  3891. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3892. : 0 /* function */);
  3893. // If too few arguments are available (and we don't have default
  3894. // arguments for the remaining parameters), don't make the call.
  3895. if (Args.size() < NumParams) {
  3896. if (Args.size() < MinArgs) {
  3897. TypoCorrection TC;
  3898. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3899. unsigned diag_id =
  3900. MinArgs == NumParams && !Proto->isVariadic()
  3901. ? diag::err_typecheck_call_too_few_args_suggest
  3902. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3903. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3904. << static_cast<unsigned>(Args.size())
  3905. << TC.getCorrectionRange());
  3906. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3907. Diag(RParenLoc,
  3908. MinArgs == NumParams && !Proto->isVariadic()
  3909. ? diag::err_typecheck_call_too_few_args_one
  3910. : diag::err_typecheck_call_too_few_args_at_least_one)
  3911. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3912. else
  3913. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3914. ? diag::err_typecheck_call_too_few_args
  3915. : diag::err_typecheck_call_too_few_args_at_least)
  3916. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3917. << Fn->getSourceRange();
  3918. // Emit the location of the prototype.
  3919. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3920. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3921. << FDecl;
  3922. return true;
  3923. }
  3924. Call->setNumArgs(Context, NumParams);
  3925. }
  3926. // If too many are passed and not variadic, error on the extras and drop
  3927. // them.
  3928. if (Args.size() > NumParams) {
  3929. if (!Proto->isVariadic()) {
  3930. TypoCorrection TC;
  3931. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3932. unsigned diag_id =
  3933. MinArgs == NumParams && !Proto->isVariadic()
  3934. ? diag::err_typecheck_call_too_many_args_suggest
  3935. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3936. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3937. << static_cast<unsigned>(Args.size())
  3938. << TC.getCorrectionRange());
  3939. } else if (NumParams == 1 && FDecl &&
  3940. FDecl->getParamDecl(0)->getDeclName())
  3941. Diag(Args[NumParams]->getLocStart(),
  3942. MinArgs == NumParams
  3943. ? diag::err_typecheck_call_too_many_args_one
  3944. : diag::err_typecheck_call_too_many_args_at_most_one)
  3945. << FnKind << FDecl->getParamDecl(0)
  3946. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  3947. << SourceRange(Args[NumParams]->getLocStart(),
  3948. Args.back()->getLocEnd());
  3949. else
  3950. Diag(Args[NumParams]->getLocStart(),
  3951. MinArgs == NumParams
  3952. ? diag::err_typecheck_call_too_many_args
  3953. : diag::err_typecheck_call_too_many_args_at_most)
  3954. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  3955. << Fn->getSourceRange()
  3956. << SourceRange(Args[NumParams]->getLocStart(),
  3957. Args.back()->getLocEnd());
  3958. // Emit the location of the prototype.
  3959. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3960. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3961. << FDecl;
  3962. // This deletes the extra arguments.
  3963. Call->setNumArgs(Context, NumParams);
  3964. return true;
  3965. }
  3966. }
  3967. SmallVector<Expr *, 8> AllArgs;
  3968. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3969. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3970. Proto, 0, Args, AllArgs, CallType);
  3971. if (Invalid)
  3972. return true;
  3973. unsigned TotalNumArgs = AllArgs.size();
  3974. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3975. Call->setArg(i, AllArgs[i]);
  3976. return false;
  3977. }
  3978. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  3979. const FunctionProtoType *Proto,
  3980. unsigned FirstParam, ArrayRef<Expr *> Args,
  3981. SmallVectorImpl<Expr *> &AllArgs,
  3982. VariadicCallType CallType, bool AllowExplicit,
  3983. bool IsListInitialization) {
  3984. unsigned NumParams = Proto->getNumParams();
  3985. bool Invalid = false;
  3986. unsigned ArgIx = 0;
  3987. // Continue to check argument types (even if we have too few/many args).
  3988. for (unsigned i = FirstParam; i < NumParams; i++) {
  3989. QualType ProtoArgType = Proto->getParamType(i);
  3990. Expr *Arg;
  3991. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  3992. if (ArgIx < Args.size()) {
  3993. Arg = Args[ArgIx++];
  3994. if (!(getLangOpts().HLSL && ProtoArgType->isIncompleteArrayType()) && // HLSL Change: allow incomplete array
  3995. RequireCompleteType(Arg->getLocStart(),
  3996. ProtoArgType,
  3997. diag::err_call_incomplete_argument, Arg))
  3998. return true;
  3999. // Strip the unbridged-cast placeholder expression off, if applicable.
  4000. bool CFAudited = false;
  4001. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4002. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4003. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4004. Arg = stripARCUnbridgedCast(Arg);
  4005. else if (getLangOpts().ObjCAutoRefCount &&
  4006. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4007. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4008. CFAudited = true;
  4009. InitializedEntity Entity =
  4010. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4011. ProtoArgType)
  4012. : InitializedEntity::InitializeParameter(
  4013. Context, ProtoArgType, Proto->isParamConsumed(i));
  4014. // Remember that parameter belongs to a CF audited API.
  4015. if (CFAudited)
  4016. Entity.setParameterCFAudited();
  4017. ExprResult ArgE = PerformCopyInitialization(
  4018. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4019. if (ArgE.isInvalid())
  4020. return true;
  4021. Arg = ArgE.getAs<Expr>();
  4022. } else {
  4023. assert(Param && "can't use default arguments without a known callee");
  4024. ExprResult ArgExpr =
  4025. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4026. if (ArgExpr.isInvalid())
  4027. return true;
  4028. Arg = ArgExpr.getAs<Expr>();
  4029. }
  4030. // Check for array bounds violations for each argument to the call. This
  4031. // check only triggers warnings when the argument isn't a more complex Expr
  4032. // with its own checking, such as a BinaryOperator.
  4033. CheckArrayAccess(Arg);
  4034. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4035. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4036. AllArgs.push_back(Arg);
  4037. }
  4038. // If this is a variadic call, handle args passed through "...".
  4039. if (CallType != VariadicDoesNotApply) {
  4040. // Assume that extern "C" functions with variadic arguments that
  4041. // return __unknown_anytype aren't *really* variadic.
  4042. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4043. FDecl->isExternC()) {
  4044. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4045. QualType paramType; // ignored
  4046. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  4047. Invalid |= arg.isInvalid();
  4048. AllArgs.push_back(arg.get());
  4049. }
  4050. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4051. } else {
  4052. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4053. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  4054. FDecl);
  4055. Invalid |= Arg.isInvalid();
  4056. AllArgs.push_back(Arg.get());
  4057. }
  4058. }
  4059. // Check for array bounds violations.
  4060. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  4061. CheckArrayAccess(Args[i]);
  4062. }
  4063. return Invalid;
  4064. }
  4065. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4066. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4067. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4068. TL = DTL.getOriginalLoc();
  4069. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4070. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4071. << ATL.getLocalSourceRange();
  4072. }
  4073. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4074. /// array parameter, check that it is non-null, and that if it is formed by
  4075. /// array-to-pointer decay, the underlying array is sufficiently large.
  4076. ///
  4077. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4078. /// array type derivation, then for each call to the function, the value of the
  4079. /// corresponding actual argument shall provide access to the first element of
  4080. /// an array with at least as many elements as specified by the size expression.
  4081. void
  4082. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4083. ParmVarDecl *Param,
  4084. const Expr *ArgExpr) {
  4085. // Static array parameters are not supported in C++.
  4086. if (!Param || getLangOpts().CPlusPlus)
  4087. return;
  4088. QualType OrigTy = Param->getOriginalType();
  4089. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4090. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4091. return;
  4092. if (ArgExpr->isNullPointerConstant(Context,
  4093. Expr::NPC_NeverValueDependent)) {
  4094. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4095. DiagnoseCalleeStaticArrayParam(*this, Param);
  4096. return;
  4097. }
  4098. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4099. if (!CAT)
  4100. return;
  4101. const ConstantArrayType *ArgCAT =
  4102. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4103. if (!ArgCAT)
  4104. return;
  4105. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4106. Diag(CallLoc, diag::warn_static_array_too_small)
  4107. << ArgExpr->getSourceRange()
  4108. << (unsigned) ArgCAT->getSize().getZExtValue()
  4109. << (unsigned) CAT->getSize().getZExtValue();
  4110. DiagnoseCalleeStaticArrayParam(*this, Param);
  4111. }
  4112. }
  4113. /// Given a function expression of unknown-any type, try to rebuild it
  4114. /// to have a function type.
  4115. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4116. /// Is the given type a placeholder that we need to lower out
  4117. /// immediately during argument processing?
  4118. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4119. // Placeholders are never sugared.
  4120. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4121. if (!placeholder) return false;
  4122. switch (placeholder->getKind()) {
  4123. // Ignore all the non-placeholder types.
  4124. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4125. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4126. #include "clang/AST/BuiltinTypes.def"
  4127. return false;
  4128. // We cannot lower out overload sets; they might validly be resolved
  4129. // by the call machinery.
  4130. case BuiltinType::Overload:
  4131. return false;
  4132. // Unbridged casts in ARC can be handled in some call positions and
  4133. // should be left in place.
  4134. case BuiltinType::ARCUnbridgedCast:
  4135. return false;
  4136. // Pseudo-objects should be converted as soon as possible.
  4137. case BuiltinType::PseudoObject:
  4138. return true;
  4139. // The debugger mode could theoretically but currently does not try
  4140. // to resolve unknown-typed arguments based on known parameter types.
  4141. case BuiltinType::UnknownAny:
  4142. return true;
  4143. // These are always invalid as call arguments and should be reported.
  4144. case BuiltinType::BoundMember:
  4145. case BuiltinType::BuiltinFn:
  4146. return true;
  4147. }
  4148. llvm_unreachable("bad builtin type kind");
  4149. }
  4150. /// Check an argument list for placeholders that we won't try to
  4151. /// handle later.
  4152. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4153. // Apply this processing to all the arguments at once instead of
  4154. // dying at the first failure.
  4155. bool hasInvalid = false;
  4156. for (size_t i = 0, e = args.size(); i != e; i++) {
  4157. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4158. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4159. if (result.isInvalid()) hasInvalid = true;
  4160. else args[i] = result.get();
  4161. } else if (hasInvalid) {
  4162. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4163. }
  4164. }
  4165. return hasInvalid;
  4166. }
  4167. /// If a builtin function has a pointer argument with no explicit address
  4168. /// space, than it should be able to accept a pointer to any address
  4169. /// space as input. In order to do this, we need to replace the
  4170. /// standard builtin declaration with one that uses the same address space
  4171. /// as the call.
  4172. ///
  4173. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4174. /// it does not contain any pointer arguments without
  4175. /// an address space qualifer. Otherwise the rewritten
  4176. /// FunctionDecl is returned.
  4177. /// TODO: Handle pointer return types.
  4178. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4179. const FunctionDecl *FDecl,
  4180. MultiExprArg ArgExprs) {
  4181. QualType DeclType = FDecl->getType();
  4182. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4183. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4184. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4185. return nullptr;
  4186. bool NeedsNewDecl = false;
  4187. unsigned i = 0;
  4188. SmallVector<QualType, 8> OverloadParams;
  4189. for (QualType ParamType : FT->param_types()) {
  4190. // Convert array arguments to pointer to simplify type lookup.
  4191. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4192. QualType ArgType = Arg->getType();
  4193. if (!ParamType->isPointerType() ||
  4194. ParamType.getQualifiers().hasAddressSpace() ||
  4195. !ArgType->isPointerType() ||
  4196. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4197. OverloadParams.push_back(ParamType);
  4198. continue;
  4199. }
  4200. NeedsNewDecl = true;
  4201. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4202. QualType PointeeType = ParamType->getPointeeType();
  4203. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4204. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4205. }
  4206. if (!NeedsNewDecl)
  4207. return nullptr;
  4208. FunctionProtoType::ExtProtoInfo EPI;
  4209. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4210. OverloadParams, EPI,
  4211. FT->getParamMods()); // HLSL Change
  4212. DeclContext *Parent = Context.getTranslationUnitDecl();
  4213. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4214. FDecl->getLocation(),
  4215. FDecl->getLocation(),
  4216. FDecl->getIdentifier(),
  4217. OverloadTy,
  4218. /*TInfo=*/nullptr,
  4219. SC_Extern, false,
  4220. /*hasPrototype=*/true);
  4221. SmallVector<ParmVarDecl*, 16> Params;
  4222. FT = cast<FunctionProtoType>(OverloadTy);
  4223. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4224. QualType ParamType = FT->getParamType(i);
  4225. ParmVarDecl *Parm =
  4226. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4227. SourceLocation(), nullptr, ParamType,
  4228. /*TInfo=*/nullptr, SC_None, nullptr);
  4229. Parm->setScopeInfo(0, i);
  4230. Params.push_back(Parm);
  4231. }
  4232. OverloadDecl->setParams(Params);
  4233. return OverloadDecl;
  4234. }
  4235. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4236. /// This provides the location of the left/right parens and a list of comma
  4237. /// locations.
  4238. ExprResult
  4239. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4240. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4241. Expr *ExecConfig, bool IsExecConfig) {
  4242. // Since this might be a postfix expression, get rid of ParenListExprs.
  4243. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4244. if (Result.isInvalid()) return ExprError();
  4245. Fn = Result.get();
  4246. if (checkArgsForPlaceholders(*this, ArgExprs))
  4247. return ExprError();
  4248. if (getLangOpts().CPlusPlus) {
  4249. // If this is a pseudo-destructor expression, build the call immediately.
  4250. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4251. if (!ArgExprs.empty()) {
  4252. // Pseudo-destructor calls should not have any arguments.
  4253. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4254. << FixItHint::CreateRemoval(
  4255. SourceRange(ArgExprs[0]->getLocStart(),
  4256. ArgExprs.back()->getLocEnd()));
  4257. }
  4258. return new (Context)
  4259. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4260. }
  4261. if (Fn->getType() == Context.PseudoObjectTy) {
  4262. ExprResult result = CheckPlaceholderExpr(Fn);
  4263. if (result.isInvalid()) return ExprError();
  4264. Fn = result.get();
  4265. }
  4266. // Determine whether this is a dependent call inside a C++ template,
  4267. // in which case we won't do any semantic analysis now.
  4268. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4269. // Fn.
  4270. bool Dependent = false;
  4271. if (Fn->isTypeDependent())
  4272. Dependent = true;
  4273. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4274. Dependent = true;
  4275. if (Dependent) {
  4276. if (ExecConfig) {
  4277. return new (Context) CUDAKernelCallExpr(
  4278. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4279. Context.DependentTy, VK_RValue, RParenLoc);
  4280. } else {
  4281. return new (Context) CallExpr(
  4282. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4283. }
  4284. }
  4285. // Determine whether this is a call to an object (C++ [over.call.object]).
  4286. if (Fn->getType()->isRecordType())
  4287. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4288. RParenLoc);
  4289. if (Fn->getType() == Context.UnknownAnyTy) {
  4290. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4291. if (result.isInvalid()) return ExprError();
  4292. Fn = result.get();
  4293. }
  4294. if (Fn->getType() == Context.BoundMemberTy) {
  4295. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4296. }
  4297. }
  4298. // Check for overloaded calls. This can happen even in C due to extensions.
  4299. if (Fn->getType() == Context.OverloadTy) {
  4300. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4301. // We aren't supposed to apply this logic for if there's an '&' involved.
  4302. if (!find.HasFormOfMemberPointer) {
  4303. OverloadExpr *ovl = find.Expression;
  4304. if (isa<UnresolvedLookupExpr>(ovl)) {
  4305. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4306. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4307. RParenLoc, ExecConfig);
  4308. } else {
  4309. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4310. RParenLoc);
  4311. }
  4312. }
  4313. }
  4314. // If we're directly calling a function, get the appropriate declaration.
  4315. if (Fn->getType() == Context.UnknownAnyTy) {
  4316. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4317. if (result.isInvalid()) return ExprError();
  4318. Fn = result.get();
  4319. }
  4320. Expr *NakedFn = Fn->IgnoreParens();
  4321. NamedDecl *NDecl = nullptr;
  4322. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4323. if (UnOp->getOpcode() == UO_AddrOf)
  4324. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4325. if (isa<DeclRefExpr>(NakedFn)) {
  4326. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4327. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4328. if (FDecl && FDecl->getBuiltinID()) {
  4329. // Rewrite the function decl for this builtin by replacing paramaters
  4330. // with no explicit address space with the address space of the arguments
  4331. // in ArgExprs.
  4332. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4333. NDecl = FDecl;
  4334. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4335. SourceLocation(), FDecl, false,
  4336. SourceLocation(), FDecl->getType(),
  4337. Fn->getValueKind(), FDecl);
  4338. }
  4339. }
  4340. } else if (isa<MemberExpr>(NakedFn))
  4341. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4342. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4343. if (FD->hasAttr<EnableIfAttr>()) {
  4344. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4345. Diag(Fn->getLocStart(),
  4346. isa<CXXMethodDecl>(FD) ?
  4347. diag::err_ovl_no_viable_member_function_in_call :
  4348. diag::err_ovl_no_viable_function_in_call)
  4349. << FD << FD->getSourceRange();
  4350. Diag(FD->getLocation(),
  4351. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4352. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4353. }
  4354. }
  4355. }
  4356. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4357. ExecConfig, IsExecConfig);
  4358. }
  4359. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4360. ///
  4361. /// __builtin_astype( value, dst type )
  4362. ///
  4363. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4364. SourceLocation BuiltinLoc,
  4365. SourceLocation RParenLoc) {
  4366. ExprValueKind VK = VK_RValue;
  4367. ExprObjectKind OK = OK_Ordinary;
  4368. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4369. QualType SrcTy = E->getType();
  4370. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4371. return ExprError(Diag(BuiltinLoc,
  4372. diag::err_invalid_astype_of_different_size)
  4373. << DstTy
  4374. << SrcTy
  4375. << E->getSourceRange());
  4376. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4377. }
  4378. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4379. /// provided arguments.
  4380. ///
  4381. /// __builtin_convertvector( value, dst type )
  4382. ///
  4383. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4384. SourceLocation BuiltinLoc,
  4385. SourceLocation RParenLoc) {
  4386. TypeSourceInfo *TInfo;
  4387. GetTypeFromParser(ParsedDestTy, &TInfo);
  4388. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4389. }
  4390. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4391. /// i.e. an expression not of \p OverloadTy. The expression should
  4392. /// unary-convert to an expression of function-pointer or
  4393. /// block-pointer type.
  4394. ///
  4395. /// \param NDecl the declaration being called, if available
  4396. ExprResult
  4397. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4398. SourceLocation LParenLoc,
  4399. ArrayRef<Expr *> Args,
  4400. SourceLocation RParenLoc,
  4401. Expr *Config, bool IsExecConfig) {
  4402. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4403. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4404. // Promote the function operand.
  4405. // We special-case function promotion here because we only allow promoting
  4406. // builtin functions to function pointers in the callee of a call.
  4407. ExprResult Result;
  4408. if (BuiltinID &&
  4409. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4410. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4411. CK_BuiltinFnToFnPtr).get();
  4412. } else {
  4413. Result = CallExprUnaryConversions(Fn);
  4414. }
  4415. if (Result.isInvalid())
  4416. return ExprError();
  4417. Fn = Result.get();
  4418. // Make the call expr early, before semantic checks. This guarantees cleanup
  4419. // of arguments and function on error.
  4420. CallExpr *TheCall;
  4421. if (Config)
  4422. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4423. cast<CallExpr>(Config), Args,
  4424. Context.BoolTy, VK_RValue,
  4425. RParenLoc);
  4426. else
  4427. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4428. VK_RValue, RParenLoc);
  4429. if (!getLangOpts().CPlusPlus) {
  4430. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4431. // function calls as their argument checking don't necessarily handle
  4432. // dependent types properly, so make sure any TypoExprs have been
  4433. // dealt with.
  4434. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4435. if (!Result.isUsable()) return ExprError();
  4436. TheCall = dyn_cast<CallExpr>(Result.get());
  4437. if (!TheCall) return Result;
  4438. Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs());
  4439. }
  4440. // Bail out early if calling a builtin with custom typechecking.
  4441. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4442. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4443. retry:
  4444. const FunctionType *FuncT;
  4445. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4446. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4447. // have type pointer to function".
  4448. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4449. if (!FuncT)
  4450. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4451. << Fn->getType() << Fn->getSourceRange());
  4452. } else if (const BlockPointerType *BPT =
  4453. Fn->getType()->getAs<BlockPointerType>()) {
  4454. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4455. } else {
  4456. // Handle calls to expressions of unknown-any type.
  4457. if (Fn->getType() == Context.UnknownAnyTy) {
  4458. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4459. if (rewrite.isInvalid()) return ExprError();
  4460. Fn = rewrite.get();
  4461. TheCall->setCallee(Fn);
  4462. goto retry;
  4463. }
  4464. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4465. << Fn->getType() << Fn->getSourceRange());
  4466. }
  4467. if (getLangOpts().CUDA) {
  4468. if (Config) {
  4469. // CUDA: Kernel calls must be to global functions
  4470. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4471. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4472. << FDecl->getName() << Fn->getSourceRange());
  4473. // CUDA: Kernel function must have 'void' return type
  4474. if (!FuncT->getReturnType()->isVoidType())
  4475. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4476. << Fn->getType() << Fn->getSourceRange());
  4477. } else {
  4478. // CUDA: Calls to global functions must be configured
  4479. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4480. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4481. << FDecl->getName() << Fn->getSourceRange());
  4482. }
  4483. }
  4484. // Check for a valid return type
  4485. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4486. FDecl))
  4487. return ExprError();
  4488. // We know the result type of the call, set it.
  4489. TheCall->setType(FuncT->getCallResultType(Context));
  4490. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4491. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4492. if (Proto) {
  4493. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4494. IsExecConfig))
  4495. return ExprError();
  4496. } else {
  4497. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4498. if (FDecl) {
  4499. // Check if we have too few/too many template arguments, based
  4500. // on our knowledge of the function definition.
  4501. const FunctionDecl *Def = nullptr;
  4502. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4503. Proto = Def->getType()->getAs<FunctionProtoType>();
  4504. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4505. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4506. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4507. }
  4508. // If the function we're calling isn't a function prototype, but we have
  4509. // a function prototype from a prior declaratiom, use that prototype.
  4510. if (!FDecl->hasPrototype())
  4511. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4512. }
  4513. // Promote the arguments (C99 6.5.2.2p6).
  4514. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4515. Expr *Arg = Args[i];
  4516. if (Proto && i < Proto->getNumParams()) {
  4517. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4518. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4519. ExprResult ArgE =
  4520. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4521. if (ArgE.isInvalid())
  4522. return true;
  4523. Arg = ArgE.getAs<Expr>();
  4524. } else {
  4525. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4526. if (ArgE.isInvalid())
  4527. return true;
  4528. Arg = ArgE.getAs<Expr>();
  4529. }
  4530. if (RequireCompleteType(Arg->getLocStart(),
  4531. Arg->getType(),
  4532. diag::err_call_incomplete_argument, Arg))
  4533. return ExprError();
  4534. TheCall->setArg(i, Arg);
  4535. }
  4536. }
  4537. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4538. if (!Method->isStatic())
  4539. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4540. << Fn->getSourceRange());
  4541. // Check for sentinels
  4542. if (NDecl)
  4543. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4544. // Do special checking on direct calls to functions.
  4545. if (FDecl) {
  4546. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4547. return ExprError();
  4548. if (BuiltinID)
  4549. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4550. } else if (NDecl) {
  4551. if (CheckPointerCall(NDecl, TheCall, Proto))
  4552. return ExprError();
  4553. } else {
  4554. if (CheckOtherCall(TheCall, Proto))
  4555. return ExprError();
  4556. }
  4557. return MaybeBindToTemporary(TheCall);
  4558. }
  4559. ExprResult
  4560. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4561. SourceLocation RParenLoc, Expr *InitExpr) {
  4562. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4563. // FIXME: put back this assert when initializers are worked out.
  4564. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  4565. TypeSourceInfo *TInfo;
  4566. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4567. if (!TInfo)
  4568. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4569. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4570. }
  4571. ExprResult
  4572. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4573. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4574. QualType literalType = TInfo->getType();
  4575. if (literalType->isArrayType()) {
  4576. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4577. diag::err_illegal_decl_array_incomplete_type,
  4578. SourceRange(LParenLoc,
  4579. LiteralExpr->getSourceRange().getEnd())))
  4580. return ExprError();
  4581. if (literalType->isVariableArrayType())
  4582. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4583. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4584. } else if (!literalType->isDependentType() &&
  4585. RequireCompleteType(LParenLoc, literalType,
  4586. diag::err_typecheck_decl_incomplete_type,
  4587. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4588. return ExprError();
  4589. InitializedEntity Entity
  4590. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4591. InitializationKind Kind
  4592. = InitializationKind::CreateCStyleCast(LParenLoc,
  4593. SourceRange(LParenLoc, RParenLoc),
  4594. /*InitList=*/true);
  4595. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4596. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4597. &literalType);
  4598. if (Result.isInvalid())
  4599. return ExprError();
  4600. LiteralExpr = Result.get();
  4601. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4602. if (isFileScope &&
  4603. !LiteralExpr->isTypeDependent() &&
  4604. !LiteralExpr->isValueDependent() &&
  4605. !literalType->isDependentType()) { // 6.5.2.5p3
  4606. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4607. return ExprError();
  4608. }
  4609. // In C, compound literals are l-values for some reason.
  4610. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4611. return MaybeBindToTemporary(
  4612. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4613. VK, LiteralExpr, isFileScope));
  4614. }
  4615. ExprResult
  4616. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4617. SourceLocation RBraceLoc) {
  4618. // Immediately handle non-overload placeholders. Overloads can be
  4619. // resolved contextually, but everything else here can't.
  4620. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4621. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4622. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4623. // Ignore failures; dropping the entire initializer list because
  4624. // of one failure would be terrible for indexing/etc.
  4625. if (result.isInvalid()) continue;
  4626. InitArgList[I] = result.get();
  4627. }
  4628. }
  4629. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4630. // CheckInitializer() - it requires knowledge of the object being intialized.
  4631. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4632. RBraceLoc);
  4633. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4634. return E;
  4635. }
  4636. /// Do an explicit extend of the given block pointer if we're in ARC.
  4637. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4638. assert(E.get()->getType()->isBlockPointerType());
  4639. assert(E.get()->isRValue());
  4640. // Only do this in an r-value context.
  4641. if (!getLangOpts().ObjCAutoRefCount) return;
  4642. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4643. CK_ARCExtendBlockObject, E.get(),
  4644. /*base path*/ nullptr, VK_RValue);
  4645. ExprNeedsCleanups = true;
  4646. }
  4647. /// Prepare a conversion of the given expression to an ObjC object
  4648. /// pointer type.
  4649. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4650. QualType type = E.get()->getType();
  4651. if (type->isObjCObjectPointerType()) {
  4652. return CK_BitCast;
  4653. } else if (type->isBlockPointerType()) {
  4654. maybeExtendBlockObject(E);
  4655. return CK_BlockPointerToObjCPointerCast;
  4656. } else {
  4657. assert(type->isPointerType());
  4658. return CK_CPointerToObjCPointerCast;
  4659. }
  4660. }
  4661. /// Prepares for a scalar cast, performing all the necessary stages
  4662. /// except the final cast and returning the kind required.
  4663. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4664. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4665. // Also, callers should have filtered out the invalid cases with
  4666. // pointers. Everything else should be possible.
  4667. QualType SrcTy = Src.get()->getType();
  4668. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4669. return CK_NoOp;
  4670. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4671. case Type::STK_MemberPointer:
  4672. llvm_unreachable("member pointer type in C");
  4673. case Type::STK_CPointer:
  4674. case Type::STK_BlockPointer:
  4675. case Type::STK_ObjCObjectPointer:
  4676. switch (DestTy->getScalarTypeKind()) {
  4677. case Type::STK_CPointer: {
  4678. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4679. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4680. if (SrcAS != DestAS)
  4681. return CK_AddressSpaceConversion;
  4682. return CK_BitCast;
  4683. }
  4684. case Type::STK_BlockPointer:
  4685. return (SrcKind == Type::STK_BlockPointer
  4686. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4687. case Type::STK_ObjCObjectPointer:
  4688. if (SrcKind == Type::STK_ObjCObjectPointer)
  4689. return CK_BitCast;
  4690. if (SrcKind == Type::STK_CPointer)
  4691. return CK_CPointerToObjCPointerCast;
  4692. maybeExtendBlockObject(Src);
  4693. return CK_BlockPointerToObjCPointerCast;
  4694. case Type::STK_Bool:
  4695. return CK_PointerToBoolean;
  4696. case Type::STK_Integral:
  4697. return CK_PointerToIntegral;
  4698. case Type::STK_Floating:
  4699. case Type::STK_FloatingComplex:
  4700. case Type::STK_IntegralComplex:
  4701. case Type::STK_MemberPointer:
  4702. llvm_unreachable("illegal cast from pointer");
  4703. }
  4704. llvm_unreachable("Should have returned before this");
  4705. case Type::STK_Bool: // casting from bool is like casting from an integer
  4706. case Type::STK_Integral:
  4707. switch (DestTy->getScalarTypeKind()) {
  4708. case Type::STK_CPointer:
  4709. case Type::STK_ObjCObjectPointer:
  4710. case Type::STK_BlockPointer:
  4711. if (Src.get()->isNullPointerConstant(Context,
  4712. Expr::NPC_ValueDependentIsNull))
  4713. return CK_NullToPointer;
  4714. return CK_IntegralToPointer;
  4715. case Type::STK_Bool:
  4716. return CK_IntegralToBoolean;
  4717. case Type::STK_Integral:
  4718. return CK_IntegralCast;
  4719. case Type::STK_Floating:
  4720. return CK_IntegralToFloating;
  4721. case Type::STK_IntegralComplex:
  4722. Src = ImpCastExprToType(Src.get(),
  4723. DestTy->castAs<ComplexType>()->getElementType(),
  4724. CK_IntegralCast);
  4725. return CK_IntegralRealToComplex;
  4726. case Type::STK_FloatingComplex:
  4727. Src = ImpCastExprToType(Src.get(),
  4728. DestTy->castAs<ComplexType>()->getElementType(),
  4729. CK_IntegralToFloating);
  4730. return CK_FloatingRealToComplex;
  4731. case Type::STK_MemberPointer:
  4732. llvm_unreachable("member pointer type in C");
  4733. }
  4734. llvm_unreachable("Should have returned before this");
  4735. case Type::STK_Floating:
  4736. switch (DestTy->getScalarTypeKind()) {
  4737. case Type::STK_Floating:
  4738. return CK_FloatingCast;
  4739. case Type::STK_Bool:
  4740. return CK_FloatingToBoolean;
  4741. case Type::STK_Integral:
  4742. return CK_FloatingToIntegral;
  4743. case Type::STK_FloatingComplex:
  4744. Src = ImpCastExprToType(Src.get(),
  4745. DestTy->castAs<ComplexType>()->getElementType(),
  4746. CK_FloatingCast);
  4747. return CK_FloatingRealToComplex;
  4748. case Type::STK_IntegralComplex:
  4749. Src = ImpCastExprToType(Src.get(),
  4750. DestTy->castAs<ComplexType>()->getElementType(),
  4751. CK_FloatingToIntegral);
  4752. return CK_IntegralRealToComplex;
  4753. case Type::STK_CPointer:
  4754. case Type::STK_ObjCObjectPointer:
  4755. case Type::STK_BlockPointer:
  4756. llvm_unreachable("valid float->pointer cast?");
  4757. case Type::STK_MemberPointer:
  4758. llvm_unreachable("member pointer type in C");
  4759. }
  4760. llvm_unreachable("Should have returned before this");
  4761. case Type::STK_FloatingComplex:
  4762. switch (DestTy->getScalarTypeKind()) {
  4763. case Type::STK_FloatingComplex:
  4764. return CK_FloatingComplexCast;
  4765. case Type::STK_IntegralComplex:
  4766. return CK_FloatingComplexToIntegralComplex;
  4767. case Type::STK_Floating: {
  4768. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4769. if (Context.hasSameType(ET, DestTy))
  4770. return CK_FloatingComplexToReal;
  4771. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4772. return CK_FloatingCast;
  4773. }
  4774. case Type::STK_Bool:
  4775. return CK_FloatingComplexToBoolean;
  4776. case Type::STK_Integral:
  4777. Src = ImpCastExprToType(Src.get(),
  4778. SrcTy->castAs<ComplexType>()->getElementType(),
  4779. CK_FloatingComplexToReal);
  4780. return CK_FloatingToIntegral;
  4781. case Type::STK_CPointer:
  4782. case Type::STK_ObjCObjectPointer:
  4783. case Type::STK_BlockPointer:
  4784. llvm_unreachable("valid complex float->pointer cast?");
  4785. case Type::STK_MemberPointer:
  4786. llvm_unreachable("member pointer type in C");
  4787. }
  4788. llvm_unreachable("Should have returned before this");
  4789. case Type::STK_IntegralComplex:
  4790. switch (DestTy->getScalarTypeKind()) {
  4791. case Type::STK_FloatingComplex:
  4792. return CK_IntegralComplexToFloatingComplex;
  4793. case Type::STK_IntegralComplex:
  4794. return CK_IntegralComplexCast;
  4795. case Type::STK_Integral: {
  4796. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4797. if (Context.hasSameType(ET, DestTy))
  4798. return CK_IntegralComplexToReal;
  4799. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4800. return CK_IntegralCast;
  4801. }
  4802. case Type::STK_Bool:
  4803. return CK_IntegralComplexToBoolean;
  4804. case Type::STK_Floating:
  4805. Src = ImpCastExprToType(Src.get(),
  4806. SrcTy->castAs<ComplexType>()->getElementType(),
  4807. CK_IntegralComplexToReal);
  4808. return CK_IntegralToFloating;
  4809. case Type::STK_CPointer:
  4810. case Type::STK_ObjCObjectPointer:
  4811. case Type::STK_BlockPointer:
  4812. llvm_unreachable("valid complex int->pointer cast?");
  4813. case Type::STK_MemberPointer:
  4814. llvm_unreachable("member pointer type in C");
  4815. }
  4816. llvm_unreachable("Should have returned before this");
  4817. }
  4818. llvm_unreachable("Unhandled scalar cast");
  4819. }
  4820. static bool breakDownVectorType(QualType type, uint64_t &len,
  4821. QualType &eltType) {
  4822. // Vectors are simple.
  4823. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4824. len = vecType->getNumElements();
  4825. eltType = vecType->getElementType();
  4826. assert(eltType->isScalarType());
  4827. return true;
  4828. }
  4829. // We allow lax conversion to and from non-vector types, but only if
  4830. // they're real types (i.e. non-complex, non-pointer scalar types).
  4831. if (!type->isRealType()) return false;
  4832. len = 1;
  4833. eltType = type;
  4834. return true;
  4835. }
  4836. static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
  4837. uint64_t srcLen, destLen;
  4838. QualType srcElt, destElt;
  4839. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4840. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4841. // ASTContext::getTypeSize will return the size rounded up to a
  4842. // power of 2, so instead of using that, we need to use the raw
  4843. // element size multiplied by the element count.
  4844. uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
  4845. uint64_t destEltSize = S.Context.getTypeSize(destElt);
  4846. return (srcLen * srcEltSize == destLen * destEltSize);
  4847. }
  4848. /// Is this a legal conversion between two known vector types?
  4849. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4850. assert(destTy->isVectorType() || srcTy->isVectorType());
  4851. if (!Context.getLangOpts().LaxVectorConversions)
  4852. return false;
  4853. return VectorTypesMatch(*this, srcTy, destTy);
  4854. }
  4855. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4856. CastKind &Kind) {
  4857. assert(VectorTy->isVectorType() && "Not a vector type!");
  4858. if (Ty->isVectorType() || Ty->isIntegerType()) {
  4859. if (!VectorTypesMatch(*this, Ty, VectorTy))
  4860. return Diag(R.getBegin(),
  4861. Ty->isVectorType() ?
  4862. diag::err_invalid_conversion_between_vectors :
  4863. diag::err_invalid_conversion_between_vector_and_integer)
  4864. << VectorTy << Ty << R;
  4865. } else
  4866. return Diag(R.getBegin(),
  4867. diag::err_invalid_conversion_between_vector_and_scalar)
  4868. << VectorTy << Ty << R;
  4869. Kind = CK_BitCast;
  4870. return false;
  4871. }
  4872. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4873. Expr *CastExpr, CastKind &Kind) {
  4874. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4875. QualType SrcTy = CastExpr->getType();
  4876. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4877. // an ExtVectorType.
  4878. // In OpenCL, casts between vectors of different types are not allowed.
  4879. // (See OpenCL 6.2).
  4880. if (SrcTy->isVectorType()) {
  4881. if (!VectorTypesMatch(*this, SrcTy, DestTy)
  4882. || (getLangOpts().OpenCL &&
  4883. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4884. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4885. << DestTy << SrcTy << R;
  4886. return ExprError();
  4887. }
  4888. Kind = CK_BitCast;
  4889. return CastExpr;
  4890. }
  4891. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4892. // conversion will take place first from scalar to elt type, and then
  4893. // splat from elt type to vector.
  4894. if (SrcTy->isPointerType())
  4895. return Diag(R.getBegin(),
  4896. diag::err_invalid_conversion_between_vector_and_scalar)
  4897. << DestTy << SrcTy << R;
  4898. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4899. ExprResult CastExprRes = CastExpr;
  4900. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4901. if (CastExprRes.isInvalid())
  4902. return ExprError();
  4903. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4904. Kind = CK_VectorSplat;
  4905. return CastExpr;
  4906. }
  4907. ExprResult
  4908. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4909. Declarator &D, ParsedType &Ty,
  4910. SourceLocation RParenLoc, Expr *CastExpr) {
  4911. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4912. "ActOnCastExpr(): missing type or expr");
  4913. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4914. if (D.isInvalidType())
  4915. return ExprError();
  4916. if (getLangOpts().CPlusPlus) {
  4917. // Check that there are no default arguments (C++ only).
  4918. CheckExtraCXXDefaultArguments(D);
  4919. } else {
  4920. // Make sure any TypoExprs have been dealt with.
  4921. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4922. if (!Res.isUsable())
  4923. return ExprError();
  4924. CastExpr = Res.get();
  4925. }
  4926. checkUnusedDeclAttributes(D);
  4927. QualType castType = castTInfo->getType();
  4928. Ty = CreateParsedType(castType, castTInfo);
  4929. bool isVectorLiteral = false;
  4930. // Check for an altivec or OpenCL literal,
  4931. // i.e. all the elements are integer constants.
  4932. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4933. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4934. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  4935. && castType->isVectorType() && (PE || PLE)) {
  4936. if (PLE && PLE->getNumExprs() == 0) {
  4937. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4938. return ExprError();
  4939. }
  4940. if (PE || PLE->getNumExprs() == 1) {
  4941. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  4942. if (!E->getType()->isVectorType())
  4943. isVectorLiteral = true;
  4944. }
  4945. else
  4946. isVectorLiteral = true;
  4947. }
  4948. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  4949. // then handle it as such.
  4950. if (isVectorLiteral)
  4951. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  4952. // If the Expr being casted is a ParenListExpr, handle it specially.
  4953. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  4954. // sequence of BinOp comma operators.
  4955. if (isa<ParenListExpr>(CastExpr)) {
  4956. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  4957. if (Result.isInvalid()) return ExprError();
  4958. CastExpr = Result.get();
  4959. }
  4960. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  4961. !getSourceManager().isInSystemMacro(LParenLoc))
  4962. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  4963. #if 0 // HLSL Change - no support for ObjC constructs
  4964. CheckTollFreeBridgeCast(castType, CastExpr);
  4965. CheckObjCBridgeRelatedCast(castType, CastExpr);
  4966. #endif // HLSL Change
  4967. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  4968. }
  4969. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  4970. SourceLocation RParenLoc, Expr *E,
  4971. TypeSourceInfo *TInfo) {
  4972. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  4973. "Expected paren or paren list expression");
  4974. Expr **exprs;
  4975. unsigned numExprs;
  4976. Expr *subExpr;
  4977. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  4978. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  4979. LiteralLParenLoc = PE->getLParenLoc();
  4980. LiteralRParenLoc = PE->getRParenLoc();
  4981. exprs = PE->getExprs();
  4982. numExprs = PE->getNumExprs();
  4983. } else { // isa<ParenExpr> by assertion at function entrance
  4984. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  4985. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  4986. subExpr = cast<ParenExpr>(E)->getSubExpr();
  4987. exprs = &subExpr;
  4988. numExprs = 1;
  4989. }
  4990. QualType Ty = TInfo->getType();
  4991. assert(Ty->isVectorType() && "Expected vector type");
  4992. SmallVector<Expr *, 8> initExprs;
  4993. const VectorType *VTy = Ty->getAs<VectorType>();
  4994. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  4995. // '(...)' form of vector initialization in AltiVec: the number of
  4996. // initializers must be one or must match the size of the vector.
  4997. // If a single value is specified in the initializer then it will be
  4998. // replicated to all the components of the vector
  4999. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5000. // The number of initializers must be one or must match the size of the
  5001. // vector. If a single value is specified in the initializer then it will
  5002. // be replicated to all the components of the vector
  5003. if (numExprs == 1) {
  5004. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5005. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5006. if (Literal.isInvalid())
  5007. return ExprError();
  5008. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5009. PrepareScalarCast(Literal, ElemTy));
  5010. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5011. }
  5012. else if (numExprs < numElems) {
  5013. Diag(E->getExprLoc(),
  5014. diag::err_incorrect_number_of_vector_initializers);
  5015. return ExprError();
  5016. }
  5017. else
  5018. initExprs.append(exprs, exprs + numExprs);
  5019. }
  5020. else {
  5021. // For OpenCL, when the number of initializers is a single value,
  5022. // it will be replicated to all components of the vector.
  5023. if (getLangOpts().OpenCL &&
  5024. VTy->getVectorKind() == VectorType::GenericVector &&
  5025. numExprs == 1) {
  5026. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5027. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5028. if (Literal.isInvalid())
  5029. return ExprError();
  5030. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5031. PrepareScalarCast(Literal, ElemTy));
  5032. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5033. }
  5034. initExprs.append(exprs, exprs + numExprs);
  5035. }
  5036. // FIXME: This means that pretty-printing the final AST will produce curly
  5037. // braces instead of the original commas.
  5038. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5039. initExprs, LiteralRParenLoc);
  5040. initE->setType(Ty);
  5041. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5042. }
  5043. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5044. /// the ParenListExpr into a sequence of comma binary operators.
  5045. ExprResult
  5046. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5047. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5048. if (!E)
  5049. return OrigExpr;
  5050. ExprResult Result(E->getExpr(0));
  5051. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5052. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5053. E->getExpr(i));
  5054. if (Result.isInvalid()) return ExprError();
  5055. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5056. }
  5057. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5058. SourceLocation R,
  5059. MultiExprArg Val) {
  5060. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5061. return expr;
  5062. }
  5063. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5064. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5065. /// emitted.
  5066. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5067. SourceLocation QuestionLoc) {
  5068. Expr *NullExpr = LHSExpr;
  5069. Expr *NonPointerExpr = RHSExpr;
  5070. Expr::NullPointerConstantKind NullKind =
  5071. NullExpr->isNullPointerConstant(Context,
  5072. Expr::NPC_ValueDependentIsNotNull);
  5073. if (NullKind == Expr::NPCK_NotNull) {
  5074. NullExpr = RHSExpr;
  5075. NonPointerExpr = LHSExpr;
  5076. NullKind =
  5077. NullExpr->isNullPointerConstant(Context,
  5078. Expr::NPC_ValueDependentIsNotNull);
  5079. }
  5080. if (NullKind == Expr::NPCK_NotNull)
  5081. return false;
  5082. if (NullKind == Expr::NPCK_ZeroExpression)
  5083. return false;
  5084. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5085. // In this case, check to make sure that we got here from a "NULL"
  5086. // string in the source code.
  5087. NullExpr = NullExpr->IgnoreParenImpCasts();
  5088. SourceLocation loc = NullExpr->getExprLoc();
  5089. if (!findMacroSpelling(loc, "NULL"))
  5090. return false;
  5091. }
  5092. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5093. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5094. << NonPointerExpr->getType() << DiagType
  5095. << NonPointerExpr->getSourceRange();
  5096. return true;
  5097. }
  5098. /// \brief Return false if the condition expression is valid, true otherwise.
  5099. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5100. QualType CondTy = Cond->getType();
  5101. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5102. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5103. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5104. << CondTy << Cond->getSourceRange();
  5105. return true;
  5106. }
  5107. // C99 6.5.15p2
  5108. if (CondTy->isScalarType()) return false;
  5109. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5110. << CondTy << Cond->getSourceRange();
  5111. return true;
  5112. }
  5113. /// \brief Handle when one or both operands are void type.
  5114. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5115. ExprResult &RHS) {
  5116. Expr *LHSExpr = LHS.get();
  5117. Expr *RHSExpr = RHS.get();
  5118. if (!LHSExpr->getType()->isVoidType())
  5119. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5120. << RHSExpr->getSourceRange();
  5121. if (!RHSExpr->getType()->isVoidType())
  5122. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5123. << LHSExpr->getSourceRange();
  5124. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5125. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5126. return S.Context.VoidTy;
  5127. }
  5128. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5129. /// true otherwise.
  5130. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5131. QualType PointerTy) {
  5132. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5133. !NullExpr.get()->isNullPointerConstant(S.Context,
  5134. Expr::NPC_ValueDependentIsNull))
  5135. return true;
  5136. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5137. return false;
  5138. }
  5139. /// \brief Checks compatibility between two pointers and return the resulting
  5140. /// type.
  5141. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5142. ExprResult &RHS,
  5143. SourceLocation Loc) {
  5144. QualType LHSTy = LHS.get()->getType();
  5145. QualType RHSTy = RHS.get()->getType();
  5146. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5147. // Two identical pointers types are always compatible.
  5148. return LHSTy;
  5149. }
  5150. QualType lhptee, rhptee;
  5151. // Get the pointee types.
  5152. bool IsBlockPointer = false;
  5153. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5154. lhptee = LHSBTy->getPointeeType();
  5155. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5156. IsBlockPointer = true;
  5157. } else {
  5158. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5159. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5160. }
  5161. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5162. // differently qualified versions of compatible types, the result type is
  5163. // a pointer to an appropriately qualified version of the composite
  5164. // type.
  5165. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5166. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5167. // be incompatible with address space 3: they may live on different devices or
  5168. // anything.
  5169. Qualifiers lhQual = lhptee.getQualifiers();
  5170. Qualifiers rhQual = rhptee.getQualifiers();
  5171. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5172. lhQual.removeCVRQualifiers();
  5173. rhQual.removeCVRQualifiers();
  5174. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5175. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5176. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5177. if (CompositeTy.isNull()) {
  5178. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5179. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5180. << RHS.get()->getSourceRange();
  5181. // In this situation, we assume void* type. No especially good
  5182. // reason, but this is what gcc does, and we do have to pick
  5183. // to get a consistent AST.
  5184. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5185. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5186. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5187. return incompatTy;
  5188. }
  5189. // The pointer types are compatible.
  5190. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5191. if (IsBlockPointer)
  5192. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5193. else
  5194. ResultTy = S.Context.getPointerType(ResultTy);
  5195. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5196. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5197. return ResultTy;
  5198. }
  5199. /// \brief Return the resulting type when the operands are both block pointers.
  5200. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5201. ExprResult &LHS,
  5202. ExprResult &RHS,
  5203. SourceLocation Loc) {
  5204. QualType LHSTy = LHS.get()->getType();
  5205. QualType RHSTy = RHS.get()->getType();
  5206. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5207. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5208. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5209. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5210. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5211. return destType;
  5212. }
  5213. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5214. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5215. << RHS.get()->getSourceRange();
  5216. return QualType();
  5217. }
  5218. // We have 2 block pointer types.
  5219. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5220. }
  5221. /// \brief Return the resulting type when the operands are both pointers.
  5222. static QualType
  5223. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5224. ExprResult &RHS,
  5225. SourceLocation Loc) {
  5226. // get the pointer types
  5227. QualType LHSTy = LHS.get()->getType();
  5228. QualType RHSTy = RHS.get()->getType();
  5229. // get the "pointed to" types
  5230. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5231. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5232. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5233. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5234. // Figure out necessary qualifiers (C99 6.5.15p6)
  5235. QualType destPointee
  5236. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5237. QualType destType = S.Context.getPointerType(destPointee);
  5238. // Add qualifiers if necessary.
  5239. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5240. // Promote to void*.
  5241. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5242. return destType;
  5243. }
  5244. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5245. QualType destPointee
  5246. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5247. QualType destType = S.Context.getPointerType(destPointee);
  5248. // Add qualifiers if necessary.
  5249. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5250. // Promote to void*.
  5251. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5252. return destType;
  5253. }
  5254. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5255. }
  5256. /// \brief Return false if the first expression is not an integer and the second
  5257. /// expression is not a pointer, true otherwise.
  5258. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5259. Expr* PointerExpr, SourceLocation Loc,
  5260. bool IsIntFirstExpr) {
  5261. if (!PointerExpr->getType()->isPointerType() ||
  5262. !Int.get()->getType()->isIntegerType())
  5263. return false;
  5264. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5265. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5266. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5267. << Expr1->getType() << Expr2->getType()
  5268. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5269. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5270. CK_IntegralToPointer);
  5271. return true;
  5272. }
  5273. /// \brief Simple conversion between integer and floating point types.
  5274. ///
  5275. /// Used when handling the OpenCL conditional operator where the
  5276. /// condition is a vector while the other operands are scalar.
  5277. ///
  5278. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5279. /// types are either integer or floating type. Between the two
  5280. /// operands, the type with the higher rank is defined as the "result
  5281. /// type". The other operand needs to be promoted to the same type. No
  5282. /// other type promotion is allowed. We cannot use
  5283. /// UsualArithmeticConversions() for this purpose, since it always
  5284. /// promotes promotable types.
  5285. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5286. ExprResult &RHS,
  5287. SourceLocation QuestionLoc) {
  5288. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5289. if (LHS.isInvalid())
  5290. return QualType();
  5291. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5292. if (RHS.isInvalid())
  5293. return QualType();
  5294. // For conversion purposes, we ignore any qualifiers.
  5295. // For example, "const float" and "float" are equivalent.
  5296. QualType LHSType =
  5297. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5298. QualType RHSType =
  5299. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5300. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5301. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5302. << LHSType << LHS.get()->getSourceRange();
  5303. return QualType();
  5304. }
  5305. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5306. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5307. << RHSType << RHS.get()->getSourceRange();
  5308. return QualType();
  5309. }
  5310. // If both types are identical, no conversion is needed.
  5311. if (LHSType == RHSType)
  5312. return LHSType;
  5313. // Now handle "real" floating types (i.e. float, double, long double).
  5314. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5315. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5316. /*IsCompAssign = */ false);
  5317. // Finally, we have two differing integer types.
  5318. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5319. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5320. }
  5321. /// \brief Convert scalar operands to a vector that matches the
  5322. /// condition in length.
  5323. ///
  5324. /// Used when handling the OpenCL conditional operator where the
  5325. /// condition is a vector while the other operands are scalar.
  5326. ///
  5327. /// We first compute the "result type" for the scalar operands
  5328. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5329. /// into a vector of that type where the length matches the condition
  5330. /// vector type. s6.11.6 requires that the element types of the result
  5331. /// and the condition must have the same number of bits.
  5332. static QualType
  5333. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5334. QualType CondTy, SourceLocation QuestionLoc) {
  5335. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5336. if (ResTy.isNull()) return QualType();
  5337. const VectorType *CV = CondTy->getAs<VectorType>();
  5338. assert(CV);
  5339. // Determine the vector result type
  5340. unsigned NumElements = CV->getNumElements();
  5341. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5342. // Ensure that all types have the same number of bits
  5343. if (S.Context.getTypeSize(CV->getElementType())
  5344. != S.Context.getTypeSize(ResTy)) {
  5345. // Since VectorTy is created internally, it does not pretty print
  5346. // with an OpenCL name. Instead, we just print a description.
  5347. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5348. SmallString<64> Str;
  5349. llvm::raw_svector_ostream OS(Str);
  5350. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5351. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5352. << CondTy << OS.str();
  5353. return QualType();
  5354. }
  5355. // Convert operands to the vector result type
  5356. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5357. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5358. return VectorTy;
  5359. }
  5360. /// \brief Return false if this is a valid OpenCL condition vector
  5361. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5362. SourceLocation QuestionLoc) {
  5363. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5364. // integral type.
  5365. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5366. assert(CondTy);
  5367. QualType EleTy = CondTy->getElementType();
  5368. if (EleTy->isIntegerType()) return false;
  5369. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5370. << Cond->getType() << Cond->getSourceRange();
  5371. return true;
  5372. }
  5373. /// \brief Return false if the vector condition type and the vector
  5374. /// result type are compatible.
  5375. ///
  5376. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5377. /// number of elements, and their element types have the same number
  5378. /// of bits.
  5379. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5380. SourceLocation QuestionLoc) {
  5381. const VectorType *CV = CondTy->getAs<VectorType>();
  5382. const VectorType *RV = VecResTy->getAs<VectorType>();
  5383. assert(CV && RV);
  5384. if (CV->getNumElements() != RV->getNumElements()) {
  5385. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5386. << CondTy << VecResTy;
  5387. return true;
  5388. }
  5389. QualType CVE = CV->getElementType();
  5390. QualType RVE = RV->getElementType();
  5391. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5392. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5393. << CondTy << VecResTy;
  5394. return true;
  5395. }
  5396. return false;
  5397. }
  5398. /// \brief Return the resulting type for the conditional operator in
  5399. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5400. /// s6.3.i) when the condition is a vector type.
  5401. static QualType
  5402. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5403. ExprResult &LHS, ExprResult &RHS,
  5404. SourceLocation QuestionLoc) {
  5405. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5406. if (Cond.isInvalid())
  5407. return QualType();
  5408. QualType CondTy = Cond.get()->getType();
  5409. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5410. return QualType();
  5411. // If either operand is a vector then find the vector type of the
  5412. // result as specified in OpenCL v1.1 s6.3.i.
  5413. if (LHS.get()->getType()->isVectorType() ||
  5414. RHS.get()->getType()->isVectorType()) {
  5415. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5416. /*isCompAssign*/false,
  5417. /*AllowBothBool*/true,
  5418. /*AllowBoolConversions*/false);
  5419. if (VecResTy.isNull()) return QualType();
  5420. // The result type must match the condition type as specified in
  5421. // OpenCL v1.1 s6.11.6.
  5422. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5423. return QualType();
  5424. return VecResTy;
  5425. }
  5426. // Both operands are scalar.
  5427. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5428. }
  5429. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5430. /// In that case, LHS = cond.
  5431. /// C99 6.5.15
  5432. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5433. ExprResult &RHS, ExprValueKind &VK,
  5434. ExprObjectKind &OK,
  5435. SourceLocation QuestionLoc) {
  5436. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5437. if (!LHSResult.isUsable()) return QualType();
  5438. LHS = LHSResult;
  5439. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5440. if (!RHSResult.isUsable()) return QualType();
  5441. RHS = RHSResult;
  5442. // HLSL Change Starts: HLSL supports a vector condition and is
  5443. // sufficiently different to merit its own checker.
  5444. if (getLangOpts().HLSL)
  5445. return hlsl::CheckVectorConditional(this, Cond, LHS, RHS, QuestionLoc);
  5446. // HLSL Change Ends
  5447. // C++ is sufficiently different to merit its own checker.
  5448. if (getLangOpts().CPlusPlus)
  5449. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5450. VK = VK_RValue;
  5451. OK = OK_Ordinary;
  5452. // The OpenCL operator with a vector condition is sufficiently
  5453. // different to merit its own checker.
  5454. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5455. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5456. // First, check the condition.
  5457. Cond = UsualUnaryConversions(Cond.get());
  5458. if (Cond.isInvalid())
  5459. return QualType();
  5460. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5461. return QualType();
  5462. // Now check the two expressions.
  5463. if (LHS.get()->getType()->isVectorType() ||
  5464. RHS.get()->getType()->isVectorType())
  5465. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5466. /*AllowBothBool*/true,
  5467. /*AllowBoolConversions*/false);
  5468. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5469. if (LHS.isInvalid() || RHS.isInvalid())
  5470. return QualType();
  5471. QualType LHSTy = LHS.get()->getType();
  5472. QualType RHSTy = RHS.get()->getType();
  5473. // If both operands have arithmetic type, do the usual arithmetic conversions
  5474. // to find a common type: C99 6.5.15p3,5.
  5475. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5476. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5477. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5478. return ResTy;
  5479. }
  5480. // If both operands are the same structure or union type, the result is that
  5481. // type.
  5482. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5483. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5484. if (LHSRT->getDecl() == RHSRT->getDecl())
  5485. // "If both the operands have structure or union type, the result has
  5486. // that type." This implies that CV qualifiers are dropped.
  5487. return LHSTy.getUnqualifiedType();
  5488. // FIXME: Type of conditional expression must be complete in C mode.
  5489. }
  5490. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5491. // The following || allows only one side to be void (a GCC-ism).
  5492. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5493. return checkConditionalVoidType(*this, LHS, RHS);
  5494. }
  5495. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5496. // the type of the other operand."
  5497. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5498. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5499. // All objective-c pointer type analysis is done here.
  5500. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5501. QuestionLoc);
  5502. if (LHS.isInvalid() || RHS.isInvalid())
  5503. return QualType();
  5504. if (!compositeType.isNull())
  5505. return compositeType;
  5506. // Handle block pointer types.
  5507. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5508. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5509. QuestionLoc);
  5510. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5511. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5512. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5513. QuestionLoc);
  5514. // GCC compatibility: soften pointer/integer mismatch. Note that
  5515. // null pointers have been filtered out by this point.
  5516. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5517. /*isIntFirstExpr=*/true))
  5518. return RHSTy;
  5519. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5520. /*isIntFirstExpr=*/false))
  5521. return LHSTy;
  5522. // Emit a better diagnostic if one of the expressions is a null pointer
  5523. // constant and the other is not a pointer type. In this case, the user most
  5524. // likely forgot to take the address of the other expression.
  5525. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5526. return QualType();
  5527. // Otherwise, the operands are not compatible.
  5528. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5529. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5530. << RHS.get()->getSourceRange();
  5531. return QualType();
  5532. }
  5533. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5534. /// two objective-c pointer types of the two input expressions.
  5535. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5536. SourceLocation QuestionLoc) {
  5537. QualType LHSTy = LHS.get()->getType();
  5538. QualType RHSTy = RHS.get()->getType();
  5539. // Handle things like Class and struct objc_class*. Here we case the result
  5540. // to the pseudo-builtin, because that will be implicitly cast back to the
  5541. // redefinition type if an attempt is made to access its fields.
  5542. if (LHSTy->isObjCClassType() &&
  5543. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5544. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5545. return LHSTy;
  5546. }
  5547. if (RHSTy->isObjCClassType() &&
  5548. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5549. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5550. return RHSTy;
  5551. }
  5552. // And the same for struct objc_object* / id
  5553. if (LHSTy->isObjCIdType() &&
  5554. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5555. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5556. return LHSTy;
  5557. }
  5558. if (RHSTy->isObjCIdType() &&
  5559. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5560. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5561. return RHSTy;
  5562. }
  5563. // And the same for struct objc_selector* / SEL
  5564. if (Context.isObjCSelType(LHSTy) &&
  5565. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5566. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5567. return LHSTy;
  5568. }
  5569. if (Context.isObjCSelType(RHSTy) &&
  5570. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5571. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5572. return RHSTy;
  5573. }
  5574. // Check constraints for Objective-C object pointers types.
  5575. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5576. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5577. // Two identical object pointer types are always compatible.
  5578. return LHSTy;
  5579. }
  5580. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5581. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5582. QualType compositeType = LHSTy;
  5583. // If both operands are interfaces and either operand can be
  5584. // assigned to the other, use that type as the composite
  5585. // type. This allows
  5586. // xxx ? (A*) a : (B*) b
  5587. // where B is a subclass of A.
  5588. //
  5589. // Additionally, as for assignment, if either type is 'id'
  5590. // allow silent coercion. Finally, if the types are
  5591. // incompatible then make sure to use 'id' as the composite
  5592. // type so the result is acceptable for sending messages to.
  5593. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5594. // It could return the composite type.
  5595. if (!(compositeType =
  5596. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5597. // Nothing more to do.
  5598. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5599. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5600. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5601. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5602. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5603. RHSTy->isObjCQualifiedIdType()) &&
  5604. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5605. // Need to handle "id<xx>" explicitly.
  5606. // GCC allows qualified id and any Objective-C type to devolve to
  5607. // id. Currently localizing to here until clear this should be
  5608. // part of ObjCQualifiedIdTypesAreCompatible.
  5609. compositeType = Context.getObjCIdType();
  5610. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5611. compositeType = Context.getObjCIdType();
  5612. } else {
  5613. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5614. << LHSTy << RHSTy
  5615. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5616. QualType incompatTy = Context.getObjCIdType();
  5617. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5618. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5619. return incompatTy;
  5620. }
  5621. // The object pointer types are compatible.
  5622. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5623. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5624. return compositeType;
  5625. }
  5626. // Check Objective-C object pointer types and 'void *'
  5627. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5628. if (getLangOpts().ObjCAutoRefCount) {
  5629. // ARC forbids the implicit conversion of object pointers to 'void *',
  5630. // so these types are not compatible.
  5631. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5632. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5633. LHS = RHS = true;
  5634. return QualType();
  5635. }
  5636. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5637. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5638. QualType destPointee
  5639. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5640. QualType destType = Context.getPointerType(destPointee);
  5641. // Add qualifiers if necessary.
  5642. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5643. // Promote to void*.
  5644. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5645. return destType;
  5646. }
  5647. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5648. if (getLangOpts().ObjCAutoRefCount) {
  5649. // ARC forbids the implicit conversion of object pointers to 'void *',
  5650. // so these types are not compatible.
  5651. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5652. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5653. LHS = RHS = true;
  5654. return QualType();
  5655. }
  5656. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5657. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5658. QualType destPointee
  5659. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5660. QualType destType = Context.getPointerType(destPointee);
  5661. // Add qualifiers if necessary.
  5662. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5663. // Promote to void*.
  5664. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5665. return destType;
  5666. }
  5667. return QualType();
  5668. }
  5669. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5670. /// ParenRange in parentheses.
  5671. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5672. const PartialDiagnostic &Note,
  5673. SourceRange ParenRange) {
  5674. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5675. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5676. EndLoc.isValid()) {
  5677. Self.Diag(Loc, Note)
  5678. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5679. << FixItHint::CreateInsertion(EndLoc, ")");
  5680. } else {
  5681. // We can't display the parentheses, so just show the bare note.
  5682. Self.Diag(Loc, Note) << ParenRange;
  5683. }
  5684. }
  5685. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5686. return Opc >= BO_Mul && Opc <= BO_Shr;
  5687. }
  5688. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5689. /// expression, either using a built-in or overloaded operator,
  5690. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5691. /// expression.
  5692. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5693. Expr **RHSExprs) {
  5694. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5695. E = E->IgnoreImpCasts();
  5696. E = E->IgnoreConversionOperator();
  5697. E = E->IgnoreImpCasts();
  5698. // Built-in binary operator.
  5699. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5700. if (IsArithmeticOp(OP->getOpcode())) {
  5701. *Opcode = OP->getOpcode();
  5702. *RHSExprs = OP->getRHS();
  5703. return true;
  5704. }
  5705. }
  5706. // Overloaded operator.
  5707. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5708. if (Call->getNumArgs() != 2)
  5709. return false;
  5710. // Make sure this is really a binary operator that is safe to pass into
  5711. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5712. OverloadedOperatorKind OO = Call->getOperator();
  5713. if (OO < OO_Plus || OO > OO_Arrow ||
  5714. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5715. return false;
  5716. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5717. if (IsArithmeticOp(OpKind)) {
  5718. *Opcode = OpKind;
  5719. *RHSExprs = Call->getArg(1);
  5720. return true;
  5721. }
  5722. }
  5723. return false;
  5724. }
  5725. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5726. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5727. }
  5728. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5729. /// or is a logical expression such as (x==y) which has int type, but is
  5730. /// commonly interpreted as boolean.
  5731. static bool ExprLooksBoolean(Expr *E) {
  5732. E = E->IgnoreParenImpCasts();
  5733. if (E->getType()->isBooleanType())
  5734. return true;
  5735. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5736. return IsLogicOp(OP->getOpcode());
  5737. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5738. return OP->getOpcode() == UO_LNot;
  5739. if (E->getType()->isPointerType())
  5740. return true;
  5741. return false;
  5742. }
  5743. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5744. /// and binary operator are mixed in a way that suggests the programmer assumed
  5745. /// the conditional operator has higher precedence, for example:
  5746. /// "int x = a + someBinaryCondition ? 1 : 2".
  5747. static void DiagnoseConditionalPrecedence(Sema &Self,
  5748. SourceLocation OpLoc,
  5749. Expr *Condition,
  5750. Expr *LHSExpr,
  5751. Expr *RHSExpr) {
  5752. BinaryOperatorKind CondOpcode;
  5753. Expr *CondRHS;
  5754. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5755. return;
  5756. if (!ExprLooksBoolean(CondRHS))
  5757. return;
  5758. // The condition is an arithmetic binary expression, with a right-
  5759. // hand side that looks boolean, so warn.
  5760. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5761. << Condition->getSourceRange()
  5762. << BinaryOperator::getOpcodeStr(CondOpcode);
  5763. SuggestParentheses(Self, OpLoc,
  5764. Self.PDiag(diag::note_precedence_silence)
  5765. << BinaryOperator::getOpcodeStr(CondOpcode),
  5766. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5767. SuggestParentheses(Self, OpLoc,
  5768. Self.PDiag(diag::note_precedence_conditional_first),
  5769. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5770. }
  5771. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5772. /// in the case of a the GNU conditional expr extension.
  5773. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5774. SourceLocation ColonLoc,
  5775. Expr *CondExpr, Expr *LHSExpr,
  5776. Expr *RHSExpr) {
  5777. if (!getLangOpts().CPlusPlus) {
  5778. // C cannot handle TypoExpr nodes in the condition because it
  5779. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5780. // been dealt with before checking the operands.
  5781. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5782. if (!CondResult.isUsable()) return ExprError();
  5783. CondExpr = CondResult.get();
  5784. }
  5785. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5786. // was the condition.
  5787. OpaqueValueExpr *opaqueValue = nullptr;
  5788. Expr *commonExpr = nullptr;
  5789. if (!LHSExpr) {
  5790. commonExpr = CondExpr;
  5791. // Lower out placeholder types first. This is important so that we don't
  5792. // try to capture a placeholder. This happens in few cases in C++; such
  5793. // as Objective-C++'s dictionary subscripting syntax.
  5794. if (commonExpr->hasPlaceholderType()) {
  5795. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5796. if (!result.isUsable()) return ExprError();
  5797. commonExpr = result.get();
  5798. }
  5799. // We usually want to apply unary conversions *before* saving, except
  5800. // in the special case of a C++ l-value conditional.
  5801. if (!(getLangOpts().CPlusPlus
  5802. && !commonExpr->isTypeDependent()
  5803. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5804. && commonExpr->isGLValue()
  5805. && commonExpr->isOrdinaryOrBitFieldObject()
  5806. && RHSExpr->isOrdinaryOrBitFieldObject()
  5807. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5808. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5809. if (commonRes.isInvalid())
  5810. return ExprError();
  5811. commonExpr = commonRes.get();
  5812. }
  5813. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5814. commonExpr->getType(),
  5815. commonExpr->getValueKind(),
  5816. commonExpr->getObjectKind(),
  5817. commonExpr);
  5818. LHSExpr = CondExpr = opaqueValue;
  5819. }
  5820. ExprValueKind VK = VK_RValue;
  5821. ExprObjectKind OK = OK_Ordinary;
  5822. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5823. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5824. VK, OK, QuestionLoc);
  5825. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5826. RHS.isInvalid())
  5827. return ExprError();
  5828. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5829. RHS.get());
  5830. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5831. if (!commonExpr)
  5832. return new (Context)
  5833. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5834. RHS.get(), result, VK, OK);
  5835. return new (Context) BinaryConditionalOperator(
  5836. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5837. ColonLoc, result, VK, OK);
  5838. }
  5839. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5840. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5841. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5842. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5843. // FIXME: add a couple examples in this comment.
  5844. static Sema::AssignConvertType
  5845. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5846. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5847. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5848. // get the "pointed to" type (ignoring qualifiers at the top level)
  5849. const Type *lhptee, *rhptee;
  5850. Qualifiers lhq, rhq;
  5851. std::tie(lhptee, lhq) =
  5852. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5853. std::tie(rhptee, rhq) =
  5854. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5855. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5856. // C99 6.5.16.1p1: This following citation is common to constraints
  5857. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5858. // qualifiers of the type *pointed to* by the right;
  5859. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5860. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5861. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5862. // Ignore lifetime for further calculation.
  5863. lhq.removeObjCLifetime();
  5864. rhq.removeObjCLifetime();
  5865. }
  5866. if (!lhq.compatiblyIncludes(rhq)) {
  5867. // Treat address-space mismatches as fatal. TODO: address subspaces
  5868. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5869. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5870. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5871. // and from void*.
  5872. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5873. .compatiblyIncludes(
  5874. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5875. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5876. ; // keep old
  5877. // Treat lifetime mismatches as fatal.
  5878. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5879. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5880. // For GCC compatibility, other qualifier mismatches are treated
  5881. // as still compatible in C.
  5882. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5883. }
  5884. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5885. // incomplete type and the other is a pointer to a qualified or unqualified
  5886. // version of void...
  5887. if (lhptee->isVoidType()) {
  5888. if (rhptee->isIncompleteOrObjectType())
  5889. return ConvTy;
  5890. // As an extension, we allow cast to/from void* to function pointer.
  5891. assert(rhptee->isFunctionType());
  5892. return Sema::FunctionVoidPointer;
  5893. }
  5894. if (rhptee->isVoidType()) {
  5895. if (lhptee->isIncompleteOrObjectType())
  5896. return ConvTy;
  5897. // As an extension, we allow cast to/from void* to function pointer.
  5898. assert(lhptee->isFunctionType());
  5899. return Sema::FunctionVoidPointer;
  5900. }
  5901. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5902. // unqualified versions of compatible types, ...
  5903. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5904. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5905. // Check if the pointee types are compatible ignoring the sign.
  5906. // We explicitly check for char so that we catch "char" vs
  5907. // "unsigned char" on systems where "char" is unsigned.
  5908. if (lhptee->isCharType())
  5909. ltrans = S.Context.UnsignedCharTy;
  5910. else if (lhptee->hasSignedIntegerRepresentation())
  5911. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5912. if (rhptee->isCharType())
  5913. rtrans = S.Context.UnsignedCharTy;
  5914. else if (rhptee->hasSignedIntegerRepresentation())
  5915. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5916. if (ltrans == rtrans) {
  5917. // Types are compatible ignoring the sign. Qualifier incompatibility
  5918. // takes priority over sign incompatibility because the sign
  5919. // warning can be disabled.
  5920. if (ConvTy != Sema::Compatible)
  5921. return ConvTy;
  5922. return Sema::IncompatiblePointerSign;
  5923. }
  5924. // If we are a multi-level pointer, it's possible that our issue is simply
  5925. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5926. // the eventual target type is the same and the pointers have the same
  5927. // level of indirection, this must be the issue.
  5928. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5929. do {
  5930. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5931. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5932. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5933. if (lhptee == rhptee)
  5934. return Sema::IncompatibleNestedPointerQualifiers;
  5935. }
  5936. // General pointer incompatibility takes priority over qualifiers.
  5937. return Sema::IncompatiblePointer;
  5938. }
  5939. if (!S.getLangOpts().CPlusPlus &&
  5940. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  5941. return Sema::IncompatiblePointer;
  5942. return ConvTy;
  5943. }
  5944. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  5945. /// block pointer types are compatible or whether a block and normal pointer
  5946. /// are compatible. It is more restrict than comparing two function pointer
  5947. // types.
  5948. static Sema::AssignConvertType
  5949. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  5950. QualType RHSType) {
  5951. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5952. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5953. QualType lhptee, rhptee;
  5954. // get the "pointed to" type (ignoring qualifiers at the top level)
  5955. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  5956. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  5957. // In C++, the types have to match exactly.
  5958. if (S.getLangOpts().CPlusPlus)
  5959. return Sema::IncompatibleBlockPointer;
  5960. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5961. // For blocks we enforce that qualifiers are identical.
  5962. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  5963. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5964. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  5965. return Sema::IncompatibleBlockPointer;
  5966. return ConvTy;
  5967. }
  5968. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  5969. /// for assignment compatibility.
  5970. static Sema::AssignConvertType
  5971. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  5972. QualType RHSType) {
  5973. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  5974. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  5975. if (LHSType->isObjCBuiltinType()) {
  5976. // Class is not compatible with ObjC object pointers.
  5977. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  5978. !RHSType->isObjCQualifiedClassType())
  5979. return Sema::IncompatiblePointer;
  5980. return Sema::Compatible;
  5981. }
  5982. if (RHSType->isObjCBuiltinType()) {
  5983. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  5984. !LHSType->isObjCQualifiedClassType())
  5985. return Sema::IncompatiblePointer;
  5986. return Sema::Compatible;
  5987. }
  5988. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5989. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5990. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  5991. // make an exception for id<P>
  5992. !LHSType->isObjCQualifiedIdType())
  5993. return Sema::CompatiblePointerDiscardsQualifiers;
  5994. if (S.Context.typesAreCompatible(LHSType, RHSType))
  5995. return Sema::Compatible;
  5996. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  5997. return Sema::IncompatibleObjCQualifiedId;
  5998. return Sema::IncompatiblePointer;
  5999. }
  6000. Sema::AssignConvertType
  6001. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6002. QualType LHSType, QualType RHSType) {
  6003. // Fake up an opaque expression. We don't actually care about what
  6004. // cast operations are required, so if CheckAssignmentConstraints
  6005. // adds casts to this they'll be wasted, but fortunately that doesn't
  6006. // usually happen on valid code.
  6007. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6008. ExprResult RHSPtr = &RHSExpr;
  6009. CastKind K = CK_Invalid;
  6010. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  6011. }
  6012. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6013. /// has code to accommodate several GCC extensions when type checking
  6014. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6015. ///
  6016. /// int a, *pint;
  6017. /// short *pshort;
  6018. /// struct foo *pfoo;
  6019. ///
  6020. /// pint = pshort; // warning: assignment from incompatible pointer type
  6021. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6022. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6023. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6024. ///
  6025. /// As a result, the code for dealing with pointers is more complex than the
  6026. /// C99 spec dictates.
  6027. ///
  6028. /// Sets 'Kind' for any result kind except Incompatible.
  6029. Sema::AssignConvertType
  6030. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6031. CastKind &Kind) {
  6032. QualType RHSType = RHS.get()->getType();
  6033. QualType OrigLHSType = LHSType;
  6034. // Get canonical types. We're not formatting these types, just comparing
  6035. // them.
  6036. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6037. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6038. // Common case: no conversion required.
  6039. if (LHSType == RHSType) {
  6040. Kind = CK_NoOp;
  6041. return Compatible;
  6042. }
  6043. // If we have an atomic type, try a non-atomic assignment, then just add an
  6044. // atomic qualification step.
  6045. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6046. Sema::AssignConvertType result =
  6047. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6048. if (result != Compatible)
  6049. return result;
  6050. if (Kind != CK_NoOp)
  6051. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6052. Kind = CK_NonAtomicToAtomic;
  6053. return Compatible;
  6054. }
  6055. // If the left-hand side is a reference type, then we are in a
  6056. // (rare!) case where we've allowed the use of references in C,
  6057. // e.g., as a parameter type in a built-in function. In this case,
  6058. // just make sure that the type referenced is compatible with the
  6059. // right-hand side type. The caller is responsible for adjusting
  6060. // LHSType so that the resulting expression does not have reference
  6061. // type.
  6062. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6063. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6064. Kind = CK_LValueBitCast;
  6065. return Compatible;
  6066. }
  6067. return Incompatible;
  6068. }
  6069. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6070. // to the same ExtVector type.
  6071. if (LHSType->isExtVectorType()) {
  6072. if (RHSType->isExtVectorType())
  6073. return Incompatible;
  6074. if (RHSType->isArithmeticType()) {
  6075. // CK_VectorSplat does T -> vector T, so first cast to the
  6076. // element type.
  6077. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  6078. if (elType != RHSType) {
  6079. Kind = PrepareScalarCast(RHS, elType);
  6080. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  6081. }
  6082. Kind = CK_VectorSplat;
  6083. return Compatible;
  6084. }
  6085. }
  6086. // Conversions to or from vector type.
  6087. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6088. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6089. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6090. // vector type and vice versa
  6091. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6092. Kind = CK_BitCast;
  6093. return Compatible;
  6094. }
  6095. // If we are allowing lax vector conversions, and LHS and RHS are both
  6096. // vectors, the total size only needs to be the same. This is a bitcast;
  6097. // no bits are changed but the result type is different.
  6098. if (isLaxVectorConversion(RHSType, LHSType)) {
  6099. Kind = CK_BitCast;
  6100. return IncompatibleVectors;
  6101. }
  6102. }
  6103. return Incompatible;
  6104. }
  6105. // Arithmetic conversions.
  6106. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6107. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6108. Kind = PrepareScalarCast(RHS, LHSType);
  6109. return Compatible;
  6110. }
  6111. // Conversions to normal pointers.
  6112. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6113. // U* -> T*
  6114. if (isa<PointerType>(RHSType)) {
  6115. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6116. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6117. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6118. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6119. }
  6120. // int -> T*
  6121. if (RHSType->isIntegerType()) {
  6122. Kind = CK_IntegralToPointer; // FIXME: null?
  6123. return IntToPointer;
  6124. }
  6125. // C pointers are not compatible with ObjC object pointers,
  6126. // with two exceptions:
  6127. if (isa<ObjCObjectPointerType>(RHSType)) {
  6128. // - conversions to void*
  6129. if (LHSPointer->getPointeeType()->isVoidType()) {
  6130. Kind = CK_BitCast;
  6131. return Compatible;
  6132. }
  6133. // - conversions from 'Class' to the redefinition type
  6134. if (RHSType->isObjCClassType() &&
  6135. Context.hasSameType(LHSType,
  6136. Context.getObjCClassRedefinitionType())) {
  6137. Kind = CK_BitCast;
  6138. return Compatible;
  6139. }
  6140. Kind = CK_BitCast;
  6141. return IncompatiblePointer;
  6142. }
  6143. // U^ -> void*
  6144. if (RHSType->getAs<BlockPointerType>()) {
  6145. if (LHSPointer->getPointeeType()->isVoidType()) {
  6146. Kind = CK_BitCast;
  6147. return Compatible;
  6148. }
  6149. }
  6150. return Incompatible;
  6151. }
  6152. // Conversions to block pointers.
  6153. if (isa<BlockPointerType>(LHSType)) {
  6154. // U^ -> T^
  6155. if (RHSType->isBlockPointerType()) {
  6156. Kind = CK_BitCast;
  6157. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6158. }
  6159. // int or null -> T^
  6160. if (RHSType->isIntegerType()) {
  6161. Kind = CK_IntegralToPointer; // FIXME: null
  6162. return IntToBlockPointer;
  6163. }
  6164. // id -> T^
  6165. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6166. Kind = CK_AnyPointerToBlockPointerCast;
  6167. return Compatible;
  6168. }
  6169. // void* -> T^
  6170. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6171. if (RHSPT->getPointeeType()->isVoidType()) {
  6172. Kind = CK_AnyPointerToBlockPointerCast;
  6173. return Compatible;
  6174. }
  6175. return Incompatible;
  6176. }
  6177. // Conversions to Objective-C pointers.
  6178. if (isa<ObjCObjectPointerType>(LHSType)) {
  6179. // A* -> B*
  6180. if (RHSType->isObjCObjectPointerType()) {
  6181. Kind = CK_BitCast;
  6182. Sema::AssignConvertType result =
  6183. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6184. if (getLangOpts().ObjCAutoRefCount &&
  6185. result == Compatible &&
  6186. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6187. result = IncompatibleObjCWeakRef;
  6188. return result;
  6189. }
  6190. // int or null -> A*
  6191. if (RHSType->isIntegerType()) {
  6192. Kind = CK_IntegralToPointer; // FIXME: null
  6193. return IntToPointer;
  6194. }
  6195. // In general, C pointers are not compatible with ObjC object pointers,
  6196. // with two exceptions:
  6197. if (isa<PointerType>(RHSType)) {
  6198. Kind = CK_CPointerToObjCPointerCast;
  6199. // - conversions from 'void*'
  6200. if (RHSType->isVoidPointerType()) {
  6201. return Compatible;
  6202. }
  6203. // - conversions to 'Class' from its redefinition type
  6204. if (LHSType->isObjCClassType() &&
  6205. Context.hasSameType(RHSType,
  6206. Context.getObjCClassRedefinitionType())) {
  6207. return Compatible;
  6208. }
  6209. return IncompatiblePointer;
  6210. }
  6211. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6212. if (RHSType->isBlockPointerType() &&
  6213. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6214. maybeExtendBlockObject(RHS);
  6215. Kind = CK_BlockPointerToObjCPointerCast;
  6216. return Compatible;
  6217. }
  6218. return Incompatible;
  6219. }
  6220. // Conversions from pointers that are not covered by the above.
  6221. if (isa<PointerType>(RHSType)) {
  6222. // T* -> _Bool
  6223. if (LHSType == Context.BoolTy) {
  6224. Kind = CK_PointerToBoolean;
  6225. return Compatible;
  6226. }
  6227. // T* -> int
  6228. if (LHSType->isIntegerType()) {
  6229. Kind = CK_PointerToIntegral;
  6230. return PointerToInt;
  6231. }
  6232. return Incompatible;
  6233. }
  6234. // Conversions from Objective-C pointers that are not covered by the above.
  6235. if (isa<ObjCObjectPointerType>(RHSType)) {
  6236. // T* -> _Bool
  6237. if (LHSType == Context.BoolTy) {
  6238. Kind = CK_PointerToBoolean;
  6239. return Compatible;
  6240. }
  6241. // T* -> int
  6242. if (LHSType->isIntegerType()) {
  6243. Kind = CK_PointerToIntegral;
  6244. return PointerToInt;
  6245. }
  6246. return Incompatible;
  6247. }
  6248. // struct A -> struct B
  6249. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6250. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6251. Kind = CK_NoOp;
  6252. return Compatible;
  6253. }
  6254. }
  6255. return Incompatible;
  6256. }
  6257. /// \brief Constructs a transparent union from an expression that is
  6258. /// used to initialize the transparent union.
  6259. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6260. ExprResult &EResult, QualType UnionType,
  6261. FieldDecl *Field) {
  6262. // Build an initializer list that designates the appropriate member
  6263. // of the transparent union.
  6264. Expr *E = EResult.get();
  6265. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6266. E, SourceLocation());
  6267. Initializer->setType(UnionType);
  6268. Initializer->setInitializedFieldInUnion(Field);
  6269. // Build a compound literal constructing a value of the transparent
  6270. // union type from this initializer list.
  6271. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6272. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6273. VK_RValue, Initializer, false);
  6274. }
  6275. Sema::AssignConvertType
  6276. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6277. ExprResult &RHS) {
  6278. QualType RHSType = RHS.get()->getType();
  6279. // If the ArgType is a Union type, we want to handle a potential
  6280. // transparent_union GCC extension.
  6281. const RecordType *UT = ArgType->getAsUnionType();
  6282. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6283. return Incompatible;
  6284. // The field to initialize within the transparent union.
  6285. RecordDecl *UD = UT->getDecl();
  6286. FieldDecl *InitField = nullptr;
  6287. // It's compatible if the expression matches any of the fields.
  6288. for (auto *it : UD->fields()) {
  6289. if (it->getType()->isPointerType()) {
  6290. // If the transparent union contains a pointer type, we allow:
  6291. // 1) void pointer
  6292. // 2) null pointer constant
  6293. if (RHSType->isPointerType())
  6294. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6295. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6296. InitField = it;
  6297. break;
  6298. }
  6299. if (RHS.get()->isNullPointerConstant(Context,
  6300. Expr::NPC_ValueDependentIsNull)) {
  6301. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6302. CK_NullToPointer);
  6303. InitField = it;
  6304. break;
  6305. }
  6306. }
  6307. CastKind Kind = CK_Invalid;
  6308. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6309. == Compatible) {
  6310. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6311. InitField = it;
  6312. break;
  6313. }
  6314. }
  6315. if (!InitField)
  6316. return Incompatible;
  6317. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6318. return Compatible;
  6319. }
  6320. Sema::AssignConvertType
  6321. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6322. bool Diagnose,
  6323. bool DiagnoseCFAudited) {
  6324. // HLSL Change Starts
  6325. if (getLangOpts().HLSL) {
  6326. // DiagnoseAssignmentResultForHLSL will take care of diagnostics.
  6327. return Compatible;
  6328. }
  6329. // HLSL Change Ends
  6330. if (getLangOpts().CPlusPlus) {
  6331. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6332. // C++ 5.17p3: If the left operand is not of class type, the
  6333. // expression is implicitly converted (C++ 4) to the
  6334. // cv-unqualified type of the left operand.
  6335. ExprResult Res;
  6336. if (Diagnose) {
  6337. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6338. AA_Assigning);
  6339. } else {
  6340. ImplicitConversionSequence ICS =
  6341. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6342. /*SuppressUserConversions=*/false,
  6343. /*AllowExplicit=*/false,
  6344. /*InOverloadResolution=*/false,
  6345. /*CStyle=*/false,
  6346. /*AllowObjCWritebackConversion=*/false);
  6347. if (ICS.isFailure())
  6348. return Incompatible;
  6349. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6350. ICS, AA_Assigning);
  6351. }
  6352. if (Res.isInvalid())
  6353. return Incompatible;
  6354. Sema::AssignConvertType result = Compatible;
  6355. if (getLangOpts().ObjCAutoRefCount &&
  6356. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6357. RHS.get()->getType()))
  6358. result = IncompatibleObjCWeakRef;
  6359. RHS = Res;
  6360. return result;
  6361. }
  6362. // FIXME: Currently, we fall through and treat C++ classes like C
  6363. // structures.
  6364. // FIXME: We also fall through for atomics; not sure what should
  6365. // happen there, though.
  6366. }
  6367. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6368. // a null pointer constant.
  6369. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6370. LHSType->isBlockPointerType()) &&
  6371. RHS.get()->isNullPointerConstant(Context,
  6372. Expr::NPC_ValueDependentIsNull)) {
  6373. CastKind Kind;
  6374. CXXCastPath Path;
  6375. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6376. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6377. return Compatible;
  6378. }
  6379. // This check seems unnatural, however it is necessary to ensure the proper
  6380. // conversion of functions/arrays. If the conversion were done for all
  6381. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6382. // expressions that suppress this implicit conversion (&, sizeof).
  6383. //
  6384. // Suppress this for references: C++ 8.5.3p5.
  6385. if (!LHSType->isReferenceType()) {
  6386. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6387. if (RHS.isInvalid())
  6388. return Incompatible;
  6389. }
  6390. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6391. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6392. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6393. if (PDecl && !PDecl->hasDefinition()) {
  6394. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6395. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6396. }
  6397. }
  6398. CastKind Kind = CK_Invalid;
  6399. Sema::AssignConvertType result =
  6400. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6401. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6402. // type of the assignment expression.
  6403. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6404. // so that we can use references in built-in functions even in C.
  6405. // The getNonReferenceType() call makes sure that the resulting expression
  6406. // does not have reference type.
  6407. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6408. QualType Ty = LHSType.getNonLValueExprType(Context);
  6409. Expr *E = RHS.get();
  6410. if (getLangOpts().ObjCAutoRefCount)
  6411. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6412. DiagnoseCFAudited);
  6413. if (getLangOpts().ObjC1 &&
  6414. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6415. LHSType, E->getType(), E) ||
  6416. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6417. RHS = E;
  6418. return Compatible;
  6419. }
  6420. RHS = ImpCastExprToType(E, Ty, Kind);
  6421. }
  6422. return result;
  6423. }
  6424. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6425. ExprResult &RHS) {
  6426. Diag(Loc, diag::err_typecheck_invalid_operands)
  6427. << LHS.get()->getType() << RHS.get()->getType()
  6428. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6429. return QualType();
  6430. }
  6431. /// Try to convert a value of non-vector type to a vector type by converting
  6432. /// the type to the element type of the vector and then performing a splat.
  6433. /// If the language is OpenCL, we only use conversions that promote scalar
  6434. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6435. /// for float->int.
  6436. ///
  6437. /// \param scalar - if non-null, actually perform the conversions
  6438. /// \return true if the operation fails (but without diagnosing the failure)
  6439. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6440. QualType scalarTy,
  6441. QualType vectorEltTy,
  6442. QualType vectorTy) {
  6443. // The conversion to apply to the scalar before splatting it,
  6444. // if necessary.
  6445. CastKind scalarCast = CK_Invalid;
  6446. if (vectorEltTy->isIntegralType(S.Context)) {
  6447. if (!scalarTy->isIntegralType(S.Context))
  6448. return true;
  6449. if (S.getLangOpts().OpenCL &&
  6450. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6451. return true;
  6452. scalarCast = CK_IntegralCast;
  6453. } else if (vectorEltTy->isRealFloatingType()) {
  6454. if (scalarTy->isRealFloatingType()) {
  6455. if (S.getLangOpts().OpenCL &&
  6456. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6457. return true;
  6458. scalarCast = CK_FloatingCast;
  6459. }
  6460. else if (scalarTy->isIntegralType(S.Context))
  6461. scalarCast = CK_IntegralToFloating;
  6462. else
  6463. return true;
  6464. } else {
  6465. return true;
  6466. }
  6467. // Adjust scalar if desired.
  6468. if (scalar) {
  6469. if (scalarCast != CK_Invalid)
  6470. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6471. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6472. }
  6473. return false;
  6474. }
  6475. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6476. SourceLocation Loc, bool IsCompAssign,
  6477. bool AllowBothBool,
  6478. bool AllowBoolConversions) {
  6479. if (!IsCompAssign) {
  6480. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6481. if (LHS.isInvalid())
  6482. return QualType();
  6483. }
  6484. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6485. if (RHS.isInvalid())
  6486. return QualType();
  6487. // For conversion purposes, we ignore any qualifiers.
  6488. // For example, "const float" and "float" are equivalent.
  6489. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6490. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6491. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6492. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6493. assert(LHSVecType || RHSVecType);
  6494. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6495. // for some operators but not others.
  6496. if (!AllowBothBool &&
  6497. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6498. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6499. return InvalidOperands(Loc, LHS, RHS);
  6500. // If the vector types are identical, return.
  6501. if (Context.hasSameType(LHSType, RHSType))
  6502. return LHSType;
  6503. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6504. if (LHSVecType && RHSVecType &&
  6505. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6506. if (isa<ExtVectorType>(LHSVecType)) {
  6507. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6508. return LHSType;
  6509. }
  6510. if (!IsCompAssign)
  6511. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6512. return RHSType;
  6513. }
  6514. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6515. // can be mixed, with the result being the non-bool type. The non-bool
  6516. // operand must have integer element type.
  6517. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6518. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6519. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6520. Context.getTypeSize(RHSVecType->getElementType()))) {
  6521. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6522. LHSVecType->getElementType()->isIntegerType() &&
  6523. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6524. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6525. return LHSType;
  6526. }
  6527. if (!IsCompAssign &&
  6528. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6529. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6530. RHSVecType->getElementType()->isIntegerType()) {
  6531. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6532. return RHSType;
  6533. }
  6534. }
  6535. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6536. // the vector element type and splat.
  6537. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6538. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6539. LHSVecType->getElementType(), LHSType))
  6540. return LHSType;
  6541. }
  6542. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6543. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6544. LHSType, RHSVecType->getElementType(),
  6545. RHSType))
  6546. return RHSType;
  6547. }
  6548. // If we're allowing lax vector conversions, only the total (data) size
  6549. // needs to be the same.
  6550. // FIXME: Should we really be allowing this?
  6551. // FIXME: We really just pick the LHS type arbitrarily?
  6552. if (isLaxVectorConversion(RHSType, LHSType)) {
  6553. QualType resultType = LHSType;
  6554. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6555. return resultType;
  6556. }
  6557. // Okay, the expression is invalid.
  6558. // If there's a non-vector, non-real operand, diagnose that.
  6559. if ((!RHSVecType && !RHSType->isRealType()) ||
  6560. (!LHSVecType && !LHSType->isRealType())) {
  6561. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6562. << LHSType << RHSType
  6563. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6564. return QualType();
  6565. }
  6566. // Otherwise, use the generic diagnostic.
  6567. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6568. << LHSType << RHSType
  6569. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6570. return QualType();
  6571. }
  6572. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6573. // expression. These are mainly cases where the null pointer is used as an
  6574. // integer instead of a pointer.
  6575. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6576. SourceLocation Loc, bool IsCompare) {
  6577. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6578. // but we use a bit of a hack here for speed; this is a relatively
  6579. // hot path, and isNullPointerConstant is slow.
  6580. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6581. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6582. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6583. // Avoid analyzing cases where the result will either be invalid (and
  6584. // diagnosed as such) or entirely valid and not something to warn about.
  6585. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6586. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6587. return;
  6588. // Comparison operations would not make sense with a null pointer no matter
  6589. // what the other expression is.
  6590. if (!IsCompare) {
  6591. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6592. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6593. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6594. return;
  6595. }
  6596. // The rest of the operations only make sense with a null pointer
  6597. // if the other expression is a pointer.
  6598. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6599. NonNullType->canDecayToPointerType())
  6600. return;
  6601. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6602. << LHSNull /* LHS is NULL */ << NonNullType
  6603. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6604. }
  6605. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6606. SourceLocation Loc,
  6607. bool IsCompAssign, bool IsDiv) {
  6608. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6609. if (LHS.get()->getType()->isVectorType() ||
  6610. RHS.get()->getType()->isVectorType())
  6611. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6612. /*AllowBothBool*/getLangOpts().AltiVec,
  6613. /*AllowBoolConversions*/false);
  6614. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6615. if (LHS.isInvalid() || RHS.isInvalid())
  6616. return QualType();
  6617. if (compType.isNull() || !compType->isArithmeticType())
  6618. return InvalidOperands(Loc, LHS, RHS);
  6619. // Check for division by zero.
  6620. llvm::APSInt RHSValue;
  6621. if (IsDiv && !RHS.get()->isValueDependent() &&
  6622. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6623. DiagRuntimeBehavior(Loc, RHS.get(),
  6624. PDiag(diag::warn_division_by_zero)
  6625. << RHS.get()->getSourceRange());
  6626. return compType;
  6627. }
  6628. QualType Sema::CheckRemainderOperands(
  6629. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6630. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6631. if (LHS.get()->getType()->isVectorType() ||
  6632. RHS.get()->getType()->isVectorType()) {
  6633. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6634. RHS.get()->getType()->hasIntegerRepresentation())
  6635. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6636. /*AllowBothBool*/getLangOpts().AltiVec,
  6637. /*AllowBoolConversions*/false);
  6638. return InvalidOperands(Loc, LHS, RHS);
  6639. }
  6640. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6641. if (LHS.isInvalid() || RHS.isInvalid())
  6642. return QualType();
  6643. if (compType.isNull() || !compType->isIntegerType())
  6644. return InvalidOperands(Loc, LHS, RHS);
  6645. // Check for remainder by zero.
  6646. llvm::APSInt RHSValue;
  6647. if (!RHS.get()->isValueDependent() &&
  6648. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6649. DiagRuntimeBehavior(Loc, RHS.get(),
  6650. PDiag(diag::warn_remainder_by_zero)
  6651. << RHS.get()->getSourceRange());
  6652. return compType;
  6653. }
  6654. /// \brief Diagnose invalid arithmetic on two void pointers.
  6655. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6656. Expr *LHSExpr, Expr *RHSExpr) {
  6657. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6658. ? diag::err_typecheck_pointer_arith_void_type
  6659. : diag::ext_gnu_void_ptr)
  6660. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6661. << RHSExpr->getSourceRange();
  6662. }
  6663. /// \brief Diagnose invalid arithmetic on a void pointer.
  6664. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6665. Expr *Pointer) {
  6666. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6667. ? diag::err_typecheck_pointer_arith_void_type
  6668. : diag::ext_gnu_void_ptr)
  6669. << 0 /* one pointer */ << Pointer->getSourceRange();
  6670. }
  6671. /// \brief Diagnose invalid arithmetic on two function pointers.
  6672. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6673. Expr *LHS, Expr *RHS) {
  6674. assert(LHS->getType()->isAnyPointerType());
  6675. assert(RHS->getType()->isAnyPointerType());
  6676. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6677. ? diag::err_typecheck_pointer_arith_function_type
  6678. : diag::ext_gnu_ptr_func_arith)
  6679. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6680. // We only show the second type if it differs from the first.
  6681. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6682. RHS->getType())
  6683. << RHS->getType()->getPointeeType()
  6684. << LHS->getSourceRange() << RHS->getSourceRange();
  6685. }
  6686. /// \brief Diagnose invalid arithmetic on a function pointer.
  6687. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6688. Expr *Pointer) {
  6689. assert(Pointer->getType()->isAnyPointerType());
  6690. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6691. ? diag::err_typecheck_pointer_arith_function_type
  6692. : diag::ext_gnu_ptr_func_arith)
  6693. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6694. << 0 /* one pointer, so only one type */
  6695. << Pointer->getSourceRange();
  6696. }
  6697. /// \brief Emit error if Operand is incomplete pointer type
  6698. ///
  6699. /// \returns True if pointer has incomplete type
  6700. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6701. Expr *Operand) {
  6702. QualType ResType = Operand->getType();
  6703. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6704. ResType = ResAtomicType->getValueType();
  6705. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6706. QualType PointeeTy = ResType->getPointeeType();
  6707. return S.RequireCompleteType(Loc, PointeeTy,
  6708. diag::err_typecheck_arithmetic_incomplete_type,
  6709. PointeeTy, Operand->getSourceRange());
  6710. }
  6711. /// \brief Check the validity of an arithmetic pointer operand.
  6712. ///
  6713. /// If the operand has pointer type, this code will check for pointer types
  6714. /// which are invalid in arithmetic operations. These will be diagnosed
  6715. /// appropriately, including whether or not the use is supported as an
  6716. /// extension.
  6717. ///
  6718. /// \returns True when the operand is valid to use (even if as an extension).
  6719. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6720. Expr *Operand) {
  6721. QualType ResType = Operand->getType();
  6722. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6723. ResType = ResAtomicType->getValueType();
  6724. if (!ResType->isAnyPointerType()) return true;
  6725. QualType PointeeTy = ResType->getPointeeType();
  6726. if (PointeeTy->isVoidType()) {
  6727. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6728. return !S.getLangOpts().CPlusPlus;
  6729. }
  6730. if (PointeeTy->isFunctionType()) {
  6731. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6732. return !S.getLangOpts().CPlusPlus;
  6733. }
  6734. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6735. return true;
  6736. }
  6737. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6738. /// operands.
  6739. ///
  6740. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6741. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6742. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6743. /// are (potentially problematic) pointers.
  6744. ///
  6745. /// \returns True when the operand is valid to use (even if as an extension).
  6746. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6747. Expr *LHSExpr, Expr *RHSExpr) {
  6748. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6749. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6750. if (!isLHSPointer && !isRHSPointer) return true;
  6751. QualType LHSPointeeTy, RHSPointeeTy;
  6752. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6753. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6754. // if both are pointers check if operation is valid wrt address spaces
  6755. if (isLHSPointer && isRHSPointer) {
  6756. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6757. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6758. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6759. S.Diag(Loc,
  6760. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6761. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6762. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6763. return false;
  6764. }
  6765. }
  6766. // Check for arithmetic on pointers to incomplete types.
  6767. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6768. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6769. if (isLHSVoidPtr || isRHSVoidPtr) {
  6770. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6771. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6772. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6773. return !S.getLangOpts().CPlusPlus;
  6774. }
  6775. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6776. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6777. if (isLHSFuncPtr || isRHSFuncPtr) {
  6778. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6779. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6780. RHSExpr);
  6781. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6782. return !S.getLangOpts().CPlusPlus;
  6783. }
  6784. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6785. return false;
  6786. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6787. return false;
  6788. return true;
  6789. }
  6790. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6791. /// literal.
  6792. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6793. Expr *LHSExpr, Expr *RHSExpr) {
  6794. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6795. Expr* IndexExpr = RHSExpr;
  6796. if (!StrExpr) {
  6797. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6798. IndexExpr = LHSExpr;
  6799. }
  6800. bool IsStringPlusInt = StrExpr &&
  6801. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6802. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6803. return;
  6804. llvm::APSInt index;
  6805. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6806. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6807. if (index.isNonNegative() &&
  6808. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6809. index.isUnsigned()))
  6810. return;
  6811. }
  6812. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6813. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6814. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6815. // Only print a fixit for "str" + int, not for int + "str".
  6816. if (IndexExpr == RHSExpr) {
  6817. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6818. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6819. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6820. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6821. << FixItHint::CreateInsertion(EndLoc, "]");
  6822. } else
  6823. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6824. }
  6825. /// \brief Emit a warning when adding a char literal to a string.
  6826. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6827. Expr *LHSExpr, Expr *RHSExpr) {
  6828. const Expr *StringRefExpr = LHSExpr;
  6829. const CharacterLiteral *CharExpr =
  6830. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6831. if (!CharExpr) {
  6832. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6833. StringRefExpr = RHSExpr;
  6834. }
  6835. if (!CharExpr || !StringRefExpr)
  6836. return;
  6837. const QualType StringType = StringRefExpr->getType();
  6838. // Return if not a PointerType.
  6839. if (!StringType->isAnyPointerType())
  6840. return;
  6841. // Return if not a CharacterType.
  6842. if (!StringType->getPointeeType()->isAnyCharacterType())
  6843. return;
  6844. ASTContext &Ctx = Self.getASTContext();
  6845. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6846. const QualType CharType = CharExpr->getType();
  6847. if (!CharType->isAnyCharacterType() &&
  6848. CharType->isIntegerType() &&
  6849. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6850. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6851. << DiagRange << Ctx.CharTy;
  6852. } else {
  6853. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6854. << DiagRange << CharExpr->getType();
  6855. }
  6856. // Only print a fixit for str + char, not for char + str.
  6857. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6858. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6859. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6860. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6861. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6862. << FixItHint::CreateInsertion(EndLoc, "]");
  6863. } else {
  6864. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6865. }
  6866. }
  6867. /// \brief Emit error when two pointers are incompatible.
  6868. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6869. Expr *LHSExpr, Expr *RHSExpr) {
  6870. assert(LHSExpr->getType()->isAnyPointerType());
  6871. assert(RHSExpr->getType()->isAnyPointerType());
  6872. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6873. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6874. << RHSExpr->getSourceRange();
  6875. }
  6876. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6877. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6878. QualType* CompLHSTy) {
  6879. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6880. if (LHS.get()->getType()->isVectorType() ||
  6881. RHS.get()->getType()->isVectorType()) {
  6882. QualType compType = CheckVectorOperands(
  6883. LHS, RHS, Loc, CompLHSTy,
  6884. /*AllowBothBool*/getLangOpts().AltiVec,
  6885. /*AllowBoolConversions*/getLangOpts().ZVector);
  6886. if (CompLHSTy) *CompLHSTy = compType;
  6887. return compType;
  6888. }
  6889. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6890. if (LHS.isInvalid() || RHS.isInvalid())
  6891. return QualType();
  6892. // Diagnose "string literal" '+' int and string '+' "char literal".
  6893. if (Opc == BO_Add) {
  6894. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6895. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6896. }
  6897. // handle the common case first (both operands are arithmetic).
  6898. if (!compType.isNull() && compType->isArithmeticType()) {
  6899. if (CompLHSTy) *CompLHSTy = compType;
  6900. return compType;
  6901. }
  6902. // Type-checking. Ultimately the pointer's going to be in PExp;
  6903. // note that we bias towards the LHS being the pointer.
  6904. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6905. bool isObjCPointer;
  6906. if (PExp->getType()->isPointerType()) {
  6907. isObjCPointer = false;
  6908. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6909. isObjCPointer = true;
  6910. } else {
  6911. std::swap(PExp, IExp);
  6912. if (PExp->getType()->isPointerType()) {
  6913. isObjCPointer = false;
  6914. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6915. isObjCPointer = true;
  6916. } else {
  6917. return InvalidOperands(Loc, LHS, RHS);
  6918. }
  6919. }
  6920. assert(PExp->getType()->isAnyPointerType());
  6921. if (!IExp->getType()->isIntegerType())
  6922. return InvalidOperands(Loc, LHS, RHS);
  6923. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6924. return QualType();
  6925. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6926. return QualType();
  6927. // Check array bounds for pointer arithemtic
  6928. CheckArrayAccess(PExp, IExp);
  6929. if (CompLHSTy) {
  6930. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6931. if (LHSTy.isNull()) {
  6932. LHSTy = LHS.get()->getType();
  6933. if (LHSTy->isPromotableIntegerType())
  6934. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6935. }
  6936. *CompLHSTy = LHSTy;
  6937. }
  6938. return PExp->getType();
  6939. }
  6940. // C99 6.5.6
  6941. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  6942. SourceLocation Loc,
  6943. QualType* CompLHSTy) {
  6944. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6945. if (LHS.get()->getType()->isVectorType() ||
  6946. RHS.get()->getType()->isVectorType()) {
  6947. QualType compType = CheckVectorOperands(
  6948. LHS, RHS, Loc, CompLHSTy,
  6949. /*AllowBothBool*/getLangOpts().AltiVec,
  6950. /*AllowBoolConversions*/getLangOpts().ZVector);
  6951. if (CompLHSTy) *CompLHSTy = compType;
  6952. return compType;
  6953. }
  6954. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6955. if (LHS.isInvalid() || RHS.isInvalid())
  6956. return QualType();
  6957. // Enforce type constraints: C99 6.5.6p3.
  6958. // Handle the common case first (both operands are arithmetic).
  6959. if (!compType.isNull() && compType->isArithmeticType()) {
  6960. if (CompLHSTy) *CompLHSTy = compType;
  6961. return compType;
  6962. }
  6963. // Either ptr - int or ptr - ptr.
  6964. if (LHS.get()->getType()->isAnyPointerType()) {
  6965. QualType lpointee = LHS.get()->getType()->getPointeeType();
  6966. // Diagnose bad cases where we step over interface counts.
  6967. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  6968. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  6969. return QualType();
  6970. // The result type of a pointer-int computation is the pointer type.
  6971. if (RHS.get()->getType()->isIntegerType()) {
  6972. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  6973. return QualType();
  6974. // Check array bounds for pointer arithemtic
  6975. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  6976. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  6977. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6978. return LHS.get()->getType();
  6979. }
  6980. // Handle pointer-pointer subtractions.
  6981. if (const PointerType *RHSPTy
  6982. = RHS.get()->getType()->getAs<PointerType>()) {
  6983. QualType rpointee = RHSPTy->getPointeeType();
  6984. if (getLangOpts().CPlusPlus) {
  6985. // Pointee types must be the same: C++ [expr.add]
  6986. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  6987. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6988. }
  6989. } else {
  6990. // Pointee types must be compatible C99 6.5.6p3
  6991. if (!Context.typesAreCompatible(
  6992. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  6993. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  6994. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6995. return QualType();
  6996. }
  6997. }
  6998. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  6999. LHS.get(), RHS.get()))
  7000. return QualType();
  7001. // The pointee type may have zero size. As an extension, a structure or
  7002. // union may have zero size or an array may have zero length. In this
  7003. // case subtraction does not make sense.
  7004. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7005. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7006. if (ElementSize.isZero()) {
  7007. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7008. << rpointee.getUnqualifiedType()
  7009. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7010. }
  7011. }
  7012. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7013. return Context.getPointerDiffType();
  7014. }
  7015. }
  7016. return InvalidOperands(Loc, LHS, RHS);
  7017. }
  7018. static bool isScopedEnumerationType(QualType T) {
  7019. if (const EnumType *ET = T->getAs<EnumType>())
  7020. return ET->getDecl()->isScoped();
  7021. return false;
  7022. }
  7023. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7024. SourceLocation Loc, unsigned Opc,
  7025. QualType LHSType) {
  7026. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7027. // so skip remaining warnings as we don't want to modify values within Sema.
  7028. if (S.getLangOpts().OpenCL)
  7029. return;
  7030. llvm::APSInt Right;
  7031. // Check right/shifter operand
  7032. if (RHS.get()->isValueDependent() ||
  7033. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7034. return;
  7035. if (Right.isNegative()) {
  7036. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7037. S.PDiag(diag::warn_shift_negative)
  7038. << RHS.get()->getSourceRange());
  7039. return;
  7040. }
  7041. llvm::APInt LeftBits(Right.getBitWidth(),
  7042. S.Context.getTypeSize(LHS.get()->getType()));
  7043. if (Right.uge(LeftBits)) {
  7044. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7045. S.PDiag(diag::warn_shift_gt_typewidth)
  7046. << RHS.get()->getSourceRange());
  7047. return;
  7048. }
  7049. if (Opc != BO_Shl)
  7050. return;
  7051. // When left shifting an ICE which is signed, we can check for overflow which
  7052. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7053. // integers have defined behavior modulo one more than the maximum value
  7054. // representable in the result type, so never warn for those.
  7055. llvm::APSInt Left;
  7056. if (LHS.get()->isValueDependent() ||
  7057. LHSType->hasUnsignedIntegerRepresentation() ||
  7058. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7059. return;
  7060. // If LHS does not have a signed type and non-negative value
  7061. // then, the behavior is undefined. Warn about it.
  7062. if (Left.isNegative()) {
  7063. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7064. S.PDiag(diag::warn_shift_lhs_negative)
  7065. << LHS.get()->getSourceRange());
  7066. return;
  7067. }
  7068. llvm::APInt ResultBits =
  7069. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7070. if (LeftBits.uge(ResultBits))
  7071. return;
  7072. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  7073. Result = Result.shl(Right);
  7074. // Print the bit representation of the signed integer as an unsigned
  7075. // hexadecimal number.
  7076. SmallString<40> HexResult;
  7077. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  7078. // If we are only missing a sign bit, this is less likely to result in actual
  7079. // bugs -- if the result is cast back to an unsigned type, it will have the
  7080. // expected value. Thus we place this behind a different warning that can be
  7081. // turned off separately if needed.
  7082. if (LeftBits == ResultBits - 1) {
  7083. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  7084. << HexResult << LHSType
  7085. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7086. return;
  7087. }
  7088. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  7089. << HexResult.str() << Result.getMinSignedBits() << LHSType
  7090. << Left.getBitWidth() << LHS.get()->getSourceRange()
  7091. << RHS.get()->getSourceRange();
  7092. }
  7093. /// \brief Return the resulting type when an OpenCL vector is shifted
  7094. /// by a scalar or vector shift amount.
  7095. static QualType checkOpenCLVectorShift(Sema &S,
  7096. ExprResult &LHS, ExprResult &RHS,
  7097. SourceLocation Loc, bool IsCompAssign) {
  7098. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  7099. if (!LHS.get()->getType()->isVectorType()) {
  7100. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  7101. << RHS.get()->getType() << LHS.get()->getType()
  7102. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7103. return QualType();
  7104. }
  7105. if (!IsCompAssign) {
  7106. LHS = S.UsualUnaryConversions(LHS.get());
  7107. if (LHS.isInvalid()) return QualType();
  7108. }
  7109. RHS = S.UsualUnaryConversions(RHS.get());
  7110. if (RHS.isInvalid()) return QualType();
  7111. QualType LHSType = LHS.get()->getType();
  7112. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  7113. QualType LHSEleType = LHSVecTy->getElementType();
  7114. // Note that RHS might not be a vector.
  7115. QualType RHSType = RHS.get()->getType();
  7116. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  7117. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  7118. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  7119. if (!LHSEleType->isIntegerType()) {
  7120. S.Diag(Loc, diag::err_typecheck_expect_int)
  7121. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7122. return QualType();
  7123. }
  7124. if (!RHSEleType->isIntegerType()) {
  7125. S.Diag(Loc, diag::err_typecheck_expect_int)
  7126. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7127. return QualType();
  7128. }
  7129. if (RHSVecTy) {
  7130. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7131. // are applied component-wise. So if RHS is a vector, then ensure
  7132. // that the number of elements is the same as LHS...
  7133. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7134. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7135. << LHS.get()->getType() << RHS.get()->getType()
  7136. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7137. return QualType();
  7138. }
  7139. } else {
  7140. // ...else expand RHS to match the number of elements in LHS.
  7141. QualType VecTy =
  7142. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7143. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7144. }
  7145. return LHSType;
  7146. }
  7147. // C99 6.5.7
  7148. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7149. SourceLocation Loc, unsigned Opc,
  7150. bool IsCompAssign) {
  7151. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7152. // Vector shifts promote their scalar inputs to vector type.
  7153. if (LHS.get()->getType()->isVectorType() ||
  7154. RHS.get()->getType()->isVectorType()) {
  7155. if (LangOpts.OpenCL)
  7156. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7157. if (LangOpts.ZVector) {
  7158. // The shift operators for the z vector extensions work basically
  7159. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7160. // allowed to be a "vector bool".
  7161. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7162. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7163. return InvalidOperands(Loc, LHS, RHS);
  7164. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7165. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7166. return InvalidOperands(Loc, LHS, RHS);
  7167. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7168. }
  7169. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7170. /*AllowBothBool*/true,
  7171. /*AllowBoolConversions*/false);
  7172. }
  7173. // Shifts don't perform usual arithmetic conversions, they just do integer
  7174. // promotions on each operand. C99 6.5.7p3
  7175. // For the LHS, do usual unary conversions, but then reset them away
  7176. // if this is a compound assignment.
  7177. ExprResult OldLHS = LHS;
  7178. LHS = UsualUnaryConversions(LHS.get());
  7179. if (LHS.isInvalid())
  7180. return QualType();
  7181. QualType LHSType = LHS.get()->getType();
  7182. if (IsCompAssign) LHS = OldLHS;
  7183. // The RHS is simpler.
  7184. RHS = UsualUnaryConversions(RHS.get());
  7185. if (RHS.isInvalid())
  7186. return QualType();
  7187. QualType RHSType = RHS.get()->getType();
  7188. // C99 6.5.7p2: Each of the operands shall have integer type.
  7189. if (!LHSType->hasIntegerRepresentation() ||
  7190. !RHSType->hasIntegerRepresentation())
  7191. return InvalidOperands(Loc, LHS, RHS);
  7192. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7193. // hasIntegerRepresentation() above instead of this.
  7194. if (isScopedEnumerationType(LHSType) ||
  7195. isScopedEnumerationType(RHSType)) {
  7196. return InvalidOperands(Loc, LHS, RHS);
  7197. }
  7198. // Sanity-check shift operands
  7199. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7200. // "The type of the result is that of the promoted left operand."
  7201. return LHSType;
  7202. }
  7203. static bool IsWithinTemplateSpecialization(Decl *D) {
  7204. if (DeclContext *DC = D->getDeclContext()) {
  7205. if (isa<ClassTemplateSpecializationDecl>(DC))
  7206. return true;
  7207. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7208. return FD->isFunctionTemplateSpecialization();
  7209. }
  7210. return false;
  7211. }
  7212. /// If two different enums are compared, raise a warning.
  7213. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7214. Expr *RHS) {
  7215. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7216. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7217. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7218. if (!LHSEnumType)
  7219. return;
  7220. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7221. if (!RHSEnumType)
  7222. return;
  7223. // Ignore anonymous enums.
  7224. if (!LHSEnumType->getDecl()->getIdentifier())
  7225. return;
  7226. if (!RHSEnumType->getDecl()->getIdentifier())
  7227. return;
  7228. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7229. return;
  7230. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7231. << LHSStrippedType << RHSStrippedType
  7232. << LHS->getSourceRange() << RHS->getSourceRange();
  7233. }
  7234. /// \brief Diagnose bad pointer comparisons.
  7235. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7236. ExprResult &LHS, ExprResult &RHS,
  7237. bool IsError) {
  7238. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7239. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7240. << LHS.get()->getType() << RHS.get()->getType()
  7241. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7242. }
  7243. /// \brief Returns false if the pointers are converted to a composite type,
  7244. /// true otherwise.
  7245. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7246. ExprResult &LHS, ExprResult &RHS) {
  7247. // C++ [expr.rel]p2:
  7248. // [...] Pointer conversions (4.10) and qualification
  7249. // conversions (4.4) are performed on pointer operands (or on
  7250. // a pointer operand and a null pointer constant) to bring
  7251. // them to their composite pointer type. [...]
  7252. //
  7253. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7254. // comparisons of pointers.
  7255. // C++ [expr.eq]p2:
  7256. // In addition, pointers to members can be compared, or a pointer to
  7257. // member and a null pointer constant. Pointer to member conversions
  7258. // (4.11) and qualification conversions (4.4) are performed to bring
  7259. // them to a common type. If one operand is a null pointer constant,
  7260. // the common type is the type of the other operand. Otherwise, the
  7261. // common type is a pointer to member type similar (4.4) to the type
  7262. // of one of the operands, with a cv-qualification signature (4.4)
  7263. // that is the union of the cv-qualification signatures of the operand
  7264. // types.
  7265. QualType LHSType = LHS.get()->getType();
  7266. QualType RHSType = RHS.get()->getType();
  7267. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7268. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7269. bool NonStandardCompositeType = false;
  7270. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7271. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7272. if (T.isNull()) {
  7273. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7274. return true;
  7275. }
  7276. if (NonStandardCompositeType)
  7277. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7278. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7279. << RHS.get()->getSourceRange();
  7280. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7281. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7282. return false;
  7283. }
  7284. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7285. ExprResult &LHS,
  7286. ExprResult &RHS,
  7287. bool IsError) {
  7288. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7289. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7290. << LHS.get()->getType() << RHS.get()->getType()
  7291. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7292. }
  7293. static bool isObjCObjectLiteral(ExprResult &E) {
  7294. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7295. case Stmt::ObjCArrayLiteralClass:
  7296. case Stmt::ObjCDictionaryLiteralClass:
  7297. case Stmt::ObjCStringLiteralClass:
  7298. case Stmt::ObjCBoxedExprClass:
  7299. return true;
  7300. default:
  7301. // Note that ObjCBoolLiteral is NOT an object literal!
  7302. return false;
  7303. }
  7304. }
  7305. #if 1 // HLSL Change Starts
  7306. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7307. return LK_None;
  7308. }
  7309. #else
  7310. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7311. const ObjCObjectPointerType *Type =
  7312. LHS->getType()->getAs<ObjCObjectPointerType>();
  7313. // If this is not actually an Objective-C object, bail out.
  7314. if (!Type)
  7315. return false;
  7316. // Get the LHS object's interface type.
  7317. QualType InterfaceType = Type->getPointeeType();
  7318. // If the RHS isn't an Objective-C object, bail out.
  7319. if (!RHS->getType()->isObjCObjectPointerType())
  7320. return false;
  7321. // Try to find the -isEqual: method.
  7322. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7323. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7324. InterfaceType,
  7325. /*instance=*/true);
  7326. if (!Method) {
  7327. if (Type->isObjCIdType()) {
  7328. // For 'id', just check the global pool.
  7329. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7330. /*receiverId=*/true);
  7331. } else {
  7332. // Check protocols.
  7333. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7334. /*instance=*/true);
  7335. }
  7336. }
  7337. if (!Method)
  7338. return false;
  7339. QualType T = Method->parameters()[0]->getType();
  7340. if (!T->isObjCObjectPointerType())
  7341. return false;
  7342. QualType R = Method->getReturnType();
  7343. if (!R->isScalarType())
  7344. return false;
  7345. return true;
  7346. }
  7347. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7348. FromE = FromE->IgnoreParenImpCasts();
  7349. switch (FromE->getStmtClass()) {
  7350. default:
  7351. break;
  7352. case Stmt::ObjCStringLiteralClass:
  7353. // "string literal"
  7354. return LK_String;
  7355. case Stmt::ObjCArrayLiteralClass:
  7356. // "array literal"
  7357. return LK_Array;
  7358. case Stmt::ObjCDictionaryLiteralClass:
  7359. // "dictionary literal"
  7360. return LK_Dictionary;
  7361. case Stmt::BlockExprClass:
  7362. return LK_Block;
  7363. case Stmt::ObjCBoxedExprClass: {
  7364. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7365. switch (Inner->getStmtClass()) {
  7366. case Stmt::IntegerLiteralClass:
  7367. case Stmt::FloatingLiteralClass:
  7368. case Stmt::CharacterLiteralClass:
  7369. case Stmt::ObjCBoolLiteralExprClass:
  7370. case Stmt::CXXBoolLiteralExprClass:
  7371. // "numeric literal"
  7372. return LK_Numeric;
  7373. case Stmt::ImplicitCastExprClass: {
  7374. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7375. // Boolean literals can be represented by implicit casts.
  7376. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7377. return LK_Numeric;
  7378. break;
  7379. }
  7380. default:
  7381. break;
  7382. }
  7383. return LK_Boxed;
  7384. }
  7385. }
  7386. return LK_None;
  7387. }
  7388. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7389. ExprResult &LHS, ExprResult &RHS,
  7390. BinaryOperator::Opcode Opc){
  7391. Expr *Literal;
  7392. Expr *Other;
  7393. if (isObjCObjectLiteral(LHS)) {
  7394. Literal = LHS.get();
  7395. Other = RHS.get();
  7396. } else {
  7397. Literal = RHS.get();
  7398. Other = LHS.get();
  7399. }
  7400. // Don't warn on comparisons against nil.
  7401. Other = Other->IgnoreParenCasts();
  7402. if (Other->isNullPointerConstant(S.getASTContext(),
  7403. Expr::NPC_ValueDependentIsNotNull))
  7404. return;
  7405. // This should be kept in sync with warn_objc_literal_comparison.
  7406. // LK_String should always be after the other literals, since it has its own
  7407. // warning flag.
  7408. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7409. assert(LiteralKind != Sema::LK_Block);
  7410. if (LiteralKind == Sema::LK_None) {
  7411. llvm_unreachable("Unknown Objective-C object literal kind");
  7412. }
  7413. if (LiteralKind == Sema::LK_String)
  7414. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7415. << Literal->getSourceRange();
  7416. else
  7417. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7418. << LiteralKind << Literal->getSourceRange();
  7419. if (BinaryOperator::isEqualityOp(Opc) &&
  7420. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7421. SourceLocation Start = LHS.get()->getLocStart();
  7422. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7423. CharSourceRange OpRange =
  7424. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7425. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7426. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7427. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7428. << FixItHint::CreateInsertion(End, "]");
  7429. }
  7430. }
  7431. #endif // HLSL Change Ends
  7432. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7433. ExprResult &RHS,
  7434. SourceLocation Loc,
  7435. unsigned OpaqueOpc) {
  7436. // This checking requires bools.
  7437. if (!S.getLangOpts().Bool) return;
  7438. // Check that left hand side is !something.
  7439. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7440. if (!UO || UO->getOpcode() != UO_LNot) return;
  7441. // Only check if the right hand side is non-bool arithmetic type.
  7442. if (RHS.get()->getType()->isBooleanType()) return;
  7443. // Make sure that the something in !something is not bool.
  7444. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7445. if (SubExpr->getType()->isBooleanType()) return;
  7446. // Emit warning.
  7447. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7448. << Loc;
  7449. // First note suggest !(x < y)
  7450. SourceLocation FirstOpen = SubExpr->getLocStart();
  7451. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7452. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7453. if (FirstClose.isInvalid())
  7454. FirstOpen = SourceLocation();
  7455. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7456. << FixItHint::CreateInsertion(FirstOpen, "(")
  7457. << FixItHint::CreateInsertion(FirstClose, ")");
  7458. // Second note suggests (!x) < y
  7459. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7460. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7461. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7462. if (SecondClose.isInvalid())
  7463. SecondOpen = SourceLocation();
  7464. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7465. << FixItHint::CreateInsertion(SecondOpen, "(")
  7466. << FixItHint::CreateInsertion(SecondClose, ")");
  7467. }
  7468. // Get the decl for a simple expression: a reference to a variable,
  7469. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7470. static ValueDecl *getCompareDecl(Expr *E) {
  7471. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7472. return DR->getDecl();
  7473. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7474. if (Ivar->isFreeIvar())
  7475. return Ivar->getDecl();
  7476. }
  7477. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7478. if (Mem->isImplicitAccess())
  7479. return Mem->getMemberDecl();
  7480. }
  7481. return nullptr;
  7482. }
  7483. // C99 6.5.8, C++ [expr.rel]
  7484. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7485. SourceLocation Loc, unsigned OpaqueOpc,
  7486. bool IsRelational) {
  7487. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7488. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7489. // Handle vector comparisons separately.
  7490. if (LHS.get()->getType()->isVectorType() ||
  7491. RHS.get()->getType()->isVectorType())
  7492. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7493. QualType LHSType = LHS.get()->getType();
  7494. QualType RHSType = RHS.get()->getType();
  7495. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7496. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7497. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7498. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7499. if (!LHSType->hasFloatingRepresentation() &&
  7500. !(LHSType->isBlockPointerType() && IsRelational) &&
  7501. !LHS.get()->getLocStart().isMacroID() &&
  7502. !RHS.get()->getLocStart().isMacroID() &&
  7503. ActiveTemplateInstantiations.empty()) {
  7504. // For non-floating point types, check for self-comparisons of the form
  7505. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7506. // often indicate logic errors in the program.
  7507. //
  7508. // NOTE: Don't warn about comparison expressions resulting from macro
  7509. // expansion. Also don't warn about comparisons which are only self
  7510. // comparisons within a template specialization. The warnings should catch
  7511. // obvious cases in the definition of the template anyways. The idea is to
  7512. // warn when the typed comparison operator will always evaluate to the same
  7513. // result.
  7514. ValueDecl *DL = getCompareDecl(LHSStripped);
  7515. ValueDecl *DR = getCompareDecl(RHSStripped);
  7516. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7517. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7518. << 0 // self-
  7519. << (Opc == BO_EQ
  7520. || Opc == BO_LE
  7521. || Opc == BO_GE));
  7522. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7523. !DL->getType()->isReferenceType() &&
  7524. !DR->getType()->isReferenceType()) {
  7525. // what is it always going to eval to?
  7526. char always_evals_to;
  7527. switch(Opc) {
  7528. case BO_EQ: // e.g. array1 == array2
  7529. always_evals_to = 0; // false
  7530. break;
  7531. case BO_NE: // e.g. array1 != array2
  7532. always_evals_to = 1; // true
  7533. break;
  7534. default:
  7535. // best we can say is 'a constant'
  7536. always_evals_to = 2; // e.g. array1 <= array2
  7537. break;
  7538. }
  7539. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7540. << 1 // array
  7541. << always_evals_to);
  7542. }
  7543. if (isa<CastExpr>(LHSStripped))
  7544. LHSStripped = LHSStripped->IgnoreParenCasts();
  7545. if (isa<CastExpr>(RHSStripped))
  7546. RHSStripped = RHSStripped->IgnoreParenCasts();
  7547. // Warn about comparisons against a string constant (unless the other
  7548. // operand is null), the user probably wants strcmp.
  7549. Expr *literalString = nullptr;
  7550. Expr *literalStringStripped = nullptr;
  7551. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7552. !RHSStripped->isNullPointerConstant(Context,
  7553. Expr::NPC_ValueDependentIsNull)) {
  7554. literalString = LHS.get();
  7555. literalStringStripped = LHSStripped;
  7556. } else if ((isa<StringLiteral>(RHSStripped) ||
  7557. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7558. !LHSStripped->isNullPointerConstant(Context,
  7559. Expr::NPC_ValueDependentIsNull)) {
  7560. literalString = RHS.get();
  7561. literalStringStripped = RHSStripped;
  7562. }
  7563. if (literalString) {
  7564. DiagRuntimeBehavior(Loc, nullptr,
  7565. PDiag(diag::warn_stringcompare)
  7566. << isa<ObjCEncodeExpr>(literalStringStripped)
  7567. << literalString->getSourceRange());
  7568. }
  7569. }
  7570. // C99 6.5.8p3 / C99 6.5.9p4
  7571. UsualArithmeticConversions(LHS, RHS);
  7572. if (LHS.isInvalid() || RHS.isInvalid())
  7573. return QualType();
  7574. LHSType = LHS.get()->getType();
  7575. RHSType = RHS.get()->getType();
  7576. // The result of comparisons is 'bool' in C++, 'int' in C.
  7577. QualType ResultTy = Context.getLogicalOperationType();
  7578. if (IsRelational) {
  7579. if (LHSType->isRealType() && RHSType->isRealType())
  7580. return ResultTy;
  7581. } else {
  7582. // Check for comparisons of floating point operands using != and ==.
  7583. if (LHSType->hasFloatingRepresentation())
  7584. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7585. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7586. return ResultTy;
  7587. }
  7588. const Expr::NullPointerConstantKind LHSNullKind =
  7589. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7590. const Expr::NullPointerConstantKind RHSNullKind =
  7591. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7592. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7593. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7594. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7595. bool IsEquality = Opc == BO_EQ;
  7596. if (RHSIsNull)
  7597. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7598. RHS.get()->getSourceRange());
  7599. else
  7600. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7601. LHS.get()->getSourceRange());
  7602. }
  7603. // All of the following pointer-related warnings are GCC extensions, except
  7604. // when handling null pointer constants.
  7605. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7606. QualType LCanPointeeTy =
  7607. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7608. QualType RCanPointeeTy =
  7609. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7610. if (getLangOpts().CPlusPlus) {
  7611. if (LCanPointeeTy == RCanPointeeTy)
  7612. return ResultTy;
  7613. if (!IsRelational &&
  7614. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7615. // Valid unless comparison between non-null pointer and function pointer
  7616. // This is a gcc extension compatibility comparison.
  7617. // In a SFINAE context, we treat this as a hard error to maintain
  7618. // conformance with the C++ standard.
  7619. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7620. && !LHSIsNull && !RHSIsNull) {
  7621. diagnoseFunctionPointerToVoidComparison(
  7622. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7623. if (isSFINAEContext())
  7624. return QualType();
  7625. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7626. return ResultTy;
  7627. }
  7628. }
  7629. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7630. return QualType();
  7631. else
  7632. return ResultTy;
  7633. }
  7634. // C99 6.5.9p2 and C99 6.5.8p2
  7635. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7636. RCanPointeeTy.getUnqualifiedType())) {
  7637. // Valid unless a relational comparison of function pointers
  7638. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7639. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7640. << LHSType << RHSType << LHS.get()->getSourceRange()
  7641. << RHS.get()->getSourceRange();
  7642. }
  7643. } else if (!IsRelational &&
  7644. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7645. // Valid unless comparison between non-null pointer and function pointer
  7646. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7647. && !LHSIsNull && !RHSIsNull)
  7648. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7649. /*isError*/false);
  7650. } else {
  7651. // Invalid
  7652. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7653. }
  7654. if (LCanPointeeTy != RCanPointeeTy) {
  7655. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7656. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7657. Diag(Loc,
  7658. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7659. << LHSType << RHSType << 0 /* comparison */
  7660. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7661. }
  7662. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7663. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7664. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7665. : CK_BitCast;
  7666. if (LHSIsNull && !RHSIsNull)
  7667. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7668. else
  7669. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7670. }
  7671. return ResultTy;
  7672. }
  7673. if (getLangOpts().CPlusPlus) {
  7674. // Comparison of nullptr_t with itself.
  7675. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7676. return ResultTy;
  7677. // Comparison of pointers with null pointer constants and equality
  7678. // comparisons of member pointers to null pointer constants.
  7679. if (RHSIsNull &&
  7680. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7681. (!IsRelational &&
  7682. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7683. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7684. LHSType->isMemberPointerType()
  7685. ? CK_NullToMemberPointer
  7686. : CK_NullToPointer);
  7687. return ResultTy;
  7688. }
  7689. if (LHSIsNull &&
  7690. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7691. (!IsRelational &&
  7692. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7693. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7694. RHSType->isMemberPointerType()
  7695. ? CK_NullToMemberPointer
  7696. : CK_NullToPointer);
  7697. return ResultTy;
  7698. }
  7699. // Comparison of member pointers.
  7700. if (!IsRelational &&
  7701. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7702. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7703. return QualType();
  7704. else
  7705. return ResultTy;
  7706. }
  7707. // Handle scoped enumeration types specifically, since they don't promote
  7708. // to integers.
  7709. if (LHS.get()->getType()->isEnumeralType() &&
  7710. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7711. RHS.get()->getType()))
  7712. return ResultTy;
  7713. }
  7714. // Handle block pointer types.
  7715. if (!IsRelational && LHSType->isBlockPointerType() &&
  7716. RHSType->isBlockPointerType()) {
  7717. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7718. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7719. if (!LHSIsNull && !RHSIsNull &&
  7720. !Context.typesAreCompatible(lpointee, rpointee)) {
  7721. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7722. << LHSType << RHSType << LHS.get()->getSourceRange()
  7723. << RHS.get()->getSourceRange();
  7724. }
  7725. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7726. return ResultTy;
  7727. }
  7728. // Allow block pointers to be compared with null pointer constants.
  7729. if (!IsRelational
  7730. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7731. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7732. if (!LHSIsNull && !RHSIsNull) {
  7733. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7734. ->getPointeeType()->isVoidType())
  7735. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7736. ->getPointeeType()->isVoidType())))
  7737. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7738. << LHSType << RHSType << LHS.get()->getSourceRange()
  7739. << RHS.get()->getSourceRange();
  7740. }
  7741. if (LHSIsNull && !RHSIsNull)
  7742. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7743. RHSType->isPointerType() ? CK_BitCast
  7744. : CK_AnyPointerToBlockPointerCast);
  7745. else
  7746. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7747. LHSType->isPointerType() ? CK_BitCast
  7748. : CK_AnyPointerToBlockPointerCast);
  7749. return ResultTy;
  7750. }
  7751. if (LHSType->isObjCObjectPointerType() ||
  7752. RHSType->isObjCObjectPointerType()) {
  7753. const PointerType *LPT = LHSType->getAs<PointerType>();
  7754. const PointerType *RPT = RHSType->getAs<PointerType>();
  7755. if (LPT || RPT) {
  7756. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7757. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7758. if (!LPtrToVoid && !RPtrToVoid &&
  7759. !Context.typesAreCompatible(LHSType, RHSType)) {
  7760. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7761. /*isError*/false);
  7762. }
  7763. if (LHSIsNull && !RHSIsNull) {
  7764. Expr *E = LHS.get();
  7765. #if 0 // HLSL Change - no ObjC support
  7766. if (getLangOpts().ObjCAutoRefCount)
  7767. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7768. #endif // HLSL Change
  7769. LHS = ImpCastExprToType(E, RHSType,
  7770. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7771. }
  7772. else {
  7773. Expr *E = RHS.get();
  7774. #if 0 // HLSL Change - no ObjC support
  7775. if (getLangOpts().ObjCAutoRefCount)
  7776. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7777. Opc);
  7778. #endif // HLSL Change
  7779. RHS = ImpCastExprToType(E, LHSType,
  7780. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7781. }
  7782. return ResultTy;
  7783. }
  7784. #if 0 // HLSL Change - no ObjC support
  7785. if (LHSType->isObjCObjectPointerType() &&
  7786. RHSType->isObjCObjectPointerType()) {
  7787. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7788. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7789. /*isError*/false);
  7790. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7791. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7792. if (LHSIsNull && !RHSIsNull)
  7793. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7794. else
  7795. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7796. return ResultTy;
  7797. }
  7798. #endif // HLSL Change
  7799. }
  7800. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7801. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7802. unsigned DiagID = 0;
  7803. bool isError = false;
  7804. if (LangOpts.DebuggerSupport) {
  7805. // Under a debugger, allow the comparison of pointers to integers,
  7806. // since users tend to want to compare addresses.
  7807. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7808. (RHSIsNull && RHSType->isIntegerType())) {
  7809. if (IsRelational && !getLangOpts().CPlusPlus)
  7810. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7811. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7812. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7813. else if (getLangOpts().CPlusPlus) {
  7814. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7815. isError = true;
  7816. } else
  7817. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7818. if (DiagID) {
  7819. Diag(Loc, DiagID)
  7820. << LHSType << RHSType << LHS.get()->getSourceRange()
  7821. << RHS.get()->getSourceRange();
  7822. if (isError)
  7823. return QualType();
  7824. }
  7825. if (LHSType->isIntegerType())
  7826. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7827. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7828. else
  7829. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7830. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7831. return ResultTy;
  7832. }
  7833. // Handle block pointers.
  7834. if (!IsRelational && RHSIsNull
  7835. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7836. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7837. return ResultTy;
  7838. }
  7839. if (!IsRelational && LHSIsNull
  7840. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7841. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7842. return ResultTy;
  7843. }
  7844. return InvalidOperands(Loc, LHS, RHS);
  7845. }
  7846. // Return a signed type that is of identical size and number of elements.
  7847. // For floating point vectors, return an integer type of identical size
  7848. // and number of elements.
  7849. QualType Sema::GetSignedVectorType(QualType V) {
  7850. const VectorType *VTy = V->getAs<VectorType>();
  7851. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7852. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7853. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7854. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7855. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7856. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7857. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7858. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7859. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7860. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7861. "Unhandled vector element size in vector compare");
  7862. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7863. }
  7864. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7865. /// operates on extended vector types. Instead of producing an IntTy result,
  7866. /// like a scalar comparison, a vector comparison produces a vector of integer
  7867. /// types.
  7868. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7869. SourceLocation Loc,
  7870. bool IsRelational) {
  7871. // Check to make sure we're operating on vectors of the same type and width,
  7872. // Allowing one side to be a scalar of element type.
  7873. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7874. /*AllowBothBool*/true,
  7875. /*AllowBoolConversions*/getLangOpts().ZVector);
  7876. if (vType.isNull())
  7877. return vType;
  7878. QualType LHSType = LHS.get()->getType();
  7879. // If AltiVec, the comparison results in a numeric type, i.e.
  7880. // bool for C++, int for C
  7881. if (getLangOpts().AltiVec &&
  7882. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7883. return Context.getLogicalOperationType();
  7884. // For non-floating point types, check for self-comparisons of the form
  7885. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7886. // often indicate logic errors in the program.
  7887. if (!LHSType->hasFloatingRepresentation() &&
  7888. ActiveTemplateInstantiations.empty()) {
  7889. if (DeclRefExpr* DRL
  7890. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7891. if (DeclRefExpr* DRR
  7892. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7893. if (DRL->getDecl() == DRR->getDecl())
  7894. DiagRuntimeBehavior(Loc, nullptr,
  7895. PDiag(diag::warn_comparison_always)
  7896. << 0 // self-
  7897. << 2 // "a constant"
  7898. );
  7899. }
  7900. // Check for comparisons of floating point operands using != and ==.
  7901. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7902. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7903. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7904. }
  7905. // Return a signed type for the vector.
  7906. return GetSignedVectorType(LHSType);
  7907. }
  7908. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7909. SourceLocation Loc) {
  7910. // Ensure that either both operands are of the same vector type, or
  7911. // one operand is of a vector type and the other is of its element type.
  7912. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7913. /*AllowBothBool*/true,
  7914. /*AllowBoolConversions*/false);
  7915. if (vType.isNull())
  7916. return InvalidOperands(Loc, LHS, RHS);
  7917. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7918. vType->hasFloatingRepresentation())
  7919. return InvalidOperands(Loc, LHS, RHS);
  7920. return GetSignedVectorType(LHS.get()->getType());
  7921. }
  7922. inline QualType Sema::CheckBitwiseOperands(
  7923. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7924. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7925. if (LHS.get()->getType()->isVectorType() ||
  7926. RHS.get()->getType()->isVectorType()) {
  7927. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7928. RHS.get()->getType()->hasIntegerRepresentation())
  7929. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7930. /*AllowBothBool*/true,
  7931. /*AllowBoolConversions*/getLangOpts().ZVector);
  7932. return InvalidOperands(Loc, LHS, RHS);
  7933. }
  7934. ExprResult LHSResult = LHS, RHSResult = RHS;
  7935. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7936. IsCompAssign);
  7937. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7938. return QualType();
  7939. LHS = LHSResult.get();
  7940. RHS = RHSResult.get();
  7941. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  7942. return compType;
  7943. return InvalidOperands(Loc, LHS, RHS);
  7944. }
  7945. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  7946. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  7947. // Check vector operands differently.
  7948. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  7949. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  7950. // Diagnose cases where the user write a logical and/or but probably meant a
  7951. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  7952. // is a constant.
  7953. if (LHS.get()->getType()->isIntegerType() &&
  7954. !LHS.get()->getType()->isBooleanType() &&
  7955. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  7956. // Don't warn in macros or template instantiations.
  7957. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  7958. // If the RHS can be constant folded, and if it constant folds to something
  7959. // that isn't 0 or 1 (which indicate a potential logical operation that
  7960. // happened to fold to true/false) then warn.
  7961. // Parens on the RHS are ignored.
  7962. llvm::APSInt Result;
  7963. if (RHS.get()->EvaluateAsInt(Result, Context))
  7964. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  7965. !RHS.get()->getExprLoc().isMacroID()) ||
  7966. (Result != 0 && Result != 1)) {
  7967. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  7968. << RHS.get()->getSourceRange()
  7969. << (Opc == BO_LAnd ? "&&" : "||");
  7970. // Suggest replacing the logical operator with the bitwise version
  7971. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  7972. << (Opc == BO_LAnd ? "&" : "|")
  7973. << FixItHint::CreateReplacement(SourceRange(
  7974. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  7975. getLangOpts())),
  7976. Opc == BO_LAnd ? "&" : "|");
  7977. if (Opc == BO_LAnd)
  7978. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  7979. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  7980. << FixItHint::CreateRemoval(
  7981. SourceRange(
  7982. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  7983. 0, getSourceManager(),
  7984. getLangOpts()),
  7985. RHS.get()->getLocEnd()));
  7986. }
  7987. }
  7988. if (!Context.getLangOpts().CPlusPlus) {
  7989. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  7990. // not operate on the built-in scalar and vector float types.
  7991. if (Context.getLangOpts().OpenCL &&
  7992. Context.getLangOpts().OpenCLVersion < 120) {
  7993. if (LHS.get()->getType()->isFloatingType() ||
  7994. RHS.get()->getType()->isFloatingType())
  7995. return InvalidOperands(Loc, LHS, RHS);
  7996. }
  7997. LHS = UsualUnaryConversions(LHS.get());
  7998. if (LHS.isInvalid())
  7999. return QualType();
  8000. RHS = UsualUnaryConversions(RHS.get());
  8001. if (RHS.isInvalid())
  8002. return QualType();
  8003. if (!LHS.get()->getType()->isScalarType() ||
  8004. !RHS.get()->getType()->isScalarType())
  8005. return InvalidOperands(Loc, LHS, RHS);
  8006. return Context.IntTy;
  8007. }
  8008. // The following is safe because we only use this method for
  8009. // non-overloadable operands.
  8010. // C++ [expr.log.and]p1
  8011. // C++ [expr.log.or]p1
  8012. // The operands are both contextually converted to type bool.
  8013. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  8014. if (LHSRes.isInvalid())
  8015. return InvalidOperands(Loc, LHS, RHS);
  8016. LHS = LHSRes;
  8017. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  8018. if (RHSRes.isInvalid())
  8019. return InvalidOperands(Loc, LHS, RHS);
  8020. RHS = RHSRes;
  8021. // C++ [expr.log.and]p2
  8022. // C++ [expr.log.or]p2
  8023. // The result is a bool.
  8024. return Context.BoolTy;
  8025. }
  8026. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  8027. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  8028. if (!ME) return false;
  8029. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  8030. ObjCMessageExpr *Base =
  8031. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  8032. if (!Base) return false;
  8033. return Base->getMethodDecl() != nullptr;
  8034. }
  8035. /// Is the given expression (which must be 'const') a reference to a
  8036. /// variable which was originally non-const, but which has become
  8037. /// 'const' due to being captured within a block?
  8038. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  8039. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  8040. assert(E->isLValue() && E->getType().isConstQualified());
  8041. E = E->IgnoreParens();
  8042. // Must be a reference to a declaration from an enclosing scope.
  8043. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  8044. if (!DRE) return NCCK_None;
  8045. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  8046. // The declaration must be a variable which is not declared 'const'.
  8047. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  8048. if (!var) return NCCK_None;
  8049. if (var->getType().isConstQualified()) return NCCK_None;
  8050. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  8051. // Decide whether the first capture was for a block or a lambda.
  8052. DeclContext *DC = S.CurContext, *Prev = nullptr;
  8053. while (DC != var->getDeclContext()) {
  8054. Prev = DC;
  8055. DC = DC->getParent();
  8056. }
  8057. // Unless we have an init-capture, we've gone one step too far.
  8058. if (!var->isInitCapture())
  8059. DC = Prev;
  8060. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  8061. }
  8062. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  8063. Ty = Ty.getNonReferenceType();
  8064. if (IsDereference && Ty->isPointerType())
  8065. Ty = Ty->getPointeeType();
  8066. return !Ty.isConstQualified();
  8067. }
  8068. /// Emit the "read-only variable not assignable" error and print notes to give
  8069. /// more information about why the variable is not assignable, such as pointing
  8070. /// to the declaration of a const variable, showing that a method is const, or
  8071. /// that the function is returning a const reference.
  8072. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  8073. SourceLocation Loc) {
  8074. // Update err_typecheck_assign_const and note_typecheck_assign_const
  8075. // when this enum is changed.
  8076. enum {
  8077. ConstFunction,
  8078. ConstVariable,
  8079. ConstMember,
  8080. ConstMethod,
  8081. ConstUnknown, // Keep as last element
  8082. };
  8083. SourceRange ExprRange = E->getSourceRange();
  8084. // Only emit one error on the first const found. All other consts will emit
  8085. // a note to the error.
  8086. bool DiagnosticEmitted = false;
  8087. // Track if the current expression is the result of a derefence, and if the
  8088. // next checked expression is the result of a derefence.
  8089. bool IsDereference = false;
  8090. bool NextIsDereference = false;
  8091. // Loop to process MemberExpr chains.
  8092. while (true) {
  8093. IsDereference = NextIsDereference;
  8094. NextIsDereference = false;
  8095. E = E->IgnoreParenImpCasts();
  8096. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  8097. NextIsDereference = ME->isArrow();
  8098. const ValueDecl *VD = ME->getMemberDecl();
  8099. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  8100. // Mutable fields can be modified even if the class is const.
  8101. if (Field->isMutable()) {
  8102. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  8103. break;
  8104. }
  8105. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  8106. if (!DiagnosticEmitted) {
  8107. S.Diag(Loc, diag::err_typecheck_assign_const)
  8108. << ExprRange << ConstMember << false /*static*/ << Field
  8109. << Field->getType();
  8110. DiagnosticEmitted = true;
  8111. }
  8112. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8113. << ConstMember << false /*static*/ << Field << Field->getType()
  8114. << Field->getSourceRange();
  8115. }
  8116. E = ME->getBase();
  8117. continue;
  8118. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  8119. if (VDecl->getType().isConstQualified()) {
  8120. if (!DiagnosticEmitted) {
  8121. S.Diag(Loc, diag::err_typecheck_assign_const)
  8122. << ExprRange << ConstMember << true /*static*/ << VDecl
  8123. << VDecl->getType();
  8124. DiagnosticEmitted = true;
  8125. }
  8126. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8127. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  8128. << VDecl->getSourceRange();
  8129. }
  8130. // Static fields do not inherit constness from parents.
  8131. break;
  8132. }
  8133. break;
  8134. } // End MemberExpr
  8135. break;
  8136. }
  8137. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8138. // Function calls
  8139. const FunctionDecl *FD = CE->getDirectCallee();
  8140. if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8141. if (!DiagnosticEmitted) {
  8142. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8143. << ConstFunction << FD;
  8144. DiagnosticEmitted = true;
  8145. }
  8146. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8147. diag::note_typecheck_assign_const)
  8148. << ConstFunction << FD << FD->getReturnType()
  8149. << FD->getReturnTypeSourceRange();
  8150. }
  8151. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8152. // Point to variable declaration.
  8153. if (const ValueDecl *VD = DRE->getDecl()) {
  8154. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8155. if (!DiagnosticEmitted) {
  8156. S.Diag(Loc, diag::err_typecheck_assign_const)
  8157. << ExprRange << ConstVariable << VD << VD->getType();
  8158. DiagnosticEmitted = true;
  8159. }
  8160. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8161. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8162. }
  8163. }
  8164. } else if (isa<CXXThisExpr>(E)) {
  8165. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8166. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8167. if (MD->isConst()) {
  8168. if (!DiagnosticEmitted) {
  8169. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8170. << ConstMethod << MD;
  8171. DiagnosticEmitted = true;
  8172. }
  8173. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8174. << ConstMethod << MD << MD->getSourceRange();
  8175. }
  8176. }
  8177. }
  8178. }
  8179. if (DiagnosticEmitted)
  8180. return;
  8181. // Can't determine a more specific message, so display the generic error.
  8182. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8183. }
  8184. static bool HLSLCheckForModifiableLValue(
  8185. Expr *E,
  8186. SourceLocation Loc,
  8187. Sema &S
  8188. ) {
  8189. assert(isa<CXXOperatorCallExpr>(E));
  8190. const CXXOperatorCallExpr *expr = cast<CXXOperatorCallExpr>(E);
  8191. const Expr *LHS = expr->getArg(0);
  8192. QualType qt = LHS->getType();
  8193. // Check modifying const matrix with double subscript operator calls
  8194. if (isa<CXXOperatorCallExpr>(expr->getArg(0)))
  8195. return HLSLCheckForModifiableLValue(const_cast<Expr *>(expr->getArg(0)), Loc, S);
  8196. if (qt.isConstQualified() && (hlsl::IsMatrixType(&S, qt) || hlsl::IsVectorType(&S, qt))) {
  8197. DiagnoseConstAssignment(S, LHS, Loc);
  8198. return true;
  8199. }
  8200. if (!LHS->isLValue()) {
  8201. S.Diag(Loc, diag::err_typecheck_expression_not_modifiable_lvalue);
  8202. return true;
  8203. }
  8204. return false;
  8205. }
  8206. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8207. /// emit an error and return true. If so, return false.
  8208. bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { // HLSL Change: export this function
  8209. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8210. // HLSL Change Starts - check const for array subscript operator for HLSL vector/matrix
  8211. if (S.Context.getLangOpts().HLSL && E->getStmtClass() == Stmt::CXXOperatorCallExprClass) {
  8212. // check if it's a vector or matrix
  8213. return HLSLCheckForModifiableLValue(E, Loc, S);
  8214. }
  8215. // HLSL Change Ends
  8216. SourceLocation OrigLoc = Loc;
  8217. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8218. &Loc);
  8219. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8220. IsLV = Expr::MLV_InvalidMessageExpression;
  8221. if (IsLV == Expr::MLV_Valid)
  8222. return false;
  8223. unsigned DiagID = 0;
  8224. bool NeedType = false;
  8225. switch (IsLV) { // C99 6.5.16p2
  8226. case Expr::MLV_ConstQualified:
  8227. // Use a specialized diagnostic when we're assigning to an object
  8228. // from an enclosing function or block.
  8229. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8230. if (NCCK == NCCK_Block)
  8231. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8232. else
  8233. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8234. break;
  8235. }
  8236. // In ARC, use some specialized diagnostics for occasions where we
  8237. // infer 'const'. These are always pseudo-strong variables.
  8238. if (S.getLangOpts().ObjCAutoRefCount) {
  8239. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8240. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8241. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8242. // Use the normal diagnostic if it's pseudo-__strong but the
  8243. // user actually wrote 'const'.
  8244. if (var->isARCPseudoStrong() &&
  8245. (!var->getTypeSourceInfo() ||
  8246. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8247. // There are two pseudo-strong cases:
  8248. // - self
  8249. ObjCMethodDecl *method = S.getCurMethodDecl();
  8250. if (method && var == method->getSelfDecl())
  8251. DiagID = method->isClassMethod()
  8252. ? diag::err_typecheck_arc_assign_self_class_method
  8253. : diag::err_typecheck_arc_assign_self;
  8254. // - fast enumeration variables
  8255. else
  8256. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8257. SourceRange Assign;
  8258. if (Loc != OrigLoc)
  8259. Assign = SourceRange(OrigLoc, OrigLoc);
  8260. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8261. // We need to preserve the AST regardless, so migration tool
  8262. // can do its job.
  8263. return false;
  8264. }
  8265. }
  8266. }
  8267. // If none of the special cases above are triggered, then this is a
  8268. // simple const assignment.
  8269. if (DiagID == 0) {
  8270. DiagnoseConstAssignment(S, E, Loc);
  8271. return true;
  8272. }
  8273. break;
  8274. case Expr::MLV_ConstAddrSpace:
  8275. DiagnoseConstAssignment(S, E, Loc);
  8276. return true;
  8277. case Expr::MLV_ArrayType:
  8278. case Expr::MLV_ArrayTemporary:
  8279. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8280. NeedType = true;
  8281. break;
  8282. case Expr::MLV_NotObjectType:
  8283. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8284. NeedType = true;
  8285. break;
  8286. case Expr::MLV_LValueCast:
  8287. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8288. break;
  8289. case Expr::MLV_Valid:
  8290. llvm_unreachable("did not take early return for MLV_Valid");
  8291. case Expr::MLV_InvalidExpression:
  8292. case Expr::MLV_MemberFunction:
  8293. case Expr::MLV_ClassTemporary:
  8294. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8295. break;
  8296. case Expr::MLV_IncompleteType:
  8297. case Expr::MLV_IncompleteVoidType:
  8298. return S.RequireCompleteType(Loc, E->getType(),
  8299. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8300. case Expr::MLV_DuplicateVectorComponents:
  8301. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8302. break;
  8303. // HLSL Change Starts
  8304. case Expr::MLV_DuplicateMatrixComponents:
  8305. DiagID = diag::err_hlsl_typecheck_duplicate_matrix_components_not_mlvalue;
  8306. break;
  8307. // HLSL Change Ends
  8308. case Expr::MLV_NoSetterProperty:
  8309. llvm_unreachable("readonly properties should be processed differently");
  8310. case Expr::MLV_InvalidMessageExpression:
  8311. DiagID = diag::error_readonly_message_assignment;
  8312. break;
  8313. case Expr::MLV_SubObjCPropertySetting:
  8314. DiagID = diag::error_no_subobject_property_setting;
  8315. break;
  8316. }
  8317. SourceRange Assign;
  8318. if (Loc != OrigLoc)
  8319. Assign = SourceRange(OrigLoc, OrigLoc);
  8320. if (NeedType)
  8321. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8322. else
  8323. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8324. return true;
  8325. }
  8326. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8327. SourceLocation Loc,
  8328. Sema &Sema) {
  8329. // C / C++ fields
  8330. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8331. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8332. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8333. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8334. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8335. }
  8336. // Objective-C instance variables
  8337. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8338. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8339. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8340. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8341. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8342. if (RL && RR && RL->getDecl() == RR->getDecl())
  8343. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8344. }
  8345. }
  8346. // C99 6.5.16.1
  8347. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8348. SourceLocation Loc,
  8349. QualType CompoundType) {
  8350. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8351. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8352. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8353. return QualType();
  8354. QualType LHSType = LHSExpr->getType();
  8355. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8356. CompoundType;
  8357. AssignConvertType ConvTy;
  8358. if (CompoundType.isNull()) {
  8359. Expr *RHSCheck = RHS.get();
  8360. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8361. QualType LHSTy(LHSType);
  8362. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8363. if (RHS.isInvalid())
  8364. return QualType();
  8365. // Special case of NSObject attributes on c-style pointer types.
  8366. if (ConvTy == IncompatiblePointer &&
  8367. ((Context.isObjCNSObjectType(LHSType) &&
  8368. RHSType->isObjCObjectPointerType()) ||
  8369. (Context.isObjCNSObjectType(RHSType) &&
  8370. LHSType->isObjCObjectPointerType())))
  8371. ConvTy = Compatible;
  8372. if (ConvTy == Compatible &&
  8373. LHSType->isObjCObjectType())
  8374. Diag(Loc, diag::err_objc_object_assignment)
  8375. << LHSType;
  8376. // If the RHS is a unary plus or minus, check to see if they = and + are
  8377. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8378. // instead of "x += 4".
  8379. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8380. RHSCheck = ICE->getSubExpr();
  8381. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8382. if ((UO->getOpcode() == UO_Plus ||
  8383. UO->getOpcode() == UO_Minus) &&
  8384. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8385. // Only if the two operators are exactly adjacent.
  8386. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8387. // And there is a space or other character before the subexpr of the
  8388. // unary +/-. We don't want to warn on "x=-1".
  8389. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8390. UO->getSubExpr()->getLocStart().isFileID()) {
  8391. Diag(Loc, diag::warn_not_compound_assign)
  8392. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8393. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8394. }
  8395. }
  8396. #if 0 // HLSL Change Starts
  8397. if (ConvTy == Compatible) {
  8398. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8399. // Warn about retain cycles where a block captures the LHS, but
  8400. // not if the LHS is a simple variable into which the block is
  8401. // being stored...unless that variable can be captured by reference!
  8402. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8403. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8404. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8405. checkRetainCycles(LHSExpr, RHS.get());
  8406. // It is safe to assign a weak reference into a strong variable.
  8407. // Although this code can still have problems:
  8408. // id x = self.weakProp;
  8409. // id y = self.weakProp;
  8410. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8411. // paths through the function. This should be revisited if
  8412. // -Wrepeated-use-of-weak is made flow-sensitive.
  8413. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8414. RHS.get()->getLocStart()))
  8415. getCurFunction()->markSafeWeakUse(RHS.get());
  8416. } else if (getLangOpts().ObjCAutoRefCount) {
  8417. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8418. }
  8419. }
  8420. #endif // HLSL Change Ends
  8421. } else {
  8422. // Compound assignment "x += y"
  8423. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8424. }
  8425. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8426. RHS.get(), AA_Assigning))
  8427. return QualType();
  8428. CheckForNullPointerDereference(*this, LHSExpr);
  8429. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8430. // left operand unless the left operand has qualified type, in which case
  8431. // it is the unqualified version of the type of the left operand.
  8432. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8433. // is converted to the type of the assignment expression (above).
  8434. // C++ 5.17p1: the type of the assignment expression is that of its left
  8435. // operand.
  8436. return (getLangOpts().CPlusPlus
  8437. ? LHSType : LHSType.getUnqualifiedType());
  8438. }
  8439. // C99 6.5.17
  8440. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8441. SourceLocation Loc) {
  8442. LHS = S.CheckPlaceholderExpr(LHS.get());
  8443. RHS = S.CheckPlaceholderExpr(RHS.get());
  8444. if (LHS.isInvalid() || RHS.isInvalid())
  8445. return QualType();
  8446. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8447. // operands, but not unary promotions.
  8448. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8449. // So we treat the LHS as a ignored value, and in C++ we allow the
  8450. // containing site to determine what should be done with the RHS.
  8451. LHS = S.IgnoredValueConversions(LHS.get());
  8452. if (LHS.isInvalid())
  8453. return QualType();
  8454. S.DiagnoseUnusedExprResult(LHS.get());
  8455. if (!S.getLangOpts().CPlusPlus) {
  8456. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8457. if (RHS.isInvalid())
  8458. return QualType();
  8459. if (!RHS.get()->getType()->isVoidType())
  8460. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8461. diag::err_incomplete_type);
  8462. }
  8463. return RHS.get()->getType();
  8464. }
  8465. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8466. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8467. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8468. ExprValueKind &VK,
  8469. ExprObjectKind &OK,
  8470. SourceLocation OpLoc,
  8471. bool IsInc, bool IsPrefix) {
  8472. if (Op->isTypeDependent())
  8473. return S.Context.DependentTy;
  8474. QualType ResType = Op->getType();
  8475. // Atomic types can be used for increment / decrement where the non-atomic
  8476. // versions can, so ignore the _Atomic() specifier for the purpose of
  8477. // checking.
  8478. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8479. ResType = ResAtomicType->getValueType();
  8480. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8481. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8482. // Decrement of bool is not allowed.
  8483. if (!IsInc) {
  8484. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8485. return QualType();
  8486. }
  8487. // Increment of bool sets it to true, but is deprecated.
  8488. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  8489. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8490. // Error on enum increments and decrements in C++ mode
  8491. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8492. return QualType();
  8493. } else if (ResType->isRealType()) {
  8494. // OK!
  8495. } else if (ResType->isPointerType()) {
  8496. // C99 6.5.2.4p2, 6.5.6p2
  8497. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8498. return QualType();
  8499. } else if (ResType->isObjCObjectPointerType()) {
  8500. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8501. // Otherwise, we just need a complete type.
  8502. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8503. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8504. return QualType();
  8505. } else if (ResType->isAnyComplexType()) {
  8506. // C99 does not support ++/-- on complex types, we allow as an extension.
  8507. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8508. << ResType << Op->getSourceRange();
  8509. } else if (ResType->isPlaceholderType()) {
  8510. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8511. if (PR.isInvalid()) return QualType();
  8512. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8513. IsInc, IsPrefix);
  8514. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8515. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8516. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8517. (ResType->getAs<VectorType>()->getVectorKind() !=
  8518. VectorType::AltiVecBool)) {
  8519. // The z vector extensions allow ++ and -- for non-bool vectors.
  8520. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8521. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8522. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8523. } else {
  8524. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8525. << ResType << int(IsInc) << Op->getSourceRange();
  8526. return QualType();
  8527. }
  8528. // At this point, we know we have a real, complex or pointer type.
  8529. // Now make sure the operand is a modifiable lvalue.
  8530. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8531. return QualType();
  8532. // In C++, a prefix increment is the same type as the operand. Otherwise
  8533. // (in C or with postfix), the increment is the unqualified type of the
  8534. // operand.
  8535. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8536. VK = VK_LValue;
  8537. OK = Op->getObjectKind();
  8538. return ResType;
  8539. } else {
  8540. VK = VK_RValue;
  8541. return ResType.getUnqualifiedType();
  8542. }
  8543. }
  8544. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8545. /// This routine allows us to typecheck complex/recursive expressions
  8546. /// where the declaration is needed for type checking. We only need to
  8547. /// handle cases when the expression references a function designator
  8548. /// or is an lvalue. Here are some examples:
  8549. /// - &(x) => x
  8550. /// - &*****f => f for f a function designator.
  8551. /// - &s.xx => s
  8552. /// - &s.zz[1].yy -> s, if zz is an array
  8553. /// - *(x + 1) -> x, if x is an array
  8554. /// - &"123"[2] -> 0
  8555. /// - & __real__ x -> x
  8556. static ValueDecl *getPrimaryDecl(Expr *E) {
  8557. switch (E->getStmtClass()) {
  8558. case Stmt::DeclRefExprClass:
  8559. return cast<DeclRefExpr>(E)->getDecl();
  8560. case Stmt::MemberExprClass:
  8561. // If this is an arrow operator, the address is an offset from
  8562. // the base's value, so the object the base refers to is
  8563. // irrelevant.
  8564. if (cast<MemberExpr>(E)->isArrow())
  8565. return nullptr;
  8566. // Otherwise, the expression refers to a part of the base
  8567. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8568. case Stmt::ArraySubscriptExprClass: {
  8569. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8570. // promotion of register arrays earlier.
  8571. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8572. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8573. if (ICE->getSubExpr()->getType()->isArrayType())
  8574. return getPrimaryDecl(ICE->getSubExpr());
  8575. }
  8576. return nullptr;
  8577. }
  8578. case Stmt::UnaryOperatorClass: {
  8579. UnaryOperator *UO = cast<UnaryOperator>(E);
  8580. switch(UO->getOpcode()) {
  8581. case UO_Real:
  8582. case UO_Imag:
  8583. case UO_Extension:
  8584. return getPrimaryDecl(UO->getSubExpr());
  8585. default:
  8586. return nullptr;
  8587. }
  8588. }
  8589. case Stmt::ParenExprClass:
  8590. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8591. case Stmt::ImplicitCastExprClass:
  8592. // If the result of an implicit cast is an l-value, we care about
  8593. // the sub-expression; otherwise, the result here doesn't matter.
  8594. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8595. default:
  8596. return nullptr;
  8597. }
  8598. }
  8599. namespace {
  8600. enum {
  8601. AO_Bit_Field = 0,
  8602. AO_Vector_Element = 1,
  8603. AO_Property_Expansion = 2,
  8604. AO_Register_Variable = 3,
  8605. AO_No_Error = 4
  8606. };
  8607. }
  8608. /// \brief Diagnose invalid operand for address of operations.
  8609. ///
  8610. /// \param Type The type of operand which cannot have its address taken.
  8611. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8612. Expr *E, unsigned Type) {
  8613. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8614. }
  8615. /// CheckAddressOfOperand - The operand of & must be either a function
  8616. /// designator or an lvalue designating an object. If it is an lvalue, the
  8617. /// object cannot be declared with storage class register or be a bit field.
  8618. /// Note: The usual conversions are *not* applied to the operand of the &
  8619. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8620. /// In C++, the operand might be an overloaded function name, in which case
  8621. /// we allow the '&' but retain the overloaded-function type.
  8622. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8623. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8624. if (PTy->getKind() == BuiltinType::Overload) {
  8625. Expr *E = OrigOp.get()->IgnoreParens();
  8626. if (!isa<OverloadExpr>(E)) {
  8627. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8628. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8629. << OrigOp.get()->getSourceRange();
  8630. return QualType();
  8631. }
  8632. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8633. if (isa<UnresolvedMemberExpr>(Ovl))
  8634. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8635. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8636. << OrigOp.get()->getSourceRange();
  8637. return QualType();
  8638. }
  8639. return Context.OverloadTy;
  8640. }
  8641. if (PTy->getKind() == BuiltinType::UnknownAny)
  8642. return Context.UnknownAnyTy;
  8643. if (PTy->getKind() == BuiltinType::BoundMember) {
  8644. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8645. << OrigOp.get()->getSourceRange();
  8646. return QualType();
  8647. }
  8648. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8649. if (OrigOp.isInvalid()) return QualType();
  8650. }
  8651. if (OrigOp.get()->isTypeDependent())
  8652. return Context.DependentTy;
  8653. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8654. // Make sure to ignore parentheses in subsequent checks
  8655. Expr *op = OrigOp.get()->IgnoreParens();
  8656. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8657. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8658. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8659. return QualType();
  8660. }
  8661. if (getLangOpts().C99) {
  8662. // Implement C99-only parts of addressof rules.
  8663. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8664. if (uOp->getOpcode() == UO_Deref)
  8665. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8666. // (assuming the deref expression is valid).
  8667. return uOp->getSubExpr()->getType();
  8668. }
  8669. // Technically, there should be a check for array subscript
  8670. // expressions here, but the result of one is always an lvalue anyway.
  8671. }
  8672. ValueDecl *dcl = getPrimaryDecl(op);
  8673. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8674. unsigned AddressOfError = AO_No_Error;
  8675. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8676. bool sfinae = (bool)isSFINAEContext();
  8677. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8678. : diag::ext_typecheck_addrof_temporary)
  8679. << op->getType() << op->getSourceRange();
  8680. if (sfinae)
  8681. return QualType();
  8682. // Materialize the temporary as an lvalue so that we can take its address.
  8683. OrigOp = op = new (Context)
  8684. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8685. } else if (isa<ObjCSelectorExpr>(op)) {
  8686. return Context.getPointerType(op->getType());
  8687. } else if (lval == Expr::LV_MemberFunction) {
  8688. // If it's an instance method, make a member pointer.
  8689. // The expression must have exactly the form &A::foo.
  8690. // If the underlying expression isn't a decl ref, give up.
  8691. if (!isa<DeclRefExpr>(op)) {
  8692. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8693. << OrigOp.get()->getSourceRange();
  8694. return QualType();
  8695. }
  8696. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8697. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8698. // The id-expression was parenthesized.
  8699. if (OrigOp.get() != DRE) {
  8700. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8701. << OrigOp.get()->getSourceRange();
  8702. // The method was named without a qualifier.
  8703. } else if (!DRE->getQualifier()) {
  8704. if (MD->getParent()->getName().empty())
  8705. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8706. << op->getSourceRange();
  8707. else {
  8708. SmallString<32> Str;
  8709. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8710. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8711. << op->getSourceRange()
  8712. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8713. }
  8714. }
  8715. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8716. if (isa<CXXDestructorDecl>(MD))
  8717. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8718. QualType MPTy = Context.getMemberPointerType(
  8719. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8720. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8721. RequireCompleteType(OpLoc, MPTy, 0);
  8722. return MPTy;
  8723. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8724. // C99 6.5.3.2p1
  8725. // The operand must be either an l-value or a function designator
  8726. if (!op->getType()->isFunctionType()) {
  8727. // Use a special diagnostic for loads from property references.
  8728. if (isa<PseudoObjectExpr>(op)) {
  8729. AddressOfError = AO_Property_Expansion;
  8730. } else {
  8731. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8732. << op->getType() << op->getSourceRange();
  8733. return QualType();
  8734. }
  8735. }
  8736. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8737. // The operand cannot be a bit-field
  8738. AddressOfError = AO_Bit_Field;
  8739. } else if (op->getObjectKind() == OK_VectorComponent) {
  8740. // The operand cannot be an element of a vector
  8741. AddressOfError = AO_Vector_Element;
  8742. } else if (dcl) { // C99 6.5.3.2p1
  8743. // We have an lvalue with a decl. Make sure the decl is not declared
  8744. // with the register storage-class specifier.
  8745. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8746. // in C++ it is not error to take address of a register
  8747. // variable (c++03 7.1.1P3)
  8748. if (vd->getStorageClass() == SC_Register &&
  8749. !getLangOpts().CPlusPlus) {
  8750. AddressOfError = AO_Register_Variable;
  8751. }
  8752. } else if (isa<MSPropertyDecl>(dcl)) {
  8753. AddressOfError = AO_Property_Expansion;
  8754. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8755. return Context.OverloadTy;
  8756. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8757. // Okay: we can take the address of a field.
  8758. // Could be a pointer to member, though, if there is an explicit
  8759. // scope qualifier for the class.
  8760. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8761. DeclContext *Ctx = dcl->getDeclContext();
  8762. if (Ctx && Ctx->isRecord()) {
  8763. if (dcl->getType()->isReferenceType()) {
  8764. Diag(OpLoc,
  8765. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8766. << dcl->getDeclName() << dcl->getType();
  8767. return QualType();
  8768. }
  8769. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8770. Ctx = Ctx->getParent();
  8771. QualType MPTy = Context.getMemberPointerType(
  8772. op->getType(),
  8773. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8774. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8775. RequireCompleteType(OpLoc, MPTy, 0);
  8776. return MPTy;
  8777. }
  8778. }
  8779. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8780. llvm_unreachable("Unknown/unexpected decl type");
  8781. }
  8782. if (AddressOfError != AO_No_Error) {
  8783. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8784. return QualType();
  8785. }
  8786. if (lval == Expr::LV_IncompleteVoidType) {
  8787. // Taking the address of a void variable is technically illegal, but we
  8788. // allow it in cases which are otherwise valid.
  8789. // Example: "extern void x; void* y = &x;".
  8790. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8791. }
  8792. // If the operand has type "type", the result has type "pointer to type".
  8793. if (op->getType()->isObjCObjectType())
  8794. return Context.getObjCObjectPointerType(op->getType());
  8795. return Context.getPointerType(op->getType());
  8796. }
  8797. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8798. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8799. if (!DRE)
  8800. return;
  8801. const Decl *D = DRE->getDecl();
  8802. if (!D)
  8803. return;
  8804. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8805. if (!Param)
  8806. return;
  8807. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8808. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8809. return;
  8810. if (FunctionScopeInfo *FD = S.getCurFunction())
  8811. if (!FD->ModifiedNonNullParams.count(Param))
  8812. FD->ModifiedNonNullParams.insert(Param);
  8813. }
  8814. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8815. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8816. SourceLocation OpLoc) {
  8817. if (Op->isTypeDependent())
  8818. return S.Context.DependentTy;
  8819. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8820. if (ConvResult.isInvalid())
  8821. return QualType();
  8822. Op = ConvResult.get();
  8823. QualType OpTy = Op->getType();
  8824. QualType Result;
  8825. if (isa<CXXReinterpretCastExpr>(Op)) {
  8826. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8827. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8828. Op->getSourceRange());
  8829. }
  8830. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8831. Result = PT->getPointeeType();
  8832. else if (const ObjCObjectPointerType *OPT =
  8833. OpTy->getAs<ObjCObjectPointerType>())
  8834. Result = OPT->getPointeeType();
  8835. else {
  8836. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8837. if (PR.isInvalid()) return QualType();
  8838. if (PR.get() != Op)
  8839. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8840. }
  8841. if (Result.isNull()) {
  8842. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8843. << OpTy << Op->getSourceRange();
  8844. return QualType();
  8845. }
  8846. // Note that per both C89 and C99, indirection is always legal, even if Result
  8847. // is an incomplete type or void. It would be possible to warn about
  8848. // dereferencing a void pointer, but it's completely well-defined, and such a
  8849. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8850. // for pointers to 'void' but is fine for any other pointer type:
  8851. //
  8852. // C++ [expr.unary.op]p1:
  8853. // [...] the expression to which [the unary * operator] is applied shall
  8854. // be a pointer to an object type, or a pointer to a function type
  8855. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8856. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8857. << OpTy << Op->getSourceRange();
  8858. // Dereferences are usually l-values...
  8859. VK = VK_LValue;
  8860. // ...except that certain expressions are never l-values in C.
  8861. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8862. VK = VK_RValue;
  8863. return Result;
  8864. }
  8865. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8866. BinaryOperatorKind Opc;
  8867. switch (Kind) {
  8868. default: llvm_unreachable("Unknown binop!");
  8869. case tok::periodstar: Opc = BO_PtrMemD; break;
  8870. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8871. case tok::star: Opc = BO_Mul; break;
  8872. case tok::slash: Opc = BO_Div; break;
  8873. case tok::percent: Opc = BO_Rem; break;
  8874. case tok::plus: Opc = BO_Add; break;
  8875. case tok::minus: Opc = BO_Sub; break;
  8876. case tok::lessless: Opc = BO_Shl; break;
  8877. case tok::greatergreater: Opc = BO_Shr; break;
  8878. case tok::lessequal: Opc = BO_LE; break;
  8879. case tok::less: Opc = BO_LT; break;
  8880. case tok::greaterequal: Opc = BO_GE; break;
  8881. case tok::greater: Opc = BO_GT; break;
  8882. case tok::exclaimequal: Opc = BO_NE; break;
  8883. case tok::equalequal: Opc = BO_EQ; break;
  8884. case tok::amp: Opc = BO_And; break;
  8885. case tok::caret: Opc = BO_Xor; break;
  8886. case tok::pipe: Opc = BO_Or; break;
  8887. case tok::ampamp: Opc = BO_LAnd; break;
  8888. case tok::pipepipe: Opc = BO_LOr; break;
  8889. case tok::equal: Opc = BO_Assign; break;
  8890. case tok::starequal: Opc = BO_MulAssign; break;
  8891. case tok::slashequal: Opc = BO_DivAssign; break;
  8892. case tok::percentequal: Opc = BO_RemAssign; break;
  8893. case tok::plusequal: Opc = BO_AddAssign; break;
  8894. case tok::minusequal: Opc = BO_SubAssign; break;
  8895. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8896. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8897. case tok::ampequal: Opc = BO_AndAssign; break;
  8898. case tok::caretequal: Opc = BO_XorAssign; break;
  8899. case tok::pipeequal: Opc = BO_OrAssign; break;
  8900. case tok::comma: Opc = BO_Comma; break;
  8901. }
  8902. return Opc;
  8903. }
  8904. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8905. tok::TokenKind Kind) {
  8906. UnaryOperatorKind Opc;
  8907. switch (Kind) {
  8908. default: llvm_unreachable("Unknown unary op!");
  8909. case tok::plusplus: Opc = UO_PreInc; break;
  8910. case tok::minusminus: Opc = UO_PreDec; break;
  8911. case tok::amp: Opc = UO_AddrOf; break;
  8912. case tok::star: Opc = UO_Deref; break;
  8913. case tok::plus: Opc = UO_Plus; break;
  8914. case tok::minus: Opc = UO_Minus; break;
  8915. case tok::tilde: Opc = UO_Not; break;
  8916. case tok::exclaim: Opc = UO_LNot; break;
  8917. case tok::kw___real: Opc = UO_Real; break;
  8918. case tok::kw___imag: Opc = UO_Imag; break;
  8919. case tok::kw___extension__: Opc = UO_Extension; break;
  8920. }
  8921. return Opc;
  8922. }
  8923. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8924. /// This warning is only emitted for builtin assignment operations. It is also
  8925. /// suppressed in the event of macro expansions.
  8926. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8927. SourceLocation OpLoc) {
  8928. if (!S.ActiveTemplateInstantiations.empty())
  8929. return;
  8930. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8931. return;
  8932. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8933. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8934. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8935. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8936. if (!LHSDeclRef || !RHSDeclRef ||
  8937. LHSDeclRef->getLocation().isMacroID() ||
  8938. RHSDeclRef->getLocation().isMacroID())
  8939. return;
  8940. const ValueDecl *LHSDecl =
  8941. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  8942. const ValueDecl *RHSDecl =
  8943. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  8944. if (LHSDecl != RHSDecl)
  8945. return;
  8946. if (LHSDecl->getType().isVolatileQualified())
  8947. return;
  8948. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  8949. if (RefTy->getPointeeType().isVolatileQualified())
  8950. return;
  8951. S.Diag(OpLoc, diag::warn_self_assignment)
  8952. << LHSDeclRef->getType()
  8953. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8954. }
  8955. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  8956. /// is usually indicative of introspection within the Objective-C pointer.
  8957. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  8958. SourceLocation OpLoc) {
  8959. if (!S.getLangOpts().ObjC1)
  8960. return;
  8961. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  8962. const Expr *LHS = L.get();
  8963. const Expr *RHS = R.get();
  8964. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8965. ObjCPointerExpr = LHS;
  8966. OtherExpr = RHS;
  8967. }
  8968. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8969. ObjCPointerExpr = RHS;
  8970. OtherExpr = LHS;
  8971. }
  8972. // This warning is deliberately made very specific to reduce false
  8973. // positives with logic that uses '&' for hashing. This logic mainly
  8974. // looks for code trying to introspect into tagged pointers, which
  8975. // code should generally never do.
  8976. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  8977. unsigned Diag = diag::warn_objc_pointer_masking;
  8978. // Determine if we are introspecting the result of performSelectorXXX.
  8979. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  8980. // Special case messages to -performSelector and friends, which
  8981. // can return non-pointer values boxed in a pointer value.
  8982. // Some clients may wish to silence warnings in this subcase.
  8983. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  8984. Selector S = ME->getSelector();
  8985. StringRef SelArg0 = S.getNameForSlot(0);
  8986. if (SelArg0.startswith("performSelector"))
  8987. Diag = diag::warn_objc_pointer_masking_performSelector;
  8988. }
  8989. S.Diag(OpLoc, Diag)
  8990. << ObjCPointerExpr->getSourceRange();
  8991. }
  8992. }
  8993. static NamedDecl *getDeclFromExpr(Expr *E) {
  8994. if (!E)
  8995. return nullptr;
  8996. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  8997. return DRE->getDecl();
  8998. if (auto *ME = dyn_cast<MemberExpr>(E))
  8999. return ME->getMemberDecl();
  9000. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  9001. return IRE->getDecl();
  9002. return nullptr;
  9003. }
  9004. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  9005. /// operator @p Opc at location @c TokLoc. This routine only supports
  9006. /// built-in operations; ActOnBinOp handles overloaded operators.
  9007. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  9008. BinaryOperatorKind Opc,
  9009. Expr *LHSExpr, Expr *RHSExpr) {
  9010. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  9011. // The syntax only allows initializer lists on the RHS of assignment,
  9012. // so we don't need to worry about accepting invalid code for
  9013. // non-assignment operators.
  9014. // C++11 5.17p9:
  9015. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  9016. // of x = {} is x = T().
  9017. InitializationKind Kind =
  9018. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  9019. InitializedEntity Entity =
  9020. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  9021. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  9022. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  9023. if (Init.isInvalid())
  9024. return Init;
  9025. RHSExpr = Init.get();
  9026. }
  9027. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  9028. QualType ResultTy; // Result type of the binary operator.
  9029. // The following two variables are used for compound assignment operators
  9030. QualType CompLHSTy; // Type of LHS after promotions for computation
  9031. QualType CompResultTy; // Type of computation result
  9032. ExprValueKind VK = VK_RValue;
  9033. ExprObjectKind OK = OK_Ordinary;
  9034. // HLSL Change Starts
  9035. // Handle HLSL binary operands differently
  9036. if (getLangOpts().HLSL) {
  9037. hlsl::CheckBinOpForHLSL(*this, OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  9038. if (!ResultTy.isNull() && Opc == BO_Comma) {
  9039. // In C/C++, the RHS value kind should propagate. In HLSL, it should yield an r-value.
  9040. // VK = RHS.get()->getValueKind();
  9041. OK = RHS.get()->getObjectKind();
  9042. }
  9043. goto CasesHandled;
  9044. }
  9045. // HLSL Change Ends
  9046. if (!getLangOpts().CPlusPlus) {
  9047. // C cannot handle TypoExpr nodes on either side of a binop because it
  9048. // doesn't handle dependent types properly, so make sure any TypoExprs have
  9049. // been dealt with before checking the operands.
  9050. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  9051. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  9052. if (Opc != BO_Assign)
  9053. return ExprResult(E);
  9054. // Avoid correcting the RHS to the same Expr as the LHS.
  9055. Decl *D = getDeclFromExpr(E);
  9056. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  9057. });
  9058. if (!LHS.isUsable() || !RHS.isUsable())
  9059. return ExprError();
  9060. }
  9061. switch (Opc) {
  9062. case BO_Assign:
  9063. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  9064. if (getLangOpts().CPlusPlus &&
  9065. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  9066. VK = LHS.get()->getValueKind();
  9067. OK = LHS.get()->getObjectKind();
  9068. }
  9069. if (!ResultTy.isNull()) {
  9070. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9071. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  9072. }
  9073. RecordModifiableNonNullParam(*this, LHS.get());
  9074. break;
  9075. case BO_PtrMemD:
  9076. case BO_PtrMemI:
  9077. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  9078. Opc == BO_PtrMemI);
  9079. break;
  9080. case BO_Mul:
  9081. case BO_Div:
  9082. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  9083. Opc == BO_Div);
  9084. break;
  9085. case BO_Rem:
  9086. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  9087. break;
  9088. case BO_Add:
  9089. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  9090. break;
  9091. case BO_Sub:
  9092. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  9093. break;
  9094. case BO_Shl:
  9095. case BO_Shr:
  9096. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  9097. break;
  9098. case BO_LE:
  9099. case BO_LT:
  9100. case BO_GE:
  9101. case BO_GT:
  9102. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  9103. break;
  9104. case BO_EQ:
  9105. case BO_NE:
  9106. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  9107. break;
  9108. case BO_And:
  9109. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  9110. case BO_Xor:
  9111. case BO_Or:
  9112. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  9113. break;
  9114. case BO_LAnd:
  9115. case BO_LOr:
  9116. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  9117. break;
  9118. case BO_MulAssign:
  9119. case BO_DivAssign:
  9120. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  9121. Opc == BO_DivAssign);
  9122. CompLHSTy = CompResultTy;
  9123. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9124. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9125. break;
  9126. case BO_RemAssign:
  9127. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  9128. CompLHSTy = CompResultTy;
  9129. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9130. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9131. break;
  9132. case BO_AddAssign:
  9133. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  9134. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9135. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9136. break;
  9137. case BO_SubAssign:
  9138. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  9139. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9140. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9141. break;
  9142. case BO_ShlAssign:
  9143. case BO_ShrAssign:
  9144. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  9145. CompLHSTy = CompResultTy;
  9146. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9147. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9148. break;
  9149. case BO_AndAssign:
  9150. case BO_OrAssign: // fallthrough
  9151. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9152. case BO_XorAssign:
  9153. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  9154. CompLHSTy = CompResultTy;
  9155. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9156. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9157. break;
  9158. case BO_Comma:
  9159. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  9160. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  9161. VK = RHS.get()->getValueKind();
  9162. OK = RHS.get()->getObjectKind();
  9163. }
  9164. break;
  9165. }
  9166. CasesHandled: // HLSL Change: minimize code changes by avoiding a branch above
  9167. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  9168. return ExprError();
  9169. // Check for array bounds violations for both sides of the BinaryOperator
  9170. CheckArrayAccess(LHS.get());
  9171. CheckArrayAccess(RHS.get());
  9172. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  9173. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  9174. &Context.Idents.get("object_setClass"),
  9175. SourceLocation(), LookupOrdinaryName);
  9176. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  9177. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  9178. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  9179. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  9180. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  9181. FixItHint::CreateInsertion(RHSLocEnd, ")");
  9182. }
  9183. else
  9184. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9185. }
  9186. else if (const ObjCIvarRefExpr *OIRE =
  9187. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9188. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9189. if (CompResultTy.isNull())
  9190. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9191. OK, OpLoc, FPFeatures.fp_contract);
  9192. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9193. OK_ObjCProperty) {
  9194. VK = VK_LValue;
  9195. OK = LHS.get()->getObjectKind();
  9196. }
  9197. return new (Context) CompoundAssignOperator(
  9198. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9199. OpLoc, FPFeatures.fp_contract);
  9200. }
  9201. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9202. /// operators are mixed in a way that suggests that the programmer forgot that
  9203. /// comparison operators have higher precedence. The most typical example of
  9204. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9205. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9206. SourceLocation OpLoc, Expr *LHSExpr,
  9207. Expr *RHSExpr) {
  9208. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9209. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9210. // Check that one of the sides is a comparison operator.
  9211. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9212. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9213. if (!isLeftComp && !isRightComp)
  9214. return;
  9215. // Bitwise operations are sometimes used as eager logical ops.
  9216. // Don't diagnose this.
  9217. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9218. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9219. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9220. return;
  9221. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9222. OpLoc)
  9223. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9224. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9225. SourceRange ParensRange = isLeftComp ?
  9226. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9227. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9228. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9229. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9230. SuggestParentheses(Self, OpLoc,
  9231. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9232. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9233. SuggestParentheses(Self, OpLoc,
  9234. Self.PDiag(diag::note_precedence_bitwise_first)
  9235. << BinaryOperator::getOpcodeStr(Opc),
  9236. ParensRange);
  9237. }
  9238. /// \brief It accepts a '&' expr that is inside a '|' one.
  9239. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9240. /// in parentheses.
  9241. static void
  9242. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9243. BinaryOperator *Bop) {
  9244. assert(Bop->getOpcode() == BO_And);
  9245. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9246. << Bop->getSourceRange() << OpLoc;
  9247. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9248. Self.PDiag(diag::note_precedence_silence)
  9249. << Bop->getOpcodeStr(),
  9250. Bop->getSourceRange());
  9251. }
  9252. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9253. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9254. /// in parentheses.
  9255. static void
  9256. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9257. BinaryOperator *Bop) {
  9258. assert(Bop->getOpcode() == BO_LAnd);
  9259. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9260. << Bop->getSourceRange() << OpLoc;
  9261. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9262. Self.PDiag(diag::note_precedence_silence)
  9263. << Bop->getOpcodeStr(),
  9264. Bop->getSourceRange());
  9265. }
  9266. /// \brief Returns true if the given expression can be evaluated as a constant
  9267. /// 'true'.
  9268. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9269. bool Res;
  9270. return !E->isValueDependent() &&
  9271. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9272. }
  9273. /// \brief Returns true if the given expression can be evaluated as a constant
  9274. /// 'false'.
  9275. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9276. bool Res;
  9277. return !E->isValueDependent() &&
  9278. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9279. }
  9280. /// \brief Look for '&&' in the left hand of a '||' expr.
  9281. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9282. Expr *LHSExpr, Expr *RHSExpr) {
  9283. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9284. if (Bop->getOpcode() == BO_LAnd) {
  9285. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9286. if (EvaluatesAsFalse(S, RHSExpr))
  9287. return;
  9288. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9289. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9290. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9291. } else if (Bop->getOpcode() == BO_LOr) {
  9292. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9293. // If it's "a || b && 1 || c" we didn't warn earlier for
  9294. // "a || b && 1", but warn now.
  9295. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9296. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9297. }
  9298. }
  9299. }
  9300. }
  9301. /// \brief Look for '&&' in the right hand of a '||' expr.
  9302. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9303. Expr *LHSExpr, Expr *RHSExpr) {
  9304. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9305. if (Bop->getOpcode() == BO_LAnd) {
  9306. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9307. if (EvaluatesAsFalse(S, LHSExpr))
  9308. return;
  9309. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9310. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9311. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9312. }
  9313. }
  9314. }
  9315. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9316. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9317. Expr *OrArg) {
  9318. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9319. if (Bop->getOpcode() == BO_And)
  9320. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9321. }
  9322. }
  9323. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9324. Expr *SubExpr, StringRef Shift) {
  9325. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9326. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9327. StringRef Op = Bop->getOpcodeStr();
  9328. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9329. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9330. SuggestParentheses(S, Bop->getOperatorLoc(),
  9331. S.PDiag(diag::note_precedence_silence) << Op,
  9332. Bop->getSourceRange());
  9333. }
  9334. }
  9335. }
  9336. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9337. Expr *LHSExpr, Expr *RHSExpr) {
  9338. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9339. if (!OCE)
  9340. return;
  9341. FunctionDecl *FD = OCE->getDirectCallee();
  9342. if (!FD || !FD->isOverloadedOperator())
  9343. return;
  9344. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9345. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9346. return;
  9347. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9348. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9349. << (Kind == OO_LessLess);
  9350. SuggestParentheses(S, OCE->getOperatorLoc(),
  9351. S.PDiag(diag::note_precedence_silence)
  9352. << (Kind == OO_LessLess ? "<<" : ">>"),
  9353. OCE->getSourceRange());
  9354. SuggestParentheses(S, OpLoc,
  9355. S.PDiag(diag::note_evaluate_comparison_first),
  9356. SourceRange(OCE->getArg(1)->getLocStart(),
  9357. RHSExpr->getLocEnd()));
  9358. }
  9359. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9360. /// precedence.
  9361. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9362. SourceLocation OpLoc, Expr *LHSExpr,
  9363. Expr *RHSExpr){
  9364. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9365. if (BinaryOperator::isBitwiseOp(Opc))
  9366. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9367. // Diagnose "arg1 & arg2 | arg3"
  9368. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9369. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9370. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9371. }
  9372. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9373. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9374. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9375. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9376. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9377. }
  9378. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9379. || Opc == BO_Shr) {
  9380. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9381. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9382. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9383. }
  9384. // Warn on overloaded shift operators and comparisons, such as:
  9385. // cout << 5 == 4;
  9386. if (BinaryOperator::isComparisonOp(Opc))
  9387. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9388. }
  9389. // Binary Operators. 'Tok' is the token for the operator.
  9390. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9391. tok::TokenKind Kind,
  9392. Expr *LHSExpr, Expr *RHSExpr) {
  9393. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9394. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9395. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9396. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9397. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9398. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9399. }
  9400. /// Build an overloaded binary operator expression in the given scope.
  9401. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9402. BinaryOperatorKind Opc,
  9403. Expr *LHS, Expr *RHS) {
  9404. // Find all of the overloaded operators visible from this
  9405. // point. We perform both an operator-name lookup from the local
  9406. // scope and an argument-dependent lookup based on the types of
  9407. // the arguments.
  9408. UnresolvedSet<16> Functions;
  9409. OverloadedOperatorKind OverOp
  9410. = BinaryOperator::getOverloadedOperator(Opc);
  9411. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9412. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9413. RHS->getType(), Functions);
  9414. // Build the (potentially-overloaded, potentially-dependent)
  9415. // binary operation.
  9416. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9417. }
  9418. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9419. BinaryOperatorKind Opc,
  9420. Expr *LHSExpr, Expr *RHSExpr) {
  9421. // We want to end up calling one of checkPseudoObjectAssignment
  9422. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9423. // both expressions are overloadable or either is type-dependent),
  9424. // or CreateBuiltinBinOp (in any other case). We also want to get
  9425. // any placeholder types out of the way.
  9426. // Handle pseudo-objects in the LHS.
  9427. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9428. // Assignments with a pseudo-object l-value need special analysis.
  9429. if (pty->getKind() == BuiltinType::PseudoObject &&
  9430. BinaryOperator::isAssignmentOp(Opc))
  9431. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9432. // Don't resolve overloads if the other type is overloadable.
  9433. if (pty->getKind() == BuiltinType::Overload) {
  9434. // We can't actually test that if we still have a placeholder,
  9435. // though. Fortunately, none of the exceptions we see in that
  9436. // code below are valid when the LHS is an overload set. Note
  9437. // that an overload set can be dependently-typed, but it never
  9438. // instantiates to having an overloadable type.
  9439. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9440. if (resolvedRHS.isInvalid()) return ExprError();
  9441. RHSExpr = resolvedRHS.get();
  9442. if (RHSExpr->isTypeDependent() ||
  9443. RHSExpr->getType()->isOverloadableType())
  9444. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9445. }
  9446. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9447. if (LHS.isInvalid()) return ExprError();
  9448. LHSExpr = LHS.get();
  9449. }
  9450. // Handle pseudo-objects in the RHS.
  9451. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9452. // An overload in the RHS can potentially be resolved by the type
  9453. // being assigned to.
  9454. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9455. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9456. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9457. if (LHSExpr->getType()->isOverloadableType())
  9458. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9459. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9460. }
  9461. // Don't resolve overloads if the other type is overloadable.
  9462. if (pty->getKind() == BuiltinType::Overload &&
  9463. LHSExpr->getType()->isOverloadableType())
  9464. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9465. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9466. if (!resolvedRHS.isUsable()) return ExprError();
  9467. RHSExpr = resolvedRHS.get();
  9468. }
  9469. // HLSL Change: bypass binary operator overload work, which isn't supported in any case;
  9470. // otherwise more extensive changes need to be done to add HLSL-specific behavior to
  9471. // be considered when building overload candidate sets
  9472. if (getLangOpts().CPlusPlus && !getLangOpts().HLSL) {
  9473. // If either expression is type-dependent, always build an
  9474. // overloaded op.
  9475. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9476. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9477. // Otherwise, build an overloaded op if either expression has an
  9478. // overloadable type.
  9479. if (LHSExpr->getType()->isOverloadableType() ||
  9480. RHSExpr->getType()->isOverloadableType())
  9481. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9482. }
  9483. // Build a built-in binary operation.
  9484. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9485. }
  9486. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9487. UnaryOperatorKind Opc,
  9488. Expr *InputExpr) {
  9489. ExprResult Input = InputExpr;
  9490. ExprValueKind VK = VK_RValue;
  9491. ExprObjectKind OK = OK_Ordinary;
  9492. QualType resultType;
  9493. // HLSL Change Starts
  9494. if (getLangOpts().HLSL) {
  9495. resultType = hlsl::CheckUnaryOpForHLSL(*this, OpLoc, Opc, Input, VK, OK);
  9496. goto CasesHandled;
  9497. }
  9498. // HLSL Change Ends
  9499. switch (Opc) {
  9500. case UO_PreInc:
  9501. case UO_PreDec:
  9502. case UO_PostInc:
  9503. case UO_PostDec:
  9504. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9505. OpLoc,
  9506. Opc == UO_PreInc ||
  9507. Opc == UO_PostInc,
  9508. Opc == UO_PreInc ||
  9509. Opc == UO_PreDec);
  9510. break;
  9511. case UO_AddrOf:
  9512. resultType = CheckAddressOfOperand(Input, OpLoc);
  9513. RecordModifiableNonNullParam(*this, InputExpr);
  9514. break;
  9515. case UO_Deref: {
  9516. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9517. if (Input.isInvalid()) return ExprError();
  9518. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9519. break;
  9520. }
  9521. case UO_Plus:
  9522. case UO_Minus:
  9523. Input = UsualUnaryConversions(Input.get());
  9524. if (Input.isInvalid()) return ExprError();
  9525. resultType = Input.get()->getType();
  9526. if (resultType->isDependentType())
  9527. break;
  9528. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9529. break;
  9530. else if (resultType->isVectorType() &&
  9531. // The z vector extensions don't allow + or - with bool vectors.
  9532. (!Context.getLangOpts().ZVector ||
  9533. resultType->getAs<VectorType>()->getVectorKind() !=
  9534. VectorType::AltiVecBool))
  9535. break;
  9536. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9537. Opc == UO_Plus &&
  9538. resultType->isPointerType())
  9539. break;
  9540. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9541. << resultType << Input.get()->getSourceRange());
  9542. case UO_Not: // bitwise complement
  9543. Input = UsualUnaryConversions(Input.get());
  9544. if (Input.isInvalid())
  9545. return ExprError();
  9546. resultType = Input.get()->getType();
  9547. if (resultType->isDependentType())
  9548. break;
  9549. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9550. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9551. // C99 does not support '~' for complex conjugation.
  9552. Diag(OpLoc, diag::ext_integer_complement_complex)
  9553. << resultType << Input.get()->getSourceRange();
  9554. else if (resultType->hasIntegerRepresentation())
  9555. break;
  9556. else if (resultType->isExtVectorType()) {
  9557. if (Context.getLangOpts().OpenCL) {
  9558. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9559. // on vector float types.
  9560. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9561. if (!T->isIntegerType())
  9562. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9563. << resultType << Input.get()->getSourceRange());
  9564. }
  9565. break;
  9566. } else {
  9567. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9568. << resultType << Input.get()->getSourceRange());
  9569. }
  9570. break;
  9571. case UO_LNot: // logical negation
  9572. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9573. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9574. if (Input.isInvalid()) return ExprError();
  9575. resultType = Input.get()->getType();
  9576. // Though we still have to promote half FP to float...
  9577. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9578. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9579. resultType = Context.FloatTy;
  9580. }
  9581. if (resultType->isDependentType())
  9582. break;
  9583. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9584. // C99 6.5.3.3p1: ok, fallthrough;
  9585. if (Context.getLangOpts().CPlusPlus) {
  9586. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9587. // operand contextually converted to bool.
  9588. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9589. ScalarTypeToBooleanCastKind(resultType));
  9590. } else if (Context.getLangOpts().OpenCL &&
  9591. Context.getLangOpts().OpenCLVersion < 120) {
  9592. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9593. // operate on scalar float types.
  9594. if (!resultType->isIntegerType())
  9595. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9596. << resultType << Input.get()->getSourceRange());
  9597. }
  9598. } else if (resultType->isExtVectorType()) {
  9599. if (Context.getLangOpts().OpenCL &&
  9600. Context.getLangOpts().OpenCLVersion < 120) {
  9601. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9602. // operate on vector float types.
  9603. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9604. if (!T->isIntegerType())
  9605. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9606. << resultType << Input.get()->getSourceRange());
  9607. }
  9608. // Vector logical not returns the signed variant of the operand type.
  9609. resultType = GetSignedVectorType(resultType);
  9610. break;
  9611. } else {
  9612. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9613. << resultType << Input.get()->getSourceRange());
  9614. }
  9615. // LNot always has type int. C99 6.5.3.3p5.
  9616. // In C++, it's bool. C++ 5.3.1p8
  9617. resultType = Context.getLogicalOperationType();
  9618. break;
  9619. case UO_Real:
  9620. case UO_Imag:
  9621. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9622. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9623. // complex l-values to ordinary l-values and all other values to r-values.
  9624. if (Input.isInvalid()) return ExprError();
  9625. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9626. if (Input.get()->getValueKind() != VK_RValue &&
  9627. Input.get()->getObjectKind() == OK_Ordinary)
  9628. VK = Input.get()->getValueKind();
  9629. } else if (!getLangOpts().CPlusPlus) {
  9630. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9631. Input = DefaultLvalueConversion(Input.get());
  9632. }
  9633. break;
  9634. case UO_Extension:
  9635. resultType = Input.get()->getType();
  9636. VK = Input.get()->getValueKind();
  9637. OK = Input.get()->getObjectKind();
  9638. break;
  9639. }
  9640. CasesHandled: // HLSL Change: add label to skip C/C++ unary operator processing
  9641. if (resultType.isNull() || Input.isInvalid())
  9642. return ExprError();
  9643. // Check for array bounds violations in the operand of the UnaryOperator,
  9644. // except for the '*' and '&' operators that have to be handled specially
  9645. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9646. // that are explicitly defined as valid by the standard).
  9647. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9648. CheckArrayAccess(Input.get());
  9649. return new (Context)
  9650. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9651. }
  9652. /// \brief Determine whether the given expression is a qualified member
  9653. /// access expression, of a form that could be turned into a pointer to member
  9654. /// with the address-of operator.
  9655. static bool isQualifiedMemberAccess(Expr *E) {
  9656. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9657. if (!DRE->getQualifier())
  9658. return false;
  9659. ValueDecl *VD = DRE->getDecl();
  9660. if (!VD->isCXXClassMember())
  9661. return false;
  9662. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9663. return true;
  9664. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9665. return Method->isInstance();
  9666. return false;
  9667. }
  9668. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9669. if (!ULE->getQualifier())
  9670. return false;
  9671. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9672. DEnd = ULE->decls_end();
  9673. D != DEnd; ++D) {
  9674. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9675. if (Method->isInstance())
  9676. return true;
  9677. } else {
  9678. // Overload set does not contain methods.
  9679. break;
  9680. }
  9681. }
  9682. return false;
  9683. }
  9684. return false;
  9685. }
  9686. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9687. UnaryOperatorKind Opc, Expr *Input) {
  9688. // HLSL Change Starts - placeholders and overloaded operators not supported
  9689. if (getLangOpts().HLSL)
  9690. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9691. // HLSL Change Ends
  9692. // First things first: handle placeholders so that the
  9693. // overloaded-operator check considers the right type.
  9694. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9695. // Increment and decrement of pseudo-object references.
  9696. if (pty->getKind() == BuiltinType::PseudoObject &&
  9697. UnaryOperator::isIncrementDecrementOp(Opc))
  9698. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9699. // extension is always a builtin operator.
  9700. if (Opc == UO_Extension)
  9701. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9702. // & gets special logic for several kinds of placeholder.
  9703. // The builtin code knows what to do.
  9704. if (Opc == UO_AddrOf &&
  9705. (pty->getKind() == BuiltinType::Overload ||
  9706. pty->getKind() == BuiltinType::UnknownAny ||
  9707. pty->getKind() == BuiltinType::BoundMember))
  9708. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9709. // Anything else needs to be handled now.
  9710. ExprResult Result = CheckPlaceholderExpr(Input);
  9711. if (Result.isInvalid()) return ExprError();
  9712. Input = Result.get();
  9713. }
  9714. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9715. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9716. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9717. // Find all of the overloaded operators visible from this
  9718. // point. We perform both an operator-name lookup from the local
  9719. // scope and an argument-dependent lookup based on the types of
  9720. // the arguments.
  9721. UnresolvedSet<16> Functions;
  9722. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9723. if (S && OverOp != OO_None)
  9724. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9725. Functions);
  9726. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9727. }
  9728. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9729. }
  9730. // Unary Operators. 'Tok' is the token for the operator.
  9731. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9732. tok::TokenKind Op, Expr *Input) {
  9733. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9734. }
  9735. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9736. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9737. LabelDecl *TheDecl) {
  9738. TheDecl->markUsed(Context);
  9739. // Create the AST node. The address of a label always has type 'void*'.
  9740. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9741. Context.getPointerType(Context.VoidTy));
  9742. }
  9743. /// Given the last statement in a statement-expression, check whether
  9744. /// the result is a producing expression (like a call to an
  9745. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9746. /// release out of the full-expression. Otherwise, return null.
  9747. /// Cannot fail.
  9748. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9749. // Should always be wrapped with one of these.
  9750. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9751. if (!cleanups) return nullptr;
  9752. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9753. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9754. return nullptr;
  9755. // Splice out the cast. This shouldn't modify any interesting
  9756. // features of the statement.
  9757. Expr *producer = cast->getSubExpr();
  9758. assert(producer->getType() == cast->getType());
  9759. assert(producer->getValueKind() == cast->getValueKind());
  9760. cleanups->setSubExpr(producer);
  9761. return cleanups;
  9762. }
  9763. void Sema::ActOnStartStmtExpr() {
  9764. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9765. }
  9766. void Sema::ActOnStmtExprError() {
  9767. // Note that function is also called by TreeTransform when leaving a
  9768. // StmtExpr scope without rebuilding anything.
  9769. DiscardCleanupsInEvaluationContext();
  9770. PopExpressionEvaluationContext();
  9771. }
  9772. ExprResult
  9773. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9774. SourceLocation RPLoc) { // "({..})"
  9775. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9776. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9777. if (hasAnyUnrecoverableErrorsInThisFunction())
  9778. DiscardCleanupsInEvaluationContext();
  9779. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9780. PopExpressionEvaluationContext();
  9781. // FIXME: there are a variety of strange constraints to enforce here, for
  9782. // example, it is not possible to goto into a stmt expression apparently.
  9783. // More semantic analysis is needed.
  9784. // If there are sub-stmts in the compound stmt, take the type of the last one
  9785. // as the type of the stmtexpr.
  9786. QualType Ty = Context.VoidTy;
  9787. bool StmtExprMayBindToTemp = false;
  9788. if (!Compound->body_empty()) {
  9789. Stmt *LastStmt = Compound->body_back();
  9790. LabelStmt *LastLabelStmt = nullptr;
  9791. // If LastStmt is a label, skip down through into the body.
  9792. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9793. LastLabelStmt = Label;
  9794. LastStmt = Label->getSubStmt();
  9795. }
  9796. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9797. // Do function/array conversion on the last expression, but not
  9798. // lvalue-to-rvalue. However, initialize an unqualified type.
  9799. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9800. if (LastExpr.isInvalid())
  9801. return ExprError();
  9802. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9803. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9804. // In ARC, if the final expression ends in a consume, splice
  9805. // the consume out and bind it later. In the alternate case
  9806. // (when dealing with a retainable type), the result
  9807. // initialization will create a produce. In both cases the
  9808. // result will be +1, and we'll need to balance that out with
  9809. // a bind.
  9810. if (Expr *rebuiltLastStmt
  9811. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9812. LastExpr = rebuiltLastStmt;
  9813. } else {
  9814. LastExpr = PerformCopyInitialization(
  9815. InitializedEntity::InitializeResult(LPLoc,
  9816. Ty,
  9817. false),
  9818. SourceLocation(),
  9819. LastExpr);
  9820. }
  9821. if (LastExpr.isInvalid())
  9822. return ExprError();
  9823. if (LastExpr.get() != nullptr) {
  9824. if (!LastLabelStmt)
  9825. Compound->setLastStmt(LastExpr.get());
  9826. else
  9827. LastLabelStmt->setSubStmt(LastExpr.get());
  9828. StmtExprMayBindToTemp = true;
  9829. }
  9830. }
  9831. }
  9832. }
  9833. // FIXME: Check that expression type is complete/non-abstract; statement
  9834. // expressions are not lvalues.
  9835. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9836. if (StmtExprMayBindToTemp)
  9837. return MaybeBindToTemporary(ResStmtExpr);
  9838. return ResStmtExpr;
  9839. }
  9840. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9841. TypeSourceInfo *TInfo,
  9842. OffsetOfComponent *CompPtr,
  9843. unsigned NumComponents,
  9844. SourceLocation RParenLoc) {
  9845. QualType ArgTy = TInfo->getType();
  9846. bool Dependent = ArgTy->isDependentType();
  9847. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9848. // We must have at least one component that refers to the type, and the first
  9849. // one is known to be a field designator. Verify that the ArgTy represents
  9850. // a struct/union/class.
  9851. if (!Dependent && !ArgTy->isRecordType())
  9852. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9853. << ArgTy << TypeRange);
  9854. // Type must be complete per C99 7.17p3 because a declaring a variable
  9855. // with an incomplete type would be ill-formed.
  9856. if (!Dependent
  9857. && RequireCompleteType(BuiltinLoc, ArgTy,
  9858. diag::err_offsetof_incomplete_type, TypeRange))
  9859. return ExprError();
  9860. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9861. // GCC extension, diagnose them.
  9862. // FIXME: This diagnostic isn't actually visible because the location is in
  9863. // a system header!
  9864. if (NumComponents != 1)
  9865. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9866. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9867. bool DidWarnAboutNonPOD = false;
  9868. QualType CurrentType = ArgTy;
  9869. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9870. SmallVector<OffsetOfNode, 4> Comps;
  9871. SmallVector<Expr*, 4> Exprs;
  9872. for (unsigned i = 0; i != NumComponents; ++i) {
  9873. const OffsetOfComponent &OC = CompPtr[i];
  9874. if (OC.isBrackets) {
  9875. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9876. if (!CurrentType->isDependentType()) {
  9877. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9878. if(!AT)
  9879. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9880. << CurrentType);
  9881. CurrentType = AT->getElementType();
  9882. } else
  9883. CurrentType = Context.DependentTy;
  9884. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9885. if (IdxRval.isInvalid())
  9886. return ExprError();
  9887. Expr *Idx = IdxRval.get();
  9888. // The expression must be an integral expression.
  9889. // FIXME: An integral constant expression?
  9890. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9891. !Idx->getType()->isIntegerType())
  9892. return ExprError(Diag(Idx->getLocStart(),
  9893. diag::err_typecheck_subscript_not_integer)
  9894. << Idx->getSourceRange());
  9895. // Record this array index.
  9896. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9897. Exprs.push_back(Idx);
  9898. continue;
  9899. }
  9900. // Offset of a field.
  9901. if (CurrentType->isDependentType()) {
  9902. // We have the offset of a field, but we can't look into the dependent
  9903. // type. Just record the identifier of the field.
  9904. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9905. CurrentType = Context.DependentTy;
  9906. continue;
  9907. }
  9908. // We need to have a complete type to look into.
  9909. if (RequireCompleteType(OC.LocStart, CurrentType,
  9910. diag::err_offsetof_incomplete_type))
  9911. return ExprError();
  9912. // Look for the designated field.
  9913. const RecordType *RC = CurrentType->getAs<RecordType>();
  9914. if (!RC)
  9915. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9916. << CurrentType);
  9917. RecordDecl *RD = RC->getDecl();
  9918. // C++ [lib.support.types]p5:
  9919. // The macro offsetof accepts a restricted set of type arguments in this
  9920. // International Standard. type shall be a POD structure or a POD union
  9921. // (clause 9).
  9922. // C++11 [support.types]p4:
  9923. // If type is not a standard-layout class (Clause 9), the results are
  9924. // undefined.
  9925. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9926. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9927. unsigned DiagID =
  9928. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9929. : diag::ext_offsetof_non_pod_type;
  9930. if (!IsSafe && !DidWarnAboutNonPOD &&
  9931. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9932. PDiag(DiagID)
  9933. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  9934. << CurrentType))
  9935. DidWarnAboutNonPOD = true;
  9936. }
  9937. // Look for the field.
  9938. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  9939. LookupQualifiedName(R, RD);
  9940. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  9941. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  9942. if (!MemberDecl) {
  9943. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  9944. MemberDecl = IndirectMemberDecl->getAnonField();
  9945. }
  9946. if (!MemberDecl)
  9947. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  9948. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  9949. OC.LocEnd));
  9950. // C99 7.17p3:
  9951. // (If the specified member is a bit-field, the behavior is undefined.)
  9952. //
  9953. // We diagnose this as an error.
  9954. if (MemberDecl->isBitField()) {
  9955. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  9956. << MemberDecl->getDeclName()
  9957. << SourceRange(BuiltinLoc, RParenLoc);
  9958. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  9959. return ExprError();
  9960. }
  9961. RecordDecl *Parent = MemberDecl->getParent();
  9962. if (IndirectMemberDecl)
  9963. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  9964. // If the member was found in a base class, introduce OffsetOfNodes for
  9965. // the base class indirections.
  9966. CXXBasePaths Paths;
  9967. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  9968. if (Paths.getDetectedVirtual()) {
  9969. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  9970. << MemberDecl->getDeclName()
  9971. << SourceRange(BuiltinLoc, RParenLoc);
  9972. return ExprError();
  9973. }
  9974. CXXBasePath &Path = Paths.front();
  9975. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  9976. B != BEnd; ++B)
  9977. Comps.push_back(OffsetOfNode(B->Base));
  9978. }
  9979. if (IndirectMemberDecl) {
  9980. for (auto *FI : IndirectMemberDecl->chain()) {
  9981. assert(isa<FieldDecl>(FI));
  9982. Comps.push_back(OffsetOfNode(OC.LocStart,
  9983. cast<FieldDecl>(FI), OC.LocEnd));
  9984. }
  9985. } else
  9986. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  9987. CurrentType = MemberDecl->getType().getNonReferenceType();
  9988. }
  9989. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  9990. Comps, Exprs, RParenLoc);
  9991. }
  9992. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  9993. SourceLocation BuiltinLoc,
  9994. SourceLocation TypeLoc,
  9995. ParsedType ParsedArgTy,
  9996. OffsetOfComponent *CompPtr,
  9997. unsigned NumComponents,
  9998. SourceLocation RParenLoc) {
  9999. TypeSourceInfo *ArgTInfo;
  10000. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  10001. if (ArgTy.isNull())
  10002. return ExprError();
  10003. if (!ArgTInfo)
  10004. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  10005. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  10006. RParenLoc);
  10007. }
  10008. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  10009. Expr *CondExpr,
  10010. Expr *LHSExpr, Expr *RHSExpr,
  10011. SourceLocation RPLoc) {
  10012. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  10013. ExprValueKind VK = VK_RValue;
  10014. ExprObjectKind OK = OK_Ordinary;
  10015. QualType resType;
  10016. bool ValueDependent = false;
  10017. bool CondIsTrue = false;
  10018. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  10019. resType = Context.DependentTy;
  10020. ValueDependent = true;
  10021. } else {
  10022. // The conditional expression is required to be a constant expression.
  10023. llvm::APSInt condEval(32);
  10024. ExprResult CondICE
  10025. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  10026. diag::err_typecheck_choose_expr_requires_constant, false);
  10027. if (CondICE.isInvalid())
  10028. return ExprError();
  10029. CondExpr = CondICE.get();
  10030. CondIsTrue = condEval.getZExtValue();
  10031. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  10032. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  10033. resType = ActiveExpr->getType();
  10034. ValueDependent = ActiveExpr->isValueDependent();
  10035. VK = ActiveExpr->getValueKind();
  10036. OK = ActiveExpr->getObjectKind();
  10037. }
  10038. return new (Context)
  10039. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  10040. CondIsTrue, resType->isDependentType(), ValueDependent);
  10041. }
  10042. //===----------------------------------------------------------------------===//
  10043. // Clang Extensions.
  10044. //===----------------------------------------------------------------------===//
  10045. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  10046. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  10047. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  10048. if (LangOpts.CPlusPlus) {
  10049. Decl *ManglingContextDecl;
  10050. if (MangleNumberingContext *MCtx =
  10051. getCurrentMangleNumberContext(Block->getDeclContext(),
  10052. ManglingContextDecl)) {
  10053. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  10054. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  10055. }
  10056. }
  10057. PushBlockScope(CurScope, Block);
  10058. CurContext->addDecl(Block);
  10059. if (CurScope)
  10060. PushDeclContext(CurScope, Block);
  10061. else
  10062. CurContext = Block;
  10063. getCurBlock()->HasImplicitReturnType = true;
  10064. // Enter a new evaluation context to insulate the block from any
  10065. // cleanups from the enclosing full-expression.
  10066. PushExpressionEvaluationContext(PotentiallyEvaluated);
  10067. }
  10068. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  10069. Scope *CurScope) {
  10070. assert(ParamInfo.getIdentifier() == nullptr &&
  10071. "block-id should have no identifier!");
  10072. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  10073. BlockScopeInfo *CurBlock = getCurBlock();
  10074. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  10075. QualType T = Sig->getType();
  10076. // FIXME: We should allow unexpanded parameter packs here, but that would,
  10077. // in turn, make the block expression contain unexpanded parameter packs.
  10078. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  10079. // Drop the parameters.
  10080. FunctionProtoType::ExtProtoInfo EPI;
  10081. EPI.HasTrailingReturn = false;
  10082. EPI.TypeQuals |= DeclSpec::TQ_const;
  10083. T = Context.getFunctionType(Context.DependentTy, None, EPI, None); // HLSL Change - add param mods
  10084. Sig = Context.getTrivialTypeSourceInfo(T);
  10085. }
  10086. // GetTypeForDeclarator always produces a function type for a block
  10087. // literal signature. Furthermore, it is always a FunctionProtoType
  10088. // unless the function was written with a typedef.
  10089. assert(T->isFunctionType() &&
  10090. "GetTypeForDeclarator made a non-function block signature");
  10091. // Look for an explicit signature in that function type.
  10092. FunctionProtoTypeLoc ExplicitSignature;
  10093. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  10094. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  10095. // Check whether that explicit signature was synthesized by
  10096. // GetTypeForDeclarator. If so, don't save that as part of the
  10097. // written signature.
  10098. if (ExplicitSignature.getLocalRangeBegin() ==
  10099. ExplicitSignature.getLocalRangeEnd()) {
  10100. // This would be much cheaper if we stored TypeLocs instead of
  10101. // TypeSourceInfos.
  10102. TypeLoc Result = ExplicitSignature.getReturnLoc();
  10103. unsigned Size = Result.getFullDataSize();
  10104. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  10105. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  10106. ExplicitSignature = FunctionProtoTypeLoc();
  10107. }
  10108. }
  10109. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  10110. CurBlock->FunctionType = T;
  10111. const FunctionType *Fn = T->getAs<FunctionType>();
  10112. QualType RetTy = Fn->getReturnType();
  10113. bool isVariadic =
  10114. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  10115. CurBlock->TheDecl->setIsVariadic(isVariadic);
  10116. // Context.DependentTy is used as a placeholder for a missing block
  10117. // return type. TODO: what should we do with declarators like:
  10118. // ^ * { ... }
  10119. // If the answer is "apply template argument deduction"....
  10120. if (RetTy != Context.DependentTy) {
  10121. CurBlock->ReturnType = RetTy;
  10122. CurBlock->TheDecl->setBlockMissingReturnType(false);
  10123. CurBlock->HasImplicitReturnType = false;
  10124. }
  10125. // Push block parameters from the declarator if we had them.
  10126. SmallVector<ParmVarDecl*, 8> Params;
  10127. if (ExplicitSignature) {
  10128. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  10129. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  10130. if (Param->getIdentifier() == nullptr &&
  10131. !Param->isImplicit() &&
  10132. !Param->isInvalidDecl() &&
  10133. !getLangOpts().CPlusPlus)
  10134. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10135. Params.push_back(Param);
  10136. }
  10137. // Fake up parameter variables if we have a typedef, like
  10138. // ^ fntype { ... }
  10139. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  10140. for (const auto &I : Fn->param_types()) {
  10141. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  10142. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  10143. Params.push_back(Param);
  10144. }
  10145. }
  10146. // Set the parameters on the block decl.
  10147. if (!Params.empty()) {
  10148. CurBlock->TheDecl->setParams(Params);
  10149. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  10150. CurBlock->TheDecl->param_end(),
  10151. /*CheckParameterNames=*/false);
  10152. }
  10153. // Finally we can process decl attributes.
  10154. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  10155. // Put the parameter variables in scope.
  10156. for (auto AI : CurBlock->TheDecl->params()) {
  10157. AI->setOwningFunction(CurBlock->TheDecl);
  10158. // If this has an identifier, add it to the scope stack.
  10159. if (AI->getIdentifier()) {
  10160. CheckShadow(CurBlock->TheScope, AI);
  10161. PushOnScopeChains(AI, CurBlock->TheScope);
  10162. }
  10163. }
  10164. }
  10165. /// ActOnBlockError - If there is an error parsing a block, this callback
  10166. /// is invoked to pop the information about the block from the action impl.
  10167. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  10168. // Leave the expression-evaluation context.
  10169. DiscardCleanupsInEvaluationContext();
  10170. PopExpressionEvaluationContext();
  10171. // Pop off CurBlock, handle nested blocks.
  10172. PopDeclContext();
  10173. PopFunctionScopeInfo();
  10174. }
  10175. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  10176. /// literal was successfully completed. ^(int x){...}
  10177. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  10178. Stmt *Body, Scope *CurScope) {
  10179. // HLSL Changes Start
  10180. llvm_unreachable("block statements unsupported and unreachable in HLSL");
  10181. #if 0
  10182. // HLSL Changes End
  10183. // If blocks are disabled, emit an error.
  10184. if (!LangOpts.Blocks)
  10185. Diag(CaretLoc, diag::err_blocks_disable);
  10186. // Leave the expression-evaluation context.
  10187. if (hasAnyUnrecoverableErrorsInThisFunction())
  10188. DiscardCleanupsInEvaluationContext();
  10189. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  10190. PopExpressionEvaluationContext();
  10191. if (getLangOpts().HLSL) {
  10192. return ExprError();
  10193. }
  10194. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  10195. if (BSI->HasImplicitReturnType)
  10196. deduceClosureReturnType(*BSI);
  10197. PopDeclContext();
  10198. QualType RetTy = Context.VoidTy;
  10199. if (!BSI->ReturnType.isNull())
  10200. RetTy = BSI->ReturnType;
  10201. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  10202. QualType BlockTy;
  10203. // Set the captured variables on the block.
  10204. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10205. SmallVector<BlockDecl::Capture, 4> Captures;
  10206. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10207. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10208. if (Cap.isThisCapture())
  10209. continue;
  10210. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10211. Cap.isNested(), Cap.getInitExpr());
  10212. Captures.push_back(NewCap);
  10213. }
  10214. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  10215. BSI->CXXThisCaptureIndex != 0);
  10216. // If the user wrote a function type in some form, try to use that.
  10217. if (!BSI->FunctionType.isNull()) {
  10218. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10219. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10220. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10221. // Turn protoless block types into nullary block types.
  10222. if (isa<FunctionNoProtoType>(FTy)) {
  10223. FunctionProtoType::ExtProtoInfo EPI;
  10224. EPI.ExtInfo = Ext;
  10225. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10226. // Otherwise, if we don't need to change anything about the function type,
  10227. // preserve its sugar structure.
  10228. } else if (FTy->getReturnType() == RetTy &&
  10229. (!NoReturn || FTy->getNoReturnAttr())) {
  10230. BlockTy = BSI->FunctionType;
  10231. // Otherwise, make the minimal modifications to the function type.
  10232. } else {
  10233. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10234. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10235. EPI.TypeQuals = 0; // FIXME: silently?
  10236. EPI.ExtInfo = Ext;
  10237. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10238. }
  10239. // If we don't have a function type, just build one from nothing.
  10240. } else {
  10241. FunctionProtoType::ExtProtoInfo EPI;
  10242. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10243. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10244. }
  10245. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10246. BSI->TheDecl->param_end());
  10247. BlockTy = Context.getBlockPointerType(BlockTy);
  10248. // If needed, diagnose invalid gotos and switches in the block.
  10249. if (getCurFunction()->NeedsScopeChecking() &&
  10250. !PP.isCodeCompletionEnabled())
  10251. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10252. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10253. // Try to apply the named return value optimization. We have to check again
  10254. // if we can do this, though, because blocks keep return statements around
  10255. // to deduce an implicit return type.
  10256. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10257. !BSI->TheDecl->isDependentContext())
  10258. computeNRVO(Body, BSI);
  10259. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10260. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10261. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10262. // If the block isn't obviously global, i.e. it captures anything at
  10263. // all, then we need to do a few things in the surrounding context:
  10264. if (Result->getBlockDecl()->hasCaptures()) {
  10265. // First, this expression has a new cleanup object.
  10266. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10267. ExprNeedsCleanups = true;
  10268. // It also gets a branch-protected scope if any of the captured
  10269. // variables needs destruction.
  10270. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10271. const VarDecl *var = CI.getVariable();
  10272. if (var->getType().isDestructedType() != QualType::DK_none) {
  10273. getCurFunction()->setHasBranchProtectedScope();
  10274. break;
  10275. }
  10276. }
  10277. }
  10278. return Result;
  10279. #endif // HLSL Change
  10280. }
  10281. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10282. Expr *E, ParsedType Ty,
  10283. SourceLocation RPLoc) {
  10284. TypeSourceInfo *TInfo;
  10285. GetTypeFromParser(Ty, &TInfo);
  10286. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10287. }
  10288. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10289. Expr *E, TypeSourceInfo *TInfo,
  10290. SourceLocation RPLoc) {
  10291. Expr *OrigExpr = E;
  10292. // Get the va_list type
  10293. QualType VaListType = Context.getBuiltinVaListType();
  10294. if (VaListType->isArrayType()) {
  10295. // Deal with implicit array decay; for example, on x86-64,
  10296. // va_list is an array, but it's supposed to decay to
  10297. // a pointer for va_arg.
  10298. VaListType = Context.getArrayDecayedType(VaListType);
  10299. // Make sure the input expression also decays appropriately.
  10300. ExprResult Result = UsualUnaryConversions(E);
  10301. if (Result.isInvalid())
  10302. return ExprError();
  10303. E = Result.get();
  10304. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10305. // If va_list is a record type and we are compiling in C++ mode,
  10306. // check the argument using reference binding.
  10307. InitializedEntity Entity
  10308. = InitializedEntity::InitializeParameter(Context,
  10309. Context.getLValueReferenceType(VaListType), false);
  10310. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10311. if (Init.isInvalid())
  10312. return ExprError();
  10313. E = Init.getAs<Expr>();
  10314. } else {
  10315. // Otherwise, the va_list argument must be an l-value because
  10316. // it is modified by va_arg.
  10317. if (!E->isTypeDependent() &&
  10318. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10319. return ExprError();
  10320. }
  10321. if (!E->isTypeDependent() &&
  10322. !Context.hasSameType(VaListType, E->getType())) {
  10323. return ExprError(Diag(E->getLocStart(),
  10324. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10325. << OrigExpr->getType() << E->getSourceRange());
  10326. }
  10327. if (!TInfo->getType()->isDependentType()) {
  10328. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10329. diag::err_second_parameter_to_va_arg_incomplete,
  10330. TInfo->getTypeLoc()))
  10331. return ExprError();
  10332. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10333. TInfo->getType(),
  10334. diag::err_second_parameter_to_va_arg_abstract,
  10335. TInfo->getTypeLoc()))
  10336. return ExprError();
  10337. if (!TInfo->getType().isPODType(Context)) {
  10338. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10339. TInfo->getType()->isObjCLifetimeType()
  10340. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10341. : diag::warn_second_parameter_to_va_arg_not_pod)
  10342. << TInfo->getType()
  10343. << TInfo->getTypeLoc().getSourceRange();
  10344. }
  10345. // Check for va_arg where arguments of the given type will be promoted
  10346. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10347. QualType PromoteType;
  10348. if (TInfo->getType()->isPromotableIntegerType()) {
  10349. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10350. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10351. PromoteType = QualType();
  10352. }
  10353. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10354. PromoteType = Context.DoubleTy;
  10355. if (!PromoteType.isNull())
  10356. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10357. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10358. << TInfo->getType()
  10359. << PromoteType
  10360. << TInfo->getTypeLoc().getSourceRange());
  10361. }
  10362. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10363. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  10364. }
  10365. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10366. // The type of __null will be int or long, depending on the size of
  10367. // pointers on the target.
  10368. QualType Ty;
  10369. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10370. if (pw == Context.getTargetInfo().getIntWidth())
  10371. Ty = Context.IntTy;
  10372. else if (pw == Context.getTargetInfo().getLongWidth())
  10373. Ty = Context.LongTy;
  10374. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10375. Ty = Context.LongLongTy;
  10376. else {
  10377. llvm_unreachable("I don't know size of pointer!");
  10378. }
  10379. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10380. }
  10381. bool
  10382. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10383. if (!getLangOpts().ObjC1)
  10384. return false;
  10385. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10386. if (!PT)
  10387. return false;
  10388. if (!PT->isObjCIdType()) {
  10389. // Check if the destination is the 'NSString' interface.
  10390. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10391. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10392. return false;
  10393. }
  10394. // Ignore any parens, implicit casts (should only be
  10395. // array-to-pointer decays), and not-so-opaque values. The last is
  10396. // important for making this trigger for property assignments.
  10397. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10398. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10399. if (OV->getSourceExpr())
  10400. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10401. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10402. if (!SL || !SL->isAscii())
  10403. return false;
  10404. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10405. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10406. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10407. return true;
  10408. }
  10409. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10410. SourceLocation Loc,
  10411. QualType DstType, QualType SrcType,
  10412. Expr *SrcExpr, AssignmentAction Action,
  10413. bool *Complained) {
  10414. if (Complained)
  10415. *Complained = false;
  10416. // Decode the result (notice that AST's are still created for extensions).
  10417. bool CheckInferredResultType = false;
  10418. bool isInvalid = false;
  10419. unsigned DiagKind = 0;
  10420. FixItHint Hint;
  10421. ConversionFixItGenerator ConvHints;
  10422. bool MayHaveConvFixit = false;
  10423. bool MayHaveFunctionDiff = false;
  10424. const ObjCInterfaceDecl *IFace = nullptr;
  10425. const ObjCProtocolDecl *PDecl = nullptr;
  10426. // HLSL Change Starts
  10427. if (LangOpts.HLSL) {
  10428. hlsl::DiagnoseAssignmentResultForHLSL(this, ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  10429. }
  10430. // HLSL Change Ends
  10431. switch (ConvTy) {
  10432. case Compatible:
  10433. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10434. return false;
  10435. case PointerToInt:
  10436. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10437. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10438. MayHaveConvFixit = true;
  10439. break;
  10440. case IntToPointer:
  10441. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10442. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10443. MayHaveConvFixit = true;
  10444. break;
  10445. case IncompatiblePointer:
  10446. DiagKind =
  10447. (Action == AA_Passing_CFAudited ?
  10448. diag::err_arc_typecheck_convert_incompatible_pointer :
  10449. diag::ext_typecheck_convert_incompatible_pointer);
  10450. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10451. SrcType->isObjCObjectPointerType();
  10452. if (Hint.isNull() && !CheckInferredResultType) {
  10453. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10454. }
  10455. else if (CheckInferredResultType) {
  10456. SrcType = SrcType.getUnqualifiedType();
  10457. DstType = DstType.getUnqualifiedType();
  10458. }
  10459. MayHaveConvFixit = true;
  10460. break;
  10461. case IncompatiblePointerSign:
  10462. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10463. break;
  10464. case FunctionVoidPointer:
  10465. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10466. break;
  10467. case IncompatiblePointerDiscardsQualifiers: {
  10468. // Perform array-to-pointer decay if necessary.
  10469. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10470. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10471. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10472. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10473. DiagKind = diag::err_typecheck_incompatible_address_space;
  10474. break;
  10475. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10476. DiagKind = diag::err_typecheck_incompatible_ownership;
  10477. break;
  10478. }
  10479. llvm_unreachable("unknown error case for discarding qualifiers!");
  10480. // fallthrough
  10481. }
  10482. case CompatiblePointerDiscardsQualifiers:
  10483. // If the qualifiers lost were because we were applying the
  10484. // (deprecated) C++ conversion from a string literal to a char*
  10485. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10486. // Ideally, this check would be performed in
  10487. // checkPointerTypesForAssignment. However, that would require a
  10488. // bit of refactoring (so that the second argument is an
  10489. // expression, rather than a type), which should be done as part
  10490. // of a larger effort to fix checkPointerTypesForAssignment for
  10491. // C++ semantics.
  10492. if (getLangOpts().CPlusPlus &&
  10493. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10494. return false;
  10495. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10496. break;
  10497. case IncompatibleNestedPointerQualifiers:
  10498. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10499. break;
  10500. case IntToBlockPointer:
  10501. DiagKind = diag::err_int_to_block_pointer;
  10502. break;
  10503. case IncompatibleBlockPointer:
  10504. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10505. break;
  10506. case IncompatibleObjCQualifiedId: {
  10507. if (SrcType->isObjCQualifiedIdType()) {
  10508. const ObjCObjectPointerType *srcOPT =
  10509. SrcType->getAs<ObjCObjectPointerType>();
  10510. for (auto *srcProto : srcOPT->quals()) {
  10511. PDecl = srcProto;
  10512. break;
  10513. }
  10514. if (const ObjCInterfaceType *IFaceT =
  10515. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10516. IFace = IFaceT->getDecl();
  10517. }
  10518. else if (DstType->isObjCQualifiedIdType()) {
  10519. const ObjCObjectPointerType *dstOPT =
  10520. DstType->getAs<ObjCObjectPointerType>();
  10521. for (auto *dstProto : dstOPT->quals()) {
  10522. PDecl = dstProto;
  10523. break;
  10524. }
  10525. if (const ObjCInterfaceType *IFaceT =
  10526. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10527. IFace = IFaceT->getDecl();
  10528. }
  10529. DiagKind = diag::warn_incompatible_qualified_id;
  10530. break;
  10531. }
  10532. case IncompatibleVectors:
  10533. DiagKind = diag::warn_incompatible_vectors;
  10534. break;
  10535. case IncompatibleObjCWeakRef:
  10536. DiagKind = diag::err_arc_weak_unavailable_assign;
  10537. break;
  10538. case Incompatible:
  10539. DiagKind = diag::err_typecheck_convert_incompatible;
  10540. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10541. MayHaveConvFixit = true;
  10542. isInvalid = true;
  10543. MayHaveFunctionDiff = true;
  10544. break;
  10545. }
  10546. QualType FirstType, SecondType;
  10547. switch (Action) {
  10548. case AA_Assigning:
  10549. case AA_Initializing:
  10550. // The destination type comes first.
  10551. FirstType = DstType;
  10552. SecondType = SrcType;
  10553. break;
  10554. case AA_Returning:
  10555. case AA_Passing:
  10556. case AA_Passing_CFAudited:
  10557. case AA_Converting:
  10558. case AA_Sending:
  10559. case AA_Casting:
  10560. // The source type comes first.
  10561. FirstType = SrcType;
  10562. SecondType = DstType;
  10563. break;
  10564. }
  10565. PartialDiagnostic FDiag = PDiag(DiagKind);
  10566. if (Action == AA_Passing_CFAudited)
  10567. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10568. else
  10569. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10570. // If we can fix the conversion, suggest the FixIts.
  10571. assert(ConvHints.isNull() || Hint.isNull());
  10572. if (!ConvHints.isNull()) {
  10573. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10574. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10575. FDiag << *HI;
  10576. } else {
  10577. FDiag << Hint;
  10578. }
  10579. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10580. if (MayHaveFunctionDiff)
  10581. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10582. Diag(Loc, FDiag);
  10583. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10584. PDecl && IFace && !IFace->hasDefinition())
  10585. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10586. << IFace->getName() << PDecl->getName();
  10587. if (SecondType == Context.OverloadTy)
  10588. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10589. FirstType);
  10590. if (CheckInferredResultType)
  10591. EmitRelatedResultTypeNote(SrcExpr);
  10592. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10593. EmitRelatedResultTypeNoteForReturn(DstType);
  10594. if (Complained)
  10595. *Complained = true;
  10596. return isInvalid;
  10597. }
  10598. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10599. llvm::APSInt *Result) {
  10600. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10601. public:
  10602. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10603. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10604. }
  10605. } Diagnoser;
  10606. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10607. }
  10608. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10609. llvm::APSInt *Result,
  10610. unsigned DiagID,
  10611. bool AllowFold) {
  10612. class IDDiagnoser : public VerifyICEDiagnoser {
  10613. unsigned DiagID;
  10614. public:
  10615. IDDiagnoser(unsigned DiagID)
  10616. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10617. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10618. S.Diag(Loc, DiagID) << SR;
  10619. }
  10620. } Diagnoser(DiagID);
  10621. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10622. }
  10623. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10624. SourceRange SR) {
  10625. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10626. }
  10627. ExprResult
  10628. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10629. VerifyICEDiagnoser &Diagnoser,
  10630. bool AllowFold) {
  10631. SourceLocation DiagLoc = E->getLocStart();
  10632. if (getLangOpts().CPlusPlus11) {
  10633. // C++11 [expr.const]p5:
  10634. // If an expression of literal class type is used in a context where an
  10635. // integral constant expression is required, then that class type shall
  10636. // have a single non-explicit conversion function to an integral or
  10637. // unscoped enumeration type
  10638. ExprResult Converted;
  10639. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10640. public:
  10641. CXX11ConvertDiagnoser(bool Silent)
  10642. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10643. Silent, true) {}
  10644. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10645. QualType T) override {
  10646. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10647. }
  10648. SemaDiagnosticBuilder diagnoseIncomplete(
  10649. Sema &S, SourceLocation Loc, QualType T) override {
  10650. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10651. }
  10652. SemaDiagnosticBuilder diagnoseExplicitConv(
  10653. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10654. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10655. }
  10656. SemaDiagnosticBuilder noteExplicitConv(
  10657. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10658. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10659. << ConvTy->isEnumeralType() << ConvTy;
  10660. }
  10661. SemaDiagnosticBuilder diagnoseAmbiguous(
  10662. Sema &S, SourceLocation Loc, QualType T) override {
  10663. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10664. }
  10665. SemaDiagnosticBuilder noteAmbiguous(
  10666. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10667. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10668. << ConvTy->isEnumeralType() << ConvTy;
  10669. }
  10670. SemaDiagnosticBuilder diagnoseConversion(
  10671. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10672. llvm_unreachable("conversion functions are permitted");
  10673. }
  10674. } ConvertDiagnoser(Diagnoser.Suppress);
  10675. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10676. ConvertDiagnoser);
  10677. if (Converted.isInvalid())
  10678. return Converted;
  10679. E = Converted.get();
  10680. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10681. return ExprError();
  10682. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10683. // An ICE must be of integral or unscoped enumeration type.
  10684. if (!Diagnoser.Suppress)
  10685. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10686. return ExprError();
  10687. }
  10688. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10689. // in the non-ICE case.
  10690. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10691. if (Result)
  10692. *Result = E->EvaluateKnownConstInt(Context);
  10693. return E;
  10694. }
  10695. Expr::EvalResult EvalResult;
  10696. SmallVector<PartialDiagnosticAt, 8> Notes;
  10697. EvalResult.Diag = &Notes;
  10698. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10699. // not a constant expression as a side-effect.
  10700. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10701. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10702. // In C++11, we can rely on diagnostics being produced for any expression
  10703. // which is not a constant expression. If no diagnostics were produced, then
  10704. // this is a constant expression.
  10705. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10706. if (Result)
  10707. *Result = EvalResult.Val.getInt();
  10708. return E;
  10709. }
  10710. // If our only note is the usual "invalid subexpression" note, just point
  10711. // the caret at its location rather than producing an essentially
  10712. // redundant note.
  10713. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10714. diag::note_invalid_subexpr_in_const_expr) {
  10715. DiagLoc = Notes[0].first;
  10716. Notes.clear();
  10717. }
  10718. if (!Folded || !AllowFold) {
  10719. if (!Diagnoser.Suppress) {
  10720. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10721. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10722. Diag(Notes[I].first, Notes[I].second);
  10723. }
  10724. return ExprError();
  10725. }
  10726. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10727. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10728. Diag(Notes[I].first, Notes[I].second);
  10729. if (Result)
  10730. *Result = EvalResult.Val.getInt();
  10731. return E;
  10732. }
  10733. namespace {
  10734. // Handle the case where we conclude a expression which we speculatively
  10735. // considered to be unevaluated is actually evaluated.
  10736. class TransformToPE : public TreeTransform<TransformToPE> {
  10737. typedef TreeTransform<TransformToPE> BaseTransform;
  10738. public:
  10739. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10740. // Make sure we redo semantic analysis
  10741. bool AlwaysRebuild() { return true; }
  10742. // Make sure we handle LabelStmts correctly.
  10743. // FIXME: This does the right thing, but maybe we need a more general
  10744. // fix to TreeTransform?
  10745. StmtResult TransformLabelStmt(LabelStmt *S) {
  10746. S->getDecl()->setStmt(nullptr);
  10747. return BaseTransform::TransformLabelStmt(S);
  10748. }
  10749. // We need to special-case DeclRefExprs referring to FieldDecls which
  10750. // are not part of a member pointer formation; normal TreeTransforming
  10751. // doesn't catch this case because of the way we represent them in the AST.
  10752. // FIXME: This is a bit ugly; is it really the best way to handle this
  10753. // case?
  10754. //
  10755. // Error on DeclRefExprs referring to FieldDecls.
  10756. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10757. if (isa<FieldDecl>(E->getDecl()) &&
  10758. !SemaRef.isUnevaluatedContext())
  10759. return SemaRef.Diag(E->getLocation(),
  10760. diag::err_invalid_non_static_member_use)
  10761. << E->getDecl() << E->getSourceRange();
  10762. return BaseTransform::TransformDeclRefExpr(E);
  10763. }
  10764. // Exception: filter out member pointer formation
  10765. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10766. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10767. return E;
  10768. return BaseTransform::TransformUnaryOperator(E);
  10769. }
  10770. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10771. // Lambdas never need to be transformed.
  10772. return E;
  10773. }
  10774. };
  10775. }
  10776. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10777. assert(isUnevaluatedContext() &&
  10778. "Should only transform unevaluated expressions");
  10779. ExprEvalContexts.back().Context =
  10780. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10781. if (isUnevaluatedContext())
  10782. return E;
  10783. return TransformToPE(*this).TransformExpr(E);
  10784. }
  10785. void
  10786. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10787. Decl *LambdaContextDecl,
  10788. bool IsDecltype) {
  10789. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10790. ExprNeedsCleanups, LambdaContextDecl,
  10791. IsDecltype);
  10792. ExprNeedsCleanups = false;
  10793. if (!MaybeODRUseExprs.empty())
  10794. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10795. }
  10796. void
  10797. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10798. ReuseLambdaContextDecl_t,
  10799. bool IsDecltype) {
  10800. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10801. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10802. }
  10803. void Sema::PopExpressionEvaluationContext() {
  10804. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10805. unsigned NumTypos = Rec.NumTypos;
  10806. if (!Rec.Lambdas.empty()) {
  10807. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10808. unsigned D;
  10809. if (Rec.isUnevaluated()) {
  10810. // C++11 [expr.prim.lambda]p2:
  10811. // A lambda-expression shall not appear in an unevaluated operand
  10812. // (Clause 5).
  10813. D = diag::err_lambda_unevaluated_operand;
  10814. } else {
  10815. // C++1y [expr.const]p2:
  10816. // A conditional-expression e is a core constant expression unless the
  10817. // evaluation of e, following the rules of the abstract machine, would
  10818. // evaluate [...] a lambda-expression.
  10819. D = diag::err_lambda_in_constant_expression;
  10820. }
  10821. for (const auto *L : Rec.Lambdas)
  10822. Diag(L->getLocStart(), D);
  10823. } else {
  10824. // Mark the capture expressions odr-used. This was deferred
  10825. // during lambda expression creation.
  10826. for (auto *Lambda : Rec.Lambdas) {
  10827. for (auto *C : Lambda->capture_inits())
  10828. MarkDeclarationsReferencedInExpr(C);
  10829. }
  10830. }
  10831. }
  10832. // When are coming out of an unevaluated context, clear out any
  10833. // temporaries that we may have created as part of the evaluation of
  10834. // the expression in that context: they aren't relevant because they
  10835. // will never be constructed.
  10836. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10837. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10838. ExprCleanupObjects.end());
  10839. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10840. CleanupVarDeclMarking();
  10841. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10842. // Otherwise, merge the contexts together.
  10843. } else {
  10844. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10845. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10846. Rec.SavedMaybeODRUseExprs.end());
  10847. }
  10848. // Pop the current expression evaluation context off the stack.
  10849. ExprEvalContexts.pop_back();
  10850. if (!ExprEvalContexts.empty())
  10851. ExprEvalContexts.back().NumTypos += NumTypos;
  10852. else
  10853. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10854. "last ExpressionEvaluationContextRecord");
  10855. }
  10856. void Sema::DiscardCleanupsInEvaluationContext() {
  10857. ExprCleanupObjects.erase(
  10858. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10859. ExprCleanupObjects.end());
  10860. ExprNeedsCleanups = false;
  10861. MaybeODRUseExprs.clear();
  10862. }
  10863. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10864. if (!E->getType()->isVariablyModifiedType())
  10865. return E;
  10866. return TransformToPotentiallyEvaluated(E);
  10867. }
  10868. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10869. // Do not mark anything as "used" within a dependent context; wait for
  10870. // an instantiation.
  10871. if (SemaRef.CurContext->isDependentContext())
  10872. return false;
  10873. switch (SemaRef.ExprEvalContexts.back().Context) {
  10874. case Sema::Unevaluated:
  10875. case Sema::UnevaluatedAbstract:
  10876. // We are in an expression that is not potentially evaluated; do nothing.
  10877. // (Depending on how you read the standard, we actually do need to do
  10878. // something here for null pointer constants, but the standard's
  10879. // definition of a null pointer constant is completely crazy.)
  10880. return false;
  10881. case Sema::ConstantEvaluated:
  10882. case Sema::PotentiallyEvaluated:
  10883. // We are in a potentially evaluated expression (or a constant-expression
  10884. // in C++03); we need to do implicit template instantiation, implicitly
  10885. // define class members, and mark most declarations as used.
  10886. return true;
  10887. case Sema::PotentiallyEvaluatedIfUsed:
  10888. // Referenced declarations will only be used if the construct in the
  10889. // containing expression is used.
  10890. return false;
  10891. }
  10892. llvm_unreachable("Invalid context");
  10893. }
  10894. /// \brief Mark a function referenced, and check whether it is odr-used
  10895. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10896. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10897. bool OdrUse) {
  10898. assert(Func && "No function?");
  10899. Func->setReferenced();
  10900. // C++11 [basic.def.odr]p3:
  10901. // A function whose name appears as a potentially-evaluated expression is
  10902. // odr-used if it is the unique lookup result or the selected member of a
  10903. // set of overloaded functions [...].
  10904. //
  10905. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10906. // can just check that here. Skip the rest of this function if we've already
  10907. // marked the function as used.
  10908. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10909. !IsPotentiallyEvaluatedContext(*this)) {
  10910. // C++11 [temp.inst]p3:
  10911. // Unless a function template specialization has been explicitly
  10912. // instantiated or explicitly specialized, the function template
  10913. // specialization is implicitly instantiated when the specialization is
  10914. // referenced in a context that requires a function definition to exist.
  10915. //
  10916. // We consider constexpr function templates to be referenced in a context
  10917. // that requires a definition to exist whenever they are referenced.
  10918. //
  10919. // FIXME: This instantiates constexpr functions too frequently. If this is
  10920. // really an unevaluated context (and we're not just in the definition of a
  10921. // function template or overload resolution or other cases which we
  10922. // incorrectly consider to be unevaluated contexts), and we're not in a
  10923. // subexpression which we actually need to evaluate (for instance, a
  10924. // template argument, array bound or an expression in a braced-init-list),
  10925. // we are not permitted to instantiate this constexpr function definition.
  10926. //
  10927. // FIXME: This also implicitly defines special members too frequently. They
  10928. // are only supposed to be implicitly defined if they are odr-used, but they
  10929. // are not odr-used from constant expressions in unevaluated contexts.
  10930. // However, they cannot be referenced if they are deleted, and they are
  10931. // deleted whenever the implicit definition of the special member would
  10932. // fail.
  10933. if (!Func->isConstexpr() || Func->getBody())
  10934. return;
  10935. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10936. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10937. return;
  10938. }
  10939. // Note that this declaration has been used.
  10940. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10941. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10942. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10943. if (Constructor->isDefaultConstructor()) {
  10944. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  10945. return;
  10946. DefineImplicitDefaultConstructor(Loc, Constructor);
  10947. } else if (Constructor->isCopyConstructor()) {
  10948. DefineImplicitCopyConstructor(Loc, Constructor);
  10949. } else if (Constructor->isMoveConstructor()) {
  10950. DefineImplicitMoveConstructor(Loc, Constructor);
  10951. }
  10952. } else if (Constructor->getInheritedConstructor()) {
  10953. DefineInheritingConstructor(Loc, Constructor);
  10954. }
  10955. } else if (CXXDestructorDecl *Destructor =
  10956. dyn_cast<CXXDestructorDecl>(Func)) {
  10957. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  10958. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  10959. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  10960. return;
  10961. DefineImplicitDestructor(Loc, Destructor);
  10962. }
  10963. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  10964. MarkVTableUsed(Loc, Destructor->getParent());
  10965. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  10966. if (MethodDecl->isOverloadedOperator() &&
  10967. MethodDecl->getOverloadedOperator() == OO_Equal) {
  10968. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  10969. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  10970. if (MethodDecl->isCopyAssignmentOperator())
  10971. DefineImplicitCopyAssignment(Loc, MethodDecl);
  10972. else
  10973. DefineImplicitMoveAssignment(Loc, MethodDecl);
  10974. }
  10975. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  10976. MethodDecl->getParent()->isLambda()) {
  10977. CXXConversionDecl *Conversion =
  10978. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  10979. if (Conversion->isLambdaToBlockPointerConversion())
  10980. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  10981. else
  10982. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  10983. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  10984. MarkVTableUsed(Loc, MethodDecl->getParent());
  10985. }
  10986. // Recursive functions should be marked when used from another function.
  10987. // FIXME: Is this really right?
  10988. if (CurContext == Func) return;
  10989. // Resolve the exception specification for any function which is
  10990. // used: CodeGen will need it.
  10991. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  10992. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  10993. ResolveExceptionSpec(Loc, FPT);
  10994. if (!OdrUse) return;
  10995. // Implicit instantiation of function templates and member functions of
  10996. // class templates.
  10997. if (Func->isImplicitlyInstantiable()) {
  10998. bool AlreadyInstantiated = false;
  10999. SourceLocation PointOfInstantiation = Loc;
  11000. if (FunctionTemplateSpecializationInfo *SpecInfo
  11001. = Func->getTemplateSpecializationInfo()) {
  11002. if (SpecInfo->getPointOfInstantiation().isInvalid())
  11003. SpecInfo->setPointOfInstantiation(Loc);
  11004. else if (SpecInfo->getTemplateSpecializationKind()
  11005. == TSK_ImplicitInstantiation) {
  11006. AlreadyInstantiated = true;
  11007. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  11008. }
  11009. } else if (MemberSpecializationInfo *MSInfo
  11010. = Func->getMemberSpecializationInfo()) {
  11011. if (MSInfo->getPointOfInstantiation().isInvalid())
  11012. MSInfo->setPointOfInstantiation(Loc);
  11013. else if (MSInfo->getTemplateSpecializationKind()
  11014. == TSK_ImplicitInstantiation) {
  11015. AlreadyInstantiated = true;
  11016. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  11017. }
  11018. }
  11019. if (!AlreadyInstantiated || Func->isConstexpr()) {
  11020. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  11021. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  11022. ActiveTemplateInstantiations.size())
  11023. PendingLocalImplicitInstantiations.push_back(
  11024. std::make_pair(Func, PointOfInstantiation));
  11025. else if (Func->isConstexpr())
  11026. // Do not defer instantiations of constexpr functions, to avoid the
  11027. // expression evaluator needing to call back into Sema if it sees a
  11028. // call to such a function.
  11029. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  11030. else {
  11031. PendingInstantiations.push_back(std::make_pair(Func,
  11032. PointOfInstantiation));
  11033. // Notify the consumer that a function was implicitly instantiated.
  11034. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  11035. }
  11036. }
  11037. } else {
  11038. // Walk redefinitions, as some of them may be instantiable.
  11039. for (auto i : Func->redecls()) {
  11040. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  11041. MarkFunctionReferenced(Loc, i);
  11042. }
  11043. }
  11044. // Keep track of used but undefined functions.
  11045. if (!Func->isDefined()) {
  11046. if (mightHaveNonExternalLinkage(Func))
  11047. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11048. else if (Func->getMostRecentDecl()->isInlined() &&
  11049. !LangOpts.GNUInline &&
  11050. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  11051. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11052. }
  11053. // Normally the most current decl is marked used while processing the use and
  11054. // any subsequent decls are marked used by decl merging. This fails with
  11055. // template instantiation since marking can happen at the end of the file
  11056. // and, because of the two phase lookup, this function is called with at
  11057. // decl in the middle of a decl chain. We loop to maintain the invariant
  11058. // that once a decl is used, all decls after it are also used.
  11059. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  11060. F->markUsed(Context);
  11061. if (F == Func)
  11062. break;
  11063. }
  11064. }
  11065. static void
  11066. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  11067. VarDecl *var, DeclContext *DC) {
  11068. DeclContext *VarDC = var->getDeclContext();
  11069. // If the parameter still belongs to the translation unit, then
  11070. // we're actually just using one parameter in the declaration of
  11071. // the next.
  11072. if (isa<ParmVarDecl>(var) &&
  11073. isa<TranslationUnitDecl>(VarDC))
  11074. return;
  11075. // For C code, don't diagnose about capture if we're not actually in code
  11076. // right now; it's impossible to write a non-constant expression outside of
  11077. // function context, so we'll get other (more useful) diagnostics later.
  11078. //
  11079. // For C++, things get a bit more nasty... it would be nice to suppress this
  11080. // diagnostic for certain cases like using a local variable in an array bound
  11081. // for a member of a local class, but the correct predicate is not obvious.
  11082. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  11083. return;
  11084. if (isa<CXXMethodDecl>(VarDC) &&
  11085. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  11086. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  11087. << var->getIdentifier();
  11088. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  11089. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  11090. << var->getIdentifier() << fn->getDeclName();
  11091. } else if (isa<BlockDecl>(VarDC)) {
  11092. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  11093. << var->getIdentifier();
  11094. } else {
  11095. // FIXME: Is there any other context where a local variable can be
  11096. // declared?
  11097. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  11098. << var->getIdentifier();
  11099. }
  11100. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  11101. << var->getIdentifier();
  11102. // FIXME: Add additional diagnostic info about class etc. which prevents
  11103. // capture.
  11104. }
  11105. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  11106. bool &SubCapturesAreNested,
  11107. QualType &CaptureType,
  11108. QualType &DeclRefType) {
  11109. // Check whether we've already captured it.
  11110. if (CSI->CaptureMap.count(Var)) {
  11111. // If we found a capture, any subcaptures are nested.
  11112. SubCapturesAreNested = true;
  11113. // Retrieve the capture type for this variable.
  11114. CaptureType = CSI->getCapture(Var).getCaptureType();
  11115. // Compute the type of an expression that refers to this variable.
  11116. DeclRefType = CaptureType.getNonReferenceType();
  11117. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  11118. if (Cap.isCopyCapture() &&
  11119. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  11120. DeclRefType.addConst();
  11121. return true;
  11122. }
  11123. return false;
  11124. }
  11125. // Only block literals, captured statements, and lambda expressions can
  11126. // capture; other scopes don't work.
  11127. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  11128. SourceLocation Loc,
  11129. const bool Diagnose, Sema &S) {
  11130. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  11131. return getLambdaAwareParentOfDeclContext(DC);
  11132. else if (Var->hasLocalStorage()) {
  11133. if (Diagnose)
  11134. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  11135. }
  11136. return nullptr;
  11137. }
  11138. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11139. // certain types of variables (unnamed, variably modified types etc.)
  11140. // so check for eligibility.
  11141. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  11142. SourceLocation Loc,
  11143. const bool Diagnose, Sema &S) {
  11144. bool IsBlock = isa<BlockScopeInfo>(CSI);
  11145. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  11146. // Lambdas are not allowed to capture unnamed variables
  11147. // (e.g. anonymous unions).
  11148. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  11149. // assuming that's the intent.
  11150. if (IsLambda && !Var->getDeclName()) {
  11151. if (Diagnose) {
  11152. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  11153. S.Diag(Var->getLocation(), diag::note_declared_at);
  11154. }
  11155. return false;
  11156. }
  11157. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  11158. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  11159. if (Diagnose) {
  11160. S.Diag(Loc, diag::err_ref_vm_type);
  11161. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11162. << Var->getDeclName();
  11163. }
  11164. return false;
  11165. }
  11166. // Prohibit structs with flexible array members too.
  11167. // We cannot capture what is in the tail end of the struct.
  11168. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  11169. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  11170. if (Diagnose) {
  11171. if (IsBlock)
  11172. S.Diag(Loc, diag::err_ref_flexarray_type);
  11173. else
  11174. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  11175. << Var->getDeclName();
  11176. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11177. << Var->getDeclName();
  11178. }
  11179. return false;
  11180. }
  11181. }
  11182. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11183. // Lambdas and captured statements are not allowed to capture __block
  11184. // variables; they don't support the expected semantics.
  11185. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  11186. if (Diagnose) {
  11187. S.Diag(Loc, diag::err_capture_block_variable)
  11188. << Var->getDeclName() << !IsLambda;
  11189. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11190. << Var->getDeclName();
  11191. }
  11192. return false;
  11193. }
  11194. return true;
  11195. }
  11196. // Returns true if the capture by block was successful.
  11197. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  11198. SourceLocation Loc,
  11199. const bool BuildAndDiagnose,
  11200. QualType &CaptureType,
  11201. QualType &DeclRefType,
  11202. const bool Nested,
  11203. Sema &S) {
  11204. Expr *CopyExpr = nullptr;
  11205. bool ByRef = false;
  11206. // Blocks are not allowed to capture arrays.
  11207. if (CaptureType->isArrayType()) {
  11208. if (BuildAndDiagnose) {
  11209. S.Diag(Loc, diag::err_ref_array_type);
  11210. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11211. << Var->getDeclName();
  11212. }
  11213. return false;
  11214. }
  11215. // Forbid the block-capture of autoreleasing variables.
  11216. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11217. if (BuildAndDiagnose) {
  11218. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11219. << /*block*/ 0;
  11220. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11221. << Var->getDeclName();
  11222. }
  11223. return false;
  11224. }
  11225. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11226. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11227. // Block capture by reference does not change the capture or
  11228. // declaration reference types.
  11229. ByRef = true;
  11230. } else {
  11231. // Block capture by copy introduces 'const'.
  11232. CaptureType = CaptureType.getNonReferenceType().withConst();
  11233. DeclRefType = CaptureType;
  11234. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11235. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11236. // The capture logic needs the destructor, so make sure we mark it.
  11237. // Usually this is unnecessary because most local variables have
  11238. // their destructors marked at declaration time, but parameters are
  11239. // an exception because it's technically only the call site that
  11240. // actually requires the destructor.
  11241. if (isa<ParmVarDecl>(Var))
  11242. S.FinalizeVarWithDestructor(Var, Record);
  11243. // Enter a new evaluation context to insulate the copy
  11244. // full-expression.
  11245. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11246. // According to the blocks spec, the capture of a variable from
  11247. // the stack requires a const copy constructor. This is not true
  11248. // of the copy/move done to move a __block variable to the heap.
  11249. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11250. DeclRefType.withConst(),
  11251. VK_LValue, Loc);
  11252. ExprResult Result
  11253. = S.PerformCopyInitialization(
  11254. InitializedEntity::InitializeBlock(Var->getLocation(),
  11255. CaptureType, false),
  11256. Loc, DeclRef);
  11257. // Build a full-expression copy expression if initialization
  11258. // succeeded and used a non-trivial constructor. Recover from
  11259. // errors by pretending that the copy isn't necessary.
  11260. if (!Result.isInvalid() &&
  11261. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11262. ->isTrivial()) {
  11263. Result = S.MaybeCreateExprWithCleanups(Result);
  11264. CopyExpr = Result.get();
  11265. }
  11266. }
  11267. }
  11268. }
  11269. // Actually capture the variable.
  11270. if (BuildAndDiagnose)
  11271. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11272. SourceLocation(), CaptureType, CopyExpr);
  11273. return true;
  11274. }
  11275. /// \brief Capture the given variable in the captured region.
  11276. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11277. VarDecl *Var,
  11278. SourceLocation Loc,
  11279. const bool BuildAndDiagnose,
  11280. QualType &CaptureType,
  11281. QualType &DeclRefType,
  11282. const bool RefersToCapturedVariable,
  11283. Sema &S) {
  11284. // By default, capture variables by reference.
  11285. bool ByRef = true;
  11286. // Using an LValue reference type is consistent with Lambdas (see below).
  11287. if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
  11288. DeclRefType = DeclRefType.getUnqualifiedType();
  11289. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11290. Expr *CopyExpr = nullptr;
  11291. if (BuildAndDiagnose) {
  11292. // The current implementation assumes that all variables are captured
  11293. // by references. Since there is no capture by copy, no expression
  11294. // evaluation will be needed.
  11295. RecordDecl *RD = RSI->TheRecordDecl;
  11296. FieldDecl *Field
  11297. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11298. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11299. nullptr, false, ICIS_NoInit);
  11300. Field->setImplicit(true);
  11301. Field->setAccess(AS_private);
  11302. RD->addDecl(Field);
  11303. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11304. DeclRefType, VK_LValue, Loc);
  11305. Var->setReferenced(true);
  11306. Var->markUsed(S.Context);
  11307. }
  11308. // Actually capture the variable.
  11309. if (BuildAndDiagnose)
  11310. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11311. SourceLocation(), CaptureType, CopyExpr);
  11312. return true;
  11313. }
  11314. /// \brief Create a field within the lambda class for the variable
  11315. /// being captured.
  11316. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11317. QualType FieldType, QualType DeclRefType,
  11318. SourceLocation Loc,
  11319. bool RefersToCapturedVariable) {
  11320. CXXRecordDecl *Lambda = LSI->Lambda;
  11321. // Build the non-static data member.
  11322. FieldDecl *Field
  11323. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11324. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11325. nullptr, false, ICIS_NoInit);
  11326. Field->setImplicit(true);
  11327. Field->setAccess(AS_private);
  11328. Lambda->addDecl(Field);
  11329. }
  11330. /// \brief Capture the given variable in the lambda.
  11331. static bool captureInLambda(LambdaScopeInfo *LSI,
  11332. VarDecl *Var,
  11333. SourceLocation Loc,
  11334. const bool BuildAndDiagnose,
  11335. QualType &CaptureType,
  11336. QualType &DeclRefType,
  11337. const bool RefersToCapturedVariable,
  11338. const Sema::TryCaptureKind Kind,
  11339. SourceLocation EllipsisLoc,
  11340. const bool IsTopScope,
  11341. Sema &S) {
  11342. // Determine whether we are capturing by reference or by value.
  11343. bool ByRef = false;
  11344. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11345. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11346. } else {
  11347. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11348. }
  11349. // Compute the type of the field that will capture this variable.
  11350. if (ByRef) {
  11351. // C++11 [expr.prim.lambda]p15:
  11352. // An entity is captured by reference if it is implicitly or
  11353. // explicitly captured but not captured by copy. It is
  11354. // unspecified whether additional unnamed non-static data
  11355. // members are declared in the closure type for entities
  11356. // captured by reference.
  11357. //
  11358. // FIXME: It is not clear whether we want to build an lvalue reference
  11359. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11360. // to do the former, while EDG does the latter. Core issue 1249 will
  11361. // clarify, but for now we follow GCC because it's a more permissive and
  11362. // easily defensible position.
  11363. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11364. } else {
  11365. // C++11 [expr.prim.lambda]p14:
  11366. // For each entity captured by copy, an unnamed non-static
  11367. // data member is declared in the closure type. The
  11368. // declaration order of these members is unspecified. The type
  11369. // of such a data member is the type of the corresponding
  11370. // captured entity if the entity is not a reference to an
  11371. // object, or the referenced type otherwise. [Note: If the
  11372. // captured entity is a reference to a function, the
  11373. // corresponding data member is also a reference to a
  11374. // function. - end note ]
  11375. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11376. if (!RefType->getPointeeType()->isFunctionType())
  11377. CaptureType = RefType->getPointeeType();
  11378. }
  11379. // Forbid the lambda copy-capture of autoreleasing variables.
  11380. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11381. if (BuildAndDiagnose) {
  11382. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11383. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11384. << Var->getDeclName();
  11385. }
  11386. return false;
  11387. }
  11388. // Make sure that by-copy captures are of a complete and non-abstract type.
  11389. if (BuildAndDiagnose) {
  11390. if (!CaptureType->isDependentType() &&
  11391. S.RequireCompleteType(Loc, CaptureType,
  11392. diag::err_capture_of_incomplete_type,
  11393. Var->getDeclName()))
  11394. return false;
  11395. if (S.RequireNonAbstractType(Loc, CaptureType,
  11396. diag::err_capture_of_abstract_type))
  11397. return false;
  11398. }
  11399. }
  11400. // Capture this variable in the lambda.
  11401. if (BuildAndDiagnose)
  11402. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11403. RefersToCapturedVariable);
  11404. // Compute the type of a reference to this captured variable.
  11405. if (ByRef)
  11406. DeclRefType = CaptureType.getNonReferenceType();
  11407. else {
  11408. // C++ [expr.prim.lambda]p5:
  11409. // The closure type for a lambda-expression has a public inline
  11410. // function call operator [...]. This function call operator is
  11411. // declared const (9.3.1) if and only if the lambda-expression’s
  11412. // parameter-declaration-clause is not followed by mutable.
  11413. DeclRefType = CaptureType.getNonReferenceType();
  11414. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11415. DeclRefType.addConst();
  11416. }
  11417. // Add the capture.
  11418. if (BuildAndDiagnose)
  11419. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11420. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11421. return true;
  11422. }
  11423. bool Sema::tryCaptureVariable(
  11424. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11425. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11426. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11427. // An init-capture is notionally from the context surrounding its
  11428. // declaration, but its parent DC is the lambda class.
  11429. DeclContext *VarDC = Var->getDeclContext();
  11430. if (Var->isInitCapture())
  11431. VarDC = VarDC->getParent();
  11432. DeclContext *DC = CurContext;
  11433. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11434. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11435. // We need to sync up the Declaration Context with the
  11436. // FunctionScopeIndexToStopAt
  11437. if (FunctionScopeIndexToStopAt) {
  11438. unsigned FSIndex = FunctionScopes.size() - 1;
  11439. while (FSIndex != MaxFunctionScopesIndex) {
  11440. DC = getLambdaAwareParentOfDeclContext(DC);
  11441. --FSIndex;
  11442. }
  11443. }
  11444. // If the variable is declared in the current context, there is no need to
  11445. // capture it.
  11446. if (VarDC == DC) return true;
  11447. // Capture global variables if it is required to use private copy of this
  11448. // variable.
  11449. bool IsGlobal = !Var->hasLocalStorage();
  11450. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11451. return true;
  11452. // Walk up the stack to determine whether we can capture the variable,
  11453. // performing the "simple" checks that don't depend on type. We stop when
  11454. // we've either hit the declared scope of the variable or find an existing
  11455. // capture of that variable. We start from the innermost capturing-entity
  11456. // (the DC) and ensure that all intervening capturing-entities
  11457. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11458. // declcontext can either capture the variable or have already captured
  11459. // the variable.
  11460. CaptureType = Var->getType();
  11461. DeclRefType = CaptureType.getNonReferenceType();
  11462. bool Nested = false;
  11463. bool Explicit = (Kind != TryCapture_Implicit);
  11464. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11465. unsigned OpenMPLevel = 0;
  11466. do {
  11467. // Only block literals, captured statements, and lambda expressions can
  11468. // capture; other scopes don't work.
  11469. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11470. ExprLoc,
  11471. BuildAndDiagnose,
  11472. *this);
  11473. // We need to check for the parent *first* because, if we *have*
  11474. // private-captured a global variable, we need to recursively capture it in
  11475. // intermediate blocks, lambdas, etc.
  11476. if (!ParentDC) {
  11477. if (IsGlobal) {
  11478. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11479. break;
  11480. }
  11481. return true;
  11482. }
  11483. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11484. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11485. // Check whether we've already captured it.
  11486. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11487. DeclRefType))
  11488. break;
  11489. if (getLangOpts().OpenMP) {
  11490. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11491. // OpenMP private variables should not be captured in outer scope, so
  11492. // just break here.
  11493. if (RSI->CapRegionKind == CR_OpenMP) {
  11494. if (isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11495. Nested = true;
  11496. DeclRefType = DeclRefType.getUnqualifiedType();
  11497. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11498. break;
  11499. }
  11500. ++OpenMPLevel;
  11501. }
  11502. }
  11503. }
  11504. // If we are instantiating a generic lambda call operator body,
  11505. // we do not want to capture new variables. What was captured
  11506. // during either a lambdas transformation or initial parsing
  11507. // should be used.
  11508. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11509. if (BuildAndDiagnose) {
  11510. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11511. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11512. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11513. Diag(Var->getLocation(), diag::note_previous_decl)
  11514. << Var->getDeclName();
  11515. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11516. } else
  11517. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11518. }
  11519. return true;
  11520. }
  11521. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11522. // certain types of variables (unnamed, variably modified types etc.)
  11523. // so check for eligibility.
  11524. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11525. return true;
  11526. // Try to capture variable-length arrays types.
  11527. if (Var->getType()->isVariablyModifiedType()) {
  11528. // We're going to walk down into the type and look for VLA
  11529. // expressions.
  11530. QualType QTy = Var->getType();
  11531. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11532. QTy = PVD->getOriginalType();
  11533. do {
  11534. const Type *Ty = QTy.getTypePtr();
  11535. switch (Ty->getTypeClass()) {
  11536. #define TYPE(Class, Base)
  11537. #define ABSTRACT_TYPE(Class, Base)
  11538. #define NON_CANONICAL_TYPE(Class, Base)
  11539. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11540. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11541. #include "clang/AST/TypeNodes.def"
  11542. QTy = QualType();
  11543. break;
  11544. // These types are never variably-modified.
  11545. case Type::Builtin:
  11546. case Type::Complex:
  11547. case Type::Vector:
  11548. case Type::ExtVector:
  11549. case Type::Record:
  11550. case Type::Enum:
  11551. case Type::Elaborated:
  11552. case Type::TemplateSpecialization:
  11553. case Type::ObjCObject:
  11554. case Type::ObjCInterface:
  11555. case Type::ObjCObjectPointer:
  11556. llvm_unreachable("type class is never variably-modified!");
  11557. case Type::Adjusted:
  11558. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11559. break;
  11560. case Type::Decayed:
  11561. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11562. break;
  11563. case Type::Pointer:
  11564. QTy = cast<PointerType>(Ty)->getPointeeType();
  11565. break;
  11566. case Type::BlockPointer:
  11567. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11568. break;
  11569. case Type::LValueReference:
  11570. case Type::RValueReference:
  11571. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11572. break;
  11573. case Type::MemberPointer:
  11574. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11575. break;
  11576. case Type::ConstantArray:
  11577. case Type::IncompleteArray:
  11578. // Losing element qualification here is fine.
  11579. QTy = cast<ArrayType>(Ty)->getElementType();
  11580. break;
  11581. case Type::VariableArray: {
  11582. // Losing element qualification here is fine.
  11583. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11584. // Unknown size indication requires no size computation.
  11585. // Otherwise, evaluate and record it.
  11586. if (auto Size = VAT->getSizeExpr()) {
  11587. if (!CSI->isVLATypeCaptured(VAT)) {
  11588. RecordDecl *CapRecord = nullptr;
  11589. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11590. CapRecord = LSI->Lambda;
  11591. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11592. CapRecord = CRSI->TheRecordDecl;
  11593. }
  11594. if (CapRecord) {
  11595. auto ExprLoc = Size->getExprLoc();
  11596. auto SizeType = Context.getSizeType();
  11597. // Build the non-static data member.
  11598. auto Field = FieldDecl::Create(
  11599. Context, CapRecord, ExprLoc, ExprLoc,
  11600. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11601. /*BW*/ nullptr, /*Mutable*/ false,
  11602. /*InitStyle*/ ICIS_NoInit);
  11603. Field->setImplicit(true);
  11604. Field->setAccess(AS_private);
  11605. Field->setCapturedVLAType(VAT);
  11606. CapRecord->addDecl(Field);
  11607. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11608. }
  11609. }
  11610. }
  11611. QTy = VAT->getElementType();
  11612. break;
  11613. }
  11614. case Type::FunctionProto:
  11615. case Type::FunctionNoProto:
  11616. QTy = cast<FunctionType>(Ty)->getReturnType();
  11617. break;
  11618. case Type::Paren:
  11619. case Type::TypeOf:
  11620. case Type::UnaryTransform:
  11621. case Type::Attributed:
  11622. case Type::SubstTemplateTypeParm:
  11623. case Type::PackExpansion:
  11624. // Keep walking after single level desugaring.
  11625. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11626. break;
  11627. case Type::Typedef:
  11628. QTy = cast<TypedefType>(Ty)->desugar();
  11629. break;
  11630. case Type::Decltype:
  11631. QTy = cast<DecltypeType>(Ty)->desugar();
  11632. break;
  11633. case Type::Auto:
  11634. QTy = cast<AutoType>(Ty)->getDeducedType();
  11635. break;
  11636. case Type::TypeOfExpr:
  11637. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11638. break;
  11639. case Type::Atomic:
  11640. QTy = cast<AtomicType>(Ty)->getValueType();
  11641. break;
  11642. }
  11643. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11644. }
  11645. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11646. // No capture-default, and this is not an explicit capture
  11647. // so cannot capture this variable.
  11648. if (BuildAndDiagnose) {
  11649. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11650. Diag(Var->getLocation(), diag::note_previous_decl)
  11651. << Var->getDeclName();
  11652. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11653. diag::note_lambda_decl);
  11654. // FIXME: If we error out because an outer lambda can not implicitly
  11655. // capture a variable that an inner lambda explicitly captures, we
  11656. // should have the inner lambda do the explicit capture - because
  11657. // it makes for cleaner diagnostics later. This would purely be done
  11658. // so that the diagnostic does not misleadingly claim that a variable
  11659. // can not be captured by a lambda implicitly even though it is captured
  11660. // explicitly. Suggestion:
  11661. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11662. // at the function head
  11663. // - cache the StartingDeclContext - this must be a lambda
  11664. // - captureInLambda in the innermost lambda the variable.
  11665. }
  11666. return true;
  11667. }
  11668. FunctionScopesIndex--;
  11669. DC = ParentDC;
  11670. Explicit = false;
  11671. } while (!VarDC->Equals(DC));
  11672. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11673. // computing the type of the capture at each step, checking type-specific
  11674. // requirements, and adding captures if requested.
  11675. // If the variable had already been captured previously, we start capturing
  11676. // at the lambda nested within that one.
  11677. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11678. ++I) {
  11679. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11680. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11681. if (!captureInBlock(BSI, Var, ExprLoc,
  11682. BuildAndDiagnose, CaptureType,
  11683. DeclRefType, Nested, *this))
  11684. return true;
  11685. Nested = true;
  11686. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11687. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11688. BuildAndDiagnose, CaptureType,
  11689. DeclRefType, Nested, *this))
  11690. return true;
  11691. Nested = true;
  11692. } else {
  11693. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11694. if (!captureInLambda(LSI, Var, ExprLoc,
  11695. BuildAndDiagnose, CaptureType,
  11696. DeclRefType, Nested, Kind, EllipsisLoc,
  11697. /*IsTopScope*/I == N - 1, *this))
  11698. return true;
  11699. Nested = true;
  11700. }
  11701. }
  11702. return false;
  11703. }
  11704. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11705. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11706. QualType CaptureType;
  11707. QualType DeclRefType;
  11708. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11709. /*BuildAndDiagnose=*/true, CaptureType,
  11710. DeclRefType, nullptr);
  11711. }
  11712. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11713. QualType CaptureType;
  11714. QualType DeclRefType;
  11715. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11716. /*BuildAndDiagnose=*/false, CaptureType,
  11717. DeclRefType, nullptr);
  11718. }
  11719. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11720. QualType CaptureType;
  11721. QualType DeclRefType;
  11722. // Determine whether we can capture this variable.
  11723. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11724. /*BuildAndDiagnose=*/false, CaptureType,
  11725. DeclRefType, nullptr))
  11726. return QualType();
  11727. return DeclRefType;
  11728. }
  11729. // If either the type of the variable or the initializer is dependent,
  11730. // return false. Otherwise, determine whether the variable is a constant
  11731. // expression. Use this if you need to know if a variable that might or
  11732. // might not be dependent is truly a constant expression.
  11733. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11734. ASTContext &Context) {
  11735. if (Var->getType()->isDependentType())
  11736. return false;
  11737. const VarDecl *DefVD = nullptr;
  11738. Var->getAnyInitializer(DefVD);
  11739. if (!DefVD)
  11740. return false;
  11741. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11742. Expr *Init = cast<Expr>(Eval->Value);
  11743. if (Init->isValueDependent())
  11744. return false;
  11745. return IsVariableAConstantExpression(Var, Context);
  11746. }
  11747. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11748. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11749. // an object that satisfies the requirements for appearing in a
  11750. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11751. // is immediately applied." This function handles the lvalue-to-rvalue
  11752. // conversion part.
  11753. MaybeODRUseExprs.erase(E->IgnoreParens());
  11754. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11755. // to a variable that is a constant expression, and if so, identify it as
  11756. // a reference to a variable that does not involve an odr-use of that
  11757. // variable.
  11758. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11759. Expr *SansParensExpr = E->IgnoreParens();
  11760. VarDecl *Var = nullptr;
  11761. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11762. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11763. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11764. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11765. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11766. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11767. }
  11768. }
  11769. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11770. Res = CorrectDelayedTyposInExpr(Res);
  11771. if (!Res.isUsable())
  11772. return Res;
  11773. // If a constant-expression is a reference to a variable where we delay
  11774. // deciding whether it is an odr-use, just assume we will apply the
  11775. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11776. // (a non-type template argument), we have special handling anyway.
  11777. UpdateMarkingForLValueToRValue(Res.get());
  11778. return Res;
  11779. }
  11780. void Sema::CleanupVarDeclMarking() {
  11781. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11782. e = MaybeODRUseExprs.end();
  11783. i != e; ++i) {
  11784. VarDecl *Var;
  11785. SourceLocation Loc;
  11786. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11787. Var = cast<VarDecl>(DRE->getDecl());
  11788. Loc = DRE->getLocation();
  11789. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11790. Var = cast<VarDecl>(ME->getMemberDecl());
  11791. Loc = ME->getMemberLoc();
  11792. } else {
  11793. llvm_unreachable("Unexpected expression");
  11794. }
  11795. MarkVarDeclODRUsed(Var, Loc, *this,
  11796. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11797. }
  11798. MaybeODRUseExprs.clear();
  11799. }
  11800. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11801. VarDecl *Var, Expr *E) {
  11802. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11803. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11804. Var->setReferenced();
  11805. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11806. bool MarkODRUsed = true;
  11807. // If the context is not potentially evaluated, this is not an odr-use and
  11808. // does not trigger instantiation.
  11809. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11810. if (SemaRef.isUnevaluatedContext())
  11811. return;
  11812. // If we don't yet know whether this context is going to end up being an
  11813. // evaluated context, and we're referencing a variable from an enclosing
  11814. // scope, add a potential capture.
  11815. //
  11816. // FIXME: Is this necessary? These contexts are only used for default
  11817. // arguments, where local variables can't be used.
  11818. const bool RefersToEnclosingScope =
  11819. (SemaRef.CurContext != Var->getDeclContext() &&
  11820. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11821. if (RefersToEnclosingScope) {
  11822. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11823. // If a variable could potentially be odr-used, defer marking it so
  11824. // until we finish analyzing the full expression for any
  11825. // lvalue-to-rvalue
  11826. // or discarded value conversions that would obviate odr-use.
  11827. // Add it to the list of potential captures that will be analyzed
  11828. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11829. // unless the variable is a reference that was initialized by a constant
  11830. // expression (this will never need to be captured or odr-used).
  11831. assert(E && "Capture variable should be used in an expression.");
  11832. if (!Var->getType()->isReferenceType() ||
  11833. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11834. LSI->addPotentialCapture(E->IgnoreParens());
  11835. }
  11836. }
  11837. if (!isTemplateInstantiation(TSK))
  11838. return;
  11839. // Instantiate, but do not mark as odr-used, variable templates.
  11840. MarkODRUsed = false;
  11841. }
  11842. VarTemplateSpecializationDecl *VarSpec =
  11843. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11844. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11845. "Can't instantiate a partial template specialization.");
  11846. // Perform implicit instantiation of static data members, static data member
  11847. // templates of class templates, and variable template specializations. Delay
  11848. // instantiations of variable templates, except for those that could be used
  11849. // in a constant expression.
  11850. if (isTemplateInstantiation(TSK)) {
  11851. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11852. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11853. if (Var->getPointOfInstantiation().isInvalid()) {
  11854. // This is a modification of an existing AST node. Notify listeners.
  11855. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11856. L->StaticDataMemberInstantiated(Var);
  11857. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11858. // Don't bother trying to instantiate it again, unless we might need
  11859. // its initializer before we get to the end of the TU.
  11860. TryInstantiating = false;
  11861. }
  11862. if (Var->getPointOfInstantiation().isInvalid())
  11863. Var->setTemplateSpecializationKind(TSK, Loc);
  11864. if (TryInstantiating) {
  11865. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11866. bool InstantiationDependent = false;
  11867. bool IsNonDependent =
  11868. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11869. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11870. : true;
  11871. // Do not instantiate specializations that are still type-dependent.
  11872. if (IsNonDependent) {
  11873. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11874. // Do not defer instantiations of variables which could be used in a
  11875. // constant expression.
  11876. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11877. } else {
  11878. SemaRef.PendingInstantiations
  11879. .push_back(std::make_pair(Var, PointOfInstantiation));
  11880. }
  11881. }
  11882. }
  11883. }
  11884. if(!MarkODRUsed) return;
  11885. // HLSL Change Begin -External variable is in cbuffer, cannot use as immediate.
  11886. // Mark used for referenced external variable.
  11887. if (SemaRef.getLangOpts().HLSL && Var->hasExternalFormalLinkage() &&
  11888. !isa<EnumConstantDecl>(Var))
  11889. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11890. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11891. // HLSL Change End.
  11892. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11893. // the requirements for appearing in a constant expression (5.19) and, if
  11894. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11895. // is immediately applied." We check the first part here, and
  11896. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11897. // Note that we use the C++11 definition everywhere because nothing in
  11898. // C++03 depends on whether we get the C++03 version correct. The second
  11899. // part does not apply to references, since they are not objects.
  11900. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11901. // A reference initialized by a constant expression can never be
  11902. // odr-used, so simply ignore it.
  11903. if (!Var->getType()->isReferenceType())
  11904. SemaRef.MaybeODRUseExprs.insert(E);
  11905. } else
  11906. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11907. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11908. }
  11909. /// \brief Mark a variable referenced, and check whether it is odr-used
  11910. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11911. /// used directly for normal expressions referring to VarDecl.
  11912. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11913. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11914. }
  11915. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11916. Decl *D, Expr *E, bool OdrUse) {
  11917. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11918. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11919. return;
  11920. }
  11921. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11922. // If this is a call to a method via a cast, also mark the method in the
  11923. // derived class used in case codegen can devirtualize the call.
  11924. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11925. if (!ME)
  11926. return;
  11927. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11928. if (!MD)
  11929. return;
  11930. // Only attempt to devirtualize if this is truly a virtual call.
  11931. bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
  11932. if (!IsVirtualCall)
  11933. return;
  11934. const Expr *Base = ME->getBase();
  11935. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11936. if (!MostDerivedClassDecl)
  11937. return;
  11938. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11939. if (!DM || DM->isPure())
  11940. return;
  11941. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11942. }
  11943. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  11944. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  11945. // TODO: update this with DR# once a defect report is filed.
  11946. // C++11 defect. The address of a pure member should not be an ODR use, even
  11947. // if it's a qualified reference.
  11948. bool OdrUse = true;
  11949. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  11950. if (Method->isVirtual())
  11951. OdrUse = false;
  11952. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  11953. }
  11954. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  11955. void Sema::MarkMemberReferenced(MemberExpr *E) {
  11956. // C++11 [basic.def.odr]p2:
  11957. // A non-overloaded function whose name appears as a potentially-evaluated
  11958. // expression or a member of a set of candidate functions, if selected by
  11959. // overload resolution when referred to from a potentially-evaluated
  11960. // expression, is odr-used, unless it is a pure virtual function and its
  11961. // name is not explicitly qualified.
  11962. bool OdrUse = true;
  11963. if (!E->hasQualifier()) {
  11964. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  11965. if (Method->isPure())
  11966. OdrUse = false;
  11967. }
  11968. SourceLocation Loc = E->getMemberLoc().isValid() ?
  11969. E->getMemberLoc() : E->getLocStart();
  11970. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  11971. }
  11972. /// \brief Perform marking for a reference to an arbitrary declaration. It
  11973. /// marks the declaration referenced, and performs odr-use checking for
  11974. /// functions and variables. This method should not be used when building a
  11975. /// normal expression which refers to a variable.
  11976. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  11977. if (OdrUse) {
  11978. if (auto *VD = dyn_cast<VarDecl>(D)) {
  11979. MarkVariableReferenced(Loc, VD);
  11980. return;
  11981. }
  11982. }
  11983. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  11984. MarkFunctionReferenced(Loc, FD, OdrUse);
  11985. return;
  11986. }
  11987. D->setReferenced();
  11988. }
  11989. namespace {
  11990. // Mark all of the declarations referenced
  11991. // FIXME: Not fully implemented yet! We need to have a better understanding
  11992. // of when we're entering
  11993. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  11994. Sema &S;
  11995. SourceLocation Loc;
  11996. public:
  11997. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  11998. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  11999. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  12000. bool TraverseRecordType(RecordType *T);
  12001. };
  12002. }
  12003. bool MarkReferencedDecls::TraverseTemplateArgument(
  12004. const TemplateArgument &Arg) {
  12005. if (Arg.getKind() == TemplateArgument::Declaration) {
  12006. if (Decl *D = Arg.getAsDecl())
  12007. S.MarkAnyDeclReferenced(Loc, D, true);
  12008. }
  12009. return Inherited::TraverseTemplateArgument(Arg);
  12010. }
  12011. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  12012. if (ClassTemplateSpecializationDecl *Spec
  12013. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  12014. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  12015. return TraverseTemplateArguments(Args.data(), Args.size());
  12016. }
  12017. return true;
  12018. }
  12019. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  12020. MarkReferencedDecls Marker(*this, Loc);
  12021. Marker.TraverseType(Context.getCanonicalType(T));
  12022. }
  12023. namespace {
  12024. /// \brief Helper class that marks all of the declarations referenced by
  12025. /// potentially-evaluated subexpressions as "referenced".
  12026. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  12027. Sema &S;
  12028. bool SkipLocalVariables;
  12029. public:
  12030. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  12031. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  12032. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  12033. void VisitDeclRefExpr(DeclRefExpr *E) {
  12034. // If we were asked not to visit local variables, don't.
  12035. if (SkipLocalVariables) {
  12036. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  12037. if (VD->hasLocalStorage())
  12038. return;
  12039. }
  12040. S.MarkDeclRefReferenced(E);
  12041. }
  12042. void VisitMemberExpr(MemberExpr *E) {
  12043. S.MarkMemberReferenced(E);
  12044. Inherited::VisitMemberExpr(E);
  12045. }
  12046. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  12047. S.MarkFunctionReferenced(E->getLocStart(),
  12048. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  12049. Visit(E->getSubExpr());
  12050. }
  12051. void VisitCXXNewExpr(CXXNewExpr *E) {
  12052. if (E->getOperatorNew())
  12053. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  12054. if (E->getOperatorDelete())
  12055. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12056. Inherited::VisitCXXNewExpr(E);
  12057. }
  12058. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  12059. if (E->getOperatorDelete())
  12060. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12061. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  12062. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  12063. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  12064. S.MarkFunctionReferenced(E->getLocStart(),
  12065. S.LookupDestructor(Record));
  12066. }
  12067. Inherited::VisitCXXDeleteExpr(E);
  12068. }
  12069. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  12070. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  12071. Inherited::VisitCXXConstructExpr(E);
  12072. }
  12073. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  12074. Visit(E->getExpr());
  12075. }
  12076. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12077. Inherited::VisitImplicitCastExpr(E);
  12078. if (E->getCastKind() == CK_LValueToRValue)
  12079. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  12080. }
  12081. };
  12082. }
  12083. /// \brief Mark any declarations that appear within this expression or any
  12084. /// potentially-evaluated subexpressions as "referenced".
  12085. ///
  12086. /// \param SkipLocalVariables If true, don't mark local variables as
  12087. /// 'referenced'.
  12088. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  12089. bool SkipLocalVariables) {
  12090. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  12091. }
  12092. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  12093. /// of the program being compiled.
  12094. ///
  12095. /// This routine emits the given diagnostic when the code currently being
  12096. /// type-checked is "potentially evaluated", meaning that there is a
  12097. /// possibility that the code will actually be executable. Code in sizeof()
  12098. /// expressions, code used only during overload resolution, etc., are not
  12099. /// potentially evaluated. This routine will suppress such diagnostics or,
  12100. /// in the absolutely nutty case of potentially potentially evaluated
  12101. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  12102. /// later.
  12103. ///
  12104. /// This routine should be used for all diagnostics that describe the run-time
  12105. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  12106. /// Failure to do so will likely result in spurious diagnostics or failures
  12107. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  12108. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  12109. const PartialDiagnostic &PD) {
  12110. switch (ExprEvalContexts.back().Context) {
  12111. case Unevaluated:
  12112. case UnevaluatedAbstract:
  12113. // The argument will never be evaluated, so don't complain.
  12114. break;
  12115. case ConstantEvaluated:
  12116. // Relevant diagnostics should be produced by constant evaluation.
  12117. break;
  12118. case PotentiallyEvaluated:
  12119. case PotentiallyEvaluatedIfUsed:
  12120. if (Statement && getCurFunctionOrMethodDecl()) {
  12121. FunctionScopes.back()->PossiblyUnreachableDiags.
  12122. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  12123. }
  12124. else
  12125. Diag(Loc, PD);
  12126. return true;
  12127. }
  12128. return false;
  12129. }
  12130. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  12131. CallExpr *CE, FunctionDecl *FD) {
  12132. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  12133. return false;
  12134. // If we're inside a decltype's expression, don't check for a valid return
  12135. // type or construct temporaries until we know whether this is the last call.
  12136. if (ExprEvalContexts.back().IsDecltype) {
  12137. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  12138. return false;
  12139. }
  12140. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  12141. FunctionDecl *FD;
  12142. CallExpr *CE;
  12143. public:
  12144. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  12145. : FD(FD), CE(CE) { }
  12146. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  12147. if (!FD) {
  12148. S.Diag(Loc, diag::err_call_incomplete_return)
  12149. << T << CE->getSourceRange();
  12150. return;
  12151. }
  12152. S.Diag(Loc, diag::err_call_function_incomplete_return)
  12153. << CE->getSourceRange() << FD->getDeclName() << T;
  12154. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  12155. << FD->getDeclName();
  12156. }
  12157. } Diagnoser(FD, CE);
  12158. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  12159. return true;
  12160. return false;
  12161. }
  12162. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  12163. // will prevent this condition from triggering, which is what we want.
  12164. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  12165. SourceLocation Loc;
  12166. unsigned diagnostic = diag::warn_condition_is_assignment;
  12167. bool IsOrAssign = false;
  12168. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  12169. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  12170. return;
  12171. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  12172. // Greylist some idioms by putting them into a warning subcategory.
  12173. if (ObjCMessageExpr *ME
  12174. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  12175. Selector Sel = ME->getSelector();
  12176. // self = [<foo> init...]
  12177. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  12178. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12179. // <foo> = [<bar> nextObject]
  12180. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  12181. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12182. }
  12183. Loc = Op->getOperatorLoc();
  12184. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  12185. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  12186. return;
  12187. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  12188. Loc = Op->getOperatorLoc();
  12189. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  12190. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  12191. else {
  12192. // Not an assignment.
  12193. return;
  12194. }
  12195. Diag(Loc, diagnostic) << E->getSourceRange();
  12196. SourceLocation Open = E->getLocStart();
  12197. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  12198. Diag(Loc, diag::note_condition_assign_silence)
  12199. << FixItHint::CreateInsertion(Open, "(")
  12200. << FixItHint::CreateInsertion(Close, ")");
  12201. if (IsOrAssign)
  12202. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  12203. << FixItHint::CreateReplacement(Loc, "!=");
  12204. else
  12205. Diag(Loc, diag::note_condition_assign_to_comparison)
  12206. << FixItHint::CreateReplacement(Loc, "==");
  12207. }
  12208. /// \brief Redundant parentheses over an equality comparison can indicate
  12209. /// that the user intended an assignment used as condition.
  12210. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  12211. // Don't warn if the parens came from a macro.
  12212. SourceLocation parenLoc = ParenE->getLocStart();
  12213. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  12214. return;
  12215. // Don't warn for dependent expressions.
  12216. if (ParenE->isTypeDependent())
  12217. return;
  12218. Expr *E = ParenE->IgnoreParens();
  12219. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12220. if (opE->getOpcode() == BO_EQ &&
  12221. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12222. == Expr::MLV_Valid) {
  12223. SourceLocation Loc = opE->getOperatorLoc();
  12224. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12225. SourceRange ParenERange = ParenE->getSourceRange();
  12226. Diag(Loc, diag::note_equality_comparison_silence)
  12227. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12228. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12229. Diag(Loc, diag::note_equality_comparison_to_assign)
  12230. << FixItHint::CreateReplacement(Loc, "=");
  12231. }
  12232. }
  12233. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12234. DiagnoseAssignmentAsCondition(E);
  12235. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12236. DiagnoseEqualityWithExtraParens(parenE);
  12237. ExprResult result = CheckPlaceholderExpr(E);
  12238. if (result.isInvalid()) return ExprError();
  12239. E = result.get();
  12240. if (!E->isTypeDependent()) {
  12241. if (getLangOpts().CPlusPlus)
  12242. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12243. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12244. if (ERes.isInvalid())
  12245. return ExprError();
  12246. E = ERes.get();
  12247. QualType T = E->getType();
  12248. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12249. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12250. << T << E->getSourceRange();
  12251. return ExprError();
  12252. }
  12253. CheckBoolLikeConversion(E, Loc);
  12254. }
  12255. return E;
  12256. }
  12257. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12258. Expr *SubExpr) {
  12259. if (!SubExpr)
  12260. return ExprError();
  12261. return CheckBooleanCondition(SubExpr, Loc);
  12262. }
  12263. namespace {
  12264. /// A visitor for rebuilding a call to an __unknown_any expression
  12265. /// to have an appropriate type.
  12266. struct RebuildUnknownAnyFunction
  12267. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12268. Sema &S;
  12269. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12270. ExprResult VisitStmt(Stmt *S) {
  12271. llvm_unreachable("unexpected statement!");
  12272. }
  12273. ExprResult VisitExpr(Expr *E) {
  12274. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12275. << E->getSourceRange();
  12276. return ExprError();
  12277. }
  12278. /// Rebuild an expression which simply semantically wraps another
  12279. /// expression which it shares the type and value kind of.
  12280. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12281. ExprResult SubResult = Visit(E->getSubExpr());
  12282. if (SubResult.isInvalid()) return ExprError();
  12283. Expr *SubExpr = SubResult.get();
  12284. E->setSubExpr(SubExpr);
  12285. E->setType(SubExpr->getType());
  12286. E->setValueKind(SubExpr->getValueKind());
  12287. assert(E->getObjectKind() == OK_Ordinary);
  12288. return E;
  12289. }
  12290. ExprResult VisitParenExpr(ParenExpr *E) {
  12291. return rebuildSugarExpr(E);
  12292. }
  12293. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12294. return rebuildSugarExpr(E);
  12295. }
  12296. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12297. ExprResult SubResult = Visit(E->getSubExpr());
  12298. if (SubResult.isInvalid()) return ExprError();
  12299. Expr *SubExpr = SubResult.get();
  12300. E->setSubExpr(SubExpr);
  12301. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12302. assert(E->getValueKind() == VK_RValue);
  12303. assert(E->getObjectKind() == OK_Ordinary);
  12304. return E;
  12305. }
  12306. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12307. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12308. E->setType(VD->getType());
  12309. assert(E->getValueKind() == VK_RValue);
  12310. if (S.getLangOpts().CPlusPlus &&
  12311. !(isa<CXXMethodDecl>(VD) &&
  12312. cast<CXXMethodDecl>(VD)->isInstance()))
  12313. E->setValueKind(VK_LValue);
  12314. return E;
  12315. }
  12316. ExprResult VisitMemberExpr(MemberExpr *E) {
  12317. return resolveDecl(E, E->getMemberDecl());
  12318. }
  12319. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12320. return resolveDecl(E, E->getDecl());
  12321. }
  12322. };
  12323. }
  12324. /// Given a function expression of unknown-any type, try to rebuild it
  12325. /// to have a function type.
  12326. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12327. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12328. if (Result.isInvalid()) return ExprError();
  12329. return S.DefaultFunctionArrayConversion(Result.get());
  12330. }
  12331. namespace {
  12332. /// A visitor for rebuilding an expression of type __unknown_anytype
  12333. /// into one which resolves the type directly on the referring
  12334. /// expression. Strict preservation of the original source
  12335. /// structure is not a goal.
  12336. struct RebuildUnknownAnyExpr
  12337. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12338. Sema &S;
  12339. /// The current destination type.
  12340. QualType DestType;
  12341. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12342. : S(S), DestType(CastType) {}
  12343. ExprResult VisitStmt(Stmt *S) {
  12344. llvm_unreachable("unexpected statement!");
  12345. }
  12346. ExprResult VisitExpr(Expr *E) {
  12347. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12348. << E->getSourceRange();
  12349. return ExprError();
  12350. }
  12351. ExprResult VisitCallExpr(CallExpr *E);
  12352. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12353. /// Rebuild an expression which simply semantically wraps another
  12354. /// expression which it shares the type and value kind of.
  12355. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12356. ExprResult SubResult = Visit(E->getSubExpr());
  12357. if (SubResult.isInvalid()) return ExprError();
  12358. Expr *SubExpr = SubResult.get();
  12359. E->setSubExpr(SubExpr);
  12360. E->setType(SubExpr->getType());
  12361. E->setValueKind(SubExpr->getValueKind());
  12362. assert(E->getObjectKind() == OK_Ordinary);
  12363. return E;
  12364. }
  12365. ExprResult VisitParenExpr(ParenExpr *E) {
  12366. return rebuildSugarExpr(E);
  12367. }
  12368. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12369. return rebuildSugarExpr(E);
  12370. }
  12371. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12372. const PointerType *Ptr = DestType->getAs<PointerType>();
  12373. if (!Ptr) {
  12374. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12375. << E->getSourceRange();
  12376. return ExprError();
  12377. }
  12378. assert(E->getValueKind() == VK_RValue);
  12379. assert(E->getObjectKind() == OK_Ordinary);
  12380. E->setType(DestType);
  12381. // Build the sub-expression as if it were an object of the pointee type.
  12382. DestType = Ptr->getPointeeType();
  12383. ExprResult SubResult = Visit(E->getSubExpr());
  12384. if (SubResult.isInvalid()) return ExprError();
  12385. E->setSubExpr(SubResult.get());
  12386. return E;
  12387. }
  12388. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12389. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12390. ExprResult VisitMemberExpr(MemberExpr *E) {
  12391. return resolveDecl(E, E->getMemberDecl());
  12392. }
  12393. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12394. return resolveDecl(E, E->getDecl());
  12395. }
  12396. };
  12397. }
  12398. /// Rebuilds a call expression which yielded __unknown_anytype.
  12399. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12400. Expr *CalleeExpr = E->getCallee();
  12401. enum FnKind {
  12402. FK_MemberFunction,
  12403. FK_FunctionPointer,
  12404. FK_BlockPointer
  12405. };
  12406. FnKind Kind;
  12407. QualType CalleeType = CalleeExpr->getType();
  12408. if (CalleeType == S.Context.BoundMemberTy) {
  12409. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12410. Kind = FK_MemberFunction;
  12411. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12412. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12413. CalleeType = Ptr->getPointeeType();
  12414. Kind = FK_FunctionPointer;
  12415. } else {
  12416. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12417. Kind = FK_BlockPointer;
  12418. }
  12419. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12420. // Verify that this is a legal result type of a function.
  12421. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12422. unsigned diagID = diag::err_func_returning_array_function;
  12423. if (Kind == FK_BlockPointer)
  12424. diagID = diag::err_block_returning_array_function;
  12425. S.Diag(E->getExprLoc(), diagID)
  12426. << DestType->isFunctionType() << DestType;
  12427. return ExprError();
  12428. }
  12429. // Otherwise, go ahead and set DestType as the call's result.
  12430. E->setType(DestType.getNonLValueExprType(S.Context));
  12431. E->setValueKind(Expr::getValueKindForType(DestType));
  12432. assert(E->getObjectKind() == OK_Ordinary);
  12433. // Rebuild the function type, replacing the result type with DestType.
  12434. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12435. if (Proto) {
  12436. // __unknown_anytype(...) is a special case used by the debugger when
  12437. // it has no idea what a function's signature is.
  12438. //
  12439. // We want to build this call essentially under the K&R
  12440. // unprototyped rules, but making a FunctionNoProtoType in C++
  12441. // would foul up all sorts of assumptions. However, we cannot
  12442. // simply pass all arguments as variadic arguments, nor can we
  12443. // portably just call the function under a non-variadic type; see
  12444. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12445. // However, it turns out that in practice it is generally safe to
  12446. // call a function declared as "A foo(B,C,D);" under the prototype
  12447. // "A foo(B,C,D,...);". The only known exception is with the
  12448. // Windows ABI, where any variadic function is implicitly cdecl
  12449. // regardless of its normal CC. Therefore we change the parameter
  12450. // types to match the types of the arguments.
  12451. //
  12452. // This is a hack, but it is far superior to moving the
  12453. // corresponding target-specific code from IR-gen to Sema/AST.
  12454. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12455. SmallVector<QualType, 8> ArgTypes;
  12456. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12457. ArgTypes.reserve(E->getNumArgs());
  12458. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12459. Expr *Arg = E->getArg(i);
  12460. QualType ArgType = Arg->getType();
  12461. if (E->isLValue()) {
  12462. ArgType = S.Context.getLValueReferenceType(ArgType);
  12463. } else if (E->isXValue()) {
  12464. ArgType = S.Context.getRValueReferenceType(ArgType);
  12465. }
  12466. ArgTypes.push_back(ArgType);
  12467. }
  12468. ParamTypes = ArgTypes;
  12469. }
  12470. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12471. Proto->getExtProtoInfo(),
  12472. Proto->getParamMods()); // HLSL Change - assume args are preserved
  12473. } else {
  12474. DestType = S.Context.getFunctionNoProtoType(DestType,
  12475. FnType->getExtInfo());
  12476. }
  12477. // Rebuild the appropriate pointer-to-function type.
  12478. switch (Kind) {
  12479. case FK_MemberFunction:
  12480. // Nothing to do.
  12481. break;
  12482. case FK_FunctionPointer:
  12483. DestType = S.Context.getPointerType(DestType);
  12484. break;
  12485. case FK_BlockPointer:
  12486. DestType = S.Context.getBlockPointerType(DestType);
  12487. break;
  12488. }
  12489. // Finally, we can recurse.
  12490. ExprResult CalleeResult = Visit(CalleeExpr);
  12491. if (!CalleeResult.isUsable()) return ExprError();
  12492. E->setCallee(CalleeResult.get());
  12493. // Bind a temporary if necessary.
  12494. return S.MaybeBindToTemporary(E);
  12495. }
  12496. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12497. // Verify that this is a legal result type of a call.
  12498. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12499. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12500. << DestType->isFunctionType() << DestType;
  12501. return ExprError();
  12502. }
  12503. // Rewrite the method result type if available.
  12504. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12505. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12506. Method->setReturnType(DestType);
  12507. }
  12508. // Change the type of the message.
  12509. E->setType(DestType.getNonReferenceType());
  12510. E->setValueKind(Expr::getValueKindForType(DestType));
  12511. return S.MaybeBindToTemporary(E);
  12512. }
  12513. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12514. // The only case we should ever see here is a function-to-pointer decay.
  12515. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12516. assert(E->getValueKind() == VK_RValue);
  12517. assert(E->getObjectKind() == OK_Ordinary);
  12518. E->setType(DestType);
  12519. // Rebuild the sub-expression as the pointee (function) type.
  12520. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12521. ExprResult Result = Visit(E->getSubExpr());
  12522. if (!Result.isUsable()) return ExprError();
  12523. E->setSubExpr(Result.get());
  12524. return E;
  12525. } else if (E->getCastKind() == CK_LValueToRValue) {
  12526. assert(E->getValueKind() == VK_RValue);
  12527. assert(E->getObjectKind() == OK_Ordinary);
  12528. assert(isa<BlockPointerType>(E->getType()));
  12529. E->setType(DestType);
  12530. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12531. DestType = S.Context.getLValueReferenceType(DestType);
  12532. ExprResult Result = Visit(E->getSubExpr());
  12533. if (!Result.isUsable()) return ExprError();
  12534. E->setSubExpr(Result.get());
  12535. return E;
  12536. } else {
  12537. llvm_unreachable("Unhandled cast type!");
  12538. }
  12539. }
  12540. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12541. ExprValueKind ValueKind = VK_LValue;
  12542. QualType Type = DestType;
  12543. // We know how to make this work for certain kinds of decls:
  12544. // - functions
  12545. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12546. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12547. DestType = Ptr->getPointeeType();
  12548. ExprResult Result = resolveDecl(E, VD);
  12549. if (Result.isInvalid()) return ExprError();
  12550. return S.ImpCastExprToType(Result.get(), Type,
  12551. CK_FunctionToPointerDecay, VK_RValue);
  12552. }
  12553. if (!Type->isFunctionType()) {
  12554. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12555. << VD << E->getSourceRange();
  12556. return ExprError();
  12557. }
  12558. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12559. // We must match the FunctionDecl's type to the hack introduced in
  12560. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12561. // type. See the lengthy commentary in that routine.
  12562. QualType FDT = FD->getType();
  12563. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12564. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12565. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12566. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12567. SourceLocation Loc = FD->getLocation();
  12568. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12569. FD->getDeclContext(),
  12570. Loc, Loc, FD->getNameInfo().getName(),
  12571. DestType, FD->getTypeSourceInfo(),
  12572. SC_None, false/*isInlineSpecified*/,
  12573. FD->hasPrototype(),
  12574. false/*isConstexprSpecified*/);
  12575. if (FD->getQualifier())
  12576. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12577. SmallVector<ParmVarDecl*, 16> Params;
  12578. for (const auto &AI : FT->param_types()) {
  12579. ParmVarDecl *Param =
  12580. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12581. Param->setScopeInfo(0, Params.size());
  12582. Params.push_back(Param);
  12583. }
  12584. NewFD->setParams(Params);
  12585. DRE->setDecl(NewFD);
  12586. VD = DRE->getDecl();
  12587. }
  12588. }
  12589. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12590. if (MD->isInstance()) {
  12591. ValueKind = VK_RValue;
  12592. Type = S.Context.BoundMemberTy;
  12593. }
  12594. // Function references aren't l-values in C.
  12595. if (!S.getLangOpts().CPlusPlus)
  12596. ValueKind = VK_RValue;
  12597. // - variables
  12598. } else if (isa<VarDecl>(VD)) {
  12599. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12600. Type = RefTy->getPointeeType();
  12601. } else if (Type->isFunctionType()) {
  12602. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12603. << VD << E->getSourceRange();
  12604. return ExprError();
  12605. }
  12606. // - nothing else
  12607. } else {
  12608. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12609. << VD << E->getSourceRange();
  12610. return ExprError();
  12611. }
  12612. // Modifying the declaration like this is friendly to IR-gen but
  12613. // also really dangerous.
  12614. VD->setType(DestType);
  12615. E->setType(Type);
  12616. E->setValueKind(ValueKind);
  12617. return E;
  12618. }
  12619. /// Check a cast of an unknown-any type. We intentionally only
  12620. /// trigger this for C-style casts.
  12621. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12622. Expr *CastExpr, CastKind &CastKind,
  12623. ExprValueKind &VK, CXXCastPath &Path) {
  12624. // Rewrite the casted expression from scratch.
  12625. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12626. if (!result.isUsable()) return ExprError();
  12627. CastExpr = result.get();
  12628. VK = CastExpr->getValueKind();
  12629. CastKind = CK_NoOp;
  12630. return CastExpr;
  12631. }
  12632. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12633. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12634. }
  12635. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12636. Expr *arg, QualType &paramType) {
  12637. // If the syntactic form of the argument is not an explicit cast of
  12638. // any sort, just do default argument promotion.
  12639. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12640. if (!castArg) {
  12641. ExprResult result = DefaultArgumentPromotion(arg);
  12642. if (result.isInvalid()) return ExprError();
  12643. paramType = result.get()->getType();
  12644. return result;
  12645. }
  12646. // Otherwise, use the type that was written in the explicit cast.
  12647. assert(!arg->hasPlaceholderType());
  12648. paramType = castArg->getTypeAsWritten();
  12649. // Copy-initialize a parameter of that type.
  12650. InitializedEntity entity =
  12651. InitializedEntity::InitializeParameter(Context, paramType,
  12652. /*consumed*/ false);
  12653. return PerformCopyInitialization(entity, callLoc, arg);
  12654. }
  12655. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12656. Expr *orig = E;
  12657. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12658. while (true) {
  12659. E = E->IgnoreParenImpCasts();
  12660. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12661. E = call->getCallee();
  12662. diagID = diag::err_uncasted_call_of_unknown_any;
  12663. } else {
  12664. break;
  12665. }
  12666. }
  12667. SourceLocation loc;
  12668. NamedDecl *d;
  12669. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12670. loc = ref->getLocation();
  12671. d = ref->getDecl();
  12672. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12673. loc = mem->getMemberLoc();
  12674. d = mem->getMemberDecl();
  12675. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12676. diagID = diag::err_uncasted_call_of_unknown_any;
  12677. loc = msg->getSelectorStartLoc();
  12678. d = msg->getMethodDecl();
  12679. if (!d) {
  12680. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12681. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12682. << orig->getSourceRange();
  12683. return ExprError();
  12684. }
  12685. } else {
  12686. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12687. << E->getSourceRange();
  12688. return ExprError();
  12689. }
  12690. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12691. // Never recoverable.
  12692. return ExprError();
  12693. }
  12694. /// Check for operands with placeholder types and complain if found.
  12695. /// Returns true if there was an error and no recovery was possible.
  12696. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12697. if (!getLangOpts().CPlusPlus) {
  12698. // C cannot handle TypoExpr nodes on either side of a binop because it
  12699. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12700. // been dealt with before checking the operands.
  12701. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12702. if (!Result.isUsable()) return ExprError();
  12703. E = Result.get();
  12704. }
  12705. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12706. if (!placeholderType) return E;
  12707. switch (placeholderType->getKind()) {
  12708. // Overloaded expressions.
  12709. case BuiltinType::Overload: {
  12710. // Try to resolve a single function template specialization.
  12711. // This is obligatory.
  12712. ExprResult result = E;
  12713. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12714. return result;
  12715. // If that failed, try to recover with a call.
  12716. } else {
  12717. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12718. /*complain*/ true);
  12719. return result;
  12720. }
  12721. }
  12722. // Bound member functions.
  12723. case BuiltinType::BoundMember: {
  12724. ExprResult result = E;
  12725. const Expr *BME = E->IgnoreParens();
  12726. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12727. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12728. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12729. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12730. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12731. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12732. DeclarationName::CXXDestructorName)
  12733. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12734. }
  12735. tryToRecoverWithCall(result, PD,
  12736. /*complain*/ true);
  12737. return result;
  12738. }
  12739. // ARC unbridged casts.
  12740. case BuiltinType::ARCUnbridgedCast: {
  12741. Expr *realCast = stripARCUnbridgedCast(E);
  12742. diagnoseARCUnbridgedCast(realCast);
  12743. return realCast;
  12744. }
  12745. // Expressions of unknown type.
  12746. case BuiltinType::UnknownAny:
  12747. return diagnoseUnknownAnyExpr(*this, E);
  12748. // Pseudo-objects.
  12749. case BuiltinType::PseudoObject:
  12750. return checkPseudoObjectRValue(E);
  12751. case BuiltinType::BuiltinFn: {
  12752. // Accept __noop without parens by implicitly converting it to a call expr.
  12753. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12754. if (DRE) {
  12755. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12756. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12757. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12758. CK_BuiltinFnToFnPtr).get();
  12759. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12760. VK_RValue, SourceLocation());
  12761. }
  12762. }
  12763. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12764. return ExprError();
  12765. }
  12766. // Everything else should be impossible.
  12767. #define BUILTIN_TYPE(Id, SingletonId) \
  12768. case BuiltinType::Id:
  12769. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12770. #include "clang/AST/BuiltinTypes.def"
  12771. break;
  12772. }
  12773. llvm_unreachable("invalid placeholder type!");
  12774. }
  12775. bool Sema::CheckCaseExpression(Expr *E) {
  12776. if (E->isTypeDependent())
  12777. return true;
  12778. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12779. return E->getType()->isIntegralOrEnumerationType();
  12780. return false;
  12781. }
  12782. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12783. ExprResult
  12784. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12785. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12786. "Unknown Objective-C Boolean value!");
  12787. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12788. if (!Context.getBOOLDecl()) {
  12789. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12790. Sema::LookupOrdinaryName);
  12791. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12792. NamedDecl *ND = Result.getFoundDecl();
  12793. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12794. Context.setBOOLDecl(TD);
  12795. }
  12796. }
  12797. if (Context.getBOOLDecl())
  12798. BoolT = Context.getBOOLType();
  12799. return new (Context)
  12800. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12801. }