SemaExpr.cpp 564 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662
  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. static bool IsExprAccessingMeshOutArray(Expr* BaseExpr) {
  542. switch (BaseExpr->getStmtClass()) {
  543. case Stmt::ArraySubscriptExprClass: {
  544. ArraySubscriptExpr* ase = cast<ArraySubscriptExpr>(BaseExpr);
  545. return IsExprAccessingMeshOutArray(ase->getBase());
  546. }
  547. case Stmt::ImplicitCastExprClass: {
  548. ImplicitCastExpr* ice = cast<ImplicitCastExpr>(BaseExpr);
  549. return IsExprAccessingMeshOutArray(ice->getSubExpr());
  550. }
  551. case Stmt::DeclRefExprClass: {
  552. DeclRefExpr* dre = cast<DeclRefExpr>(BaseExpr);
  553. ValueDecl* vd = dre->getDecl();
  554. if (vd->getAttr<HLSLOutAttr>() &&
  555. (vd->getAttr<HLSLIndicesAttr>() ||
  556. vd->getAttr<HLSLVerticesAttr>() ||
  557. vd->getAttr<HLSLPrimitivesAttr>())) {
  558. return true;
  559. }
  560. return false;
  561. }
  562. default:
  563. return false;
  564. }
  565. }
  566. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  567. // Handle any placeholder expressions which made it here.
  568. if (E->getType()->isPlaceholderType()) {
  569. ExprResult result = CheckPlaceholderExpr(E);
  570. if (result.isInvalid()) return ExprError();
  571. E = result.get();
  572. }
  573. // C++ [conv.lval]p1:
  574. // A glvalue of a non-function, non-array type T can be
  575. // converted to a prvalue.
  576. if (!E->isGLValue()) return E;
  577. QualType T = E->getType();
  578. assert(!T.isNull() && "r-value conversion on typeless expression?");
  579. // We don't want to throw lvalue-to-rvalue casts on top of
  580. // expressions of certain types in C++.
  581. if (getLangOpts().CPlusPlus &&
  582. !getLangOpts().HLSL && // HLSL Change - matrices and object types should turn into lvalues
  583. (E->getType() == Context.OverloadTy ||
  584. T->isDependentType() ||
  585. T->isRecordType()))
  586. return E;
  587. // The C standard is actually really unclear on this point, and
  588. // DR106 tells us what the result should be but not why. It's
  589. // generally best to say that void types just doesn't undergo
  590. // lvalue-to-rvalue at all. Note that expressions of unqualified
  591. // 'void' type are never l-values, but qualified void can be.
  592. if (T->isVoidType())
  593. return E;
  594. // OpenCL usually rejects direct accesses to values of 'half' type.
  595. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  596. T->isHalfType()) {
  597. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  598. << 0 << T;
  599. return ExprError();
  600. }
  601. CheckForNullPointerDereference(*this, E);
  602. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  603. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  604. &Context.Idents.get("object_getClass"),
  605. SourceLocation(), LookupOrdinaryName);
  606. if (ObjectGetClass)
  607. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  608. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  609. FixItHint::CreateReplacement(
  610. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  611. else
  612. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  613. }
  614. else if (const ObjCIvarRefExpr *OIRE =
  615. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  616. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  617. // check the access to mesh shader output arrays
  618. if (isa<ArraySubscriptExpr>(E) && IsExprAccessingMeshOutArray(E)) {
  619. Diag(E->getExprLoc(), diag::err_hlsl_load_from_mesh_out_arrays);
  620. return ExprError();
  621. }
  622. // C++ [conv.lval]p1:
  623. // [...] If T is a non-class type, the type of the prvalue is the
  624. // cv-unqualified version of T. Otherwise, the type of the
  625. // rvalue is T.
  626. //
  627. // C99 6.3.2.1p2:
  628. // If the lvalue has qualified type, the value has the unqualified
  629. // version of the type of the lvalue; otherwise, the value has the
  630. // type of the lvalue.
  631. if (T.hasQualifiers())
  632. T = T.getUnqualifiedType();
  633. UpdateMarkingForLValueToRValue(E);
  634. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  635. // balance that.
  636. if (getLangOpts().ObjCAutoRefCount &&
  637. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  638. ExprNeedsCleanups = true;
  639. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  640. nullptr, VK_RValue);
  641. // C11 6.3.2.1p2:
  642. // ... if the lvalue has atomic type, the value has the non-atomic version
  643. // of the type of the lvalue ...
  644. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  645. T = Atomic->getValueType().getUnqualifiedType();
  646. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  647. nullptr, VK_RValue);
  648. }
  649. return Res;
  650. }
  651. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  652. ExprResult Res = DefaultFunctionArrayConversion(E);
  653. if (Res.isInvalid())
  654. return ExprError();
  655. Res = DefaultLvalueConversion(Res.get());
  656. if (Res.isInvalid())
  657. return ExprError();
  658. return Res;
  659. }
  660. /// CallExprUnaryConversions - a special case of an unary conversion
  661. /// performed on a function designator of a call expression.
  662. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  663. QualType Ty = E->getType();
  664. ExprResult Res = E;
  665. // Only do implicit cast for a function type, but not for a pointer
  666. // to function type.
  667. if (Ty->isFunctionType()) {
  668. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  669. CK_FunctionToPointerDecay).get();
  670. if (Res.isInvalid())
  671. return ExprError();
  672. }
  673. Res = DefaultLvalueConversion(Res.get());
  674. if (Res.isInvalid())
  675. return ExprError();
  676. return Res.get();
  677. }
  678. /// UsualUnaryConversions - Performs various conversions that are common to most
  679. /// operators (C99 6.3). The conversions of array and function types are
  680. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  681. /// apply if the array is an argument to the sizeof or address (&) operators.
  682. /// In these instances, this routine should *not* be called.
  683. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  684. // First, convert to an r-value.
  685. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  686. if (Res.isInvalid())
  687. return ExprError();
  688. E = Res.get();
  689. QualType Ty = E->getType();
  690. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  691. // Half FP have to be promoted to float unless it is natively supported
  692. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  693. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  694. // Try to perform integral promotions if the object has a theoretically
  695. // promotable type.
  696. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  697. // C99 6.3.1.1p2:
  698. //
  699. // The following may be used in an expression wherever an int or
  700. // unsigned int may be used:
  701. // - an object or expression with an integer type whose integer
  702. // conversion rank is less than or equal to the rank of int
  703. // and unsigned int.
  704. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  705. //
  706. // If an int can represent all values of the original type, the
  707. // value is converted to an int; otherwise, it is converted to an
  708. // unsigned int. These are called the integer promotions. All
  709. // other types are unchanged by the integer promotions.
  710. QualType PTy = Context.isPromotableBitField(E);
  711. if (!PTy.isNull()) {
  712. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  713. return E;
  714. }
  715. if (Ty->isPromotableIntegerType() && !getLangOpts().HLSL) { // HLSL Change: leave low-precision integrals as such for intermediate operations
  716. QualType PT = Context.getPromotedIntegerType(Ty);
  717. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  718. return E;
  719. }
  720. }
  721. return E;
  722. }
  723. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  724. /// do not have a prototype. Arguments that have type float or __fp16
  725. /// are promoted to double. All other argument types are converted by
  726. /// UsualUnaryConversions().
  727. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  728. QualType Ty = E->getType();
  729. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  730. ExprResult Res = UsualUnaryConversions(E);
  731. if (Res.isInvalid())
  732. return ExprError();
  733. E = Res.get();
  734. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  735. // double.
  736. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  737. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  738. BTy->getKind() == BuiltinType::Float))
  739. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  740. // C++ performs lvalue-to-rvalue conversion as a default argument
  741. // promotion, even on class types, but note:
  742. // C++11 [conv.lval]p2:
  743. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  744. // operand or a subexpression thereof the value contained in the
  745. // referenced object is not accessed. Otherwise, if the glvalue
  746. // has a class type, the conversion copy-initializes a temporary
  747. // of type T from the glvalue and the result of the conversion
  748. // is a prvalue for the temporary.
  749. // FIXME: add some way to gate this entire thing for correctness in
  750. // potentially potentially evaluated contexts.
  751. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  752. ExprResult Temp = PerformCopyInitialization(
  753. InitializedEntity::InitializeTemporary(E->getType()),
  754. E->getExprLoc(), E);
  755. if (Temp.isInvalid())
  756. return ExprError();
  757. E = Temp.get();
  758. }
  759. return E;
  760. }
  761. /// Determine the degree of POD-ness for an expression.
  762. /// Incomplete types are considered POD, since this check can be performed
  763. /// when we're in an unevaluated context.
  764. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  765. if (Ty->isIncompleteType()) {
  766. // C++11 [expr.call]p7:
  767. // After these conversions, if the argument does not have arithmetic,
  768. // enumeration, pointer, pointer to member, or class type, the program
  769. // is ill-formed.
  770. //
  771. // Since we've already performed array-to-pointer and function-to-pointer
  772. // decay, the only such type in C++ is cv void. This also handles
  773. // initializer lists as variadic arguments.
  774. if (Ty->isVoidType())
  775. return VAK_Invalid;
  776. if (Ty->isObjCObjectType())
  777. return VAK_Invalid;
  778. return VAK_Valid;
  779. }
  780. if (Ty.isCXX98PODType(Context))
  781. return VAK_Valid;
  782. // C++11 [expr.call]p7:
  783. // Passing a potentially-evaluated argument of class type (Clause 9)
  784. // having a non-trivial copy constructor, a non-trivial move constructor,
  785. // or a non-trivial destructor, with no corresponding parameter,
  786. // is conditionally-supported with implementation-defined semantics.
  787. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  788. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  789. if (!Record->hasNonTrivialCopyConstructor() &&
  790. !Record->hasNonTrivialMoveConstructor() &&
  791. !Record->hasNonTrivialDestructor())
  792. return VAK_ValidInCXX11;
  793. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  794. return VAK_Valid;
  795. if (Ty->isObjCObjectType())
  796. return VAK_Invalid;
  797. if (getLangOpts().MSVCCompat)
  798. return VAK_MSVCUndefined;
  799. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  800. // permitted to reject them. We should consider doing so.
  801. return VAK_Undefined;
  802. }
  803. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  804. // Don't allow one to pass an Objective-C interface to a vararg.
  805. const QualType &Ty = E->getType();
  806. VarArgKind VAK = isValidVarArgType(Ty);
  807. // Complain about passing non-POD types through varargs.
  808. switch (VAK) {
  809. case VAK_ValidInCXX11:
  810. DiagRuntimeBehavior(
  811. E->getLocStart(), nullptr,
  812. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  813. << Ty << CT);
  814. // Fall through.
  815. case VAK_Valid:
  816. if (Ty->isRecordType()) {
  817. // This is unlikely to be what the user intended. If the class has a
  818. // 'c_str' member function, the user probably meant to call that.
  819. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  820. PDiag(diag::warn_pass_class_arg_to_vararg)
  821. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  822. }
  823. break;
  824. case VAK_Undefined:
  825. case VAK_MSVCUndefined:
  826. DiagRuntimeBehavior(
  827. E->getLocStart(), nullptr,
  828. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  829. << getLangOpts().CPlusPlus11 << Ty << CT);
  830. break;
  831. case VAK_Invalid:
  832. if (Ty->isObjCObjectType())
  833. DiagRuntimeBehavior(
  834. E->getLocStart(), nullptr,
  835. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  836. << Ty << CT);
  837. else
  838. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  839. << isa<InitListExpr>(E) << Ty << CT;
  840. break;
  841. }
  842. }
  843. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  844. /// will create a trap if the resulting type is not a POD type.
  845. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  846. FunctionDecl *FDecl) {
  847. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  848. // Strip the unbridged-cast placeholder expression off, if applicable.
  849. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  850. (CT == VariadicMethod ||
  851. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  852. E = stripARCUnbridgedCast(E);
  853. // Otherwise, do normal placeholder checking.
  854. } else {
  855. ExprResult ExprRes = CheckPlaceholderExpr(E);
  856. if (ExprRes.isInvalid())
  857. return ExprError();
  858. E = ExprRes.get();
  859. }
  860. }
  861. ExprResult ExprRes = DefaultArgumentPromotion(E);
  862. if (ExprRes.isInvalid())
  863. return ExprError();
  864. E = ExprRes.get();
  865. // Diagnostics regarding non-POD argument types are
  866. // emitted along with format string checking in Sema::CheckFunctionCall().
  867. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  868. // Turn this into a trap.
  869. CXXScopeSpec SS;
  870. SourceLocation TemplateKWLoc;
  871. UnqualifiedId Name;
  872. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  873. E->getLocStart());
  874. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  875. Name, true, false);
  876. if (TrapFn.isInvalid())
  877. return ExprError();
  878. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  879. E->getLocStart(), None,
  880. E->getLocEnd());
  881. if (Call.isInvalid())
  882. return ExprError();
  883. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  884. Call.get(), E);
  885. if (Comma.isInvalid())
  886. return ExprError();
  887. return Comma.get();
  888. }
  889. if (!getLangOpts().CPlusPlus &&
  890. RequireCompleteType(E->getExprLoc(), E->getType(),
  891. diag::err_call_incomplete_argument))
  892. return ExprError();
  893. return E;
  894. }
  895. /// \brief Converts an integer to complex float type. Helper function of
  896. /// UsualArithmeticConversions()
  897. ///
  898. /// \return false if the integer expression is an integer type and is
  899. /// successfully converted to the complex type.
  900. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  901. ExprResult &ComplexExpr,
  902. QualType IntTy,
  903. QualType ComplexTy,
  904. bool SkipCast) {
  905. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  906. if (SkipCast) return false;
  907. if (IntTy->isIntegerType()) {
  908. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  909. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  910. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  911. CK_FloatingRealToComplex);
  912. } else {
  913. assert(IntTy->isComplexIntegerType());
  914. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  915. CK_IntegralComplexToFloatingComplex);
  916. }
  917. return false;
  918. }
  919. /// \brief Handle arithmetic conversion with complex types. Helper function of
  920. /// UsualArithmeticConversions()
  921. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  922. ExprResult &RHS, QualType LHSType,
  923. QualType RHSType,
  924. bool IsCompAssign) {
  925. // if we have an integer operand, the result is the complex type.
  926. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  927. /*skipCast*/false))
  928. return LHSType;
  929. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  930. /*skipCast*/IsCompAssign))
  931. return RHSType;
  932. // This handles complex/complex, complex/float, or float/complex.
  933. // When both operands are complex, the shorter operand is converted to the
  934. // type of the longer, and that is the type of the result. This corresponds
  935. // to what is done when combining two real floating-point operands.
  936. // The fun begins when size promotion occur across type domains.
  937. // From H&S 6.3.4: When one operand is complex and the other is a real
  938. // floating-point type, the less precise type is converted, within it's
  939. // real or complex domain, to the precision of the other type. For example,
  940. // when combining a "long double" with a "double _Complex", the
  941. // "double _Complex" is promoted to "long double _Complex".
  942. // Compute the rank of the two types, regardless of whether they are complex.
  943. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  944. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  945. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  946. QualType LHSElementType =
  947. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  948. QualType RHSElementType =
  949. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  950. QualType ResultType = S.Context.getComplexType(LHSElementType);
  951. if (Order < 0) {
  952. // Promote the precision of the LHS if not an assignment.
  953. ResultType = S.Context.getComplexType(RHSElementType);
  954. if (!IsCompAssign) {
  955. if (LHSComplexType)
  956. LHS =
  957. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  958. else
  959. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  960. }
  961. } else if (Order > 0) {
  962. // Promote the precision of the RHS.
  963. if (RHSComplexType)
  964. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  965. else
  966. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  967. }
  968. return ResultType;
  969. }
  970. /// \brief Hande arithmetic conversion from integer to float. Helper function
  971. /// of UsualArithmeticConversions()
  972. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  973. ExprResult &IntExpr,
  974. QualType FloatTy, QualType IntTy,
  975. bool ConvertFloat, bool ConvertInt) {
  976. if (IntTy->isIntegerType()) {
  977. if (ConvertInt)
  978. // Convert intExpr to the lhs floating point type.
  979. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  980. CK_IntegralToFloating);
  981. return FloatTy;
  982. }
  983. // Convert both sides to the appropriate complex float.
  984. assert(IntTy->isComplexIntegerType());
  985. QualType result = S.Context.getComplexType(FloatTy);
  986. // _Complex int -> _Complex float
  987. if (ConvertInt)
  988. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  989. CK_IntegralComplexToFloatingComplex);
  990. // float -> _Complex float
  991. if (ConvertFloat)
  992. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  993. CK_FloatingRealToComplex);
  994. return result;
  995. }
  996. /// \brief Handle arithmethic conversion with floating point types. Helper
  997. /// function of UsualArithmeticConversions()
  998. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  999. ExprResult &RHS, QualType LHSType,
  1000. QualType RHSType, bool IsCompAssign) {
  1001. bool LHSFloat = LHSType->isRealFloatingType();
  1002. bool RHSFloat = RHSType->isRealFloatingType();
  1003. // If we have two real floating types, convert the smaller operand
  1004. // to the bigger result.
  1005. if (LHSFloat && RHSFloat) {
  1006. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  1007. if (order > 0) {
  1008. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  1009. return LHSType;
  1010. }
  1011. assert(order < 0 && "illegal float comparison");
  1012. if (!IsCompAssign)
  1013. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  1014. return RHSType;
  1015. }
  1016. if (LHSFloat) {
  1017. // Half FP has to be promoted to float unless it is natively supported
  1018. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  1019. LHSType = S.Context.FloatTy;
  1020. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  1021. /*convertFloat=*/!IsCompAssign,
  1022. /*convertInt=*/ true);
  1023. }
  1024. assert(RHSFloat);
  1025. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  1026. /*convertInt=*/ true,
  1027. /*convertFloat=*/!IsCompAssign);
  1028. }
  1029. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1030. namespace {
  1031. /// These helper callbacks are placed in an anonymous namespace to
  1032. /// permit their use as function template parameters.
  1033. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1034. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1035. }
  1036. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1037. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1038. CK_IntegralComplexCast);
  1039. }
  1040. }
  1041. /// \brief Handle integer arithmetic conversions. Helper function of
  1042. /// UsualArithmeticConversions()
  1043. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1044. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1045. ExprResult &RHS, QualType LHSType,
  1046. QualType RHSType, bool IsCompAssign) {
  1047. // The rules for this case are in C99 6.3.1.8
  1048. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1049. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1050. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1051. if (LHSSigned == RHSSigned) {
  1052. // Same signedness; use the higher-ranked type
  1053. if (order >= 0) {
  1054. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1055. return LHSType;
  1056. } else if (!IsCompAssign)
  1057. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1058. return RHSType;
  1059. } else if (order != (LHSSigned ? 1 : -1)) {
  1060. // The unsigned type has greater than or equal rank to the
  1061. // signed type, so use the unsigned type
  1062. if (RHSSigned) {
  1063. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1064. return LHSType;
  1065. } else if (!IsCompAssign)
  1066. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1067. return RHSType;
  1068. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1069. // The two types are different widths; if we are here, that
  1070. // means the signed type is larger than the unsigned type, so
  1071. // use the signed type.
  1072. if (LHSSigned) {
  1073. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1074. return LHSType;
  1075. } else if (!IsCompAssign)
  1076. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1077. return RHSType;
  1078. } else {
  1079. // The signed type is higher-ranked than the unsigned type,
  1080. // but isn't actually any bigger (like unsigned int and long
  1081. // on most 32-bit systems). Use the unsigned type corresponding
  1082. // to the signed type.
  1083. QualType result =
  1084. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1085. RHS = (*doRHSCast)(S, RHS.get(), result);
  1086. if (!IsCompAssign)
  1087. LHS = (*doLHSCast)(S, LHS.get(), result);
  1088. return result;
  1089. }
  1090. }
  1091. /// \brief Handle conversions with GCC complex int extension. Helper function
  1092. /// of UsualArithmeticConversions()
  1093. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1094. ExprResult &RHS, QualType LHSType,
  1095. QualType RHSType,
  1096. bool IsCompAssign) {
  1097. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1098. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1099. if (LHSComplexInt && RHSComplexInt) {
  1100. QualType LHSEltType = LHSComplexInt->getElementType();
  1101. QualType RHSEltType = RHSComplexInt->getElementType();
  1102. QualType ScalarType =
  1103. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1104. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1105. return S.Context.getComplexType(ScalarType);
  1106. }
  1107. if (LHSComplexInt) {
  1108. QualType LHSEltType = LHSComplexInt->getElementType();
  1109. QualType ScalarType =
  1110. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1111. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1112. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1113. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1114. CK_IntegralRealToComplex);
  1115. return ComplexType;
  1116. }
  1117. assert(RHSComplexInt);
  1118. QualType RHSEltType = RHSComplexInt->getElementType();
  1119. QualType ScalarType =
  1120. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1121. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1122. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1123. if (!IsCompAssign)
  1124. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1125. CK_IntegralRealToComplex);
  1126. return ComplexType;
  1127. }
  1128. /// UsualArithmeticConversions - Performs various conversions that are common to
  1129. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1130. /// routine returns the first non-arithmetic type found. The client is
  1131. /// responsible for emitting appropriate error diagnostics.
  1132. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1133. bool IsCompAssign) {
  1134. if (!IsCompAssign) {
  1135. LHS = UsualUnaryConversions(LHS.get());
  1136. if (LHS.isInvalid())
  1137. return QualType();
  1138. }
  1139. RHS = UsualUnaryConversions(RHS.get());
  1140. if (RHS.isInvalid())
  1141. return QualType();
  1142. // For conversion purposes, we ignore any qualifiers.
  1143. // For example, "const float" and "float" are equivalent.
  1144. QualType LHSType =
  1145. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1146. QualType RHSType =
  1147. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1148. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1149. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1150. LHSType = AtomicLHS->getValueType();
  1151. // If both types are identical, no conversion is needed.
  1152. if (LHSType == RHSType)
  1153. return LHSType;
  1154. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1155. // The caller can deal with this (e.g. pointer + int).
  1156. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1157. return QualType();
  1158. // Apply unary and bitfield promotions to the LHS's type.
  1159. QualType LHSUnpromotedType = LHSType;
  1160. if (LHSType->isPromotableIntegerType())
  1161. LHSType = Context.getPromotedIntegerType(LHSType);
  1162. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1163. if (!LHSBitfieldPromoteTy.isNull())
  1164. LHSType = LHSBitfieldPromoteTy;
  1165. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1166. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1167. // If both types are identical, no conversion is needed.
  1168. if (LHSType == RHSType)
  1169. return LHSType;
  1170. // At this point, we have two different arithmetic types.
  1171. // Handle complex types first (C99 6.3.1.8p1).
  1172. if (LHSType->isComplexType() || RHSType->isComplexType())
  1173. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1174. IsCompAssign);
  1175. // Now handle "real" floating types (i.e. float, double, long double).
  1176. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1177. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1178. IsCompAssign);
  1179. // Handle GCC complex int extension.
  1180. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1181. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1182. IsCompAssign);
  1183. // Finally, we have two differing integer types.
  1184. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1185. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1186. }
  1187. //===----------------------------------------------------------------------===//
  1188. // Semantic Analysis for various Expression Types
  1189. //===----------------------------------------------------------------------===//
  1190. ExprResult
  1191. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1192. SourceLocation DefaultLoc,
  1193. SourceLocation RParenLoc,
  1194. Expr *ControllingExpr,
  1195. ArrayRef<ParsedType> ArgTypes,
  1196. ArrayRef<Expr *> ArgExprs) {
  1197. unsigned NumAssocs = ArgTypes.size();
  1198. assert(NumAssocs == ArgExprs.size());
  1199. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1200. for (unsigned i = 0; i < NumAssocs; ++i) {
  1201. if (ArgTypes[i])
  1202. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1203. else
  1204. Types[i] = nullptr;
  1205. }
  1206. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1207. ControllingExpr,
  1208. llvm::makeArrayRef(Types, NumAssocs),
  1209. ArgExprs);
  1210. delete [] Types;
  1211. return ER;
  1212. }
  1213. ExprResult
  1214. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1215. SourceLocation DefaultLoc,
  1216. SourceLocation RParenLoc,
  1217. Expr *ControllingExpr,
  1218. ArrayRef<TypeSourceInfo *> Types,
  1219. ArrayRef<Expr *> Exprs) {
  1220. unsigned NumAssocs = Types.size();
  1221. assert(NumAssocs == Exprs.size());
  1222. if (ControllingExpr->getType()->isPlaceholderType()) {
  1223. ExprResult result = CheckPlaceholderExpr(ControllingExpr);
  1224. if (result.isInvalid()) return ExprError();
  1225. ControllingExpr = result.get();
  1226. }
  1227. // The controlling expression is an unevaluated operand, so side effects are
  1228. // likely unintended.
  1229. if (ActiveTemplateInstantiations.empty() &&
  1230. ControllingExpr->HasSideEffects(Context, false))
  1231. Diag(ControllingExpr->getExprLoc(),
  1232. diag::warn_side_effects_unevaluated_context);
  1233. bool TypeErrorFound = false,
  1234. IsResultDependent = ControllingExpr->isTypeDependent(),
  1235. ContainsUnexpandedParameterPack
  1236. = ControllingExpr->containsUnexpandedParameterPack();
  1237. for (unsigned i = 0; i < NumAssocs; ++i) {
  1238. if (Exprs[i]->containsUnexpandedParameterPack())
  1239. ContainsUnexpandedParameterPack = true;
  1240. if (Types[i]) {
  1241. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1242. ContainsUnexpandedParameterPack = true;
  1243. if (Types[i]->getType()->isDependentType()) {
  1244. IsResultDependent = true;
  1245. } else {
  1246. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1247. // complete object type other than a variably modified type."
  1248. unsigned D = 0;
  1249. if (Types[i]->getType()->isIncompleteType())
  1250. D = diag::err_assoc_type_incomplete;
  1251. else if (!Types[i]->getType()->isObjectType())
  1252. D = diag::err_assoc_type_nonobject;
  1253. else if (Types[i]->getType()->isVariablyModifiedType())
  1254. D = diag::err_assoc_type_variably_modified;
  1255. if (D != 0) {
  1256. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1257. << Types[i]->getTypeLoc().getSourceRange()
  1258. << Types[i]->getType();
  1259. TypeErrorFound = true;
  1260. }
  1261. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1262. // selection shall specify compatible types."
  1263. for (unsigned j = i+1; j < NumAssocs; ++j)
  1264. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1265. Context.typesAreCompatible(Types[i]->getType(),
  1266. Types[j]->getType())) {
  1267. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1268. diag::err_assoc_compatible_types)
  1269. << Types[j]->getTypeLoc().getSourceRange()
  1270. << Types[j]->getType()
  1271. << Types[i]->getType();
  1272. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1273. diag::note_compat_assoc)
  1274. << Types[i]->getTypeLoc().getSourceRange()
  1275. << Types[i]->getType();
  1276. TypeErrorFound = true;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. if (TypeErrorFound)
  1282. return ExprError();
  1283. // If we determined that the generic selection is result-dependent, don't
  1284. // try to compute the result expression.
  1285. if (IsResultDependent)
  1286. return new (Context) GenericSelectionExpr(
  1287. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1288. ContainsUnexpandedParameterPack);
  1289. SmallVector<unsigned, 1> CompatIndices;
  1290. unsigned DefaultIndex = -1U;
  1291. for (unsigned i = 0; i < NumAssocs; ++i) {
  1292. if (!Types[i])
  1293. DefaultIndex = i;
  1294. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1295. Types[i]->getType()))
  1296. CompatIndices.push_back(i);
  1297. }
  1298. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1299. // type compatible with at most one of the types named in its generic
  1300. // association list."
  1301. if (CompatIndices.size() > 1) {
  1302. // We strip parens here because the controlling expression is typically
  1303. // parenthesized in macro definitions.
  1304. ControllingExpr = ControllingExpr->IgnoreParens();
  1305. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1306. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1307. << (unsigned) CompatIndices.size();
  1308. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1309. E = CompatIndices.end(); I != E; ++I) {
  1310. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1311. diag::note_compat_assoc)
  1312. << Types[*I]->getTypeLoc().getSourceRange()
  1313. << Types[*I]->getType();
  1314. }
  1315. return ExprError();
  1316. }
  1317. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1318. // its controlling expression shall have type compatible with exactly one of
  1319. // the types named in its generic association list."
  1320. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1321. // We strip parens here because the controlling expression is typically
  1322. // parenthesized in macro definitions.
  1323. ControllingExpr = ControllingExpr->IgnoreParens();
  1324. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1325. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1326. return ExprError();
  1327. }
  1328. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1329. // type name that is compatible with the type of the controlling expression,
  1330. // then the result expression of the generic selection is the expression
  1331. // in that generic association. Otherwise, the result expression of the
  1332. // generic selection is the expression in the default generic association."
  1333. unsigned ResultIndex =
  1334. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1335. return new (Context) GenericSelectionExpr(
  1336. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1337. ContainsUnexpandedParameterPack, ResultIndex);
  1338. }
  1339. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1340. /// location of the token and the offset of the ud-suffix within it.
  1341. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1342. unsigned Offset) {
  1343. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1344. S.getLangOpts());
  1345. }
  1346. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1347. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1348. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1349. IdentifierInfo *UDSuffix,
  1350. SourceLocation UDSuffixLoc,
  1351. ArrayRef<Expr*> Args,
  1352. SourceLocation LitEndLoc) {
  1353. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1354. QualType ArgTy[2];
  1355. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1356. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1357. if (ArgTy[ArgIdx]->isArrayType())
  1358. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1359. }
  1360. DeclarationName OpName =
  1361. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1362. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1363. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1364. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1365. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1366. /*AllowRaw*/false, /*AllowTemplate*/false,
  1367. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1368. return ExprError();
  1369. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1370. }
  1371. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1372. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1373. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1374. /// multiple tokens. However, the common case is that StringToks points to one
  1375. /// string.
  1376. ///
  1377. ExprResult
  1378. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1379. assert(!StringToks.empty() && "Must have at least one string!");
  1380. StringLiteralParser Literal(StringToks, PP);
  1381. if (Literal.hadError)
  1382. return ExprError();
  1383. SmallVector<SourceLocation, 4> StringTokLocs;
  1384. for (unsigned i = 0; i != StringToks.size(); ++i)
  1385. StringTokLocs.push_back(StringToks[i].getLocation());
  1386. // HLSL Change Starts
  1387. if (getLangOpts().HLSL) {
  1388. assert(!Literal.isWide() && !Literal.isUTF16() && !Literal.isUTF32() && !Literal.isPascal()
  1389. && "HLSL parser always produces simple string literals");
  1390. QualType CharTyConst = Context.CharTy;
  1391. CharTyConst.addConst();
  1392. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1393. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1394. ArrayType::Normal, 0);
  1395. StringLiteral *Result = StringLiteral::Create(Context, Literal.GetString(), StringLiteral::StringKind::Ascii,
  1396. false, StrTy, &StringTokLocs[0], StringTokLocs.size());
  1397. return Result;
  1398. }
  1399. // HLSL Change Ends
  1400. QualType CharTy = Context.CharTy;
  1401. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1402. if (Literal.isWide()) {
  1403. CharTy = Context.getWideCharType();
  1404. Kind = StringLiteral::Wide;
  1405. } else if (Literal.isUTF8()) {
  1406. Kind = StringLiteral::UTF8;
  1407. } else if (Literal.isUTF16()) {
  1408. CharTy = Context.Char16Ty;
  1409. Kind = StringLiteral::UTF16;
  1410. } else if (Literal.isUTF32()) {
  1411. CharTy = Context.Char32Ty;
  1412. Kind = StringLiteral::UTF32;
  1413. } else if (Literal.isPascal()) {
  1414. CharTy = Context.UnsignedCharTy;
  1415. }
  1416. QualType CharTyConst = CharTy;
  1417. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1418. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1419. CharTyConst.addConst();
  1420. // Get an array type for the string, according to C99 6.4.5. This includes
  1421. // the nul terminator character as well as the string length for pascal
  1422. // strings.
  1423. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1424. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1425. ArrayType::Normal, 0);
  1426. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1427. if (getLangOpts().OpenCL) {
  1428. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1429. }
  1430. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1431. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1432. Kind, Literal.Pascal, StrTy,
  1433. &StringTokLocs[0],
  1434. StringTokLocs.size());
  1435. if (Literal.getUDSuffix().empty())
  1436. return Lit;
  1437. // We're building a user-defined literal.
  1438. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1439. SourceLocation UDSuffixLoc =
  1440. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1441. Literal.getUDSuffixOffset());
  1442. // Make sure we're allowed user-defined literals here.
  1443. if (!UDLScope)
  1444. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1445. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1446. // operator "" X (str, len)
  1447. QualType SizeType = Context.getSizeType();
  1448. DeclarationName OpName =
  1449. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1450. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1451. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1452. QualType ArgTy[] = {
  1453. Context.getArrayDecayedType(StrTy), SizeType
  1454. };
  1455. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1456. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1457. /*AllowRaw*/false, /*AllowTemplate*/false,
  1458. /*AllowStringTemplate*/true)) {
  1459. case LOLR_Cooked: {
  1460. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1461. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1462. StringTokLocs[0]);
  1463. Expr *Args[] = { Lit, LenArg };
  1464. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1465. }
  1466. case LOLR_StringTemplate: {
  1467. TemplateArgumentListInfo ExplicitArgs;
  1468. unsigned CharBits = Context.getIntWidth(CharTy);
  1469. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1470. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1471. TemplateArgument TypeArg(CharTy);
  1472. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1473. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1474. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1475. Value = Lit->getCodeUnit(I);
  1476. TemplateArgument Arg(Context, Value, CharTy);
  1477. TemplateArgumentLocInfo ArgInfo;
  1478. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1479. }
  1480. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1481. &ExplicitArgs);
  1482. }
  1483. case LOLR_Raw:
  1484. case LOLR_Template:
  1485. llvm_unreachable("unexpected literal operator lookup result");
  1486. case LOLR_Error:
  1487. return ExprError();
  1488. }
  1489. llvm_unreachable("unexpected literal operator lookup result");
  1490. }
  1491. ExprResult
  1492. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1493. SourceLocation Loc,
  1494. const CXXScopeSpec *SS) {
  1495. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1496. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1497. }
  1498. /// BuildDeclRefExpr - Build an expression that references a
  1499. /// declaration that does not require a closure capture.
  1500. ExprResult
  1501. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1502. const DeclarationNameInfo &NameInfo,
  1503. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1504. const TemplateArgumentListInfo *TemplateArgs) {
  1505. if (getLangOpts().CUDA)
  1506. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1507. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1508. if (CheckCUDATarget(Caller, Callee)) {
  1509. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1510. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1511. << IdentifyCUDATarget(Caller);
  1512. Diag(D->getLocation(), diag::note_previous_decl)
  1513. << D->getIdentifier();
  1514. return ExprError();
  1515. }
  1516. }
  1517. bool RefersToCapturedVariable =
  1518. isa<VarDecl>(D) &&
  1519. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1520. DeclRefExpr *E;
  1521. if (isa<VarTemplateSpecializationDecl>(D)) {
  1522. VarTemplateSpecializationDecl *VarSpec =
  1523. cast<VarTemplateSpecializationDecl>(D);
  1524. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1525. : NestedNameSpecifierLoc(),
  1526. VarSpec->getTemplateKeywordLoc(), D,
  1527. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1528. FoundD, TemplateArgs);
  1529. } else {
  1530. assert(!TemplateArgs && "No template arguments for non-variable"
  1531. " template specialization references");
  1532. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1533. : NestedNameSpecifierLoc(),
  1534. SourceLocation(), D, RefersToCapturedVariable,
  1535. NameInfo, Ty, VK, FoundD);
  1536. }
  1537. MarkDeclRefReferenced(E);
  1538. if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
  1539. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1540. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1541. recordUseOfEvaluatedWeak(E);
  1542. // Just in case we're building an illegal pointer-to-member.
  1543. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1544. if (FD && FD->isBitField())
  1545. E->setObjectKind(OK_BitField);
  1546. return E;
  1547. }
  1548. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1549. /// possibly a list of template arguments.
  1550. ///
  1551. /// If this produces template arguments, it is permitted to call
  1552. /// DecomposeTemplateName.
  1553. ///
  1554. /// This actually loses a lot of source location information for
  1555. /// non-standard name kinds; we should consider preserving that in
  1556. /// some way.
  1557. void
  1558. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1559. TemplateArgumentListInfo &Buffer,
  1560. DeclarationNameInfo &NameInfo,
  1561. const TemplateArgumentListInfo *&TemplateArgs) {
  1562. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1563. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1564. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1565. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1566. Id.TemplateId->NumArgs);
  1567. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1568. TemplateName TName = Id.TemplateId->Template.get();
  1569. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1570. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1571. TemplateArgs = &Buffer;
  1572. } else {
  1573. NameInfo = GetNameFromUnqualifiedId(Id);
  1574. TemplateArgs = nullptr;
  1575. }
  1576. }
  1577. static void emitEmptyLookupTypoDiagnostic(
  1578. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1579. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1580. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1581. DeclContext *Ctx =
  1582. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1583. if (!TC) {
  1584. // Emit a special diagnostic for failed member lookups.
  1585. // FIXME: computing the declaration context might fail here (?)
  1586. if (Ctx)
  1587. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1588. << SS.getRange();
  1589. else
  1590. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1591. return;
  1592. }
  1593. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1594. bool DroppedSpecifier =
  1595. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1596. unsigned NoteID =
  1597. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1598. ? diag::note_implicit_param_decl
  1599. : diag::note_previous_decl;
  1600. if (!Ctx)
  1601. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1602. SemaRef.PDiag(NoteID));
  1603. else
  1604. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1605. << Typo << Ctx << DroppedSpecifier
  1606. << SS.getRange(),
  1607. SemaRef.PDiag(NoteID));
  1608. }
  1609. /// Diagnose an empty lookup.
  1610. ///
  1611. /// \return false if new lookup candidates were found
  1612. bool
  1613. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1614. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1615. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1616. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1617. DeclarationName Name = R.getLookupName();
  1618. unsigned diagnostic = diag::err_undeclared_var_use;
  1619. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1620. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1621. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1622. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1623. diagnostic = diag::err_undeclared_use;
  1624. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1625. }
  1626. // If the original lookup was an unqualified lookup, fake an
  1627. // unqualified lookup. This is useful when (for example) the
  1628. // original lookup would not have found something because it was a
  1629. // dependent name.
  1630. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1631. ? CurContext : nullptr;
  1632. while (DC) {
  1633. if (isa<CXXRecordDecl>(DC)) {
  1634. LookupQualifiedName(R, DC);
  1635. if (!R.empty()) {
  1636. // Don't give errors about ambiguities in this lookup.
  1637. R.suppressDiagnostics();
  1638. // During a default argument instantiation the CurContext points
  1639. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1640. // function parameter list, hence add an explicit check.
  1641. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1642. ActiveTemplateInstantiations.back().Kind ==
  1643. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1644. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1645. bool isInstance = CurMethod &&
  1646. CurMethod->isInstance() &&
  1647. DC == CurMethod->getParent() && !isDefaultArgument;
  1648. // Give a code modification hint to insert 'this->'.
  1649. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1650. // Actually quite difficult!
  1651. if (getLangOpts().MSVCCompat)
  1652. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1653. if (isInstance) {
  1654. Diag(R.getNameLoc(), diagnostic) << Name
  1655. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1656. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1657. CallsUndergoingInstantiation.back()->getCallee());
  1658. CXXMethodDecl *DepMethod;
  1659. if (CurMethod->isDependentContext())
  1660. DepMethod = CurMethod;
  1661. else if (CurMethod->getTemplatedKind() ==
  1662. FunctionDecl::TK_FunctionTemplateSpecialization)
  1663. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1664. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1665. else
  1666. DepMethod = cast<CXXMethodDecl>(
  1667. CurMethod->getInstantiatedFromMemberFunction());
  1668. assert(DepMethod && "No template pattern found");
  1669. QualType DepThisType = DepMethod->getThisType(Context);
  1670. CheckCXXThisCapture(R.getNameLoc());
  1671. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1672. R.getNameLoc(), DepThisType, false);
  1673. TemplateArgumentListInfo TList;
  1674. if (ULE->hasExplicitTemplateArgs())
  1675. ULE->copyTemplateArgumentsInto(TList);
  1676. CXXScopeSpec SS;
  1677. SS.Adopt(ULE->getQualifierLoc());
  1678. CXXDependentScopeMemberExpr *DepExpr =
  1679. CXXDependentScopeMemberExpr::Create(
  1680. Context, DepThis, DepThisType, true, SourceLocation(),
  1681. SS.getWithLocInContext(Context),
  1682. ULE->getTemplateKeywordLoc(), nullptr,
  1683. R.getLookupNameInfo(),
  1684. ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
  1685. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1686. } else {
  1687. Diag(R.getNameLoc(), diagnostic) << Name;
  1688. }
  1689. // Do we really want to note all of these?
  1690. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1691. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1692. // Return true if we are inside a default argument instantiation
  1693. // and the found name refers to an instance member function, otherwise
  1694. // the function calling DiagnoseEmptyLookup will try to create an
  1695. // implicit member call and this is wrong for default argument.
  1696. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1697. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1698. return true;
  1699. }
  1700. // Tell the callee to try to recover.
  1701. return false;
  1702. }
  1703. R.clear();
  1704. }
  1705. // In Microsoft mode, if we are performing lookup from within a friend
  1706. // function definition declared at class scope then we must set
  1707. // DC to the lexical parent to be able to search into the parent
  1708. // class.
  1709. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1710. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1711. DC->getLexicalParent()->isRecord())
  1712. DC = DC->getLexicalParent();
  1713. else
  1714. DC = DC->getParent();
  1715. }
  1716. // We didn't find anything, so try to correct for a typo.
  1717. TypoCorrection Corrected;
  1718. if (S && Out) {
  1719. SourceLocation TypoLoc = R.getNameLoc();
  1720. assert(!ExplicitTemplateArgs &&
  1721. "Diagnosing an empty lookup with explicit template args!");
  1722. *Out = CorrectTypoDelayed(
  1723. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1724. [=](const TypoCorrection &TC) {
  1725. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1726. diagnostic, diagnostic_suggest);
  1727. },
  1728. nullptr, CTK_ErrorRecovery);
  1729. if (*Out)
  1730. return true;
  1731. } else if (S && (Corrected =
  1732. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1733. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1734. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1735. bool DroppedSpecifier =
  1736. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1737. R.setLookupName(Corrected.getCorrection());
  1738. bool AcceptableWithRecovery = false;
  1739. bool AcceptableWithoutRecovery = false;
  1740. NamedDecl *ND = Corrected.getCorrectionDecl();
  1741. if (ND) {
  1742. if (Corrected.isOverloaded()) {
  1743. OverloadCandidateSet OCS(R.getNameLoc(),
  1744. OverloadCandidateSet::CSK_Normal);
  1745. OverloadCandidateSet::iterator Best;
  1746. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1747. CDEnd = Corrected.end();
  1748. CD != CDEnd; ++CD) {
  1749. if (FunctionTemplateDecl *FTD =
  1750. dyn_cast<FunctionTemplateDecl>(*CD))
  1751. AddTemplateOverloadCandidate(
  1752. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1753. Args, OCS);
  1754. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1755. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1756. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1757. Args, OCS);
  1758. }
  1759. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1760. case OR_Success:
  1761. ND = Best->Function;
  1762. Corrected.setCorrectionDecl(ND);
  1763. break;
  1764. default:
  1765. // FIXME: Arbitrarily pick the first declaration for the note.
  1766. Corrected.setCorrectionDecl(ND);
  1767. break;
  1768. }
  1769. }
  1770. R.addDecl(ND);
  1771. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1772. CXXRecordDecl *Record = nullptr;
  1773. if (Corrected.getCorrectionSpecifier()) {
  1774. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1775. Record = Ty->getAsCXXRecordDecl();
  1776. }
  1777. if (!Record)
  1778. Record = cast<CXXRecordDecl>(
  1779. ND->getDeclContext()->getRedeclContext());
  1780. R.setNamingClass(Record);
  1781. }
  1782. AcceptableWithRecovery =
  1783. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1784. // FIXME: If we ended up with a typo for a type name or
  1785. // Objective-C class name, we're in trouble because the parser
  1786. // is in the wrong place to recover. Suggest the typo
  1787. // correction, but don't make it a fix-it since we're not going
  1788. // to recover well anyway.
  1789. AcceptableWithoutRecovery =
  1790. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1791. } else {
  1792. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1793. // because we aren't able to recover.
  1794. AcceptableWithoutRecovery = true;
  1795. }
  1796. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1797. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1798. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1799. ? diag::note_implicit_param_decl
  1800. : diag::note_previous_decl;
  1801. if (SS.isEmpty())
  1802. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1803. PDiag(NoteID), AcceptableWithRecovery);
  1804. else
  1805. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1806. << Name << computeDeclContext(SS, false)
  1807. << DroppedSpecifier << SS.getRange(),
  1808. PDiag(NoteID), AcceptableWithRecovery);
  1809. // Tell the callee whether to try to recover.
  1810. return !AcceptableWithRecovery;
  1811. }
  1812. }
  1813. R.clear();
  1814. // Emit a special diagnostic for failed member lookups.
  1815. // FIXME: computing the declaration context might fail here (?)
  1816. if (!SS.isEmpty()) {
  1817. Diag(R.getNameLoc(), diag::err_no_member)
  1818. << Name << computeDeclContext(SS, false)
  1819. << SS.getRange();
  1820. return true;
  1821. }
  1822. // Give up, we can't recover.
  1823. Diag(R.getNameLoc(), diagnostic) << Name;
  1824. return true;
  1825. }
  1826. /// In Microsoft mode, if we are inside a template class whose parent class has
  1827. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1828. /// assume the identifier is a member of a dependent base class. We can only
  1829. /// recover successfully in static methods, instance methods, and other contexts
  1830. /// where 'this' is available. This doesn't precisely match MSVC's
  1831. /// instantiation model, but it's close enough.
  1832. static Expr *
  1833. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1834. DeclarationNameInfo &NameInfo,
  1835. SourceLocation TemplateKWLoc,
  1836. const TemplateArgumentListInfo *TemplateArgs) {
  1837. // Only try to recover from lookup into dependent bases in static methods or
  1838. // contexts where 'this' is available.
  1839. QualType ThisType = S.getCurrentThisType();
  1840. const CXXRecordDecl *RD = nullptr;
  1841. if (!ThisType.isNull())
  1842. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1843. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1844. RD = MD->getParent();
  1845. if (!RD || !RD->hasAnyDependentBases())
  1846. return nullptr;
  1847. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1848. // is available, suggest inserting 'this->' as a fixit.
  1849. SourceLocation Loc = NameInfo.getLoc();
  1850. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1851. DB << NameInfo.getName() << RD;
  1852. if (!ThisType.isNull()) {
  1853. DB << FixItHint::CreateInsertion(Loc, "this->");
  1854. return CXXDependentScopeMemberExpr::Create(
  1855. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1856. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1857. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1858. }
  1859. // Synthesize a fake NNS that points to the derived class. This will
  1860. // perform name lookup during template instantiation.
  1861. CXXScopeSpec SS;
  1862. auto *NNS =
  1863. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1864. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1865. return DependentScopeDeclRefExpr::Create(
  1866. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1867. TemplateArgs);
  1868. }
  1869. ExprResult
  1870. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1871. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1872. bool HasTrailingLParen, bool IsAddressOfOperand,
  1873. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1874. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1875. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1876. "cannot be direct & operand and have a trailing lparen");
  1877. if (SS.isInvalid())
  1878. return ExprError();
  1879. TemplateArgumentListInfo TemplateArgsBuffer;
  1880. // Decompose the UnqualifiedId into the following data.
  1881. DeclarationNameInfo NameInfo;
  1882. const TemplateArgumentListInfo *TemplateArgs;
  1883. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1884. DeclarationName Name = NameInfo.getName();
  1885. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1886. SourceLocation NameLoc = NameInfo.getLoc();
  1887. // C++ [temp.dep.expr]p3:
  1888. // An id-expression is type-dependent if it contains:
  1889. // -- an identifier that was declared with a dependent type,
  1890. // (note: handled after lookup)
  1891. // -- a template-id that is dependent,
  1892. // (note: handled in BuildTemplateIdExpr)
  1893. // -- a conversion-function-id that specifies a dependent type,
  1894. // -- a nested-name-specifier that contains a class-name that
  1895. // names a dependent type.
  1896. // Determine whether this is a member of an unknown specialization;
  1897. // we need to handle these differently.
  1898. bool DependentID = false;
  1899. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1900. Name.getCXXNameType()->isDependentType()) {
  1901. DependentID = true;
  1902. } else if (SS.isSet()) {
  1903. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1904. if (RequireCompleteDeclContext(SS, DC))
  1905. return ExprError();
  1906. } else {
  1907. DependentID = true;
  1908. }
  1909. }
  1910. if (DependentID)
  1911. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1912. IsAddressOfOperand, TemplateArgs);
  1913. // Perform the required lookup.
  1914. LookupResult R(*this, NameInfo,
  1915. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1916. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1917. if (TemplateArgs) {
  1918. // Lookup the template name again to correctly establish the context in
  1919. // which it was found. This is really unfortunate as we already did the
  1920. // lookup to determine that it was a template name in the first place. If
  1921. // this becomes a performance hit, we can work harder to preserve those
  1922. // results until we get here but it's likely not worth it.
  1923. bool MemberOfUnknownSpecialization;
  1924. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1925. MemberOfUnknownSpecialization);
  1926. if (MemberOfUnknownSpecialization ||
  1927. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1928. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1929. IsAddressOfOperand, TemplateArgs);
  1930. } else {
  1931. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1932. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1933. // If the result might be in a dependent base class, this is a dependent
  1934. // id-expression.
  1935. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1936. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1937. IsAddressOfOperand, TemplateArgs);
  1938. // If this reference is in an Objective-C method, then we need to do
  1939. // some special Objective-C lookup, too.
  1940. if (IvarLookupFollowUp) {
  1941. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1942. if (E.isInvalid())
  1943. return ExprError();
  1944. if (Expr *Ex = E.getAs<Expr>())
  1945. return Ex;
  1946. }
  1947. }
  1948. if (R.isAmbiguous())
  1949. return ExprError();
  1950. // This could be an implicitly declared function reference (legal in C90,
  1951. // extension in C99, forbidden in C++).
  1952. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1953. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1954. if (D) R.addDecl(D);
  1955. }
  1956. // Determine whether this name might be a candidate for
  1957. // argument-dependent lookup.
  1958. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1959. if (R.empty() && !ADL) {
  1960. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1961. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1962. TemplateKWLoc, TemplateArgs))
  1963. return E;
  1964. }
  1965. // Don't diagnose an empty lookup for inline assembly.
  1966. if (IsInlineAsmIdentifier)
  1967. return ExprError();
  1968. // If this name wasn't predeclared and if this is not a function
  1969. // call, diagnose the problem.
  1970. TypoExpr *TE = nullptr;
  1971. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1972. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1973. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1974. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1975. "Typo correction callback misconfigured");
  1976. if (CCC) {
  1977. // Make sure the callback knows what the typo being diagnosed is.
  1978. CCC->setTypoName(II);
  1979. if (SS.isValid())
  1980. CCC->setTypoNNS(SS.getScopeRep());
  1981. }
  1982. if (DiagnoseEmptyLookup(S, SS, R,
  1983. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1984. nullptr, None, &TE)) {
  1985. if (TE && KeywordReplacement) {
  1986. auto &State = getTypoExprState(TE);
  1987. auto BestTC = State.Consumer->getNextCorrection();
  1988. if (BestTC.isKeyword()) {
  1989. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1990. if (State.DiagHandler)
  1991. State.DiagHandler(BestTC);
  1992. KeywordReplacement->startToken();
  1993. KeywordReplacement->setKind(II->getTokenID());
  1994. KeywordReplacement->setIdentifierInfo(II);
  1995. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1996. // Clean up the state associated with the TypoExpr, since it has
  1997. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1998. clearDelayedTypo(TE);
  1999. // Signal that a correction to a keyword was performed by returning a
  2000. // valid-but-null ExprResult.
  2001. return (Expr*)nullptr;
  2002. }
  2003. State.Consumer->resetCorrectionStream();
  2004. }
  2005. return TE ? TE : ExprError();
  2006. }
  2007. assert(!R.empty() &&
  2008. "DiagnoseEmptyLookup returned false but added no results");
  2009. // If we found an Objective-C instance variable, let
  2010. // LookupInObjCMethod build the appropriate expression to
  2011. // reference the ivar.
  2012. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2013. R.clear();
  2014. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2015. // In a hopelessly buggy code, Objective-C instance variable
  2016. // lookup fails and no expression will be built to reference it.
  2017. if (!E.isInvalid() && !E.get())
  2018. return ExprError();
  2019. return E;
  2020. }
  2021. }
  2022. // This is guaranteed from this point on.
  2023. assert(!R.empty() || ADL);
  2024. // Check whether this might be a C++ implicit instance member access.
  2025. // C++ [class.mfct.non-static]p3:
  2026. // When an id-expression that is not part of a class member access
  2027. // syntax and not used to form a pointer to member is used in the
  2028. // body of a non-static member function of class X, if name lookup
  2029. // resolves the name in the id-expression to a non-static non-type
  2030. // member of some class C, the id-expression is transformed into a
  2031. // class member access expression using (*this) as the
  2032. // postfix-expression to the left of the . operator.
  2033. //
  2034. // But we don't actually need to do this for '&' operands if R
  2035. // resolved to a function or overloaded function set, because the
  2036. // expression is ill-formed if it actually works out to be a
  2037. // non-static member function:
  2038. //
  2039. // C++ [expr.ref]p4:
  2040. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2041. // [t]he expression can be used only as the left-hand operand of a
  2042. // member function call.
  2043. //
  2044. // There are other safeguards against such uses, but it's important
  2045. // to get this right here so that we don't end up making a
  2046. // spuriously dependent expression if we're inside a dependent
  2047. // instance method.
  2048. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2049. bool MightBeImplicitMember;
  2050. if (!IsAddressOfOperand)
  2051. MightBeImplicitMember = true;
  2052. else if (!SS.isEmpty())
  2053. MightBeImplicitMember = false;
  2054. else if (R.isOverloadedResult())
  2055. MightBeImplicitMember = false;
  2056. else if (R.isUnresolvableResult())
  2057. MightBeImplicitMember = true;
  2058. else
  2059. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2060. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2061. isa<MSPropertyDecl>(R.getFoundDecl());
  2062. if (MightBeImplicitMember)
  2063. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2064. R, TemplateArgs);
  2065. }
  2066. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2067. // In C++1y, if this is a variable template id, then check it
  2068. // in BuildTemplateIdExpr().
  2069. // The single lookup result must be a variable template declaration.
  2070. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  2071. Id.TemplateId->Kind == TNK_Var_template) {
  2072. assert(R.getAsSingle<VarTemplateDecl>() &&
  2073. "There should only be one declaration found.");
  2074. }
  2075. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2076. }
  2077. return BuildDeclarationNameExpr(SS, R, ADL);
  2078. }
  2079. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2080. /// declaration name, generally during template instantiation.
  2081. /// There's a large number of things which don't need to be done along
  2082. /// this path.
  2083. ExprResult
  2084. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  2085. const DeclarationNameInfo &NameInfo,
  2086. bool IsAddressOfOperand,
  2087. TypeSourceInfo **RecoveryTSI) {
  2088. DeclContext *DC = computeDeclContext(SS, false);
  2089. if (!DC)
  2090. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2091. NameInfo, /*TemplateArgs=*/nullptr);
  2092. if (RequireCompleteDeclContext(SS, DC))
  2093. return ExprError();
  2094. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2095. LookupQualifiedName(R, DC);
  2096. if (R.isAmbiguous())
  2097. return ExprError();
  2098. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2099. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2100. NameInfo, /*TemplateArgs=*/nullptr);
  2101. if (R.empty()) {
  2102. Diag(NameInfo.getLoc(), diag::err_no_member)
  2103. << NameInfo.getName() << DC << SS.getRange();
  2104. return ExprError();
  2105. }
  2106. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2107. // Diagnose a missing typename if this resolved unambiguously to a type in
  2108. // a dependent context. If we can recover with a type, downgrade this to
  2109. // a warning in Microsoft compatibility mode.
  2110. unsigned DiagID = diag::err_typename_missing;
  2111. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2112. DiagID = diag::ext_typename_missing;
  2113. SourceLocation Loc = SS.getBeginLoc();
  2114. auto D = Diag(Loc, DiagID);
  2115. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2116. << SourceRange(Loc, NameInfo.getEndLoc());
  2117. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2118. // context.
  2119. if (!RecoveryTSI)
  2120. return ExprError();
  2121. // Only issue the fixit if we're prepared to recover.
  2122. D << FixItHint::CreateInsertion(Loc, "typename ");
  2123. // Recover by pretending this was an elaborated type.
  2124. QualType Ty = Context.getTypeDeclType(TD);
  2125. TypeLocBuilder TLB;
  2126. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2127. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2128. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2129. QTL.setElaboratedKeywordLoc(SourceLocation());
  2130. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2131. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2132. return ExprEmpty();
  2133. }
  2134. // Defend against this resolving to an implicit member access. We usually
  2135. // won't get here if this might be a legitimate a class member (we end up in
  2136. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2137. // a pointer-to-member or in an unevaluated context in C++11.
  2138. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2139. return BuildPossibleImplicitMemberExpr(SS,
  2140. /*TemplateKWLoc=*/SourceLocation(),
  2141. R, /*TemplateArgs=*/nullptr);
  2142. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2143. }
  2144. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2145. /// detected that we're currently inside an ObjC method. Perform some
  2146. /// additional lookup.
  2147. ///
  2148. /// Ideally, most of this would be done by lookup, but there's
  2149. /// actually quite a lot of extra work involved.
  2150. ///
  2151. /// Returns a null sentinel to indicate trivial success.
  2152. ExprResult
  2153. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2154. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2155. SourceLocation Loc = Lookup.getNameLoc();
  2156. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2157. // Check for error condition which is already reported.
  2158. if (!CurMethod)
  2159. return ExprError();
  2160. // There are two cases to handle here. 1) scoped lookup could have failed,
  2161. // in which case we should look for an ivar. 2) scoped lookup could have
  2162. // found a decl, but that decl is outside the current instance method (i.e.
  2163. // a global variable). In these two cases, we do a lookup for an ivar with
  2164. // this name, if the lookup sucedes, we replace it our current decl.
  2165. // If we're in a class method, we don't normally want to look for
  2166. // ivars. But if we don't find anything else, and there's an
  2167. // ivar, that's an error.
  2168. bool IsClassMethod = CurMethod->isClassMethod();
  2169. bool LookForIvars;
  2170. if (Lookup.empty())
  2171. LookForIvars = true;
  2172. else if (IsClassMethod)
  2173. LookForIvars = false;
  2174. else
  2175. LookForIvars = (Lookup.isSingleResult() &&
  2176. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2177. ObjCInterfaceDecl *IFace = nullptr;
  2178. if (LookForIvars) {
  2179. IFace = CurMethod->getClassInterface();
  2180. ObjCInterfaceDecl *ClassDeclared;
  2181. ObjCIvarDecl *IV = nullptr;
  2182. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2183. // Diagnose using an ivar in a class method.
  2184. if (IsClassMethod)
  2185. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2186. << IV->getDeclName());
  2187. // If we're referencing an invalid decl, just return this as a silent
  2188. // error node. The error diagnostic was already emitted on the decl.
  2189. if (IV->isInvalidDecl())
  2190. return ExprError();
  2191. // Check if referencing a field with __attribute__((deprecated)).
  2192. if (DiagnoseUseOfDecl(IV, Loc))
  2193. return ExprError();
  2194. // Diagnose the use of an ivar outside of the declaring class.
  2195. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2196. !declaresSameEntity(ClassDeclared, IFace) &&
  2197. !getLangOpts().DebuggerSupport)
  2198. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2199. // FIXME: This should use a new expr for a direct reference, don't
  2200. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2201. IdentifierInfo &II = Context.Idents.get("self");
  2202. UnqualifiedId SelfName;
  2203. SelfName.setIdentifier(&II, SourceLocation());
  2204. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2205. CXXScopeSpec SelfScopeSpec;
  2206. SourceLocation TemplateKWLoc;
  2207. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2208. SelfName, false, false);
  2209. if (SelfExpr.isInvalid())
  2210. return ExprError();
  2211. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2212. if (SelfExpr.isInvalid())
  2213. return ExprError();
  2214. MarkAnyDeclReferenced(Loc, IV, true);
  2215. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2216. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2217. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2218. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2219. ObjCIvarRefExpr *Result = new (Context)
  2220. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2221. IV->getLocation(), SelfExpr.get(), true, true);
  2222. if (getLangOpts().ObjCAutoRefCount) {
  2223. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2224. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2225. recordUseOfEvaluatedWeak(Result);
  2226. }
  2227. if (CurContext->isClosure())
  2228. Diag(Loc, diag::warn_implicitly_retains_self)
  2229. << FixItHint::CreateInsertion(Loc, "self->");
  2230. }
  2231. return Result;
  2232. }
  2233. } else if (CurMethod->isInstanceMethod()) {
  2234. // We should warn if a local variable hides an ivar.
  2235. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2236. ObjCInterfaceDecl *ClassDeclared;
  2237. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2238. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2239. declaresSameEntity(IFace, ClassDeclared))
  2240. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2241. }
  2242. }
  2243. } else if (Lookup.isSingleResult() &&
  2244. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2245. // If accessing a stand-alone ivar in a class method, this is an error.
  2246. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2247. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2248. << IV->getDeclName());
  2249. }
  2250. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2251. // FIXME. Consolidate this with similar code in LookupName.
  2252. if (unsigned BuiltinID = II->getBuiltinID()) {
  2253. if (!(getLangOpts().CPlusPlus &&
  2254. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2255. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2256. S, Lookup.isForRedeclaration(),
  2257. Lookup.getNameLoc());
  2258. if (D) Lookup.addDecl(D);
  2259. }
  2260. }
  2261. }
  2262. // Sentinel value saying that we didn't do anything special.
  2263. return ExprResult((Expr *)nullptr);
  2264. }
  2265. /// \brief Cast a base object to a member's actual type.
  2266. ///
  2267. /// Logically this happens in three phases:
  2268. ///
  2269. /// * First we cast from the base type to the naming class.
  2270. /// The naming class is the class into which we were looking
  2271. /// when we found the member; it's the qualifier type if a
  2272. /// qualifier was provided, and otherwise it's the base type.
  2273. ///
  2274. /// * Next we cast from the naming class to the declaring class.
  2275. /// If the member we found was brought into a class's scope by
  2276. /// a using declaration, this is that class; otherwise it's
  2277. /// the class declaring the member.
  2278. ///
  2279. /// * Finally we cast from the declaring class to the "true"
  2280. /// declaring class of the member. This conversion does not
  2281. /// obey access control.
  2282. ExprResult
  2283. Sema::PerformObjectMemberConversion(Expr *From,
  2284. NestedNameSpecifier *Qualifier,
  2285. NamedDecl *FoundDecl,
  2286. NamedDecl *Member) {
  2287. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2288. if (!RD)
  2289. return From;
  2290. QualType DestRecordType;
  2291. QualType DestType;
  2292. QualType FromRecordType;
  2293. QualType FromType = From->getType();
  2294. bool PointerConversions = false;
  2295. if (isa<FieldDecl>(Member)) {
  2296. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2297. if (FromType->getAs<PointerType>()) {
  2298. DestType = Context.getPointerType(DestRecordType);
  2299. FromRecordType = FromType->getPointeeType();
  2300. PointerConversions = true;
  2301. } else {
  2302. DestType = DestRecordType;
  2303. FromRecordType = FromType;
  2304. }
  2305. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2306. if (Method->isStatic())
  2307. return From;
  2308. DestType = Method->getThisType(Context);
  2309. DestRecordType = DestType->getPointeeType();
  2310. if (FromType->getAs<PointerType>()) {
  2311. FromRecordType = FromType->getPointeeType();
  2312. PointerConversions = true;
  2313. } else {
  2314. FromRecordType = FromType;
  2315. DestType = DestRecordType;
  2316. }
  2317. } else {
  2318. // No conversion necessary.
  2319. return From;
  2320. }
  2321. if (DestType->isDependentType() || FromType->isDependentType())
  2322. return From;
  2323. // If the unqualified types are the same, no conversion is necessary.
  2324. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2325. return From;
  2326. SourceRange FromRange = From->getSourceRange();
  2327. SourceLocation FromLoc = FromRange.getBegin();
  2328. ExprValueKind VK = From->getValueKind();
  2329. // C++ [class.member.lookup]p8:
  2330. // [...] Ambiguities can often be resolved by qualifying a name with its
  2331. // class name.
  2332. //
  2333. // If the member was a qualified name and the qualified referred to a
  2334. // specific base subobject type, we'll cast to that intermediate type
  2335. // first and then to the object in which the member is declared. That allows
  2336. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2337. //
  2338. // class Base { public: int x; };
  2339. // class Derived1 : public Base { };
  2340. // class Derived2 : public Base { };
  2341. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2342. //
  2343. // void VeryDerived::f() {
  2344. // x = 17; // error: ambiguous base subobjects
  2345. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2346. // }
  2347. if (Qualifier && Qualifier->getAsType()) {
  2348. QualType QType = QualType(Qualifier->getAsType(), 0);
  2349. assert(QType->isRecordType() && "lookup done with non-record type");
  2350. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2351. // In C++98, the qualifier type doesn't actually have to be a base
  2352. // type of the object type, in which case we just ignore it.
  2353. // Otherwise build the appropriate casts.
  2354. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2355. CXXCastPath BasePath;
  2356. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2357. FromLoc, FromRange, &BasePath))
  2358. return ExprError();
  2359. if (PointerConversions)
  2360. QType = Context.getPointerType(QType);
  2361. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2362. VK, &BasePath).get();
  2363. FromType = QType;
  2364. FromRecordType = QRecordType;
  2365. // If the qualifier type was the same as the destination type,
  2366. // we're done.
  2367. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2368. return From;
  2369. }
  2370. }
  2371. bool IgnoreAccess = false;
  2372. // If we actually found the member through a using declaration, cast
  2373. // down to the using declaration's type.
  2374. //
  2375. // Pointer equality is fine here because only one declaration of a
  2376. // class ever has member declarations.
  2377. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2378. assert(isa<UsingShadowDecl>(FoundDecl));
  2379. QualType URecordType = Context.getTypeDeclType(
  2380. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2381. // We only need to do this if the naming-class to declaring-class
  2382. // conversion is non-trivial.
  2383. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2384. assert(IsDerivedFrom(FromRecordType, URecordType));
  2385. CXXCastPath BasePath;
  2386. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2387. FromLoc, FromRange, &BasePath))
  2388. return ExprError();
  2389. QualType UType = URecordType;
  2390. if (PointerConversions)
  2391. UType = Context.getPointerType(UType);
  2392. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2393. VK, &BasePath).get();
  2394. FromType = UType;
  2395. FromRecordType = URecordType;
  2396. }
  2397. // We don't do access control for the conversion from the
  2398. // declaring class to the true declaring class.
  2399. IgnoreAccess = true;
  2400. }
  2401. CXXCastPath BasePath;
  2402. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2403. FromLoc, FromRange, &BasePath,
  2404. IgnoreAccess))
  2405. return ExprError();
  2406. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2407. VK, &BasePath);
  2408. }
  2409. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2410. const LookupResult &R,
  2411. bool HasTrailingLParen) {
  2412. // Only when used directly as the postfix-expression of a call.
  2413. if (!HasTrailingLParen)
  2414. return false;
  2415. // Never if a scope specifier was provided.
  2416. if (SS.isSet()) {
  2417. // HLSL Change begins
  2418. // We want to be able to have intrinsics inside the "vk" namespace.
  2419. const bool isVkNamespace =
  2420. SS.getScopeRep() && SS.getScopeRep()->getAsNamespace() &&
  2421. SS.getScopeRep()->getAsNamespace()->getName() == "vk";
  2422. if (!isVkNamespace)
  2423. // HLSL Change ends
  2424. return false;
  2425. }
  2426. // Only in C++ or ObjC++.
  2427. if (!getLangOpts().CPlusPlus)
  2428. return false;
  2429. // Turn off ADL when we find certain kinds of declarations during
  2430. // normal lookup:
  2431. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2432. NamedDecl *D = *I;
  2433. // C++0x [basic.lookup.argdep]p3:
  2434. // -- a declaration of a class member
  2435. // Since using decls preserve this property, we check this on the
  2436. // original decl.
  2437. if (D->isCXXClassMember())
  2438. return false;
  2439. // C++0x [basic.lookup.argdep]p3:
  2440. // -- a block-scope function declaration that is not a
  2441. // using-declaration
  2442. // NOTE: we also trigger this for function templates (in fact, we
  2443. // don't check the decl type at all, since all other decl types
  2444. // turn off ADL anyway).
  2445. if (isa<UsingShadowDecl>(D))
  2446. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2447. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2448. return false;
  2449. // C++0x [basic.lookup.argdep]p3:
  2450. // -- a declaration that is neither a function or a function
  2451. // template
  2452. // And also for builtin functions.
  2453. if (isa<FunctionDecl>(D)) {
  2454. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2455. // But also builtin functions.
  2456. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2457. return false;
  2458. } else if (!isa<FunctionTemplateDecl>(D))
  2459. return false;
  2460. }
  2461. return true;
  2462. }
  2463. /// Diagnoses obvious problems with the use of the given declaration
  2464. /// as an expression. This is only actually called for lookups that
  2465. /// were not overloaded, and it doesn't promise that the declaration
  2466. /// will in fact be used.
  2467. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2468. if (isa<TypedefNameDecl>(D)) {
  2469. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2470. return true;
  2471. }
  2472. if (isa<ObjCInterfaceDecl>(D)) {
  2473. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2474. return true;
  2475. }
  2476. if (isa<NamespaceDecl>(D)) {
  2477. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2478. return true;
  2479. }
  2480. return false;
  2481. }
  2482. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2483. LookupResult &R, bool NeedsADL,
  2484. bool AcceptInvalidDecl) {
  2485. // If this is a single, fully-resolved result and we don't need ADL,
  2486. // just build an ordinary singleton decl ref.
  2487. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2488. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2489. R.getRepresentativeDecl(), nullptr,
  2490. AcceptInvalidDecl);
  2491. // We only need to check the declaration if there's exactly one
  2492. // result, because in the overloaded case the results can only be
  2493. // functions and function templates.
  2494. if (R.isSingleResult() &&
  2495. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2496. return ExprError();
  2497. // Otherwise, just build an unresolved lookup expression. Suppress
  2498. // any lookup-related diagnostics; we'll hash these out later, when
  2499. // we've picked a target.
  2500. R.suppressDiagnostics();
  2501. UnresolvedLookupExpr *ULE
  2502. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2503. SS.getWithLocInContext(Context),
  2504. R.getLookupNameInfo(),
  2505. NeedsADL, R.isOverloadedResult(),
  2506. R.begin(), R.end());
  2507. return ULE;
  2508. }
  2509. /// \brief Complete semantic analysis for a reference to the given declaration.
  2510. ExprResult Sema::BuildDeclarationNameExpr(
  2511. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2512. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2513. bool AcceptInvalidDecl) {
  2514. assert(D && "Cannot refer to a NULL declaration");
  2515. assert(!isa<FunctionTemplateDecl>(D) &&
  2516. "Cannot refer unambiguously to a function template");
  2517. SourceLocation Loc = NameInfo.getLoc();
  2518. if (CheckDeclInExpr(*this, Loc, D))
  2519. return ExprError();
  2520. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2521. // Specifically diagnose references to class templates that are missing
  2522. // a template argument list.
  2523. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2524. << Template << SS.getRange();
  2525. if (Template->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  2526. Diag(Template->getLocation(), diag::note_template_decl_here);
  2527. }
  2528. return ExprError();
  2529. }
  2530. // Make sure that we're referring to a value.
  2531. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2532. if (!VD) {
  2533. Diag(Loc, diag::err_ref_non_value)
  2534. << D << SS.getRange();
  2535. Diag(D->getLocation(), diag::note_declared_at);
  2536. return ExprError();
  2537. }
  2538. // Check whether this declaration can be used. Note that we suppress
  2539. // this check when we're going to perform argument-dependent lookup
  2540. // on this function name, because this might not be the function
  2541. // that overload resolution actually selects.
  2542. if (DiagnoseUseOfDecl(VD, Loc))
  2543. return ExprError();
  2544. // Only create DeclRefExpr's for valid Decl's.
  2545. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2546. return ExprError();
  2547. // Handle members of anonymous structs and unions. If we got here,
  2548. // and the reference is to a class member indirect field, then this
  2549. // must be the subject of a pointer-to-member expression.
  2550. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2551. if (!indirectField->isCXXClassMember())
  2552. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2553. indirectField);
  2554. {
  2555. QualType type = VD->getType();
  2556. ExprValueKind valueKind = VK_RValue;
  2557. switch (D->getKind()) {
  2558. // Ignore all the non-ValueDecl kinds.
  2559. #define ABSTRACT_DECL(kind)
  2560. #define VALUE(type, base)
  2561. #define DECL(type, base) \
  2562. case Decl::type:
  2563. #include "clang/AST/DeclNodes.inc"
  2564. llvm_unreachable("invalid value decl kind");
  2565. // These shouldn't make it here.
  2566. case Decl::ObjCAtDefsField:
  2567. case Decl::ObjCIvar:
  2568. llvm_unreachable("forming non-member reference to ivar?");
  2569. // Enum constants are always r-values and never references.
  2570. // Unresolved using declarations are dependent.
  2571. case Decl::EnumConstant:
  2572. case Decl::UnresolvedUsingValue:
  2573. valueKind = VK_RValue;
  2574. break;
  2575. // Fields and indirect fields that got here must be for
  2576. // pointer-to-member expressions; we just call them l-values for
  2577. // internal consistency, because this subexpression doesn't really
  2578. // exist in the high-level semantics.
  2579. case Decl::Field:
  2580. case Decl::IndirectField:
  2581. assert(getLangOpts().CPlusPlus &&
  2582. "building reference to field in C?");
  2583. // These can't have reference type in well-formed programs, but
  2584. // for internal consistency we do this anyway.
  2585. type = type.getNonReferenceType();
  2586. valueKind = VK_LValue;
  2587. break;
  2588. // Non-type template parameters are either l-values or r-values
  2589. // depending on the type.
  2590. case Decl::NonTypeTemplateParm: {
  2591. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2592. type = reftype->getPointeeType();
  2593. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2594. break;
  2595. }
  2596. // For non-references, we need to strip qualifiers just in case
  2597. // the template parameter was declared as 'const int' or whatever.
  2598. valueKind = VK_RValue;
  2599. type = type.getUnqualifiedType();
  2600. break;
  2601. }
  2602. case Decl::Var:
  2603. case Decl::VarTemplateSpecialization:
  2604. case Decl::VarTemplatePartialSpecialization:
  2605. // In C, "extern void blah;" is valid and is an r-value.
  2606. if (!getLangOpts().CPlusPlus &&
  2607. !type.hasQualifiers() &&
  2608. type->isVoidType()) {
  2609. valueKind = VK_RValue;
  2610. break;
  2611. }
  2612. // fallthrough
  2613. case Decl::ImplicitParam:
  2614. case Decl::ParmVar: {
  2615. // These are always l-values.
  2616. valueKind = VK_LValue;
  2617. type = type.getNonReferenceType();
  2618. // FIXME: Does the addition of const really only apply in
  2619. // potentially-evaluated contexts? Since the variable isn't actually
  2620. // captured in an unevaluated context, it seems that the answer is no.
  2621. if (!isUnevaluatedContext()) {
  2622. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2623. if (!CapturedType.isNull())
  2624. type = CapturedType;
  2625. }
  2626. break;
  2627. }
  2628. case Decl::Function: {
  2629. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2630. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2631. type = Context.BuiltinFnTy;
  2632. valueKind = VK_RValue;
  2633. break;
  2634. }
  2635. }
  2636. const FunctionType *fty = type->castAs<FunctionType>();
  2637. // If we're referring to a function with an __unknown_anytype
  2638. // result type, make the entire expression __unknown_anytype.
  2639. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2640. type = Context.UnknownAnyTy;
  2641. valueKind = VK_RValue;
  2642. break;
  2643. }
  2644. // Functions are l-values in C++.
  2645. if (getLangOpts().CPlusPlus) {
  2646. valueKind = VK_LValue;
  2647. break;
  2648. }
  2649. // C99 DR 316 says that, if a function type comes from a
  2650. // function definition (without a prototype), that type is only
  2651. // used for checking compatibility. Therefore, when referencing
  2652. // the function, we pretend that we don't have the full function
  2653. // type.
  2654. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2655. isa<FunctionProtoType>(fty))
  2656. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2657. fty->getExtInfo());
  2658. // Functions are r-values in C.
  2659. valueKind = VK_RValue;
  2660. break;
  2661. }
  2662. case Decl::MSProperty:
  2663. valueKind = VK_LValue;
  2664. break;
  2665. case Decl::CXXMethod:
  2666. // If we're referring to a method with an __unknown_anytype
  2667. // result type, make the entire expression __unknown_anytype.
  2668. // This should only be possible with a type written directly.
  2669. if (const FunctionProtoType *proto
  2670. = dyn_cast<FunctionProtoType>(VD->getType()))
  2671. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2672. type = Context.UnknownAnyTy;
  2673. valueKind = VK_RValue;
  2674. break;
  2675. }
  2676. // C++ methods are l-values if static, r-values if non-static.
  2677. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2678. valueKind = VK_LValue;
  2679. break;
  2680. }
  2681. // fallthrough
  2682. case Decl::CXXConversion:
  2683. case Decl::CXXDestructor:
  2684. case Decl::CXXConstructor:
  2685. valueKind = VK_RValue;
  2686. break;
  2687. }
  2688. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2689. TemplateArgs);
  2690. }
  2691. }
  2692. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2693. SmallString<32> &Target) {
  2694. Target.resize(CharByteWidth * (Source.size() + 1));
  2695. char *ResultPtr = &Target[0];
  2696. const UTF8 *ErrorPtr;
  2697. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2698. (void)success;
  2699. assert(success);
  2700. Target.resize(ResultPtr - &Target[0]);
  2701. }
  2702. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2703. PredefinedExpr::IdentType IT) {
  2704. // Pick the current block, lambda, captured statement or function.
  2705. Decl *currentDecl = nullptr;
  2706. if (const BlockScopeInfo *BSI = getCurBlock())
  2707. currentDecl = BSI->TheDecl;
  2708. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2709. currentDecl = LSI->CallOperator;
  2710. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2711. currentDecl = CSI->TheCapturedDecl;
  2712. else
  2713. currentDecl = getCurFunctionOrMethodDecl();
  2714. if (!currentDecl) {
  2715. Diag(Loc, diag::ext_predef_outside_function);
  2716. currentDecl = Context.getTranslationUnitDecl();
  2717. }
  2718. QualType ResTy;
  2719. StringLiteral *SL = nullptr;
  2720. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2721. ResTy = Context.DependentTy;
  2722. else {
  2723. // Pre-defined identifiers are of type char[x], where x is the length of
  2724. // the string.
  2725. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2726. unsigned Length = Str.length();
  2727. llvm::APInt LengthI(32, Length + 1);
  2728. if (IT == PredefinedExpr::LFunction) {
  2729. ResTy = Context.WideCharTy.withConst();
  2730. SmallString<32> RawChars;
  2731. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2732. Str, RawChars);
  2733. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2734. /*IndexTypeQuals*/ 0);
  2735. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2736. /*Pascal*/ false, ResTy, Loc);
  2737. } else {
  2738. ResTy = Context.CharTy.withConst();
  2739. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2740. /*IndexTypeQuals*/ 0);
  2741. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2742. /*Pascal*/ false, ResTy, Loc);
  2743. }
  2744. }
  2745. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2746. }
  2747. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2748. PredefinedExpr::IdentType IT;
  2749. switch (Kind) {
  2750. default: llvm_unreachable("Unknown simple primary expr!");
  2751. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2752. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2753. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2754. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2755. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2756. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2757. }
  2758. return BuildPredefinedExpr(Loc, IT);
  2759. }
  2760. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2761. SmallString<16> CharBuffer;
  2762. bool Invalid = false;
  2763. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2764. if (Invalid)
  2765. return ExprError();
  2766. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2767. PP, Tok.getKind());
  2768. if (Literal.hadError())
  2769. return ExprError();
  2770. // HLSL Change Starts
  2771. if (getLangOpts().HLSL) {
  2772. if (Literal.isWide() || Literal.isUTF16() || Literal.isUTF32() || Literal.isMultiChar()) {
  2773. Diag(Tok.getLocation(), diag::err_hlsl_unsupported_char_literal);
  2774. return ExprError();
  2775. }
  2776. Expr *CharLit = new (Context)CharacterLiteral(Literal.getValue(), CharacterLiteral::Ascii, Context.CharTy,
  2777. Tok.getLocation());
  2778. Expr* Result = ImplicitCastExpr::Create(Context,
  2779. Context.UnsignedIntTy, CK_IntegralCast, CharLit, nullptr, VK_RValue);
  2780. return Result;
  2781. }
  2782. // HLSL Change Ends
  2783. QualType Ty;
  2784. if (Literal.isWide())
  2785. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2786. else if (Literal.isUTF16())
  2787. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2788. else if (Literal.isUTF32())
  2789. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2790. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2791. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2792. else
  2793. Ty = Context.CharTy; // 'x' -> char in C++
  2794. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2795. if (Literal.isWide())
  2796. Kind = CharacterLiteral::Wide;
  2797. else if (Literal.isUTF16())
  2798. Kind = CharacterLiteral::UTF16;
  2799. else if (Literal.isUTF32())
  2800. Kind = CharacterLiteral::UTF32;
  2801. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2802. Tok.getLocation());
  2803. if (Literal.getUDSuffix().empty())
  2804. return Lit;
  2805. // We're building a user-defined literal.
  2806. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2807. SourceLocation UDSuffixLoc =
  2808. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2809. // Make sure we're allowed user-defined literals here.
  2810. if (!UDLScope)
  2811. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2812. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2813. // operator "" X (ch)
  2814. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2815. Lit, Tok.getLocation());
  2816. }
  2817. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2818. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2819. // HLSL Change Starts - HLSL literal int
  2820. QualType Ty;
  2821. if (getLangOpts().HLSL) {
  2822. IntSize = 64;
  2823. Ty = Context.LitIntTy;
  2824. } else
  2825. Ty = Context.IntTy;
  2826. // HLSL Change Ends
  2827. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2828. Ty, Loc); // HLSL Change
  2829. }
  2830. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2831. QualType Ty, SourceLocation Loc) {
  2832. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2833. using llvm::APFloat;
  2834. APFloat Val(Format);
  2835. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2836. // Overflow is always an error, but underflow is only an error if
  2837. // we underflowed to zero (APFloat reports denormals as underflow).
  2838. if ((result & APFloat::opOverflow) ||
  2839. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2840. unsigned diagnostic;
  2841. SmallString<20> buffer;
  2842. if (result & APFloat::opOverflow) {
  2843. diagnostic = diag::warn_float_overflow;
  2844. APFloat::getLargest(Format).toString(buffer);
  2845. } else {
  2846. diagnostic = diag::warn_float_underflow;
  2847. APFloat::getSmallest(Format).toString(buffer);
  2848. }
  2849. S.Diag(Loc, diagnostic)
  2850. << Ty
  2851. << StringRef(buffer.data(), buffer.size());
  2852. }
  2853. bool isExact = (result == APFloat::opOK);
  2854. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2855. }
  2856. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2857. assert(E && "Invalid expression");
  2858. if (E->isValueDependent())
  2859. return false;
  2860. QualType QT = E->getType();
  2861. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2862. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2863. return true;
  2864. }
  2865. llvm::APSInt ValueAPS;
  2866. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2867. if (R.isInvalid())
  2868. return true;
  2869. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2870. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2871. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2872. << ValueAPS.toString(10) << ValueIsPositive;
  2873. return true;
  2874. }
  2875. return false;
  2876. }
  2877. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2878. // Fast path for a single digit (which is quite common). A single digit
  2879. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2880. if (Tok.getLength() == 1) {
  2881. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2882. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2883. }
  2884. SmallString<128> SpellingBuffer;
  2885. // NumericLiteralParser wants to overread by one character. Add padding to
  2886. // the buffer in case the token is copied to the buffer. If getSpelling()
  2887. // returns a StringRef to the memory buffer, it should have a null char at
  2888. // the EOF, so it is also safe.
  2889. SpellingBuffer.resize(Tok.getLength() + 1);
  2890. // Get the spelling of the token, which eliminates trigraphs, etc.
  2891. bool Invalid = false;
  2892. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2893. if (Invalid)
  2894. return ExprError();
  2895. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2896. if (Literal.hadError)
  2897. return ExprError();
  2898. if (Literal.hasUDSuffix()) {
  2899. // We're building a user-defined literal.
  2900. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2901. SourceLocation UDSuffixLoc =
  2902. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2903. // Make sure we're allowed user-defined literals here.
  2904. if (!UDLScope)
  2905. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2906. QualType CookedTy;
  2907. if (Literal.isFloatingLiteral()) {
  2908. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2909. // long double, the literal is treated as a call of the form
  2910. // operator "" X (f L)
  2911. CookedTy = Context.LongDoubleTy;
  2912. } else {
  2913. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2914. // unsigned long long, the literal is treated as a call of the form
  2915. // operator "" X (n ULL)
  2916. CookedTy = Context.UnsignedLongLongTy;
  2917. }
  2918. DeclarationName OpName =
  2919. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2920. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2921. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2922. SourceLocation TokLoc = Tok.getLocation();
  2923. // Perform literal operator lookup to determine if we're building a raw
  2924. // literal or a cooked one.
  2925. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2926. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2927. /*AllowRaw*/true, /*AllowTemplate*/true,
  2928. /*AllowStringTemplate*/false)) {
  2929. case LOLR_Error:
  2930. return ExprError();
  2931. case LOLR_Cooked: {
  2932. Expr *Lit;
  2933. if (Literal.isFloatingLiteral()) {
  2934. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2935. } else {
  2936. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2937. if (Literal.GetIntegerValue(ResultVal))
  2938. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2939. << /* Unsigned */ 1;
  2940. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2941. Tok.getLocation());
  2942. }
  2943. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2944. }
  2945. case LOLR_Raw: {
  2946. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2947. // literal is treated as a call of the form
  2948. // operator "" X ("n")
  2949. unsigned Length = Literal.getUDSuffixOffset();
  2950. QualType StrTy = Context.getConstantArrayType(
  2951. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2952. ArrayType::Normal, 0);
  2953. Expr *Lit = StringLiteral::Create(
  2954. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2955. /*Pascal*/false, StrTy, &TokLoc, 1);
  2956. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2957. }
  2958. case LOLR_Template: {
  2959. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2960. // template), L is treated as a call fo the form
  2961. // operator "" X <'c1', 'c2', ... 'ck'>()
  2962. // where n is the source character sequence c1 c2 ... ck.
  2963. TemplateArgumentListInfo ExplicitArgs;
  2964. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2965. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2966. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2967. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2968. Value = TokSpelling[I];
  2969. TemplateArgument Arg(Context, Value, Context.CharTy);
  2970. TemplateArgumentLocInfo ArgInfo;
  2971. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2972. }
  2973. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2974. &ExplicitArgs);
  2975. }
  2976. case LOLR_StringTemplate:
  2977. llvm_unreachable("unexpected literal operator lookup result");
  2978. }
  2979. }
  2980. Expr *Res;
  2981. if (Literal.isFloatingLiteral()) {
  2982. QualType Ty;
  2983. if (Literal.isFloat)
  2984. Ty = Context.FloatTy;
  2985. // HLSL Change Starts
  2986. else if (getLangOpts().HLSL && !Literal.isLong && !Literal.isHalf)
  2987. Ty = Context.LitFloatTy;
  2988. else if (getLangOpts().HLSL && Literal.isLong)
  2989. Ty = Context.DoubleTy;
  2990. else if (getLangOpts().HLSL && Literal.isHalf) {
  2991. Ty = getLangOpts().UseMinPrecision ? Context.FloatTy : Context.HalfTy;
  2992. }
  2993. // HLSL Change Ends
  2994. else if (!Literal.isLong)
  2995. Ty = Context.DoubleTy;
  2996. else
  2997. Ty = Context.LongDoubleTy;
  2998. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2999. if (Ty == Context.DoubleTy) {
  3000. if (getLangOpts().SinglePrecisionConstants) {
  3001. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3002. } else if (getLangOpts().OpenCL &&
  3003. !((getLangOpts().OpenCLVersion >= 120) ||
  3004. getOpenCLOptions().cl_khr_fp64)) {
  3005. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3006. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3007. }
  3008. }
  3009. } else if (!Literal.isIntegerLiteral()) {
  3010. return ExprError();
  3011. // HLSL Change Starts
  3012. } else if (getLangOpts().HLSL) {
  3013. QualType Ty;
  3014. unsigned Width = 64;
  3015. llvm::APInt ResultVal(Width, 0);
  3016. if (!Literal.isLong && !Literal.isLongLong && !Literal.isUnsigned) {
  3017. // in HLSL, unspecific literal ints are LitIntTy, using 64-bit
  3018. Ty = Context.LitIntTy;
  3019. if (Literal.GetIntegerValue(ResultVal)) {
  3020. // If this value didn't fit into 64-bit literal int, report error.
  3021. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  3022. }
  3023. } else {
  3024. if (Literal.GetIntegerValue(ResultVal)) {
  3025. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  3026. }
  3027. if (Literal.isLongLong) {
  3028. if (Literal.isUnsigned)
  3029. Ty = Context.UnsignedLongLongTy;
  3030. else
  3031. Ty = Context.LongLongTy;
  3032. }
  3033. else {
  3034. // long is the same as int for HLSL, so ignore isLong here
  3035. Width = 32;
  3036. ResultVal = ResultVal.trunc(Width);
  3037. if (Literal.isUnsigned || Literal.getRadix() != 10)
  3038. Ty = Context.UnsignedIntTy;
  3039. else
  3040. Ty = Context.IntTy;
  3041. }
  3042. }
  3043. return IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3044. // HLSL Change Ends
  3045. } else {
  3046. QualType Ty;
  3047. // 'long long' is a C99 or C++11 feature.
  3048. if (!getLangOpts().C99 && Literal.isLongLong) {
  3049. if (getLangOpts().CPlusPlus)
  3050. Diag(Tok.getLocation(),
  3051. getLangOpts().CPlusPlus11 ?
  3052. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3053. else
  3054. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3055. }
  3056. // Get the value in the widest-possible width.
  3057. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3058. // The microsoft literal suffix extensions support 128-bit literals, which
  3059. // may be wider than [u]intmax_t.
  3060. // FIXME: Actually, they don't. We seem to have accidentally invented the
  3061. // i128 suffix.
  3062. if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
  3063. Context.getTargetInfo().hasInt128Type())
  3064. MaxWidth = 128;
  3065. llvm::APInt ResultVal(MaxWidth, 0);
  3066. if (Literal.GetIntegerValue(ResultVal)) {
  3067. // If this value didn't fit into uintmax_t, error and force to ull.
  3068. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3069. << /* Unsigned */ 1;
  3070. Ty = Context.UnsignedLongLongTy;
  3071. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3072. "long long is not intmax_t?");
  3073. } else {
  3074. // If this value fits into a ULL, try to figure out what else it fits into
  3075. // according to the rules of C99 6.4.4.1p5.
  3076. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3077. // be an unsigned int.
  3078. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3079. // Check from smallest to largest, picking the smallest type we can.
  3080. unsigned Width = 0;
  3081. // Microsoft specific integer suffixes are explicitly sized.
  3082. if (Literal.MicrosoftInteger) {
  3083. if (Literal.MicrosoftInteger > MaxWidth) {
  3084. // If this target doesn't support __int128, error and force to ull.
  3085. Diag(Tok.getLocation(), diag::err_int128_unsupported);
  3086. Width = MaxWidth;
  3087. Ty = Context.getIntMaxType();
  3088. } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3089. Width = 8;
  3090. Ty = Context.CharTy;
  3091. } else {
  3092. Width = Literal.MicrosoftInteger;
  3093. Ty = Context.getIntTypeForBitwidth(Width,
  3094. /*Signed=*/!Literal.isUnsigned);
  3095. }
  3096. }
  3097. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3098. // Are int/unsigned possibilities?
  3099. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3100. // Does it fit in a unsigned int?
  3101. if (ResultVal.isIntN(IntSize)) {
  3102. // Does it fit in a signed int?
  3103. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3104. Ty = Context.IntTy;
  3105. else if (AllowUnsigned)
  3106. Ty = Context.UnsignedIntTy;
  3107. Width = IntSize;
  3108. }
  3109. }
  3110. // Are long/unsigned long possibilities?
  3111. if (Ty.isNull() && !Literal.isLongLong) {
  3112. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3113. // Does it fit in a unsigned long?
  3114. if (ResultVal.isIntN(LongSize)) {
  3115. // Does it fit in a signed long?
  3116. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3117. Ty = Context.LongTy;
  3118. else if (AllowUnsigned)
  3119. Ty = Context.UnsignedLongTy;
  3120. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3121. // is compatible.
  3122. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3123. const unsigned LongLongSize =
  3124. Context.getTargetInfo().getLongLongWidth();
  3125. Diag(Tok.getLocation(),
  3126. getLangOpts().CPlusPlus
  3127. ? Literal.isLong
  3128. ? diag::warn_old_implicitly_unsigned_long_cxx
  3129. : /*C++98 UB*/ diag::
  3130. ext_old_implicitly_unsigned_long_cxx
  3131. : diag::warn_old_implicitly_unsigned_long)
  3132. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3133. : /*will be ill-formed*/ 1);
  3134. Ty = Context.UnsignedLongTy;
  3135. }
  3136. Width = LongSize;
  3137. }
  3138. }
  3139. // Check long long if needed.
  3140. if (Ty.isNull()) {
  3141. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3142. // Does it fit in a unsigned long long?
  3143. if (ResultVal.isIntN(LongLongSize)) {
  3144. // Does it fit in a signed long long?
  3145. // To be compatible with MSVC, hex integer literals ending with the
  3146. // LL or i64 suffix are always signed in Microsoft mode.
  3147. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3148. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  3149. Ty = Context.LongLongTy;
  3150. else if (AllowUnsigned)
  3151. Ty = Context.UnsignedLongLongTy;
  3152. Width = LongLongSize;
  3153. }
  3154. }
  3155. // If we still couldn't decide a type, we probably have something that
  3156. // does not fit in a signed long long, but has no U suffix.
  3157. if (Ty.isNull()) {
  3158. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3159. Ty = Context.UnsignedLongLongTy;
  3160. Width = Context.getTargetInfo().getLongLongWidth();
  3161. }
  3162. if (ResultVal.getBitWidth() != Width)
  3163. ResultVal = ResultVal.trunc(Width);
  3164. }
  3165. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3166. }
  3167. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3168. if (Literal.isImaginary)
  3169. Res = new (Context) ImaginaryLiteral(Res,
  3170. Context.getComplexType(Res->getType()));
  3171. return Res;
  3172. }
  3173. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3174. assert(E && "ActOnParenExpr() missing expr");
  3175. return new (Context) ParenExpr(L, R, E);
  3176. }
  3177. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3178. SourceLocation Loc,
  3179. SourceRange ArgRange) {
  3180. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3181. // scalar or vector data type argument..."
  3182. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3183. // type (C99 6.2.5p18) or void.
  3184. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3185. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3186. << T << ArgRange;
  3187. return true;
  3188. }
  3189. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3190. "Scalar types should always be complete");
  3191. return false;
  3192. }
  3193. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3194. SourceLocation Loc,
  3195. SourceRange ArgRange,
  3196. UnaryExprOrTypeTrait TraitKind) {
  3197. // Invalid types must be hard errors for SFINAE in C++.
  3198. if (S.LangOpts.CPlusPlus)
  3199. return true;
  3200. // C99 6.5.3.4p1:
  3201. if (T->isFunctionType() &&
  3202. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3203. // sizeof(function)/alignof(function) is allowed as an extension.
  3204. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3205. << TraitKind << ArgRange;
  3206. return false;
  3207. }
  3208. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3209. // this is an error (OpenCL v1.1 s6.3.k)
  3210. if (T->isVoidType()) {
  3211. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3212. : diag::ext_sizeof_alignof_void_type;
  3213. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3214. return false;
  3215. }
  3216. return true;
  3217. }
  3218. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3219. SourceLocation Loc,
  3220. SourceRange ArgRange,
  3221. UnaryExprOrTypeTrait TraitKind) {
  3222. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3223. // runtime doesn't allow it.
  3224. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3225. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3226. << T << (TraitKind == UETT_SizeOf)
  3227. << ArgRange;
  3228. return true;
  3229. }
  3230. return false;
  3231. }
  3232. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3233. /// pointer type is equal to T) and emit a warning if it is.
  3234. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3235. Expr *E) {
  3236. // Don't warn if the operation changed the type.
  3237. if (T != E->getType())
  3238. return;
  3239. // Now look for array decays.
  3240. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3241. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3242. return;
  3243. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3244. << ICE->getType()
  3245. << ICE->getSubExpr()->getType();
  3246. }
  3247. // HLSL Change Begins
  3248. bool Sema::CheckHLSLUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation Loc,
  3249. UnaryExprOrTypeTrait ExprKind) {
  3250. assert(ExprKind == UnaryExprOrTypeTrait::UETT_SizeOf);
  3251. // "sizeof 42" is ill-defined because HLSL has literal int type which can decay to an int of any size.
  3252. const BuiltinType* BuiltinTy = ExprType->getAs<BuiltinType>();
  3253. if (BuiltinTy != nullptr && (BuiltinTy->getKind() == BuiltinType::LitInt || BuiltinTy->getKind() == BuiltinType::LitFloat)) {
  3254. Diag(Loc, diag::err_hlsl_sizeof_literal) << ExprType;
  3255. return true;
  3256. }
  3257. if (!hlsl::IsHLSLNumericOrAggregateOfNumericType(ExprType)) {
  3258. Diag(Loc, diag::err_hlsl_sizeof_nonnumeric) << ExprType;
  3259. return true;
  3260. }
  3261. return false;
  3262. }
  3263. // HLSL Change Ends
  3264. /// \brief Check the constraints on expression operands to unary type expression
  3265. /// and type traits.
  3266. ///
  3267. /// Completes any types necessary and validates the constraints on the operand
  3268. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3269. /// the expression as it completes the type for that expression through template
  3270. /// instantiation, etc.
  3271. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3272. UnaryExprOrTypeTrait ExprKind) {
  3273. QualType ExprTy = E->getType();
  3274. assert(!ExprTy->isReferenceType());
  3275. if (ExprKind == UETT_VecStep)
  3276. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3277. E->getSourceRange());
  3278. // Whitelist some types as extensions
  3279. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3280. E->getSourceRange(), ExprKind))
  3281. return false;
  3282. // 'alignof' applied to an expression only requires the base element type of
  3283. // the expression to be complete. 'sizeof' requires the expression's type to
  3284. // be complete (and will attempt to complete it if it's an array of unknown
  3285. // bound).
  3286. if (ExprKind == UETT_AlignOf) {
  3287. if (RequireCompleteType(E->getExprLoc(),
  3288. Context.getBaseElementType(E->getType()),
  3289. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3290. E->getSourceRange()))
  3291. return true;
  3292. } else {
  3293. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3294. ExprKind, E->getSourceRange()))
  3295. return true;
  3296. }
  3297. // Completing the expression's type may have changed it.
  3298. ExprTy = E->getType();
  3299. assert(!ExprTy->isReferenceType());
  3300. if (getLangOpts().HLSL && CheckHLSLUnaryExprOrTypeTraitOperand(ExprTy, E->getExprLoc(), ExprKind)) {
  3301. return true;
  3302. }
  3303. if (ExprTy->isFunctionType()) {
  3304. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3305. << ExprKind << E->getSourceRange();
  3306. return true;
  3307. }
  3308. // The operand for sizeof and alignof is in an unevaluated expression context,
  3309. // so side effects could result in unintended consequences.
  3310. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3311. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3312. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3313. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3314. E->getSourceRange(), ExprKind))
  3315. return true;
  3316. if (ExprKind == UETT_SizeOf) {
  3317. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3318. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3319. QualType OType = PVD->getOriginalType();
  3320. QualType Type = PVD->getType();
  3321. if (Type->isPointerType() && OType->isArrayType()) {
  3322. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3323. << Type << OType;
  3324. Diag(PVD->getLocation(), diag::note_declared_at);
  3325. }
  3326. }
  3327. }
  3328. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3329. // decays into a pointer and returns an unintended result. This is most
  3330. // likely a typo for "sizeof(array) op x".
  3331. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3332. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3333. BO->getLHS());
  3334. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3335. BO->getRHS());
  3336. }
  3337. }
  3338. return false;
  3339. }
  3340. /// \brief Check the constraints on operands to unary expression and type
  3341. /// traits.
  3342. ///
  3343. /// This will complete any types necessary, and validate the various constraints
  3344. /// on those operands.
  3345. ///
  3346. /// The UsualUnaryConversions() function is *not* called by this routine.
  3347. /// C99 6.3.2.1p[2-4] all state:
  3348. /// Except when it is the operand of the sizeof operator ...
  3349. ///
  3350. /// C++ [expr.sizeof]p4
  3351. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3352. /// standard conversions are not applied to the operand of sizeof.
  3353. ///
  3354. /// This policy is followed for all of the unary trait expressions.
  3355. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3356. SourceLocation OpLoc,
  3357. SourceRange ExprRange,
  3358. UnaryExprOrTypeTrait ExprKind) {
  3359. if (ExprType->isDependentType())
  3360. return false;
  3361. // C++ [expr.sizeof]p2:
  3362. // When applied to a reference or a reference type, the result
  3363. // is the size of the referenced type.
  3364. // C++11 [expr.alignof]p3:
  3365. // When alignof is applied to a reference type, the result
  3366. // shall be the alignment of the referenced type.
  3367. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3368. ExprType = Ref->getPointeeType();
  3369. if (getLangOpts().HLSL && CheckHLSLUnaryExprOrTypeTraitOperand(ExprType, OpLoc, ExprKind)) {
  3370. return true;
  3371. }
  3372. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3373. // When alignof or _Alignof is applied to an array type, the result
  3374. // is the alignment of the element type.
  3375. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3376. ExprType = Context.getBaseElementType(ExprType);
  3377. if (ExprKind == UETT_VecStep)
  3378. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3379. // Whitelist some types as extensions
  3380. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3381. ExprKind))
  3382. return false;
  3383. if (RequireCompleteType(OpLoc, ExprType,
  3384. diag::err_sizeof_alignof_incomplete_type,
  3385. ExprKind, ExprRange))
  3386. return true;
  3387. if (ExprType->isFunctionType()) {
  3388. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3389. << ExprKind << ExprRange;
  3390. return true;
  3391. }
  3392. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3393. ExprKind))
  3394. return true;
  3395. return false;
  3396. }
  3397. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3398. E = E->IgnoreParens();
  3399. // Cannot know anything else if the expression is dependent.
  3400. if (E->isTypeDependent())
  3401. return false;
  3402. if (E->getObjectKind() == OK_BitField) {
  3403. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3404. << 1 << E->getSourceRange();
  3405. return true;
  3406. }
  3407. ValueDecl *D = nullptr;
  3408. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3409. D = DRE->getDecl();
  3410. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3411. D = ME->getMemberDecl();
  3412. }
  3413. // If it's a field, require the containing struct to have a
  3414. // complete definition so that we can compute the layout.
  3415. //
  3416. // This can happen in C++11 onwards, either by naming the member
  3417. // in a way that is not transformed into a member access expression
  3418. // (in an unevaluated operand, for instance), or by naming the member
  3419. // in a trailing-return-type.
  3420. //
  3421. // For the record, since __alignof__ on expressions is a GCC
  3422. // extension, GCC seems to permit this but always gives the
  3423. // nonsensical answer 0.
  3424. //
  3425. // We don't really need the layout here --- we could instead just
  3426. // directly check for all the appropriate alignment-lowing
  3427. // attributes --- but that would require duplicating a lot of
  3428. // logic that just isn't worth duplicating for such a marginal
  3429. // use-case.
  3430. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3431. // Fast path this check, since we at least know the record has a
  3432. // definition if we can find a member of it.
  3433. if (!FD->getParent()->isCompleteDefinition()) {
  3434. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3435. << E->getSourceRange();
  3436. return true;
  3437. }
  3438. // Otherwise, if it's a field, and the field doesn't have
  3439. // reference type, then it must have a complete type (or be a
  3440. // flexible array member, which we explicitly want to
  3441. // white-list anyway), which makes the following checks trivial.
  3442. if (!FD->getType()->isReferenceType())
  3443. return false;
  3444. }
  3445. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3446. }
  3447. bool Sema::CheckVecStepExpr(Expr *E) {
  3448. E = E->IgnoreParens();
  3449. // Cannot know anything else if the expression is dependent.
  3450. if (E->isTypeDependent())
  3451. return false;
  3452. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3453. }
  3454. /// \brief Build a sizeof or alignof expression given a type operand.
  3455. ExprResult
  3456. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3457. SourceLocation OpLoc,
  3458. UnaryExprOrTypeTrait ExprKind,
  3459. SourceRange R) {
  3460. if (!TInfo)
  3461. return ExprError();
  3462. QualType T = TInfo->getType();
  3463. if (!T->isDependentType() &&
  3464. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3465. return ExprError();
  3466. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3467. return new (Context) UnaryExprOrTypeTraitExpr(
  3468. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3469. }
  3470. /// \brief Build a sizeof or alignof expression given an expression
  3471. /// operand.
  3472. ExprResult
  3473. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3474. UnaryExprOrTypeTrait ExprKind) {
  3475. ExprResult PE = CheckPlaceholderExpr(E);
  3476. if (PE.isInvalid())
  3477. return ExprError();
  3478. E = PE.get();
  3479. // Verify that the operand is valid.
  3480. bool isInvalid = false;
  3481. if (E->isTypeDependent()) {
  3482. // Delay type-checking for type-dependent expressions.
  3483. } else if (ExprKind == UETT_AlignOf) {
  3484. isInvalid = CheckAlignOfExpr(*this, E);
  3485. } else if (ExprKind == UETT_VecStep) {
  3486. isInvalid = CheckVecStepExpr(E);
  3487. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3488. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3489. isInvalid = true;
  3490. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3491. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3492. isInvalid = true;
  3493. } else {
  3494. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3495. }
  3496. if (isInvalid)
  3497. return ExprError();
  3498. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3499. PE = TransformToPotentiallyEvaluated(E);
  3500. if (PE.isInvalid()) return ExprError();
  3501. E = PE.get();
  3502. }
  3503. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3504. return new (Context) UnaryExprOrTypeTraitExpr(
  3505. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3506. }
  3507. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3508. /// expr and the same for @c alignof and @c __alignof
  3509. /// Note that the ArgRange is invalid if isType is false.
  3510. ExprResult
  3511. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3512. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3513. void *TyOrEx, const SourceRange &ArgRange) {
  3514. // If error parsing type, ignore.
  3515. if (!TyOrEx) return ExprError();
  3516. if (IsType) {
  3517. TypeSourceInfo *TInfo;
  3518. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3519. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3520. }
  3521. Expr *ArgEx = (Expr *)TyOrEx;
  3522. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3523. return Result;
  3524. }
  3525. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3526. bool IsReal) {
  3527. if (V.get()->isTypeDependent())
  3528. return S.Context.DependentTy;
  3529. // _Real and _Imag are only l-values for normal l-values.
  3530. if (V.get()->getObjectKind() != OK_Ordinary) {
  3531. V = S.DefaultLvalueConversion(V.get());
  3532. if (V.isInvalid())
  3533. return QualType();
  3534. }
  3535. // These operators return the element type of a complex type.
  3536. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3537. return CT->getElementType();
  3538. // Otherwise they pass through real integer and floating point types here.
  3539. if (V.get()->getType()->isArithmeticType())
  3540. return V.get()->getType();
  3541. // Test for placeholders.
  3542. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3543. if (PR.isInvalid()) return QualType();
  3544. if (PR.get() != V.get()) {
  3545. V = PR;
  3546. return CheckRealImagOperand(S, V, Loc, IsReal);
  3547. }
  3548. // Reject anything else.
  3549. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3550. << (IsReal ? "__real" : "__imag");
  3551. return QualType();
  3552. }
  3553. ExprResult
  3554. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3555. tok::TokenKind Kind, Expr *Input) {
  3556. UnaryOperatorKind Opc;
  3557. switch (Kind) {
  3558. default: llvm_unreachable("Unknown unary op!");
  3559. case tok::plusplus: Opc = UO_PostInc; break;
  3560. case tok::minusminus: Opc = UO_PostDec; break;
  3561. }
  3562. // Since this might is a postfix expression, get rid of ParenListExprs.
  3563. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3564. if (Result.isInvalid()) return ExprError();
  3565. Input = Result.get();
  3566. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3567. }
  3568. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3569. ///
  3570. /// \return true on error
  3571. static bool checkArithmeticOnObjCPointer(Sema &S,
  3572. SourceLocation opLoc,
  3573. Expr *op) {
  3574. assert(op->getType()->isObjCObjectPointerType());
  3575. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3576. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3577. return false;
  3578. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3579. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3580. << op->getSourceRange();
  3581. return true;
  3582. }
  3583. ExprResult
  3584. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3585. Expr *idx, SourceLocation rbLoc) {
  3586. // Since this might be a postfix expression, get rid of ParenListExprs.
  3587. if (isa<ParenListExpr>(base)) {
  3588. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3589. if (result.isInvalid()) return ExprError();
  3590. base = result.get();
  3591. }
  3592. // Handle any non-overload placeholder types in the base and index
  3593. // expressions. We can't handle overloads here because the other
  3594. // operand might be an overloadable type, in which case the overload
  3595. // resolution for the operator overload should get the first crack
  3596. // at the overload.
  3597. if (base->getType()->isNonOverloadPlaceholderType()) {
  3598. ExprResult result = CheckPlaceholderExpr(base);
  3599. if (result.isInvalid()) return ExprError();
  3600. base = result.get();
  3601. }
  3602. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3603. ExprResult result = CheckPlaceholderExpr(idx);
  3604. if (result.isInvalid()) return ExprError();
  3605. idx = result.get();
  3606. }
  3607. // HLSL Change Starts - Check for subscript access of out indices
  3608. // Disallow component access for out indices for DXIL path. We still allow
  3609. // this in SPIR-V path.
  3610. if (getLangOpts().HLSL && !getLangOpts().SPIRV &&
  3611. base->getType()->isRecordType() && IsExprAccessingOutIndicesArray(base)) {
  3612. Diag(lbLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  3613. return ExprError();
  3614. }
  3615. // HLSL Change Ends
  3616. // Build an unanalyzed expression if either operand is type-dependent.
  3617. if (getLangOpts().CPlusPlus &&
  3618. (base->isTypeDependent() || idx->isTypeDependent())) {
  3619. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3620. VK_LValue, OK_Ordinary, rbLoc);
  3621. }
  3622. // Use C++ overloaded-operator rules if either operand has record
  3623. // type. The spec says to do this if either type is *overloadable*,
  3624. // but enum types can't declare subscript operators or conversion
  3625. // operators, so there's nothing interesting for overload resolution
  3626. // to do if there aren't any record types involved.
  3627. //
  3628. // ObjC pointers have their own subscripting logic that is not tied
  3629. // to overload resolution and so should not take this path.
  3630. if (getLangOpts().CPlusPlus &&
  3631. (base->getType()->isRecordType() ||
  3632. (!base->getType()->isObjCObjectPointerType() &&
  3633. idx->getType()->isRecordType()))) {
  3634. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3635. }
  3636. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3637. }
  3638. ExprResult
  3639. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3640. Expr *Idx, SourceLocation RLoc) {
  3641. Expr *LHSExp = Base;
  3642. Expr *RHSExp = Idx;
  3643. // Perform default conversions.
  3644. if (!LHSExp->getType()->getAs<VectorType>()) {
  3645. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3646. if (Result.isInvalid())
  3647. return ExprError();
  3648. LHSExp = Result.get();
  3649. }
  3650. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3651. if (Result.isInvalid())
  3652. return ExprError();
  3653. RHSExp = Result.get();
  3654. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3655. ExprValueKind VK = VK_LValue;
  3656. ExprObjectKind OK = OK_Ordinary;
  3657. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3658. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3659. // in the subscript position. As a result, we need to derive the array base
  3660. // and index from the expression types.
  3661. Expr *BaseExpr, *IndexExpr;
  3662. QualType ResultType;
  3663. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3664. BaseExpr = LHSExp;
  3665. IndexExpr = RHSExp;
  3666. ResultType = Context.DependentTy;
  3667. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3668. BaseExpr = LHSExp;
  3669. IndexExpr = RHSExp;
  3670. ResultType = PTy->getPointeeType();
  3671. } else if (const ObjCObjectPointerType *PTy =
  3672. LHSTy->getAs<ObjCObjectPointerType>()) {
  3673. BaseExpr = LHSExp;
  3674. IndexExpr = RHSExp;
  3675. // Use custom logic if this should be the pseudo-object subscript
  3676. // expression.
  3677. if (!LangOpts.isSubscriptPointerArithmetic())
  3678. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3679. nullptr);
  3680. ResultType = PTy->getPointeeType();
  3681. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3682. // Handle the uncommon case of "123[Ptr]".
  3683. BaseExpr = RHSExp;
  3684. IndexExpr = LHSExp;
  3685. ResultType = PTy->getPointeeType();
  3686. } else if (const ObjCObjectPointerType *PTy =
  3687. RHSTy->getAs<ObjCObjectPointerType>()) {
  3688. // Handle the uncommon case of "123[Ptr]".
  3689. BaseExpr = RHSExp;
  3690. IndexExpr = LHSExp;
  3691. ResultType = PTy->getPointeeType();
  3692. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3693. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3694. << ResultType << BaseExpr->getSourceRange();
  3695. return ExprError();
  3696. }
  3697. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3698. BaseExpr = LHSExp; // vectors: V[123]
  3699. IndexExpr = RHSExp;
  3700. VK = LHSExp->getValueKind();
  3701. if (VK != VK_RValue)
  3702. OK = OK_VectorComponent;
  3703. // FIXME: need to deal with const...
  3704. ResultType = VTy->getElementType();
  3705. } else if (LHSTy->isArrayType()) {
  3706. // If we see an array that wasn't promoted by
  3707. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3708. // wasn't promoted because of the C90 rule that doesn't
  3709. // allow promoting non-lvalue arrays. Warn, then
  3710. // force the promotion here.
  3711. // HLSL Change Starts - arrays won't decay
  3712. if (getLangOpts().HLSL) {
  3713. BaseExpr = LHSExp;
  3714. IndexExpr = RHSExp;
  3715. ResultType = LHSTy->getAsArrayTypeUnsafe()->getElementType();
  3716. } else {
  3717. // HLSL Change Ends
  3718. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3719. LHSExp->getSourceRange();
  3720. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3721. CK_ArrayToPointerDecay).get();
  3722. LHSTy = LHSExp->getType();
  3723. BaseExpr = LHSExp;
  3724. IndexExpr = RHSExp;
  3725. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3726. } // HLSL Change - end else block
  3727. } else if (RHSTy->isArrayType()) {
  3728. // Same as previous, except for 123[f().a] case
  3729. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3730. RHSExp->getSourceRange();
  3731. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3732. CK_ArrayToPointerDecay).get();
  3733. RHSTy = RHSExp->getType();
  3734. BaseExpr = RHSExp;
  3735. IndexExpr = LHSExp;
  3736. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3737. } else {
  3738. // HLSL Change: use HLSL variation of error message
  3739. return ExprError(Diag(LLoc, getLangOpts().HLSL ? diag::err_hlsl_typecheck_subscript_value : diag::err_typecheck_subscript_value)
  3740. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3741. }
  3742. // HLSL Change Starts
  3743. if (getLangOpts().HLSL && BaseExpr != LHSExp) {
  3744. Diag(RHSExp->getLocStart(), diag::err_hlsl_unsupported_subscript_base_rhs);
  3745. }
  3746. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent() &&
  3747. IndexExpr->getType()->isFloatingType()) {
  3748. IndexExpr = ImpCastExprToType(IndexExpr, Context.UnsignedIntTy,
  3749. CK_FloatingToIntegral).get();
  3750. }
  3751. // HLSL Change Ends
  3752. // C99 6.5.2.1p1
  3753. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3754. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3755. << IndexExpr->getSourceRange());
  3756. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3757. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3758. && !IndexExpr->isTypeDependent())
  3759. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3760. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3761. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3762. // type. Note that Functions are not objects, and that (in C99 parlance)
  3763. // incomplete types are not object types.
  3764. if (ResultType->isFunctionType()) {
  3765. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3766. << ResultType << BaseExpr->getSourceRange();
  3767. return ExprError();
  3768. }
  3769. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3770. // GNU extension: subscripting on pointer to void
  3771. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3772. << BaseExpr->getSourceRange();
  3773. // C forbids expressions of unqualified void type from being l-values.
  3774. // See IsCForbiddenLValueType.
  3775. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3776. } else if (!ResultType->isDependentType() &&
  3777. RequireCompleteType(LLoc, ResultType,
  3778. diag::err_subscript_incomplete_type, BaseExpr))
  3779. return ExprError();
  3780. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3781. !ResultType.isCForbiddenLValueType());
  3782. if (getLangOpts().HLSL) RHSExp = IndexExpr; // HLSL Change - refer to right-hands side as indexer
  3783. return new (Context)
  3784. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3785. }
  3786. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3787. FunctionDecl *FD,
  3788. ParmVarDecl *Param) {
  3789. if (Param->hasUnparsedDefaultArg()) {
  3790. Diag(CallLoc,
  3791. diag::err_use_of_default_argument_to_function_declared_later) <<
  3792. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3793. Diag(UnparsedDefaultArgLocs[Param],
  3794. diag::note_default_argument_declared_here);
  3795. return ExprError();
  3796. }
  3797. if (Param->hasUninstantiatedDefaultArg()) {
  3798. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3799. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3800. Param);
  3801. // Instantiate the expression.
  3802. MultiLevelTemplateArgumentList MutiLevelArgList
  3803. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3804. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3805. MutiLevelArgList.getInnermost());
  3806. if (Inst.isInvalid())
  3807. return ExprError();
  3808. ExprResult Result;
  3809. {
  3810. // C++ [dcl.fct.default]p5:
  3811. // The names in the [default argument] expression are bound, and
  3812. // the semantic constraints are checked, at the point where the
  3813. // default argument expression appears.
  3814. ContextRAII SavedContext(*this, FD);
  3815. LocalInstantiationScope Local(*this);
  3816. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3817. }
  3818. if (Result.isInvalid())
  3819. return ExprError();
  3820. // Check the expression as an initializer for the parameter.
  3821. InitializedEntity Entity
  3822. = InitializedEntity::InitializeParameter(Context, Param);
  3823. InitializationKind Kind
  3824. = InitializationKind::CreateCopy(Param->getLocation(),
  3825. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3826. Expr *ResultE = Result.getAs<Expr>();
  3827. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3828. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3829. if (Result.isInvalid())
  3830. return ExprError();
  3831. Expr *Arg = Result.getAs<Expr>();
  3832. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3833. // Build the default argument expression.
  3834. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3835. }
  3836. // If the default expression creates temporaries, we need to
  3837. // push them to the current stack of expression temporaries so they'll
  3838. // be properly destroyed.
  3839. // FIXME: We should really be rebuilding the default argument with new
  3840. // bound temporaries; see the comment in PR5810.
  3841. // We don't need to do that with block decls, though, because
  3842. // blocks in default argument expression can never capture anything.
  3843. if (isa<ExprWithCleanups>(Param->getInit())) {
  3844. // Set the "needs cleanups" bit regardless of whether there are
  3845. // any explicit objects.
  3846. ExprNeedsCleanups = true;
  3847. // Append all the objects to the cleanup list. Right now, this
  3848. // should always be a no-op, because blocks in default argument
  3849. // expressions should never be able to capture anything.
  3850. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3851. "default argument expression has capturing blocks?");
  3852. }
  3853. // We already type-checked the argument, so we know it works.
  3854. // Just mark all of the declarations in this potentially-evaluated expression
  3855. // as being "referenced".
  3856. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3857. /*SkipLocalVariables=*/true);
  3858. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3859. }
  3860. Sema::VariadicCallType
  3861. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3862. Expr *Fn) {
  3863. if (Proto && Proto->isVariadic()) {
  3864. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3865. return VariadicConstructor;
  3866. else if (Fn && Fn->getType()->isBlockPointerType())
  3867. return VariadicBlock;
  3868. else if (FDecl) {
  3869. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3870. if (Method->isInstance())
  3871. return VariadicMethod;
  3872. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3873. return VariadicMethod;
  3874. return VariadicFunction;
  3875. }
  3876. return VariadicDoesNotApply;
  3877. }
  3878. namespace {
  3879. class FunctionCallCCC : public FunctionCallFilterCCC {
  3880. public:
  3881. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3882. unsigned NumArgs, MemberExpr *ME)
  3883. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3884. FunctionName(FuncName) {}
  3885. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3886. if (!candidate.getCorrectionSpecifier() ||
  3887. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3888. return false;
  3889. }
  3890. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3891. }
  3892. private:
  3893. const IdentifierInfo *const FunctionName;
  3894. };
  3895. }
  3896. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3897. FunctionDecl *FDecl,
  3898. ArrayRef<Expr *> Args) {
  3899. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3900. DeclarationName FuncName = FDecl->getDeclName();
  3901. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3902. if (TypoCorrection Corrected = S.CorrectTypo(
  3903. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3904. S.getScopeForContext(S.CurContext), nullptr,
  3905. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3906. Args.size(), ME),
  3907. Sema::CTK_ErrorRecovery)) {
  3908. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3909. if (Corrected.isOverloaded()) {
  3910. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3911. OverloadCandidateSet::iterator Best;
  3912. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3913. CDEnd = Corrected.end();
  3914. CD != CDEnd; ++CD) {
  3915. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3916. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3917. OCS);
  3918. }
  3919. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3920. case OR_Success:
  3921. ND = Best->Function;
  3922. Corrected.setCorrectionDecl(ND);
  3923. break;
  3924. default:
  3925. break;
  3926. }
  3927. }
  3928. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3929. return Corrected;
  3930. }
  3931. }
  3932. }
  3933. return TypoCorrection();
  3934. }
  3935. /// ConvertArgumentsForCall - Converts the arguments specified in
  3936. /// Args/NumArgs to the parameter types of the function FDecl with
  3937. /// function prototype Proto. Call is the call expression itself, and
  3938. /// Fn is the function expression. For a C++ member function, this
  3939. /// routine does not attempt to convert the object argument. Returns
  3940. /// true if the call is ill-formed.
  3941. bool
  3942. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3943. FunctionDecl *FDecl,
  3944. const FunctionProtoType *Proto,
  3945. ArrayRef<Expr *> Args,
  3946. SourceLocation RParenLoc,
  3947. bool IsExecConfig) {
  3948. // Bail out early if calling a builtin with custom typechecking.
  3949. if (FDecl)
  3950. if (unsigned ID = FDecl->getBuiltinID())
  3951. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3952. return false;
  3953. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3954. // assignment, to the types of the corresponding parameter, ...
  3955. unsigned NumParams = Proto->getNumParams();
  3956. bool Invalid = false;
  3957. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3958. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3959. ? 1 /* block */
  3960. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3961. : 0 /* function */);
  3962. // If too few arguments are available (and we don't have default
  3963. // arguments for the remaining parameters), don't make the call.
  3964. if (Args.size() < NumParams) {
  3965. if (Args.size() < MinArgs) {
  3966. TypoCorrection TC;
  3967. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3968. unsigned diag_id =
  3969. MinArgs == NumParams && !Proto->isVariadic()
  3970. ? diag::err_typecheck_call_too_few_args_suggest
  3971. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3972. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3973. << static_cast<unsigned>(Args.size())
  3974. << TC.getCorrectionRange());
  3975. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3976. Diag(RParenLoc,
  3977. MinArgs == NumParams && !Proto->isVariadic()
  3978. ? diag::err_typecheck_call_too_few_args_one
  3979. : diag::err_typecheck_call_too_few_args_at_least_one)
  3980. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3981. else
  3982. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3983. ? diag::err_typecheck_call_too_few_args
  3984. : diag::err_typecheck_call_too_few_args_at_least)
  3985. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3986. << Fn->getSourceRange();
  3987. // Emit the location of the prototype.
  3988. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3989. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3990. << FDecl;
  3991. return true;
  3992. }
  3993. Call->setNumArgs(Context, NumParams);
  3994. }
  3995. // If too many are passed and not variadic, error on the extras and drop
  3996. // them.
  3997. if (Args.size() > NumParams) {
  3998. if (!Proto->isVariadic()) {
  3999. TypoCorrection TC;
  4000. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4001. unsigned diag_id =
  4002. MinArgs == NumParams && !Proto->isVariadic()
  4003. ? diag::err_typecheck_call_too_many_args_suggest
  4004. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4005. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4006. << static_cast<unsigned>(Args.size())
  4007. << TC.getCorrectionRange());
  4008. } else if (NumParams == 1 && FDecl &&
  4009. FDecl->getParamDecl(0)->getDeclName())
  4010. Diag(Args[NumParams]->getLocStart(),
  4011. MinArgs == NumParams
  4012. ? diag::err_typecheck_call_too_many_args_one
  4013. : diag::err_typecheck_call_too_many_args_at_most_one)
  4014. << FnKind << FDecl->getParamDecl(0)
  4015. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4016. << SourceRange(Args[NumParams]->getLocStart(),
  4017. Args.back()->getLocEnd());
  4018. else
  4019. Diag(Args[NumParams]->getLocStart(),
  4020. MinArgs == NumParams
  4021. ? diag::err_typecheck_call_too_many_args
  4022. : diag::err_typecheck_call_too_many_args_at_most)
  4023. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4024. << Fn->getSourceRange()
  4025. << SourceRange(Args[NumParams]->getLocStart(),
  4026. Args.back()->getLocEnd());
  4027. // Emit the location of the prototype.
  4028. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4029. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4030. << FDecl;
  4031. // This deletes the extra arguments.
  4032. Call->setNumArgs(Context, NumParams);
  4033. return true;
  4034. }
  4035. }
  4036. SmallVector<Expr *, 8> AllArgs;
  4037. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4038. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  4039. Proto, 0, Args, AllArgs, CallType);
  4040. if (Invalid)
  4041. return true;
  4042. unsigned TotalNumArgs = AllArgs.size();
  4043. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4044. Call->setArg(i, AllArgs[i]);
  4045. return false;
  4046. }
  4047. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4048. const FunctionProtoType *Proto,
  4049. unsigned FirstParam, ArrayRef<Expr *> Args,
  4050. SmallVectorImpl<Expr *> &AllArgs,
  4051. VariadicCallType CallType, bool AllowExplicit,
  4052. bool IsListInitialization) {
  4053. unsigned NumParams = Proto->getNumParams();
  4054. bool Invalid = false;
  4055. unsigned ArgIx = 0;
  4056. // Continue to check argument types (even if we have too few/many args).
  4057. for (unsigned i = FirstParam; i < NumParams; i++) {
  4058. QualType ProtoArgType = Proto->getParamType(i);
  4059. Expr *Arg;
  4060. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4061. if (ArgIx < Args.size()) {
  4062. Arg = Args[ArgIx++];
  4063. if (!(getLangOpts().HLSL && ProtoArgType->isIncompleteArrayType()) && // HLSL Change: allow incomplete array
  4064. RequireCompleteType(Arg->getLocStart(),
  4065. ProtoArgType,
  4066. diag::err_call_incomplete_argument, Arg))
  4067. return true;
  4068. // Strip the unbridged-cast placeholder expression off, if applicable.
  4069. bool CFAudited = false;
  4070. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4071. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4072. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4073. Arg = stripARCUnbridgedCast(Arg);
  4074. else if (getLangOpts().ObjCAutoRefCount &&
  4075. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4076. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4077. CFAudited = true;
  4078. InitializedEntity Entity =
  4079. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4080. ProtoArgType)
  4081. : InitializedEntity::InitializeParameter(
  4082. Context, ProtoArgType, Proto->isParamConsumed(i));
  4083. // Remember that parameter belongs to a CF audited API.
  4084. if (CFAudited)
  4085. Entity.setParameterCFAudited();
  4086. ExprResult ArgE = PerformCopyInitialization(
  4087. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4088. if (ArgE.isInvalid())
  4089. return true;
  4090. Arg = ArgE.getAs<Expr>();
  4091. } else {
  4092. assert(Param && "can't use default arguments without a known callee");
  4093. ExprResult ArgExpr =
  4094. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4095. if (ArgExpr.isInvalid())
  4096. return true;
  4097. Arg = ArgExpr.getAs<Expr>();
  4098. }
  4099. // Check for array bounds violations for each argument to the call. This
  4100. // check only triggers warnings when the argument isn't a more complex Expr
  4101. // with its own checking, such as a BinaryOperator.
  4102. CheckArrayAccess(Arg);
  4103. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4104. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4105. AllArgs.push_back(Arg);
  4106. }
  4107. // If this is a variadic call, handle args passed through "...".
  4108. if (CallType != VariadicDoesNotApply) {
  4109. // Assume that extern "C" functions with variadic arguments that
  4110. // return __unknown_anytype aren't *really* variadic.
  4111. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4112. FDecl->isExternC()) {
  4113. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4114. QualType paramType; // ignored
  4115. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  4116. Invalid |= arg.isInvalid();
  4117. AllArgs.push_back(arg.get());
  4118. }
  4119. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4120. } else {
  4121. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4122. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  4123. FDecl);
  4124. Invalid |= Arg.isInvalid();
  4125. AllArgs.push_back(Arg.get());
  4126. }
  4127. }
  4128. // Check for array bounds violations.
  4129. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  4130. CheckArrayAccess(Args[i]);
  4131. }
  4132. return Invalid;
  4133. }
  4134. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4135. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4136. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4137. TL = DTL.getOriginalLoc();
  4138. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4139. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4140. << ATL.getLocalSourceRange();
  4141. }
  4142. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4143. /// array parameter, check that it is non-null, and that if it is formed by
  4144. /// array-to-pointer decay, the underlying array is sufficiently large.
  4145. ///
  4146. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4147. /// array type derivation, then for each call to the function, the value of the
  4148. /// corresponding actual argument shall provide access to the first element of
  4149. /// an array with at least as many elements as specified by the size expression.
  4150. void
  4151. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4152. ParmVarDecl *Param,
  4153. const Expr *ArgExpr) {
  4154. // Static array parameters are not supported in C++.
  4155. if (!Param || getLangOpts().CPlusPlus)
  4156. return;
  4157. QualType OrigTy = Param->getOriginalType();
  4158. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4159. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4160. return;
  4161. if (ArgExpr->isNullPointerConstant(Context,
  4162. Expr::NPC_NeverValueDependent)) {
  4163. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4164. DiagnoseCalleeStaticArrayParam(*this, Param);
  4165. return;
  4166. }
  4167. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4168. if (!CAT)
  4169. return;
  4170. const ConstantArrayType *ArgCAT =
  4171. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4172. if (!ArgCAT)
  4173. return;
  4174. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4175. Diag(CallLoc, diag::warn_static_array_too_small)
  4176. << ArgExpr->getSourceRange()
  4177. << (unsigned) ArgCAT->getSize().getZExtValue()
  4178. << (unsigned) CAT->getSize().getZExtValue();
  4179. DiagnoseCalleeStaticArrayParam(*this, Param);
  4180. }
  4181. }
  4182. /// Given a function expression of unknown-any type, try to rebuild it
  4183. /// to have a function type.
  4184. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4185. /// Is the given type a placeholder that we need to lower out
  4186. /// immediately during argument processing?
  4187. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4188. // Placeholders are never sugared.
  4189. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4190. if (!placeholder) return false;
  4191. switch (placeholder->getKind()) {
  4192. // Ignore all the non-placeholder types.
  4193. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4194. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4195. #include "clang/AST/BuiltinTypes.def"
  4196. return false;
  4197. // We cannot lower out overload sets; they might validly be resolved
  4198. // by the call machinery.
  4199. case BuiltinType::Overload:
  4200. return false;
  4201. // Unbridged casts in ARC can be handled in some call positions and
  4202. // should be left in place.
  4203. case BuiltinType::ARCUnbridgedCast:
  4204. return false;
  4205. // Pseudo-objects should be converted as soon as possible.
  4206. case BuiltinType::PseudoObject:
  4207. return true;
  4208. // The debugger mode could theoretically but currently does not try
  4209. // to resolve unknown-typed arguments based on known parameter types.
  4210. case BuiltinType::UnknownAny:
  4211. return true;
  4212. // These are always invalid as call arguments and should be reported.
  4213. case BuiltinType::BoundMember:
  4214. case BuiltinType::BuiltinFn:
  4215. return true;
  4216. }
  4217. llvm_unreachable("bad builtin type kind");
  4218. }
  4219. /// Check an argument list for placeholders that we won't try to
  4220. /// handle later.
  4221. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4222. // Apply this processing to all the arguments at once instead of
  4223. // dying at the first failure.
  4224. bool hasInvalid = false;
  4225. for (size_t i = 0, e = args.size(); i != e; i++) {
  4226. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4227. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4228. if (result.isInvalid()) hasInvalid = true;
  4229. else args[i] = result.get();
  4230. } else if (hasInvalid) {
  4231. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4232. }
  4233. }
  4234. return hasInvalid;
  4235. }
  4236. /// If a builtin function has a pointer argument with no explicit address
  4237. /// space, than it should be able to accept a pointer to any address
  4238. /// space as input. In order to do this, we need to replace the
  4239. /// standard builtin declaration with one that uses the same address space
  4240. /// as the call.
  4241. ///
  4242. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4243. /// it does not contain any pointer arguments without
  4244. /// an address space qualifer. Otherwise the rewritten
  4245. /// FunctionDecl is returned.
  4246. /// TODO: Handle pointer return types.
  4247. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4248. const FunctionDecl *FDecl,
  4249. MultiExprArg ArgExprs) {
  4250. QualType DeclType = FDecl->getType();
  4251. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4252. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4253. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4254. return nullptr;
  4255. bool NeedsNewDecl = false;
  4256. unsigned i = 0;
  4257. SmallVector<QualType, 8> OverloadParams;
  4258. for (QualType ParamType : FT->param_types()) {
  4259. // Convert array arguments to pointer to simplify type lookup.
  4260. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4261. QualType ArgType = Arg->getType();
  4262. if (!ParamType->isPointerType() ||
  4263. ParamType.getQualifiers().hasAddressSpace() ||
  4264. !ArgType->isPointerType() ||
  4265. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4266. OverloadParams.push_back(ParamType);
  4267. continue;
  4268. }
  4269. NeedsNewDecl = true;
  4270. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4271. QualType PointeeType = ParamType->getPointeeType();
  4272. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4273. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4274. }
  4275. if (!NeedsNewDecl)
  4276. return nullptr;
  4277. FunctionProtoType::ExtProtoInfo EPI;
  4278. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4279. OverloadParams, EPI,
  4280. FT->getParamMods()); // HLSL Change
  4281. DeclContext *Parent = Context.getTranslationUnitDecl();
  4282. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4283. FDecl->getLocation(),
  4284. FDecl->getLocation(),
  4285. FDecl->getIdentifier(),
  4286. OverloadTy,
  4287. /*TInfo=*/nullptr,
  4288. SC_Extern, false,
  4289. /*hasPrototype=*/true);
  4290. SmallVector<ParmVarDecl*, 16> Params;
  4291. FT = cast<FunctionProtoType>(OverloadTy);
  4292. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4293. QualType ParamType = FT->getParamType(i);
  4294. ParmVarDecl *Parm =
  4295. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4296. SourceLocation(), nullptr, ParamType,
  4297. /*TInfo=*/nullptr, SC_None, nullptr);
  4298. Parm->setScopeInfo(0, i);
  4299. Params.push_back(Parm);
  4300. }
  4301. OverloadDecl->setParams(Params);
  4302. return OverloadDecl;
  4303. }
  4304. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4305. /// This provides the location of the left/right parens and a list of comma
  4306. /// locations.
  4307. ExprResult
  4308. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4309. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4310. Expr *ExecConfig, bool IsExecConfig) {
  4311. // Since this might be a postfix expression, get rid of ParenListExprs.
  4312. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4313. if (Result.isInvalid()) return ExprError();
  4314. Fn = Result.get();
  4315. if (checkArgsForPlaceholders(*this, ArgExprs))
  4316. return ExprError();
  4317. if (getLangOpts().CPlusPlus) {
  4318. // If this is a pseudo-destructor expression, build the call immediately.
  4319. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4320. if (!ArgExprs.empty()) {
  4321. // Pseudo-destructor calls should not have any arguments.
  4322. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4323. << FixItHint::CreateRemoval(
  4324. SourceRange(ArgExprs[0]->getLocStart(),
  4325. ArgExprs.back()->getLocEnd()));
  4326. }
  4327. return new (Context)
  4328. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4329. }
  4330. if (Fn->getType() == Context.PseudoObjectTy) {
  4331. ExprResult result = CheckPlaceholderExpr(Fn);
  4332. if (result.isInvalid()) return ExprError();
  4333. Fn = result.get();
  4334. }
  4335. // Determine whether this is a dependent call inside a C++ template,
  4336. // in which case we won't do any semantic analysis now.
  4337. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4338. // Fn.
  4339. bool Dependent = false;
  4340. if (Fn->isTypeDependent())
  4341. Dependent = true;
  4342. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4343. Dependent = true;
  4344. if (Dependent) {
  4345. if (ExecConfig) {
  4346. return new (Context) CUDAKernelCallExpr(
  4347. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4348. Context.DependentTy, VK_RValue, RParenLoc);
  4349. } else {
  4350. return new (Context) CallExpr(
  4351. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4352. }
  4353. }
  4354. // Determine whether this is a call to an object (C++ [over.call.object]).
  4355. if (Fn->getType()->isRecordType())
  4356. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4357. RParenLoc);
  4358. if (Fn->getType() == Context.UnknownAnyTy) {
  4359. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4360. if (result.isInvalid()) return ExprError();
  4361. Fn = result.get();
  4362. }
  4363. if (Fn->getType() == Context.BoundMemberTy) {
  4364. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4365. }
  4366. }
  4367. // Check for overloaded calls. This can happen even in C due to extensions.
  4368. if (Fn->getType() == Context.OverloadTy) {
  4369. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4370. // We aren't supposed to apply this logic for if there's an '&' involved.
  4371. if (!find.HasFormOfMemberPointer) {
  4372. OverloadExpr *ovl = find.Expression;
  4373. if (isa<UnresolvedLookupExpr>(ovl)) {
  4374. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4375. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4376. RParenLoc, ExecConfig);
  4377. } else {
  4378. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4379. RParenLoc);
  4380. }
  4381. }
  4382. }
  4383. // If we're directly calling a function, get the appropriate declaration.
  4384. if (Fn->getType() == Context.UnknownAnyTy) {
  4385. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4386. if (result.isInvalid()) return ExprError();
  4387. Fn = result.get();
  4388. }
  4389. Expr *NakedFn = Fn->IgnoreParens();
  4390. NamedDecl *NDecl = nullptr;
  4391. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4392. if (UnOp->getOpcode() == UO_AddrOf)
  4393. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4394. if (isa<DeclRefExpr>(NakedFn)) {
  4395. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4396. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4397. if (FDecl && FDecl->getBuiltinID()) {
  4398. // Rewrite the function decl for this builtin by replacing paramaters
  4399. // with no explicit address space with the address space of the arguments
  4400. // in ArgExprs.
  4401. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4402. NDecl = FDecl;
  4403. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4404. SourceLocation(), FDecl, false,
  4405. SourceLocation(), FDecl->getType(),
  4406. Fn->getValueKind(), FDecl);
  4407. }
  4408. }
  4409. } else if (isa<MemberExpr>(NakedFn))
  4410. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4411. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4412. if (FD->hasAttr<EnableIfAttr>()) {
  4413. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4414. Diag(Fn->getLocStart(),
  4415. isa<CXXMethodDecl>(FD) ?
  4416. diag::err_ovl_no_viable_member_function_in_call :
  4417. diag::err_ovl_no_viable_function_in_call)
  4418. << FD << FD->getSourceRange();
  4419. Diag(FD->getLocation(),
  4420. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4421. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4422. }
  4423. }
  4424. }
  4425. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4426. ExecConfig, IsExecConfig);
  4427. }
  4428. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4429. ///
  4430. /// __builtin_astype( value, dst type )
  4431. ///
  4432. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4433. SourceLocation BuiltinLoc,
  4434. SourceLocation RParenLoc) {
  4435. ExprValueKind VK = VK_RValue;
  4436. ExprObjectKind OK = OK_Ordinary;
  4437. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4438. QualType SrcTy = E->getType();
  4439. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4440. return ExprError(Diag(BuiltinLoc,
  4441. diag::err_invalid_astype_of_different_size)
  4442. << DstTy
  4443. << SrcTy
  4444. << E->getSourceRange());
  4445. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4446. }
  4447. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4448. /// provided arguments.
  4449. ///
  4450. /// __builtin_convertvector( value, dst type )
  4451. ///
  4452. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4453. SourceLocation BuiltinLoc,
  4454. SourceLocation RParenLoc) {
  4455. TypeSourceInfo *TInfo;
  4456. GetTypeFromParser(ParsedDestTy, &TInfo);
  4457. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4458. }
  4459. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4460. /// i.e. an expression not of \p OverloadTy. The expression should
  4461. /// unary-convert to an expression of function-pointer or
  4462. /// block-pointer type.
  4463. ///
  4464. /// \param NDecl the declaration being called, if available
  4465. ExprResult
  4466. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4467. SourceLocation LParenLoc,
  4468. ArrayRef<Expr *> Args,
  4469. SourceLocation RParenLoc,
  4470. Expr *Config, bool IsExecConfig) {
  4471. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4472. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4473. // Promote the function operand.
  4474. // We special-case function promotion here because we only allow promoting
  4475. // builtin functions to function pointers in the callee of a call.
  4476. ExprResult Result;
  4477. if (BuiltinID &&
  4478. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4479. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4480. CK_BuiltinFnToFnPtr).get();
  4481. } else {
  4482. Result = CallExprUnaryConversions(Fn);
  4483. }
  4484. if (Result.isInvalid())
  4485. return ExprError();
  4486. Fn = Result.get();
  4487. // Make the call expr early, before semantic checks. This guarantees cleanup
  4488. // of arguments and function on error.
  4489. CallExpr *TheCall;
  4490. if (Config)
  4491. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4492. cast<CallExpr>(Config), Args,
  4493. Context.BoolTy, VK_RValue,
  4494. RParenLoc);
  4495. else
  4496. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4497. VK_RValue, RParenLoc);
  4498. if (!getLangOpts().CPlusPlus) {
  4499. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4500. // function calls as their argument checking don't necessarily handle
  4501. // dependent types properly, so make sure any TypoExprs have been
  4502. // dealt with.
  4503. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4504. if (!Result.isUsable()) return ExprError();
  4505. TheCall = dyn_cast<CallExpr>(Result.get());
  4506. if (!TheCall) return Result;
  4507. Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs());
  4508. }
  4509. // Bail out early if calling a builtin with custom typechecking.
  4510. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4511. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4512. retry:
  4513. const FunctionType *FuncT;
  4514. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4515. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4516. // have type pointer to function".
  4517. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4518. if (!FuncT)
  4519. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4520. << Fn->getType() << Fn->getSourceRange());
  4521. } else if (const BlockPointerType *BPT =
  4522. Fn->getType()->getAs<BlockPointerType>()) {
  4523. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4524. } else {
  4525. // Handle calls to expressions of unknown-any type.
  4526. if (Fn->getType() == Context.UnknownAnyTy) {
  4527. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4528. if (rewrite.isInvalid()) return ExprError();
  4529. Fn = rewrite.get();
  4530. TheCall->setCallee(Fn);
  4531. goto retry;
  4532. }
  4533. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4534. << Fn->getType() << Fn->getSourceRange());
  4535. }
  4536. if (getLangOpts().CUDA) {
  4537. if (Config) {
  4538. // CUDA: Kernel calls must be to global functions
  4539. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4540. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4541. << FDecl->getName() << Fn->getSourceRange());
  4542. // CUDA: Kernel function must have 'void' return type
  4543. if (!FuncT->getReturnType()->isVoidType())
  4544. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4545. << Fn->getType() << Fn->getSourceRange());
  4546. } else {
  4547. // CUDA: Calls to global functions must be configured
  4548. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4549. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4550. << FDecl->getName() << Fn->getSourceRange());
  4551. }
  4552. }
  4553. // Check for a valid return type
  4554. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4555. FDecl))
  4556. return ExprError();
  4557. // We know the result type of the call, set it.
  4558. TheCall->setType(FuncT->getCallResultType(Context));
  4559. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4560. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4561. if (Proto) {
  4562. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4563. IsExecConfig))
  4564. return ExprError();
  4565. } else {
  4566. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4567. if (FDecl) {
  4568. // Check if we have too few/too many template arguments, based
  4569. // on our knowledge of the function definition.
  4570. const FunctionDecl *Def = nullptr;
  4571. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4572. Proto = Def->getType()->getAs<FunctionProtoType>();
  4573. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4574. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4575. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4576. }
  4577. // If the function we're calling isn't a function prototype, but we have
  4578. // a function prototype from a prior declaratiom, use that prototype.
  4579. if (!FDecl->hasPrototype())
  4580. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4581. }
  4582. // Promote the arguments (C99 6.5.2.2p6).
  4583. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4584. Expr *Arg = Args[i];
  4585. if (Proto && i < Proto->getNumParams()) {
  4586. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4587. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4588. ExprResult ArgE =
  4589. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4590. if (ArgE.isInvalid())
  4591. return true;
  4592. Arg = ArgE.getAs<Expr>();
  4593. } else {
  4594. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4595. if (ArgE.isInvalid())
  4596. return true;
  4597. Arg = ArgE.getAs<Expr>();
  4598. }
  4599. if (RequireCompleteType(Arg->getLocStart(),
  4600. Arg->getType(),
  4601. diag::err_call_incomplete_argument, Arg))
  4602. return ExprError();
  4603. TheCall->setArg(i, Arg);
  4604. }
  4605. }
  4606. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4607. if (!Method->isStatic())
  4608. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4609. << Fn->getSourceRange());
  4610. // Check for sentinels
  4611. if (NDecl)
  4612. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4613. // Do special checking on direct calls to functions.
  4614. if (FDecl) {
  4615. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4616. return ExprError();
  4617. if (BuiltinID)
  4618. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4619. } else if (NDecl) {
  4620. if (CheckPointerCall(NDecl, TheCall, Proto))
  4621. return ExprError();
  4622. } else {
  4623. if (CheckOtherCall(TheCall, Proto))
  4624. return ExprError();
  4625. }
  4626. return MaybeBindToTemporary(TheCall);
  4627. }
  4628. ExprResult
  4629. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4630. SourceLocation RParenLoc, Expr *InitExpr) {
  4631. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4632. // FIXME: put back this assert when initializers are worked out.
  4633. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  4634. TypeSourceInfo *TInfo;
  4635. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4636. if (!TInfo)
  4637. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4638. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4639. }
  4640. ExprResult
  4641. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4642. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4643. QualType literalType = TInfo->getType();
  4644. if (literalType->isArrayType()) {
  4645. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4646. diag::err_illegal_decl_array_incomplete_type,
  4647. SourceRange(LParenLoc,
  4648. LiteralExpr->getSourceRange().getEnd())))
  4649. return ExprError();
  4650. if (literalType->isVariableArrayType())
  4651. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4652. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4653. } else if (!literalType->isDependentType() &&
  4654. RequireCompleteType(LParenLoc, literalType,
  4655. diag::err_typecheck_decl_incomplete_type,
  4656. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4657. return ExprError();
  4658. InitializedEntity Entity
  4659. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4660. InitializationKind Kind
  4661. = InitializationKind::CreateCStyleCast(LParenLoc,
  4662. SourceRange(LParenLoc, RParenLoc),
  4663. /*InitList=*/true);
  4664. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4665. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4666. &literalType);
  4667. if (Result.isInvalid())
  4668. return ExprError();
  4669. LiteralExpr = Result.get();
  4670. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4671. if (isFileScope &&
  4672. !LiteralExpr->isTypeDependent() &&
  4673. !LiteralExpr->isValueDependent() &&
  4674. !literalType->isDependentType()) { // 6.5.2.5p3
  4675. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4676. return ExprError();
  4677. }
  4678. // In C, compound literals are l-values for some reason.
  4679. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4680. return MaybeBindToTemporary(
  4681. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4682. VK, LiteralExpr, isFileScope));
  4683. }
  4684. ExprResult
  4685. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4686. SourceLocation RBraceLoc) {
  4687. // Immediately handle non-overload placeholders. Overloads can be
  4688. // resolved contextually, but everything else here can't.
  4689. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4690. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4691. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4692. // Ignore failures; dropping the entire initializer list because
  4693. // of one failure would be terrible for indexing/etc.
  4694. if (result.isInvalid()) continue;
  4695. InitArgList[I] = result.get();
  4696. }
  4697. }
  4698. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4699. // CheckInitializer() - it requires knowledge of the object being intialized.
  4700. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4701. RBraceLoc);
  4702. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4703. return E;
  4704. }
  4705. /// Do an explicit extend of the given block pointer if we're in ARC.
  4706. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4707. assert(E.get()->getType()->isBlockPointerType());
  4708. assert(E.get()->isRValue());
  4709. // Only do this in an r-value context.
  4710. if (!getLangOpts().ObjCAutoRefCount) return;
  4711. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4712. CK_ARCExtendBlockObject, E.get(),
  4713. /*base path*/ nullptr, VK_RValue);
  4714. ExprNeedsCleanups = true;
  4715. }
  4716. /// Prepare a conversion of the given expression to an ObjC object
  4717. /// pointer type.
  4718. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4719. QualType type = E.get()->getType();
  4720. if (type->isObjCObjectPointerType()) {
  4721. return CK_BitCast;
  4722. } else if (type->isBlockPointerType()) {
  4723. maybeExtendBlockObject(E);
  4724. return CK_BlockPointerToObjCPointerCast;
  4725. } else {
  4726. assert(type->isPointerType());
  4727. return CK_CPointerToObjCPointerCast;
  4728. }
  4729. }
  4730. /// Prepares for a scalar cast, performing all the necessary stages
  4731. /// except the final cast and returning the kind required.
  4732. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4733. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4734. // Also, callers should have filtered out the invalid cases with
  4735. // pointers. Everything else should be possible.
  4736. QualType SrcTy = Src.get()->getType();
  4737. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4738. return CK_NoOp;
  4739. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4740. case Type::STK_MemberPointer:
  4741. llvm_unreachable("member pointer type in C");
  4742. case Type::STK_CPointer:
  4743. case Type::STK_BlockPointer:
  4744. case Type::STK_ObjCObjectPointer:
  4745. switch (DestTy->getScalarTypeKind()) {
  4746. case Type::STK_CPointer: {
  4747. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4748. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4749. if (SrcAS != DestAS)
  4750. return CK_AddressSpaceConversion;
  4751. return CK_BitCast;
  4752. }
  4753. case Type::STK_BlockPointer:
  4754. return (SrcKind == Type::STK_BlockPointer
  4755. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4756. case Type::STK_ObjCObjectPointer:
  4757. if (SrcKind == Type::STK_ObjCObjectPointer)
  4758. return CK_BitCast;
  4759. if (SrcKind == Type::STK_CPointer)
  4760. return CK_CPointerToObjCPointerCast;
  4761. maybeExtendBlockObject(Src);
  4762. return CK_BlockPointerToObjCPointerCast;
  4763. case Type::STK_Bool:
  4764. return CK_PointerToBoolean;
  4765. case Type::STK_Integral:
  4766. return CK_PointerToIntegral;
  4767. case Type::STK_Floating:
  4768. case Type::STK_FloatingComplex:
  4769. case Type::STK_IntegralComplex:
  4770. case Type::STK_MemberPointer:
  4771. llvm_unreachable("illegal cast from pointer");
  4772. }
  4773. llvm_unreachable("Should have returned before this");
  4774. case Type::STK_Bool: // casting from bool is like casting from an integer
  4775. case Type::STK_Integral:
  4776. switch (DestTy->getScalarTypeKind()) {
  4777. case Type::STK_CPointer:
  4778. case Type::STK_ObjCObjectPointer:
  4779. case Type::STK_BlockPointer:
  4780. if (Src.get()->isNullPointerConstant(Context,
  4781. Expr::NPC_ValueDependentIsNull))
  4782. return CK_NullToPointer;
  4783. return CK_IntegralToPointer;
  4784. case Type::STK_Bool:
  4785. return CK_IntegralToBoolean;
  4786. case Type::STK_Integral:
  4787. return CK_IntegralCast;
  4788. case Type::STK_Floating:
  4789. return CK_IntegralToFloating;
  4790. case Type::STK_IntegralComplex:
  4791. Src = ImpCastExprToType(Src.get(),
  4792. DestTy->castAs<ComplexType>()->getElementType(),
  4793. CK_IntegralCast);
  4794. return CK_IntegralRealToComplex;
  4795. case Type::STK_FloatingComplex:
  4796. Src = ImpCastExprToType(Src.get(),
  4797. DestTy->castAs<ComplexType>()->getElementType(),
  4798. CK_IntegralToFloating);
  4799. return CK_FloatingRealToComplex;
  4800. case Type::STK_MemberPointer:
  4801. llvm_unreachable("member pointer type in C");
  4802. }
  4803. llvm_unreachable("Should have returned before this");
  4804. case Type::STK_Floating:
  4805. switch (DestTy->getScalarTypeKind()) {
  4806. case Type::STK_Floating:
  4807. return CK_FloatingCast;
  4808. case Type::STK_Bool:
  4809. return CK_FloatingToBoolean;
  4810. case Type::STK_Integral:
  4811. return CK_FloatingToIntegral;
  4812. case Type::STK_FloatingComplex:
  4813. Src = ImpCastExprToType(Src.get(),
  4814. DestTy->castAs<ComplexType>()->getElementType(),
  4815. CK_FloatingCast);
  4816. return CK_FloatingRealToComplex;
  4817. case Type::STK_IntegralComplex:
  4818. Src = ImpCastExprToType(Src.get(),
  4819. DestTy->castAs<ComplexType>()->getElementType(),
  4820. CK_FloatingToIntegral);
  4821. return CK_IntegralRealToComplex;
  4822. case Type::STK_CPointer:
  4823. case Type::STK_ObjCObjectPointer:
  4824. case Type::STK_BlockPointer:
  4825. llvm_unreachable("valid float->pointer cast?");
  4826. case Type::STK_MemberPointer:
  4827. llvm_unreachable("member pointer type in C");
  4828. }
  4829. llvm_unreachable("Should have returned before this");
  4830. case Type::STK_FloatingComplex:
  4831. switch (DestTy->getScalarTypeKind()) {
  4832. case Type::STK_FloatingComplex:
  4833. return CK_FloatingComplexCast;
  4834. case Type::STK_IntegralComplex:
  4835. return CK_FloatingComplexToIntegralComplex;
  4836. case Type::STK_Floating: {
  4837. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4838. if (Context.hasSameType(ET, DestTy))
  4839. return CK_FloatingComplexToReal;
  4840. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4841. return CK_FloatingCast;
  4842. }
  4843. case Type::STK_Bool:
  4844. return CK_FloatingComplexToBoolean;
  4845. case Type::STK_Integral:
  4846. Src = ImpCastExprToType(Src.get(),
  4847. SrcTy->castAs<ComplexType>()->getElementType(),
  4848. CK_FloatingComplexToReal);
  4849. return CK_FloatingToIntegral;
  4850. case Type::STK_CPointer:
  4851. case Type::STK_ObjCObjectPointer:
  4852. case Type::STK_BlockPointer:
  4853. llvm_unreachable("valid complex float->pointer cast?");
  4854. case Type::STK_MemberPointer:
  4855. llvm_unreachable("member pointer type in C");
  4856. }
  4857. llvm_unreachable("Should have returned before this");
  4858. case Type::STK_IntegralComplex:
  4859. switch (DestTy->getScalarTypeKind()) {
  4860. case Type::STK_FloatingComplex:
  4861. return CK_IntegralComplexToFloatingComplex;
  4862. case Type::STK_IntegralComplex:
  4863. return CK_IntegralComplexCast;
  4864. case Type::STK_Integral: {
  4865. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4866. if (Context.hasSameType(ET, DestTy))
  4867. return CK_IntegralComplexToReal;
  4868. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4869. return CK_IntegralCast;
  4870. }
  4871. case Type::STK_Bool:
  4872. return CK_IntegralComplexToBoolean;
  4873. case Type::STK_Floating:
  4874. Src = ImpCastExprToType(Src.get(),
  4875. SrcTy->castAs<ComplexType>()->getElementType(),
  4876. CK_IntegralComplexToReal);
  4877. return CK_IntegralToFloating;
  4878. case Type::STK_CPointer:
  4879. case Type::STK_ObjCObjectPointer:
  4880. case Type::STK_BlockPointer:
  4881. llvm_unreachable("valid complex int->pointer cast?");
  4882. case Type::STK_MemberPointer:
  4883. llvm_unreachable("member pointer type in C");
  4884. }
  4885. llvm_unreachable("Should have returned before this");
  4886. }
  4887. llvm_unreachable("Unhandled scalar cast");
  4888. }
  4889. static bool breakDownVectorType(QualType type, uint64_t &len,
  4890. QualType &eltType) {
  4891. // Vectors are simple.
  4892. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4893. len = vecType->getNumElements();
  4894. eltType = vecType->getElementType();
  4895. assert(eltType->isScalarType());
  4896. return true;
  4897. }
  4898. // We allow lax conversion to and from non-vector types, but only if
  4899. // they're real types (i.e. non-complex, non-pointer scalar types).
  4900. if (!type->isRealType()) return false;
  4901. len = 1;
  4902. eltType = type;
  4903. return true;
  4904. }
  4905. static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
  4906. uint64_t srcLen, destLen;
  4907. QualType srcElt, destElt;
  4908. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4909. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4910. // ASTContext::getTypeSize will return the size rounded up to a
  4911. // power of 2, so instead of using that, we need to use the raw
  4912. // element size multiplied by the element count.
  4913. uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
  4914. uint64_t destEltSize = S.Context.getTypeSize(destElt);
  4915. return (srcLen * srcEltSize == destLen * destEltSize);
  4916. }
  4917. /// Is this a legal conversion between two known vector types?
  4918. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4919. assert(destTy->isVectorType() || srcTy->isVectorType());
  4920. if (!Context.getLangOpts().LaxVectorConversions)
  4921. return false;
  4922. return VectorTypesMatch(*this, srcTy, destTy);
  4923. }
  4924. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4925. CastKind &Kind) {
  4926. assert(VectorTy->isVectorType() && "Not a vector type!");
  4927. if (Ty->isVectorType() || Ty->isIntegerType()) {
  4928. if (!VectorTypesMatch(*this, Ty, VectorTy))
  4929. return Diag(R.getBegin(),
  4930. Ty->isVectorType() ?
  4931. diag::err_invalid_conversion_between_vectors :
  4932. diag::err_invalid_conversion_between_vector_and_integer)
  4933. << VectorTy << Ty << R;
  4934. } else
  4935. return Diag(R.getBegin(),
  4936. diag::err_invalid_conversion_between_vector_and_scalar)
  4937. << VectorTy << Ty << R;
  4938. Kind = CK_BitCast;
  4939. return false;
  4940. }
  4941. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4942. Expr *CastExpr, CastKind &Kind) {
  4943. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4944. QualType SrcTy = CastExpr->getType();
  4945. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4946. // an ExtVectorType.
  4947. // In OpenCL, casts between vectors of different types are not allowed.
  4948. // (See OpenCL 6.2).
  4949. if (SrcTy->isVectorType()) {
  4950. if (!VectorTypesMatch(*this, SrcTy, DestTy)
  4951. || (getLangOpts().OpenCL &&
  4952. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4953. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4954. << DestTy << SrcTy << R;
  4955. return ExprError();
  4956. }
  4957. Kind = CK_BitCast;
  4958. return CastExpr;
  4959. }
  4960. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4961. // conversion will take place first from scalar to elt type, and then
  4962. // splat from elt type to vector.
  4963. if (SrcTy->isPointerType())
  4964. return Diag(R.getBegin(),
  4965. diag::err_invalid_conversion_between_vector_and_scalar)
  4966. << DestTy << SrcTy << R;
  4967. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4968. ExprResult CastExprRes = CastExpr;
  4969. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4970. if (CastExprRes.isInvalid())
  4971. return ExprError();
  4972. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4973. Kind = CK_VectorSplat;
  4974. return CastExpr;
  4975. }
  4976. ExprResult
  4977. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4978. Declarator &D, ParsedType &Ty,
  4979. SourceLocation RParenLoc, Expr *CastExpr) {
  4980. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4981. "ActOnCastExpr(): missing type or expr");
  4982. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4983. if (D.isInvalidType())
  4984. return ExprError();
  4985. if (getLangOpts().CPlusPlus) {
  4986. // Check that there are no default arguments (C++ only).
  4987. CheckExtraCXXDefaultArguments(D);
  4988. } else {
  4989. // Make sure any TypoExprs have been dealt with.
  4990. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4991. if (!Res.isUsable())
  4992. return ExprError();
  4993. CastExpr = Res.get();
  4994. }
  4995. checkUnusedDeclAttributes(D);
  4996. QualType castType = castTInfo->getType();
  4997. Ty = CreateParsedType(castType, castTInfo);
  4998. bool isVectorLiteral = false;
  4999. // Check for an altivec or OpenCL literal,
  5000. // i.e. all the elements are integer constants.
  5001. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5002. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5003. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5004. && castType->isVectorType() && (PE || PLE)) {
  5005. if (PLE && PLE->getNumExprs() == 0) {
  5006. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5007. return ExprError();
  5008. }
  5009. if (PE || PLE->getNumExprs() == 1) {
  5010. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5011. if (!E->getType()->isVectorType())
  5012. isVectorLiteral = true;
  5013. }
  5014. else
  5015. isVectorLiteral = true;
  5016. }
  5017. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5018. // then handle it as such.
  5019. if (isVectorLiteral)
  5020. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5021. // If the Expr being casted is a ParenListExpr, handle it specially.
  5022. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5023. // sequence of BinOp comma operators.
  5024. if (isa<ParenListExpr>(CastExpr)) {
  5025. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5026. if (Result.isInvalid()) return ExprError();
  5027. CastExpr = Result.get();
  5028. }
  5029. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5030. !getSourceManager().isInSystemMacro(LParenLoc))
  5031. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5032. #if 0 // HLSL Change - no support for ObjC constructs
  5033. CheckTollFreeBridgeCast(castType, CastExpr);
  5034. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5035. #endif // HLSL Change
  5036. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5037. }
  5038. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5039. SourceLocation RParenLoc, Expr *E,
  5040. TypeSourceInfo *TInfo) {
  5041. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5042. "Expected paren or paren list expression");
  5043. Expr **exprs;
  5044. unsigned numExprs;
  5045. Expr *subExpr;
  5046. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5047. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5048. LiteralLParenLoc = PE->getLParenLoc();
  5049. LiteralRParenLoc = PE->getRParenLoc();
  5050. exprs = PE->getExprs();
  5051. numExprs = PE->getNumExprs();
  5052. } else { // isa<ParenExpr> by assertion at function entrance
  5053. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5054. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5055. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5056. exprs = &subExpr;
  5057. numExprs = 1;
  5058. }
  5059. QualType Ty = TInfo->getType();
  5060. assert(Ty->isVectorType() && "Expected vector type");
  5061. SmallVector<Expr *, 8> initExprs;
  5062. const VectorType *VTy = Ty->getAs<VectorType>();
  5063. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5064. // '(...)' form of vector initialization in AltiVec: the number of
  5065. // initializers must be one or must match the size of the vector.
  5066. // If a single value is specified in the initializer then it will be
  5067. // replicated to all the components of the vector
  5068. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5069. // The number of initializers must be one or must match the size of the
  5070. // vector. If a single value is specified in the initializer then it will
  5071. // be replicated to all the components of the vector
  5072. if (numExprs == 1) {
  5073. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5074. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5075. if (Literal.isInvalid())
  5076. return ExprError();
  5077. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5078. PrepareScalarCast(Literal, ElemTy));
  5079. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5080. }
  5081. else if (numExprs < numElems) {
  5082. Diag(E->getExprLoc(),
  5083. diag::err_incorrect_number_of_vector_initializers);
  5084. return ExprError();
  5085. }
  5086. else
  5087. initExprs.append(exprs, exprs + numExprs);
  5088. }
  5089. else {
  5090. // For OpenCL, when the number of initializers is a single value,
  5091. // it will be replicated to all components of the vector.
  5092. if (getLangOpts().OpenCL &&
  5093. VTy->getVectorKind() == VectorType::GenericVector &&
  5094. numExprs == 1) {
  5095. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5096. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5097. if (Literal.isInvalid())
  5098. return ExprError();
  5099. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5100. PrepareScalarCast(Literal, ElemTy));
  5101. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5102. }
  5103. initExprs.append(exprs, exprs + numExprs);
  5104. }
  5105. // FIXME: This means that pretty-printing the final AST will produce curly
  5106. // braces instead of the original commas.
  5107. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5108. initExprs, LiteralRParenLoc);
  5109. initE->setType(Ty);
  5110. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5111. }
  5112. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5113. /// the ParenListExpr into a sequence of comma binary operators.
  5114. ExprResult
  5115. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5116. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5117. if (!E)
  5118. return OrigExpr;
  5119. ExprResult Result(E->getExpr(0));
  5120. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5121. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5122. E->getExpr(i));
  5123. if (Result.isInvalid()) return ExprError();
  5124. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5125. }
  5126. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5127. SourceLocation R,
  5128. MultiExprArg Val) {
  5129. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5130. return expr;
  5131. }
  5132. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5133. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5134. /// emitted.
  5135. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5136. SourceLocation QuestionLoc) {
  5137. Expr *NullExpr = LHSExpr;
  5138. Expr *NonPointerExpr = RHSExpr;
  5139. Expr::NullPointerConstantKind NullKind =
  5140. NullExpr->isNullPointerConstant(Context,
  5141. Expr::NPC_ValueDependentIsNotNull);
  5142. if (NullKind == Expr::NPCK_NotNull) {
  5143. NullExpr = RHSExpr;
  5144. NonPointerExpr = LHSExpr;
  5145. NullKind =
  5146. NullExpr->isNullPointerConstant(Context,
  5147. Expr::NPC_ValueDependentIsNotNull);
  5148. }
  5149. if (NullKind == Expr::NPCK_NotNull)
  5150. return false;
  5151. if (NullKind == Expr::NPCK_ZeroExpression)
  5152. return false;
  5153. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5154. // In this case, check to make sure that we got here from a "NULL"
  5155. // string in the source code.
  5156. NullExpr = NullExpr->IgnoreParenImpCasts();
  5157. SourceLocation loc = NullExpr->getExprLoc();
  5158. if (!findMacroSpelling(loc, "NULL"))
  5159. return false;
  5160. }
  5161. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5162. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5163. << NonPointerExpr->getType() << DiagType
  5164. << NonPointerExpr->getSourceRange();
  5165. return true;
  5166. }
  5167. /// \brief Return false if the condition expression is valid, true otherwise.
  5168. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5169. QualType CondTy = Cond->getType();
  5170. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5171. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5172. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5173. << CondTy << Cond->getSourceRange();
  5174. return true;
  5175. }
  5176. // C99 6.5.15p2
  5177. if (CondTy->isScalarType()) return false;
  5178. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5179. << CondTy << Cond->getSourceRange();
  5180. return true;
  5181. }
  5182. /// \brief Handle when one or both operands are void type.
  5183. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5184. ExprResult &RHS) {
  5185. Expr *LHSExpr = LHS.get();
  5186. Expr *RHSExpr = RHS.get();
  5187. if (!LHSExpr->getType()->isVoidType())
  5188. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5189. << RHSExpr->getSourceRange();
  5190. if (!RHSExpr->getType()->isVoidType())
  5191. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5192. << LHSExpr->getSourceRange();
  5193. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5194. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5195. return S.Context.VoidTy;
  5196. }
  5197. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5198. /// true otherwise.
  5199. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5200. QualType PointerTy) {
  5201. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5202. !NullExpr.get()->isNullPointerConstant(S.Context,
  5203. Expr::NPC_ValueDependentIsNull))
  5204. return true;
  5205. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5206. return false;
  5207. }
  5208. /// \brief Checks compatibility between two pointers and return the resulting
  5209. /// type.
  5210. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5211. ExprResult &RHS,
  5212. SourceLocation Loc) {
  5213. QualType LHSTy = LHS.get()->getType();
  5214. QualType RHSTy = RHS.get()->getType();
  5215. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5216. // Two identical pointers types are always compatible.
  5217. return LHSTy;
  5218. }
  5219. QualType lhptee, rhptee;
  5220. // Get the pointee types.
  5221. bool IsBlockPointer = false;
  5222. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5223. lhptee = LHSBTy->getPointeeType();
  5224. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5225. IsBlockPointer = true;
  5226. } else {
  5227. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5228. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5229. }
  5230. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5231. // differently qualified versions of compatible types, the result type is
  5232. // a pointer to an appropriately qualified version of the composite
  5233. // type.
  5234. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5235. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5236. // be incompatible with address space 3: they may live on different devices or
  5237. // anything.
  5238. Qualifiers lhQual = lhptee.getQualifiers();
  5239. Qualifiers rhQual = rhptee.getQualifiers();
  5240. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5241. lhQual.removeCVRQualifiers();
  5242. rhQual.removeCVRQualifiers();
  5243. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5244. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5245. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5246. if (CompositeTy.isNull()) {
  5247. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5248. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5249. << RHS.get()->getSourceRange();
  5250. // In this situation, we assume void* type. No especially good
  5251. // reason, but this is what gcc does, and we do have to pick
  5252. // to get a consistent AST.
  5253. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5254. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5255. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5256. return incompatTy;
  5257. }
  5258. // The pointer types are compatible.
  5259. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5260. if (IsBlockPointer)
  5261. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5262. else
  5263. ResultTy = S.Context.getPointerType(ResultTy);
  5264. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5265. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5266. return ResultTy;
  5267. }
  5268. /// \brief Return the resulting type when the operands are both block pointers.
  5269. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5270. ExprResult &LHS,
  5271. ExprResult &RHS,
  5272. SourceLocation Loc) {
  5273. QualType LHSTy = LHS.get()->getType();
  5274. QualType RHSTy = RHS.get()->getType();
  5275. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5276. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5277. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5278. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5279. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5280. return destType;
  5281. }
  5282. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5283. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5284. << RHS.get()->getSourceRange();
  5285. return QualType();
  5286. }
  5287. // We have 2 block pointer types.
  5288. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5289. }
  5290. /// \brief Return the resulting type when the operands are both pointers.
  5291. static QualType
  5292. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5293. ExprResult &RHS,
  5294. SourceLocation Loc) {
  5295. // get the pointer types
  5296. QualType LHSTy = LHS.get()->getType();
  5297. QualType RHSTy = RHS.get()->getType();
  5298. // get the "pointed to" types
  5299. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5300. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5301. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5302. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5303. // Figure out necessary qualifiers (C99 6.5.15p6)
  5304. QualType destPointee
  5305. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5306. QualType destType = S.Context.getPointerType(destPointee);
  5307. // Add qualifiers if necessary.
  5308. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5309. // Promote to void*.
  5310. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5311. return destType;
  5312. }
  5313. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5314. QualType destPointee
  5315. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5316. QualType destType = S.Context.getPointerType(destPointee);
  5317. // Add qualifiers if necessary.
  5318. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5319. // Promote to void*.
  5320. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5321. return destType;
  5322. }
  5323. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5324. }
  5325. /// \brief Return false if the first expression is not an integer and the second
  5326. /// expression is not a pointer, true otherwise.
  5327. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5328. Expr* PointerExpr, SourceLocation Loc,
  5329. bool IsIntFirstExpr) {
  5330. if (!PointerExpr->getType()->isPointerType() ||
  5331. !Int.get()->getType()->isIntegerType())
  5332. return false;
  5333. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5334. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5335. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5336. << Expr1->getType() << Expr2->getType()
  5337. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5338. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5339. CK_IntegralToPointer);
  5340. return true;
  5341. }
  5342. /// \brief Simple conversion between integer and floating point types.
  5343. ///
  5344. /// Used when handling the OpenCL conditional operator where the
  5345. /// condition is a vector while the other operands are scalar.
  5346. ///
  5347. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5348. /// types are either integer or floating type. Between the two
  5349. /// operands, the type with the higher rank is defined as the "result
  5350. /// type". The other operand needs to be promoted to the same type. No
  5351. /// other type promotion is allowed. We cannot use
  5352. /// UsualArithmeticConversions() for this purpose, since it always
  5353. /// promotes promotable types.
  5354. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5355. ExprResult &RHS,
  5356. SourceLocation QuestionLoc) {
  5357. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5358. if (LHS.isInvalid())
  5359. return QualType();
  5360. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5361. if (RHS.isInvalid())
  5362. return QualType();
  5363. // For conversion purposes, we ignore any qualifiers.
  5364. // For example, "const float" and "float" are equivalent.
  5365. QualType LHSType =
  5366. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5367. QualType RHSType =
  5368. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5369. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5370. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5371. << LHSType << LHS.get()->getSourceRange();
  5372. return QualType();
  5373. }
  5374. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5375. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5376. << RHSType << RHS.get()->getSourceRange();
  5377. return QualType();
  5378. }
  5379. // If both types are identical, no conversion is needed.
  5380. if (LHSType == RHSType)
  5381. return LHSType;
  5382. // Now handle "real" floating types (i.e. float, double, long double).
  5383. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5384. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5385. /*IsCompAssign = */ false);
  5386. // Finally, we have two differing integer types.
  5387. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5388. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5389. }
  5390. /// \brief Convert scalar operands to a vector that matches the
  5391. /// condition in length.
  5392. ///
  5393. /// Used when handling the OpenCL conditional operator where the
  5394. /// condition is a vector while the other operands are scalar.
  5395. ///
  5396. /// We first compute the "result type" for the scalar operands
  5397. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5398. /// into a vector of that type where the length matches the condition
  5399. /// vector type. s6.11.6 requires that the element types of the result
  5400. /// and the condition must have the same number of bits.
  5401. static QualType
  5402. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5403. QualType CondTy, SourceLocation QuestionLoc) {
  5404. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5405. if (ResTy.isNull()) return QualType();
  5406. const VectorType *CV = CondTy->getAs<VectorType>();
  5407. assert(CV);
  5408. // Determine the vector result type
  5409. unsigned NumElements = CV->getNumElements();
  5410. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5411. // Ensure that all types have the same number of bits
  5412. if (S.Context.getTypeSize(CV->getElementType())
  5413. != S.Context.getTypeSize(ResTy)) {
  5414. // Since VectorTy is created internally, it does not pretty print
  5415. // with an OpenCL name. Instead, we just print a description.
  5416. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5417. SmallString<64> Str;
  5418. llvm::raw_svector_ostream OS(Str);
  5419. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5420. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5421. << CondTy << OS.str();
  5422. return QualType();
  5423. }
  5424. // Convert operands to the vector result type
  5425. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5426. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5427. return VectorTy;
  5428. }
  5429. /// \brief Return false if this is a valid OpenCL condition vector
  5430. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5431. SourceLocation QuestionLoc) {
  5432. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5433. // integral type.
  5434. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5435. assert(CondTy);
  5436. QualType EleTy = CondTy->getElementType();
  5437. if (EleTy->isIntegerType()) return false;
  5438. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5439. << Cond->getType() << Cond->getSourceRange();
  5440. return true;
  5441. }
  5442. /// \brief Return false if the vector condition type and the vector
  5443. /// result type are compatible.
  5444. ///
  5445. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5446. /// number of elements, and their element types have the same number
  5447. /// of bits.
  5448. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5449. SourceLocation QuestionLoc) {
  5450. const VectorType *CV = CondTy->getAs<VectorType>();
  5451. const VectorType *RV = VecResTy->getAs<VectorType>();
  5452. assert(CV && RV);
  5453. if (CV->getNumElements() != RV->getNumElements()) {
  5454. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5455. << CondTy << VecResTy;
  5456. return true;
  5457. }
  5458. QualType CVE = CV->getElementType();
  5459. QualType RVE = RV->getElementType();
  5460. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5461. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5462. << CondTy << VecResTy;
  5463. return true;
  5464. }
  5465. return false;
  5466. }
  5467. /// \brief Return the resulting type for the conditional operator in
  5468. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5469. /// s6.3.i) when the condition is a vector type.
  5470. static QualType
  5471. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5472. ExprResult &LHS, ExprResult &RHS,
  5473. SourceLocation QuestionLoc) {
  5474. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5475. if (Cond.isInvalid())
  5476. return QualType();
  5477. QualType CondTy = Cond.get()->getType();
  5478. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5479. return QualType();
  5480. // If either operand is a vector then find the vector type of the
  5481. // result as specified in OpenCL v1.1 s6.3.i.
  5482. if (LHS.get()->getType()->isVectorType() ||
  5483. RHS.get()->getType()->isVectorType()) {
  5484. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5485. /*isCompAssign*/false,
  5486. /*AllowBothBool*/true,
  5487. /*AllowBoolConversions*/false);
  5488. if (VecResTy.isNull()) return QualType();
  5489. // The result type must match the condition type as specified in
  5490. // OpenCL v1.1 s6.11.6.
  5491. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5492. return QualType();
  5493. return VecResTy;
  5494. }
  5495. // Both operands are scalar.
  5496. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5497. }
  5498. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5499. /// In that case, LHS = cond.
  5500. /// C99 6.5.15
  5501. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5502. ExprResult &RHS, ExprValueKind &VK,
  5503. ExprObjectKind &OK,
  5504. SourceLocation QuestionLoc) {
  5505. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5506. if (!LHSResult.isUsable()) return QualType();
  5507. LHS = LHSResult;
  5508. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5509. if (!RHSResult.isUsable()) return QualType();
  5510. RHS = RHSResult;
  5511. // HLSL Change Starts: HLSL supports a vector condition and is
  5512. // sufficiently different to merit its own checker.
  5513. if (getLangOpts().HLSL)
  5514. return hlsl::CheckVectorConditional(this, Cond, LHS, RHS, QuestionLoc);
  5515. // HLSL Change Ends
  5516. // C++ is sufficiently different to merit its own checker.
  5517. if (getLangOpts().CPlusPlus)
  5518. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5519. VK = VK_RValue;
  5520. OK = OK_Ordinary;
  5521. // The OpenCL operator with a vector condition is sufficiently
  5522. // different to merit its own checker.
  5523. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5524. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5525. // First, check the condition.
  5526. Cond = UsualUnaryConversions(Cond.get());
  5527. if (Cond.isInvalid())
  5528. return QualType();
  5529. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5530. return QualType();
  5531. // Now check the two expressions.
  5532. if (LHS.get()->getType()->isVectorType() ||
  5533. RHS.get()->getType()->isVectorType())
  5534. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5535. /*AllowBothBool*/true,
  5536. /*AllowBoolConversions*/false);
  5537. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5538. if (LHS.isInvalid() || RHS.isInvalid())
  5539. return QualType();
  5540. QualType LHSTy = LHS.get()->getType();
  5541. QualType RHSTy = RHS.get()->getType();
  5542. // If both operands have arithmetic type, do the usual arithmetic conversions
  5543. // to find a common type: C99 6.5.15p3,5.
  5544. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5545. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5546. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5547. return ResTy;
  5548. }
  5549. // If both operands are the same structure or union type, the result is that
  5550. // type.
  5551. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5552. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5553. if (LHSRT->getDecl() == RHSRT->getDecl())
  5554. // "If both the operands have structure or union type, the result has
  5555. // that type." This implies that CV qualifiers are dropped.
  5556. return LHSTy.getUnqualifiedType();
  5557. // FIXME: Type of conditional expression must be complete in C mode.
  5558. }
  5559. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5560. // The following || allows only one side to be void (a GCC-ism).
  5561. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5562. return checkConditionalVoidType(*this, LHS, RHS);
  5563. }
  5564. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5565. // the type of the other operand."
  5566. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5567. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5568. // All objective-c pointer type analysis is done here.
  5569. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5570. QuestionLoc);
  5571. if (LHS.isInvalid() || RHS.isInvalid())
  5572. return QualType();
  5573. if (!compositeType.isNull())
  5574. return compositeType;
  5575. // Handle block pointer types.
  5576. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5577. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5578. QuestionLoc);
  5579. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5580. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5581. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5582. QuestionLoc);
  5583. // GCC compatibility: soften pointer/integer mismatch. Note that
  5584. // null pointers have been filtered out by this point.
  5585. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5586. /*isIntFirstExpr=*/true))
  5587. return RHSTy;
  5588. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5589. /*isIntFirstExpr=*/false))
  5590. return LHSTy;
  5591. // Emit a better diagnostic if one of the expressions is a null pointer
  5592. // constant and the other is not a pointer type. In this case, the user most
  5593. // likely forgot to take the address of the other expression.
  5594. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5595. return QualType();
  5596. // Otherwise, the operands are not compatible.
  5597. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5598. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5599. << RHS.get()->getSourceRange();
  5600. return QualType();
  5601. }
  5602. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5603. /// two objective-c pointer types of the two input expressions.
  5604. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5605. SourceLocation QuestionLoc) {
  5606. QualType LHSTy = LHS.get()->getType();
  5607. QualType RHSTy = RHS.get()->getType();
  5608. // Handle things like Class and struct objc_class*. Here we case the result
  5609. // to the pseudo-builtin, because that will be implicitly cast back to the
  5610. // redefinition type if an attempt is made to access its fields.
  5611. if (LHSTy->isObjCClassType() &&
  5612. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5613. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5614. return LHSTy;
  5615. }
  5616. if (RHSTy->isObjCClassType() &&
  5617. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5618. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5619. return RHSTy;
  5620. }
  5621. // And the same for struct objc_object* / id
  5622. if (LHSTy->isObjCIdType() &&
  5623. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5624. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5625. return LHSTy;
  5626. }
  5627. if (RHSTy->isObjCIdType() &&
  5628. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5629. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5630. return RHSTy;
  5631. }
  5632. // And the same for struct objc_selector* / SEL
  5633. if (Context.isObjCSelType(LHSTy) &&
  5634. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5635. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5636. return LHSTy;
  5637. }
  5638. if (Context.isObjCSelType(RHSTy) &&
  5639. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5640. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5641. return RHSTy;
  5642. }
  5643. // Check constraints for Objective-C object pointers types.
  5644. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5645. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5646. // Two identical object pointer types are always compatible.
  5647. return LHSTy;
  5648. }
  5649. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5650. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5651. QualType compositeType = LHSTy;
  5652. // If both operands are interfaces and either operand can be
  5653. // assigned to the other, use that type as the composite
  5654. // type. This allows
  5655. // xxx ? (A*) a : (B*) b
  5656. // where B is a subclass of A.
  5657. //
  5658. // Additionally, as for assignment, if either type is 'id'
  5659. // allow silent coercion. Finally, if the types are
  5660. // incompatible then make sure to use 'id' as the composite
  5661. // type so the result is acceptable for sending messages to.
  5662. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5663. // It could return the composite type.
  5664. if (!(compositeType =
  5665. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5666. // Nothing more to do.
  5667. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5668. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5669. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5670. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5671. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5672. RHSTy->isObjCQualifiedIdType()) &&
  5673. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5674. // Need to handle "id<xx>" explicitly.
  5675. // GCC allows qualified id and any Objective-C type to devolve to
  5676. // id. Currently localizing to here until clear this should be
  5677. // part of ObjCQualifiedIdTypesAreCompatible.
  5678. compositeType = Context.getObjCIdType();
  5679. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5680. compositeType = Context.getObjCIdType();
  5681. } else {
  5682. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5683. << LHSTy << RHSTy
  5684. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5685. QualType incompatTy = Context.getObjCIdType();
  5686. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5687. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5688. return incompatTy;
  5689. }
  5690. // The object pointer types are compatible.
  5691. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5692. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5693. return compositeType;
  5694. }
  5695. // Check Objective-C object pointer types and 'void *'
  5696. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5697. if (getLangOpts().ObjCAutoRefCount) {
  5698. // ARC forbids the implicit conversion of object pointers to 'void *',
  5699. // so these types are not compatible.
  5700. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5701. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5702. LHS = RHS = true;
  5703. return QualType();
  5704. }
  5705. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5706. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5707. QualType destPointee
  5708. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5709. QualType destType = Context.getPointerType(destPointee);
  5710. // Add qualifiers if necessary.
  5711. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5712. // Promote to void*.
  5713. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5714. return destType;
  5715. }
  5716. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5717. if (getLangOpts().ObjCAutoRefCount) {
  5718. // ARC forbids the implicit conversion of object pointers to 'void *',
  5719. // so these types are not compatible.
  5720. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5721. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5722. LHS = RHS = true;
  5723. return QualType();
  5724. }
  5725. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5726. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5727. QualType destPointee
  5728. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5729. QualType destType = Context.getPointerType(destPointee);
  5730. // Add qualifiers if necessary.
  5731. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5732. // Promote to void*.
  5733. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5734. return destType;
  5735. }
  5736. return QualType();
  5737. }
  5738. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5739. /// ParenRange in parentheses.
  5740. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5741. const PartialDiagnostic &Note,
  5742. SourceRange ParenRange) {
  5743. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5744. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5745. EndLoc.isValid()) {
  5746. Self.Diag(Loc, Note)
  5747. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5748. << FixItHint::CreateInsertion(EndLoc, ")");
  5749. } else {
  5750. // We can't display the parentheses, so just show the bare note.
  5751. Self.Diag(Loc, Note) << ParenRange;
  5752. }
  5753. }
  5754. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5755. return Opc >= BO_Mul && Opc <= BO_Shr;
  5756. }
  5757. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5758. /// expression, either using a built-in or overloaded operator,
  5759. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5760. /// expression.
  5761. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5762. Expr **RHSExprs) {
  5763. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5764. E = E->IgnoreImpCasts();
  5765. E = E->IgnoreConversionOperator();
  5766. E = E->IgnoreImpCasts();
  5767. // Built-in binary operator.
  5768. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5769. if (IsArithmeticOp(OP->getOpcode())) {
  5770. *Opcode = OP->getOpcode();
  5771. *RHSExprs = OP->getRHS();
  5772. return true;
  5773. }
  5774. }
  5775. // Overloaded operator.
  5776. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5777. if (Call->getNumArgs() != 2)
  5778. return false;
  5779. // Make sure this is really a binary operator that is safe to pass into
  5780. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5781. OverloadedOperatorKind OO = Call->getOperator();
  5782. if (OO < OO_Plus || OO > OO_Arrow ||
  5783. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5784. return false;
  5785. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5786. if (IsArithmeticOp(OpKind)) {
  5787. *Opcode = OpKind;
  5788. *RHSExprs = Call->getArg(1);
  5789. return true;
  5790. }
  5791. }
  5792. return false;
  5793. }
  5794. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5795. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5796. }
  5797. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5798. /// or is a logical expression such as (x==y) which has int type, but is
  5799. /// commonly interpreted as boolean.
  5800. static bool ExprLooksBoolean(Expr *E) {
  5801. E = E->IgnoreParenImpCasts();
  5802. if (E->getType()->isBooleanType())
  5803. return true;
  5804. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5805. return IsLogicOp(OP->getOpcode());
  5806. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5807. return OP->getOpcode() == UO_LNot;
  5808. if (E->getType()->isPointerType())
  5809. return true;
  5810. return false;
  5811. }
  5812. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5813. /// and binary operator are mixed in a way that suggests the programmer assumed
  5814. /// the conditional operator has higher precedence, for example:
  5815. /// "int x = a + someBinaryCondition ? 1 : 2".
  5816. static void DiagnoseConditionalPrecedence(Sema &Self,
  5817. SourceLocation OpLoc,
  5818. Expr *Condition,
  5819. Expr *LHSExpr,
  5820. Expr *RHSExpr) {
  5821. BinaryOperatorKind CondOpcode;
  5822. Expr *CondRHS;
  5823. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5824. return;
  5825. if (!ExprLooksBoolean(CondRHS))
  5826. return;
  5827. // The condition is an arithmetic binary expression, with a right-
  5828. // hand side that looks boolean, so warn.
  5829. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5830. << Condition->getSourceRange()
  5831. << BinaryOperator::getOpcodeStr(CondOpcode);
  5832. SuggestParentheses(Self, OpLoc,
  5833. Self.PDiag(diag::note_precedence_silence)
  5834. << BinaryOperator::getOpcodeStr(CondOpcode),
  5835. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5836. SuggestParentheses(Self, OpLoc,
  5837. Self.PDiag(diag::note_precedence_conditional_first),
  5838. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5839. }
  5840. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5841. /// in the case of a the GNU conditional expr extension.
  5842. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5843. SourceLocation ColonLoc,
  5844. Expr *CondExpr, Expr *LHSExpr,
  5845. Expr *RHSExpr) {
  5846. if (!getLangOpts().CPlusPlus) {
  5847. // C cannot handle TypoExpr nodes in the condition because it
  5848. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5849. // been dealt with before checking the operands.
  5850. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5851. if (!CondResult.isUsable()) return ExprError();
  5852. CondExpr = CondResult.get();
  5853. }
  5854. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5855. // was the condition.
  5856. OpaqueValueExpr *opaqueValue = nullptr;
  5857. Expr *commonExpr = nullptr;
  5858. if (!LHSExpr) {
  5859. commonExpr = CondExpr;
  5860. // Lower out placeholder types first. This is important so that we don't
  5861. // try to capture a placeholder. This happens in few cases in C++; such
  5862. // as Objective-C++'s dictionary subscripting syntax.
  5863. if (commonExpr->hasPlaceholderType()) {
  5864. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5865. if (!result.isUsable()) return ExprError();
  5866. commonExpr = result.get();
  5867. }
  5868. // We usually want to apply unary conversions *before* saving, except
  5869. // in the special case of a C++ l-value conditional.
  5870. if (!(getLangOpts().CPlusPlus
  5871. && !commonExpr->isTypeDependent()
  5872. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5873. && commonExpr->isGLValue()
  5874. && commonExpr->isOrdinaryOrBitFieldObject()
  5875. && RHSExpr->isOrdinaryOrBitFieldObject()
  5876. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5877. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5878. if (commonRes.isInvalid())
  5879. return ExprError();
  5880. commonExpr = commonRes.get();
  5881. }
  5882. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5883. commonExpr->getType(),
  5884. commonExpr->getValueKind(),
  5885. commonExpr->getObjectKind(),
  5886. commonExpr);
  5887. LHSExpr = CondExpr = opaqueValue;
  5888. }
  5889. ExprValueKind VK = VK_RValue;
  5890. ExprObjectKind OK = OK_Ordinary;
  5891. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5892. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5893. VK, OK, QuestionLoc);
  5894. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5895. RHS.isInvalid())
  5896. return ExprError();
  5897. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5898. RHS.get());
  5899. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5900. if (!commonExpr)
  5901. return new (Context)
  5902. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5903. RHS.get(), result, VK, OK);
  5904. return new (Context) BinaryConditionalOperator(
  5905. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5906. ColonLoc, result, VK, OK);
  5907. }
  5908. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5909. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5910. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5911. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5912. // FIXME: add a couple examples in this comment.
  5913. static Sema::AssignConvertType
  5914. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5915. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5916. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5917. // get the "pointed to" type (ignoring qualifiers at the top level)
  5918. const Type *lhptee, *rhptee;
  5919. Qualifiers lhq, rhq;
  5920. std::tie(lhptee, lhq) =
  5921. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5922. std::tie(rhptee, rhq) =
  5923. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5924. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5925. // C99 6.5.16.1p1: This following citation is common to constraints
  5926. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5927. // qualifiers of the type *pointed to* by the right;
  5928. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5929. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5930. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5931. // Ignore lifetime for further calculation.
  5932. lhq.removeObjCLifetime();
  5933. rhq.removeObjCLifetime();
  5934. }
  5935. if (!lhq.compatiblyIncludes(rhq)) {
  5936. // Treat address-space mismatches as fatal. TODO: address subspaces
  5937. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5938. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5939. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5940. // and from void*.
  5941. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5942. .compatiblyIncludes(
  5943. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5944. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5945. ; // keep old
  5946. // Treat lifetime mismatches as fatal.
  5947. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5948. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5949. // For GCC compatibility, other qualifier mismatches are treated
  5950. // as still compatible in C.
  5951. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5952. }
  5953. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5954. // incomplete type and the other is a pointer to a qualified or unqualified
  5955. // version of void...
  5956. if (lhptee->isVoidType()) {
  5957. if (rhptee->isIncompleteOrObjectType())
  5958. return ConvTy;
  5959. // As an extension, we allow cast to/from void* to function pointer.
  5960. assert(rhptee->isFunctionType());
  5961. return Sema::FunctionVoidPointer;
  5962. }
  5963. if (rhptee->isVoidType()) {
  5964. if (lhptee->isIncompleteOrObjectType())
  5965. return ConvTy;
  5966. // As an extension, we allow cast to/from void* to function pointer.
  5967. assert(lhptee->isFunctionType());
  5968. return Sema::FunctionVoidPointer;
  5969. }
  5970. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5971. // unqualified versions of compatible types, ...
  5972. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5973. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5974. // Check if the pointee types are compatible ignoring the sign.
  5975. // We explicitly check for char so that we catch "char" vs
  5976. // "unsigned char" on systems where "char" is unsigned.
  5977. if (lhptee->isCharType())
  5978. ltrans = S.Context.UnsignedCharTy;
  5979. else if (lhptee->hasSignedIntegerRepresentation())
  5980. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5981. if (rhptee->isCharType())
  5982. rtrans = S.Context.UnsignedCharTy;
  5983. else if (rhptee->hasSignedIntegerRepresentation())
  5984. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5985. if (ltrans == rtrans) {
  5986. // Types are compatible ignoring the sign. Qualifier incompatibility
  5987. // takes priority over sign incompatibility because the sign
  5988. // warning can be disabled.
  5989. if (ConvTy != Sema::Compatible)
  5990. return ConvTy;
  5991. return Sema::IncompatiblePointerSign;
  5992. }
  5993. // If we are a multi-level pointer, it's possible that our issue is simply
  5994. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5995. // the eventual target type is the same and the pointers have the same
  5996. // level of indirection, this must be the issue.
  5997. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5998. do {
  5999. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  6000. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  6001. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6002. if (lhptee == rhptee)
  6003. return Sema::IncompatibleNestedPointerQualifiers;
  6004. }
  6005. // General pointer incompatibility takes priority over qualifiers.
  6006. return Sema::IncompatiblePointer;
  6007. }
  6008. if (!S.getLangOpts().CPlusPlus &&
  6009. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  6010. return Sema::IncompatiblePointer;
  6011. return ConvTy;
  6012. }
  6013. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6014. /// block pointer types are compatible or whether a block and normal pointer
  6015. /// are compatible. It is more restrict than comparing two function pointer
  6016. // types.
  6017. static Sema::AssignConvertType
  6018. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6019. QualType RHSType) {
  6020. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6021. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6022. QualType lhptee, rhptee;
  6023. // get the "pointed to" type (ignoring qualifiers at the top level)
  6024. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6025. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6026. // In C++, the types have to match exactly.
  6027. if (S.getLangOpts().CPlusPlus)
  6028. return Sema::IncompatibleBlockPointer;
  6029. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6030. // For blocks we enforce that qualifiers are identical.
  6031. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  6032. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6033. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6034. return Sema::IncompatibleBlockPointer;
  6035. return ConvTy;
  6036. }
  6037. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6038. /// for assignment compatibility.
  6039. static Sema::AssignConvertType
  6040. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6041. QualType RHSType) {
  6042. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6043. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6044. if (LHSType->isObjCBuiltinType()) {
  6045. // Class is not compatible with ObjC object pointers.
  6046. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6047. !RHSType->isObjCQualifiedClassType())
  6048. return Sema::IncompatiblePointer;
  6049. return Sema::Compatible;
  6050. }
  6051. if (RHSType->isObjCBuiltinType()) {
  6052. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6053. !LHSType->isObjCQualifiedClassType())
  6054. return Sema::IncompatiblePointer;
  6055. return Sema::Compatible;
  6056. }
  6057. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6058. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6059. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6060. // make an exception for id<P>
  6061. !LHSType->isObjCQualifiedIdType())
  6062. return Sema::CompatiblePointerDiscardsQualifiers;
  6063. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6064. return Sema::Compatible;
  6065. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6066. return Sema::IncompatibleObjCQualifiedId;
  6067. return Sema::IncompatiblePointer;
  6068. }
  6069. Sema::AssignConvertType
  6070. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6071. QualType LHSType, QualType RHSType) {
  6072. // Fake up an opaque expression. We don't actually care about what
  6073. // cast operations are required, so if CheckAssignmentConstraints
  6074. // adds casts to this they'll be wasted, but fortunately that doesn't
  6075. // usually happen on valid code.
  6076. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6077. ExprResult RHSPtr = &RHSExpr;
  6078. CastKind K = CK_Invalid;
  6079. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  6080. }
  6081. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6082. /// has code to accommodate several GCC extensions when type checking
  6083. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6084. ///
  6085. /// int a, *pint;
  6086. /// short *pshort;
  6087. /// struct foo *pfoo;
  6088. ///
  6089. /// pint = pshort; // warning: assignment from incompatible pointer type
  6090. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6091. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6092. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6093. ///
  6094. /// As a result, the code for dealing with pointers is more complex than the
  6095. /// C99 spec dictates.
  6096. ///
  6097. /// Sets 'Kind' for any result kind except Incompatible.
  6098. Sema::AssignConvertType
  6099. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6100. CastKind &Kind) {
  6101. QualType RHSType = RHS.get()->getType();
  6102. QualType OrigLHSType = LHSType;
  6103. // Get canonical types. We're not formatting these types, just comparing
  6104. // them.
  6105. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6106. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6107. // Common case: no conversion required.
  6108. if (LHSType == RHSType) {
  6109. Kind = CK_NoOp;
  6110. return Compatible;
  6111. }
  6112. // If we have an atomic type, try a non-atomic assignment, then just add an
  6113. // atomic qualification step.
  6114. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6115. Sema::AssignConvertType result =
  6116. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6117. if (result != Compatible)
  6118. return result;
  6119. if (Kind != CK_NoOp)
  6120. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6121. Kind = CK_NonAtomicToAtomic;
  6122. return Compatible;
  6123. }
  6124. // If the left-hand side is a reference type, then we are in a
  6125. // (rare!) case where we've allowed the use of references in C,
  6126. // e.g., as a parameter type in a built-in function. In this case,
  6127. // just make sure that the type referenced is compatible with the
  6128. // right-hand side type. The caller is responsible for adjusting
  6129. // LHSType so that the resulting expression does not have reference
  6130. // type.
  6131. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6132. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6133. Kind = CK_LValueBitCast;
  6134. return Compatible;
  6135. }
  6136. return Incompatible;
  6137. }
  6138. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6139. // to the same ExtVector type.
  6140. if (LHSType->isExtVectorType()) {
  6141. if (RHSType->isExtVectorType())
  6142. return Incompatible;
  6143. if (RHSType->isArithmeticType()) {
  6144. // CK_VectorSplat does T -> vector T, so first cast to the
  6145. // element type.
  6146. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  6147. if (elType != RHSType) {
  6148. Kind = PrepareScalarCast(RHS, elType);
  6149. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  6150. }
  6151. Kind = CK_VectorSplat;
  6152. return Compatible;
  6153. }
  6154. }
  6155. // Conversions to or from vector type.
  6156. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6157. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6158. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6159. // vector type and vice versa
  6160. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6161. Kind = CK_BitCast;
  6162. return Compatible;
  6163. }
  6164. // If we are allowing lax vector conversions, and LHS and RHS are both
  6165. // vectors, the total size only needs to be the same. This is a bitcast;
  6166. // no bits are changed but the result type is different.
  6167. if (isLaxVectorConversion(RHSType, LHSType)) {
  6168. Kind = CK_BitCast;
  6169. return IncompatibleVectors;
  6170. }
  6171. }
  6172. return Incompatible;
  6173. }
  6174. // Arithmetic conversions.
  6175. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6176. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6177. Kind = PrepareScalarCast(RHS, LHSType);
  6178. return Compatible;
  6179. }
  6180. // Conversions to normal pointers.
  6181. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6182. // U* -> T*
  6183. if (isa<PointerType>(RHSType)) {
  6184. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6185. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6186. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6187. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6188. }
  6189. // int -> T*
  6190. if (RHSType->isIntegerType()) {
  6191. Kind = CK_IntegralToPointer; // FIXME: null?
  6192. return IntToPointer;
  6193. }
  6194. // C pointers are not compatible with ObjC object pointers,
  6195. // with two exceptions:
  6196. if (isa<ObjCObjectPointerType>(RHSType)) {
  6197. // - conversions to void*
  6198. if (LHSPointer->getPointeeType()->isVoidType()) {
  6199. Kind = CK_BitCast;
  6200. return Compatible;
  6201. }
  6202. // - conversions from 'Class' to the redefinition type
  6203. if (RHSType->isObjCClassType() &&
  6204. Context.hasSameType(LHSType,
  6205. Context.getObjCClassRedefinitionType())) {
  6206. Kind = CK_BitCast;
  6207. return Compatible;
  6208. }
  6209. Kind = CK_BitCast;
  6210. return IncompatiblePointer;
  6211. }
  6212. // U^ -> void*
  6213. if (RHSType->getAs<BlockPointerType>()) {
  6214. if (LHSPointer->getPointeeType()->isVoidType()) {
  6215. Kind = CK_BitCast;
  6216. return Compatible;
  6217. }
  6218. }
  6219. return Incompatible;
  6220. }
  6221. // Conversions to block pointers.
  6222. if (isa<BlockPointerType>(LHSType)) {
  6223. // U^ -> T^
  6224. if (RHSType->isBlockPointerType()) {
  6225. Kind = CK_BitCast;
  6226. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6227. }
  6228. // int or null -> T^
  6229. if (RHSType->isIntegerType()) {
  6230. Kind = CK_IntegralToPointer; // FIXME: null
  6231. return IntToBlockPointer;
  6232. }
  6233. // id -> T^
  6234. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6235. Kind = CK_AnyPointerToBlockPointerCast;
  6236. return Compatible;
  6237. }
  6238. // void* -> T^
  6239. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6240. if (RHSPT->getPointeeType()->isVoidType()) {
  6241. Kind = CK_AnyPointerToBlockPointerCast;
  6242. return Compatible;
  6243. }
  6244. return Incompatible;
  6245. }
  6246. // Conversions to Objective-C pointers.
  6247. if (isa<ObjCObjectPointerType>(LHSType)) {
  6248. // A* -> B*
  6249. if (RHSType->isObjCObjectPointerType()) {
  6250. Kind = CK_BitCast;
  6251. Sema::AssignConvertType result =
  6252. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6253. if (getLangOpts().ObjCAutoRefCount &&
  6254. result == Compatible &&
  6255. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6256. result = IncompatibleObjCWeakRef;
  6257. return result;
  6258. }
  6259. // int or null -> A*
  6260. if (RHSType->isIntegerType()) {
  6261. Kind = CK_IntegralToPointer; // FIXME: null
  6262. return IntToPointer;
  6263. }
  6264. // In general, C pointers are not compatible with ObjC object pointers,
  6265. // with two exceptions:
  6266. if (isa<PointerType>(RHSType)) {
  6267. Kind = CK_CPointerToObjCPointerCast;
  6268. // - conversions from 'void*'
  6269. if (RHSType->isVoidPointerType()) {
  6270. return Compatible;
  6271. }
  6272. // - conversions to 'Class' from its redefinition type
  6273. if (LHSType->isObjCClassType() &&
  6274. Context.hasSameType(RHSType,
  6275. Context.getObjCClassRedefinitionType())) {
  6276. return Compatible;
  6277. }
  6278. return IncompatiblePointer;
  6279. }
  6280. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6281. if (RHSType->isBlockPointerType() &&
  6282. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6283. maybeExtendBlockObject(RHS);
  6284. Kind = CK_BlockPointerToObjCPointerCast;
  6285. return Compatible;
  6286. }
  6287. return Incompatible;
  6288. }
  6289. // Conversions from pointers that are not covered by the above.
  6290. if (isa<PointerType>(RHSType)) {
  6291. // T* -> _Bool
  6292. if (LHSType == Context.BoolTy) {
  6293. Kind = CK_PointerToBoolean;
  6294. return Compatible;
  6295. }
  6296. // T* -> int
  6297. if (LHSType->isIntegerType()) {
  6298. Kind = CK_PointerToIntegral;
  6299. return PointerToInt;
  6300. }
  6301. return Incompatible;
  6302. }
  6303. // Conversions from Objective-C pointers that are not covered by the above.
  6304. if (isa<ObjCObjectPointerType>(RHSType)) {
  6305. // T* -> _Bool
  6306. if (LHSType == Context.BoolTy) {
  6307. Kind = CK_PointerToBoolean;
  6308. return Compatible;
  6309. }
  6310. // T* -> int
  6311. if (LHSType->isIntegerType()) {
  6312. Kind = CK_PointerToIntegral;
  6313. return PointerToInt;
  6314. }
  6315. return Incompatible;
  6316. }
  6317. // struct A -> struct B
  6318. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6319. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6320. Kind = CK_NoOp;
  6321. return Compatible;
  6322. }
  6323. }
  6324. return Incompatible;
  6325. }
  6326. /// \brief Constructs a transparent union from an expression that is
  6327. /// used to initialize the transparent union.
  6328. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6329. ExprResult &EResult, QualType UnionType,
  6330. FieldDecl *Field) {
  6331. // Build an initializer list that designates the appropriate member
  6332. // of the transparent union.
  6333. Expr *E = EResult.get();
  6334. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6335. E, SourceLocation());
  6336. Initializer->setType(UnionType);
  6337. Initializer->setInitializedFieldInUnion(Field);
  6338. // Build a compound literal constructing a value of the transparent
  6339. // union type from this initializer list.
  6340. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6341. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6342. VK_RValue, Initializer, false);
  6343. }
  6344. Sema::AssignConvertType
  6345. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6346. ExprResult &RHS) {
  6347. QualType RHSType = RHS.get()->getType();
  6348. // If the ArgType is a Union type, we want to handle a potential
  6349. // transparent_union GCC extension.
  6350. const RecordType *UT = ArgType->getAsUnionType();
  6351. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6352. return Incompatible;
  6353. // The field to initialize within the transparent union.
  6354. RecordDecl *UD = UT->getDecl();
  6355. FieldDecl *InitField = nullptr;
  6356. // It's compatible if the expression matches any of the fields.
  6357. for (auto *it : UD->fields()) {
  6358. if (it->getType()->isPointerType()) {
  6359. // If the transparent union contains a pointer type, we allow:
  6360. // 1) void pointer
  6361. // 2) null pointer constant
  6362. if (RHSType->isPointerType())
  6363. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6364. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6365. InitField = it;
  6366. break;
  6367. }
  6368. if (RHS.get()->isNullPointerConstant(Context,
  6369. Expr::NPC_ValueDependentIsNull)) {
  6370. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6371. CK_NullToPointer);
  6372. InitField = it;
  6373. break;
  6374. }
  6375. }
  6376. CastKind Kind = CK_Invalid;
  6377. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6378. == Compatible) {
  6379. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6380. InitField = it;
  6381. break;
  6382. }
  6383. }
  6384. if (!InitField)
  6385. return Incompatible;
  6386. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6387. return Compatible;
  6388. }
  6389. Sema::AssignConvertType
  6390. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6391. bool Diagnose,
  6392. bool DiagnoseCFAudited) {
  6393. // HLSL Change Starts
  6394. if (getLangOpts().HLSL) {
  6395. // implicit conversion will take care of diagnostics.
  6396. return Compatible;
  6397. }
  6398. // HLSL Change Ends
  6399. if (getLangOpts().CPlusPlus) {
  6400. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6401. // C++ 5.17p3: If the left operand is not of class type, the
  6402. // expression is implicitly converted (C++ 4) to the
  6403. // cv-unqualified type of the left operand.
  6404. ExprResult Res;
  6405. if (Diagnose) {
  6406. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6407. AA_Assigning);
  6408. } else {
  6409. ImplicitConversionSequence ICS =
  6410. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6411. /*SuppressUserConversions=*/false,
  6412. /*AllowExplicit=*/false,
  6413. /*InOverloadResolution=*/false,
  6414. /*CStyle=*/false,
  6415. /*AllowObjCWritebackConversion=*/false);
  6416. if (ICS.isFailure())
  6417. return Incompatible;
  6418. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6419. ICS, AA_Assigning);
  6420. }
  6421. if (Res.isInvalid())
  6422. return Incompatible;
  6423. Sema::AssignConvertType result = Compatible;
  6424. if (getLangOpts().ObjCAutoRefCount &&
  6425. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6426. RHS.get()->getType()))
  6427. result = IncompatibleObjCWeakRef;
  6428. RHS = Res;
  6429. return result;
  6430. }
  6431. // FIXME: Currently, we fall through and treat C++ classes like C
  6432. // structures.
  6433. // FIXME: We also fall through for atomics; not sure what should
  6434. // happen there, though.
  6435. }
  6436. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6437. // a null pointer constant.
  6438. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6439. LHSType->isBlockPointerType()) &&
  6440. RHS.get()->isNullPointerConstant(Context,
  6441. Expr::NPC_ValueDependentIsNull)) {
  6442. CastKind Kind;
  6443. CXXCastPath Path;
  6444. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6445. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6446. return Compatible;
  6447. }
  6448. // This check seems unnatural, however it is necessary to ensure the proper
  6449. // conversion of functions/arrays. If the conversion were done for all
  6450. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6451. // expressions that suppress this implicit conversion (&, sizeof).
  6452. //
  6453. // Suppress this for references: C++ 8.5.3p5.
  6454. if (!LHSType->isReferenceType()) {
  6455. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6456. if (RHS.isInvalid())
  6457. return Incompatible;
  6458. }
  6459. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6460. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6461. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6462. if (PDecl && !PDecl->hasDefinition()) {
  6463. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6464. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6465. }
  6466. }
  6467. CastKind Kind = CK_Invalid;
  6468. Sema::AssignConvertType result =
  6469. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6470. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6471. // type of the assignment expression.
  6472. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6473. // so that we can use references in built-in functions even in C.
  6474. // The getNonReferenceType() call makes sure that the resulting expression
  6475. // does not have reference type.
  6476. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6477. QualType Ty = LHSType.getNonLValueExprType(Context);
  6478. Expr *E = RHS.get();
  6479. if (getLangOpts().ObjCAutoRefCount)
  6480. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6481. DiagnoseCFAudited);
  6482. if (getLangOpts().ObjC1 &&
  6483. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6484. LHSType, E->getType(), E) ||
  6485. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6486. RHS = E;
  6487. return Compatible;
  6488. }
  6489. RHS = ImpCastExprToType(E, Ty, Kind);
  6490. }
  6491. return result;
  6492. }
  6493. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6494. ExprResult &RHS) {
  6495. Diag(Loc, diag::err_typecheck_invalid_operands)
  6496. << LHS.get()->getType() << RHS.get()->getType()
  6497. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6498. return QualType();
  6499. }
  6500. /// Try to convert a value of non-vector type to a vector type by converting
  6501. /// the type to the element type of the vector and then performing a splat.
  6502. /// If the language is OpenCL, we only use conversions that promote scalar
  6503. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6504. /// for float->int.
  6505. ///
  6506. /// \param scalar - if non-null, actually perform the conversions
  6507. /// \return true if the operation fails (but without diagnosing the failure)
  6508. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6509. QualType scalarTy,
  6510. QualType vectorEltTy,
  6511. QualType vectorTy) {
  6512. // The conversion to apply to the scalar before splatting it,
  6513. // if necessary.
  6514. CastKind scalarCast = CK_Invalid;
  6515. if (vectorEltTy->isIntegralType(S.Context)) {
  6516. if (!scalarTy->isIntegralType(S.Context))
  6517. return true;
  6518. if (S.getLangOpts().OpenCL &&
  6519. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6520. return true;
  6521. scalarCast = CK_IntegralCast;
  6522. } else if (vectorEltTy->isRealFloatingType()) {
  6523. if (scalarTy->isRealFloatingType()) {
  6524. if (S.getLangOpts().OpenCL &&
  6525. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6526. return true;
  6527. scalarCast = CK_FloatingCast;
  6528. }
  6529. else if (scalarTy->isIntegralType(S.Context))
  6530. scalarCast = CK_IntegralToFloating;
  6531. else
  6532. return true;
  6533. } else {
  6534. return true;
  6535. }
  6536. // Adjust scalar if desired.
  6537. if (scalar) {
  6538. if (scalarCast != CK_Invalid)
  6539. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6540. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6541. }
  6542. return false;
  6543. }
  6544. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6545. SourceLocation Loc, bool IsCompAssign,
  6546. bool AllowBothBool,
  6547. bool AllowBoolConversions) {
  6548. if (!IsCompAssign) {
  6549. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6550. if (LHS.isInvalid())
  6551. return QualType();
  6552. }
  6553. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6554. if (RHS.isInvalid())
  6555. return QualType();
  6556. // For conversion purposes, we ignore any qualifiers.
  6557. // For example, "const float" and "float" are equivalent.
  6558. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6559. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6560. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6561. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6562. assert(LHSVecType || RHSVecType);
  6563. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6564. // for some operators but not others.
  6565. if (!AllowBothBool &&
  6566. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6567. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6568. return InvalidOperands(Loc, LHS, RHS);
  6569. // If the vector types are identical, return.
  6570. if (Context.hasSameType(LHSType, RHSType))
  6571. return LHSType;
  6572. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6573. if (LHSVecType && RHSVecType &&
  6574. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6575. if (isa<ExtVectorType>(LHSVecType)) {
  6576. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6577. return LHSType;
  6578. }
  6579. if (!IsCompAssign)
  6580. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6581. return RHSType;
  6582. }
  6583. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6584. // can be mixed, with the result being the non-bool type. The non-bool
  6585. // operand must have integer element type.
  6586. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6587. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6588. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6589. Context.getTypeSize(RHSVecType->getElementType()))) {
  6590. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6591. LHSVecType->getElementType()->isIntegerType() &&
  6592. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6593. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6594. return LHSType;
  6595. }
  6596. if (!IsCompAssign &&
  6597. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6598. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6599. RHSVecType->getElementType()->isIntegerType()) {
  6600. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6601. return RHSType;
  6602. }
  6603. }
  6604. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6605. // the vector element type and splat.
  6606. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6607. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6608. LHSVecType->getElementType(), LHSType))
  6609. return LHSType;
  6610. }
  6611. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6612. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6613. LHSType, RHSVecType->getElementType(),
  6614. RHSType))
  6615. return RHSType;
  6616. }
  6617. // If we're allowing lax vector conversions, only the total (data) size
  6618. // needs to be the same.
  6619. // FIXME: Should we really be allowing this?
  6620. // FIXME: We really just pick the LHS type arbitrarily?
  6621. if (isLaxVectorConversion(RHSType, LHSType)) {
  6622. QualType resultType = LHSType;
  6623. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6624. return resultType;
  6625. }
  6626. // Okay, the expression is invalid.
  6627. // If there's a non-vector, non-real operand, diagnose that.
  6628. if ((!RHSVecType && !RHSType->isRealType()) ||
  6629. (!LHSVecType && !LHSType->isRealType())) {
  6630. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6631. << LHSType << RHSType
  6632. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6633. return QualType();
  6634. }
  6635. // Otherwise, use the generic diagnostic.
  6636. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6637. << LHSType << RHSType
  6638. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6639. return QualType();
  6640. }
  6641. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6642. // expression. These are mainly cases where the null pointer is used as an
  6643. // integer instead of a pointer.
  6644. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6645. SourceLocation Loc, bool IsCompare) {
  6646. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6647. // but we use a bit of a hack here for speed; this is a relatively
  6648. // hot path, and isNullPointerConstant is slow.
  6649. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6650. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6651. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6652. // Avoid analyzing cases where the result will either be invalid (and
  6653. // diagnosed as such) or entirely valid and not something to warn about.
  6654. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6655. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6656. return;
  6657. // Comparison operations would not make sense with a null pointer no matter
  6658. // what the other expression is.
  6659. if (!IsCompare) {
  6660. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6661. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6662. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6663. return;
  6664. }
  6665. // The rest of the operations only make sense with a null pointer
  6666. // if the other expression is a pointer.
  6667. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6668. NonNullType->canDecayToPointerType())
  6669. return;
  6670. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6671. << LHSNull /* LHS is NULL */ << NonNullType
  6672. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6673. }
  6674. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6675. SourceLocation Loc,
  6676. bool IsCompAssign, bool IsDiv) {
  6677. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6678. if (LHS.get()->getType()->isVectorType() ||
  6679. RHS.get()->getType()->isVectorType())
  6680. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6681. /*AllowBothBool*/getLangOpts().AltiVec,
  6682. /*AllowBoolConversions*/false);
  6683. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6684. if (LHS.isInvalid() || RHS.isInvalid())
  6685. return QualType();
  6686. if (compType.isNull() || !compType->isArithmeticType())
  6687. return InvalidOperands(Loc, LHS, RHS);
  6688. // Check for division by zero.
  6689. llvm::APSInt RHSValue;
  6690. if (IsDiv && !RHS.get()->isValueDependent() &&
  6691. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6692. DiagRuntimeBehavior(Loc, RHS.get(),
  6693. PDiag(diag::warn_division_by_zero)
  6694. << RHS.get()->getSourceRange());
  6695. return compType;
  6696. }
  6697. QualType Sema::CheckRemainderOperands(
  6698. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6699. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6700. if (LHS.get()->getType()->isVectorType() ||
  6701. RHS.get()->getType()->isVectorType()) {
  6702. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6703. RHS.get()->getType()->hasIntegerRepresentation())
  6704. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6705. /*AllowBothBool*/getLangOpts().AltiVec,
  6706. /*AllowBoolConversions*/false);
  6707. return InvalidOperands(Loc, LHS, RHS);
  6708. }
  6709. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6710. if (LHS.isInvalid() || RHS.isInvalid())
  6711. return QualType();
  6712. if (compType.isNull() || !compType->isIntegerType())
  6713. return InvalidOperands(Loc, LHS, RHS);
  6714. // Check for remainder by zero.
  6715. llvm::APSInt RHSValue;
  6716. if (!RHS.get()->isValueDependent() &&
  6717. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6718. DiagRuntimeBehavior(Loc, RHS.get(),
  6719. PDiag(diag::warn_remainder_by_zero)
  6720. << RHS.get()->getSourceRange());
  6721. return compType;
  6722. }
  6723. /// \brief Diagnose invalid arithmetic on two void pointers.
  6724. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6725. Expr *LHSExpr, Expr *RHSExpr) {
  6726. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6727. ? diag::err_typecheck_pointer_arith_void_type
  6728. : diag::ext_gnu_void_ptr)
  6729. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6730. << RHSExpr->getSourceRange();
  6731. }
  6732. /// \brief Diagnose invalid arithmetic on a void pointer.
  6733. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6734. Expr *Pointer) {
  6735. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6736. ? diag::err_typecheck_pointer_arith_void_type
  6737. : diag::ext_gnu_void_ptr)
  6738. << 0 /* one pointer */ << Pointer->getSourceRange();
  6739. }
  6740. /// \brief Diagnose invalid arithmetic on two function pointers.
  6741. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6742. Expr *LHS, Expr *RHS) {
  6743. assert(LHS->getType()->isAnyPointerType());
  6744. assert(RHS->getType()->isAnyPointerType());
  6745. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6746. ? diag::err_typecheck_pointer_arith_function_type
  6747. : diag::ext_gnu_ptr_func_arith)
  6748. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6749. // We only show the second type if it differs from the first.
  6750. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6751. RHS->getType())
  6752. << RHS->getType()->getPointeeType()
  6753. << LHS->getSourceRange() << RHS->getSourceRange();
  6754. }
  6755. /// \brief Diagnose invalid arithmetic on a function pointer.
  6756. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6757. Expr *Pointer) {
  6758. assert(Pointer->getType()->isAnyPointerType());
  6759. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6760. ? diag::err_typecheck_pointer_arith_function_type
  6761. : diag::ext_gnu_ptr_func_arith)
  6762. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6763. << 0 /* one pointer, so only one type */
  6764. << Pointer->getSourceRange();
  6765. }
  6766. /// \brief Emit error if Operand is incomplete pointer type
  6767. ///
  6768. /// \returns True if pointer has incomplete type
  6769. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6770. Expr *Operand) {
  6771. QualType ResType = Operand->getType();
  6772. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6773. ResType = ResAtomicType->getValueType();
  6774. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6775. QualType PointeeTy = ResType->getPointeeType();
  6776. return S.RequireCompleteType(Loc, PointeeTy,
  6777. diag::err_typecheck_arithmetic_incomplete_type,
  6778. PointeeTy, Operand->getSourceRange());
  6779. }
  6780. /// \brief Check the validity of an arithmetic pointer operand.
  6781. ///
  6782. /// If the operand has pointer type, this code will check for pointer types
  6783. /// which are invalid in arithmetic operations. These will be diagnosed
  6784. /// appropriately, including whether or not the use is supported as an
  6785. /// extension.
  6786. ///
  6787. /// \returns True when the operand is valid to use (even if as an extension).
  6788. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6789. Expr *Operand) {
  6790. QualType ResType = Operand->getType();
  6791. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6792. ResType = ResAtomicType->getValueType();
  6793. if (!ResType->isAnyPointerType()) return true;
  6794. QualType PointeeTy = ResType->getPointeeType();
  6795. if (PointeeTy->isVoidType()) {
  6796. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6797. return !S.getLangOpts().CPlusPlus;
  6798. }
  6799. if (PointeeTy->isFunctionType()) {
  6800. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6801. return !S.getLangOpts().CPlusPlus;
  6802. }
  6803. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6804. return true;
  6805. }
  6806. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6807. /// operands.
  6808. ///
  6809. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6810. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6811. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6812. /// are (potentially problematic) pointers.
  6813. ///
  6814. /// \returns True when the operand is valid to use (even if as an extension).
  6815. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6816. Expr *LHSExpr, Expr *RHSExpr) {
  6817. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6818. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6819. if (!isLHSPointer && !isRHSPointer) return true;
  6820. QualType LHSPointeeTy, RHSPointeeTy;
  6821. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6822. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6823. // if both are pointers check if operation is valid wrt address spaces
  6824. if (isLHSPointer && isRHSPointer) {
  6825. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6826. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6827. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6828. S.Diag(Loc,
  6829. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6830. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6831. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6832. return false;
  6833. }
  6834. }
  6835. // Check for arithmetic on pointers to incomplete types.
  6836. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6837. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6838. if (isLHSVoidPtr || isRHSVoidPtr) {
  6839. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6840. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6841. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6842. return !S.getLangOpts().CPlusPlus;
  6843. }
  6844. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6845. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6846. if (isLHSFuncPtr || isRHSFuncPtr) {
  6847. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6848. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6849. RHSExpr);
  6850. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6851. return !S.getLangOpts().CPlusPlus;
  6852. }
  6853. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6854. return false;
  6855. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6856. return false;
  6857. return true;
  6858. }
  6859. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6860. /// literal.
  6861. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6862. Expr *LHSExpr, Expr *RHSExpr) {
  6863. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6864. Expr* IndexExpr = RHSExpr;
  6865. if (!StrExpr) {
  6866. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6867. IndexExpr = LHSExpr;
  6868. }
  6869. bool IsStringPlusInt = StrExpr &&
  6870. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6871. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6872. return;
  6873. llvm::APSInt index;
  6874. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6875. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6876. if (index.isNonNegative() &&
  6877. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6878. index.isUnsigned()))
  6879. return;
  6880. }
  6881. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6882. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6883. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6884. // Only print a fixit for "str" + int, not for int + "str".
  6885. if (IndexExpr == RHSExpr) {
  6886. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6887. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6888. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6889. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6890. << FixItHint::CreateInsertion(EndLoc, "]");
  6891. } else
  6892. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6893. }
  6894. /// \brief Emit a warning when adding a char literal to a string.
  6895. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6896. Expr *LHSExpr, Expr *RHSExpr) {
  6897. const Expr *StringRefExpr = LHSExpr;
  6898. const CharacterLiteral *CharExpr =
  6899. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6900. if (!CharExpr) {
  6901. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6902. StringRefExpr = RHSExpr;
  6903. }
  6904. if (!CharExpr || !StringRefExpr)
  6905. return;
  6906. const QualType StringType = StringRefExpr->getType();
  6907. // Return if not a PointerType.
  6908. if (!StringType->isAnyPointerType())
  6909. return;
  6910. // Return if not a CharacterType.
  6911. if (!StringType->getPointeeType()->isAnyCharacterType())
  6912. return;
  6913. ASTContext &Ctx = Self.getASTContext();
  6914. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6915. const QualType CharType = CharExpr->getType();
  6916. if (!CharType->isAnyCharacterType() &&
  6917. CharType->isIntegerType() &&
  6918. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6919. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6920. << DiagRange << Ctx.CharTy;
  6921. } else {
  6922. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6923. << DiagRange << CharExpr->getType();
  6924. }
  6925. // Only print a fixit for str + char, not for char + str.
  6926. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6927. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6928. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6929. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6930. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6931. << FixItHint::CreateInsertion(EndLoc, "]");
  6932. } else {
  6933. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6934. }
  6935. }
  6936. /// \brief Emit error when two pointers are incompatible.
  6937. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6938. Expr *LHSExpr, Expr *RHSExpr) {
  6939. assert(LHSExpr->getType()->isAnyPointerType());
  6940. assert(RHSExpr->getType()->isAnyPointerType());
  6941. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6942. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6943. << RHSExpr->getSourceRange();
  6944. }
  6945. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6946. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6947. QualType* CompLHSTy) {
  6948. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6949. if (LHS.get()->getType()->isVectorType() ||
  6950. RHS.get()->getType()->isVectorType()) {
  6951. QualType compType = CheckVectorOperands(
  6952. LHS, RHS, Loc, CompLHSTy,
  6953. /*AllowBothBool*/getLangOpts().AltiVec,
  6954. /*AllowBoolConversions*/getLangOpts().ZVector);
  6955. if (CompLHSTy) *CompLHSTy = compType;
  6956. return compType;
  6957. }
  6958. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6959. if (LHS.isInvalid() || RHS.isInvalid())
  6960. return QualType();
  6961. // Diagnose "string literal" '+' int and string '+' "char literal".
  6962. if (Opc == BO_Add) {
  6963. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6964. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6965. }
  6966. // handle the common case first (both operands are arithmetic).
  6967. if (!compType.isNull() && compType->isArithmeticType()) {
  6968. if (CompLHSTy) *CompLHSTy = compType;
  6969. return compType;
  6970. }
  6971. // Type-checking. Ultimately the pointer's going to be in PExp;
  6972. // note that we bias towards the LHS being the pointer.
  6973. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6974. bool isObjCPointer;
  6975. if (PExp->getType()->isPointerType()) {
  6976. isObjCPointer = false;
  6977. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6978. isObjCPointer = true;
  6979. } else {
  6980. std::swap(PExp, IExp);
  6981. if (PExp->getType()->isPointerType()) {
  6982. isObjCPointer = false;
  6983. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6984. isObjCPointer = true;
  6985. } else {
  6986. return InvalidOperands(Loc, LHS, RHS);
  6987. }
  6988. }
  6989. assert(PExp->getType()->isAnyPointerType());
  6990. if (!IExp->getType()->isIntegerType())
  6991. return InvalidOperands(Loc, LHS, RHS);
  6992. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6993. return QualType();
  6994. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6995. return QualType();
  6996. // Check array bounds for pointer arithemtic
  6997. CheckArrayAccess(PExp, IExp);
  6998. if (CompLHSTy) {
  6999. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  7000. if (LHSTy.isNull()) {
  7001. LHSTy = LHS.get()->getType();
  7002. if (LHSTy->isPromotableIntegerType())
  7003. LHSTy = Context.getPromotedIntegerType(LHSTy);
  7004. }
  7005. *CompLHSTy = LHSTy;
  7006. }
  7007. return PExp->getType();
  7008. }
  7009. // C99 6.5.6
  7010. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  7011. SourceLocation Loc,
  7012. QualType* CompLHSTy) {
  7013. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7014. if (LHS.get()->getType()->isVectorType() ||
  7015. RHS.get()->getType()->isVectorType()) {
  7016. QualType compType = CheckVectorOperands(
  7017. LHS, RHS, Loc, CompLHSTy,
  7018. /*AllowBothBool*/getLangOpts().AltiVec,
  7019. /*AllowBoolConversions*/getLangOpts().ZVector);
  7020. if (CompLHSTy) *CompLHSTy = compType;
  7021. return compType;
  7022. }
  7023. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7024. if (LHS.isInvalid() || RHS.isInvalid())
  7025. return QualType();
  7026. // Enforce type constraints: C99 6.5.6p3.
  7027. // Handle the common case first (both operands are arithmetic).
  7028. if (!compType.isNull() && compType->isArithmeticType()) {
  7029. if (CompLHSTy) *CompLHSTy = compType;
  7030. return compType;
  7031. }
  7032. // Either ptr - int or ptr - ptr.
  7033. if (LHS.get()->getType()->isAnyPointerType()) {
  7034. QualType lpointee = LHS.get()->getType()->getPointeeType();
  7035. // Diagnose bad cases where we step over interface counts.
  7036. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  7037. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  7038. return QualType();
  7039. // The result type of a pointer-int computation is the pointer type.
  7040. if (RHS.get()->getType()->isIntegerType()) {
  7041. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  7042. return QualType();
  7043. // Check array bounds for pointer arithemtic
  7044. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  7045. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  7046. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7047. return LHS.get()->getType();
  7048. }
  7049. // Handle pointer-pointer subtractions.
  7050. if (const PointerType *RHSPTy
  7051. = RHS.get()->getType()->getAs<PointerType>()) {
  7052. QualType rpointee = RHSPTy->getPointeeType();
  7053. if (getLangOpts().CPlusPlus) {
  7054. // Pointee types must be the same: C++ [expr.add]
  7055. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  7056. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7057. }
  7058. } else {
  7059. // Pointee types must be compatible C99 6.5.6p3
  7060. if (!Context.typesAreCompatible(
  7061. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  7062. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  7063. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7064. return QualType();
  7065. }
  7066. }
  7067. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  7068. LHS.get(), RHS.get()))
  7069. return QualType();
  7070. // The pointee type may have zero size. As an extension, a structure or
  7071. // union may have zero size or an array may have zero length. In this
  7072. // case subtraction does not make sense.
  7073. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7074. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7075. if (ElementSize.isZero()) {
  7076. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7077. << rpointee.getUnqualifiedType()
  7078. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7079. }
  7080. }
  7081. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7082. return Context.getPointerDiffType();
  7083. }
  7084. }
  7085. return InvalidOperands(Loc, LHS, RHS);
  7086. }
  7087. static bool isScopedEnumerationType(QualType T) {
  7088. if (const EnumType *ET = T->getAs<EnumType>())
  7089. return ET->getDecl()->isScoped();
  7090. return false;
  7091. }
  7092. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7093. SourceLocation Loc, unsigned Opc,
  7094. QualType LHSType) {
  7095. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7096. // so skip remaining warnings as we don't want to modify values within Sema.
  7097. if (S.getLangOpts().OpenCL)
  7098. return;
  7099. llvm::APSInt Right;
  7100. // Check right/shifter operand
  7101. if (RHS.get()->isValueDependent() ||
  7102. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7103. return;
  7104. if (Right.isNegative()) {
  7105. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7106. S.PDiag(diag::warn_shift_negative)
  7107. << RHS.get()->getSourceRange());
  7108. return;
  7109. }
  7110. llvm::APInt LeftBits(Right.getBitWidth(),
  7111. S.Context.getTypeSize(LHS.get()->getType()));
  7112. if (Right.uge(LeftBits)) {
  7113. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7114. S.PDiag(diag::warn_shift_gt_typewidth)
  7115. << RHS.get()->getSourceRange());
  7116. return;
  7117. }
  7118. if (Opc != BO_Shl)
  7119. return;
  7120. // When left shifting an ICE which is signed, we can check for overflow which
  7121. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7122. // integers have defined behavior modulo one more than the maximum value
  7123. // representable in the result type, so never warn for those.
  7124. llvm::APSInt Left;
  7125. if (LHS.get()->isValueDependent() ||
  7126. LHSType->hasUnsignedIntegerRepresentation() ||
  7127. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7128. return;
  7129. // If LHS does not have a signed type and non-negative value
  7130. // then, the behavior is undefined. Warn about it.
  7131. if (Left.isNegative()) {
  7132. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7133. S.PDiag(diag::warn_shift_lhs_negative)
  7134. << LHS.get()->getSourceRange());
  7135. return;
  7136. }
  7137. llvm::APInt ResultBits =
  7138. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7139. if (LeftBits.uge(ResultBits))
  7140. return;
  7141. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  7142. Result = Result.shl(Right);
  7143. // Print the bit representation of the signed integer as an unsigned
  7144. // hexadecimal number.
  7145. SmallString<40> HexResult;
  7146. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  7147. // If we are only missing a sign bit, this is less likely to result in actual
  7148. // bugs -- if the result is cast back to an unsigned type, it will have the
  7149. // expected value. Thus we place this behind a different warning that can be
  7150. // turned off separately if needed.
  7151. if (LeftBits == ResultBits - 1) {
  7152. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  7153. << HexResult << LHSType
  7154. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7155. return;
  7156. }
  7157. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  7158. << HexResult.str() << Result.getMinSignedBits() << LHSType
  7159. << Left.getBitWidth() << LHS.get()->getSourceRange()
  7160. << RHS.get()->getSourceRange();
  7161. }
  7162. /// \brief Return the resulting type when an OpenCL vector is shifted
  7163. /// by a scalar or vector shift amount.
  7164. static QualType checkOpenCLVectorShift(Sema &S,
  7165. ExprResult &LHS, ExprResult &RHS,
  7166. SourceLocation Loc, bool IsCompAssign) {
  7167. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  7168. if (!LHS.get()->getType()->isVectorType()) {
  7169. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  7170. << RHS.get()->getType() << LHS.get()->getType()
  7171. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7172. return QualType();
  7173. }
  7174. if (!IsCompAssign) {
  7175. LHS = S.UsualUnaryConversions(LHS.get());
  7176. if (LHS.isInvalid()) return QualType();
  7177. }
  7178. RHS = S.UsualUnaryConversions(RHS.get());
  7179. if (RHS.isInvalid()) return QualType();
  7180. QualType LHSType = LHS.get()->getType();
  7181. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  7182. QualType LHSEleType = LHSVecTy->getElementType();
  7183. // Note that RHS might not be a vector.
  7184. QualType RHSType = RHS.get()->getType();
  7185. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  7186. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  7187. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  7188. if (!LHSEleType->isIntegerType()) {
  7189. S.Diag(Loc, diag::err_typecheck_expect_int)
  7190. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7191. return QualType();
  7192. }
  7193. if (!RHSEleType->isIntegerType()) {
  7194. S.Diag(Loc, diag::err_typecheck_expect_int)
  7195. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7196. return QualType();
  7197. }
  7198. if (RHSVecTy) {
  7199. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7200. // are applied component-wise. So if RHS is a vector, then ensure
  7201. // that the number of elements is the same as LHS...
  7202. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7203. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7204. << LHS.get()->getType() << RHS.get()->getType()
  7205. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7206. return QualType();
  7207. }
  7208. } else {
  7209. // ...else expand RHS to match the number of elements in LHS.
  7210. QualType VecTy =
  7211. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7212. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7213. }
  7214. return LHSType;
  7215. }
  7216. // C99 6.5.7
  7217. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7218. SourceLocation Loc, unsigned Opc,
  7219. bool IsCompAssign) {
  7220. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7221. // Vector shifts promote their scalar inputs to vector type.
  7222. if (LHS.get()->getType()->isVectorType() ||
  7223. RHS.get()->getType()->isVectorType()) {
  7224. if (LangOpts.OpenCL)
  7225. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7226. if (LangOpts.ZVector) {
  7227. // The shift operators for the z vector extensions work basically
  7228. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7229. // allowed to be a "vector bool".
  7230. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7231. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7232. return InvalidOperands(Loc, LHS, RHS);
  7233. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7234. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7235. return InvalidOperands(Loc, LHS, RHS);
  7236. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7237. }
  7238. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7239. /*AllowBothBool*/true,
  7240. /*AllowBoolConversions*/false);
  7241. }
  7242. // Shifts don't perform usual arithmetic conversions, they just do integer
  7243. // promotions on each operand. C99 6.5.7p3
  7244. // For the LHS, do usual unary conversions, but then reset them away
  7245. // if this is a compound assignment.
  7246. ExprResult OldLHS = LHS;
  7247. LHS = UsualUnaryConversions(LHS.get());
  7248. if (LHS.isInvalid())
  7249. return QualType();
  7250. QualType LHSType = LHS.get()->getType();
  7251. if (IsCompAssign) LHS = OldLHS;
  7252. // The RHS is simpler.
  7253. RHS = UsualUnaryConversions(RHS.get());
  7254. if (RHS.isInvalid())
  7255. return QualType();
  7256. QualType RHSType = RHS.get()->getType();
  7257. // C99 6.5.7p2: Each of the operands shall have integer type.
  7258. if (!LHSType->hasIntegerRepresentation() ||
  7259. !RHSType->hasIntegerRepresentation())
  7260. return InvalidOperands(Loc, LHS, RHS);
  7261. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7262. // hasIntegerRepresentation() above instead of this.
  7263. if (isScopedEnumerationType(LHSType) ||
  7264. isScopedEnumerationType(RHSType)) {
  7265. return InvalidOperands(Loc, LHS, RHS);
  7266. }
  7267. // Sanity-check shift operands
  7268. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7269. // "The type of the result is that of the promoted left operand."
  7270. return LHSType;
  7271. }
  7272. static bool IsWithinTemplateSpecialization(Decl *D) {
  7273. if (DeclContext *DC = D->getDeclContext()) {
  7274. if (isa<ClassTemplateSpecializationDecl>(DC))
  7275. return true;
  7276. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7277. return FD->isFunctionTemplateSpecialization();
  7278. }
  7279. return false;
  7280. }
  7281. /// If two different enums are compared, raise a warning.
  7282. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7283. Expr *RHS) {
  7284. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7285. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7286. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7287. if (!LHSEnumType)
  7288. return;
  7289. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7290. if (!RHSEnumType)
  7291. return;
  7292. // Ignore anonymous enums.
  7293. if (!LHSEnumType->getDecl()->getIdentifier())
  7294. return;
  7295. if (!RHSEnumType->getDecl()->getIdentifier())
  7296. return;
  7297. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7298. return;
  7299. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7300. << LHSStrippedType << RHSStrippedType
  7301. << LHS->getSourceRange() << RHS->getSourceRange();
  7302. }
  7303. /// \brief Diagnose bad pointer comparisons.
  7304. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7305. ExprResult &LHS, ExprResult &RHS,
  7306. bool IsError) {
  7307. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7308. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7309. << LHS.get()->getType() << RHS.get()->getType()
  7310. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7311. }
  7312. /// \brief Returns false if the pointers are converted to a composite type,
  7313. /// true otherwise.
  7314. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7315. ExprResult &LHS, ExprResult &RHS) {
  7316. // C++ [expr.rel]p2:
  7317. // [...] Pointer conversions (4.10) and qualification
  7318. // conversions (4.4) are performed on pointer operands (or on
  7319. // a pointer operand and a null pointer constant) to bring
  7320. // them to their composite pointer type. [...]
  7321. //
  7322. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7323. // comparisons of pointers.
  7324. // C++ [expr.eq]p2:
  7325. // In addition, pointers to members can be compared, or a pointer to
  7326. // member and a null pointer constant. Pointer to member conversions
  7327. // (4.11) and qualification conversions (4.4) are performed to bring
  7328. // them to a common type. If one operand is a null pointer constant,
  7329. // the common type is the type of the other operand. Otherwise, the
  7330. // common type is a pointer to member type similar (4.4) to the type
  7331. // of one of the operands, with a cv-qualification signature (4.4)
  7332. // that is the union of the cv-qualification signatures of the operand
  7333. // types.
  7334. QualType LHSType = LHS.get()->getType();
  7335. QualType RHSType = RHS.get()->getType();
  7336. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7337. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7338. bool NonStandardCompositeType = false;
  7339. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7340. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7341. if (T.isNull()) {
  7342. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7343. return true;
  7344. }
  7345. if (NonStandardCompositeType)
  7346. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7347. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7348. << RHS.get()->getSourceRange();
  7349. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7350. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7351. return false;
  7352. }
  7353. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7354. ExprResult &LHS,
  7355. ExprResult &RHS,
  7356. bool IsError) {
  7357. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7358. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7359. << LHS.get()->getType() << RHS.get()->getType()
  7360. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7361. }
  7362. #if 1 // HLSL Change Starts
  7363. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7364. return LK_None;
  7365. }
  7366. #else
  7367. static bool isObjCObjectLiteral(ExprResult &E) {
  7368. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7369. case Stmt::ObjCArrayLiteralClass:
  7370. case Stmt::ObjCDictionaryLiteralClass:
  7371. case Stmt::ObjCStringLiteralClass:
  7372. case Stmt::ObjCBoxedExprClass:
  7373. return true;
  7374. default:
  7375. // Note that ObjCBoolLiteral is NOT an object literal!
  7376. return false;
  7377. }
  7378. }
  7379. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7380. const ObjCObjectPointerType *Type =
  7381. LHS->getType()->getAs<ObjCObjectPointerType>();
  7382. // If this is not actually an Objective-C object, bail out.
  7383. if (!Type)
  7384. return false;
  7385. // Get the LHS object's interface type.
  7386. QualType InterfaceType = Type->getPointeeType();
  7387. // If the RHS isn't an Objective-C object, bail out.
  7388. if (!RHS->getType()->isObjCObjectPointerType())
  7389. return false;
  7390. // Try to find the -isEqual: method.
  7391. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7392. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7393. InterfaceType,
  7394. /*instance=*/true);
  7395. if (!Method) {
  7396. if (Type->isObjCIdType()) {
  7397. // For 'id', just check the global pool.
  7398. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7399. /*receiverId=*/true);
  7400. } else {
  7401. // Check protocols.
  7402. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7403. /*instance=*/true);
  7404. }
  7405. }
  7406. if (!Method)
  7407. return false;
  7408. QualType T = Method->parameters()[0]->getType();
  7409. if (!T->isObjCObjectPointerType())
  7410. return false;
  7411. QualType R = Method->getReturnType();
  7412. if (!R->isScalarType())
  7413. return false;
  7414. return true;
  7415. }
  7416. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7417. FromE = FromE->IgnoreParenImpCasts();
  7418. switch (FromE->getStmtClass()) {
  7419. default:
  7420. break;
  7421. case Stmt::ObjCStringLiteralClass:
  7422. // "string literal"
  7423. return LK_String;
  7424. case Stmt::ObjCArrayLiteralClass:
  7425. // "array literal"
  7426. return LK_Array;
  7427. case Stmt::ObjCDictionaryLiteralClass:
  7428. // "dictionary literal"
  7429. return LK_Dictionary;
  7430. case Stmt::BlockExprClass:
  7431. return LK_Block;
  7432. case Stmt::ObjCBoxedExprClass: {
  7433. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7434. switch (Inner->getStmtClass()) {
  7435. case Stmt::IntegerLiteralClass:
  7436. case Stmt::FloatingLiteralClass:
  7437. case Stmt::CharacterLiteralClass:
  7438. case Stmt::ObjCBoolLiteralExprClass:
  7439. case Stmt::CXXBoolLiteralExprClass:
  7440. // "numeric literal"
  7441. return LK_Numeric;
  7442. case Stmt::ImplicitCastExprClass: {
  7443. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7444. // Boolean literals can be represented by implicit casts.
  7445. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7446. return LK_Numeric;
  7447. break;
  7448. }
  7449. default:
  7450. break;
  7451. }
  7452. return LK_Boxed;
  7453. }
  7454. }
  7455. return LK_None;
  7456. }
  7457. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7458. ExprResult &LHS, ExprResult &RHS,
  7459. BinaryOperator::Opcode Opc){
  7460. Expr *Literal;
  7461. Expr *Other;
  7462. if (isObjCObjectLiteral(LHS)) {
  7463. Literal = LHS.get();
  7464. Other = RHS.get();
  7465. } else {
  7466. Literal = RHS.get();
  7467. Other = LHS.get();
  7468. }
  7469. // Don't warn on comparisons against nil.
  7470. Other = Other->IgnoreParenCasts();
  7471. if (Other->isNullPointerConstant(S.getASTContext(),
  7472. Expr::NPC_ValueDependentIsNotNull))
  7473. return;
  7474. // This should be kept in sync with warn_objc_literal_comparison.
  7475. // LK_String should always be after the other literals, since it has its own
  7476. // warning flag.
  7477. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7478. assert(LiteralKind != Sema::LK_Block);
  7479. if (LiteralKind == Sema::LK_None) {
  7480. llvm_unreachable("Unknown Objective-C object literal kind");
  7481. }
  7482. if (LiteralKind == Sema::LK_String)
  7483. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7484. << Literal->getSourceRange();
  7485. else
  7486. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7487. << LiteralKind << Literal->getSourceRange();
  7488. if (BinaryOperator::isEqualityOp(Opc) &&
  7489. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7490. SourceLocation Start = LHS.get()->getLocStart();
  7491. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7492. CharSourceRange OpRange =
  7493. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7494. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7495. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7496. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7497. << FixItHint::CreateInsertion(End, "]");
  7498. }
  7499. }
  7500. #endif // HLSL Change Ends
  7501. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7502. ExprResult &RHS,
  7503. SourceLocation Loc,
  7504. unsigned OpaqueOpc) {
  7505. // This checking requires bools.
  7506. if (!S.getLangOpts().Bool) return;
  7507. // Check that left hand side is !something.
  7508. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7509. if (!UO || UO->getOpcode() != UO_LNot) return;
  7510. // Only check if the right hand side is non-bool arithmetic type.
  7511. if (RHS.get()->getType()->isBooleanType()) return;
  7512. // Make sure that the something in !something is not bool.
  7513. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7514. if (SubExpr->getType()->isBooleanType()) return;
  7515. // Emit warning.
  7516. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7517. << Loc;
  7518. // First note suggest !(x < y)
  7519. SourceLocation FirstOpen = SubExpr->getLocStart();
  7520. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7521. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7522. if (FirstClose.isInvalid())
  7523. FirstOpen = SourceLocation();
  7524. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7525. << FixItHint::CreateInsertion(FirstOpen, "(")
  7526. << FixItHint::CreateInsertion(FirstClose, ")");
  7527. // Second note suggests (!x) < y
  7528. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7529. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7530. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7531. if (SecondClose.isInvalid())
  7532. SecondOpen = SourceLocation();
  7533. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7534. << FixItHint::CreateInsertion(SecondOpen, "(")
  7535. << FixItHint::CreateInsertion(SecondClose, ")");
  7536. }
  7537. // Get the decl for a simple expression: a reference to a variable,
  7538. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7539. static ValueDecl *getCompareDecl(Expr *E) {
  7540. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7541. return DR->getDecl();
  7542. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7543. if (Ivar->isFreeIvar())
  7544. return Ivar->getDecl();
  7545. }
  7546. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7547. if (Mem->isImplicitAccess())
  7548. return Mem->getMemberDecl();
  7549. }
  7550. return nullptr;
  7551. }
  7552. // C99 6.5.8, C++ [expr.rel]
  7553. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7554. SourceLocation Loc, unsigned OpaqueOpc,
  7555. bool IsRelational) {
  7556. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7557. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7558. // Handle vector comparisons separately.
  7559. if (LHS.get()->getType()->isVectorType() ||
  7560. RHS.get()->getType()->isVectorType())
  7561. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7562. QualType LHSType = LHS.get()->getType();
  7563. QualType RHSType = RHS.get()->getType();
  7564. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7565. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7566. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7567. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7568. if (!LHSType->hasFloatingRepresentation() &&
  7569. !(LHSType->isBlockPointerType() && IsRelational) &&
  7570. !LHS.get()->getLocStart().isMacroID() &&
  7571. !RHS.get()->getLocStart().isMacroID() &&
  7572. ActiveTemplateInstantiations.empty()) {
  7573. // For non-floating point types, check for self-comparisons of the form
  7574. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7575. // often indicate logic errors in the program.
  7576. //
  7577. // NOTE: Don't warn about comparison expressions resulting from macro
  7578. // expansion. Also don't warn about comparisons which are only self
  7579. // comparisons within a template specialization. The warnings should catch
  7580. // obvious cases in the definition of the template anyways. The idea is to
  7581. // warn when the typed comparison operator will always evaluate to the same
  7582. // result.
  7583. ValueDecl *DL = getCompareDecl(LHSStripped);
  7584. ValueDecl *DR = getCompareDecl(RHSStripped);
  7585. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7586. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7587. << 0 // self-
  7588. << (Opc == BO_EQ
  7589. || Opc == BO_LE
  7590. || Opc == BO_GE));
  7591. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7592. !DL->getType()->isReferenceType() &&
  7593. !DR->getType()->isReferenceType()) {
  7594. // what is it always going to eval to?
  7595. char always_evals_to;
  7596. switch(Opc) {
  7597. case BO_EQ: // e.g. array1 == array2
  7598. always_evals_to = 0; // false
  7599. break;
  7600. case BO_NE: // e.g. array1 != array2
  7601. always_evals_to = 1; // true
  7602. break;
  7603. default:
  7604. // best we can say is 'a constant'
  7605. always_evals_to = 2; // e.g. array1 <= array2
  7606. break;
  7607. }
  7608. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7609. << 1 // array
  7610. << always_evals_to);
  7611. }
  7612. if (isa<CastExpr>(LHSStripped))
  7613. LHSStripped = LHSStripped->IgnoreParenCasts();
  7614. if (isa<CastExpr>(RHSStripped))
  7615. RHSStripped = RHSStripped->IgnoreParenCasts();
  7616. // Warn about comparisons against a string constant (unless the other
  7617. // operand is null), the user probably wants strcmp.
  7618. Expr *literalString = nullptr;
  7619. Expr *literalStringStripped = nullptr;
  7620. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7621. !RHSStripped->isNullPointerConstant(Context,
  7622. Expr::NPC_ValueDependentIsNull)) {
  7623. literalString = LHS.get();
  7624. literalStringStripped = LHSStripped;
  7625. } else if ((isa<StringLiteral>(RHSStripped) ||
  7626. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7627. !LHSStripped->isNullPointerConstant(Context,
  7628. Expr::NPC_ValueDependentIsNull)) {
  7629. literalString = RHS.get();
  7630. literalStringStripped = RHSStripped;
  7631. }
  7632. if (literalString) {
  7633. DiagRuntimeBehavior(Loc, nullptr,
  7634. PDiag(diag::warn_stringcompare)
  7635. << isa<ObjCEncodeExpr>(literalStringStripped)
  7636. << literalString->getSourceRange());
  7637. }
  7638. }
  7639. // C99 6.5.8p3 / C99 6.5.9p4
  7640. UsualArithmeticConversions(LHS, RHS);
  7641. if (LHS.isInvalid() || RHS.isInvalid())
  7642. return QualType();
  7643. LHSType = LHS.get()->getType();
  7644. RHSType = RHS.get()->getType();
  7645. // The result of comparisons is 'bool' in C++, 'int' in C.
  7646. QualType ResultTy = Context.getLogicalOperationType();
  7647. if (IsRelational) {
  7648. if (LHSType->isRealType() && RHSType->isRealType())
  7649. return ResultTy;
  7650. } else {
  7651. // Check for comparisons of floating point operands using != and ==.
  7652. if (LHSType->hasFloatingRepresentation())
  7653. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7654. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7655. return ResultTy;
  7656. }
  7657. const Expr::NullPointerConstantKind LHSNullKind =
  7658. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7659. const Expr::NullPointerConstantKind RHSNullKind =
  7660. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7661. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7662. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7663. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7664. bool IsEquality = Opc == BO_EQ;
  7665. if (RHSIsNull)
  7666. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7667. RHS.get()->getSourceRange());
  7668. else
  7669. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7670. LHS.get()->getSourceRange());
  7671. }
  7672. // All of the following pointer-related warnings are GCC extensions, except
  7673. // when handling null pointer constants.
  7674. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7675. QualType LCanPointeeTy =
  7676. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7677. QualType RCanPointeeTy =
  7678. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7679. if (getLangOpts().CPlusPlus) {
  7680. if (LCanPointeeTy == RCanPointeeTy)
  7681. return ResultTy;
  7682. if (!IsRelational &&
  7683. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7684. // Valid unless comparison between non-null pointer and function pointer
  7685. // This is a gcc extension compatibility comparison.
  7686. // In a SFINAE context, we treat this as a hard error to maintain
  7687. // conformance with the C++ standard.
  7688. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7689. && !LHSIsNull && !RHSIsNull) {
  7690. diagnoseFunctionPointerToVoidComparison(
  7691. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7692. if (isSFINAEContext())
  7693. return QualType();
  7694. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7695. return ResultTy;
  7696. }
  7697. }
  7698. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7699. return QualType();
  7700. else
  7701. return ResultTy;
  7702. }
  7703. // C99 6.5.9p2 and C99 6.5.8p2
  7704. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7705. RCanPointeeTy.getUnqualifiedType())) {
  7706. // Valid unless a relational comparison of function pointers
  7707. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7708. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7709. << LHSType << RHSType << LHS.get()->getSourceRange()
  7710. << RHS.get()->getSourceRange();
  7711. }
  7712. } else if (!IsRelational &&
  7713. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7714. // Valid unless comparison between non-null pointer and function pointer
  7715. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7716. && !LHSIsNull && !RHSIsNull)
  7717. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7718. /*isError*/false);
  7719. } else {
  7720. // Invalid
  7721. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7722. }
  7723. if (LCanPointeeTy != RCanPointeeTy) {
  7724. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7725. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7726. Diag(Loc,
  7727. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7728. << LHSType << RHSType << 0 /* comparison */
  7729. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7730. }
  7731. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7732. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7733. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7734. : CK_BitCast;
  7735. if (LHSIsNull && !RHSIsNull)
  7736. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7737. else
  7738. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7739. }
  7740. return ResultTy;
  7741. }
  7742. if (getLangOpts().CPlusPlus) {
  7743. // Comparison of nullptr_t with itself.
  7744. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7745. return ResultTy;
  7746. // Comparison of pointers with null pointer constants and equality
  7747. // comparisons of member pointers to null pointer constants.
  7748. if (RHSIsNull &&
  7749. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7750. (!IsRelational &&
  7751. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7752. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7753. LHSType->isMemberPointerType()
  7754. ? CK_NullToMemberPointer
  7755. : CK_NullToPointer);
  7756. return ResultTy;
  7757. }
  7758. if (LHSIsNull &&
  7759. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7760. (!IsRelational &&
  7761. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7762. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7763. RHSType->isMemberPointerType()
  7764. ? CK_NullToMemberPointer
  7765. : CK_NullToPointer);
  7766. return ResultTy;
  7767. }
  7768. // Comparison of member pointers.
  7769. if (!IsRelational &&
  7770. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7771. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7772. return QualType();
  7773. else
  7774. return ResultTy;
  7775. }
  7776. // Handle scoped enumeration types specifically, since they don't promote
  7777. // to integers.
  7778. if (LHS.get()->getType()->isEnumeralType() &&
  7779. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7780. RHS.get()->getType()))
  7781. return ResultTy;
  7782. }
  7783. // Handle block pointer types.
  7784. if (!IsRelational && LHSType->isBlockPointerType() &&
  7785. RHSType->isBlockPointerType()) {
  7786. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7787. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7788. if (!LHSIsNull && !RHSIsNull &&
  7789. !Context.typesAreCompatible(lpointee, rpointee)) {
  7790. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7791. << LHSType << RHSType << LHS.get()->getSourceRange()
  7792. << RHS.get()->getSourceRange();
  7793. }
  7794. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7795. return ResultTy;
  7796. }
  7797. // Allow block pointers to be compared with null pointer constants.
  7798. if (!IsRelational
  7799. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7800. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7801. if (!LHSIsNull && !RHSIsNull) {
  7802. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7803. ->getPointeeType()->isVoidType())
  7804. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7805. ->getPointeeType()->isVoidType())))
  7806. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7807. << LHSType << RHSType << LHS.get()->getSourceRange()
  7808. << RHS.get()->getSourceRange();
  7809. }
  7810. if (LHSIsNull && !RHSIsNull)
  7811. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7812. RHSType->isPointerType() ? CK_BitCast
  7813. : CK_AnyPointerToBlockPointerCast);
  7814. else
  7815. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7816. LHSType->isPointerType() ? CK_BitCast
  7817. : CK_AnyPointerToBlockPointerCast);
  7818. return ResultTy;
  7819. }
  7820. if (LHSType->isObjCObjectPointerType() ||
  7821. RHSType->isObjCObjectPointerType()) {
  7822. const PointerType *LPT = LHSType->getAs<PointerType>();
  7823. const PointerType *RPT = RHSType->getAs<PointerType>();
  7824. if (LPT || RPT) {
  7825. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7826. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7827. if (!LPtrToVoid && !RPtrToVoid &&
  7828. !Context.typesAreCompatible(LHSType, RHSType)) {
  7829. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7830. /*isError*/false);
  7831. }
  7832. if (LHSIsNull && !RHSIsNull) {
  7833. Expr *E = LHS.get();
  7834. #if 0 // HLSL Change - no ObjC support
  7835. if (getLangOpts().ObjCAutoRefCount)
  7836. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7837. #endif // HLSL Change
  7838. LHS = ImpCastExprToType(E, RHSType,
  7839. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7840. }
  7841. else {
  7842. Expr *E = RHS.get();
  7843. #if 0 // HLSL Change - no ObjC support
  7844. if (getLangOpts().ObjCAutoRefCount)
  7845. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7846. Opc);
  7847. #endif // HLSL Change
  7848. RHS = ImpCastExprToType(E, LHSType,
  7849. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7850. }
  7851. return ResultTy;
  7852. }
  7853. #if 0 // HLSL Change - no ObjC support
  7854. if (LHSType->isObjCObjectPointerType() &&
  7855. RHSType->isObjCObjectPointerType()) {
  7856. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7857. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7858. /*isError*/false);
  7859. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7860. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7861. if (LHSIsNull && !RHSIsNull)
  7862. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7863. else
  7864. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7865. return ResultTy;
  7866. }
  7867. #endif // HLSL Change
  7868. }
  7869. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7870. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7871. unsigned DiagID = 0;
  7872. bool isError = false;
  7873. if (LangOpts.DebuggerSupport) {
  7874. // Under a debugger, allow the comparison of pointers to integers,
  7875. // since users tend to want to compare addresses.
  7876. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7877. (RHSIsNull && RHSType->isIntegerType())) {
  7878. if (IsRelational && !getLangOpts().CPlusPlus)
  7879. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7880. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7881. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7882. else if (getLangOpts().CPlusPlus) {
  7883. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7884. isError = true;
  7885. } else
  7886. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7887. if (DiagID) {
  7888. Diag(Loc, DiagID)
  7889. << LHSType << RHSType << LHS.get()->getSourceRange()
  7890. << RHS.get()->getSourceRange();
  7891. if (isError)
  7892. return QualType();
  7893. }
  7894. if (LHSType->isIntegerType())
  7895. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7896. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7897. else
  7898. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7899. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7900. return ResultTy;
  7901. }
  7902. // Handle block pointers.
  7903. if (!IsRelational && RHSIsNull
  7904. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7905. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7906. return ResultTy;
  7907. }
  7908. if (!IsRelational && LHSIsNull
  7909. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7910. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7911. return ResultTy;
  7912. }
  7913. return InvalidOperands(Loc, LHS, RHS);
  7914. }
  7915. // Return a signed type that is of identical size and number of elements.
  7916. // For floating point vectors, return an integer type of identical size
  7917. // and number of elements.
  7918. QualType Sema::GetSignedVectorType(QualType V) {
  7919. const VectorType *VTy = V->getAs<VectorType>();
  7920. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7921. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7922. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7923. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7924. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7925. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7926. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7927. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7928. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7929. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7930. "Unhandled vector element size in vector compare");
  7931. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7932. }
  7933. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7934. /// operates on extended vector types. Instead of producing an IntTy result,
  7935. /// like a scalar comparison, a vector comparison produces a vector of integer
  7936. /// types.
  7937. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7938. SourceLocation Loc,
  7939. bool IsRelational) {
  7940. // Check to make sure we're operating on vectors of the same type and width,
  7941. // Allowing one side to be a scalar of element type.
  7942. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7943. /*AllowBothBool*/true,
  7944. /*AllowBoolConversions*/getLangOpts().ZVector);
  7945. if (vType.isNull())
  7946. return vType;
  7947. QualType LHSType = LHS.get()->getType();
  7948. // If AltiVec, the comparison results in a numeric type, i.e.
  7949. // bool for C++, int for C
  7950. if (getLangOpts().AltiVec &&
  7951. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7952. return Context.getLogicalOperationType();
  7953. // For non-floating point types, check for self-comparisons of the form
  7954. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7955. // often indicate logic errors in the program.
  7956. if (!LHSType->hasFloatingRepresentation() &&
  7957. ActiveTemplateInstantiations.empty()) {
  7958. if (DeclRefExpr* DRL
  7959. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7960. if (DeclRefExpr* DRR
  7961. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7962. if (DRL->getDecl() == DRR->getDecl())
  7963. DiagRuntimeBehavior(Loc, nullptr,
  7964. PDiag(diag::warn_comparison_always)
  7965. << 0 // self-
  7966. << 2 // "a constant"
  7967. );
  7968. }
  7969. // Check for comparisons of floating point operands using != and ==.
  7970. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7971. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7972. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7973. }
  7974. // Return a signed type for the vector.
  7975. return GetSignedVectorType(LHSType);
  7976. }
  7977. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7978. SourceLocation Loc) {
  7979. // Ensure that either both operands are of the same vector type, or
  7980. // one operand is of a vector type and the other is of its element type.
  7981. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7982. /*AllowBothBool*/true,
  7983. /*AllowBoolConversions*/false);
  7984. if (vType.isNull())
  7985. return InvalidOperands(Loc, LHS, RHS);
  7986. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7987. vType->hasFloatingRepresentation())
  7988. return InvalidOperands(Loc, LHS, RHS);
  7989. return GetSignedVectorType(LHS.get()->getType());
  7990. }
  7991. inline QualType Sema::CheckBitwiseOperands(
  7992. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7993. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7994. if (LHS.get()->getType()->isVectorType() ||
  7995. RHS.get()->getType()->isVectorType()) {
  7996. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7997. RHS.get()->getType()->hasIntegerRepresentation())
  7998. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7999. /*AllowBothBool*/true,
  8000. /*AllowBoolConversions*/getLangOpts().ZVector);
  8001. return InvalidOperands(Loc, LHS, RHS);
  8002. }
  8003. ExprResult LHSResult = LHS, RHSResult = RHS;
  8004. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  8005. IsCompAssign);
  8006. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  8007. return QualType();
  8008. LHS = LHSResult.get();
  8009. RHS = RHSResult.get();
  8010. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  8011. return compType;
  8012. return InvalidOperands(Loc, LHS, RHS);
  8013. }
  8014. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  8015. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  8016. // Check vector operands differently.
  8017. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  8018. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  8019. // Diagnose cases where the user write a logical and/or but probably meant a
  8020. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  8021. // is a constant.
  8022. if (LHS.get()->getType()->isIntegerType() &&
  8023. !LHS.get()->getType()->isBooleanType() &&
  8024. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  8025. // Don't warn in macros or template instantiations.
  8026. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  8027. // If the RHS can be constant folded, and if it constant folds to something
  8028. // that isn't 0 or 1 (which indicate a potential logical operation that
  8029. // happened to fold to true/false) then warn.
  8030. // Parens on the RHS are ignored.
  8031. llvm::APSInt Result;
  8032. if (RHS.get()->EvaluateAsInt(Result, Context))
  8033. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  8034. !RHS.get()->getExprLoc().isMacroID()) ||
  8035. (Result != 0 && Result != 1)) {
  8036. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  8037. << RHS.get()->getSourceRange()
  8038. << (Opc == BO_LAnd ? "&&" : "||");
  8039. // Suggest replacing the logical operator with the bitwise version
  8040. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  8041. << (Opc == BO_LAnd ? "&" : "|")
  8042. << FixItHint::CreateReplacement(SourceRange(
  8043. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  8044. getLangOpts())),
  8045. Opc == BO_LAnd ? "&" : "|");
  8046. if (Opc == BO_LAnd)
  8047. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  8048. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  8049. << FixItHint::CreateRemoval(
  8050. SourceRange(
  8051. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  8052. 0, getSourceManager(),
  8053. getLangOpts()),
  8054. RHS.get()->getLocEnd()));
  8055. }
  8056. }
  8057. if (!Context.getLangOpts().CPlusPlus) {
  8058. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  8059. // not operate on the built-in scalar and vector float types.
  8060. if (Context.getLangOpts().OpenCL &&
  8061. Context.getLangOpts().OpenCLVersion < 120) {
  8062. if (LHS.get()->getType()->isFloatingType() ||
  8063. RHS.get()->getType()->isFloatingType())
  8064. return InvalidOperands(Loc, LHS, RHS);
  8065. }
  8066. LHS = UsualUnaryConversions(LHS.get());
  8067. if (LHS.isInvalid())
  8068. return QualType();
  8069. RHS = UsualUnaryConversions(RHS.get());
  8070. if (RHS.isInvalid())
  8071. return QualType();
  8072. if (!LHS.get()->getType()->isScalarType() ||
  8073. !RHS.get()->getType()->isScalarType())
  8074. return InvalidOperands(Loc, LHS, RHS);
  8075. return Context.IntTy;
  8076. }
  8077. // The following is safe because we only use this method for
  8078. // non-overloadable operands.
  8079. // C++ [expr.log.and]p1
  8080. // C++ [expr.log.or]p1
  8081. // The operands are both contextually converted to type bool.
  8082. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  8083. if (LHSRes.isInvalid())
  8084. return InvalidOperands(Loc, LHS, RHS);
  8085. LHS = LHSRes;
  8086. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  8087. if (RHSRes.isInvalid())
  8088. return InvalidOperands(Loc, LHS, RHS);
  8089. RHS = RHSRes;
  8090. // C++ [expr.log.and]p2
  8091. // C++ [expr.log.or]p2
  8092. // The result is a bool.
  8093. return Context.BoolTy;
  8094. }
  8095. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  8096. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  8097. if (!ME) return false;
  8098. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  8099. ObjCMessageExpr *Base =
  8100. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  8101. if (!Base) return false;
  8102. return Base->getMethodDecl() != nullptr;
  8103. }
  8104. /// Is the given expression (which must be 'const') a reference to a
  8105. /// variable which was originally non-const, but which has become
  8106. /// 'const' due to being captured within a block?
  8107. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  8108. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  8109. assert(E->isLValue() && E->getType().isConstQualified());
  8110. E = E->IgnoreParens();
  8111. // Must be a reference to a declaration from an enclosing scope.
  8112. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  8113. if (!DRE) return NCCK_None;
  8114. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  8115. // The declaration must be a variable which is not declared 'const'.
  8116. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  8117. if (!var) return NCCK_None;
  8118. if (var->getType().isConstQualified()) return NCCK_None;
  8119. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  8120. // Decide whether the first capture was for a block or a lambda.
  8121. DeclContext *DC = S.CurContext, *Prev = nullptr;
  8122. while (DC != var->getDeclContext()) {
  8123. Prev = DC;
  8124. DC = DC->getParent();
  8125. }
  8126. // Unless we have an init-capture, we've gone one step too far.
  8127. if (!var->isInitCapture())
  8128. DC = Prev;
  8129. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  8130. }
  8131. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  8132. Ty = Ty.getNonReferenceType();
  8133. if (IsDereference && Ty->isPointerType())
  8134. Ty = Ty->getPointeeType();
  8135. return !Ty.isConstQualified();
  8136. }
  8137. /// Emit the "read-only variable not assignable" error and print notes to give
  8138. /// more information about why the variable is not assignable, such as pointing
  8139. /// to the declaration of a const variable, showing that a method is const, or
  8140. /// that the function is returning a const reference.
  8141. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  8142. SourceLocation Loc) {
  8143. // Update err_typecheck_assign_const and note_typecheck_assign_const
  8144. // when this enum is changed.
  8145. enum {
  8146. ConstFunction,
  8147. ConstVariable,
  8148. ConstMember,
  8149. ConstMethod,
  8150. ConstUnknown, // Keep as last element
  8151. };
  8152. SourceRange ExprRange = E->getSourceRange();
  8153. // Only emit one error on the first const found. All other consts will emit
  8154. // a note to the error.
  8155. bool DiagnosticEmitted = false;
  8156. // Track if the current expression is the result of a derefence, and if the
  8157. // next checked expression is the result of a derefence.
  8158. bool IsDereference = false;
  8159. bool NextIsDereference = false;
  8160. // Loop to process MemberExpr chains.
  8161. while (true) {
  8162. IsDereference = NextIsDereference;
  8163. NextIsDereference = false;
  8164. E = E->IgnoreParenImpCasts();
  8165. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  8166. NextIsDereference = ME->isArrow();
  8167. const ValueDecl *VD = ME->getMemberDecl();
  8168. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  8169. // Mutable fields can be modified even if the class is const.
  8170. if (Field->isMutable()) {
  8171. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  8172. break;
  8173. }
  8174. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  8175. if (!DiagnosticEmitted) {
  8176. S.Diag(Loc, diag::err_typecheck_assign_const)
  8177. << ExprRange << ConstMember << false /*static*/ << Field
  8178. << Field->getType();
  8179. DiagnosticEmitted = true;
  8180. }
  8181. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8182. << ConstMember << false /*static*/ << Field << Field->getType()
  8183. << Field->getSourceRange();
  8184. }
  8185. E = ME->getBase();
  8186. continue;
  8187. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  8188. if (VDecl->getType().isConstQualified()) {
  8189. if (!DiagnosticEmitted) {
  8190. S.Diag(Loc, diag::err_typecheck_assign_const)
  8191. << ExprRange << ConstMember << true /*static*/ << VDecl
  8192. << VDecl->getType();
  8193. DiagnosticEmitted = true;
  8194. }
  8195. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8196. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  8197. << VDecl->getSourceRange();
  8198. }
  8199. // Static fields do not inherit constness from parents.
  8200. break;
  8201. }
  8202. break;
  8203. } // End MemberExpr
  8204. break;
  8205. }
  8206. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8207. // Function calls
  8208. const FunctionDecl *FD = CE->getDirectCallee();
  8209. if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8210. if (!DiagnosticEmitted) {
  8211. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8212. << ConstFunction << FD;
  8213. DiagnosticEmitted = true;
  8214. }
  8215. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8216. diag::note_typecheck_assign_const)
  8217. << ConstFunction << FD << FD->getReturnType()
  8218. << FD->getReturnTypeSourceRange();
  8219. }
  8220. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8221. // Point to variable declaration.
  8222. if (const ValueDecl *VD = DRE->getDecl()) {
  8223. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8224. if (!DiagnosticEmitted) {
  8225. S.Diag(Loc, diag::err_typecheck_assign_const)
  8226. << ExprRange << ConstVariable << VD << VD->getType();
  8227. DiagnosticEmitted = true;
  8228. }
  8229. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8230. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8231. }
  8232. }
  8233. } else if (isa<CXXThisExpr>(E)) {
  8234. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8235. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8236. if (MD->isConst()) {
  8237. if (!DiagnosticEmitted) {
  8238. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8239. << ConstMethod << MD;
  8240. DiagnosticEmitted = true;
  8241. }
  8242. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8243. << ConstMethod << MD << MD->getSourceRange();
  8244. }
  8245. }
  8246. }
  8247. }
  8248. if (DiagnosticEmitted)
  8249. return;
  8250. // Can't determine a more specific message, so display the generic error.
  8251. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8252. }
  8253. static bool HLSLCheckForModifiableLValue(
  8254. Expr *E,
  8255. SourceLocation Loc,
  8256. Sema &S
  8257. ) {
  8258. assert(isa<CXXOperatorCallExpr>(E));
  8259. const CXXOperatorCallExpr *expr = cast<CXXOperatorCallExpr>(E);
  8260. const Expr *LHS = expr->getArg(0);
  8261. QualType qt = LHS->getType();
  8262. // Check modifying const matrix with double subscript operator calls
  8263. if (isa<CXXOperatorCallExpr>(expr->getArg(0)))
  8264. return HLSLCheckForModifiableLValue(const_cast<Expr *>(expr->getArg(0)), Loc, S);
  8265. if (qt.isConstQualified() && (hlsl::IsMatrixType(&S, qt) || hlsl::IsVectorType(&S, qt))) {
  8266. DiagnoseConstAssignment(S, LHS, Loc);
  8267. return true;
  8268. }
  8269. if (!LHS->isLValue()) {
  8270. S.Diag(Loc, diag::err_typecheck_expression_not_modifiable_lvalue);
  8271. return true;
  8272. }
  8273. return false;
  8274. }
  8275. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8276. /// emit an error and return true. If so, return false.
  8277. bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { // HLSL Change: export this function
  8278. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8279. // HLSL Change Starts - check const for array subscript operator for HLSL vector/matrix
  8280. if (S.Context.getLangOpts().HLSL && E->getStmtClass() == Stmt::CXXOperatorCallExprClass) {
  8281. // check if it's a vector or matrix
  8282. const CXXOperatorCallExpr *expr = cast<CXXOperatorCallExpr>(E);
  8283. QualType qt = expr->getArg(0)->getType();
  8284. if ((hlsl::IsMatrixType(&S, qt) || hlsl::IsVectorType(&S, qt)))
  8285. return HLSLCheckForModifiableLValue(E, Loc, S);
  8286. }
  8287. // HLSL Change Ends
  8288. SourceLocation OrigLoc = Loc;
  8289. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8290. &Loc);
  8291. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8292. IsLV = Expr::MLV_InvalidMessageExpression;
  8293. if (IsLV == Expr::MLV_Valid)
  8294. return false;
  8295. unsigned DiagID = 0;
  8296. bool NeedType = false;
  8297. switch (IsLV) { // C99 6.5.16p2
  8298. case Expr::MLV_ConstQualified:
  8299. // Use a specialized diagnostic when we're assigning to an object
  8300. // from an enclosing function or block.
  8301. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8302. if (NCCK == NCCK_Block)
  8303. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8304. else
  8305. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8306. break;
  8307. }
  8308. // In ARC, use some specialized diagnostics for occasions where we
  8309. // infer 'const'. These are always pseudo-strong variables.
  8310. if (S.getLangOpts().ObjCAutoRefCount) {
  8311. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8312. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8313. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8314. // Use the normal diagnostic if it's pseudo-__strong but the
  8315. // user actually wrote 'const'.
  8316. if (var->isARCPseudoStrong() &&
  8317. (!var->getTypeSourceInfo() ||
  8318. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8319. // There are two pseudo-strong cases:
  8320. // - self
  8321. ObjCMethodDecl *method = S.getCurMethodDecl();
  8322. if (method && var == method->getSelfDecl())
  8323. DiagID = method->isClassMethod()
  8324. ? diag::err_typecheck_arc_assign_self_class_method
  8325. : diag::err_typecheck_arc_assign_self;
  8326. // - fast enumeration variables
  8327. else
  8328. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8329. SourceRange Assign;
  8330. if (Loc != OrigLoc)
  8331. Assign = SourceRange(OrigLoc, OrigLoc);
  8332. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8333. // We need to preserve the AST regardless, so migration tool
  8334. // can do its job.
  8335. return false;
  8336. }
  8337. }
  8338. }
  8339. // If none of the special cases above are triggered, then this is a
  8340. // simple const assignment.
  8341. if (DiagID == 0) {
  8342. DiagnoseConstAssignment(S, E, Loc);
  8343. return true;
  8344. }
  8345. break;
  8346. case Expr::MLV_ConstAddrSpace:
  8347. DiagnoseConstAssignment(S, E, Loc);
  8348. return true;
  8349. case Expr::MLV_ArrayType:
  8350. case Expr::MLV_ArrayTemporary:
  8351. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8352. NeedType = true;
  8353. break;
  8354. case Expr::MLV_NotObjectType:
  8355. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8356. NeedType = true;
  8357. break;
  8358. case Expr::MLV_LValueCast:
  8359. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8360. break;
  8361. case Expr::MLV_Valid:
  8362. llvm_unreachable("did not take early return for MLV_Valid");
  8363. case Expr::MLV_InvalidExpression:
  8364. case Expr::MLV_MemberFunction:
  8365. case Expr::MLV_ClassTemporary:
  8366. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8367. break;
  8368. case Expr::MLV_IncompleteType:
  8369. case Expr::MLV_IncompleteVoidType:
  8370. return S.RequireCompleteType(Loc, E->getType(),
  8371. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8372. case Expr::MLV_DuplicateVectorComponents:
  8373. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8374. break;
  8375. // HLSL Change Starts
  8376. case Expr::MLV_DuplicateMatrixComponents:
  8377. DiagID = diag::err_hlsl_typecheck_duplicate_matrix_components_not_mlvalue;
  8378. break;
  8379. // HLSL Change Ends
  8380. case Expr::MLV_NoSetterProperty:
  8381. llvm_unreachable("readonly properties should be processed differently");
  8382. case Expr::MLV_InvalidMessageExpression:
  8383. DiagID = diag::error_readonly_message_assignment;
  8384. break;
  8385. case Expr::MLV_SubObjCPropertySetting:
  8386. DiagID = diag::error_no_subobject_property_setting;
  8387. break;
  8388. }
  8389. SourceRange Assign;
  8390. if (Loc != OrigLoc)
  8391. Assign = SourceRange(OrigLoc, OrigLoc);
  8392. if (NeedType)
  8393. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8394. else
  8395. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8396. return true;
  8397. }
  8398. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8399. SourceLocation Loc,
  8400. Sema &Sema) {
  8401. // C / C++ fields
  8402. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8403. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8404. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8405. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8406. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8407. }
  8408. // Objective-C instance variables
  8409. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8410. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8411. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8412. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8413. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8414. if (RL && RR && RL->getDecl() == RR->getDecl())
  8415. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8416. }
  8417. }
  8418. // C99 6.5.16.1
  8419. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8420. SourceLocation Loc,
  8421. QualType CompoundType) {
  8422. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8423. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8424. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8425. return QualType();
  8426. QualType LHSType = LHSExpr->getType();
  8427. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8428. CompoundType;
  8429. AssignConvertType ConvTy;
  8430. if (CompoundType.isNull()) {
  8431. Expr *RHSCheck = RHS.get();
  8432. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8433. QualType LHSTy(LHSType);
  8434. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8435. if (RHS.isInvalid())
  8436. return QualType();
  8437. // Special case of NSObject attributes on c-style pointer types.
  8438. if (ConvTy == IncompatiblePointer &&
  8439. ((Context.isObjCNSObjectType(LHSType) &&
  8440. RHSType->isObjCObjectPointerType()) ||
  8441. (Context.isObjCNSObjectType(RHSType) &&
  8442. LHSType->isObjCObjectPointerType())))
  8443. ConvTy = Compatible;
  8444. if (ConvTy == Compatible &&
  8445. LHSType->isObjCObjectType())
  8446. Diag(Loc, diag::err_objc_object_assignment)
  8447. << LHSType;
  8448. // If the RHS is a unary plus or minus, check to see if they = and + are
  8449. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8450. // instead of "x += 4".
  8451. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8452. RHSCheck = ICE->getSubExpr();
  8453. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8454. if ((UO->getOpcode() == UO_Plus ||
  8455. UO->getOpcode() == UO_Minus) &&
  8456. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8457. // Only if the two operators are exactly adjacent.
  8458. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8459. // And there is a space or other character before the subexpr of the
  8460. // unary +/-. We don't want to warn on "x=-1".
  8461. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8462. UO->getSubExpr()->getLocStart().isFileID()) {
  8463. Diag(Loc, diag::warn_not_compound_assign)
  8464. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8465. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8466. }
  8467. }
  8468. #if 0 // HLSL Change Starts
  8469. if (ConvTy == Compatible) {
  8470. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8471. // Warn about retain cycles where a block captures the LHS, but
  8472. // not if the LHS is a simple variable into which the block is
  8473. // being stored...unless that variable can be captured by reference!
  8474. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8475. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8476. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8477. checkRetainCycles(LHSExpr, RHS.get());
  8478. // It is safe to assign a weak reference into a strong variable.
  8479. // Although this code can still have problems:
  8480. // id x = self.weakProp;
  8481. // id y = self.weakProp;
  8482. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8483. // paths through the function. This should be revisited if
  8484. // -Wrepeated-use-of-weak is made flow-sensitive.
  8485. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8486. RHS.get()->getLocStart()))
  8487. getCurFunction()->markSafeWeakUse(RHS.get());
  8488. } else if (getLangOpts().ObjCAutoRefCount) {
  8489. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8490. }
  8491. }
  8492. #endif // HLSL Change Ends
  8493. } else {
  8494. // Compound assignment "x += y"
  8495. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8496. }
  8497. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8498. RHS.get(), AA_Assigning))
  8499. return QualType();
  8500. CheckForNullPointerDereference(*this, LHSExpr);
  8501. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8502. // left operand unless the left operand has qualified type, in which case
  8503. // it is the unqualified version of the type of the left operand.
  8504. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8505. // is converted to the type of the assignment expression (above).
  8506. // C++ 5.17p1: the type of the assignment expression is that of its left
  8507. // operand.
  8508. return (getLangOpts().CPlusPlus
  8509. ? LHSType : LHSType.getUnqualifiedType());
  8510. }
  8511. // C99 6.5.17
  8512. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8513. SourceLocation Loc) {
  8514. LHS = S.CheckPlaceholderExpr(LHS.get());
  8515. RHS = S.CheckPlaceholderExpr(RHS.get());
  8516. if (LHS.isInvalid() || RHS.isInvalid())
  8517. return QualType();
  8518. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8519. // operands, but not unary promotions.
  8520. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8521. // So we treat the LHS as a ignored value, and in C++ we allow the
  8522. // containing site to determine what should be done with the RHS.
  8523. LHS = S.IgnoredValueConversions(LHS.get());
  8524. if (LHS.isInvalid())
  8525. return QualType();
  8526. S.DiagnoseUnusedExprResult(LHS.get());
  8527. if (!S.getLangOpts().CPlusPlus) {
  8528. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8529. if (RHS.isInvalid())
  8530. return QualType();
  8531. if (!RHS.get()->getType()->isVoidType())
  8532. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8533. diag::err_incomplete_type);
  8534. }
  8535. return RHS.get()->getType();
  8536. }
  8537. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8538. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8539. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8540. ExprValueKind &VK,
  8541. ExprObjectKind &OK,
  8542. SourceLocation OpLoc,
  8543. bool IsInc, bool IsPrefix) {
  8544. if (Op->isTypeDependent())
  8545. return S.Context.DependentTy;
  8546. QualType ResType = Op->getType();
  8547. // Atomic types can be used for increment / decrement where the non-atomic
  8548. // versions can, so ignore the _Atomic() specifier for the purpose of
  8549. // checking.
  8550. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8551. ResType = ResAtomicType->getValueType();
  8552. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8553. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8554. // Decrement of bool is not allowed.
  8555. if (!IsInc) {
  8556. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8557. return QualType();
  8558. }
  8559. // Increment of bool sets it to true, but is deprecated.
  8560. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  8561. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8562. // Error on enum increments and decrements in C++ mode
  8563. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8564. return QualType();
  8565. } else if (ResType->isRealType()) {
  8566. // OK!
  8567. } else if (ResType->isPointerType()) {
  8568. // C99 6.5.2.4p2, 6.5.6p2
  8569. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8570. return QualType();
  8571. } else if (ResType->isObjCObjectPointerType()) {
  8572. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8573. // Otherwise, we just need a complete type.
  8574. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8575. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8576. return QualType();
  8577. } else if (ResType->isAnyComplexType()) {
  8578. // C99 does not support ++/-- on complex types, we allow as an extension.
  8579. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8580. << ResType << Op->getSourceRange();
  8581. } else if (ResType->isPlaceholderType()) {
  8582. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8583. if (PR.isInvalid()) return QualType();
  8584. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8585. IsInc, IsPrefix);
  8586. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8587. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8588. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8589. (ResType->getAs<VectorType>()->getVectorKind() !=
  8590. VectorType::AltiVecBool)) {
  8591. // The z vector extensions allow ++ and -- for non-bool vectors.
  8592. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8593. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8594. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8595. } else {
  8596. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8597. << ResType << int(IsInc) << Op->getSourceRange();
  8598. return QualType();
  8599. }
  8600. // At this point, we know we have a real, complex or pointer type.
  8601. // Now make sure the operand is a modifiable lvalue.
  8602. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8603. return QualType();
  8604. // In C++, a prefix increment is the same type as the operand. Otherwise
  8605. // (in C or with postfix), the increment is the unqualified type of the
  8606. // operand.
  8607. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8608. VK = VK_LValue;
  8609. OK = Op->getObjectKind();
  8610. return ResType;
  8611. } else {
  8612. VK = VK_RValue;
  8613. return ResType.getUnqualifiedType();
  8614. }
  8615. }
  8616. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8617. /// This routine allows us to typecheck complex/recursive expressions
  8618. /// where the declaration is needed for type checking. We only need to
  8619. /// handle cases when the expression references a function designator
  8620. /// or is an lvalue. Here are some examples:
  8621. /// - &(x) => x
  8622. /// - &*****f => f for f a function designator.
  8623. /// - &s.xx => s
  8624. /// - &s.zz[1].yy -> s, if zz is an array
  8625. /// - *(x + 1) -> x, if x is an array
  8626. /// - &"123"[2] -> 0
  8627. /// - & __real__ x -> x
  8628. static ValueDecl *getPrimaryDecl(Expr *E) {
  8629. switch (E->getStmtClass()) {
  8630. case Stmt::DeclRefExprClass:
  8631. return cast<DeclRefExpr>(E)->getDecl();
  8632. case Stmt::MemberExprClass:
  8633. // If this is an arrow operator, the address is an offset from
  8634. // the base's value, so the object the base refers to is
  8635. // irrelevant.
  8636. if (cast<MemberExpr>(E)->isArrow())
  8637. return nullptr;
  8638. // Otherwise, the expression refers to a part of the base
  8639. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8640. case Stmt::ArraySubscriptExprClass: {
  8641. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8642. // promotion of register arrays earlier.
  8643. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8644. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8645. if (ICE->getSubExpr()->getType()->isArrayType())
  8646. return getPrimaryDecl(ICE->getSubExpr());
  8647. }
  8648. return nullptr;
  8649. }
  8650. case Stmt::UnaryOperatorClass: {
  8651. UnaryOperator *UO = cast<UnaryOperator>(E);
  8652. switch(UO->getOpcode()) {
  8653. case UO_Real:
  8654. case UO_Imag:
  8655. case UO_Extension:
  8656. return getPrimaryDecl(UO->getSubExpr());
  8657. default:
  8658. return nullptr;
  8659. }
  8660. }
  8661. case Stmt::ParenExprClass:
  8662. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8663. case Stmt::ImplicitCastExprClass:
  8664. // If the result of an implicit cast is an l-value, we care about
  8665. // the sub-expression; otherwise, the result here doesn't matter.
  8666. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8667. default:
  8668. return nullptr;
  8669. }
  8670. }
  8671. namespace {
  8672. enum {
  8673. AO_Bit_Field = 0,
  8674. AO_Vector_Element = 1,
  8675. AO_Property_Expansion = 2,
  8676. AO_Register_Variable = 3,
  8677. AO_No_Error = 4
  8678. };
  8679. }
  8680. /// \brief Diagnose invalid operand for address of operations.
  8681. ///
  8682. /// \param Type The type of operand which cannot have its address taken.
  8683. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8684. Expr *E, unsigned Type) {
  8685. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8686. }
  8687. /// CheckAddressOfOperand - The operand of & must be either a function
  8688. /// designator or an lvalue designating an object. If it is an lvalue, the
  8689. /// object cannot be declared with storage class register or be a bit field.
  8690. /// Note: The usual conversions are *not* applied to the operand of the &
  8691. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8692. /// In C++, the operand might be an overloaded function name, in which case
  8693. /// we allow the '&' but retain the overloaded-function type.
  8694. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8695. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8696. if (PTy->getKind() == BuiltinType::Overload) {
  8697. Expr *E = OrigOp.get()->IgnoreParens();
  8698. if (!isa<OverloadExpr>(E)) {
  8699. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8700. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8701. << OrigOp.get()->getSourceRange();
  8702. return QualType();
  8703. }
  8704. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8705. if (isa<UnresolvedMemberExpr>(Ovl))
  8706. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8707. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8708. << OrigOp.get()->getSourceRange();
  8709. return QualType();
  8710. }
  8711. return Context.OverloadTy;
  8712. }
  8713. if (PTy->getKind() == BuiltinType::UnknownAny)
  8714. return Context.UnknownAnyTy;
  8715. if (PTy->getKind() == BuiltinType::BoundMember) {
  8716. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8717. << OrigOp.get()->getSourceRange();
  8718. return QualType();
  8719. }
  8720. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8721. if (OrigOp.isInvalid()) return QualType();
  8722. }
  8723. if (OrigOp.get()->isTypeDependent())
  8724. return Context.DependentTy;
  8725. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8726. // Make sure to ignore parentheses in subsequent checks
  8727. Expr *op = OrigOp.get()->IgnoreParens();
  8728. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8729. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8730. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8731. return QualType();
  8732. }
  8733. if (getLangOpts().C99) {
  8734. // Implement C99-only parts of addressof rules.
  8735. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8736. if (uOp->getOpcode() == UO_Deref)
  8737. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8738. // (assuming the deref expression is valid).
  8739. return uOp->getSubExpr()->getType();
  8740. }
  8741. // Technically, there should be a check for array subscript
  8742. // expressions here, but the result of one is always an lvalue anyway.
  8743. }
  8744. ValueDecl *dcl = getPrimaryDecl(op);
  8745. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8746. unsigned AddressOfError = AO_No_Error;
  8747. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8748. bool sfinae = (bool)isSFINAEContext();
  8749. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8750. : diag::ext_typecheck_addrof_temporary)
  8751. << op->getType() << op->getSourceRange();
  8752. if (sfinae)
  8753. return QualType();
  8754. // Materialize the temporary as an lvalue so that we can take its address.
  8755. OrigOp = op = new (Context)
  8756. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8757. } else if (isa<ObjCSelectorExpr>(op)) {
  8758. return Context.getPointerType(op->getType());
  8759. } else if (lval == Expr::LV_MemberFunction) {
  8760. // If it's an instance method, make a member pointer.
  8761. // The expression must have exactly the form &A::foo.
  8762. // If the underlying expression isn't a decl ref, give up.
  8763. if (!isa<DeclRefExpr>(op)) {
  8764. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8765. << OrigOp.get()->getSourceRange();
  8766. return QualType();
  8767. }
  8768. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8769. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8770. // The id-expression was parenthesized.
  8771. if (OrigOp.get() != DRE) {
  8772. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8773. << OrigOp.get()->getSourceRange();
  8774. // The method was named without a qualifier.
  8775. } else if (!DRE->getQualifier()) {
  8776. if (MD->getParent()->getName().empty())
  8777. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8778. << op->getSourceRange();
  8779. else {
  8780. SmallString<32> Str;
  8781. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8782. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8783. << op->getSourceRange()
  8784. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8785. }
  8786. }
  8787. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8788. if (isa<CXXDestructorDecl>(MD))
  8789. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8790. QualType MPTy = Context.getMemberPointerType(
  8791. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8792. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8793. RequireCompleteType(OpLoc, MPTy, 0);
  8794. return MPTy;
  8795. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8796. // C99 6.5.3.2p1
  8797. // The operand must be either an l-value or a function designator
  8798. if (!op->getType()->isFunctionType()) {
  8799. // Use a special diagnostic for loads from property references.
  8800. if (isa<PseudoObjectExpr>(op)) {
  8801. AddressOfError = AO_Property_Expansion;
  8802. } else {
  8803. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8804. << op->getType() << op->getSourceRange();
  8805. return QualType();
  8806. }
  8807. }
  8808. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8809. // The operand cannot be a bit-field
  8810. AddressOfError = AO_Bit_Field;
  8811. } else if (op->getObjectKind() == OK_VectorComponent) {
  8812. // The operand cannot be an element of a vector
  8813. AddressOfError = AO_Vector_Element;
  8814. } else if (dcl) { // C99 6.5.3.2p1
  8815. // We have an lvalue with a decl. Make sure the decl is not declared
  8816. // with the register storage-class specifier.
  8817. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8818. // in C++ it is not error to take address of a register
  8819. // variable (c++03 7.1.1P3)
  8820. if (vd->getStorageClass() == SC_Register &&
  8821. !getLangOpts().CPlusPlus) {
  8822. AddressOfError = AO_Register_Variable;
  8823. }
  8824. } else if (isa<MSPropertyDecl>(dcl)) {
  8825. AddressOfError = AO_Property_Expansion;
  8826. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8827. return Context.OverloadTy;
  8828. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8829. // Okay: we can take the address of a field.
  8830. // Could be a pointer to member, though, if there is an explicit
  8831. // scope qualifier for the class.
  8832. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8833. DeclContext *Ctx = dcl->getDeclContext();
  8834. if (Ctx && Ctx->isRecord()) {
  8835. if (dcl->getType()->isReferenceType()) {
  8836. Diag(OpLoc,
  8837. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8838. << dcl->getDeclName() << dcl->getType();
  8839. return QualType();
  8840. }
  8841. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8842. Ctx = Ctx->getParent();
  8843. QualType MPTy = Context.getMemberPointerType(
  8844. op->getType(),
  8845. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8846. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8847. RequireCompleteType(OpLoc, MPTy, 0);
  8848. return MPTy;
  8849. }
  8850. }
  8851. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8852. llvm_unreachable("Unknown/unexpected decl type");
  8853. }
  8854. if (AddressOfError != AO_No_Error) {
  8855. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8856. return QualType();
  8857. }
  8858. if (lval == Expr::LV_IncompleteVoidType) {
  8859. // Taking the address of a void variable is technically illegal, but we
  8860. // allow it in cases which are otherwise valid.
  8861. // Example: "extern void x; void* y = &x;".
  8862. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8863. }
  8864. // If the operand has type "type", the result has type "pointer to type".
  8865. if (op->getType()->isObjCObjectType())
  8866. return Context.getObjCObjectPointerType(op->getType());
  8867. return Context.getPointerType(op->getType());
  8868. }
  8869. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8870. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8871. if (!DRE)
  8872. return;
  8873. const Decl *D = DRE->getDecl();
  8874. if (!D)
  8875. return;
  8876. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8877. if (!Param)
  8878. return;
  8879. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8880. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8881. return;
  8882. if (FunctionScopeInfo *FD = S.getCurFunction())
  8883. if (!FD->ModifiedNonNullParams.count(Param))
  8884. FD->ModifiedNonNullParams.insert(Param);
  8885. }
  8886. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8887. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8888. SourceLocation OpLoc) {
  8889. if (Op->isTypeDependent())
  8890. return S.Context.DependentTy;
  8891. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8892. if (ConvResult.isInvalid())
  8893. return QualType();
  8894. Op = ConvResult.get();
  8895. QualType OpTy = Op->getType();
  8896. QualType Result;
  8897. if (isa<CXXReinterpretCastExpr>(Op)) {
  8898. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8899. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8900. Op->getSourceRange());
  8901. }
  8902. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8903. Result = PT->getPointeeType();
  8904. else if (const ObjCObjectPointerType *OPT =
  8905. OpTy->getAs<ObjCObjectPointerType>())
  8906. Result = OPT->getPointeeType();
  8907. else {
  8908. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8909. if (PR.isInvalid()) return QualType();
  8910. if (PR.get() != Op)
  8911. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8912. }
  8913. if (Result.isNull()) {
  8914. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8915. << OpTy << Op->getSourceRange();
  8916. return QualType();
  8917. }
  8918. // Note that per both C89 and C99, indirection is always legal, even if Result
  8919. // is an incomplete type or void. It would be possible to warn about
  8920. // dereferencing a void pointer, but it's completely well-defined, and such a
  8921. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8922. // for pointers to 'void' but is fine for any other pointer type:
  8923. //
  8924. // C++ [expr.unary.op]p1:
  8925. // [...] the expression to which [the unary * operator] is applied shall
  8926. // be a pointer to an object type, or a pointer to a function type
  8927. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8928. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8929. << OpTy << Op->getSourceRange();
  8930. // Dereferences are usually l-values...
  8931. VK = VK_LValue;
  8932. // ...except that certain expressions are never l-values in C.
  8933. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8934. VK = VK_RValue;
  8935. return Result;
  8936. }
  8937. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8938. BinaryOperatorKind Opc;
  8939. switch (Kind) {
  8940. default: llvm_unreachable("Unknown binop!");
  8941. case tok::periodstar: Opc = BO_PtrMemD; break;
  8942. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8943. case tok::star: Opc = BO_Mul; break;
  8944. case tok::slash: Opc = BO_Div; break;
  8945. case tok::percent: Opc = BO_Rem; break;
  8946. case tok::plus: Opc = BO_Add; break;
  8947. case tok::minus: Opc = BO_Sub; break;
  8948. case tok::lessless: Opc = BO_Shl; break;
  8949. case tok::greatergreater: Opc = BO_Shr; break;
  8950. case tok::lessequal: Opc = BO_LE; break;
  8951. case tok::less: Opc = BO_LT; break;
  8952. case tok::greaterequal: Opc = BO_GE; break;
  8953. case tok::greater: Opc = BO_GT; break;
  8954. case tok::exclaimequal: Opc = BO_NE; break;
  8955. case tok::equalequal: Opc = BO_EQ; break;
  8956. case tok::amp: Opc = BO_And; break;
  8957. case tok::caret: Opc = BO_Xor; break;
  8958. case tok::pipe: Opc = BO_Or; break;
  8959. case tok::ampamp: Opc = BO_LAnd; break;
  8960. case tok::pipepipe: Opc = BO_LOr; break;
  8961. case tok::equal: Opc = BO_Assign; break;
  8962. case tok::starequal: Opc = BO_MulAssign; break;
  8963. case tok::slashequal: Opc = BO_DivAssign; break;
  8964. case tok::percentequal: Opc = BO_RemAssign; break;
  8965. case tok::plusequal: Opc = BO_AddAssign; break;
  8966. case tok::minusequal: Opc = BO_SubAssign; break;
  8967. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8968. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8969. case tok::ampequal: Opc = BO_AndAssign; break;
  8970. case tok::caretequal: Opc = BO_XorAssign; break;
  8971. case tok::pipeequal: Opc = BO_OrAssign; break;
  8972. case tok::comma: Opc = BO_Comma; break;
  8973. }
  8974. return Opc;
  8975. }
  8976. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8977. tok::TokenKind Kind) {
  8978. UnaryOperatorKind Opc;
  8979. switch (Kind) {
  8980. default: llvm_unreachable("Unknown unary op!");
  8981. case tok::plusplus: Opc = UO_PreInc; break;
  8982. case tok::minusminus: Opc = UO_PreDec; break;
  8983. case tok::amp: Opc = UO_AddrOf; break;
  8984. case tok::star: Opc = UO_Deref; break;
  8985. case tok::plus: Opc = UO_Plus; break;
  8986. case tok::minus: Opc = UO_Minus; break;
  8987. case tok::tilde: Opc = UO_Not; break;
  8988. case tok::exclaim: Opc = UO_LNot; break;
  8989. case tok::kw___real: Opc = UO_Real; break;
  8990. case tok::kw___imag: Opc = UO_Imag; break;
  8991. case tok::kw___extension__: Opc = UO_Extension; break;
  8992. }
  8993. return Opc;
  8994. }
  8995. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8996. /// This warning is only emitted for builtin assignment operations. It is also
  8997. /// suppressed in the event of macro expansions.
  8998. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8999. SourceLocation OpLoc) {
  9000. if (!S.ActiveTemplateInstantiations.empty())
  9001. return;
  9002. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  9003. return;
  9004. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  9005. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  9006. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  9007. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  9008. if (!LHSDeclRef || !RHSDeclRef ||
  9009. LHSDeclRef->getLocation().isMacroID() ||
  9010. RHSDeclRef->getLocation().isMacroID())
  9011. return;
  9012. const ValueDecl *LHSDecl =
  9013. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  9014. const ValueDecl *RHSDecl =
  9015. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  9016. if (LHSDecl != RHSDecl)
  9017. return;
  9018. if (LHSDecl->getType().isVolatileQualified())
  9019. return;
  9020. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  9021. if (RefTy->getPointeeType().isVolatileQualified())
  9022. return;
  9023. S.Diag(OpLoc, diag::warn_self_assignment)
  9024. << LHSDeclRef->getType()
  9025. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  9026. }
  9027. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  9028. /// is usually indicative of introspection within the Objective-C pointer.
  9029. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  9030. SourceLocation OpLoc) {
  9031. if (!S.getLangOpts().ObjC1)
  9032. return;
  9033. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  9034. const Expr *LHS = L.get();
  9035. const Expr *RHS = R.get();
  9036. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  9037. ObjCPointerExpr = LHS;
  9038. OtherExpr = RHS;
  9039. }
  9040. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  9041. ObjCPointerExpr = RHS;
  9042. OtherExpr = LHS;
  9043. }
  9044. // This warning is deliberately made very specific to reduce false
  9045. // positives with logic that uses '&' for hashing. This logic mainly
  9046. // looks for code trying to introspect into tagged pointers, which
  9047. // code should generally never do.
  9048. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  9049. unsigned Diag = diag::warn_objc_pointer_masking;
  9050. // Determine if we are introspecting the result of performSelectorXXX.
  9051. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  9052. // Special case messages to -performSelector and friends, which
  9053. // can return non-pointer values boxed in a pointer value.
  9054. // Some clients may wish to silence warnings in this subcase.
  9055. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  9056. Selector S = ME->getSelector();
  9057. StringRef SelArg0 = S.getNameForSlot(0);
  9058. if (SelArg0.startswith("performSelector"))
  9059. Diag = diag::warn_objc_pointer_masking_performSelector;
  9060. }
  9061. S.Diag(OpLoc, Diag)
  9062. << ObjCPointerExpr->getSourceRange();
  9063. }
  9064. }
  9065. static NamedDecl *getDeclFromExpr(Expr *E) {
  9066. if (!E)
  9067. return nullptr;
  9068. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  9069. return DRE->getDecl();
  9070. if (auto *ME = dyn_cast<MemberExpr>(E))
  9071. return ME->getMemberDecl();
  9072. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  9073. return IRE->getDecl();
  9074. return nullptr;
  9075. }
  9076. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  9077. /// operator @p Opc at location @c TokLoc. This routine only supports
  9078. /// built-in operations; ActOnBinOp handles overloaded operators.
  9079. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  9080. BinaryOperatorKind Opc,
  9081. Expr *LHSExpr, Expr *RHSExpr) {
  9082. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  9083. // The syntax only allows initializer lists on the RHS of assignment,
  9084. // so we don't need to worry about accepting invalid code for
  9085. // non-assignment operators.
  9086. // C++11 5.17p9:
  9087. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  9088. // of x = {} is x = T().
  9089. InitializationKind Kind =
  9090. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  9091. InitializedEntity Entity =
  9092. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  9093. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  9094. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  9095. if (Init.isInvalid())
  9096. return Init;
  9097. RHSExpr = Init.get();
  9098. }
  9099. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  9100. QualType ResultTy; // Result type of the binary operator.
  9101. // The following two variables are used for compound assignment operators
  9102. QualType CompLHSTy; // Type of LHS after promotions for computation
  9103. QualType CompResultTy; // Type of computation result
  9104. ExprValueKind VK = VK_RValue;
  9105. ExprObjectKind OK = OK_Ordinary;
  9106. // HLSL Change Starts
  9107. // Handle HLSL binary operands differently
  9108. if (getLangOpts().HLSL) {
  9109. hlsl::CheckBinOpForHLSL(*this, OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  9110. if (!ResultTy.isNull() && Opc == BO_Comma) {
  9111. // In C/C++, the RHS value kind should propagate. In HLSL, it should yield an r-value.
  9112. // VK = RHS.get()->getValueKind();
  9113. OK = RHS.get()->getObjectKind();
  9114. }
  9115. goto CasesHandled;
  9116. }
  9117. // HLSL Change Ends
  9118. if (!getLangOpts().CPlusPlus) {
  9119. // C cannot handle TypoExpr nodes on either side of a binop because it
  9120. // doesn't handle dependent types properly, so make sure any TypoExprs have
  9121. // been dealt with before checking the operands.
  9122. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  9123. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  9124. if (Opc != BO_Assign)
  9125. return ExprResult(E);
  9126. // Avoid correcting the RHS to the same Expr as the LHS.
  9127. Decl *D = getDeclFromExpr(E);
  9128. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  9129. });
  9130. if (!LHS.isUsable() || !RHS.isUsable())
  9131. return ExprError();
  9132. }
  9133. switch (Opc) {
  9134. case BO_Assign:
  9135. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  9136. if (getLangOpts().CPlusPlus &&
  9137. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  9138. VK = LHS.get()->getValueKind();
  9139. OK = LHS.get()->getObjectKind();
  9140. }
  9141. if (!ResultTy.isNull()) {
  9142. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9143. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  9144. }
  9145. RecordModifiableNonNullParam(*this, LHS.get());
  9146. break;
  9147. case BO_PtrMemD:
  9148. case BO_PtrMemI:
  9149. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  9150. Opc == BO_PtrMemI);
  9151. break;
  9152. case BO_Mul:
  9153. case BO_Div:
  9154. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  9155. Opc == BO_Div);
  9156. break;
  9157. case BO_Rem:
  9158. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  9159. break;
  9160. case BO_Add:
  9161. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  9162. break;
  9163. case BO_Sub:
  9164. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  9165. break;
  9166. case BO_Shl:
  9167. case BO_Shr:
  9168. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  9169. break;
  9170. case BO_LE:
  9171. case BO_LT:
  9172. case BO_GE:
  9173. case BO_GT:
  9174. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  9175. break;
  9176. case BO_EQ:
  9177. case BO_NE:
  9178. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  9179. break;
  9180. case BO_And:
  9181. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  9182. case BO_Xor:
  9183. case BO_Or:
  9184. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  9185. break;
  9186. case BO_LAnd:
  9187. case BO_LOr:
  9188. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  9189. break;
  9190. case BO_MulAssign:
  9191. case BO_DivAssign:
  9192. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  9193. Opc == BO_DivAssign);
  9194. CompLHSTy = CompResultTy;
  9195. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9196. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9197. break;
  9198. case BO_RemAssign:
  9199. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  9200. CompLHSTy = CompResultTy;
  9201. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9202. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9203. break;
  9204. case BO_AddAssign:
  9205. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  9206. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9207. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9208. break;
  9209. case BO_SubAssign:
  9210. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  9211. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9212. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9213. break;
  9214. case BO_ShlAssign:
  9215. case BO_ShrAssign:
  9216. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  9217. CompLHSTy = CompResultTy;
  9218. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9219. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9220. break;
  9221. case BO_AndAssign:
  9222. case BO_OrAssign: // fallthrough
  9223. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9224. case BO_XorAssign:
  9225. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  9226. CompLHSTy = CompResultTy;
  9227. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9228. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9229. break;
  9230. case BO_Comma:
  9231. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  9232. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  9233. VK = RHS.get()->getValueKind();
  9234. OK = RHS.get()->getObjectKind();
  9235. }
  9236. break;
  9237. }
  9238. CasesHandled: // HLSL Change: minimize code changes by avoiding a branch above
  9239. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  9240. return ExprError();
  9241. // Check for array bounds violations for both sides of the BinaryOperator
  9242. CheckArrayAccess(LHS.get());
  9243. CheckArrayAccess(RHS.get());
  9244. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  9245. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  9246. &Context.Idents.get("object_setClass"),
  9247. SourceLocation(), LookupOrdinaryName);
  9248. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  9249. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  9250. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  9251. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  9252. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  9253. FixItHint::CreateInsertion(RHSLocEnd, ")");
  9254. }
  9255. else
  9256. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9257. }
  9258. else if (const ObjCIvarRefExpr *OIRE =
  9259. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9260. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9261. if (CompResultTy.isNull())
  9262. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9263. OK, OpLoc, FPFeatures.fp_contract);
  9264. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9265. OK_ObjCProperty) {
  9266. VK = VK_LValue;
  9267. OK = LHS.get()->getObjectKind();
  9268. }
  9269. return new (Context) CompoundAssignOperator(
  9270. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9271. OpLoc, FPFeatures.fp_contract);
  9272. }
  9273. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9274. /// operators are mixed in a way that suggests that the programmer forgot that
  9275. /// comparison operators have higher precedence. The most typical example of
  9276. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9277. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9278. SourceLocation OpLoc, Expr *LHSExpr,
  9279. Expr *RHSExpr) {
  9280. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9281. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9282. // Check that one of the sides is a comparison operator.
  9283. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9284. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9285. if (!isLeftComp && !isRightComp)
  9286. return;
  9287. // Bitwise operations are sometimes used as eager logical ops.
  9288. // Don't diagnose this.
  9289. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9290. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9291. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9292. return;
  9293. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9294. OpLoc)
  9295. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9296. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9297. SourceRange ParensRange = isLeftComp ?
  9298. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9299. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9300. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9301. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9302. SuggestParentheses(Self, OpLoc,
  9303. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9304. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9305. SuggestParentheses(Self, OpLoc,
  9306. Self.PDiag(diag::note_precedence_bitwise_first)
  9307. << BinaryOperator::getOpcodeStr(Opc),
  9308. ParensRange);
  9309. }
  9310. /// \brief It accepts a '&' expr that is inside a '|' one.
  9311. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9312. /// in parentheses.
  9313. static void
  9314. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9315. BinaryOperator *Bop) {
  9316. assert(Bop->getOpcode() == BO_And);
  9317. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9318. << Bop->getSourceRange() << OpLoc;
  9319. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9320. Self.PDiag(diag::note_precedence_silence)
  9321. << Bop->getOpcodeStr(),
  9322. Bop->getSourceRange());
  9323. }
  9324. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9325. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9326. /// in parentheses.
  9327. static void
  9328. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9329. BinaryOperator *Bop) {
  9330. assert(Bop->getOpcode() == BO_LAnd);
  9331. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9332. << Bop->getSourceRange() << OpLoc;
  9333. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9334. Self.PDiag(diag::note_precedence_silence)
  9335. << Bop->getOpcodeStr(),
  9336. Bop->getSourceRange());
  9337. }
  9338. /// \brief Returns true if the given expression can be evaluated as a constant
  9339. /// 'true'.
  9340. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9341. bool Res;
  9342. return !E->isValueDependent() &&
  9343. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9344. }
  9345. /// \brief Returns true if the given expression can be evaluated as a constant
  9346. /// 'false'.
  9347. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9348. bool Res;
  9349. return !E->isValueDependent() &&
  9350. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9351. }
  9352. /// \brief Look for '&&' in the left hand of a '||' expr.
  9353. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9354. Expr *LHSExpr, Expr *RHSExpr) {
  9355. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9356. if (Bop->getOpcode() == BO_LAnd) {
  9357. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9358. if (EvaluatesAsFalse(S, RHSExpr))
  9359. return;
  9360. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9361. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9362. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9363. } else if (Bop->getOpcode() == BO_LOr) {
  9364. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9365. // If it's "a || b && 1 || c" we didn't warn earlier for
  9366. // "a || b && 1", but warn now.
  9367. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9368. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9369. }
  9370. }
  9371. }
  9372. }
  9373. /// \brief Look for '&&' in the right hand of a '||' expr.
  9374. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9375. Expr *LHSExpr, Expr *RHSExpr) {
  9376. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9377. if (Bop->getOpcode() == BO_LAnd) {
  9378. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9379. if (EvaluatesAsFalse(S, LHSExpr))
  9380. return;
  9381. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9382. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9383. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9384. }
  9385. }
  9386. }
  9387. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9388. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9389. Expr *OrArg) {
  9390. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9391. if (Bop->getOpcode() == BO_And)
  9392. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9393. }
  9394. }
  9395. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9396. Expr *SubExpr, StringRef Shift) {
  9397. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9398. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9399. StringRef Op = Bop->getOpcodeStr();
  9400. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9401. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9402. SuggestParentheses(S, Bop->getOperatorLoc(),
  9403. S.PDiag(diag::note_precedence_silence) << Op,
  9404. Bop->getSourceRange());
  9405. }
  9406. }
  9407. }
  9408. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9409. Expr *LHSExpr, Expr *RHSExpr) {
  9410. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9411. if (!OCE)
  9412. return;
  9413. FunctionDecl *FD = OCE->getDirectCallee();
  9414. if (!FD || !FD->isOverloadedOperator())
  9415. return;
  9416. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9417. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9418. return;
  9419. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9420. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9421. << (Kind == OO_LessLess);
  9422. SuggestParentheses(S, OCE->getOperatorLoc(),
  9423. S.PDiag(diag::note_precedence_silence)
  9424. << (Kind == OO_LessLess ? "<<" : ">>"),
  9425. OCE->getSourceRange());
  9426. SuggestParentheses(S, OpLoc,
  9427. S.PDiag(diag::note_evaluate_comparison_first),
  9428. SourceRange(OCE->getArg(1)->getLocStart(),
  9429. RHSExpr->getLocEnd()));
  9430. }
  9431. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9432. /// precedence.
  9433. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9434. SourceLocation OpLoc, Expr *LHSExpr,
  9435. Expr *RHSExpr){
  9436. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9437. if (BinaryOperator::isBitwiseOp(Opc))
  9438. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9439. // Diagnose "arg1 & arg2 | arg3"
  9440. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9441. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9442. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9443. }
  9444. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9445. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9446. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9447. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9448. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9449. }
  9450. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9451. || Opc == BO_Shr) {
  9452. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9453. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9454. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9455. }
  9456. // Warn on overloaded shift operators and comparisons, such as:
  9457. // cout << 5 == 4;
  9458. if (BinaryOperator::isComparisonOp(Opc))
  9459. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9460. }
  9461. // Binary Operators. 'Tok' is the token for the operator.
  9462. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9463. tok::TokenKind Kind,
  9464. Expr *LHSExpr, Expr *RHSExpr) {
  9465. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9466. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9467. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9468. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9469. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9470. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9471. }
  9472. /// Build an overloaded binary operator expression in the given scope.
  9473. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9474. BinaryOperatorKind Opc,
  9475. Expr *LHS, Expr *RHS) {
  9476. // Find all of the overloaded operators visible from this
  9477. // point. We perform both an operator-name lookup from the local
  9478. // scope and an argument-dependent lookup based on the types of
  9479. // the arguments.
  9480. UnresolvedSet<16> Functions;
  9481. OverloadedOperatorKind OverOp
  9482. = BinaryOperator::getOverloadedOperator(Opc);
  9483. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9484. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9485. RHS->getType(), Functions);
  9486. // Build the (potentially-overloaded, potentially-dependent)
  9487. // binary operation.
  9488. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9489. }
  9490. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9491. BinaryOperatorKind Opc,
  9492. Expr *LHSExpr, Expr *RHSExpr) {
  9493. // We want to end up calling one of checkPseudoObjectAssignment
  9494. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9495. // both expressions are overloadable or either is type-dependent),
  9496. // or CreateBuiltinBinOp (in any other case). We also want to get
  9497. // any placeholder types out of the way.
  9498. // Handle pseudo-objects in the LHS.
  9499. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9500. // Assignments with a pseudo-object l-value need special analysis.
  9501. if (pty->getKind() == BuiltinType::PseudoObject &&
  9502. BinaryOperator::isAssignmentOp(Opc))
  9503. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9504. // Don't resolve overloads if the other type is overloadable.
  9505. if (pty->getKind() == BuiltinType::Overload) {
  9506. // We can't actually test that if we still have a placeholder,
  9507. // though. Fortunately, none of the exceptions we see in that
  9508. // code below are valid when the LHS is an overload set. Note
  9509. // that an overload set can be dependently-typed, but it never
  9510. // instantiates to having an overloadable type.
  9511. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9512. if (resolvedRHS.isInvalid()) return ExprError();
  9513. RHSExpr = resolvedRHS.get();
  9514. if (RHSExpr->isTypeDependent() ||
  9515. RHSExpr->getType()->isOverloadableType())
  9516. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9517. }
  9518. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9519. if (LHS.isInvalid()) return ExprError();
  9520. LHSExpr = LHS.get();
  9521. }
  9522. // Handle pseudo-objects in the RHS.
  9523. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9524. // An overload in the RHS can potentially be resolved by the type
  9525. // being assigned to.
  9526. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9527. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9528. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9529. if (LHSExpr->getType()->isOverloadableType())
  9530. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9531. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9532. }
  9533. // Don't resolve overloads if the other type is overloadable.
  9534. if (pty->getKind() == BuiltinType::Overload &&
  9535. LHSExpr->getType()->isOverloadableType())
  9536. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9537. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9538. if (!resolvedRHS.isUsable()) return ExprError();
  9539. RHSExpr = resolvedRHS.get();
  9540. }
  9541. // HLSL Change: bypass binary operator overload work, which isn't supported in any case;
  9542. // otherwise more extensive changes need to be done to add HLSL-specific behavior to
  9543. // be considered when building overload candidate sets
  9544. if (getLangOpts().CPlusPlus && !getLangOpts().HLSL) {
  9545. // If either expression is type-dependent, always build an
  9546. // overloaded op.
  9547. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9548. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9549. // Otherwise, build an overloaded op if either expression has an
  9550. // overloadable type.
  9551. if (LHSExpr->getType()->isOverloadableType() ||
  9552. RHSExpr->getType()->isOverloadableType())
  9553. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9554. }
  9555. // Build a built-in binary operation.
  9556. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9557. }
  9558. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9559. UnaryOperatorKind Opc,
  9560. Expr *InputExpr) {
  9561. ExprResult Input = InputExpr;
  9562. ExprValueKind VK = VK_RValue;
  9563. ExprObjectKind OK = OK_Ordinary;
  9564. QualType resultType;
  9565. // HLSL Change Starts
  9566. if (getLangOpts().HLSL) {
  9567. resultType = hlsl::CheckUnaryOpForHLSL(*this, OpLoc, Opc, Input, VK, OK);
  9568. goto CasesHandled;
  9569. }
  9570. // HLSL Change Ends
  9571. switch (Opc) {
  9572. case UO_PreInc:
  9573. case UO_PreDec:
  9574. case UO_PostInc:
  9575. case UO_PostDec:
  9576. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9577. OpLoc,
  9578. Opc == UO_PreInc ||
  9579. Opc == UO_PostInc,
  9580. Opc == UO_PreInc ||
  9581. Opc == UO_PreDec);
  9582. break;
  9583. case UO_AddrOf:
  9584. resultType = CheckAddressOfOperand(Input, OpLoc);
  9585. RecordModifiableNonNullParam(*this, InputExpr);
  9586. break;
  9587. case UO_Deref: {
  9588. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9589. if (Input.isInvalid()) return ExprError();
  9590. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9591. break;
  9592. }
  9593. case UO_Plus:
  9594. case UO_Minus:
  9595. Input = UsualUnaryConversions(Input.get());
  9596. if (Input.isInvalid()) return ExprError();
  9597. resultType = Input.get()->getType();
  9598. if (resultType->isDependentType())
  9599. break;
  9600. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9601. break;
  9602. else if (resultType->isVectorType() &&
  9603. // The z vector extensions don't allow + or - with bool vectors.
  9604. (!Context.getLangOpts().ZVector ||
  9605. resultType->getAs<VectorType>()->getVectorKind() !=
  9606. VectorType::AltiVecBool))
  9607. break;
  9608. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9609. Opc == UO_Plus &&
  9610. resultType->isPointerType())
  9611. break;
  9612. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9613. << resultType << Input.get()->getSourceRange());
  9614. case UO_Not: // bitwise complement
  9615. Input = UsualUnaryConversions(Input.get());
  9616. if (Input.isInvalid())
  9617. return ExprError();
  9618. resultType = Input.get()->getType();
  9619. if (resultType->isDependentType())
  9620. break;
  9621. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9622. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9623. // C99 does not support '~' for complex conjugation.
  9624. Diag(OpLoc, diag::ext_integer_complement_complex)
  9625. << resultType << Input.get()->getSourceRange();
  9626. else if (resultType->hasIntegerRepresentation())
  9627. break;
  9628. else if (resultType->isExtVectorType()) {
  9629. if (Context.getLangOpts().OpenCL) {
  9630. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9631. // on vector float types.
  9632. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9633. if (!T->isIntegerType())
  9634. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9635. << resultType << Input.get()->getSourceRange());
  9636. }
  9637. break;
  9638. } else {
  9639. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9640. << resultType << Input.get()->getSourceRange());
  9641. }
  9642. break;
  9643. case UO_LNot: // logical negation
  9644. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9645. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9646. if (Input.isInvalid()) return ExprError();
  9647. resultType = Input.get()->getType();
  9648. // Though we still have to promote half FP to float...
  9649. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9650. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9651. resultType = Context.FloatTy;
  9652. }
  9653. if (resultType->isDependentType())
  9654. break;
  9655. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9656. // C99 6.5.3.3p1: ok, fallthrough;
  9657. if (Context.getLangOpts().CPlusPlus) {
  9658. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9659. // operand contextually converted to bool.
  9660. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9661. ScalarTypeToBooleanCastKind(resultType));
  9662. } else if (Context.getLangOpts().OpenCL &&
  9663. Context.getLangOpts().OpenCLVersion < 120) {
  9664. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9665. // operate on scalar float types.
  9666. if (!resultType->isIntegerType())
  9667. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9668. << resultType << Input.get()->getSourceRange());
  9669. }
  9670. } else if (resultType->isExtVectorType()) {
  9671. if (Context.getLangOpts().OpenCL &&
  9672. Context.getLangOpts().OpenCLVersion < 120) {
  9673. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9674. // operate on vector float types.
  9675. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9676. if (!T->isIntegerType())
  9677. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9678. << resultType << Input.get()->getSourceRange());
  9679. }
  9680. // Vector logical not returns the signed variant of the operand type.
  9681. resultType = GetSignedVectorType(resultType);
  9682. break;
  9683. } else {
  9684. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9685. << resultType << Input.get()->getSourceRange());
  9686. }
  9687. // LNot always has type int. C99 6.5.3.3p5.
  9688. // In C++, it's bool. C++ 5.3.1p8
  9689. resultType = Context.getLogicalOperationType();
  9690. break;
  9691. case UO_Real:
  9692. case UO_Imag:
  9693. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9694. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9695. // complex l-values to ordinary l-values and all other values to r-values.
  9696. if (Input.isInvalid()) return ExprError();
  9697. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9698. if (Input.get()->getValueKind() != VK_RValue &&
  9699. Input.get()->getObjectKind() == OK_Ordinary)
  9700. VK = Input.get()->getValueKind();
  9701. } else if (!getLangOpts().CPlusPlus) {
  9702. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9703. Input = DefaultLvalueConversion(Input.get());
  9704. }
  9705. break;
  9706. case UO_Extension:
  9707. resultType = Input.get()->getType();
  9708. VK = Input.get()->getValueKind();
  9709. OK = Input.get()->getObjectKind();
  9710. break;
  9711. }
  9712. CasesHandled: // HLSL Change: add label to skip C/C++ unary operator processing
  9713. if (resultType.isNull() || Input.isInvalid())
  9714. return ExprError();
  9715. // Check for array bounds violations in the operand of the UnaryOperator,
  9716. // except for the '*' and '&' operators that have to be handled specially
  9717. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9718. // that are explicitly defined as valid by the standard).
  9719. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9720. CheckArrayAccess(Input.get());
  9721. return new (Context)
  9722. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9723. }
  9724. /// \brief Determine whether the given expression is a qualified member
  9725. /// access expression, of a form that could be turned into a pointer to member
  9726. /// with the address-of operator.
  9727. static bool isQualifiedMemberAccess(Expr *E) {
  9728. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9729. if (!DRE->getQualifier())
  9730. return false;
  9731. ValueDecl *VD = DRE->getDecl();
  9732. if (!VD->isCXXClassMember())
  9733. return false;
  9734. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9735. return true;
  9736. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9737. return Method->isInstance();
  9738. return false;
  9739. }
  9740. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9741. if (!ULE->getQualifier())
  9742. return false;
  9743. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9744. DEnd = ULE->decls_end();
  9745. D != DEnd; ++D) {
  9746. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9747. if (Method->isInstance())
  9748. return true;
  9749. } else {
  9750. // Overload set does not contain methods.
  9751. break;
  9752. }
  9753. }
  9754. return false;
  9755. }
  9756. return false;
  9757. }
  9758. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9759. UnaryOperatorKind Opc, Expr *Input) {
  9760. // HLSL Change Starts - placeholders and overloaded operators not supported
  9761. if (getLangOpts().HLSL)
  9762. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9763. // HLSL Change Ends
  9764. // First things first: handle placeholders so that the
  9765. // overloaded-operator check considers the right type.
  9766. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9767. // Increment and decrement of pseudo-object references.
  9768. if (pty->getKind() == BuiltinType::PseudoObject &&
  9769. UnaryOperator::isIncrementDecrementOp(Opc))
  9770. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9771. // extension is always a builtin operator.
  9772. if (Opc == UO_Extension)
  9773. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9774. // & gets special logic for several kinds of placeholder.
  9775. // The builtin code knows what to do.
  9776. if (Opc == UO_AddrOf &&
  9777. (pty->getKind() == BuiltinType::Overload ||
  9778. pty->getKind() == BuiltinType::UnknownAny ||
  9779. pty->getKind() == BuiltinType::BoundMember))
  9780. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9781. // Anything else needs to be handled now.
  9782. ExprResult Result = CheckPlaceholderExpr(Input);
  9783. if (Result.isInvalid()) return ExprError();
  9784. Input = Result.get();
  9785. }
  9786. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9787. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9788. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9789. // Find all of the overloaded operators visible from this
  9790. // point. We perform both an operator-name lookup from the local
  9791. // scope and an argument-dependent lookup based on the types of
  9792. // the arguments.
  9793. UnresolvedSet<16> Functions;
  9794. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9795. if (S && OverOp != OO_None)
  9796. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9797. Functions);
  9798. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9799. }
  9800. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9801. }
  9802. // Unary Operators. 'Tok' is the token for the operator.
  9803. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9804. tok::TokenKind Op, Expr *Input) {
  9805. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9806. }
  9807. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9808. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9809. LabelDecl *TheDecl) {
  9810. TheDecl->markUsed(Context);
  9811. // Create the AST node. The address of a label always has type 'void*'.
  9812. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9813. Context.getPointerType(Context.VoidTy));
  9814. }
  9815. /// Given the last statement in a statement-expression, check whether
  9816. /// the result is a producing expression (like a call to an
  9817. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9818. /// release out of the full-expression. Otherwise, return null.
  9819. /// Cannot fail.
  9820. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9821. // Should always be wrapped with one of these.
  9822. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9823. if (!cleanups) return nullptr;
  9824. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9825. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9826. return nullptr;
  9827. // Splice out the cast. This shouldn't modify any interesting
  9828. // features of the statement.
  9829. Expr *producer = cast->getSubExpr();
  9830. assert(producer->getType() == cast->getType());
  9831. assert(producer->getValueKind() == cast->getValueKind());
  9832. cleanups->setSubExpr(producer);
  9833. return cleanups;
  9834. }
  9835. void Sema::ActOnStartStmtExpr() {
  9836. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9837. }
  9838. void Sema::ActOnStmtExprError() {
  9839. // Note that function is also called by TreeTransform when leaving a
  9840. // StmtExpr scope without rebuilding anything.
  9841. DiscardCleanupsInEvaluationContext();
  9842. PopExpressionEvaluationContext();
  9843. }
  9844. ExprResult
  9845. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9846. SourceLocation RPLoc) { // "({..})"
  9847. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9848. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9849. if (hasAnyUnrecoverableErrorsInThisFunction())
  9850. DiscardCleanupsInEvaluationContext();
  9851. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9852. PopExpressionEvaluationContext();
  9853. // FIXME: there are a variety of strange constraints to enforce here, for
  9854. // example, it is not possible to goto into a stmt expression apparently.
  9855. // More semantic analysis is needed.
  9856. // If there are sub-stmts in the compound stmt, take the type of the last one
  9857. // as the type of the stmtexpr.
  9858. QualType Ty = Context.VoidTy;
  9859. bool StmtExprMayBindToTemp = false;
  9860. if (!Compound->body_empty()) {
  9861. Stmt *LastStmt = Compound->body_back();
  9862. LabelStmt *LastLabelStmt = nullptr;
  9863. // If LastStmt is a label, skip down through into the body.
  9864. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9865. LastLabelStmt = Label;
  9866. LastStmt = Label->getSubStmt();
  9867. }
  9868. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9869. // Do function/array conversion on the last expression, but not
  9870. // lvalue-to-rvalue. However, initialize an unqualified type.
  9871. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9872. if (LastExpr.isInvalid())
  9873. return ExprError();
  9874. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9875. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9876. // In ARC, if the final expression ends in a consume, splice
  9877. // the consume out and bind it later. In the alternate case
  9878. // (when dealing with a retainable type), the result
  9879. // initialization will create a produce. In both cases the
  9880. // result will be +1, and we'll need to balance that out with
  9881. // a bind.
  9882. if (Expr *rebuiltLastStmt
  9883. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9884. LastExpr = rebuiltLastStmt;
  9885. } else {
  9886. LastExpr = PerformCopyInitialization(
  9887. InitializedEntity::InitializeResult(LPLoc,
  9888. Ty,
  9889. false),
  9890. SourceLocation(),
  9891. LastExpr);
  9892. }
  9893. if (LastExpr.isInvalid())
  9894. return ExprError();
  9895. if (LastExpr.get() != nullptr) {
  9896. if (!LastLabelStmt)
  9897. Compound->setLastStmt(LastExpr.get());
  9898. else
  9899. LastLabelStmt->setSubStmt(LastExpr.get());
  9900. StmtExprMayBindToTemp = true;
  9901. }
  9902. }
  9903. }
  9904. }
  9905. // FIXME: Check that expression type is complete/non-abstract; statement
  9906. // expressions are not lvalues.
  9907. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9908. if (StmtExprMayBindToTemp)
  9909. return MaybeBindToTemporary(ResStmtExpr);
  9910. return ResStmtExpr;
  9911. }
  9912. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9913. TypeSourceInfo *TInfo,
  9914. OffsetOfComponent *CompPtr,
  9915. unsigned NumComponents,
  9916. SourceLocation RParenLoc) {
  9917. QualType ArgTy = TInfo->getType();
  9918. bool Dependent = ArgTy->isDependentType();
  9919. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9920. // We must have at least one component that refers to the type, and the first
  9921. // one is known to be a field designator. Verify that the ArgTy represents
  9922. // a struct/union/class.
  9923. if (!Dependent && !ArgTy->isRecordType())
  9924. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9925. << ArgTy << TypeRange);
  9926. // Type must be complete per C99 7.17p3 because a declaring a variable
  9927. // with an incomplete type would be ill-formed.
  9928. if (!Dependent
  9929. && RequireCompleteType(BuiltinLoc, ArgTy,
  9930. diag::err_offsetof_incomplete_type, TypeRange))
  9931. return ExprError();
  9932. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9933. // GCC extension, diagnose them.
  9934. // FIXME: This diagnostic isn't actually visible because the location is in
  9935. // a system header!
  9936. if (NumComponents != 1)
  9937. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9938. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9939. bool DidWarnAboutNonPOD = false;
  9940. QualType CurrentType = ArgTy;
  9941. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9942. SmallVector<OffsetOfNode, 4> Comps;
  9943. SmallVector<Expr*, 4> Exprs;
  9944. for (unsigned i = 0; i != NumComponents; ++i) {
  9945. const OffsetOfComponent &OC = CompPtr[i];
  9946. if (OC.isBrackets) {
  9947. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9948. if (!CurrentType->isDependentType()) {
  9949. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9950. if(!AT)
  9951. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9952. << CurrentType);
  9953. CurrentType = AT->getElementType();
  9954. } else
  9955. CurrentType = Context.DependentTy;
  9956. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9957. if (IdxRval.isInvalid())
  9958. return ExprError();
  9959. Expr *Idx = IdxRval.get();
  9960. // The expression must be an integral expression.
  9961. // FIXME: An integral constant expression?
  9962. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9963. !Idx->getType()->isIntegerType())
  9964. return ExprError(Diag(Idx->getLocStart(),
  9965. diag::err_typecheck_subscript_not_integer)
  9966. << Idx->getSourceRange());
  9967. // Record this array index.
  9968. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9969. Exprs.push_back(Idx);
  9970. continue;
  9971. }
  9972. // Offset of a field.
  9973. if (CurrentType->isDependentType()) {
  9974. // We have the offset of a field, but we can't look into the dependent
  9975. // type. Just record the identifier of the field.
  9976. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9977. CurrentType = Context.DependentTy;
  9978. continue;
  9979. }
  9980. // We need to have a complete type to look into.
  9981. if (RequireCompleteType(OC.LocStart, CurrentType,
  9982. diag::err_offsetof_incomplete_type))
  9983. return ExprError();
  9984. // Look for the designated field.
  9985. const RecordType *RC = CurrentType->getAs<RecordType>();
  9986. if (!RC)
  9987. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9988. << CurrentType);
  9989. RecordDecl *RD = RC->getDecl();
  9990. // C++ [lib.support.types]p5:
  9991. // The macro offsetof accepts a restricted set of type arguments in this
  9992. // International Standard. type shall be a POD structure or a POD union
  9993. // (clause 9).
  9994. // C++11 [support.types]p4:
  9995. // If type is not a standard-layout class (Clause 9), the results are
  9996. // undefined.
  9997. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9998. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9999. unsigned DiagID =
  10000. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  10001. : diag::ext_offsetof_non_pod_type;
  10002. if (!IsSafe && !DidWarnAboutNonPOD &&
  10003. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  10004. PDiag(DiagID)
  10005. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  10006. << CurrentType))
  10007. DidWarnAboutNonPOD = true;
  10008. }
  10009. // Look for the field.
  10010. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  10011. LookupQualifiedName(R, RD);
  10012. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  10013. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  10014. if (!MemberDecl) {
  10015. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  10016. MemberDecl = IndirectMemberDecl->getAnonField();
  10017. }
  10018. if (!MemberDecl)
  10019. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  10020. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  10021. OC.LocEnd));
  10022. // C99 7.17p3:
  10023. // (If the specified member is a bit-field, the behavior is undefined.)
  10024. //
  10025. // We diagnose this as an error.
  10026. if (MemberDecl->isBitField()) {
  10027. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  10028. << MemberDecl->getDeclName()
  10029. << SourceRange(BuiltinLoc, RParenLoc);
  10030. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  10031. return ExprError();
  10032. }
  10033. RecordDecl *Parent = MemberDecl->getParent();
  10034. if (IndirectMemberDecl)
  10035. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  10036. // If the member was found in a base class, introduce OffsetOfNodes for
  10037. // the base class indirections.
  10038. CXXBasePaths Paths;
  10039. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  10040. if (Paths.getDetectedVirtual()) {
  10041. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  10042. << MemberDecl->getDeclName()
  10043. << SourceRange(BuiltinLoc, RParenLoc);
  10044. return ExprError();
  10045. }
  10046. CXXBasePath &Path = Paths.front();
  10047. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  10048. B != BEnd; ++B)
  10049. Comps.push_back(OffsetOfNode(B->Base));
  10050. }
  10051. if (IndirectMemberDecl) {
  10052. for (auto *FI : IndirectMemberDecl->chain()) {
  10053. assert(isa<FieldDecl>(FI));
  10054. Comps.push_back(OffsetOfNode(OC.LocStart,
  10055. cast<FieldDecl>(FI), OC.LocEnd));
  10056. }
  10057. } else
  10058. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  10059. CurrentType = MemberDecl->getType().getNonReferenceType();
  10060. }
  10061. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  10062. Comps, Exprs, RParenLoc);
  10063. }
  10064. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  10065. SourceLocation BuiltinLoc,
  10066. SourceLocation TypeLoc,
  10067. ParsedType ParsedArgTy,
  10068. OffsetOfComponent *CompPtr,
  10069. unsigned NumComponents,
  10070. SourceLocation RParenLoc) {
  10071. TypeSourceInfo *ArgTInfo;
  10072. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  10073. if (ArgTy.isNull())
  10074. return ExprError();
  10075. if (!ArgTInfo)
  10076. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  10077. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  10078. RParenLoc);
  10079. }
  10080. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  10081. Expr *CondExpr,
  10082. Expr *LHSExpr, Expr *RHSExpr,
  10083. SourceLocation RPLoc) {
  10084. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  10085. ExprValueKind VK = VK_RValue;
  10086. ExprObjectKind OK = OK_Ordinary;
  10087. QualType resType;
  10088. bool ValueDependent = false;
  10089. bool CondIsTrue = false;
  10090. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  10091. resType = Context.DependentTy;
  10092. ValueDependent = true;
  10093. } else {
  10094. // The conditional expression is required to be a constant expression.
  10095. llvm::APSInt condEval(32);
  10096. ExprResult CondICE
  10097. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  10098. diag::err_typecheck_choose_expr_requires_constant, false);
  10099. if (CondICE.isInvalid())
  10100. return ExprError();
  10101. CondExpr = CondICE.get();
  10102. CondIsTrue = condEval.getZExtValue();
  10103. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  10104. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  10105. resType = ActiveExpr->getType();
  10106. ValueDependent = ActiveExpr->isValueDependent();
  10107. VK = ActiveExpr->getValueKind();
  10108. OK = ActiveExpr->getObjectKind();
  10109. }
  10110. return new (Context)
  10111. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  10112. CondIsTrue, resType->isDependentType(), ValueDependent);
  10113. }
  10114. //===----------------------------------------------------------------------===//
  10115. // Clang Extensions.
  10116. //===----------------------------------------------------------------------===//
  10117. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  10118. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  10119. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  10120. if (LangOpts.CPlusPlus) {
  10121. Decl *ManglingContextDecl;
  10122. if (MangleNumberingContext *MCtx =
  10123. getCurrentMangleNumberContext(Block->getDeclContext(),
  10124. ManglingContextDecl)) {
  10125. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  10126. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  10127. }
  10128. }
  10129. PushBlockScope(CurScope, Block);
  10130. CurContext->addDecl(Block);
  10131. if (CurScope)
  10132. PushDeclContext(CurScope, Block);
  10133. else
  10134. CurContext = Block;
  10135. getCurBlock()->HasImplicitReturnType = true;
  10136. // Enter a new evaluation context to insulate the block from any
  10137. // cleanups from the enclosing full-expression.
  10138. PushExpressionEvaluationContext(PotentiallyEvaluated);
  10139. }
  10140. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  10141. Scope *CurScope) {
  10142. assert(ParamInfo.getIdentifier() == nullptr &&
  10143. "block-id should have no identifier!");
  10144. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  10145. BlockScopeInfo *CurBlock = getCurBlock();
  10146. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  10147. QualType T = Sig->getType();
  10148. // FIXME: We should allow unexpanded parameter packs here, but that would,
  10149. // in turn, make the block expression contain unexpanded parameter packs.
  10150. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  10151. // Drop the parameters.
  10152. FunctionProtoType::ExtProtoInfo EPI;
  10153. EPI.HasTrailingReturn = false;
  10154. EPI.TypeQuals |= DeclSpec::TQ_const;
  10155. T = Context.getFunctionType(Context.DependentTy, None, EPI, None); // HLSL Change - add param mods
  10156. Sig = Context.getTrivialTypeSourceInfo(T);
  10157. }
  10158. // GetTypeForDeclarator always produces a function type for a block
  10159. // literal signature. Furthermore, it is always a FunctionProtoType
  10160. // unless the function was written with a typedef.
  10161. assert(T->isFunctionType() &&
  10162. "GetTypeForDeclarator made a non-function block signature");
  10163. // Look for an explicit signature in that function type.
  10164. FunctionProtoTypeLoc ExplicitSignature;
  10165. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  10166. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  10167. // Check whether that explicit signature was synthesized by
  10168. // GetTypeForDeclarator. If so, don't save that as part of the
  10169. // written signature.
  10170. if (ExplicitSignature.getLocalRangeBegin() ==
  10171. ExplicitSignature.getLocalRangeEnd()) {
  10172. // This would be much cheaper if we stored TypeLocs instead of
  10173. // TypeSourceInfos.
  10174. TypeLoc Result = ExplicitSignature.getReturnLoc();
  10175. unsigned Size = Result.getFullDataSize();
  10176. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  10177. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  10178. ExplicitSignature = FunctionProtoTypeLoc();
  10179. }
  10180. }
  10181. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  10182. CurBlock->FunctionType = T;
  10183. const FunctionType *Fn = T->getAs<FunctionType>();
  10184. QualType RetTy = Fn->getReturnType();
  10185. bool isVariadic =
  10186. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  10187. CurBlock->TheDecl->setIsVariadic(isVariadic);
  10188. // Context.DependentTy is used as a placeholder for a missing block
  10189. // return type. TODO: what should we do with declarators like:
  10190. // ^ * { ... }
  10191. // If the answer is "apply template argument deduction"....
  10192. if (RetTy != Context.DependentTy) {
  10193. CurBlock->ReturnType = RetTy;
  10194. CurBlock->TheDecl->setBlockMissingReturnType(false);
  10195. CurBlock->HasImplicitReturnType = false;
  10196. }
  10197. // Push block parameters from the declarator if we had them.
  10198. SmallVector<ParmVarDecl*, 8> Params;
  10199. if (ExplicitSignature) {
  10200. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  10201. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  10202. if (Param->getIdentifier() == nullptr &&
  10203. !Param->isImplicit() &&
  10204. !Param->isInvalidDecl() &&
  10205. !getLangOpts().CPlusPlus)
  10206. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10207. Params.push_back(Param);
  10208. }
  10209. // Fake up parameter variables if we have a typedef, like
  10210. // ^ fntype { ... }
  10211. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  10212. for (const auto &I : Fn->param_types()) {
  10213. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  10214. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  10215. Params.push_back(Param);
  10216. }
  10217. }
  10218. // Set the parameters on the block decl.
  10219. if (!Params.empty()) {
  10220. CurBlock->TheDecl->setParams(Params);
  10221. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  10222. CurBlock->TheDecl->param_end(),
  10223. /*CheckParameterNames=*/false);
  10224. }
  10225. // Finally we can process decl attributes.
  10226. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  10227. // Put the parameter variables in scope.
  10228. for (auto AI : CurBlock->TheDecl->params()) {
  10229. AI->setOwningFunction(CurBlock->TheDecl);
  10230. // If this has an identifier, add it to the scope stack.
  10231. if (AI->getIdentifier()) {
  10232. CheckShadow(CurBlock->TheScope, AI);
  10233. PushOnScopeChains(AI, CurBlock->TheScope);
  10234. }
  10235. }
  10236. }
  10237. /// ActOnBlockError - If there is an error parsing a block, this callback
  10238. /// is invoked to pop the information about the block from the action impl.
  10239. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  10240. // Leave the expression-evaluation context.
  10241. DiscardCleanupsInEvaluationContext();
  10242. PopExpressionEvaluationContext();
  10243. // Pop off CurBlock, handle nested blocks.
  10244. PopDeclContext();
  10245. PopFunctionScopeInfo();
  10246. }
  10247. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  10248. /// literal was successfully completed. ^(int x){...}
  10249. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  10250. Stmt *Body, Scope *CurScope) {
  10251. // HLSL Changes Start
  10252. llvm_unreachable("block statements unsupported and unreachable in HLSL");
  10253. #if 0
  10254. // HLSL Changes End
  10255. // If blocks are disabled, emit an error.
  10256. if (!LangOpts.Blocks)
  10257. Diag(CaretLoc, diag::err_blocks_disable);
  10258. // Leave the expression-evaluation context.
  10259. if (hasAnyUnrecoverableErrorsInThisFunction())
  10260. DiscardCleanupsInEvaluationContext();
  10261. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  10262. PopExpressionEvaluationContext();
  10263. if (getLangOpts().HLSL) {
  10264. return ExprError();
  10265. }
  10266. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  10267. if (BSI->HasImplicitReturnType)
  10268. deduceClosureReturnType(*BSI);
  10269. PopDeclContext();
  10270. QualType RetTy = Context.VoidTy;
  10271. if (!BSI->ReturnType.isNull())
  10272. RetTy = BSI->ReturnType;
  10273. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  10274. QualType BlockTy;
  10275. // Set the captured variables on the block.
  10276. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10277. SmallVector<BlockDecl::Capture, 4> Captures;
  10278. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10279. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10280. if (Cap.isThisCapture())
  10281. continue;
  10282. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10283. Cap.isNested(), Cap.getInitExpr());
  10284. Captures.push_back(NewCap);
  10285. }
  10286. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  10287. BSI->CXXThisCaptureIndex != 0);
  10288. // If the user wrote a function type in some form, try to use that.
  10289. if (!BSI->FunctionType.isNull()) {
  10290. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10291. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10292. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10293. // Turn protoless block types into nullary block types.
  10294. if (isa<FunctionNoProtoType>(FTy)) {
  10295. FunctionProtoType::ExtProtoInfo EPI;
  10296. EPI.ExtInfo = Ext;
  10297. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10298. // Otherwise, if we don't need to change anything about the function type,
  10299. // preserve its sugar structure.
  10300. } else if (FTy->getReturnType() == RetTy &&
  10301. (!NoReturn || FTy->getNoReturnAttr())) {
  10302. BlockTy = BSI->FunctionType;
  10303. // Otherwise, make the minimal modifications to the function type.
  10304. } else {
  10305. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10306. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10307. EPI.TypeQuals = 0; // FIXME: silently?
  10308. EPI.ExtInfo = Ext;
  10309. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10310. }
  10311. // If we don't have a function type, just build one from nothing.
  10312. } else {
  10313. FunctionProtoType::ExtProtoInfo EPI;
  10314. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10315. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10316. }
  10317. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10318. BSI->TheDecl->param_end());
  10319. BlockTy = Context.getBlockPointerType(BlockTy);
  10320. // If needed, diagnose invalid gotos and switches in the block.
  10321. if (getCurFunction()->NeedsScopeChecking() &&
  10322. !PP.isCodeCompletionEnabled())
  10323. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10324. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10325. // Try to apply the named return value optimization. We have to check again
  10326. // if we can do this, though, because blocks keep return statements around
  10327. // to deduce an implicit return type.
  10328. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10329. !BSI->TheDecl->isDependentContext())
  10330. computeNRVO(Body, BSI);
  10331. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10332. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10333. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10334. // If the block isn't obviously global, i.e. it captures anything at
  10335. // all, then we need to do a few things in the surrounding context:
  10336. if (Result->getBlockDecl()->hasCaptures()) {
  10337. // First, this expression has a new cleanup object.
  10338. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10339. ExprNeedsCleanups = true;
  10340. // It also gets a branch-protected scope if any of the captured
  10341. // variables needs destruction.
  10342. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10343. const VarDecl *var = CI.getVariable();
  10344. if (var->getType().isDestructedType() != QualType::DK_none) {
  10345. getCurFunction()->setHasBranchProtectedScope();
  10346. break;
  10347. }
  10348. }
  10349. }
  10350. return Result;
  10351. #endif // HLSL Change
  10352. }
  10353. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10354. Expr *E, ParsedType Ty,
  10355. SourceLocation RPLoc) {
  10356. TypeSourceInfo *TInfo;
  10357. GetTypeFromParser(Ty, &TInfo);
  10358. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10359. }
  10360. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10361. Expr *E, TypeSourceInfo *TInfo,
  10362. SourceLocation RPLoc) {
  10363. Expr *OrigExpr = E;
  10364. // Get the va_list type
  10365. QualType VaListType = Context.getBuiltinVaListType();
  10366. if (VaListType->isArrayType()) {
  10367. // Deal with implicit array decay; for example, on x86-64,
  10368. // va_list is an array, but it's supposed to decay to
  10369. // a pointer for va_arg.
  10370. VaListType = Context.getArrayDecayedType(VaListType);
  10371. // Make sure the input expression also decays appropriately.
  10372. ExprResult Result = UsualUnaryConversions(E);
  10373. if (Result.isInvalid())
  10374. return ExprError();
  10375. E = Result.get();
  10376. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10377. // If va_list is a record type and we are compiling in C++ mode,
  10378. // check the argument using reference binding.
  10379. InitializedEntity Entity
  10380. = InitializedEntity::InitializeParameter(Context,
  10381. Context.getLValueReferenceType(VaListType), false);
  10382. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10383. if (Init.isInvalid())
  10384. return ExprError();
  10385. E = Init.getAs<Expr>();
  10386. } else {
  10387. // Otherwise, the va_list argument must be an l-value because
  10388. // it is modified by va_arg.
  10389. if (!E->isTypeDependent() &&
  10390. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10391. return ExprError();
  10392. }
  10393. if (!E->isTypeDependent() &&
  10394. !Context.hasSameType(VaListType, E->getType())) {
  10395. return ExprError(Diag(E->getLocStart(),
  10396. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10397. << OrigExpr->getType() << E->getSourceRange());
  10398. }
  10399. if (!TInfo->getType()->isDependentType()) {
  10400. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10401. diag::err_second_parameter_to_va_arg_incomplete,
  10402. TInfo->getTypeLoc()))
  10403. return ExprError();
  10404. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10405. TInfo->getType(),
  10406. diag::err_second_parameter_to_va_arg_abstract,
  10407. TInfo->getTypeLoc()))
  10408. return ExprError();
  10409. if (!TInfo->getType().isPODType(Context)) {
  10410. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10411. TInfo->getType()->isObjCLifetimeType()
  10412. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10413. : diag::warn_second_parameter_to_va_arg_not_pod)
  10414. << TInfo->getType()
  10415. << TInfo->getTypeLoc().getSourceRange();
  10416. }
  10417. // Check for va_arg where arguments of the given type will be promoted
  10418. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10419. QualType PromoteType;
  10420. if (TInfo->getType()->isPromotableIntegerType()) {
  10421. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10422. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10423. PromoteType = QualType();
  10424. }
  10425. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10426. PromoteType = Context.DoubleTy;
  10427. if (!PromoteType.isNull())
  10428. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10429. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10430. << TInfo->getType()
  10431. << PromoteType
  10432. << TInfo->getTypeLoc().getSourceRange());
  10433. }
  10434. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10435. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  10436. }
  10437. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10438. // The type of __null will be int or long, depending on the size of
  10439. // pointers on the target.
  10440. QualType Ty;
  10441. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10442. if (pw == Context.getTargetInfo().getIntWidth())
  10443. Ty = Context.IntTy;
  10444. else if (pw == Context.getTargetInfo().getLongWidth())
  10445. Ty = Context.LongTy;
  10446. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10447. Ty = Context.LongLongTy;
  10448. else {
  10449. llvm_unreachable("I don't know size of pointer!");
  10450. }
  10451. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10452. }
  10453. bool
  10454. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10455. if (!getLangOpts().ObjC1)
  10456. return false;
  10457. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10458. if (!PT)
  10459. return false;
  10460. if (!PT->isObjCIdType()) {
  10461. // Check if the destination is the 'NSString' interface.
  10462. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10463. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10464. return false;
  10465. }
  10466. // Ignore any parens, implicit casts (should only be
  10467. // array-to-pointer decays), and not-so-opaque values. The last is
  10468. // important for making this trigger for property assignments.
  10469. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10470. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10471. if (OV->getSourceExpr())
  10472. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10473. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10474. if (!SL || !SL->isAscii())
  10475. return false;
  10476. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10477. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10478. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10479. return true;
  10480. }
  10481. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10482. SourceLocation Loc,
  10483. QualType DstType, QualType SrcType,
  10484. Expr *SrcExpr, AssignmentAction Action,
  10485. bool *Complained) {
  10486. if (Complained)
  10487. *Complained = false;
  10488. // Decode the result (notice that AST's are still created for extensions).
  10489. bool CheckInferredResultType = false;
  10490. bool isInvalid = false;
  10491. unsigned DiagKind = 0;
  10492. FixItHint Hint;
  10493. ConversionFixItGenerator ConvHints;
  10494. bool MayHaveConvFixit = false;
  10495. bool MayHaveFunctionDiff = false;
  10496. const ObjCInterfaceDecl *IFace = nullptr;
  10497. const ObjCProtocolDecl *PDecl = nullptr;
  10498. switch (ConvTy) {
  10499. case Compatible:
  10500. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10501. return false;
  10502. case PointerToInt:
  10503. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10504. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10505. MayHaveConvFixit = true;
  10506. break;
  10507. case IntToPointer:
  10508. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10509. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10510. MayHaveConvFixit = true;
  10511. break;
  10512. case IncompatiblePointer:
  10513. DiagKind =
  10514. (Action == AA_Passing_CFAudited ?
  10515. diag::err_arc_typecheck_convert_incompatible_pointer :
  10516. diag::ext_typecheck_convert_incompatible_pointer);
  10517. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10518. SrcType->isObjCObjectPointerType();
  10519. if (Hint.isNull() && !CheckInferredResultType) {
  10520. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10521. }
  10522. else if (CheckInferredResultType) {
  10523. SrcType = SrcType.getUnqualifiedType();
  10524. DstType = DstType.getUnqualifiedType();
  10525. }
  10526. MayHaveConvFixit = true;
  10527. break;
  10528. case IncompatiblePointerSign:
  10529. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10530. break;
  10531. case FunctionVoidPointer:
  10532. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10533. break;
  10534. case IncompatiblePointerDiscardsQualifiers: {
  10535. // Perform array-to-pointer decay if necessary.
  10536. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10537. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10538. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10539. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10540. DiagKind = diag::err_typecheck_incompatible_address_space;
  10541. break;
  10542. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10543. DiagKind = diag::err_typecheck_incompatible_ownership;
  10544. break;
  10545. }
  10546. llvm_unreachable("unknown error case for discarding qualifiers!");
  10547. // fallthrough
  10548. }
  10549. case CompatiblePointerDiscardsQualifiers:
  10550. // If the qualifiers lost were because we were applying the
  10551. // (deprecated) C++ conversion from a string literal to a char*
  10552. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10553. // Ideally, this check would be performed in
  10554. // checkPointerTypesForAssignment. However, that would require a
  10555. // bit of refactoring (so that the second argument is an
  10556. // expression, rather than a type), which should be done as part
  10557. // of a larger effort to fix checkPointerTypesForAssignment for
  10558. // C++ semantics.
  10559. if (getLangOpts().CPlusPlus &&
  10560. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10561. return false;
  10562. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10563. break;
  10564. case IncompatibleNestedPointerQualifiers:
  10565. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10566. break;
  10567. case IntToBlockPointer:
  10568. DiagKind = diag::err_int_to_block_pointer;
  10569. break;
  10570. case IncompatibleBlockPointer:
  10571. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10572. break;
  10573. case IncompatibleObjCQualifiedId: {
  10574. if (SrcType->isObjCQualifiedIdType()) {
  10575. const ObjCObjectPointerType *srcOPT =
  10576. SrcType->getAs<ObjCObjectPointerType>();
  10577. for (auto *srcProto : srcOPT->quals()) {
  10578. PDecl = srcProto;
  10579. break;
  10580. }
  10581. if (const ObjCInterfaceType *IFaceT =
  10582. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10583. IFace = IFaceT->getDecl();
  10584. }
  10585. else if (DstType->isObjCQualifiedIdType()) {
  10586. const ObjCObjectPointerType *dstOPT =
  10587. DstType->getAs<ObjCObjectPointerType>();
  10588. for (auto *dstProto : dstOPT->quals()) {
  10589. PDecl = dstProto;
  10590. break;
  10591. }
  10592. if (const ObjCInterfaceType *IFaceT =
  10593. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10594. IFace = IFaceT->getDecl();
  10595. }
  10596. DiagKind = diag::warn_incompatible_qualified_id;
  10597. break;
  10598. }
  10599. case IncompatibleVectors:
  10600. DiagKind = diag::warn_incompatible_vectors;
  10601. break;
  10602. case IncompatibleObjCWeakRef:
  10603. DiagKind = diag::err_arc_weak_unavailable_assign;
  10604. break;
  10605. case Incompatible:
  10606. DiagKind = diag::err_typecheck_convert_incompatible;
  10607. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10608. MayHaveConvFixit = true;
  10609. isInvalid = true;
  10610. MayHaveFunctionDiff = true;
  10611. break;
  10612. }
  10613. QualType FirstType, SecondType;
  10614. switch (Action) {
  10615. case AA_Assigning:
  10616. case AA_Initializing:
  10617. // The destination type comes first.
  10618. FirstType = DstType;
  10619. SecondType = SrcType;
  10620. break;
  10621. case AA_Returning:
  10622. case AA_Passing:
  10623. case AA_Passing_CFAudited:
  10624. case AA_Converting:
  10625. case AA_Sending:
  10626. case AA_Casting:
  10627. // The source type comes first.
  10628. FirstType = SrcType;
  10629. SecondType = DstType;
  10630. break;
  10631. }
  10632. PartialDiagnostic FDiag = PDiag(DiagKind);
  10633. if (Action == AA_Passing_CFAudited)
  10634. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10635. else
  10636. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10637. // If we can fix the conversion, suggest the FixIts.
  10638. assert(ConvHints.isNull() || Hint.isNull());
  10639. if (!ConvHints.isNull()) {
  10640. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10641. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10642. FDiag << *HI;
  10643. } else {
  10644. FDiag << Hint;
  10645. }
  10646. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10647. if (MayHaveFunctionDiff)
  10648. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10649. Diag(Loc, FDiag);
  10650. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10651. PDecl && IFace && !IFace->hasDefinition())
  10652. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10653. << IFace->getName() << PDecl->getName();
  10654. if (SecondType == Context.OverloadTy)
  10655. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10656. FirstType);
  10657. if (CheckInferredResultType)
  10658. EmitRelatedResultTypeNote(SrcExpr);
  10659. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10660. EmitRelatedResultTypeNoteForReturn(DstType);
  10661. if (Complained)
  10662. *Complained = true;
  10663. return isInvalid;
  10664. }
  10665. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10666. llvm::APSInt *Result) {
  10667. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10668. public:
  10669. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10670. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10671. }
  10672. } Diagnoser;
  10673. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10674. }
  10675. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10676. llvm::APSInt *Result,
  10677. unsigned DiagID,
  10678. bool AllowFold) {
  10679. class IDDiagnoser : public VerifyICEDiagnoser {
  10680. unsigned DiagID;
  10681. public:
  10682. IDDiagnoser(unsigned DiagID)
  10683. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10684. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10685. S.Diag(Loc, DiagID) << SR;
  10686. }
  10687. } Diagnoser(DiagID);
  10688. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10689. }
  10690. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10691. SourceRange SR) {
  10692. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10693. }
  10694. ExprResult
  10695. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10696. VerifyICEDiagnoser &Diagnoser,
  10697. bool AllowFold) {
  10698. SourceLocation DiagLoc = E->getLocStart();
  10699. if (getLangOpts().CPlusPlus11) {
  10700. // C++11 [expr.const]p5:
  10701. // If an expression of literal class type is used in a context where an
  10702. // integral constant expression is required, then that class type shall
  10703. // have a single non-explicit conversion function to an integral or
  10704. // unscoped enumeration type
  10705. ExprResult Converted;
  10706. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10707. public:
  10708. CXX11ConvertDiagnoser(bool Silent)
  10709. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10710. Silent, true) {}
  10711. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10712. QualType T) override {
  10713. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10714. }
  10715. SemaDiagnosticBuilder diagnoseIncomplete(
  10716. Sema &S, SourceLocation Loc, QualType T) override {
  10717. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10718. }
  10719. SemaDiagnosticBuilder diagnoseExplicitConv(
  10720. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10721. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10722. }
  10723. SemaDiagnosticBuilder noteExplicitConv(
  10724. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10725. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10726. << ConvTy->isEnumeralType() << ConvTy;
  10727. }
  10728. SemaDiagnosticBuilder diagnoseAmbiguous(
  10729. Sema &S, SourceLocation Loc, QualType T) override {
  10730. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10731. }
  10732. SemaDiagnosticBuilder noteAmbiguous(
  10733. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10734. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10735. << ConvTy->isEnumeralType() << ConvTy;
  10736. }
  10737. SemaDiagnosticBuilder diagnoseConversion(
  10738. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10739. llvm_unreachable("conversion functions are permitted");
  10740. }
  10741. } ConvertDiagnoser(Diagnoser.Suppress);
  10742. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10743. ConvertDiagnoser);
  10744. if (Converted.isInvalid())
  10745. return Converted;
  10746. E = Converted.get();
  10747. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10748. return ExprError();
  10749. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10750. // An ICE must be of integral or unscoped enumeration type.
  10751. if (!Diagnoser.Suppress)
  10752. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10753. return ExprError();
  10754. }
  10755. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10756. // in the non-ICE case.
  10757. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10758. if (Result)
  10759. *Result = E->EvaluateKnownConstInt(Context);
  10760. return E;
  10761. }
  10762. Expr::EvalResult EvalResult;
  10763. SmallVector<PartialDiagnosticAt, 8> Notes;
  10764. EvalResult.Diag = &Notes;
  10765. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10766. // not a constant expression as a side-effect.
  10767. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10768. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10769. // In C++11, we can rely on diagnostics being produced for any expression
  10770. // which is not a constant expression. If no diagnostics were produced, then
  10771. // this is a constant expression.
  10772. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10773. if (Result)
  10774. *Result = EvalResult.Val.getInt();
  10775. return E;
  10776. }
  10777. // If our only note is the usual "invalid subexpression" note, just point
  10778. // the caret at its location rather than producing an essentially
  10779. // redundant note.
  10780. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10781. diag::note_invalid_subexpr_in_const_expr) {
  10782. DiagLoc = Notes[0].first;
  10783. Notes.clear();
  10784. }
  10785. if (!Folded || !AllowFold) {
  10786. if (!Diagnoser.Suppress) {
  10787. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10788. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10789. Diag(Notes[I].first, Notes[I].second);
  10790. }
  10791. return ExprError();
  10792. }
  10793. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10794. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10795. Diag(Notes[I].first, Notes[I].second);
  10796. if (Result)
  10797. *Result = EvalResult.Val.getInt();
  10798. return E;
  10799. }
  10800. namespace {
  10801. // Handle the case where we conclude a expression which we speculatively
  10802. // considered to be unevaluated is actually evaluated.
  10803. class TransformToPE : public TreeTransform<TransformToPE> {
  10804. typedef TreeTransform<TransformToPE> BaseTransform;
  10805. public:
  10806. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10807. // Make sure we redo semantic analysis
  10808. bool AlwaysRebuild() { return true; }
  10809. // Make sure we handle LabelStmts correctly.
  10810. // FIXME: This does the right thing, but maybe we need a more general
  10811. // fix to TreeTransform?
  10812. StmtResult TransformLabelStmt(LabelStmt *S) {
  10813. S->getDecl()->setStmt(nullptr);
  10814. return BaseTransform::TransformLabelStmt(S);
  10815. }
  10816. // We need to special-case DeclRefExprs referring to FieldDecls which
  10817. // are not part of a member pointer formation; normal TreeTransforming
  10818. // doesn't catch this case because of the way we represent them in the AST.
  10819. // FIXME: This is a bit ugly; is it really the best way to handle this
  10820. // case?
  10821. //
  10822. // Error on DeclRefExprs referring to FieldDecls.
  10823. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10824. if (isa<FieldDecl>(E->getDecl()) &&
  10825. !SemaRef.isUnevaluatedContext())
  10826. return SemaRef.Diag(E->getLocation(),
  10827. diag::err_invalid_non_static_member_use)
  10828. << E->getDecl() << E->getSourceRange();
  10829. return BaseTransform::TransformDeclRefExpr(E);
  10830. }
  10831. // Exception: filter out member pointer formation
  10832. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10833. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10834. return E;
  10835. return BaseTransform::TransformUnaryOperator(E);
  10836. }
  10837. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10838. // Lambdas never need to be transformed.
  10839. return E;
  10840. }
  10841. };
  10842. }
  10843. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10844. assert(isUnevaluatedContext() &&
  10845. "Should only transform unevaluated expressions");
  10846. ExprEvalContexts.back().Context =
  10847. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10848. if (isUnevaluatedContext())
  10849. return E;
  10850. return TransformToPE(*this).TransformExpr(E);
  10851. }
  10852. void
  10853. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10854. Decl *LambdaContextDecl,
  10855. bool IsDecltype) {
  10856. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10857. ExprNeedsCleanups, LambdaContextDecl,
  10858. IsDecltype);
  10859. ExprNeedsCleanups = false;
  10860. if (!MaybeODRUseExprs.empty())
  10861. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10862. }
  10863. void
  10864. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10865. ReuseLambdaContextDecl_t,
  10866. bool IsDecltype) {
  10867. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10868. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10869. }
  10870. void Sema::PopExpressionEvaluationContext() {
  10871. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10872. unsigned NumTypos = Rec.NumTypos;
  10873. if (!Rec.Lambdas.empty()) {
  10874. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10875. unsigned D;
  10876. if (Rec.isUnevaluated()) {
  10877. // C++11 [expr.prim.lambda]p2:
  10878. // A lambda-expression shall not appear in an unevaluated operand
  10879. // (Clause 5).
  10880. D = diag::err_lambda_unevaluated_operand;
  10881. } else {
  10882. // C++1y [expr.const]p2:
  10883. // A conditional-expression e is a core constant expression unless the
  10884. // evaluation of e, following the rules of the abstract machine, would
  10885. // evaluate [...] a lambda-expression.
  10886. D = diag::err_lambda_in_constant_expression;
  10887. }
  10888. for (const auto *L : Rec.Lambdas)
  10889. Diag(L->getLocStart(), D);
  10890. } else {
  10891. // Mark the capture expressions odr-used. This was deferred
  10892. // during lambda expression creation.
  10893. for (auto *Lambda : Rec.Lambdas) {
  10894. for (auto *C : Lambda->capture_inits())
  10895. MarkDeclarationsReferencedInExpr(C);
  10896. }
  10897. }
  10898. }
  10899. // When are coming out of an unevaluated context, clear out any
  10900. // temporaries that we may have created as part of the evaluation of
  10901. // the expression in that context: they aren't relevant because they
  10902. // will never be constructed.
  10903. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10904. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10905. ExprCleanupObjects.end());
  10906. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10907. CleanupVarDeclMarking();
  10908. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10909. // Otherwise, merge the contexts together.
  10910. } else {
  10911. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10912. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10913. Rec.SavedMaybeODRUseExprs.end());
  10914. }
  10915. // Pop the current expression evaluation context off the stack.
  10916. ExprEvalContexts.pop_back();
  10917. if (!ExprEvalContexts.empty())
  10918. ExprEvalContexts.back().NumTypos += NumTypos;
  10919. else
  10920. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10921. "last ExpressionEvaluationContextRecord");
  10922. }
  10923. void Sema::DiscardCleanupsInEvaluationContext() {
  10924. ExprCleanupObjects.erase(
  10925. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10926. ExprCleanupObjects.end());
  10927. ExprNeedsCleanups = false;
  10928. MaybeODRUseExprs.clear();
  10929. }
  10930. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10931. if (!E->getType()->isVariablyModifiedType())
  10932. return E;
  10933. return TransformToPotentiallyEvaluated(E);
  10934. }
  10935. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10936. // Do not mark anything as "used" within a dependent context; wait for
  10937. // an instantiation.
  10938. if (SemaRef.CurContext->isDependentContext())
  10939. return false;
  10940. switch (SemaRef.ExprEvalContexts.back().Context) {
  10941. case Sema::Unevaluated:
  10942. case Sema::UnevaluatedAbstract:
  10943. // We are in an expression that is not potentially evaluated; do nothing.
  10944. // (Depending on how you read the standard, we actually do need to do
  10945. // something here for null pointer constants, but the standard's
  10946. // definition of a null pointer constant is completely crazy.)
  10947. return false;
  10948. case Sema::ConstantEvaluated:
  10949. case Sema::PotentiallyEvaluated:
  10950. // We are in a potentially evaluated expression (or a constant-expression
  10951. // in C++03); we need to do implicit template instantiation, implicitly
  10952. // define class members, and mark most declarations as used.
  10953. return true;
  10954. case Sema::PotentiallyEvaluatedIfUsed:
  10955. // Referenced declarations will only be used if the construct in the
  10956. // containing expression is used.
  10957. return false;
  10958. }
  10959. llvm_unreachable("Invalid context");
  10960. }
  10961. /// \brief Mark a function referenced, and check whether it is odr-used
  10962. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10963. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10964. bool OdrUse) {
  10965. assert(Func && "No function?");
  10966. Func->setReferenced();
  10967. // C++11 [basic.def.odr]p3:
  10968. // A function whose name appears as a potentially-evaluated expression is
  10969. // odr-used if it is the unique lookup result or the selected member of a
  10970. // set of overloaded functions [...].
  10971. //
  10972. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10973. // can just check that here. Skip the rest of this function if we've already
  10974. // marked the function as used.
  10975. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10976. !IsPotentiallyEvaluatedContext(*this)) {
  10977. // C++11 [temp.inst]p3:
  10978. // Unless a function template specialization has been explicitly
  10979. // instantiated or explicitly specialized, the function template
  10980. // specialization is implicitly instantiated when the specialization is
  10981. // referenced in a context that requires a function definition to exist.
  10982. //
  10983. // We consider constexpr function templates to be referenced in a context
  10984. // that requires a definition to exist whenever they are referenced.
  10985. //
  10986. // FIXME: This instantiates constexpr functions too frequently. If this is
  10987. // really an unevaluated context (and we're not just in the definition of a
  10988. // function template or overload resolution or other cases which we
  10989. // incorrectly consider to be unevaluated contexts), and we're not in a
  10990. // subexpression which we actually need to evaluate (for instance, a
  10991. // template argument, array bound or an expression in a braced-init-list),
  10992. // we are not permitted to instantiate this constexpr function definition.
  10993. //
  10994. // FIXME: This also implicitly defines special members too frequently. They
  10995. // are only supposed to be implicitly defined if they are odr-used, but they
  10996. // are not odr-used from constant expressions in unevaluated contexts.
  10997. // However, they cannot be referenced if they are deleted, and they are
  10998. // deleted whenever the implicit definition of the special member would
  10999. // fail.
  11000. if (!Func->isConstexpr() || Func->getBody())
  11001. return;
  11002. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  11003. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  11004. return;
  11005. }
  11006. // Note that this declaration has been used.
  11007. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  11008. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  11009. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  11010. if (Constructor->isDefaultConstructor()) {
  11011. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  11012. return;
  11013. DefineImplicitDefaultConstructor(Loc, Constructor);
  11014. } else if (Constructor->isCopyConstructor()) {
  11015. DefineImplicitCopyConstructor(Loc, Constructor);
  11016. } else if (Constructor->isMoveConstructor()) {
  11017. DefineImplicitMoveConstructor(Loc, Constructor);
  11018. }
  11019. } else if (Constructor->getInheritedConstructor()) {
  11020. DefineInheritingConstructor(Loc, Constructor);
  11021. }
  11022. } else if (CXXDestructorDecl *Destructor =
  11023. dyn_cast<CXXDestructorDecl>(Func)) {
  11024. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  11025. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  11026. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  11027. return;
  11028. DefineImplicitDestructor(Loc, Destructor);
  11029. }
  11030. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  11031. MarkVTableUsed(Loc, Destructor->getParent());
  11032. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  11033. if (MethodDecl->isOverloadedOperator() &&
  11034. MethodDecl->getOverloadedOperator() == OO_Equal) {
  11035. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  11036. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  11037. if (MethodDecl->isCopyAssignmentOperator())
  11038. DefineImplicitCopyAssignment(Loc, MethodDecl);
  11039. else
  11040. DefineImplicitMoveAssignment(Loc, MethodDecl);
  11041. }
  11042. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  11043. MethodDecl->getParent()->isLambda()) {
  11044. CXXConversionDecl *Conversion =
  11045. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  11046. if (Conversion->isLambdaToBlockPointerConversion())
  11047. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  11048. else
  11049. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  11050. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  11051. MarkVTableUsed(Loc, MethodDecl->getParent());
  11052. }
  11053. // Recursive functions should be marked when used from another function.
  11054. // FIXME: Is this really right?
  11055. if (CurContext == Func) return;
  11056. // Resolve the exception specification for any function which is
  11057. // used: CodeGen will need it.
  11058. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  11059. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  11060. ResolveExceptionSpec(Loc, FPT);
  11061. if (!OdrUse) return;
  11062. // Implicit instantiation of function templates and member functions of
  11063. // class templates.
  11064. if (Func->isImplicitlyInstantiable()) {
  11065. bool AlreadyInstantiated = false;
  11066. SourceLocation PointOfInstantiation = Loc;
  11067. if (FunctionTemplateSpecializationInfo *SpecInfo
  11068. = Func->getTemplateSpecializationInfo()) {
  11069. if (SpecInfo->getPointOfInstantiation().isInvalid())
  11070. SpecInfo->setPointOfInstantiation(Loc);
  11071. else if (SpecInfo->getTemplateSpecializationKind()
  11072. == TSK_ImplicitInstantiation) {
  11073. AlreadyInstantiated = true;
  11074. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  11075. }
  11076. } else if (MemberSpecializationInfo *MSInfo
  11077. = Func->getMemberSpecializationInfo()) {
  11078. if (MSInfo->getPointOfInstantiation().isInvalid())
  11079. MSInfo->setPointOfInstantiation(Loc);
  11080. else if (MSInfo->getTemplateSpecializationKind()
  11081. == TSK_ImplicitInstantiation) {
  11082. AlreadyInstantiated = true;
  11083. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  11084. }
  11085. }
  11086. if (!AlreadyInstantiated || Func->isConstexpr()) {
  11087. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  11088. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  11089. ActiveTemplateInstantiations.size())
  11090. PendingLocalImplicitInstantiations.push_back(
  11091. std::make_pair(Func, PointOfInstantiation));
  11092. else if (Func->isConstexpr())
  11093. // Do not defer instantiations of constexpr functions, to avoid the
  11094. // expression evaluator needing to call back into Sema if it sees a
  11095. // call to such a function.
  11096. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  11097. else {
  11098. PendingInstantiations.push_back(std::make_pair(Func,
  11099. PointOfInstantiation));
  11100. // Notify the consumer that a function was implicitly instantiated.
  11101. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  11102. }
  11103. }
  11104. } else {
  11105. // Walk redefinitions, as some of them may be instantiable.
  11106. for (auto i : Func->redecls()) {
  11107. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  11108. MarkFunctionReferenced(Loc, i);
  11109. }
  11110. }
  11111. // Keep track of used but undefined functions.
  11112. if (!Func->isDefined()) {
  11113. if (mightHaveNonExternalLinkage(Func))
  11114. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11115. else if (Func->getMostRecentDecl()->isInlined() &&
  11116. !LangOpts.GNUInline &&
  11117. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  11118. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11119. }
  11120. // Normally the most current decl is marked used while processing the use and
  11121. // any subsequent decls are marked used by decl merging. This fails with
  11122. // template instantiation since marking can happen at the end of the file
  11123. // and, because of the two phase lookup, this function is called with at
  11124. // decl in the middle of a decl chain. We loop to maintain the invariant
  11125. // that once a decl is used, all decls after it are also used.
  11126. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  11127. F->markUsed(Context);
  11128. if (F == Func)
  11129. break;
  11130. }
  11131. }
  11132. static void
  11133. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  11134. VarDecl *var, DeclContext *DC) {
  11135. DeclContext *VarDC = var->getDeclContext();
  11136. // If the parameter still belongs to the translation unit, then
  11137. // we're actually just using one parameter in the declaration of
  11138. // the next.
  11139. if (isa<ParmVarDecl>(var) &&
  11140. isa<TranslationUnitDecl>(VarDC))
  11141. return;
  11142. // For C code, don't diagnose about capture if we're not actually in code
  11143. // right now; it's impossible to write a non-constant expression outside of
  11144. // function context, so we'll get other (more useful) diagnostics later.
  11145. //
  11146. // For C++, things get a bit more nasty... it would be nice to suppress this
  11147. // diagnostic for certain cases like using a local variable in an array bound
  11148. // for a member of a local class, but the correct predicate is not obvious.
  11149. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  11150. return;
  11151. if (isa<CXXMethodDecl>(VarDC) &&
  11152. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  11153. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  11154. << var->getIdentifier();
  11155. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  11156. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  11157. << var->getIdentifier() << fn->getDeclName();
  11158. } else if (isa<BlockDecl>(VarDC)) {
  11159. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  11160. << var->getIdentifier();
  11161. } else {
  11162. // FIXME: Is there any other context where a local variable can be
  11163. // declared?
  11164. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  11165. << var->getIdentifier();
  11166. }
  11167. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  11168. << var->getIdentifier();
  11169. // FIXME: Add additional diagnostic info about class etc. which prevents
  11170. // capture.
  11171. }
  11172. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  11173. bool &SubCapturesAreNested,
  11174. QualType &CaptureType,
  11175. QualType &DeclRefType) {
  11176. // Check whether we've already captured it.
  11177. if (CSI->CaptureMap.count(Var)) {
  11178. // If we found a capture, any subcaptures are nested.
  11179. SubCapturesAreNested = true;
  11180. // Retrieve the capture type for this variable.
  11181. CaptureType = CSI->getCapture(Var).getCaptureType();
  11182. // Compute the type of an expression that refers to this variable.
  11183. DeclRefType = CaptureType.getNonReferenceType();
  11184. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  11185. if (Cap.isCopyCapture() &&
  11186. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  11187. DeclRefType.addConst();
  11188. return true;
  11189. }
  11190. return false;
  11191. }
  11192. // Only block literals, captured statements, and lambda expressions can
  11193. // capture; other scopes don't work.
  11194. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  11195. SourceLocation Loc,
  11196. const bool Diagnose, Sema &S) {
  11197. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  11198. return getLambdaAwareParentOfDeclContext(DC);
  11199. else if (Var->hasLocalStorage()) {
  11200. if (Diagnose)
  11201. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  11202. }
  11203. return nullptr;
  11204. }
  11205. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11206. // certain types of variables (unnamed, variably modified types etc.)
  11207. // so check for eligibility.
  11208. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  11209. SourceLocation Loc,
  11210. const bool Diagnose, Sema &S) {
  11211. bool IsBlock = isa<BlockScopeInfo>(CSI);
  11212. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  11213. // Lambdas are not allowed to capture unnamed variables
  11214. // (e.g. anonymous unions).
  11215. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  11216. // assuming that's the intent.
  11217. if (IsLambda && !Var->getDeclName()) {
  11218. if (Diagnose) {
  11219. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  11220. S.Diag(Var->getLocation(), diag::note_declared_at);
  11221. }
  11222. return false;
  11223. }
  11224. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  11225. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  11226. if (Diagnose) {
  11227. S.Diag(Loc, diag::err_ref_vm_type);
  11228. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11229. << Var->getDeclName();
  11230. }
  11231. return false;
  11232. }
  11233. // Prohibit structs with flexible array members too.
  11234. // We cannot capture what is in the tail end of the struct.
  11235. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  11236. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  11237. if (Diagnose) {
  11238. if (IsBlock)
  11239. S.Diag(Loc, diag::err_ref_flexarray_type);
  11240. else
  11241. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  11242. << Var->getDeclName();
  11243. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11244. << Var->getDeclName();
  11245. }
  11246. return false;
  11247. }
  11248. }
  11249. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11250. // Lambdas and captured statements are not allowed to capture __block
  11251. // variables; they don't support the expected semantics.
  11252. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  11253. if (Diagnose) {
  11254. S.Diag(Loc, diag::err_capture_block_variable)
  11255. << Var->getDeclName() << !IsLambda;
  11256. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11257. << Var->getDeclName();
  11258. }
  11259. return false;
  11260. }
  11261. return true;
  11262. }
  11263. // Returns true if the capture by block was successful.
  11264. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  11265. SourceLocation Loc,
  11266. const bool BuildAndDiagnose,
  11267. QualType &CaptureType,
  11268. QualType &DeclRefType,
  11269. const bool Nested,
  11270. Sema &S) {
  11271. Expr *CopyExpr = nullptr;
  11272. bool ByRef = false;
  11273. // Blocks are not allowed to capture arrays.
  11274. if (CaptureType->isArrayType()) {
  11275. if (BuildAndDiagnose) {
  11276. S.Diag(Loc, diag::err_ref_array_type);
  11277. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11278. << Var->getDeclName();
  11279. }
  11280. return false;
  11281. }
  11282. // Forbid the block-capture of autoreleasing variables.
  11283. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11284. if (BuildAndDiagnose) {
  11285. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11286. << /*block*/ 0;
  11287. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11288. << Var->getDeclName();
  11289. }
  11290. return false;
  11291. }
  11292. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11293. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11294. // Block capture by reference does not change the capture or
  11295. // declaration reference types.
  11296. ByRef = true;
  11297. } else {
  11298. // Block capture by copy introduces 'const'.
  11299. CaptureType = CaptureType.getNonReferenceType().withConst();
  11300. DeclRefType = CaptureType;
  11301. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11302. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11303. // The capture logic needs the destructor, so make sure we mark it.
  11304. // Usually this is unnecessary because most local variables have
  11305. // their destructors marked at declaration time, but parameters are
  11306. // an exception because it's technically only the call site that
  11307. // actually requires the destructor.
  11308. if (isa<ParmVarDecl>(Var))
  11309. S.FinalizeVarWithDestructor(Var, Record);
  11310. // Enter a new evaluation context to insulate the copy
  11311. // full-expression.
  11312. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11313. // According to the blocks spec, the capture of a variable from
  11314. // the stack requires a const copy constructor. This is not true
  11315. // of the copy/move done to move a __block variable to the heap.
  11316. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11317. DeclRefType.withConst(),
  11318. VK_LValue, Loc);
  11319. ExprResult Result
  11320. = S.PerformCopyInitialization(
  11321. InitializedEntity::InitializeBlock(Var->getLocation(),
  11322. CaptureType, false),
  11323. Loc, DeclRef);
  11324. // Build a full-expression copy expression if initialization
  11325. // succeeded and used a non-trivial constructor. Recover from
  11326. // errors by pretending that the copy isn't necessary.
  11327. if (!Result.isInvalid() &&
  11328. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11329. ->isTrivial()) {
  11330. Result = S.MaybeCreateExprWithCleanups(Result);
  11331. CopyExpr = Result.get();
  11332. }
  11333. }
  11334. }
  11335. }
  11336. // Actually capture the variable.
  11337. if (BuildAndDiagnose)
  11338. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11339. SourceLocation(), CaptureType, CopyExpr);
  11340. return true;
  11341. }
  11342. /// \brief Capture the given variable in the captured region.
  11343. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11344. VarDecl *Var,
  11345. SourceLocation Loc,
  11346. const bool BuildAndDiagnose,
  11347. QualType &CaptureType,
  11348. QualType &DeclRefType,
  11349. const bool RefersToCapturedVariable,
  11350. Sema &S) {
  11351. // By default, capture variables by reference.
  11352. bool ByRef = true;
  11353. // Using an LValue reference type is consistent with Lambdas (see below).
  11354. if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
  11355. DeclRefType = DeclRefType.getUnqualifiedType();
  11356. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11357. Expr *CopyExpr = nullptr;
  11358. if (BuildAndDiagnose) {
  11359. // The current implementation assumes that all variables are captured
  11360. // by references. Since there is no capture by copy, no expression
  11361. // evaluation will be needed.
  11362. RecordDecl *RD = RSI->TheRecordDecl;
  11363. FieldDecl *Field
  11364. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11365. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11366. nullptr, false, ICIS_NoInit);
  11367. Field->setImplicit(true);
  11368. Field->setAccess(AS_private);
  11369. RD->addDecl(Field);
  11370. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11371. DeclRefType, VK_LValue, Loc);
  11372. Var->setReferenced(true);
  11373. Var->markUsed(S.Context);
  11374. }
  11375. // Actually capture the variable.
  11376. if (BuildAndDiagnose)
  11377. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11378. SourceLocation(), CaptureType, CopyExpr);
  11379. return true;
  11380. }
  11381. /// \brief Create a field within the lambda class for the variable
  11382. /// being captured.
  11383. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11384. QualType FieldType, QualType DeclRefType,
  11385. SourceLocation Loc,
  11386. bool RefersToCapturedVariable) {
  11387. CXXRecordDecl *Lambda = LSI->Lambda;
  11388. // Build the non-static data member.
  11389. FieldDecl *Field
  11390. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11391. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11392. nullptr, false, ICIS_NoInit);
  11393. Field->setImplicit(true);
  11394. Field->setAccess(AS_private);
  11395. Lambda->addDecl(Field);
  11396. }
  11397. /// \brief Capture the given variable in the lambda.
  11398. static bool captureInLambda(LambdaScopeInfo *LSI,
  11399. VarDecl *Var,
  11400. SourceLocation Loc,
  11401. const bool BuildAndDiagnose,
  11402. QualType &CaptureType,
  11403. QualType &DeclRefType,
  11404. const bool RefersToCapturedVariable,
  11405. const Sema::TryCaptureKind Kind,
  11406. SourceLocation EllipsisLoc,
  11407. const bool IsTopScope,
  11408. Sema &S) {
  11409. // Determine whether we are capturing by reference or by value.
  11410. bool ByRef = false;
  11411. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11412. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11413. } else {
  11414. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11415. }
  11416. // Compute the type of the field that will capture this variable.
  11417. if (ByRef) {
  11418. // C++11 [expr.prim.lambda]p15:
  11419. // An entity is captured by reference if it is implicitly or
  11420. // explicitly captured but not captured by copy. It is
  11421. // unspecified whether additional unnamed non-static data
  11422. // members are declared in the closure type for entities
  11423. // captured by reference.
  11424. //
  11425. // FIXME: It is not clear whether we want to build an lvalue reference
  11426. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11427. // to do the former, while EDG does the latter. Core issue 1249 will
  11428. // clarify, but for now we follow GCC because it's a more permissive and
  11429. // easily defensible position.
  11430. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11431. } else {
  11432. // C++11 [expr.prim.lambda]p14:
  11433. // For each entity captured by copy, an unnamed non-static
  11434. // data member is declared in the closure type. The
  11435. // declaration order of these members is unspecified. The type
  11436. // of such a data member is the type of the corresponding
  11437. // captured entity if the entity is not a reference to an
  11438. // object, or the referenced type otherwise. [Note: If the
  11439. // captured entity is a reference to a function, the
  11440. // corresponding data member is also a reference to a
  11441. // function. - end note ]
  11442. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11443. if (!RefType->getPointeeType()->isFunctionType())
  11444. CaptureType = RefType->getPointeeType();
  11445. }
  11446. // Forbid the lambda copy-capture of autoreleasing variables.
  11447. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11448. if (BuildAndDiagnose) {
  11449. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11450. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11451. << Var->getDeclName();
  11452. }
  11453. return false;
  11454. }
  11455. // Make sure that by-copy captures are of a complete and non-abstract type.
  11456. if (BuildAndDiagnose) {
  11457. if (!CaptureType->isDependentType() &&
  11458. S.RequireCompleteType(Loc, CaptureType,
  11459. diag::err_capture_of_incomplete_type,
  11460. Var->getDeclName()))
  11461. return false;
  11462. if (S.RequireNonAbstractType(Loc, CaptureType,
  11463. diag::err_capture_of_abstract_type))
  11464. return false;
  11465. }
  11466. }
  11467. // Capture this variable in the lambda.
  11468. if (BuildAndDiagnose)
  11469. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11470. RefersToCapturedVariable);
  11471. // Compute the type of a reference to this captured variable.
  11472. if (ByRef)
  11473. DeclRefType = CaptureType.getNonReferenceType();
  11474. else {
  11475. // C++ [expr.prim.lambda]p5:
  11476. // The closure type for a lambda-expression has a public inline
  11477. // function call operator [...]. This function call operator is
  11478. // declared const (9.3.1) if and only if the lambda-expression’s
  11479. // parameter-declaration-clause is not followed by mutable.
  11480. DeclRefType = CaptureType.getNonReferenceType();
  11481. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11482. DeclRefType.addConst();
  11483. }
  11484. // Add the capture.
  11485. if (BuildAndDiagnose)
  11486. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11487. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11488. return true;
  11489. }
  11490. bool Sema::tryCaptureVariable(
  11491. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11492. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11493. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11494. // An init-capture is notionally from the context surrounding its
  11495. // declaration, but its parent DC is the lambda class.
  11496. DeclContext *VarDC = Var->getDeclContext();
  11497. if (Var->isInitCapture())
  11498. VarDC = VarDC->getParent();
  11499. DeclContext *DC = CurContext;
  11500. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11501. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11502. // We need to sync up the Declaration Context with the
  11503. // FunctionScopeIndexToStopAt
  11504. if (FunctionScopeIndexToStopAt) {
  11505. unsigned FSIndex = FunctionScopes.size() - 1;
  11506. while (FSIndex != MaxFunctionScopesIndex) {
  11507. DC = getLambdaAwareParentOfDeclContext(DC);
  11508. --FSIndex;
  11509. }
  11510. }
  11511. // If the variable is declared in the current context, there is no need to
  11512. // capture it.
  11513. if (VarDC == DC) return true;
  11514. // Capture global variables if it is required to use private copy of this
  11515. // variable.
  11516. bool IsGlobal = !Var->hasLocalStorage();
  11517. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11518. return true;
  11519. // Walk up the stack to determine whether we can capture the variable,
  11520. // performing the "simple" checks that don't depend on type. We stop when
  11521. // we've either hit the declared scope of the variable or find an existing
  11522. // capture of that variable. We start from the innermost capturing-entity
  11523. // (the DC) and ensure that all intervening capturing-entities
  11524. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11525. // declcontext can either capture the variable or have already captured
  11526. // the variable.
  11527. CaptureType = Var->getType();
  11528. DeclRefType = CaptureType.getNonReferenceType();
  11529. bool Nested = false;
  11530. bool Explicit = (Kind != TryCapture_Implicit);
  11531. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11532. unsigned OpenMPLevel = 0;
  11533. do {
  11534. // Only block literals, captured statements, and lambda expressions can
  11535. // capture; other scopes don't work.
  11536. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11537. ExprLoc,
  11538. BuildAndDiagnose,
  11539. *this);
  11540. // We need to check for the parent *first* because, if we *have*
  11541. // private-captured a global variable, we need to recursively capture it in
  11542. // intermediate blocks, lambdas, etc.
  11543. if (!ParentDC) {
  11544. if (IsGlobal) {
  11545. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11546. break;
  11547. }
  11548. return true;
  11549. }
  11550. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11551. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11552. // Check whether we've already captured it.
  11553. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11554. DeclRefType))
  11555. break;
  11556. if (getLangOpts().OpenMP) {
  11557. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11558. // OpenMP private variables should not be captured in outer scope, so
  11559. // just break here.
  11560. if (RSI->CapRegionKind == CR_OpenMP) {
  11561. if (isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11562. Nested = true;
  11563. DeclRefType = DeclRefType.getUnqualifiedType();
  11564. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11565. break;
  11566. }
  11567. ++OpenMPLevel;
  11568. }
  11569. }
  11570. }
  11571. // If we are instantiating a generic lambda call operator body,
  11572. // we do not want to capture new variables. What was captured
  11573. // during either a lambdas transformation or initial parsing
  11574. // should be used.
  11575. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11576. if (BuildAndDiagnose) {
  11577. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11578. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11579. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11580. Diag(Var->getLocation(), diag::note_previous_decl)
  11581. << Var->getDeclName();
  11582. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11583. } else
  11584. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11585. }
  11586. return true;
  11587. }
  11588. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11589. // certain types of variables (unnamed, variably modified types etc.)
  11590. // so check for eligibility.
  11591. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11592. return true;
  11593. // Try to capture variable-length arrays types.
  11594. if (Var->getType()->isVariablyModifiedType()) {
  11595. // We're going to walk down into the type and look for VLA
  11596. // expressions.
  11597. QualType QTy = Var->getType();
  11598. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11599. QTy = PVD->getOriginalType();
  11600. do {
  11601. const Type *Ty = QTy.getTypePtr();
  11602. switch (Ty->getTypeClass()) {
  11603. #define TYPE(Class, Base)
  11604. #define ABSTRACT_TYPE(Class, Base)
  11605. #define NON_CANONICAL_TYPE(Class, Base)
  11606. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11607. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11608. #include "clang/AST/TypeNodes.def"
  11609. QTy = QualType();
  11610. break;
  11611. // These types are never variably-modified.
  11612. case Type::Builtin:
  11613. case Type::Complex:
  11614. case Type::Vector:
  11615. case Type::ExtVector:
  11616. case Type::Record:
  11617. case Type::Enum:
  11618. case Type::Elaborated:
  11619. case Type::TemplateSpecialization:
  11620. case Type::ObjCObject:
  11621. case Type::ObjCInterface:
  11622. case Type::ObjCObjectPointer:
  11623. llvm_unreachable("type class is never variably-modified!");
  11624. case Type::Adjusted:
  11625. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11626. break;
  11627. case Type::Decayed:
  11628. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11629. break;
  11630. case Type::Pointer:
  11631. QTy = cast<PointerType>(Ty)->getPointeeType();
  11632. break;
  11633. case Type::BlockPointer:
  11634. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11635. break;
  11636. case Type::LValueReference:
  11637. case Type::RValueReference:
  11638. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11639. break;
  11640. case Type::MemberPointer:
  11641. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11642. break;
  11643. case Type::ConstantArray:
  11644. case Type::IncompleteArray:
  11645. // Losing element qualification here is fine.
  11646. QTy = cast<ArrayType>(Ty)->getElementType();
  11647. break;
  11648. case Type::VariableArray: {
  11649. // Losing element qualification here is fine.
  11650. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11651. // Unknown size indication requires no size computation.
  11652. // Otherwise, evaluate and record it.
  11653. if (auto Size = VAT->getSizeExpr()) {
  11654. if (!CSI->isVLATypeCaptured(VAT)) {
  11655. RecordDecl *CapRecord = nullptr;
  11656. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11657. CapRecord = LSI->Lambda;
  11658. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11659. CapRecord = CRSI->TheRecordDecl;
  11660. }
  11661. if (CapRecord) {
  11662. auto ExprLoc = Size->getExprLoc();
  11663. auto SizeType = Context.getSizeType();
  11664. // Build the non-static data member.
  11665. auto Field = FieldDecl::Create(
  11666. Context, CapRecord, ExprLoc, ExprLoc,
  11667. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11668. /*BW*/ nullptr, /*Mutable*/ false,
  11669. /*InitStyle*/ ICIS_NoInit);
  11670. Field->setImplicit(true);
  11671. Field->setAccess(AS_private);
  11672. Field->setCapturedVLAType(VAT);
  11673. CapRecord->addDecl(Field);
  11674. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11675. }
  11676. }
  11677. }
  11678. QTy = VAT->getElementType();
  11679. break;
  11680. }
  11681. case Type::FunctionProto:
  11682. case Type::FunctionNoProto:
  11683. QTy = cast<FunctionType>(Ty)->getReturnType();
  11684. break;
  11685. case Type::Paren:
  11686. case Type::TypeOf:
  11687. case Type::UnaryTransform:
  11688. case Type::Attributed:
  11689. case Type::SubstTemplateTypeParm:
  11690. case Type::PackExpansion:
  11691. // Keep walking after single level desugaring.
  11692. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11693. break;
  11694. case Type::Typedef:
  11695. QTy = cast<TypedefType>(Ty)->desugar();
  11696. break;
  11697. case Type::Decltype:
  11698. QTy = cast<DecltypeType>(Ty)->desugar();
  11699. break;
  11700. case Type::Auto:
  11701. QTy = cast<AutoType>(Ty)->getDeducedType();
  11702. break;
  11703. case Type::TypeOfExpr:
  11704. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11705. break;
  11706. case Type::Atomic:
  11707. QTy = cast<AtomicType>(Ty)->getValueType();
  11708. break;
  11709. }
  11710. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11711. }
  11712. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11713. // No capture-default, and this is not an explicit capture
  11714. // so cannot capture this variable.
  11715. if (BuildAndDiagnose) {
  11716. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11717. Diag(Var->getLocation(), diag::note_previous_decl)
  11718. << Var->getDeclName();
  11719. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11720. diag::note_lambda_decl);
  11721. // FIXME: If we error out because an outer lambda can not implicitly
  11722. // capture a variable that an inner lambda explicitly captures, we
  11723. // should have the inner lambda do the explicit capture - because
  11724. // it makes for cleaner diagnostics later. This would purely be done
  11725. // so that the diagnostic does not misleadingly claim that a variable
  11726. // can not be captured by a lambda implicitly even though it is captured
  11727. // explicitly. Suggestion:
  11728. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11729. // at the function head
  11730. // - cache the StartingDeclContext - this must be a lambda
  11731. // - captureInLambda in the innermost lambda the variable.
  11732. }
  11733. return true;
  11734. }
  11735. FunctionScopesIndex--;
  11736. DC = ParentDC;
  11737. Explicit = false;
  11738. } while (!VarDC->Equals(DC));
  11739. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11740. // computing the type of the capture at each step, checking type-specific
  11741. // requirements, and adding captures if requested.
  11742. // If the variable had already been captured previously, we start capturing
  11743. // at the lambda nested within that one.
  11744. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11745. ++I) {
  11746. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11747. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11748. if (!captureInBlock(BSI, Var, ExprLoc,
  11749. BuildAndDiagnose, CaptureType,
  11750. DeclRefType, Nested, *this))
  11751. return true;
  11752. Nested = true;
  11753. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11754. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11755. BuildAndDiagnose, CaptureType,
  11756. DeclRefType, Nested, *this))
  11757. return true;
  11758. Nested = true;
  11759. } else {
  11760. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11761. if (!captureInLambda(LSI, Var, ExprLoc,
  11762. BuildAndDiagnose, CaptureType,
  11763. DeclRefType, Nested, Kind, EllipsisLoc,
  11764. /*IsTopScope*/I == N - 1, *this))
  11765. return true;
  11766. Nested = true;
  11767. }
  11768. }
  11769. return false;
  11770. }
  11771. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11772. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11773. QualType CaptureType;
  11774. QualType DeclRefType;
  11775. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11776. /*BuildAndDiagnose=*/true, CaptureType,
  11777. DeclRefType, nullptr);
  11778. }
  11779. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11780. QualType CaptureType;
  11781. QualType DeclRefType;
  11782. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11783. /*BuildAndDiagnose=*/false, CaptureType,
  11784. DeclRefType, nullptr);
  11785. }
  11786. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11787. QualType CaptureType;
  11788. QualType DeclRefType;
  11789. // Determine whether we can capture this variable.
  11790. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11791. /*BuildAndDiagnose=*/false, CaptureType,
  11792. DeclRefType, nullptr))
  11793. return QualType();
  11794. return DeclRefType;
  11795. }
  11796. // If either the type of the variable or the initializer is dependent,
  11797. // return false. Otherwise, determine whether the variable is a constant
  11798. // expression. Use this if you need to know if a variable that might or
  11799. // might not be dependent is truly a constant expression.
  11800. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11801. ASTContext &Context) {
  11802. if (Var->getType()->isDependentType())
  11803. return false;
  11804. const VarDecl *DefVD = nullptr;
  11805. Var->getAnyInitializer(DefVD);
  11806. if (!DefVD)
  11807. return false;
  11808. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11809. Expr *Init = cast<Expr>(Eval->Value);
  11810. if (Init->isValueDependent())
  11811. return false;
  11812. return IsVariableAConstantExpression(Var, Context);
  11813. }
  11814. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11815. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11816. // an object that satisfies the requirements for appearing in a
  11817. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11818. // is immediately applied." This function handles the lvalue-to-rvalue
  11819. // conversion part.
  11820. MaybeODRUseExprs.erase(E->IgnoreParens());
  11821. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11822. // to a variable that is a constant expression, and if so, identify it as
  11823. // a reference to a variable that does not involve an odr-use of that
  11824. // variable.
  11825. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11826. Expr *SansParensExpr = E->IgnoreParens();
  11827. VarDecl *Var = nullptr;
  11828. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11829. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11830. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11831. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11832. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11833. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11834. }
  11835. }
  11836. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11837. Res = CorrectDelayedTyposInExpr(Res);
  11838. if (!Res.isUsable())
  11839. return Res;
  11840. // If a constant-expression is a reference to a variable where we delay
  11841. // deciding whether it is an odr-use, just assume we will apply the
  11842. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11843. // (a non-type template argument), we have special handling anyway.
  11844. UpdateMarkingForLValueToRValue(Res.get());
  11845. return Res;
  11846. }
  11847. void Sema::CleanupVarDeclMarking() {
  11848. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11849. e = MaybeODRUseExprs.end();
  11850. i != e; ++i) {
  11851. VarDecl *Var;
  11852. SourceLocation Loc;
  11853. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11854. Var = cast<VarDecl>(DRE->getDecl());
  11855. Loc = DRE->getLocation();
  11856. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11857. Var = cast<VarDecl>(ME->getMemberDecl());
  11858. Loc = ME->getMemberLoc();
  11859. } else {
  11860. llvm_unreachable("Unexpected expression");
  11861. }
  11862. MarkVarDeclODRUsed(Var, Loc, *this,
  11863. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11864. }
  11865. MaybeODRUseExprs.clear();
  11866. }
  11867. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11868. VarDecl *Var, Expr *E) {
  11869. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11870. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11871. Var->setReferenced();
  11872. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11873. bool MarkODRUsed = true;
  11874. // If the context is not potentially evaluated, this is not an odr-use and
  11875. // does not trigger instantiation.
  11876. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11877. if (SemaRef.isUnevaluatedContext())
  11878. return;
  11879. // If we don't yet know whether this context is going to end up being an
  11880. // evaluated context, and we're referencing a variable from an enclosing
  11881. // scope, add a potential capture.
  11882. //
  11883. // FIXME: Is this necessary? These contexts are only used for default
  11884. // arguments, where local variables can't be used.
  11885. const bool RefersToEnclosingScope =
  11886. (SemaRef.CurContext != Var->getDeclContext() &&
  11887. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11888. if (RefersToEnclosingScope) {
  11889. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11890. // If a variable could potentially be odr-used, defer marking it so
  11891. // until we finish analyzing the full expression for any
  11892. // lvalue-to-rvalue
  11893. // or discarded value conversions that would obviate odr-use.
  11894. // Add it to the list of potential captures that will be analyzed
  11895. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11896. // unless the variable is a reference that was initialized by a constant
  11897. // expression (this will never need to be captured or odr-used).
  11898. assert(E && "Capture variable should be used in an expression.");
  11899. if (!Var->getType()->isReferenceType() ||
  11900. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11901. LSI->addPotentialCapture(E->IgnoreParens());
  11902. }
  11903. }
  11904. if (!isTemplateInstantiation(TSK))
  11905. return;
  11906. // Instantiate, but do not mark as odr-used, variable templates.
  11907. MarkODRUsed = false;
  11908. }
  11909. VarTemplateSpecializationDecl *VarSpec =
  11910. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11911. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11912. "Can't instantiate a partial template specialization.");
  11913. // Perform implicit instantiation of static data members, static data member
  11914. // templates of class templates, and variable template specializations. Delay
  11915. // instantiations of variable templates, except for those that could be used
  11916. // in a constant expression.
  11917. if (isTemplateInstantiation(TSK)) {
  11918. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11919. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11920. if (Var->getPointOfInstantiation().isInvalid()) {
  11921. // This is a modification of an existing AST node. Notify listeners.
  11922. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11923. L->StaticDataMemberInstantiated(Var);
  11924. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11925. // Don't bother trying to instantiate it again, unless we might need
  11926. // its initializer before we get to the end of the TU.
  11927. TryInstantiating = false;
  11928. }
  11929. if (Var->getPointOfInstantiation().isInvalid())
  11930. Var->setTemplateSpecializationKind(TSK, Loc);
  11931. if (TryInstantiating) {
  11932. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11933. bool InstantiationDependent = false;
  11934. bool IsNonDependent =
  11935. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11936. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11937. : true;
  11938. // Do not instantiate specializations that are still type-dependent.
  11939. if (IsNonDependent) {
  11940. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11941. // Do not defer instantiations of variables which could be used in a
  11942. // constant expression.
  11943. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11944. } else {
  11945. SemaRef.PendingInstantiations
  11946. .push_back(std::make_pair(Var, PointOfInstantiation));
  11947. }
  11948. }
  11949. }
  11950. }
  11951. if(!MarkODRUsed) return;
  11952. // HLSL Change Begin -External variable is in cbuffer, cannot use as immediate.
  11953. // Mark used for referenced external variable.
  11954. if (SemaRef.getLangOpts().HLSL && Var->hasExternalFormalLinkage() &&
  11955. !isa<EnumConstantDecl>(Var))
  11956. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11957. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11958. // HLSL Change End.
  11959. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11960. // the requirements for appearing in a constant expression (5.19) and, if
  11961. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11962. // is immediately applied." We check the first part here, and
  11963. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11964. // Note that we use the C++11 definition everywhere because nothing in
  11965. // C++03 depends on whether we get the C++03 version correct. The second
  11966. // part does not apply to references, since they are not objects.
  11967. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11968. // A reference initialized by a constant expression can never be
  11969. // odr-used, so simply ignore it.
  11970. if (!Var->getType()->isReferenceType())
  11971. SemaRef.MaybeODRUseExprs.insert(E);
  11972. } else
  11973. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11974. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11975. }
  11976. /// \brief Mark a variable referenced, and check whether it is odr-used
  11977. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11978. /// used directly for normal expressions referring to VarDecl.
  11979. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11980. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11981. }
  11982. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11983. Decl *D, Expr *E, bool OdrUse) {
  11984. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11985. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11986. return;
  11987. }
  11988. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11989. // If this is a call to a method via a cast, also mark the method in the
  11990. // derived class used in case codegen can devirtualize the call.
  11991. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11992. if (!ME)
  11993. return;
  11994. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11995. if (!MD)
  11996. return;
  11997. // Only attempt to devirtualize if this is truly a virtual call.
  11998. bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
  11999. if (!IsVirtualCall)
  12000. return;
  12001. const Expr *Base = ME->getBase();
  12002. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  12003. if (!MostDerivedClassDecl)
  12004. return;
  12005. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  12006. if (!DM || DM->isPure())
  12007. return;
  12008. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  12009. }
  12010. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  12011. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  12012. // TODO: update this with DR# once a defect report is filed.
  12013. // C++11 defect. The address of a pure member should not be an ODR use, even
  12014. // if it's a qualified reference.
  12015. bool OdrUse = true;
  12016. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  12017. if (Method->isVirtual())
  12018. OdrUse = false;
  12019. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  12020. }
  12021. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  12022. void Sema::MarkMemberReferenced(MemberExpr *E) {
  12023. // C++11 [basic.def.odr]p2:
  12024. // A non-overloaded function whose name appears as a potentially-evaluated
  12025. // expression or a member of a set of candidate functions, if selected by
  12026. // overload resolution when referred to from a potentially-evaluated
  12027. // expression, is odr-used, unless it is a pure virtual function and its
  12028. // name is not explicitly qualified.
  12029. bool OdrUse = true;
  12030. if (!E->hasQualifier()) {
  12031. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  12032. if (Method->isPure())
  12033. OdrUse = false;
  12034. }
  12035. SourceLocation Loc = E->getMemberLoc().isValid() ?
  12036. E->getMemberLoc() : E->getLocStart();
  12037. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  12038. }
  12039. /// \brief Perform marking for a reference to an arbitrary declaration. It
  12040. /// marks the declaration referenced, and performs odr-use checking for
  12041. /// functions and variables. This method should not be used when building a
  12042. /// normal expression which refers to a variable.
  12043. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  12044. if (OdrUse) {
  12045. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12046. MarkVariableReferenced(Loc, VD);
  12047. return;
  12048. }
  12049. }
  12050. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  12051. MarkFunctionReferenced(Loc, FD, OdrUse);
  12052. return;
  12053. }
  12054. D->setReferenced();
  12055. }
  12056. namespace {
  12057. // Mark all of the declarations referenced
  12058. // FIXME: Not fully implemented yet! We need to have a better understanding
  12059. // of when we're entering
  12060. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  12061. Sema &S;
  12062. SourceLocation Loc;
  12063. public:
  12064. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  12065. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  12066. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  12067. bool TraverseRecordType(RecordType *T);
  12068. };
  12069. }
  12070. bool MarkReferencedDecls::TraverseTemplateArgument(
  12071. const TemplateArgument &Arg) {
  12072. if (Arg.getKind() == TemplateArgument::Declaration) {
  12073. if (Decl *D = Arg.getAsDecl())
  12074. S.MarkAnyDeclReferenced(Loc, D, true);
  12075. }
  12076. return Inherited::TraverseTemplateArgument(Arg);
  12077. }
  12078. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  12079. if (ClassTemplateSpecializationDecl *Spec
  12080. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  12081. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  12082. return TraverseTemplateArguments(Args.data(), Args.size());
  12083. }
  12084. return true;
  12085. }
  12086. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  12087. MarkReferencedDecls Marker(*this, Loc);
  12088. Marker.TraverseType(Context.getCanonicalType(T));
  12089. }
  12090. namespace {
  12091. /// \brief Helper class that marks all of the declarations referenced by
  12092. /// potentially-evaluated subexpressions as "referenced".
  12093. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  12094. Sema &S;
  12095. bool SkipLocalVariables;
  12096. public:
  12097. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  12098. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  12099. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  12100. void VisitDeclRefExpr(DeclRefExpr *E) {
  12101. // If we were asked not to visit local variables, don't.
  12102. if (SkipLocalVariables) {
  12103. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  12104. if (VD->hasLocalStorage())
  12105. return;
  12106. }
  12107. S.MarkDeclRefReferenced(E);
  12108. }
  12109. void VisitMemberExpr(MemberExpr *E) {
  12110. S.MarkMemberReferenced(E);
  12111. Inherited::VisitMemberExpr(E);
  12112. }
  12113. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  12114. S.MarkFunctionReferenced(E->getLocStart(),
  12115. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  12116. Visit(E->getSubExpr());
  12117. }
  12118. void VisitCXXNewExpr(CXXNewExpr *E) {
  12119. if (E->getOperatorNew())
  12120. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  12121. if (E->getOperatorDelete())
  12122. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12123. Inherited::VisitCXXNewExpr(E);
  12124. }
  12125. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  12126. if (E->getOperatorDelete())
  12127. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12128. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  12129. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  12130. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  12131. S.MarkFunctionReferenced(E->getLocStart(),
  12132. S.LookupDestructor(Record));
  12133. }
  12134. Inherited::VisitCXXDeleteExpr(E);
  12135. }
  12136. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  12137. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  12138. Inherited::VisitCXXConstructExpr(E);
  12139. }
  12140. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  12141. Visit(E->getExpr());
  12142. }
  12143. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12144. Inherited::VisitImplicitCastExpr(E);
  12145. if (E->getCastKind() == CK_LValueToRValue)
  12146. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  12147. }
  12148. };
  12149. }
  12150. /// \brief Mark any declarations that appear within this expression or any
  12151. /// potentially-evaluated subexpressions as "referenced".
  12152. ///
  12153. /// \param SkipLocalVariables If true, don't mark local variables as
  12154. /// 'referenced'.
  12155. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  12156. bool SkipLocalVariables) {
  12157. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  12158. }
  12159. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  12160. /// of the program being compiled.
  12161. ///
  12162. /// This routine emits the given diagnostic when the code currently being
  12163. /// type-checked is "potentially evaluated", meaning that there is a
  12164. /// possibility that the code will actually be executable. Code in sizeof()
  12165. /// expressions, code used only during overload resolution, etc., are not
  12166. /// potentially evaluated. This routine will suppress such diagnostics or,
  12167. /// in the absolutely nutty case of potentially potentially evaluated
  12168. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  12169. /// later.
  12170. ///
  12171. /// This routine should be used for all diagnostics that describe the run-time
  12172. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  12173. /// Failure to do so will likely result in spurious diagnostics or failures
  12174. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  12175. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  12176. const PartialDiagnostic &PD) {
  12177. switch (ExprEvalContexts.back().Context) {
  12178. case Unevaluated:
  12179. case UnevaluatedAbstract:
  12180. // The argument will never be evaluated, so don't complain.
  12181. break;
  12182. case ConstantEvaluated:
  12183. // Relevant diagnostics should be produced by constant evaluation.
  12184. break;
  12185. case PotentiallyEvaluated:
  12186. case PotentiallyEvaluatedIfUsed:
  12187. if (Statement && getCurFunctionOrMethodDecl()) {
  12188. FunctionScopes.back()->PossiblyUnreachableDiags.
  12189. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  12190. }
  12191. else
  12192. Diag(Loc, PD);
  12193. return true;
  12194. }
  12195. return false;
  12196. }
  12197. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  12198. CallExpr *CE, FunctionDecl *FD) {
  12199. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  12200. return false;
  12201. // If we're inside a decltype's expression, don't check for a valid return
  12202. // type or construct temporaries until we know whether this is the last call.
  12203. if (ExprEvalContexts.back().IsDecltype) {
  12204. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  12205. return false;
  12206. }
  12207. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  12208. FunctionDecl *FD;
  12209. CallExpr *CE;
  12210. public:
  12211. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  12212. : FD(FD), CE(CE) { }
  12213. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  12214. if (!FD) {
  12215. S.Diag(Loc, diag::err_call_incomplete_return)
  12216. << T << CE->getSourceRange();
  12217. return;
  12218. }
  12219. S.Diag(Loc, diag::err_call_function_incomplete_return)
  12220. << CE->getSourceRange() << FD->getDeclName() << T;
  12221. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  12222. << FD->getDeclName();
  12223. }
  12224. } Diagnoser(FD, CE);
  12225. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  12226. return true;
  12227. return false;
  12228. }
  12229. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  12230. // will prevent this condition from triggering, which is what we want.
  12231. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  12232. SourceLocation Loc;
  12233. unsigned diagnostic = diag::warn_condition_is_assignment;
  12234. bool IsOrAssign = false;
  12235. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  12236. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  12237. return;
  12238. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  12239. // Greylist some idioms by putting them into a warning subcategory.
  12240. if (ObjCMessageExpr *ME
  12241. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  12242. Selector Sel = ME->getSelector();
  12243. // self = [<foo> init...]
  12244. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  12245. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12246. // <foo> = [<bar> nextObject]
  12247. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  12248. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12249. }
  12250. Loc = Op->getOperatorLoc();
  12251. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  12252. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  12253. return;
  12254. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  12255. Loc = Op->getOperatorLoc();
  12256. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  12257. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  12258. else {
  12259. // Not an assignment.
  12260. return;
  12261. }
  12262. Diag(Loc, diagnostic) << E->getSourceRange();
  12263. SourceLocation Open = E->getLocStart();
  12264. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  12265. Diag(Loc, diag::note_condition_assign_silence)
  12266. << FixItHint::CreateInsertion(Open, "(")
  12267. << FixItHint::CreateInsertion(Close, ")");
  12268. if (IsOrAssign)
  12269. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  12270. << FixItHint::CreateReplacement(Loc, "!=");
  12271. else
  12272. Diag(Loc, diag::note_condition_assign_to_comparison)
  12273. << FixItHint::CreateReplacement(Loc, "==");
  12274. }
  12275. /// \brief Redundant parentheses over an equality comparison can indicate
  12276. /// that the user intended an assignment used as condition.
  12277. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  12278. // Don't warn if the parens came from a macro.
  12279. SourceLocation parenLoc = ParenE->getLocStart();
  12280. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  12281. return;
  12282. // Don't warn for dependent expressions.
  12283. if (ParenE->isTypeDependent())
  12284. return;
  12285. Expr *E = ParenE->IgnoreParens();
  12286. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12287. if (opE->getOpcode() == BO_EQ &&
  12288. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12289. == Expr::MLV_Valid) {
  12290. SourceLocation Loc = opE->getOperatorLoc();
  12291. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12292. SourceRange ParenERange = ParenE->getSourceRange();
  12293. Diag(Loc, diag::note_equality_comparison_silence)
  12294. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12295. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12296. Diag(Loc, diag::note_equality_comparison_to_assign)
  12297. << FixItHint::CreateReplacement(Loc, "=");
  12298. }
  12299. }
  12300. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12301. DiagnoseAssignmentAsCondition(E);
  12302. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12303. DiagnoseEqualityWithExtraParens(parenE);
  12304. ExprResult result = CheckPlaceholderExpr(E);
  12305. if (result.isInvalid()) return ExprError();
  12306. E = result.get();
  12307. if (!E->isTypeDependent()) {
  12308. if (getLangOpts().CPlusPlus)
  12309. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12310. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12311. if (ERes.isInvalid())
  12312. return ExprError();
  12313. E = ERes.get();
  12314. QualType T = E->getType();
  12315. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12316. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12317. << T << E->getSourceRange();
  12318. return ExprError();
  12319. }
  12320. CheckBoolLikeConversion(E, Loc);
  12321. }
  12322. return E;
  12323. }
  12324. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12325. Expr *SubExpr) {
  12326. if (!SubExpr)
  12327. return ExprError();
  12328. return CheckBooleanCondition(SubExpr, Loc);
  12329. }
  12330. namespace {
  12331. /// A visitor for rebuilding a call to an __unknown_any expression
  12332. /// to have an appropriate type.
  12333. struct RebuildUnknownAnyFunction
  12334. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12335. Sema &S;
  12336. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12337. ExprResult VisitStmt(Stmt *S) {
  12338. llvm_unreachable("unexpected statement!");
  12339. }
  12340. ExprResult VisitExpr(Expr *E) {
  12341. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12342. << E->getSourceRange();
  12343. return ExprError();
  12344. }
  12345. /// Rebuild an expression which simply semantically wraps another
  12346. /// expression which it shares the type and value kind of.
  12347. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12348. ExprResult SubResult = Visit(E->getSubExpr());
  12349. if (SubResult.isInvalid()) return ExprError();
  12350. Expr *SubExpr = SubResult.get();
  12351. E->setSubExpr(SubExpr);
  12352. E->setType(SubExpr->getType());
  12353. E->setValueKind(SubExpr->getValueKind());
  12354. assert(E->getObjectKind() == OK_Ordinary);
  12355. return E;
  12356. }
  12357. ExprResult VisitParenExpr(ParenExpr *E) {
  12358. return rebuildSugarExpr(E);
  12359. }
  12360. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12361. return rebuildSugarExpr(E);
  12362. }
  12363. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12364. ExprResult SubResult = Visit(E->getSubExpr());
  12365. if (SubResult.isInvalid()) return ExprError();
  12366. Expr *SubExpr = SubResult.get();
  12367. E->setSubExpr(SubExpr);
  12368. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12369. assert(E->getValueKind() == VK_RValue);
  12370. assert(E->getObjectKind() == OK_Ordinary);
  12371. return E;
  12372. }
  12373. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12374. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12375. E->setType(VD->getType());
  12376. assert(E->getValueKind() == VK_RValue);
  12377. if (S.getLangOpts().CPlusPlus &&
  12378. !(isa<CXXMethodDecl>(VD) &&
  12379. cast<CXXMethodDecl>(VD)->isInstance()))
  12380. E->setValueKind(VK_LValue);
  12381. return E;
  12382. }
  12383. ExprResult VisitMemberExpr(MemberExpr *E) {
  12384. return resolveDecl(E, E->getMemberDecl());
  12385. }
  12386. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12387. return resolveDecl(E, E->getDecl());
  12388. }
  12389. };
  12390. }
  12391. /// Given a function expression of unknown-any type, try to rebuild it
  12392. /// to have a function type.
  12393. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12394. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12395. if (Result.isInvalid()) return ExprError();
  12396. return S.DefaultFunctionArrayConversion(Result.get());
  12397. }
  12398. namespace {
  12399. /// A visitor for rebuilding an expression of type __unknown_anytype
  12400. /// into one which resolves the type directly on the referring
  12401. /// expression. Strict preservation of the original source
  12402. /// structure is not a goal.
  12403. struct RebuildUnknownAnyExpr
  12404. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12405. Sema &S;
  12406. /// The current destination type.
  12407. QualType DestType;
  12408. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12409. : S(S), DestType(CastType) {}
  12410. ExprResult VisitStmt(Stmt *S) {
  12411. llvm_unreachable("unexpected statement!");
  12412. }
  12413. ExprResult VisitExpr(Expr *E) {
  12414. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12415. << E->getSourceRange();
  12416. return ExprError();
  12417. }
  12418. ExprResult VisitCallExpr(CallExpr *E);
  12419. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12420. /// Rebuild an expression which simply semantically wraps another
  12421. /// expression which it shares the type and value kind of.
  12422. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12423. ExprResult SubResult = Visit(E->getSubExpr());
  12424. if (SubResult.isInvalid()) return ExprError();
  12425. Expr *SubExpr = SubResult.get();
  12426. E->setSubExpr(SubExpr);
  12427. E->setType(SubExpr->getType());
  12428. E->setValueKind(SubExpr->getValueKind());
  12429. assert(E->getObjectKind() == OK_Ordinary);
  12430. return E;
  12431. }
  12432. ExprResult VisitParenExpr(ParenExpr *E) {
  12433. return rebuildSugarExpr(E);
  12434. }
  12435. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12436. return rebuildSugarExpr(E);
  12437. }
  12438. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12439. const PointerType *Ptr = DestType->getAs<PointerType>();
  12440. if (!Ptr) {
  12441. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12442. << E->getSourceRange();
  12443. return ExprError();
  12444. }
  12445. assert(E->getValueKind() == VK_RValue);
  12446. assert(E->getObjectKind() == OK_Ordinary);
  12447. E->setType(DestType);
  12448. // Build the sub-expression as if it were an object of the pointee type.
  12449. DestType = Ptr->getPointeeType();
  12450. ExprResult SubResult = Visit(E->getSubExpr());
  12451. if (SubResult.isInvalid()) return ExprError();
  12452. E->setSubExpr(SubResult.get());
  12453. return E;
  12454. }
  12455. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12456. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12457. ExprResult VisitMemberExpr(MemberExpr *E) {
  12458. return resolveDecl(E, E->getMemberDecl());
  12459. }
  12460. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12461. return resolveDecl(E, E->getDecl());
  12462. }
  12463. };
  12464. }
  12465. /// Rebuilds a call expression which yielded __unknown_anytype.
  12466. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12467. Expr *CalleeExpr = E->getCallee();
  12468. enum FnKind {
  12469. FK_MemberFunction,
  12470. FK_FunctionPointer,
  12471. FK_BlockPointer
  12472. };
  12473. FnKind Kind;
  12474. QualType CalleeType = CalleeExpr->getType();
  12475. if (CalleeType == S.Context.BoundMemberTy) {
  12476. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12477. Kind = FK_MemberFunction;
  12478. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12479. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12480. CalleeType = Ptr->getPointeeType();
  12481. Kind = FK_FunctionPointer;
  12482. } else {
  12483. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12484. Kind = FK_BlockPointer;
  12485. }
  12486. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12487. // Verify that this is a legal result type of a function.
  12488. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12489. unsigned diagID = diag::err_func_returning_array_function;
  12490. if (Kind == FK_BlockPointer)
  12491. diagID = diag::err_block_returning_array_function;
  12492. S.Diag(E->getExprLoc(), diagID)
  12493. << DestType->isFunctionType() << DestType;
  12494. return ExprError();
  12495. }
  12496. // Otherwise, go ahead and set DestType as the call's result.
  12497. E->setType(DestType.getNonLValueExprType(S.Context));
  12498. E->setValueKind(Expr::getValueKindForType(DestType));
  12499. assert(E->getObjectKind() == OK_Ordinary);
  12500. // Rebuild the function type, replacing the result type with DestType.
  12501. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12502. if (Proto) {
  12503. // __unknown_anytype(...) is a special case used by the debugger when
  12504. // it has no idea what a function's signature is.
  12505. //
  12506. // We want to build this call essentially under the K&R
  12507. // unprototyped rules, but making a FunctionNoProtoType in C++
  12508. // would foul up all sorts of assumptions. However, we cannot
  12509. // simply pass all arguments as variadic arguments, nor can we
  12510. // portably just call the function under a non-variadic type; see
  12511. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12512. // However, it turns out that in practice it is generally safe to
  12513. // call a function declared as "A foo(B,C,D);" under the prototype
  12514. // "A foo(B,C,D,...);". The only known exception is with the
  12515. // Windows ABI, where any variadic function is implicitly cdecl
  12516. // regardless of its normal CC. Therefore we change the parameter
  12517. // types to match the types of the arguments.
  12518. //
  12519. // This is a hack, but it is far superior to moving the
  12520. // corresponding target-specific code from IR-gen to Sema/AST.
  12521. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12522. SmallVector<QualType, 8> ArgTypes;
  12523. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12524. ArgTypes.reserve(E->getNumArgs());
  12525. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12526. Expr *Arg = E->getArg(i);
  12527. QualType ArgType = Arg->getType();
  12528. if (E->isLValue()) {
  12529. ArgType = S.Context.getLValueReferenceType(ArgType);
  12530. } else if (E->isXValue()) {
  12531. ArgType = S.Context.getRValueReferenceType(ArgType);
  12532. }
  12533. ArgTypes.push_back(ArgType);
  12534. }
  12535. ParamTypes = ArgTypes;
  12536. }
  12537. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12538. Proto->getExtProtoInfo(),
  12539. Proto->getParamMods()); // HLSL Change - assume args are preserved
  12540. } else {
  12541. DestType = S.Context.getFunctionNoProtoType(DestType,
  12542. FnType->getExtInfo());
  12543. }
  12544. // Rebuild the appropriate pointer-to-function type.
  12545. switch (Kind) {
  12546. case FK_MemberFunction:
  12547. // Nothing to do.
  12548. break;
  12549. case FK_FunctionPointer:
  12550. DestType = S.Context.getPointerType(DestType);
  12551. break;
  12552. case FK_BlockPointer:
  12553. DestType = S.Context.getBlockPointerType(DestType);
  12554. break;
  12555. }
  12556. // Finally, we can recurse.
  12557. ExprResult CalleeResult = Visit(CalleeExpr);
  12558. if (!CalleeResult.isUsable()) return ExprError();
  12559. E->setCallee(CalleeResult.get());
  12560. // Bind a temporary if necessary.
  12561. return S.MaybeBindToTemporary(E);
  12562. }
  12563. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12564. // Verify that this is a legal result type of a call.
  12565. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12566. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12567. << DestType->isFunctionType() << DestType;
  12568. return ExprError();
  12569. }
  12570. // Rewrite the method result type if available.
  12571. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12572. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12573. Method->setReturnType(DestType);
  12574. }
  12575. // Change the type of the message.
  12576. E->setType(DestType.getNonReferenceType());
  12577. E->setValueKind(Expr::getValueKindForType(DestType));
  12578. return S.MaybeBindToTemporary(E);
  12579. }
  12580. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12581. // The only case we should ever see here is a function-to-pointer decay.
  12582. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12583. assert(E->getValueKind() == VK_RValue);
  12584. assert(E->getObjectKind() == OK_Ordinary);
  12585. E->setType(DestType);
  12586. // Rebuild the sub-expression as the pointee (function) type.
  12587. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12588. ExprResult Result = Visit(E->getSubExpr());
  12589. if (!Result.isUsable()) return ExprError();
  12590. E->setSubExpr(Result.get());
  12591. return E;
  12592. } else if (E->getCastKind() == CK_LValueToRValue) {
  12593. assert(E->getValueKind() == VK_RValue);
  12594. assert(E->getObjectKind() == OK_Ordinary);
  12595. assert(isa<BlockPointerType>(E->getType()));
  12596. E->setType(DestType);
  12597. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12598. DestType = S.Context.getLValueReferenceType(DestType);
  12599. ExprResult Result = Visit(E->getSubExpr());
  12600. if (!Result.isUsable()) return ExprError();
  12601. E->setSubExpr(Result.get());
  12602. return E;
  12603. } else {
  12604. llvm_unreachable("Unhandled cast type!");
  12605. }
  12606. }
  12607. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12608. ExprValueKind ValueKind = VK_LValue;
  12609. QualType Type = DestType;
  12610. // We know how to make this work for certain kinds of decls:
  12611. // - functions
  12612. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12613. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12614. DestType = Ptr->getPointeeType();
  12615. ExprResult Result = resolveDecl(E, VD);
  12616. if (Result.isInvalid()) return ExprError();
  12617. return S.ImpCastExprToType(Result.get(), Type,
  12618. CK_FunctionToPointerDecay, VK_RValue);
  12619. }
  12620. if (!Type->isFunctionType()) {
  12621. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12622. << VD << E->getSourceRange();
  12623. return ExprError();
  12624. }
  12625. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12626. // We must match the FunctionDecl's type to the hack introduced in
  12627. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12628. // type. See the lengthy commentary in that routine.
  12629. QualType FDT = FD->getType();
  12630. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12631. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12632. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12633. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12634. SourceLocation Loc = FD->getLocation();
  12635. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12636. FD->getDeclContext(),
  12637. Loc, Loc, FD->getNameInfo().getName(),
  12638. DestType, FD->getTypeSourceInfo(),
  12639. SC_None, false/*isInlineSpecified*/,
  12640. FD->hasPrototype(),
  12641. false/*isConstexprSpecified*/);
  12642. if (FD->getQualifier())
  12643. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12644. SmallVector<ParmVarDecl*, 16> Params;
  12645. for (const auto &AI : FT->param_types()) {
  12646. ParmVarDecl *Param =
  12647. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12648. Param->setScopeInfo(0, Params.size());
  12649. Params.push_back(Param);
  12650. }
  12651. NewFD->setParams(Params);
  12652. DRE->setDecl(NewFD);
  12653. VD = DRE->getDecl();
  12654. }
  12655. }
  12656. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12657. if (MD->isInstance()) {
  12658. ValueKind = VK_RValue;
  12659. Type = S.Context.BoundMemberTy;
  12660. }
  12661. // Function references aren't l-values in C.
  12662. if (!S.getLangOpts().CPlusPlus)
  12663. ValueKind = VK_RValue;
  12664. // - variables
  12665. } else if (isa<VarDecl>(VD)) {
  12666. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12667. Type = RefTy->getPointeeType();
  12668. } else if (Type->isFunctionType()) {
  12669. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12670. << VD << E->getSourceRange();
  12671. return ExprError();
  12672. }
  12673. // - nothing else
  12674. } else {
  12675. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12676. << VD << E->getSourceRange();
  12677. return ExprError();
  12678. }
  12679. // Modifying the declaration like this is friendly to IR-gen but
  12680. // also really dangerous.
  12681. VD->setType(DestType);
  12682. E->setType(Type);
  12683. E->setValueKind(ValueKind);
  12684. return E;
  12685. }
  12686. /// Check a cast of an unknown-any type. We intentionally only
  12687. /// trigger this for C-style casts.
  12688. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12689. Expr *CastExpr, CastKind &CastKind,
  12690. ExprValueKind &VK, CXXCastPath &Path) {
  12691. // Rewrite the casted expression from scratch.
  12692. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12693. if (!result.isUsable()) return ExprError();
  12694. CastExpr = result.get();
  12695. VK = CastExpr->getValueKind();
  12696. CastKind = CK_NoOp;
  12697. return CastExpr;
  12698. }
  12699. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12700. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12701. }
  12702. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12703. Expr *arg, QualType &paramType) {
  12704. // If the syntactic form of the argument is not an explicit cast of
  12705. // any sort, just do default argument promotion.
  12706. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12707. if (!castArg) {
  12708. ExprResult result = DefaultArgumentPromotion(arg);
  12709. if (result.isInvalid()) return ExprError();
  12710. paramType = result.get()->getType();
  12711. return result;
  12712. }
  12713. // Otherwise, use the type that was written in the explicit cast.
  12714. assert(!arg->hasPlaceholderType());
  12715. paramType = castArg->getTypeAsWritten();
  12716. // Copy-initialize a parameter of that type.
  12717. InitializedEntity entity =
  12718. InitializedEntity::InitializeParameter(Context, paramType,
  12719. /*consumed*/ false);
  12720. return PerformCopyInitialization(entity, callLoc, arg);
  12721. }
  12722. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12723. Expr *orig = E;
  12724. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12725. while (true) {
  12726. E = E->IgnoreParenImpCasts();
  12727. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12728. E = call->getCallee();
  12729. diagID = diag::err_uncasted_call_of_unknown_any;
  12730. } else {
  12731. break;
  12732. }
  12733. }
  12734. SourceLocation loc;
  12735. NamedDecl *d;
  12736. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12737. loc = ref->getLocation();
  12738. d = ref->getDecl();
  12739. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12740. loc = mem->getMemberLoc();
  12741. d = mem->getMemberDecl();
  12742. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12743. diagID = diag::err_uncasted_call_of_unknown_any;
  12744. loc = msg->getSelectorStartLoc();
  12745. d = msg->getMethodDecl();
  12746. if (!d) {
  12747. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12748. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12749. << orig->getSourceRange();
  12750. return ExprError();
  12751. }
  12752. } else {
  12753. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12754. << E->getSourceRange();
  12755. return ExprError();
  12756. }
  12757. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12758. // Never recoverable.
  12759. return ExprError();
  12760. }
  12761. /// Check for operands with placeholder types and complain if found.
  12762. /// Returns true if there was an error and no recovery was possible.
  12763. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12764. if (!getLangOpts().CPlusPlus) {
  12765. // C cannot handle TypoExpr nodes on either side of a binop because it
  12766. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12767. // been dealt with before checking the operands.
  12768. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12769. if (!Result.isUsable()) return ExprError();
  12770. E = Result.get();
  12771. }
  12772. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12773. if (!placeholderType) return E;
  12774. switch (placeholderType->getKind()) {
  12775. // Overloaded expressions.
  12776. case BuiltinType::Overload: {
  12777. // Try to resolve a single function template specialization.
  12778. // This is obligatory.
  12779. ExprResult result = E;
  12780. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12781. return result;
  12782. // If that failed, try to recover with a call.
  12783. } else {
  12784. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12785. /*complain*/ true);
  12786. return result;
  12787. }
  12788. }
  12789. // Bound member functions.
  12790. case BuiltinType::BoundMember: {
  12791. ExprResult result = E;
  12792. const Expr *BME = E->IgnoreParens();
  12793. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12794. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12795. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12796. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12797. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12798. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12799. DeclarationName::CXXDestructorName)
  12800. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12801. }
  12802. tryToRecoverWithCall(result, PD,
  12803. /*complain*/ true);
  12804. return result;
  12805. }
  12806. // ARC unbridged casts.
  12807. case BuiltinType::ARCUnbridgedCast: {
  12808. Expr *realCast = stripARCUnbridgedCast(E);
  12809. diagnoseARCUnbridgedCast(realCast);
  12810. return realCast;
  12811. }
  12812. // Expressions of unknown type.
  12813. case BuiltinType::UnknownAny:
  12814. return diagnoseUnknownAnyExpr(*this, E);
  12815. // Pseudo-objects.
  12816. case BuiltinType::PseudoObject:
  12817. return checkPseudoObjectRValue(E);
  12818. case BuiltinType::BuiltinFn: {
  12819. // Accept __noop without parens by implicitly converting it to a call expr.
  12820. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12821. if (DRE) {
  12822. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12823. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12824. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12825. CK_BuiltinFnToFnPtr).get();
  12826. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12827. VK_RValue, SourceLocation());
  12828. }
  12829. }
  12830. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12831. return ExprError();
  12832. }
  12833. // Everything else should be impossible.
  12834. #define BUILTIN_TYPE(Id, SingletonId) \
  12835. case BuiltinType::Id:
  12836. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12837. #include "clang/AST/BuiltinTypes.def"
  12838. break;
  12839. }
  12840. llvm_unreachable("invalid placeholder type!");
  12841. }
  12842. bool Sema::CheckCaseExpression(Expr *E) {
  12843. if (E->isTypeDependent())
  12844. return true;
  12845. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12846. return E->getType()->isIntegralOrEnumerationType();
  12847. return false;
  12848. }
  12849. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12850. ExprResult
  12851. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12852. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12853. "Unknown Objective-C Boolean value!");
  12854. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12855. if (!Context.getBOOLDecl()) {
  12856. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12857. Sema::LookupOrdinaryName);
  12858. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12859. NamedDecl *ND = Result.getFoundDecl();
  12860. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12861. Context.setBOOLDecl(TD);
  12862. }
  12863. }
  12864. if (Context.getBOOLDecl())
  12865. BoolT = Context.getBOOLType();
  12866. return new (Context)
  12867. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12868. }