SemaExpr.cpp 564 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650
  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. return false;
  2418. // Only in C++ or ObjC++.
  2419. if (!getLangOpts().CPlusPlus)
  2420. return false;
  2421. // Turn off ADL when we find certain kinds of declarations during
  2422. // normal lookup:
  2423. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2424. NamedDecl *D = *I;
  2425. // C++0x [basic.lookup.argdep]p3:
  2426. // -- a declaration of a class member
  2427. // Since using decls preserve this property, we check this on the
  2428. // original decl.
  2429. if (D->isCXXClassMember())
  2430. return false;
  2431. // C++0x [basic.lookup.argdep]p3:
  2432. // -- a block-scope function declaration that is not a
  2433. // using-declaration
  2434. // NOTE: we also trigger this for function templates (in fact, we
  2435. // don't check the decl type at all, since all other decl types
  2436. // turn off ADL anyway).
  2437. if (isa<UsingShadowDecl>(D))
  2438. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2439. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2440. return false;
  2441. // C++0x [basic.lookup.argdep]p3:
  2442. // -- a declaration that is neither a function or a function
  2443. // template
  2444. // And also for builtin functions.
  2445. if (isa<FunctionDecl>(D)) {
  2446. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2447. // But also builtin functions.
  2448. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2449. return false;
  2450. } else if (!isa<FunctionTemplateDecl>(D))
  2451. return false;
  2452. }
  2453. return true;
  2454. }
  2455. /// Diagnoses obvious problems with the use of the given declaration
  2456. /// as an expression. This is only actually called for lookups that
  2457. /// were not overloaded, and it doesn't promise that the declaration
  2458. /// will in fact be used.
  2459. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2460. if (isa<TypedefNameDecl>(D)) {
  2461. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2462. return true;
  2463. }
  2464. if (isa<ObjCInterfaceDecl>(D)) {
  2465. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2466. return true;
  2467. }
  2468. if (isa<NamespaceDecl>(D)) {
  2469. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2470. return true;
  2471. }
  2472. return false;
  2473. }
  2474. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2475. LookupResult &R, bool NeedsADL,
  2476. bool AcceptInvalidDecl) {
  2477. // If this is a single, fully-resolved result and we don't need ADL,
  2478. // just build an ordinary singleton decl ref.
  2479. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2480. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2481. R.getRepresentativeDecl(), nullptr,
  2482. AcceptInvalidDecl);
  2483. // We only need to check the declaration if there's exactly one
  2484. // result, because in the overloaded case the results can only be
  2485. // functions and function templates.
  2486. if (R.isSingleResult() &&
  2487. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2488. return ExprError();
  2489. // Otherwise, just build an unresolved lookup expression. Suppress
  2490. // any lookup-related diagnostics; we'll hash these out later, when
  2491. // we've picked a target.
  2492. R.suppressDiagnostics();
  2493. UnresolvedLookupExpr *ULE
  2494. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2495. SS.getWithLocInContext(Context),
  2496. R.getLookupNameInfo(),
  2497. NeedsADL, R.isOverloadedResult(),
  2498. R.begin(), R.end());
  2499. return ULE;
  2500. }
  2501. /// \brief Complete semantic analysis for a reference to the given declaration.
  2502. ExprResult Sema::BuildDeclarationNameExpr(
  2503. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2504. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2505. bool AcceptInvalidDecl) {
  2506. assert(D && "Cannot refer to a NULL declaration");
  2507. assert(!isa<FunctionTemplateDecl>(D) &&
  2508. "Cannot refer unambiguously to a function template");
  2509. SourceLocation Loc = NameInfo.getLoc();
  2510. if (CheckDeclInExpr(*this, Loc, D))
  2511. return ExprError();
  2512. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2513. // Specifically diagnose references to class templates that are missing
  2514. // a template argument list.
  2515. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2516. << Template << SS.getRange();
  2517. if (Template->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  2518. Diag(Template->getLocation(), diag::note_template_decl_here);
  2519. }
  2520. return ExprError();
  2521. }
  2522. // Make sure that we're referring to a value.
  2523. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2524. if (!VD) {
  2525. Diag(Loc, diag::err_ref_non_value)
  2526. << D << SS.getRange();
  2527. Diag(D->getLocation(), diag::note_declared_at);
  2528. return ExprError();
  2529. }
  2530. // Check whether this declaration can be used. Note that we suppress
  2531. // this check when we're going to perform argument-dependent lookup
  2532. // on this function name, because this might not be the function
  2533. // that overload resolution actually selects.
  2534. if (DiagnoseUseOfDecl(VD, Loc))
  2535. return ExprError();
  2536. // Only create DeclRefExpr's for valid Decl's.
  2537. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2538. return ExprError();
  2539. // Handle members of anonymous structs and unions. If we got here,
  2540. // and the reference is to a class member indirect field, then this
  2541. // must be the subject of a pointer-to-member expression.
  2542. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2543. if (!indirectField->isCXXClassMember())
  2544. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2545. indirectField);
  2546. {
  2547. QualType type = VD->getType();
  2548. ExprValueKind valueKind = VK_RValue;
  2549. switch (D->getKind()) {
  2550. // Ignore all the non-ValueDecl kinds.
  2551. #define ABSTRACT_DECL(kind)
  2552. #define VALUE(type, base)
  2553. #define DECL(type, base) \
  2554. case Decl::type:
  2555. #include "clang/AST/DeclNodes.inc"
  2556. llvm_unreachable("invalid value decl kind");
  2557. // These shouldn't make it here.
  2558. case Decl::ObjCAtDefsField:
  2559. case Decl::ObjCIvar:
  2560. llvm_unreachable("forming non-member reference to ivar?");
  2561. // Enum constants are always r-values and never references.
  2562. // Unresolved using declarations are dependent.
  2563. case Decl::EnumConstant:
  2564. case Decl::UnresolvedUsingValue:
  2565. valueKind = VK_RValue;
  2566. break;
  2567. // Fields and indirect fields that got here must be for
  2568. // pointer-to-member expressions; we just call them l-values for
  2569. // internal consistency, because this subexpression doesn't really
  2570. // exist in the high-level semantics.
  2571. case Decl::Field:
  2572. case Decl::IndirectField:
  2573. assert(getLangOpts().CPlusPlus &&
  2574. "building reference to field in C?");
  2575. // These can't have reference type in well-formed programs, but
  2576. // for internal consistency we do this anyway.
  2577. type = type.getNonReferenceType();
  2578. valueKind = VK_LValue;
  2579. break;
  2580. // Non-type template parameters are either l-values or r-values
  2581. // depending on the type.
  2582. case Decl::NonTypeTemplateParm: {
  2583. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2584. type = reftype->getPointeeType();
  2585. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2586. break;
  2587. }
  2588. // For non-references, we need to strip qualifiers just in case
  2589. // the template parameter was declared as 'const int' or whatever.
  2590. valueKind = VK_RValue;
  2591. type = type.getUnqualifiedType();
  2592. break;
  2593. }
  2594. case Decl::Var:
  2595. case Decl::VarTemplateSpecialization:
  2596. case Decl::VarTemplatePartialSpecialization:
  2597. // In C, "extern void blah;" is valid and is an r-value.
  2598. if (!getLangOpts().CPlusPlus &&
  2599. !type.hasQualifiers() &&
  2600. type->isVoidType()) {
  2601. valueKind = VK_RValue;
  2602. break;
  2603. }
  2604. // fallthrough
  2605. case Decl::ImplicitParam:
  2606. case Decl::ParmVar: {
  2607. // These are always l-values.
  2608. valueKind = VK_LValue;
  2609. type = type.getNonReferenceType();
  2610. // FIXME: Does the addition of const really only apply in
  2611. // potentially-evaluated contexts? Since the variable isn't actually
  2612. // captured in an unevaluated context, it seems that the answer is no.
  2613. if (!isUnevaluatedContext()) {
  2614. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2615. if (!CapturedType.isNull())
  2616. type = CapturedType;
  2617. }
  2618. break;
  2619. }
  2620. case Decl::Function: {
  2621. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2622. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2623. type = Context.BuiltinFnTy;
  2624. valueKind = VK_RValue;
  2625. break;
  2626. }
  2627. }
  2628. const FunctionType *fty = type->castAs<FunctionType>();
  2629. // If we're referring to a function with an __unknown_anytype
  2630. // result type, make the entire expression __unknown_anytype.
  2631. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2632. type = Context.UnknownAnyTy;
  2633. valueKind = VK_RValue;
  2634. break;
  2635. }
  2636. // Functions are l-values in C++.
  2637. if (getLangOpts().CPlusPlus) {
  2638. valueKind = VK_LValue;
  2639. break;
  2640. }
  2641. // C99 DR 316 says that, if a function type comes from a
  2642. // function definition (without a prototype), that type is only
  2643. // used for checking compatibility. Therefore, when referencing
  2644. // the function, we pretend that we don't have the full function
  2645. // type.
  2646. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2647. isa<FunctionProtoType>(fty))
  2648. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2649. fty->getExtInfo());
  2650. // Functions are r-values in C.
  2651. valueKind = VK_RValue;
  2652. break;
  2653. }
  2654. case Decl::MSProperty:
  2655. valueKind = VK_LValue;
  2656. break;
  2657. case Decl::CXXMethod:
  2658. // If we're referring to a method with an __unknown_anytype
  2659. // result type, make the entire expression __unknown_anytype.
  2660. // This should only be possible with a type written directly.
  2661. if (const FunctionProtoType *proto
  2662. = dyn_cast<FunctionProtoType>(VD->getType()))
  2663. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2664. type = Context.UnknownAnyTy;
  2665. valueKind = VK_RValue;
  2666. break;
  2667. }
  2668. // C++ methods are l-values if static, r-values if non-static.
  2669. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2670. valueKind = VK_LValue;
  2671. break;
  2672. }
  2673. // fallthrough
  2674. case Decl::CXXConversion:
  2675. case Decl::CXXDestructor:
  2676. case Decl::CXXConstructor:
  2677. valueKind = VK_RValue;
  2678. break;
  2679. }
  2680. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2681. TemplateArgs);
  2682. }
  2683. }
  2684. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2685. SmallString<32> &Target) {
  2686. Target.resize(CharByteWidth * (Source.size() + 1));
  2687. char *ResultPtr = &Target[0];
  2688. const UTF8 *ErrorPtr;
  2689. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2690. (void)success;
  2691. assert(success);
  2692. Target.resize(ResultPtr - &Target[0]);
  2693. }
  2694. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2695. PredefinedExpr::IdentType IT) {
  2696. // Pick the current block, lambda, captured statement or function.
  2697. Decl *currentDecl = nullptr;
  2698. if (const BlockScopeInfo *BSI = getCurBlock())
  2699. currentDecl = BSI->TheDecl;
  2700. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2701. currentDecl = LSI->CallOperator;
  2702. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2703. currentDecl = CSI->TheCapturedDecl;
  2704. else
  2705. currentDecl = getCurFunctionOrMethodDecl();
  2706. if (!currentDecl) {
  2707. Diag(Loc, diag::ext_predef_outside_function);
  2708. currentDecl = Context.getTranslationUnitDecl();
  2709. }
  2710. QualType ResTy;
  2711. StringLiteral *SL = nullptr;
  2712. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2713. ResTy = Context.DependentTy;
  2714. else {
  2715. // Pre-defined identifiers are of type char[x], where x is the length of
  2716. // the string.
  2717. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2718. unsigned Length = Str.length();
  2719. llvm::APInt LengthI(32, Length + 1);
  2720. if (IT == PredefinedExpr::LFunction) {
  2721. ResTy = Context.WideCharTy.withConst();
  2722. SmallString<32> RawChars;
  2723. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2724. Str, RawChars);
  2725. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2726. /*IndexTypeQuals*/ 0);
  2727. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2728. /*Pascal*/ false, ResTy, Loc);
  2729. } else {
  2730. ResTy = Context.CharTy.withConst();
  2731. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2732. /*IndexTypeQuals*/ 0);
  2733. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2734. /*Pascal*/ false, ResTy, Loc);
  2735. }
  2736. }
  2737. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2738. }
  2739. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2740. PredefinedExpr::IdentType IT;
  2741. switch (Kind) {
  2742. default: llvm_unreachable("Unknown simple primary expr!");
  2743. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2744. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2745. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2746. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2747. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2748. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2749. }
  2750. return BuildPredefinedExpr(Loc, IT);
  2751. }
  2752. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2753. SmallString<16> CharBuffer;
  2754. bool Invalid = false;
  2755. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2756. if (Invalid)
  2757. return ExprError();
  2758. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2759. PP, Tok.getKind());
  2760. if (Literal.hadError())
  2761. return ExprError();
  2762. // HLSL Change Starts
  2763. if (getLangOpts().HLSL) {
  2764. if (Literal.isWide() || Literal.isUTF16() || Literal.isUTF32() || Literal.isMultiChar()) {
  2765. Diag(Tok.getLocation(), diag::err_hlsl_unsupported_char_literal);
  2766. return ExprError();
  2767. }
  2768. Expr *CharLit = new (Context)CharacterLiteral(Literal.getValue(), CharacterLiteral::Ascii, Context.CharTy,
  2769. Tok.getLocation());
  2770. Expr* Result = ImplicitCastExpr::Create(Context,
  2771. Context.UnsignedIntTy, CK_IntegralCast, CharLit, nullptr, VK_RValue);
  2772. return Result;
  2773. }
  2774. // HLSL Change Ends
  2775. QualType Ty;
  2776. if (Literal.isWide())
  2777. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2778. else if (Literal.isUTF16())
  2779. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2780. else if (Literal.isUTF32())
  2781. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2782. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2783. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2784. else
  2785. Ty = Context.CharTy; // 'x' -> char in C++
  2786. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2787. if (Literal.isWide())
  2788. Kind = CharacterLiteral::Wide;
  2789. else if (Literal.isUTF16())
  2790. Kind = CharacterLiteral::UTF16;
  2791. else if (Literal.isUTF32())
  2792. Kind = CharacterLiteral::UTF32;
  2793. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2794. Tok.getLocation());
  2795. if (Literal.getUDSuffix().empty())
  2796. return Lit;
  2797. // We're building a user-defined literal.
  2798. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2799. SourceLocation UDSuffixLoc =
  2800. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2801. // Make sure we're allowed user-defined literals here.
  2802. if (!UDLScope)
  2803. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2804. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2805. // operator "" X (ch)
  2806. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2807. Lit, Tok.getLocation());
  2808. }
  2809. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2810. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2811. // HLSL Change Starts - HLSL literal int
  2812. QualType Ty;
  2813. if (getLangOpts().HLSL) {
  2814. IntSize = 64;
  2815. Ty = Context.LitIntTy;
  2816. } else
  2817. Ty = Context.IntTy;
  2818. // HLSL Change Ends
  2819. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2820. Ty, Loc); // HLSL Change
  2821. }
  2822. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2823. QualType Ty, SourceLocation Loc) {
  2824. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2825. using llvm::APFloat;
  2826. APFloat Val(Format);
  2827. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2828. // Overflow is always an error, but underflow is only an error if
  2829. // we underflowed to zero (APFloat reports denormals as underflow).
  2830. if ((result & APFloat::opOverflow) ||
  2831. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2832. unsigned diagnostic;
  2833. SmallString<20> buffer;
  2834. if (result & APFloat::opOverflow) {
  2835. diagnostic = diag::warn_float_overflow;
  2836. APFloat::getLargest(Format).toString(buffer);
  2837. } else {
  2838. diagnostic = diag::warn_float_underflow;
  2839. APFloat::getSmallest(Format).toString(buffer);
  2840. }
  2841. S.Diag(Loc, diagnostic)
  2842. << Ty
  2843. << StringRef(buffer.data(), buffer.size());
  2844. }
  2845. bool isExact = (result == APFloat::opOK);
  2846. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2847. }
  2848. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2849. assert(E && "Invalid expression");
  2850. if (E->isValueDependent())
  2851. return false;
  2852. QualType QT = E->getType();
  2853. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2854. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2855. return true;
  2856. }
  2857. llvm::APSInt ValueAPS;
  2858. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2859. if (R.isInvalid())
  2860. return true;
  2861. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2862. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2863. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2864. << ValueAPS.toString(10) << ValueIsPositive;
  2865. return true;
  2866. }
  2867. return false;
  2868. }
  2869. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2870. // Fast path for a single digit (which is quite common). A single digit
  2871. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2872. if (Tok.getLength() == 1) {
  2873. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2874. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2875. }
  2876. SmallString<128> SpellingBuffer;
  2877. // NumericLiteralParser wants to overread by one character. Add padding to
  2878. // the buffer in case the token is copied to the buffer. If getSpelling()
  2879. // returns a StringRef to the memory buffer, it should have a null char at
  2880. // the EOF, so it is also safe.
  2881. SpellingBuffer.resize(Tok.getLength() + 1);
  2882. // Get the spelling of the token, which eliminates trigraphs, etc.
  2883. bool Invalid = false;
  2884. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2885. if (Invalid)
  2886. return ExprError();
  2887. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2888. if (Literal.hadError)
  2889. return ExprError();
  2890. if (Literal.hasUDSuffix()) {
  2891. // We're building a user-defined literal.
  2892. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2893. SourceLocation UDSuffixLoc =
  2894. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2895. // Make sure we're allowed user-defined literals here.
  2896. if (!UDLScope)
  2897. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2898. QualType CookedTy;
  2899. if (Literal.isFloatingLiteral()) {
  2900. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2901. // long double, the literal is treated as a call of the form
  2902. // operator "" X (f L)
  2903. CookedTy = Context.LongDoubleTy;
  2904. } else {
  2905. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2906. // unsigned long long, the literal is treated as a call of the form
  2907. // operator "" X (n ULL)
  2908. CookedTy = Context.UnsignedLongLongTy;
  2909. }
  2910. DeclarationName OpName =
  2911. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2912. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2913. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2914. SourceLocation TokLoc = Tok.getLocation();
  2915. // Perform literal operator lookup to determine if we're building a raw
  2916. // literal or a cooked one.
  2917. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2918. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2919. /*AllowRaw*/true, /*AllowTemplate*/true,
  2920. /*AllowStringTemplate*/false)) {
  2921. case LOLR_Error:
  2922. return ExprError();
  2923. case LOLR_Cooked: {
  2924. Expr *Lit;
  2925. if (Literal.isFloatingLiteral()) {
  2926. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2927. } else {
  2928. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2929. if (Literal.GetIntegerValue(ResultVal))
  2930. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2931. << /* Unsigned */ 1;
  2932. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2933. Tok.getLocation());
  2934. }
  2935. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2936. }
  2937. case LOLR_Raw: {
  2938. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2939. // literal is treated as a call of the form
  2940. // operator "" X ("n")
  2941. unsigned Length = Literal.getUDSuffixOffset();
  2942. QualType StrTy = Context.getConstantArrayType(
  2943. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2944. ArrayType::Normal, 0);
  2945. Expr *Lit = StringLiteral::Create(
  2946. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2947. /*Pascal*/false, StrTy, &TokLoc, 1);
  2948. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2949. }
  2950. case LOLR_Template: {
  2951. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2952. // template), L is treated as a call fo the form
  2953. // operator "" X <'c1', 'c2', ... 'ck'>()
  2954. // where n is the source character sequence c1 c2 ... ck.
  2955. TemplateArgumentListInfo ExplicitArgs;
  2956. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2957. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2958. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2959. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2960. Value = TokSpelling[I];
  2961. TemplateArgument Arg(Context, Value, Context.CharTy);
  2962. TemplateArgumentLocInfo ArgInfo;
  2963. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2964. }
  2965. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2966. &ExplicitArgs);
  2967. }
  2968. case LOLR_StringTemplate:
  2969. llvm_unreachable("unexpected literal operator lookup result");
  2970. }
  2971. }
  2972. Expr *Res;
  2973. if (Literal.isFloatingLiteral()) {
  2974. QualType Ty;
  2975. if (Literal.isFloat)
  2976. Ty = Context.FloatTy;
  2977. // HLSL Change Starts
  2978. else if (getLangOpts().HLSL && !Literal.isLong && !Literal.isHalf)
  2979. Ty = Context.LitFloatTy;
  2980. else if (getLangOpts().HLSL && Literal.isLong)
  2981. Ty = Context.DoubleTy;
  2982. else if (getLangOpts().HLSL && Literal.isHalf) {
  2983. Ty = getLangOpts().UseMinPrecision ? Context.FloatTy : Context.HalfTy;
  2984. }
  2985. // HLSL Change Ends
  2986. else if (!Literal.isLong)
  2987. Ty = Context.DoubleTy;
  2988. else
  2989. Ty = Context.LongDoubleTy;
  2990. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2991. if (Ty == Context.DoubleTy) {
  2992. if (getLangOpts().SinglePrecisionConstants) {
  2993. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2994. } else if (getLangOpts().OpenCL &&
  2995. !((getLangOpts().OpenCLVersion >= 120) ||
  2996. getOpenCLOptions().cl_khr_fp64)) {
  2997. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2998. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2999. }
  3000. }
  3001. } else if (!Literal.isIntegerLiteral()) {
  3002. return ExprError();
  3003. // HLSL Change Starts
  3004. } else if (getLangOpts().HLSL) {
  3005. QualType Ty;
  3006. unsigned Width = 64;
  3007. llvm::APInt ResultVal(Width, 0);
  3008. if (!Literal.isLong && !Literal.isLongLong && !Literal.isUnsigned) {
  3009. // in HLSL, unspecific literal ints are LitIntTy, using 64-bit
  3010. Ty = Context.LitIntTy;
  3011. if (Literal.GetIntegerValue(ResultVal)) {
  3012. // If this value didn't fit into 64-bit literal int, report error.
  3013. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  3014. }
  3015. } else {
  3016. if (Literal.GetIntegerValue(ResultVal)) {
  3017. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  3018. }
  3019. if (Literal.isLongLong) {
  3020. if (Literal.isUnsigned)
  3021. Ty = Context.UnsignedLongLongTy;
  3022. else
  3023. Ty = Context.LongLongTy;
  3024. }
  3025. else {
  3026. // long is the same as int for HLSL, so ignore isLong here
  3027. Width = 32;
  3028. ResultVal = ResultVal.trunc(Width);
  3029. if (Literal.isUnsigned || Literal.getRadix() != 10)
  3030. Ty = Context.UnsignedIntTy;
  3031. else
  3032. Ty = Context.IntTy;
  3033. }
  3034. }
  3035. return IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3036. // HLSL Change Ends
  3037. } else {
  3038. QualType Ty;
  3039. // 'long long' is a C99 or C++11 feature.
  3040. if (!getLangOpts().C99 && Literal.isLongLong) {
  3041. if (getLangOpts().CPlusPlus)
  3042. Diag(Tok.getLocation(),
  3043. getLangOpts().CPlusPlus11 ?
  3044. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3045. else
  3046. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3047. }
  3048. // Get the value in the widest-possible width.
  3049. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3050. // The microsoft literal suffix extensions support 128-bit literals, which
  3051. // may be wider than [u]intmax_t.
  3052. // FIXME: Actually, they don't. We seem to have accidentally invented the
  3053. // i128 suffix.
  3054. if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
  3055. Context.getTargetInfo().hasInt128Type())
  3056. MaxWidth = 128;
  3057. llvm::APInt ResultVal(MaxWidth, 0);
  3058. if (Literal.GetIntegerValue(ResultVal)) {
  3059. // If this value didn't fit into uintmax_t, error and force to ull.
  3060. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3061. << /* Unsigned */ 1;
  3062. Ty = Context.UnsignedLongLongTy;
  3063. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3064. "long long is not intmax_t?");
  3065. } else {
  3066. // If this value fits into a ULL, try to figure out what else it fits into
  3067. // according to the rules of C99 6.4.4.1p5.
  3068. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3069. // be an unsigned int.
  3070. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3071. // Check from smallest to largest, picking the smallest type we can.
  3072. unsigned Width = 0;
  3073. // Microsoft specific integer suffixes are explicitly sized.
  3074. if (Literal.MicrosoftInteger) {
  3075. if (Literal.MicrosoftInteger > MaxWidth) {
  3076. // If this target doesn't support __int128, error and force to ull.
  3077. Diag(Tok.getLocation(), diag::err_int128_unsupported);
  3078. Width = MaxWidth;
  3079. Ty = Context.getIntMaxType();
  3080. } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3081. Width = 8;
  3082. Ty = Context.CharTy;
  3083. } else {
  3084. Width = Literal.MicrosoftInteger;
  3085. Ty = Context.getIntTypeForBitwidth(Width,
  3086. /*Signed=*/!Literal.isUnsigned);
  3087. }
  3088. }
  3089. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3090. // Are int/unsigned possibilities?
  3091. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3092. // Does it fit in a unsigned int?
  3093. if (ResultVal.isIntN(IntSize)) {
  3094. // Does it fit in a signed int?
  3095. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3096. Ty = Context.IntTy;
  3097. else if (AllowUnsigned)
  3098. Ty = Context.UnsignedIntTy;
  3099. Width = IntSize;
  3100. }
  3101. }
  3102. // Are long/unsigned long possibilities?
  3103. if (Ty.isNull() && !Literal.isLongLong) {
  3104. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3105. // Does it fit in a unsigned long?
  3106. if (ResultVal.isIntN(LongSize)) {
  3107. // Does it fit in a signed long?
  3108. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3109. Ty = Context.LongTy;
  3110. else if (AllowUnsigned)
  3111. Ty = Context.UnsignedLongTy;
  3112. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3113. // is compatible.
  3114. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3115. const unsigned LongLongSize =
  3116. Context.getTargetInfo().getLongLongWidth();
  3117. Diag(Tok.getLocation(),
  3118. getLangOpts().CPlusPlus
  3119. ? Literal.isLong
  3120. ? diag::warn_old_implicitly_unsigned_long_cxx
  3121. : /*C++98 UB*/ diag::
  3122. ext_old_implicitly_unsigned_long_cxx
  3123. : diag::warn_old_implicitly_unsigned_long)
  3124. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3125. : /*will be ill-formed*/ 1);
  3126. Ty = Context.UnsignedLongTy;
  3127. }
  3128. Width = LongSize;
  3129. }
  3130. }
  3131. // Check long long if needed.
  3132. if (Ty.isNull()) {
  3133. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3134. // Does it fit in a unsigned long long?
  3135. if (ResultVal.isIntN(LongLongSize)) {
  3136. // Does it fit in a signed long long?
  3137. // To be compatible with MSVC, hex integer literals ending with the
  3138. // LL or i64 suffix are always signed in Microsoft mode.
  3139. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3140. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  3141. Ty = Context.LongLongTy;
  3142. else if (AllowUnsigned)
  3143. Ty = Context.UnsignedLongLongTy;
  3144. Width = LongLongSize;
  3145. }
  3146. }
  3147. // If we still couldn't decide a type, we probably have something that
  3148. // does not fit in a signed long long, but has no U suffix.
  3149. if (Ty.isNull()) {
  3150. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3151. Ty = Context.UnsignedLongLongTy;
  3152. Width = Context.getTargetInfo().getLongLongWidth();
  3153. }
  3154. if (ResultVal.getBitWidth() != Width)
  3155. ResultVal = ResultVal.trunc(Width);
  3156. }
  3157. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3158. }
  3159. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3160. if (Literal.isImaginary)
  3161. Res = new (Context) ImaginaryLiteral(Res,
  3162. Context.getComplexType(Res->getType()));
  3163. return Res;
  3164. }
  3165. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3166. assert(E && "ActOnParenExpr() missing expr");
  3167. return new (Context) ParenExpr(L, R, E);
  3168. }
  3169. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3170. SourceLocation Loc,
  3171. SourceRange ArgRange) {
  3172. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3173. // scalar or vector data type argument..."
  3174. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3175. // type (C99 6.2.5p18) or void.
  3176. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3177. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3178. << T << ArgRange;
  3179. return true;
  3180. }
  3181. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3182. "Scalar types should always be complete");
  3183. return false;
  3184. }
  3185. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3186. SourceLocation Loc,
  3187. SourceRange ArgRange,
  3188. UnaryExprOrTypeTrait TraitKind) {
  3189. // Invalid types must be hard errors for SFINAE in C++.
  3190. if (S.LangOpts.CPlusPlus)
  3191. return true;
  3192. // C99 6.5.3.4p1:
  3193. if (T->isFunctionType() &&
  3194. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3195. // sizeof(function)/alignof(function) is allowed as an extension.
  3196. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3197. << TraitKind << ArgRange;
  3198. return false;
  3199. }
  3200. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3201. // this is an error (OpenCL v1.1 s6.3.k)
  3202. if (T->isVoidType()) {
  3203. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3204. : diag::ext_sizeof_alignof_void_type;
  3205. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3206. return false;
  3207. }
  3208. return true;
  3209. }
  3210. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3211. SourceLocation Loc,
  3212. SourceRange ArgRange,
  3213. UnaryExprOrTypeTrait TraitKind) {
  3214. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3215. // runtime doesn't allow it.
  3216. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3217. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3218. << T << (TraitKind == UETT_SizeOf)
  3219. << ArgRange;
  3220. return true;
  3221. }
  3222. return false;
  3223. }
  3224. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3225. /// pointer type is equal to T) and emit a warning if it is.
  3226. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3227. Expr *E) {
  3228. // Don't warn if the operation changed the type.
  3229. if (T != E->getType())
  3230. return;
  3231. // Now look for array decays.
  3232. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3233. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3234. return;
  3235. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3236. << ICE->getType()
  3237. << ICE->getSubExpr()->getType();
  3238. }
  3239. // HLSL Change Begins
  3240. bool Sema::CheckHLSLUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation Loc,
  3241. UnaryExprOrTypeTrait ExprKind) {
  3242. assert(ExprKind == UnaryExprOrTypeTrait::UETT_SizeOf);
  3243. // "sizeof 42" is ill-defined because HLSL has literal int type which can decay to an int of any size.
  3244. const BuiltinType* BuiltinTy = ExprType->getAs<BuiltinType>();
  3245. if (BuiltinTy != nullptr && (BuiltinTy->getKind() == BuiltinType::LitInt || BuiltinTy->getKind() == BuiltinType::LitFloat)) {
  3246. Diag(Loc, diag::err_hlsl_sizeof_literal) << ExprType;
  3247. return true;
  3248. }
  3249. if (!hlsl::IsHLSLNumericOrAggregateOfNumericType(ExprType)) {
  3250. Diag(Loc, diag::err_hlsl_sizeof_nonnumeric) << ExprType;
  3251. return true;
  3252. }
  3253. return false;
  3254. }
  3255. // HLSL Change Ends
  3256. /// \brief Check the constraints on expression operands to unary type expression
  3257. /// and type traits.
  3258. ///
  3259. /// Completes any types necessary and validates the constraints on the operand
  3260. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3261. /// the expression as it completes the type for that expression through template
  3262. /// instantiation, etc.
  3263. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3264. UnaryExprOrTypeTrait ExprKind) {
  3265. QualType ExprTy = E->getType();
  3266. assert(!ExprTy->isReferenceType());
  3267. if (ExprKind == UETT_VecStep)
  3268. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3269. E->getSourceRange());
  3270. // Whitelist some types as extensions
  3271. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3272. E->getSourceRange(), ExprKind))
  3273. return false;
  3274. // 'alignof' applied to an expression only requires the base element type of
  3275. // the expression to be complete. 'sizeof' requires the expression's type to
  3276. // be complete (and will attempt to complete it if it's an array of unknown
  3277. // bound).
  3278. if (ExprKind == UETT_AlignOf) {
  3279. if (RequireCompleteType(E->getExprLoc(),
  3280. Context.getBaseElementType(E->getType()),
  3281. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3282. E->getSourceRange()))
  3283. return true;
  3284. } else {
  3285. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3286. ExprKind, E->getSourceRange()))
  3287. return true;
  3288. }
  3289. // Completing the expression's type may have changed it.
  3290. ExprTy = E->getType();
  3291. assert(!ExprTy->isReferenceType());
  3292. if (getLangOpts().HLSL && CheckHLSLUnaryExprOrTypeTraitOperand(ExprTy, E->getExprLoc(), ExprKind)) {
  3293. return true;
  3294. }
  3295. if (ExprTy->isFunctionType()) {
  3296. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3297. << ExprKind << E->getSourceRange();
  3298. return true;
  3299. }
  3300. // The operand for sizeof and alignof is in an unevaluated expression context,
  3301. // so side effects could result in unintended consequences.
  3302. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3303. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3304. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3305. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3306. E->getSourceRange(), ExprKind))
  3307. return true;
  3308. if (ExprKind == UETT_SizeOf) {
  3309. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3310. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3311. QualType OType = PVD->getOriginalType();
  3312. QualType Type = PVD->getType();
  3313. if (Type->isPointerType() && OType->isArrayType()) {
  3314. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3315. << Type << OType;
  3316. Diag(PVD->getLocation(), diag::note_declared_at);
  3317. }
  3318. }
  3319. }
  3320. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3321. // decays into a pointer and returns an unintended result. This is most
  3322. // likely a typo for "sizeof(array) op x".
  3323. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3324. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3325. BO->getLHS());
  3326. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3327. BO->getRHS());
  3328. }
  3329. }
  3330. return false;
  3331. }
  3332. /// \brief Check the constraints on operands to unary expression and type
  3333. /// traits.
  3334. ///
  3335. /// This will complete any types necessary, and validate the various constraints
  3336. /// on those operands.
  3337. ///
  3338. /// The UsualUnaryConversions() function is *not* called by this routine.
  3339. /// C99 6.3.2.1p[2-4] all state:
  3340. /// Except when it is the operand of the sizeof operator ...
  3341. ///
  3342. /// C++ [expr.sizeof]p4
  3343. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3344. /// standard conversions are not applied to the operand of sizeof.
  3345. ///
  3346. /// This policy is followed for all of the unary trait expressions.
  3347. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3348. SourceLocation OpLoc,
  3349. SourceRange ExprRange,
  3350. UnaryExprOrTypeTrait ExprKind) {
  3351. if (ExprType->isDependentType())
  3352. return false;
  3353. // C++ [expr.sizeof]p2:
  3354. // When applied to a reference or a reference type, the result
  3355. // is the size of the referenced type.
  3356. // C++11 [expr.alignof]p3:
  3357. // When alignof is applied to a reference type, the result
  3358. // shall be the alignment of the referenced type.
  3359. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3360. ExprType = Ref->getPointeeType();
  3361. if (getLangOpts().HLSL && CheckHLSLUnaryExprOrTypeTraitOperand(ExprType, OpLoc, ExprKind)) {
  3362. return true;
  3363. }
  3364. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3365. // When alignof or _Alignof is applied to an array type, the result
  3366. // is the alignment of the element type.
  3367. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3368. ExprType = Context.getBaseElementType(ExprType);
  3369. if (ExprKind == UETT_VecStep)
  3370. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3371. // Whitelist some types as extensions
  3372. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3373. ExprKind))
  3374. return false;
  3375. if (RequireCompleteType(OpLoc, ExprType,
  3376. diag::err_sizeof_alignof_incomplete_type,
  3377. ExprKind, ExprRange))
  3378. return true;
  3379. if (ExprType->isFunctionType()) {
  3380. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3381. << ExprKind << ExprRange;
  3382. return true;
  3383. }
  3384. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3385. ExprKind))
  3386. return true;
  3387. return false;
  3388. }
  3389. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3390. E = E->IgnoreParens();
  3391. // Cannot know anything else if the expression is dependent.
  3392. if (E->isTypeDependent())
  3393. return false;
  3394. if (E->getObjectKind() == OK_BitField) {
  3395. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3396. << 1 << E->getSourceRange();
  3397. return true;
  3398. }
  3399. ValueDecl *D = nullptr;
  3400. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3401. D = DRE->getDecl();
  3402. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3403. D = ME->getMemberDecl();
  3404. }
  3405. // If it's a field, require the containing struct to have a
  3406. // complete definition so that we can compute the layout.
  3407. //
  3408. // This can happen in C++11 onwards, either by naming the member
  3409. // in a way that is not transformed into a member access expression
  3410. // (in an unevaluated operand, for instance), or by naming the member
  3411. // in a trailing-return-type.
  3412. //
  3413. // For the record, since __alignof__ on expressions is a GCC
  3414. // extension, GCC seems to permit this but always gives the
  3415. // nonsensical answer 0.
  3416. //
  3417. // We don't really need the layout here --- we could instead just
  3418. // directly check for all the appropriate alignment-lowing
  3419. // attributes --- but that would require duplicating a lot of
  3420. // logic that just isn't worth duplicating for such a marginal
  3421. // use-case.
  3422. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3423. // Fast path this check, since we at least know the record has a
  3424. // definition if we can find a member of it.
  3425. if (!FD->getParent()->isCompleteDefinition()) {
  3426. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3427. << E->getSourceRange();
  3428. return true;
  3429. }
  3430. // Otherwise, if it's a field, and the field doesn't have
  3431. // reference type, then it must have a complete type (or be a
  3432. // flexible array member, which we explicitly want to
  3433. // white-list anyway), which makes the following checks trivial.
  3434. if (!FD->getType()->isReferenceType())
  3435. return false;
  3436. }
  3437. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3438. }
  3439. bool Sema::CheckVecStepExpr(Expr *E) {
  3440. E = E->IgnoreParens();
  3441. // Cannot know anything else if the expression is dependent.
  3442. if (E->isTypeDependent())
  3443. return false;
  3444. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3445. }
  3446. /// \brief Build a sizeof or alignof expression given a type operand.
  3447. ExprResult
  3448. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3449. SourceLocation OpLoc,
  3450. UnaryExprOrTypeTrait ExprKind,
  3451. SourceRange R) {
  3452. if (!TInfo)
  3453. return ExprError();
  3454. QualType T = TInfo->getType();
  3455. if (!T->isDependentType() &&
  3456. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3457. return ExprError();
  3458. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3459. return new (Context) UnaryExprOrTypeTraitExpr(
  3460. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3461. }
  3462. /// \brief Build a sizeof or alignof expression given an expression
  3463. /// operand.
  3464. ExprResult
  3465. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3466. UnaryExprOrTypeTrait ExprKind) {
  3467. ExprResult PE = CheckPlaceholderExpr(E);
  3468. if (PE.isInvalid())
  3469. return ExprError();
  3470. E = PE.get();
  3471. // Verify that the operand is valid.
  3472. bool isInvalid = false;
  3473. if (E->isTypeDependent()) {
  3474. // Delay type-checking for type-dependent expressions.
  3475. } else if (ExprKind == UETT_AlignOf) {
  3476. isInvalid = CheckAlignOfExpr(*this, E);
  3477. } else if (ExprKind == UETT_VecStep) {
  3478. isInvalid = CheckVecStepExpr(E);
  3479. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3480. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3481. isInvalid = true;
  3482. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3483. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3484. isInvalid = true;
  3485. } else {
  3486. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3487. }
  3488. if (isInvalid)
  3489. return ExprError();
  3490. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3491. PE = TransformToPotentiallyEvaluated(E);
  3492. if (PE.isInvalid()) return ExprError();
  3493. E = PE.get();
  3494. }
  3495. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3496. return new (Context) UnaryExprOrTypeTraitExpr(
  3497. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3498. }
  3499. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3500. /// expr and the same for @c alignof and @c __alignof
  3501. /// Note that the ArgRange is invalid if isType is false.
  3502. ExprResult
  3503. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3504. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3505. void *TyOrEx, const SourceRange &ArgRange) {
  3506. // If error parsing type, ignore.
  3507. if (!TyOrEx) return ExprError();
  3508. if (IsType) {
  3509. TypeSourceInfo *TInfo;
  3510. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3511. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3512. }
  3513. Expr *ArgEx = (Expr *)TyOrEx;
  3514. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3515. return Result;
  3516. }
  3517. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3518. bool IsReal) {
  3519. if (V.get()->isTypeDependent())
  3520. return S.Context.DependentTy;
  3521. // _Real and _Imag are only l-values for normal l-values.
  3522. if (V.get()->getObjectKind() != OK_Ordinary) {
  3523. V = S.DefaultLvalueConversion(V.get());
  3524. if (V.isInvalid())
  3525. return QualType();
  3526. }
  3527. // These operators return the element type of a complex type.
  3528. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3529. return CT->getElementType();
  3530. // Otherwise they pass through real integer and floating point types here.
  3531. if (V.get()->getType()->isArithmeticType())
  3532. return V.get()->getType();
  3533. // Test for placeholders.
  3534. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3535. if (PR.isInvalid()) return QualType();
  3536. if (PR.get() != V.get()) {
  3537. V = PR;
  3538. return CheckRealImagOperand(S, V, Loc, IsReal);
  3539. }
  3540. // Reject anything else.
  3541. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3542. << (IsReal ? "__real" : "__imag");
  3543. return QualType();
  3544. }
  3545. ExprResult
  3546. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3547. tok::TokenKind Kind, Expr *Input) {
  3548. UnaryOperatorKind Opc;
  3549. switch (Kind) {
  3550. default: llvm_unreachable("Unknown unary op!");
  3551. case tok::plusplus: Opc = UO_PostInc; break;
  3552. case tok::minusminus: Opc = UO_PostDec; break;
  3553. }
  3554. // Since this might is a postfix expression, get rid of ParenListExprs.
  3555. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3556. if (Result.isInvalid()) return ExprError();
  3557. Input = Result.get();
  3558. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3559. }
  3560. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3561. ///
  3562. /// \return true on error
  3563. static bool checkArithmeticOnObjCPointer(Sema &S,
  3564. SourceLocation opLoc,
  3565. Expr *op) {
  3566. assert(op->getType()->isObjCObjectPointerType());
  3567. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3568. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3569. return false;
  3570. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3571. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3572. << op->getSourceRange();
  3573. return true;
  3574. }
  3575. ExprResult
  3576. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3577. Expr *idx, SourceLocation rbLoc) {
  3578. // Since this might be a postfix expression, get rid of ParenListExprs.
  3579. if (isa<ParenListExpr>(base)) {
  3580. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3581. if (result.isInvalid()) return ExprError();
  3582. base = result.get();
  3583. }
  3584. // Handle any non-overload placeholder types in the base and index
  3585. // expressions. We can't handle overloads here because the other
  3586. // operand might be an overloadable type, in which case the overload
  3587. // resolution for the operator overload should get the first crack
  3588. // at the overload.
  3589. if (base->getType()->isNonOverloadPlaceholderType()) {
  3590. ExprResult result = CheckPlaceholderExpr(base);
  3591. if (result.isInvalid()) return ExprError();
  3592. base = result.get();
  3593. }
  3594. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3595. ExprResult result = CheckPlaceholderExpr(idx);
  3596. if (result.isInvalid()) return ExprError();
  3597. idx = result.get();
  3598. }
  3599. // HLSL Change Starts - Check for subscript access of out indices
  3600. // Disallow component access for out indices for DXIL path. We still allow
  3601. // this in SPIR-V path.
  3602. if (getLangOpts().HLSL && !getLangOpts().SPIRV &&
  3603. base->getType()->isRecordType() && IsExprAccessingOutIndicesArray(base)) {
  3604. Diag(lbLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  3605. return ExprError();
  3606. }
  3607. // HLSL Change Ends
  3608. // Build an unanalyzed expression if either operand is type-dependent.
  3609. if (getLangOpts().CPlusPlus &&
  3610. (base->isTypeDependent() || idx->isTypeDependent())) {
  3611. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3612. VK_LValue, OK_Ordinary, rbLoc);
  3613. }
  3614. // Use C++ overloaded-operator rules if either operand has record
  3615. // type. The spec says to do this if either type is *overloadable*,
  3616. // but enum types can't declare subscript operators or conversion
  3617. // operators, so there's nothing interesting for overload resolution
  3618. // to do if there aren't any record types involved.
  3619. //
  3620. // ObjC pointers have their own subscripting logic that is not tied
  3621. // to overload resolution and so should not take this path.
  3622. if (getLangOpts().CPlusPlus &&
  3623. (base->getType()->isRecordType() ||
  3624. (!base->getType()->isObjCObjectPointerType() &&
  3625. idx->getType()->isRecordType()))) {
  3626. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3627. }
  3628. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3629. }
  3630. ExprResult
  3631. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3632. Expr *Idx, SourceLocation RLoc) {
  3633. Expr *LHSExp = Base;
  3634. Expr *RHSExp = Idx;
  3635. // Perform default conversions.
  3636. if (!LHSExp->getType()->getAs<VectorType>()) {
  3637. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3638. if (Result.isInvalid())
  3639. return ExprError();
  3640. LHSExp = Result.get();
  3641. }
  3642. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3643. if (Result.isInvalid())
  3644. return ExprError();
  3645. RHSExp = Result.get();
  3646. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3647. ExprValueKind VK = VK_LValue;
  3648. ExprObjectKind OK = OK_Ordinary;
  3649. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3650. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3651. // in the subscript position. As a result, we need to derive the array base
  3652. // and index from the expression types.
  3653. Expr *BaseExpr, *IndexExpr;
  3654. QualType ResultType;
  3655. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3656. BaseExpr = LHSExp;
  3657. IndexExpr = RHSExp;
  3658. ResultType = Context.DependentTy;
  3659. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3660. BaseExpr = LHSExp;
  3661. IndexExpr = RHSExp;
  3662. ResultType = PTy->getPointeeType();
  3663. } else if (const ObjCObjectPointerType *PTy =
  3664. LHSTy->getAs<ObjCObjectPointerType>()) {
  3665. BaseExpr = LHSExp;
  3666. IndexExpr = RHSExp;
  3667. // Use custom logic if this should be the pseudo-object subscript
  3668. // expression.
  3669. if (!LangOpts.isSubscriptPointerArithmetic())
  3670. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3671. nullptr);
  3672. ResultType = PTy->getPointeeType();
  3673. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3674. // Handle the uncommon case of "123[Ptr]".
  3675. BaseExpr = RHSExp;
  3676. IndexExpr = LHSExp;
  3677. ResultType = PTy->getPointeeType();
  3678. } else if (const ObjCObjectPointerType *PTy =
  3679. RHSTy->getAs<ObjCObjectPointerType>()) {
  3680. // Handle the uncommon case of "123[Ptr]".
  3681. BaseExpr = RHSExp;
  3682. IndexExpr = LHSExp;
  3683. ResultType = PTy->getPointeeType();
  3684. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3685. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3686. << ResultType << BaseExpr->getSourceRange();
  3687. return ExprError();
  3688. }
  3689. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3690. BaseExpr = LHSExp; // vectors: V[123]
  3691. IndexExpr = RHSExp;
  3692. VK = LHSExp->getValueKind();
  3693. if (VK != VK_RValue)
  3694. OK = OK_VectorComponent;
  3695. // FIXME: need to deal with const...
  3696. ResultType = VTy->getElementType();
  3697. } else if (LHSTy->isArrayType()) {
  3698. // If we see an array that wasn't promoted by
  3699. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3700. // wasn't promoted because of the C90 rule that doesn't
  3701. // allow promoting non-lvalue arrays. Warn, then
  3702. // force the promotion here.
  3703. // HLSL Change Starts - arrays won't decay
  3704. if (getLangOpts().HLSL) {
  3705. BaseExpr = LHSExp;
  3706. IndexExpr = RHSExp;
  3707. ResultType = LHSTy->getAsArrayTypeUnsafe()->getElementType();
  3708. } else {
  3709. // HLSL Change Ends
  3710. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3711. LHSExp->getSourceRange();
  3712. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3713. CK_ArrayToPointerDecay).get();
  3714. LHSTy = LHSExp->getType();
  3715. BaseExpr = LHSExp;
  3716. IndexExpr = RHSExp;
  3717. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3718. } // HLSL Change - end else block
  3719. } else if (RHSTy->isArrayType()) {
  3720. // Same as previous, except for 123[f().a] case
  3721. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3722. RHSExp->getSourceRange();
  3723. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3724. CK_ArrayToPointerDecay).get();
  3725. RHSTy = RHSExp->getType();
  3726. BaseExpr = RHSExp;
  3727. IndexExpr = LHSExp;
  3728. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3729. } else {
  3730. // HLSL Change: use HLSL variation of error message
  3731. return ExprError(Diag(LLoc, getLangOpts().HLSL ? diag::err_hlsl_typecheck_subscript_value : diag::err_typecheck_subscript_value)
  3732. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3733. }
  3734. // HLSL Change Starts
  3735. if (getLangOpts().HLSL && BaseExpr != LHSExp) {
  3736. Diag(RHSExp->getLocStart(), diag::err_hlsl_unsupported_subscript_base_rhs);
  3737. }
  3738. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent() &&
  3739. IndexExpr->getType()->isFloatingType()) {
  3740. IndexExpr = ImpCastExprToType(IndexExpr, Context.UnsignedIntTy,
  3741. CK_FloatingToIntegral).get();
  3742. }
  3743. // HLSL Change Ends
  3744. // C99 6.5.2.1p1
  3745. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3746. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3747. << IndexExpr->getSourceRange());
  3748. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3749. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3750. && !IndexExpr->isTypeDependent())
  3751. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3752. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3753. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3754. // type. Note that Functions are not objects, and that (in C99 parlance)
  3755. // incomplete types are not object types.
  3756. if (ResultType->isFunctionType()) {
  3757. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3758. << ResultType << BaseExpr->getSourceRange();
  3759. return ExprError();
  3760. }
  3761. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3762. // GNU extension: subscripting on pointer to void
  3763. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3764. << BaseExpr->getSourceRange();
  3765. // C forbids expressions of unqualified void type from being l-values.
  3766. // See IsCForbiddenLValueType.
  3767. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3768. } else if (!ResultType->isDependentType() &&
  3769. RequireCompleteType(LLoc, ResultType,
  3770. diag::err_subscript_incomplete_type, BaseExpr))
  3771. return ExprError();
  3772. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3773. !ResultType.isCForbiddenLValueType());
  3774. if (getLangOpts().HLSL) RHSExp = IndexExpr; // HLSL Change - refer to right-hands side as indexer
  3775. return new (Context)
  3776. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3777. }
  3778. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3779. FunctionDecl *FD,
  3780. ParmVarDecl *Param) {
  3781. if (Param->hasUnparsedDefaultArg()) {
  3782. Diag(CallLoc,
  3783. diag::err_use_of_default_argument_to_function_declared_later) <<
  3784. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3785. Diag(UnparsedDefaultArgLocs[Param],
  3786. diag::note_default_argument_declared_here);
  3787. return ExprError();
  3788. }
  3789. if (Param->hasUninstantiatedDefaultArg()) {
  3790. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3791. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3792. Param);
  3793. // Instantiate the expression.
  3794. MultiLevelTemplateArgumentList MutiLevelArgList
  3795. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3796. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3797. MutiLevelArgList.getInnermost());
  3798. if (Inst.isInvalid())
  3799. return ExprError();
  3800. ExprResult Result;
  3801. {
  3802. // C++ [dcl.fct.default]p5:
  3803. // The names in the [default argument] expression are bound, and
  3804. // the semantic constraints are checked, at the point where the
  3805. // default argument expression appears.
  3806. ContextRAII SavedContext(*this, FD);
  3807. LocalInstantiationScope Local(*this);
  3808. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3809. }
  3810. if (Result.isInvalid())
  3811. return ExprError();
  3812. // Check the expression as an initializer for the parameter.
  3813. InitializedEntity Entity
  3814. = InitializedEntity::InitializeParameter(Context, Param);
  3815. InitializationKind Kind
  3816. = InitializationKind::CreateCopy(Param->getLocation(),
  3817. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3818. Expr *ResultE = Result.getAs<Expr>();
  3819. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3820. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3821. if (Result.isInvalid())
  3822. return ExprError();
  3823. Expr *Arg = Result.getAs<Expr>();
  3824. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3825. // Build the default argument expression.
  3826. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3827. }
  3828. // If the default expression creates temporaries, we need to
  3829. // push them to the current stack of expression temporaries so they'll
  3830. // be properly destroyed.
  3831. // FIXME: We should really be rebuilding the default argument with new
  3832. // bound temporaries; see the comment in PR5810.
  3833. // We don't need to do that with block decls, though, because
  3834. // blocks in default argument expression can never capture anything.
  3835. if (isa<ExprWithCleanups>(Param->getInit())) {
  3836. // Set the "needs cleanups" bit regardless of whether there are
  3837. // any explicit objects.
  3838. ExprNeedsCleanups = true;
  3839. // Append all the objects to the cleanup list. Right now, this
  3840. // should always be a no-op, because blocks in default argument
  3841. // expressions should never be able to capture anything.
  3842. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3843. "default argument expression has capturing blocks?");
  3844. }
  3845. // We already type-checked the argument, so we know it works.
  3846. // Just mark all of the declarations in this potentially-evaluated expression
  3847. // as being "referenced".
  3848. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3849. /*SkipLocalVariables=*/true);
  3850. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3851. }
  3852. Sema::VariadicCallType
  3853. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3854. Expr *Fn) {
  3855. if (Proto && Proto->isVariadic()) {
  3856. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3857. return VariadicConstructor;
  3858. else if (Fn && Fn->getType()->isBlockPointerType())
  3859. return VariadicBlock;
  3860. else if (FDecl) {
  3861. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3862. if (Method->isInstance())
  3863. return VariadicMethod;
  3864. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3865. return VariadicMethod;
  3866. return VariadicFunction;
  3867. }
  3868. return VariadicDoesNotApply;
  3869. }
  3870. namespace {
  3871. class FunctionCallCCC : public FunctionCallFilterCCC {
  3872. public:
  3873. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3874. unsigned NumArgs, MemberExpr *ME)
  3875. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3876. FunctionName(FuncName) {}
  3877. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3878. if (!candidate.getCorrectionSpecifier() ||
  3879. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3880. return false;
  3881. }
  3882. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3883. }
  3884. private:
  3885. const IdentifierInfo *const FunctionName;
  3886. };
  3887. }
  3888. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3889. FunctionDecl *FDecl,
  3890. ArrayRef<Expr *> Args) {
  3891. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3892. DeclarationName FuncName = FDecl->getDeclName();
  3893. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3894. if (TypoCorrection Corrected = S.CorrectTypo(
  3895. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3896. S.getScopeForContext(S.CurContext), nullptr,
  3897. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3898. Args.size(), ME),
  3899. Sema::CTK_ErrorRecovery)) {
  3900. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3901. if (Corrected.isOverloaded()) {
  3902. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3903. OverloadCandidateSet::iterator Best;
  3904. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3905. CDEnd = Corrected.end();
  3906. CD != CDEnd; ++CD) {
  3907. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3908. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3909. OCS);
  3910. }
  3911. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3912. case OR_Success:
  3913. ND = Best->Function;
  3914. Corrected.setCorrectionDecl(ND);
  3915. break;
  3916. default:
  3917. break;
  3918. }
  3919. }
  3920. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3921. return Corrected;
  3922. }
  3923. }
  3924. }
  3925. return TypoCorrection();
  3926. }
  3927. /// ConvertArgumentsForCall - Converts the arguments specified in
  3928. /// Args/NumArgs to the parameter types of the function FDecl with
  3929. /// function prototype Proto. Call is the call expression itself, and
  3930. /// Fn is the function expression. For a C++ member function, this
  3931. /// routine does not attempt to convert the object argument. Returns
  3932. /// true if the call is ill-formed.
  3933. bool
  3934. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3935. FunctionDecl *FDecl,
  3936. const FunctionProtoType *Proto,
  3937. ArrayRef<Expr *> Args,
  3938. SourceLocation RParenLoc,
  3939. bool IsExecConfig) {
  3940. // Bail out early if calling a builtin with custom typechecking.
  3941. if (FDecl)
  3942. if (unsigned ID = FDecl->getBuiltinID())
  3943. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3944. return false;
  3945. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3946. // assignment, to the types of the corresponding parameter, ...
  3947. unsigned NumParams = Proto->getNumParams();
  3948. bool Invalid = false;
  3949. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3950. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3951. ? 1 /* block */
  3952. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3953. : 0 /* function */);
  3954. // If too few arguments are available (and we don't have default
  3955. // arguments for the remaining parameters), don't make the call.
  3956. if (Args.size() < NumParams) {
  3957. if (Args.size() < MinArgs) {
  3958. TypoCorrection TC;
  3959. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3960. unsigned diag_id =
  3961. MinArgs == NumParams && !Proto->isVariadic()
  3962. ? diag::err_typecheck_call_too_few_args_suggest
  3963. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3964. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3965. << static_cast<unsigned>(Args.size())
  3966. << TC.getCorrectionRange());
  3967. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3968. Diag(RParenLoc,
  3969. MinArgs == NumParams && !Proto->isVariadic()
  3970. ? diag::err_typecheck_call_too_few_args_one
  3971. : diag::err_typecheck_call_too_few_args_at_least_one)
  3972. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3973. else
  3974. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3975. ? diag::err_typecheck_call_too_few_args
  3976. : diag::err_typecheck_call_too_few_args_at_least)
  3977. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3978. << Fn->getSourceRange();
  3979. // Emit the location of the prototype.
  3980. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3981. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3982. << FDecl;
  3983. return true;
  3984. }
  3985. Call->setNumArgs(Context, NumParams);
  3986. }
  3987. // If too many are passed and not variadic, error on the extras and drop
  3988. // them.
  3989. if (Args.size() > NumParams) {
  3990. if (!Proto->isVariadic()) {
  3991. TypoCorrection TC;
  3992. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3993. unsigned diag_id =
  3994. MinArgs == NumParams && !Proto->isVariadic()
  3995. ? diag::err_typecheck_call_too_many_args_suggest
  3996. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3997. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3998. << static_cast<unsigned>(Args.size())
  3999. << TC.getCorrectionRange());
  4000. } else if (NumParams == 1 && FDecl &&
  4001. FDecl->getParamDecl(0)->getDeclName())
  4002. Diag(Args[NumParams]->getLocStart(),
  4003. MinArgs == NumParams
  4004. ? diag::err_typecheck_call_too_many_args_one
  4005. : diag::err_typecheck_call_too_many_args_at_most_one)
  4006. << FnKind << FDecl->getParamDecl(0)
  4007. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4008. << SourceRange(Args[NumParams]->getLocStart(),
  4009. Args.back()->getLocEnd());
  4010. else
  4011. Diag(Args[NumParams]->getLocStart(),
  4012. MinArgs == NumParams
  4013. ? diag::err_typecheck_call_too_many_args
  4014. : diag::err_typecheck_call_too_many_args_at_most)
  4015. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4016. << Fn->getSourceRange()
  4017. << SourceRange(Args[NumParams]->getLocStart(),
  4018. Args.back()->getLocEnd());
  4019. // Emit the location of the prototype.
  4020. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4021. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4022. << FDecl;
  4023. // This deletes the extra arguments.
  4024. Call->setNumArgs(Context, NumParams);
  4025. return true;
  4026. }
  4027. }
  4028. SmallVector<Expr *, 8> AllArgs;
  4029. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4030. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  4031. Proto, 0, Args, AllArgs, CallType);
  4032. if (Invalid)
  4033. return true;
  4034. unsigned TotalNumArgs = AllArgs.size();
  4035. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4036. Call->setArg(i, AllArgs[i]);
  4037. return false;
  4038. }
  4039. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4040. const FunctionProtoType *Proto,
  4041. unsigned FirstParam, ArrayRef<Expr *> Args,
  4042. SmallVectorImpl<Expr *> &AllArgs,
  4043. VariadicCallType CallType, bool AllowExplicit,
  4044. bool IsListInitialization) {
  4045. unsigned NumParams = Proto->getNumParams();
  4046. bool Invalid = false;
  4047. unsigned ArgIx = 0;
  4048. // Continue to check argument types (even if we have too few/many args).
  4049. for (unsigned i = FirstParam; i < NumParams; i++) {
  4050. QualType ProtoArgType = Proto->getParamType(i);
  4051. Expr *Arg;
  4052. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4053. if (ArgIx < Args.size()) {
  4054. Arg = Args[ArgIx++];
  4055. if (!(getLangOpts().HLSL && ProtoArgType->isIncompleteArrayType()) && // HLSL Change: allow incomplete array
  4056. RequireCompleteType(Arg->getLocStart(),
  4057. ProtoArgType,
  4058. diag::err_call_incomplete_argument, Arg))
  4059. return true;
  4060. // Strip the unbridged-cast placeholder expression off, if applicable.
  4061. bool CFAudited = false;
  4062. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4063. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4064. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4065. Arg = stripARCUnbridgedCast(Arg);
  4066. else if (getLangOpts().ObjCAutoRefCount &&
  4067. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4068. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4069. CFAudited = true;
  4070. InitializedEntity Entity =
  4071. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4072. ProtoArgType)
  4073. : InitializedEntity::InitializeParameter(
  4074. Context, ProtoArgType, Proto->isParamConsumed(i));
  4075. // Remember that parameter belongs to a CF audited API.
  4076. if (CFAudited)
  4077. Entity.setParameterCFAudited();
  4078. ExprResult ArgE = PerformCopyInitialization(
  4079. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4080. if (ArgE.isInvalid())
  4081. return true;
  4082. Arg = ArgE.getAs<Expr>();
  4083. } else {
  4084. assert(Param && "can't use default arguments without a known callee");
  4085. ExprResult ArgExpr =
  4086. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4087. if (ArgExpr.isInvalid())
  4088. return true;
  4089. Arg = ArgExpr.getAs<Expr>();
  4090. }
  4091. // Check for array bounds violations for each argument to the call. This
  4092. // check only triggers warnings when the argument isn't a more complex Expr
  4093. // with its own checking, such as a BinaryOperator.
  4094. CheckArrayAccess(Arg);
  4095. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4096. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4097. AllArgs.push_back(Arg);
  4098. }
  4099. // If this is a variadic call, handle args passed through "...".
  4100. if (CallType != VariadicDoesNotApply) {
  4101. // Assume that extern "C" functions with variadic arguments that
  4102. // return __unknown_anytype aren't *really* variadic.
  4103. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4104. FDecl->isExternC()) {
  4105. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4106. QualType paramType; // ignored
  4107. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  4108. Invalid |= arg.isInvalid();
  4109. AllArgs.push_back(arg.get());
  4110. }
  4111. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4112. } else {
  4113. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4114. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  4115. FDecl);
  4116. Invalid |= Arg.isInvalid();
  4117. AllArgs.push_back(Arg.get());
  4118. }
  4119. }
  4120. // Check for array bounds violations.
  4121. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  4122. CheckArrayAccess(Args[i]);
  4123. }
  4124. return Invalid;
  4125. }
  4126. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4127. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4128. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4129. TL = DTL.getOriginalLoc();
  4130. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4131. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4132. << ATL.getLocalSourceRange();
  4133. }
  4134. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4135. /// array parameter, check that it is non-null, and that if it is formed by
  4136. /// array-to-pointer decay, the underlying array is sufficiently large.
  4137. ///
  4138. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4139. /// array type derivation, then for each call to the function, the value of the
  4140. /// corresponding actual argument shall provide access to the first element of
  4141. /// an array with at least as many elements as specified by the size expression.
  4142. void
  4143. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4144. ParmVarDecl *Param,
  4145. const Expr *ArgExpr) {
  4146. // Static array parameters are not supported in C++.
  4147. if (!Param || getLangOpts().CPlusPlus)
  4148. return;
  4149. QualType OrigTy = Param->getOriginalType();
  4150. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4151. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4152. return;
  4153. if (ArgExpr->isNullPointerConstant(Context,
  4154. Expr::NPC_NeverValueDependent)) {
  4155. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4156. DiagnoseCalleeStaticArrayParam(*this, Param);
  4157. return;
  4158. }
  4159. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4160. if (!CAT)
  4161. return;
  4162. const ConstantArrayType *ArgCAT =
  4163. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4164. if (!ArgCAT)
  4165. return;
  4166. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4167. Diag(CallLoc, diag::warn_static_array_too_small)
  4168. << ArgExpr->getSourceRange()
  4169. << (unsigned) ArgCAT->getSize().getZExtValue()
  4170. << (unsigned) CAT->getSize().getZExtValue();
  4171. DiagnoseCalleeStaticArrayParam(*this, Param);
  4172. }
  4173. }
  4174. /// Given a function expression of unknown-any type, try to rebuild it
  4175. /// to have a function type.
  4176. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4177. /// Is the given type a placeholder that we need to lower out
  4178. /// immediately during argument processing?
  4179. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4180. // Placeholders are never sugared.
  4181. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4182. if (!placeholder) return false;
  4183. switch (placeholder->getKind()) {
  4184. // Ignore all the non-placeholder types.
  4185. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4186. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4187. #include "clang/AST/BuiltinTypes.def"
  4188. return false;
  4189. // We cannot lower out overload sets; they might validly be resolved
  4190. // by the call machinery.
  4191. case BuiltinType::Overload:
  4192. return false;
  4193. // Unbridged casts in ARC can be handled in some call positions and
  4194. // should be left in place.
  4195. case BuiltinType::ARCUnbridgedCast:
  4196. return false;
  4197. // Pseudo-objects should be converted as soon as possible.
  4198. case BuiltinType::PseudoObject:
  4199. return true;
  4200. // The debugger mode could theoretically but currently does not try
  4201. // to resolve unknown-typed arguments based on known parameter types.
  4202. case BuiltinType::UnknownAny:
  4203. return true;
  4204. // These are always invalid as call arguments and should be reported.
  4205. case BuiltinType::BoundMember:
  4206. case BuiltinType::BuiltinFn:
  4207. return true;
  4208. }
  4209. llvm_unreachable("bad builtin type kind");
  4210. }
  4211. /// Check an argument list for placeholders that we won't try to
  4212. /// handle later.
  4213. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4214. // Apply this processing to all the arguments at once instead of
  4215. // dying at the first failure.
  4216. bool hasInvalid = false;
  4217. for (size_t i = 0, e = args.size(); i != e; i++) {
  4218. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4219. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4220. if (result.isInvalid()) hasInvalid = true;
  4221. else args[i] = result.get();
  4222. } else if (hasInvalid) {
  4223. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4224. }
  4225. }
  4226. return hasInvalid;
  4227. }
  4228. /// If a builtin function has a pointer argument with no explicit address
  4229. /// space, than it should be able to accept a pointer to any address
  4230. /// space as input. In order to do this, we need to replace the
  4231. /// standard builtin declaration with one that uses the same address space
  4232. /// as the call.
  4233. ///
  4234. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4235. /// it does not contain any pointer arguments without
  4236. /// an address space qualifer. Otherwise the rewritten
  4237. /// FunctionDecl is returned.
  4238. /// TODO: Handle pointer return types.
  4239. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4240. const FunctionDecl *FDecl,
  4241. MultiExprArg ArgExprs) {
  4242. QualType DeclType = FDecl->getType();
  4243. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4244. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4245. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4246. return nullptr;
  4247. bool NeedsNewDecl = false;
  4248. unsigned i = 0;
  4249. SmallVector<QualType, 8> OverloadParams;
  4250. for (QualType ParamType : FT->param_types()) {
  4251. // Convert array arguments to pointer to simplify type lookup.
  4252. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4253. QualType ArgType = Arg->getType();
  4254. if (!ParamType->isPointerType() ||
  4255. ParamType.getQualifiers().hasAddressSpace() ||
  4256. !ArgType->isPointerType() ||
  4257. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4258. OverloadParams.push_back(ParamType);
  4259. continue;
  4260. }
  4261. NeedsNewDecl = true;
  4262. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4263. QualType PointeeType = ParamType->getPointeeType();
  4264. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4265. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4266. }
  4267. if (!NeedsNewDecl)
  4268. return nullptr;
  4269. FunctionProtoType::ExtProtoInfo EPI;
  4270. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4271. OverloadParams, EPI,
  4272. FT->getParamMods()); // HLSL Change
  4273. DeclContext *Parent = Context.getTranslationUnitDecl();
  4274. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4275. FDecl->getLocation(),
  4276. FDecl->getLocation(),
  4277. FDecl->getIdentifier(),
  4278. OverloadTy,
  4279. /*TInfo=*/nullptr,
  4280. SC_Extern, false,
  4281. /*hasPrototype=*/true);
  4282. SmallVector<ParmVarDecl*, 16> Params;
  4283. FT = cast<FunctionProtoType>(OverloadTy);
  4284. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4285. QualType ParamType = FT->getParamType(i);
  4286. ParmVarDecl *Parm =
  4287. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4288. SourceLocation(), nullptr, ParamType,
  4289. /*TInfo=*/nullptr, SC_None, nullptr);
  4290. Parm->setScopeInfo(0, i);
  4291. Params.push_back(Parm);
  4292. }
  4293. OverloadDecl->setParams(Params);
  4294. return OverloadDecl;
  4295. }
  4296. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4297. /// This provides the location of the left/right parens and a list of comma
  4298. /// locations.
  4299. ExprResult
  4300. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4301. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4302. Expr *ExecConfig, bool IsExecConfig) {
  4303. // Since this might be a postfix expression, get rid of ParenListExprs.
  4304. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4305. if (Result.isInvalid()) return ExprError();
  4306. Fn = Result.get();
  4307. if (checkArgsForPlaceholders(*this, ArgExprs))
  4308. return ExprError();
  4309. if (getLangOpts().CPlusPlus) {
  4310. // If this is a pseudo-destructor expression, build the call immediately.
  4311. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4312. if (!ArgExprs.empty()) {
  4313. // Pseudo-destructor calls should not have any arguments.
  4314. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4315. << FixItHint::CreateRemoval(
  4316. SourceRange(ArgExprs[0]->getLocStart(),
  4317. ArgExprs.back()->getLocEnd()));
  4318. }
  4319. return new (Context)
  4320. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4321. }
  4322. if (Fn->getType() == Context.PseudoObjectTy) {
  4323. ExprResult result = CheckPlaceholderExpr(Fn);
  4324. if (result.isInvalid()) return ExprError();
  4325. Fn = result.get();
  4326. }
  4327. // Determine whether this is a dependent call inside a C++ template,
  4328. // in which case we won't do any semantic analysis now.
  4329. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4330. // Fn.
  4331. bool Dependent = false;
  4332. if (Fn->isTypeDependent())
  4333. Dependent = true;
  4334. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4335. Dependent = true;
  4336. if (Dependent) {
  4337. if (ExecConfig) {
  4338. return new (Context) CUDAKernelCallExpr(
  4339. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4340. Context.DependentTy, VK_RValue, RParenLoc);
  4341. } else {
  4342. return new (Context) CallExpr(
  4343. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4344. }
  4345. }
  4346. // Determine whether this is a call to an object (C++ [over.call.object]).
  4347. if (Fn->getType()->isRecordType())
  4348. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4349. RParenLoc);
  4350. if (Fn->getType() == Context.UnknownAnyTy) {
  4351. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4352. if (result.isInvalid()) return ExprError();
  4353. Fn = result.get();
  4354. }
  4355. if (Fn->getType() == Context.BoundMemberTy) {
  4356. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4357. }
  4358. }
  4359. // Check for overloaded calls. This can happen even in C due to extensions.
  4360. if (Fn->getType() == Context.OverloadTy) {
  4361. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4362. // We aren't supposed to apply this logic for if there's an '&' involved.
  4363. if (!find.HasFormOfMemberPointer) {
  4364. OverloadExpr *ovl = find.Expression;
  4365. if (isa<UnresolvedLookupExpr>(ovl)) {
  4366. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4367. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4368. RParenLoc, ExecConfig);
  4369. } else {
  4370. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4371. RParenLoc);
  4372. }
  4373. }
  4374. }
  4375. // If we're directly calling a function, get the appropriate declaration.
  4376. if (Fn->getType() == Context.UnknownAnyTy) {
  4377. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4378. if (result.isInvalid()) return ExprError();
  4379. Fn = result.get();
  4380. }
  4381. Expr *NakedFn = Fn->IgnoreParens();
  4382. NamedDecl *NDecl = nullptr;
  4383. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4384. if (UnOp->getOpcode() == UO_AddrOf)
  4385. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4386. if (isa<DeclRefExpr>(NakedFn)) {
  4387. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4388. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4389. if (FDecl && FDecl->getBuiltinID()) {
  4390. // Rewrite the function decl for this builtin by replacing paramaters
  4391. // with no explicit address space with the address space of the arguments
  4392. // in ArgExprs.
  4393. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4394. NDecl = FDecl;
  4395. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4396. SourceLocation(), FDecl, false,
  4397. SourceLocation(), FDecl->getType(),
  4398. Fn->getValueKind(), FDecl);
  4399. }
  4400. }
  4401. } else if (isa<MemberExpr>(NakedFn))
  4402. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4403. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4404. if (FD->hasAttr<EnableIfAttr>()) {
  4405. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4406. Diag(Fn->getLocStart(),
  4407. isa<CXXMethodDecl>(FD) ?
  4408. diag::err_ovl_no_viable_member_function_in_call :
  4409. diag::err_ovl_no_viable_function_in_call)
  4410. << FD << FD->getSourceRange();
  4411. Diag(FD->getLocation(),
  4412. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4413. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4414. }
  4415. }
  4416. }
  4417. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4418. ExecConfig, IsExecConfig);
  4419. }
  4420. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4421. ///
  4422. /// __builtin_astype( value, dst type )
  4423. ///
  4424. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4425. SourceLocation BuiltinLoc,
  4426. SourceLocation RParenLoc) {
  4427. ExprValueKind VK = VK_RValue;
  4428. ExprObjectKind OK = OK_Ordinary;
  4429. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4430. QualType SrcTy = E->getType();
  4431. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4432. return ExprError(Diag(BuiltinLoc,
  4433. diag::err_invalid_astype_of_different_size)
  4434. << DstTy
  4435. << SrcTy
  4436. << E->getSourceRange());
  4437. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4438. }
  4439. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4440. /// provided arguments.
  4441. ///
  4442. /// __builtin_convertvector( value, dst type )
  4443. ///
  4444. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4445. SourceLocation BuiltinLoc,
  4446. SourceLocation RParenLoc) {
  4447. TypeSourceInfo *TInfo;
  4448. GetTypeFromParser(ParsedDestTy, &TInfo);
  4449. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4450. }
  4451. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4452. /// i.e. an expression not of \p OverloadTy. The expression should
  4453. /// unary-convert to an expression of function-pointer or
  4454. /// block-pointer type.
  4455. ///
  4456. /// \param NDecl the declaration being called, if available
  4457. ExprResult
  4458. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4459. SourceLocation LParenLoc,
  4460. ArrayRef<Expr *> Args,
  4461. SourceLocation RParenLoc,
  4462. Expr *Config, bool IsExecConfig) {
  4463. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4464. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4465. // Promote the function operand.
  4466. // We special-case function promotion here because we only allow promoting
  4467. // builtin functions to function pointers in the callee of a call.
  4468. ExprResult Result;
  4469. if (BuiltinID &&
  4470. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4471. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4472. CK_BuiltinFnToFnPtr).get();
  4473. } else {
  4474. Result = CallExprUnaryConversions(Fn);
  4475. }
  4476. if (Result.isInvalid())
  4477. return ExprError();
  4478. Fn = Result.get();
  4479. // Make the call expr early, before semantic checks. This guarantees cleanup
  4480. // of arguments and function on error.
  4481. CallExpr *TheCall;
  4482. if (Config)
  4483. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4484. cast<CallExpr>(Config), Args,
  4485. Context.BoolTy, VK_RValue,
  4486. RParenLoc);
  4487. else
  4488. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4489. VK_RValue, RParenLoc);
  4490. if (!getLangOpts().CPlusPlus) {
  4491. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4492. // function calls as their argument checking don't necessarily handle
  4493. // dependent types properly, so make sure any TypoExprs have been
  4494. // dealt with.
  4495. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4496. if (!Result.isUsable()) return ExprError();
  4497. TheCall = dyn_cast<CallExpr>(Result.get());
  4498. if (!TheCall) return Result;
  4499. Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs());
  4500. }
  4501. // Bail out early if calling a builtin with custom typechecking.
  4502. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4503. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4504. retry:
  4505. const FunctionType *FuncT;
  4506. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4507. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4508. // have type pointer to function".
  4509. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4510. if (!FuncT)
  4511. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4512. << Fn->getType() << Fn->getSourceRange());
  4513. } else if (const BlockPointerType *BPT =
  4514. Fn->getType()->getAs<BlockPointerType>()) {
  4515. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4516. } else {
  4517. // Handle calls to expressions of unknown-any type.
  4518. if (Fn->getType() == Context.UnknownAnyTy) {
  4519. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4520. if (rewrite.isInvalid()) return ExprError();
  4521. Fn = rewrite.get();
  4522. TheCall->setCallee(Fn);
  4523. goto retry;
  4524. }
  4525. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4526. << Fn->getType() << Fn->getSourceRange());
  4527. }
  4528. if (getLangOpts().CUDA) {
  4529. if (Config) {
  4530. // CUDA: Kernel calls must be to global functions
  4531. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4532. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4533. << FDecl->getName() << Fn->getSourceRange());
  4534. // CUDA: Kernel function must have 'void' return type
  4535. if (!FuncT->getReturnType()->isVoidType())
  4536. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4537. << Fn->getType() << Fn->getSourceRange());
  4538. } else {
  4539. // CUDA: Calls to global functions must be configured
  4540. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4541. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4542. << FDecl->getName() << Fn->getSourceRange());
  4543. }
  4544. }
  4545. // Check for a valid return type
  4546. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4547. FDecl))
  4548. return ExprError();
  4549. // We know the result type of the call, set it.
  4550. TheCall->setType(FuncT->getCallResultType(Context));
  4551. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4552. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4553. if (Proto) {
  4554. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4555. IsExecConfig))
  4556. return ExprError();
  4557. } else {
  4558. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4559. if (FDecl) {
  4560. // Check if we have too few/too many template arguments, based
  4561. // on our knowledge of the function definition.
  4562. const FunctionDecl *Def = nullptr;
  4563. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4564. Proto = Def->getType()->getAs<FunctionProtoType>();
  4565. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4566. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4567. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4568. }
  4569. // If the function we're calling isn't a function prototype, but we have
  4570. // a function prototype from a prior declaratiom, use that prototype.
  4571. if (!FDecl->hasPrototype())
  4572. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4573. }
  4574. // Promote the arguments (C99 6.5.2.2p6).
  4575. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4576. Expr *Arg = Args[i];
  4577. if (Proto && i < Proto->getNumParams()) {
  4578. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4579. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4580. ExprResult ArgE =
  4581. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4582. if (ArgE.isInvalid())
  4583. return true;
  4584. Arg = ArgE.getAs<Expr>();
  4585. } else {
  4586. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4587. if (ArgE.isInvalid())
  4588. return true;
  4589. Arg = ArgE.getAs<Expr>();
  4590. }
  4591. if (RequireCompleteType(Arg->getLocStart(),
  4592. Arg->getType(),
  4593. diag::err_call_incomplete_argument, Arg))
  4594. return ExprError();
  4595. TheCall->setArg(i, Arg);
  4596. }
  4597. }
  4598. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4599. if (!Method->isStatic())
  4600. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4601. << Fn->getSourceRange());
  4602. // Check for sentinels
  4603. if (NDecl)
  4604. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4605. // Do special checking on direct calls to functions.
  4606. if (FDecl) {
  4607. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4608. return ExprError();
  4609. if (BuiltinID)
  4610. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4611. } else if (NDecl) {
  4612. if (CheckPointerCall(NDecl, TheCall, Proto))
  4613. return ExprError();
  4614. } else {
  4615. if (CheckOtherCall(TheCall, Proto))
  4616. return ExprError();
  4617. }
  4618. return MaybeBindToTemporary(TheCall);
  4619. }
  4620. ExprResult
  4621. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4622. SourceLocation RParenLoc, Expr *InitExpr) {
  4623. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4624. // FIXME: put back this assert when initializers are worked out.
  4625. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  4626. TypeSourceInfo *TInfo;
  4627. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4628. if (!TInfo)
  4629. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4630. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4631. }
  4632. ExprResult
  4633. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4634. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4635. QualType literalType = TInfo->getType();
  4636. if (literalType->isArrayType()) {
  4637. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4638. diag::err_illegal_decl_array_incomplete_type,
  4639. SourceRange(LParenLoc,
  4640. LiteralExpr->getSourceRange().getEnd())))
  4641. return ExprError();
  4642. if (literalType->isVariableArrayType())
  4643. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4644. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4645. } else if (!literalType->isDependentType() &&
  4646. RequireCompleteType(LParenLoc, literalType,
  4647. diag::err_typecheck_decl_incomplete_type,
  4648. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4649. return ExprError();
  4650. InitializedEntity Entity
  4651. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4652. InitializationKind Kind
  4653. = InitializationKind::CreateCStyleCast(LParenLoc,
  4654. SourceRange(LParenLoc, RParenLoc),
  4655. /*InitList=*/true);
  4656. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4657. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4658. &literalType);
  4659. if (Result.isInvalid())
  4660. return ExprError();
  4661. LiteralExpr = Result.get();
  4662. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4663. if (isFileScope &&
  4664. !LiteralExpr->isTypeDependent() &&
  4665. !LiteralExpr->isValueDependent() &&
  4666. !literalType->isDependentType()) { // 6.5.2.5p3
  4667. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4668. return ExprError();
  4669. }
  4670. // In C, compound literals are l-values for some reason.
  4671. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4672. return MaybeBindToTemporary(
  4673. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4674. VK, LiteralExpr, isFileScope));
  4675. }
  4676. ExprResult
  4677. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4678. SourceLocation RBraceLoc) {
  4679. // Immediately handle non-overload placeholders. Overloads can be
  4680. // resolved contextually, but everything else here can't.
  4681. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4682. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4683. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4684. // Ignore failures; dropping the entire initializer list because
  4685. // of one failure would be terrible for indexing/etc.
  4686. if (result.isInvalid()) continue;
  4687. InitArgList[I] = result.get();
  4688. }
  4689. }
  4690. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4691. // CheckInitializer() - it requires knowledge of the object being intialized.
  4692. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4693. RBraceLoc);
  4694. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4695. return E;
  4696. }
  4697. /// Do an explicit extend of the given block pointer if we're in ARC.
  4698. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4699. assert(E.get()->getType()->isBlockPointerType());
  4700. assert(E.get()->isRValue());
  4701. // Only do this in an r-value context.
  4702. if (!getLangOpts().ObjCAutoRefCount) return;
  4703. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4704. CK_ARCExtendBlockObject, E.get(),
  4705. /*base path*/ nullptr, VK_RValue);
  4706. ExprNeedsCleanups = true;
  4707. }
  4708. /// Prepare a conversion of the given expression to an ObjC object
  4709. /// pointer type.
  4710. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4711. QualType type = E.get()->getType();
  4712. if (type->isObjCObjectPointerType()) {
  4713. return CK_BitCast;
  4714. } else if (type->isBlockPointerType()) {
  4715. maybeExtendBlockObject(E);
  4716. return CK_BlockPointerToObjCPointerCast;
  4717. } else {
  4718. assert(type->isPointerType());
  4719. return CK_CPointerToObjCPointerCast;
  4720. }
  4721. }
  4722. /// Prepares for a scalar cast, performing all the necessary stages
  4723. /// except the final cast and returning the kind required.
  4724. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4725. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4726. // Also, callers should have filtered out the invalid cases with
  4727. // pointers. Everything else should be possible.
  4728. QualType SrcTy = Src.get()->getType();
  4729. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4730. return CK_NoOp;
  4731. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4732. case Type::STK_MemberPointer:
  4733. llvm_unreachable("member pointer type in C");
  4734. case Type::STK_CPointer:
  4735. case Type::STK_BlockPointer:
  4736. case Type::STK_ObjCObjectPointer:
  4737. switch (DestTy->getScalarTypeKind()) {
  4738. case Type::STK_CPointer: {
  4739. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4740. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4741. if (SrcAS != DestAS)
  4742. return CK_AddressSpaceConversion;
  4743. return CK_BitCast;
  4744. }
  4745. case Type::STK_BlockPointer:
  4746. return (SrcKind == Type::STK_BlockPointer
  4747. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4748. case Type::STK_ObjCObjectPointer:
  4749. if (SrcKind == Type::STK_ObjCObjectPointer)
  4750. return CK_BitCast;
  4751. if (SrcKind == Type::STK_CPointer)
  4752. return CK_CPointerToObjCPointerCast;
  4753. maybeExtendBlockObject(Src);
  4754. return CK_BlockPointerToObjCPointerCast;
  4755. case Type::STK_Bool:
  4756. return CK_PointerToBoolean;
  4757. case Type::STK_Integral:
  4758. return CK_PointerToIntegral;
  4759. case Type::STK_Floating:
  4760. case Type::STK_FloatingComplex:
  4761. case Type::STK_IntegralComplex:
  4762. case Type::STK_MemberPointer:
  4763. llvm_unreachable("illegal cast from pointer");
  4764. }
  4765. llvm_unreachable("Should have returned before this");
  4766. case Type::STK_Bool: // casting from bool is like casting from an integer
  4767. case Type::STK_Integral:
  4768. switch (DestTy->getScalarTypeKind()) {
  4769. case Type::STK_CPointer:
  4770. case Type::STK_ObjCObjectPointer:
  4771. case Type::STK_BlockPointer:
  4772. if (Src.get()->isNullPointerConstant(Context,
  4773. Expr::NPC_ValueDependentIsNull))
  4774. return CK_NullToPointer;
  4775. return CK_IntegralToPointer;
  4776. case Type::STK_Bool:
  4777. return CK_IntegralToBoolean;
  4778. case Type::STK_Integral:
  4779. return CK_IntegralCast;
  4780. case Type::STK_Floating:
  4781. return CK_IntegralToFloating;
  4782. case Type::STK_IntegralComplex:
  4783. Src = ImpCastExprToType(Src.get(),
  4784. DestTy->castAs<ComplexType>()->getElementType(),
  4785. CK_IntegralCast);
  4786. return CK_IntegralRealToComplex;
  4787. case Type::STK_FloatingComplex:
  4788. Src = ImpCastExprToType(Src.get(),
  4789. DestTy->castAs<ComplexType>()->getElementType(),
  4790. CK_IntegralToFloating);
  4791. return CK_FloatingRealToComplex;
  4792. case Type::STK_MemberPointer:
  4793. llvm_unreachable("member pointer type in C");
  4794. }
  4795. llvm_unreachable("Should have returned before this");
  4796. case Type::STK_Floating:
  4797. switch (DestTy->getScalarTypeKind()) {
  4798. case Type::STK_Floating:
  4799. return CK_FloatingCast;
  4800. case Type::STK_Bool:
  4801. return CK_FloatingToBoolean;
  4802. case Type::STK_Integral:
  4803. return CK_FloatingToIntegral;
  4804. case Type::STK_FloatingComplex:
  4805. Src = ImpCastExprToType(Src.get(),
  4806. DestTy->castAs<ComplexType>()->getElementType(),
  4807. CK_FloatingCast);
  4808. return CK_FloatingRealToComplex;
  4809. case Type::STK_IntegralComplex:
  4810. Src = ImpCastExprToType(Src.get(),
  4811. DestTy->castAs<ComplexType>()->getElementType(),
  4812. CK_FloatingToIntegral);
  4813. return CK_IntegralRealToComplex;
  4814. case Type::STK_CPointer:
  4815. case Type::STK_ObjCObjectPointer:
  4816. case Type::STK_BlockPointer:
  4817. llvm_unreachable("valid float->pointer cast?");
  4818. case Type::STK_MemberPointer:
  4819. llvm_unreachable("member pointer type in C");
  4820. }
  4821. llvm_unreachable("Should have returned before this");
  4822. case Type::STK_FloatingComplex:
  4823. switch (DestTy->getScalarTypeKind()) {
  4824. case Type::STK_FloatingComplex:
  4825. return CK_FloatingComplexCast;
  4826. case Type::STK_IntegralComplex:
  4827. return CK_FloatingComplexToIntegralComplex;
  4828. case Type::STK_Floating: {
  4829. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4830. if (Context.hasSameType(ET, DestTy))
  4831. return CK_FloatingComplexToReal;
  4832. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4833. return CK_FloatingCast;
  4834. }
  4835. case Type::STK_Bool:
  4836. return CK_FloatingComplexToBoolean;
  4837. case Type::STK_Integral:
  4838. Src = ImpCastExprToType(Src.get(),
  4839. SrcTy->castAs<ComplexType>()->getElementType(),
  4840. CK_FloatingComplexToReal);
  4841. return CK_FloatingToIntegral;
  4842. case Type::STK_CPointer:
  4843. case Type::STK_ObjCObjectPointer:
  4844. case Type::STK_BlockPointer:
  4845. llvm_unreachable("valid complex float->pointer cast?");
  4846. case Type::STK_MemberPointer:
  4847. llvm_unreachable("member pointer type in C");
  4848. }
  4849. llvm_unreachable("Should have returned before this");
  4850. case Type::STK_IntegralComplex:
  4851. switch (DestTy->getScalarTypeKind()) {
  4852. case Type::STK_FloatingComplex:
  4853. return CK_IntegralComplexToFloatingComplex;
  4854. case Type::STK_IntegralComplex:
  4855. return CK_IntegralComplexCast;
  4856. case Type::STK_Integral: {
  4857. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4858. if (Context.hasSameType(ET, DestTy))
  4859. return CK_IntegralComplexToReal;
  4860. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4861. return CK_IntegralCast;
  4862. }
  4863. case Type::STK_Bool:
  4864. return CK_IntegralComplexToBoolean;
  4865. case Type::STK_Floating:
  4866. Src = ImpCastExprToType(Src.get(),
  4867. SrcTy->castAs<ComplexType>()->getElementType(),
  4868. CK_IntegralComplexToReal);
  4869. return CK_IntegralToFloating;
  4870. case Type::STK_CPointer:
  4871. case Type::STK_ObjCObjectPointer:
  4872. case Type::STK_BlockPointer:
  4873. llvm_unreachable("valid complex int->pointer cast?");
  4874. case Type::STK_MemberPointer:
  4875. llvm_unreachable("member pointer type in C");
  4876. }
  4877. llvm_unreachable("Should have returned before this");
  4878. }
  4879. llvm_unreachable("Unhandled scalar cast");
  4880. }
  4881. static bool breakDownVectorType(QualType type, uint64_t &len,
  4882. QualType &eltType) {
  4883. // Vectors are simple.
  4884. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4885. len = vecType->getNumElements();
  4886. eltType = vecType->getElementType();
  4887. assert(eltType->isScalarType());
  4888. return true;
  4889. }
  4890. // We allow lax conversion to and from non-vector types, but only if
  4891. // they're real types (i.e. non-complex, non-pointer scalar types).
  4892. if (!type->isRealType()) return false;
  4893. len = 1;
  4894. eltType = type;
  4895. return true;
  4896. }
  4897. static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
  4898. uint64_t srcLen, destLen;
  4899. QualType srcElt, destElt;
  4900. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4901. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4902. // ASTContext::getTypeSize will return the size rounded up to a
  4903. // power of 2, so instead of using that, we need to use the raw
  4904. // element size multiplied by the element count.
  4905. uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
  4906. uint64_t destEltSize = S.Context.getTypeSize(destElt);
  4907. return (srcLen * srcEltSize == destLen * destEltSize);
  4908. }
  4909. /// Is this a legal conversion between two known vector types?
  4910. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4911. assert(destTy->isVectorType() || srcTy->isVectorType());
  4912. if (!Context.getLangOpts().LaxVectorConversions)
  4913. return false;
  4914. return VectorTypesMatch(*this, srcTy, destTy);
  4915. }
  4916. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4917. CastKind &Kind) {
  4918. assert(VectorTy->isVectorType() && "Not a vector type!");
  4919. if (Ty->isVectorType() || Ty->isIntegerType()) {
  4920. if (!VectorTypesMatch(*this, Ty, VectorTy))
  4921. return Diag(R.getBegin(),
  4922. Ty->isVectorType() ?
  4923. diag::err_invalid_conversion_between_vectors :
  4924. diag::err_invalid_conversion_between_vector_and_integer)
  4925. << VectorTy << Ty << R;
  4926. } else
  4927. return Diag(R.getBegin(),
  4928. diag::err_invalid_conversion_between_vector_and_scalar)
  4929. << VectorTy << Ty << R;
  4930. Kind = CK_BitCast;
  4931. return false;
  4932. }
  4933. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4934. Expr *CastExpr, CastKind &Kind) {
  4935. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4936. QualType SrcTy = CastExpr->getType();
  4937. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4938. // an ExtVectorType.
  4939. // In OpenCL, casts between vectors of different types are not allowed.
  4940. // (See OpenCL 6.2).
  4941. if (SrcTy->isVectorType()) {
  4942. if (!VectorTypesMatch(*this, SrcTy, DestTy)
  4943. || (getLangOpts().OpenCL &&
  4944. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4945. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4946. << DestTy << SrcTy << R;
  4947. return ExprError();
  4948. }
  4949. Kind = CK_BitCast;
  4950. return CastExpr;
  4951. }
  4952. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4953. // conversion will take place first from scalar to elt type, and then
  4954. // splat from elt type to vector.
  4955. if (SrcTy->isPointerType())
  4956. return Diag(R.getBegin(),
  4957. diag::err_invalid_conversion_between_vector_and_scalar)
  4958. << DestTy << SrcTy << R;
  4959. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4960. ExprResult CastExprRes = CastExpr;
  4961. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4962. if (CastExprRes.isInvalid())
  4963. return ExprError();
  4964. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4965. Kind = CK_VectorSplat;
  4966. return CastExpr;
  4967. }
  4968. ExprResult
  4969. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4970. Declarator &D, ParsedType &Ty,
  4971. SourceLocation RParenLoc, Expr *CastExpr) {
  4972. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4973. "ActOnCastExpr(): missing type or expr");
  4974. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4975. if (D.isInvalidType())
  4976. return ExprError();
  4977. if (getLangOpts().CPlusPlus) {
  4978. // Check that there are no default arguments (C++ only).
  4979. CheckExtraCXXDefaultArguments(D);
  4980. } else {
  4981. // Make sure any TypoExprs have been dealt with.
  4982. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4983. if (!Res.isUsable())
  4984. return ExprError();
  4985. CastExpr = Res.get();
  4986. }
  4987. checkUnusedDeclAttributes(D);
  4988. QualType castType = castTInfo->getType();
  4989. Ty = CreateParsedType(castType, castTInfo);
  4990. bool isVectorLiteral = false;
  4991. // Check for an altivec or OpenCL literal,
  4992. // i.e. all the elements are integer constants.
  4993. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4994. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4995. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  4996. && castType->isVectorType() && (PE || PLE)) {
  4997. if (PLE && PLE->getNumExprs() == 0) {
  4998. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4999. return ExprError();
  5000. }
  5001. if (PE || PLE->getNumExprs() == 1) {
  5002. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5003. if (!E->getType()->isVectorType())
  5004. isVectorLiteral = true;
  5005. }
  5006. else
  5007. isVectorLiteral = true;
  5008. }
  5009. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5010. // then handle it as such.
  5011. if (isVectorLiteral)
  5012. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5013. // If the Expr being casted is a ParenListExpr, handle it specially.
  5014. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5015. // sequence of BinOp comma operators.
  5016. if (isa<ParenListExpr>(CastExpr)) {
  5017. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5018. if (Result.isInvalid()) return ExprError();
  5019. CastExpr = Result.get();
  5020. }
  5021. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5022. !getSourceManager().isInSystemMacro(LParenLoc))
  5023. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5024. #if 0 // HLSL Change - no support for ObjC constructs
  5025. CheckTollFreeBridgeCast(castType, CastExpr);
  5026. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5027. #endif // HLSL Change
  5028. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5029. }
  5030. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5031. SourceLocation RParenLoc, Expr *E,
  5032. TypeSourceInfo *TInfo) {
  5033. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5034. "Expected paren or paren list expression");
  5035. Expr **exprs;
  5036. unsigned numExprs;
  5037. Expr *subExpr;
  5038. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5039. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5040. LiteralLParenLoc = PE->getLParenLoc();
  5041. LiteralRParenLoc = PE->getRParenLoc();
  5042. exprs = PE->getExprs();
  5043. numExprs = PE->getNumExprs();
  5044. } else { // isa<ParenExpr> by assertion at function entrance
  5045. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5046. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5047. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5048. exprs = &subExpr;
  5049. numExprs = 1;
  5050. }
  5051. QualType Ty = TInfo->getType();
  5052. assert(Ty->isVectorType() && "Expected vector type");
  5053. SmallVector<Expr *, 8> initExprs;
  5054. const VectorType *VTy = Ty->getAs<VectorType>();
  5055. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5056. // '(...)' form of vector initialization in AltiVec: the number of
  5057. // initializers must be one or must match the size of the vector.
  5058. // If a single value is specified in the initializer then it will be
  5059. // replicated to all the components of the vector
  5060. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5061. // The number of initializers must be one or must match the size of the
  5062. // vector. If a single value is specified in the initializer then it will
  5063. // be replicated to all the components of the vector
  5064. if (numExprs == 1) {
  5065. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5066. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5067. if (Literal.isInvalid())
  5068. return ExprError();
  5069. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5070. PrepareScalarCast(Literal, ElemTy));
  5071. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5072. }
  5073. else if (numExprs < numElems) {
  5074. Diag(E->getExprLoc(),
  5075. diag::err_incorrect_number_of_vector_initializers);
  5076. return ExprError();
  5077. }
  5078. else
  5079. initExprs.append(exprs, exprs + numExprs);
  5080. }
  5081. else {
  5082. // For OpenCL, when the number of initializers is a single value,
  5083. // it will be replicated to all components of the vector.
  5084. if (getLangOpts().OpenCL &&
  5085. VTy->getVectorKind() == VectorType::GenericVector &&
  5086. numExprs == 1) {
  5087. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5088. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5089. if (Literal.isInvalid())
  5090. return ExprError();
  5091. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5092. PrepareScalarCast(Literal, ElemTy));
  5093. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5094. }
  5095. initExprs.append(exprs, exprs + numExprs);
  5096. }
  5097. // FIXME: This means that pretty-printing the final AST will produce curly
  5098. // braces instead of the original commas.
  5099. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5100. initExprs, LiteralRParenLoc);
  5101. initE->setType(Ty);
  5102. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5103. }
  5104. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5105. /// the ParenListExpr into a sequence of comma binary operators.
  5106. ExprResult
  5107. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5108. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5109. if (!E)
  5110. return OrigExpr;
  5111. ExprResult Result(E->getExpr(0));
  5112. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5113. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5114. E->getExpr(i));
  5115. if (Result.isInvalid()) return ExprError();
  5116. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5117. }
  5118. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5119. SourceLocation R,
  5120. MultiExprArg Val) {
  5121. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5122. return expr;
  5123. }
  5124. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5125. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5126. /// emitted.
  5127. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5128. SourceLocation QuestionLoc) {
  5129. Expr *NullExpr = LHSExpr;
  5130. Expr *NonPointerExpr = RHSExpr;
  5131. Expr::NullPointerConstantKind NullKind =
  5132. NullExpr->isNullPointerConstant(Context,
  5133. Expr::NPC_ValueDependentIsNotNull);
  5134. if (NullKind == Expr::NPCK_NotNull) {
  5135. NullExpr = RHSExpr;
  5136. NonPointerExpr = LHSExpr;
  5137. NullKind =
  5138. NullExpr->isNullPointerConstant(Context,
  5139. Expr::NPC_ValueDependentIsNotNull);
  5140. }
  5141. if (NullKind == Expr::NPCK_NotNull)
  5142. return false;
  5143. if (NullKind == Expr::NPCK_ZeroExpression)
  5144. return false;
  5145. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5146. // In this case, check to make sure that we got here from a "NULL"
  5147. // string in the source code.
  5148. NullExpr = NullExpr->IgnoreParenImpCasts();
  5149. SourceLocation loc = NullExpr->getExprLoc();
  5150. if (!findMacroSpelling(loc, "NULL"))
  5151. return false;
  5152. }
  5153. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5154. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5155. << NonPointerExpr->getType() << DiagType
  5156. << NonPointerExpr->getSourceRange();
  5157. return true;
  5158. }
  5159. /// \brief Return false if the condition expression is valid, true otherwise.
  5160. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5161. QualType CondTy = Cond->getType();
  5162. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5163. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5164. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5165. << CondTy << Cond->getSourceRange();
  5166. return true;
  5167. }
  5168. // C99 6.5.15p2
  5169. if (CondTy->isScalarType()) return false;
  5170. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5171. << CondTy << Cond->getSourceRange();
  5172. return true;
  5173. }
  5174. /// \brief Handle when one or both operands are void type.
  5175. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5176. ExprResult &RHS) {
  5177. Expr *LHSExpr = LHS.get();
  5178. Expr *RHSExpr = RHS.get();
  5179. if (!LHSExpr->getType()->isVoidType())
  5180. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5181. << RHSExpr->getSourceRange();
  5182. if (!RHSExpr->getType()->isVoidType())
  5183. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5184. << LHSExpr->getSourceRange();
  5185. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5186. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5187. return S.Context.VoidTy;
  5188. }
  5189. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5190. /// true otherwise.
  5191. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5192. QualType PointerTy) {
  5193. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5194. !NullExpr.get()->isNullPointerConstant(S.Context,
  5195. Expr::NPC_ValueDependentIsNull))
  5196. return true;
  5197. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5198. return false;
  5199. }
  5200. /// \brief Checks compatibility between two pointers and return the resulting
  5201. /// type.
  5202. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5203. ExprResult &RHS,
  5204. SourceLocation Loc) {
  5205. QualType LHSTy = LHS.get()->getType();
  5206. QualType RHSTy = RHS.get()->getType();
  5207. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5208. // Two identical pointers types are always compatible.
  5209. return LHSTy;
  5210. }
  5211. QualType lhptee, rhptee;
  5212. // Get the pointee types.
  5213. bool IsBlockPointer = false;
  5214. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5215. lhptee = LHSBTy->getPointeeType();
  5216. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5217. IsBlockPointer = true;
  5218. } else {
  5219. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5220. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5221. }
  5222. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5223. // differently qualified versions of compatible types, the result type is
  5224. // a pointer to an appropriately qualified version of the composite
  5225. // type.
  5226. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5227. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5228. // be incompatible with address space 3: they may live on different devices or
  5229. // anything.
  5230. Qualifiers lhQual = lhptee.getQualifiers();
  5231. Qualifiers rhQual = rhptee.getQualifiers();
  5232. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5233. lhQual.removeCVRQualifiers();
  5234. rhQual.removeCVRQualifiers();
  5235. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5236. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5237. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5238. if (CompositeTy.isNull()) {
  5239. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5240. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5241. << RHS.get()->getSourceRange();
  5242. // In this situation, we assume void* type. No especially good
  5243. // reason, but this is what gcc does, and we do have to pick
  5244. // to get a consistent AST.
  5245. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5246. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5247. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5248. return incompatTy;
  5249. }
  5250. // The pointer types are compatible.
  5251. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5252. if (IsBlockPointer)
  5253. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5254. else
  5255. ResultTy = S.Context.getPointerType(ResultTy);
  5256. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5257. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5258. return ResultTy;
  5259. }
  5260. /// \brief Return the resulting type when the operands are both block pointers.
  5261. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5262. ExprResult &LHS,
  5263. ExprResult &RHS,
  5264. SourceLocation Loc) {
  5265. QualType LHSTy = LHS.get()->getType();
  5266. QualType RHSTy = RHS.get()->getType();
  5267. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5268. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5269. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5270. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5271. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5272. return destType;
  5273. }
  5274. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5275. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5276. << RHS.get()->getSourceRange();
  5277. return QualType();
  5278. }
  5279. // We have 2 block pointer types.
  5280. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5281. }
  5282. /// \brief Return the resulting type when the operands are both pointers.
  5283. static QualType
  5284. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5285. ExprResult &RHS,
  5286. SourceLocation Loc) {
  5287. // get the pointer types
  5288. QualType LHSTy = LHS.get()->getType();
  5289. QualType RHSTy = RHS.get()->getType();
  5290. // get the "pointed to" types
  5291. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5292. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5293. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5294. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5295. // Figure out necessary qualifiers (C99 6.5.15p6)
  5296. QualType destPointee
  5297. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5298. QualType destType = S.Context.getPointerType(destPointee);
  5299. // Add qualifiers if necessary.
  5300. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5301. // Promote to void*.
  5302. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5303. return destType;
  5304. }
  5305. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5306. QualType destPointee
  5307. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5308. QualType destType = S.Context.getPointerType(destPointee);
  5309. // Add qualifiers if necessary.
  5310. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5311. // Promote to void*.
  5312. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5313. return destType;
  5314. }
  5315. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5316. }
  5317. /// \brief Return false if the first expression is not an integer and the second
  5318. /// expression is not a pointer, true otherwise.
  5319. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5320. Expr* PointerExpr, SourceLocation Loc,
  5321. bool IsIntFirstExpr) {
  5322. if (!PointerExpr->getType()->isPointerType() ||
  5323. !Int.get()->getType()->isIntegerType())
  5324. return false;
  5325. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5326. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5327. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5328. << Expr1->getType() << Expr2->getType()
  5329. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5330. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5331. CK_IntegralToPointer);
  5332. return true;
  5333. }
  5334. /// \brief Simple conversion between integer and floating point types.
  5335. ///
  5336. /// Used when handling the OpenCL conditional operator where the
  5337. /// condition is a vector while the other operands are scalar.
  5338. ///
  5339. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5340. /// types are either integer or floating type. Between the two
  5341. /// operands, the type with the higher rank is defined as the "result
  5342. /// type". The other operand needs to be promoted to the same type. No
  5343. /// other type promotion is allowed. We cannot use
  5344. /// UsualArithmeticConversions() for this purpose, since it always
  5345. /// promotes promotable types.
  5346. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5347. ExprResult &RHS,
  5348. SourceLocation QuestionLoc) {
  5349. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5350. if (LHS.isInvalid())
  5351. return QualType();
  5352. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5353. if (RHS.isInvalid())
  5354. return QualType();
  5355. // For conversion purposes, we ignore any qualifiers.
  5356. // For example, "const float" and "float" are equivalent.
  5357. QualType LHSType =
  5358. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5359. QualType RHSType =
  5360. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5361. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5362. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5363. << LHSType << LHS.get()->getSourceRange();
  5364. return QualType();
  5365. }
  5366. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5367. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5368. << RHSType << RHS.get()->getSourceRange();
  5369. return QualType();
  5370. }
  5371. // If both types are identical, no conversion is needed.
  5372. if (LHSType == RHSType)
  5373. return LHSType;
  5374. // Now handle "real" floating types (i.e. float, double, long double).
  5375. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5376. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5377. /*IsCompAssign = */ false);
  5378. // Finally, we have two differing integer types.
  5379. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5380. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5381. }
  5382. /// \brief Convert scalar operands to a vector that matches the
  5383. /// condition in length.
  5384. ///
  5385. /// Used when handling the OpenCL conditional operator where the
  5386. /// condition is a vector while the other operands are scalar.
  5387. ///
  5388. /// We first compute the "result type" for the scalar operands
  5389. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5390. /// into a vector of that type where the length matches the condition
  5391. /// vector type. s6.11.6 requires that the element types of the result
  5392. /// and the condition must have the same number of bits.
  5393. static QualType
  5394. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5395. QualType CondTy, SourceLocation QuestionLoc) {
  5396. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5397. if (ResTy.isNull()) return QualType();
  5398. const VectorType *CV = CondTy->getAs<VectorType>();
  5399. assert(CV);
  5400. // Determine the vector result type
  5401. unsigned NumElements = CV->getNumElements();
  5402. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5403. // Ensure that all types have the same number of bits
  5404. if (S.Context.getTypeSize(CV->getElementType())
  5405. != S.Context.getTypeSize(ResTy)) {
  5406. // Since VectorTy is created internally, it does not pretty print
  5407. // with an OpenCL name. Instead, we just print a description.
  5408. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5409. SmallString<64> Str;
  5410. llvm::raw_svector_ostream OS(Str);
  5411. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5412. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5413. << CondTy << OS.str();
  5414. return QualType();
  5415. }
  5416. // Convert operands to the vector result type
  5417. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5418. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5419. return VectorTy;
  5420. }
  5421. /// \brief Return false if this is a valid OpenCL condition vector
  5422. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5423. SourceLocation QuestionLoc) {
  5424. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5425. // integral type.
  5426. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5427. assert(CondTy);
  5428. QualType EleTy = CondTy->getElementType();
  5429. if (EleTy->isIntegerType()) return false;
  5430. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5431. << Cond->getType() << Cond->getSourceRange();
  5432. return true;
  5433. }
  5434. /// \brief Return false if the vector condition type and the vector
  5435. /// result type are compatible.
  5436. ///
  5437. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5438. /// number of elements, and their element types have the same number
  5439. /// of bits.
  5440. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5441. SourceLocation QuestionLoc) {
  5442. const VectorType *CV = CondTy->getAs<VectorType>();
  5443. const VectorType *RV = VecResTy->getAs<VectorType>();
  5444. assert(CV && RV);
  5445. if (CV->getNumElements() != RV->getNumElements()) {
  5446. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5447. << CondTy << VecResTy;
  5448. return true;
  5449. }
  5450. QualType CVE = CV->getElementType();
  5451. QualType RVE = RV->getElementType();
  5452. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5453. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5454. << CondTy << VecResTy;
  5455. return true;
  5456. }
  5457. return false;
  5458. }
  5459. /// \brief Return the resulting type for the conditional operator in
  5460. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5461. /// s6.3.i) when the condition is a vector type.
  5462. static QualType
  5463. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5464. ExprResult &LHS, ExprResult &RHS,
  5465. SourceLocation QuestionLoc) {
  5466. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5467. if (Cond.isInvalid())
  5468. return QualType();
  5469. QualType CondTy = Cond.get()->getType();
  5470. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5471. return QualType();
  5472. // If either operand is a vector then find the vector type of the
  5473. // result as specified in OpenCL v1.1 s6.3.i.
  5474. if (LHS.get()->getType()->isVectorType() ||
  5475. RHS.get()->getType()->isVectorType()) {
  5476. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5477. /*isCompAssign*/false,
  5478. /*AllowBothBool*/true,
  5479. /*AllowBoolConversions*/false);
  5480. if (VecResTy.isNull()) return QualType();
  5481. // The result type must match the condition type as specified in
  5482. // OpenCL v1.1 s6.11.6.
  5483. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5484. return QualType();
  5485. return VecResTy;
  5486. }
  5487. // Both operands are scalar.
  5488. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5489. }
  5490. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5491. /// In that case, LHS = cond.
  5492. /// C99 6.5.15
  5493. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5494. ExprResult &RHS, ExprValueKind &VK,
  5495. ExprObjectKind &OK,
  5496. SourceLocation QuestionLoc) {
  5497. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5498. if (!LHSResult.isUsable()) return QualType();
  5499. LHS = LHSResult;
  5500. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5501. if (!RHSResult.isUsable()) return QualType();
  5502. RHS = RHSResult;
  5503. // HLSL Change Starts: HLSL supports a vector condition and is
  5504. // sufficiently different to merit its own checker.
  5505. if (getLangOpts().HLSL)
  5506. return hlsl::CheckVectorConditional(this, Cond, LHS, RHS, QuestionLoc);
  5507. // HLSL Change Ends
  5508. // C++ is sufficiently different to merit its own checker.
  5509. if (getLangOpts().CPlusPlus)
  5510. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5511. VK = VK_RValue;
  5512. OK = OK_Ordinary;
  5513. // The OpenCL operator with a vector condition is sufficiently
  5514. // different to merit its own checker.
  5515. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5516. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5517. // First, check the condition.
  5518. Cond = UsualUnaryConversions(Cond.get());
  5519. if (Cond.isInvalid())
  5520. return QualType();
  5521. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5522. return QualType();
  5523. // Now check the two expressions.
  5524. if (LHS.get()->getType()->isVectorType() ||
  5525. RHS.get()->getType()->isVectorType())
  5526. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5527. /*AllowBothBool*/true,
  5528. /*AllowBoolConversions*/false);
  5529. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5530. if (LHS.isInvalid() || RHS.isInvalid())
  5531. return QualType();
  5532. QualType LHSTy = LHS.get()->getType();
  5533. QualType RHSTy = RHS.get()->getType();
  5534. // If both operands have arithmetic type, do the usual arithmetic conversions
  5535. // to find a common type: C99 6.5.15p3,5.
  5536. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5537. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5538. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5539. return ResTy;
  5540. }
  5541. // If both operands are the same structure or union type, the result is that
  5542. // type.
  5543. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5544. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5545. if (LHSRT->getDecl() == RHSRT->getDecl())
  5546. // "If both the operands have structure or union type, the result has
  5547. // that type." This implies that CV qualifiers are dropped.
  5548. return LHSTy.getUnqualifiedType();
  5549. // FIXME: Type of conditional expression must be complete in C mode.
  5550. }
  5551. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5552. // The following || allows only one side to be void (a GCC-ism).
  5553. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5554. return checkConditionalVoidType(*this, LHS, RHS);
  5555. }
  5556. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5557. // the type of the other operand."
  5558. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5559. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5560. // All objective-c pointer type analysis is done here.
  5561. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5562. QuestionLoc);
  5563. if (LHS.isInvalid() || RHS.isInvalid())
  5564. return QualType();
  5565. if (!compositeType.isNull())
  5566. return compositeType;
  5567. // Handle block pointer types.
  5568. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5569. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5570. QuestionLoc);
  5571. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5572. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5573. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5574. QuestionLoc);
  5575. // GCC compatibility: soften pointer/integer mismatch. Note that
  5576. // null pointers have been filtered out by this point.
  5577. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5578. /*isIntFirstExpr=*/true))
  5579. return RHSTy;
  5580. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5581. /*isIntFirstExpr=*/false))
  5582. return LHSTy;
  5583. // Emit a better diagnostic if one of the expressions is a null pointer
  5584. // constant and the other is not a pointer type. In this case, the user most
  5585. // likely forgot to take the address of the other expression.
  5586. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5587. return QualType();
  5588. // Otherwise, the operands are not compatible.
  5589. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5590. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5591. << RHS.get()->getSourceRange();
  5592. return QualType();
  5593. }
  5594. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5595. /// two objective-c pointer types of the two input expressions.
  5596. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5597. SourceLocation QuestionLoc) {
  5598. QualType LHSTy = LHS.get()->getType();
  5599. QualType RHSTy = RHS.get()->getType();
  5600. // Handle things like Class and struct objc_class*. Here we case the result
  5601. // to the pseudo-builtin, because that will be implicitly cast back to the
  5602. // redefinition type if an attempt is made to access its fields.
  5603. if (LHSTy->isObjCClassType() &&
  5604. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5605. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5606. return LHSTy;
  5607. }
  5608. if (RHSTy->isObjCClassType() &&
  5609. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5610. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5611. return RHSTy;
  5612. }
  5613. // And the same for struct objc_object* / id
  5614. if (LHSTy->isObjCIdType() &&
  5615. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5616. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5617. return LHSTy;
  5618. }
  5619. if (RHSTy->isObjCIdType() &&
  5620. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5621. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5622. return RHSTy;
  5623. }
  5624. // And the same for struct objc_selector* / SEL
  5625. if (Context.isObjCSelType(LHSTy) &&
  5626. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5627. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5628. return LHSTy;
  5629. }
  5630. if (Context.isObjCSelType(RHSTy) &&
  5631. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5632. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5633. return RHSTy;
  5634. }
  5635. // Check constraints for Objective-C object pointers types.
  5636. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5637. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5638. // Two identical object pointer types are always compatible.
  5639. return LHSTy;
  5640. }
  5641. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5642. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5643. QualType compositeType = LHSTy;
  5644. // If both operands are interfaces and either operand can be
  5645. // assigned to the other, use that type as the composite
  5646. // type. This allows
  5647. // xxx ? (A*) a : (B*) b
  5648. // where B is a subclass of A.
  5649. //
  5650. // Additionally, as for assignment, if either type is 'id'
  5651. // allow silent coercion. Finally, if the types are
  5652. // incompatible then make sure to use 'id' as the composite
  5653. // type so the result is acceptable for sending messages to.
  5654. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5655. // It could return the composite type.
  5656. if (!(compositeType =
  5657. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5658. // Nothing more to do.
  5659. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5660. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5661. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5662. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5663. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5664. RHSTy->isObjCQualifiedIdType()) &&
  5665. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5666. // Need to handle "id<xx>" explicitly.
  5667. // GCC allows qualified id and any Objective-C type to devolve to
  5668. // id. Currently localizing to here until clear this should be
  5669. // part of ObjCQualifiedIdTypesAreCompatible.
  5670. compositeType = Context.getObjCIdType();
  5671. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5672. compositeType = Context.getObjCIdType();
  5673. } else {
  5674. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5675. << LHSTy << RHSTy
  5676. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5677. QualType incompatTy = Context.getObjCIdType();
  5678. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5679. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5680. return incompatTy;
  5681. }
  5682. // The object pointer types are compatible.
  5683. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5684. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5685. return compositeType;
  5686. }
  5687. // Check Objective-C object pointer types and 'void *'
  5688. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5689. if (getLangOpts().ObjCAutoRefCount) {
  5690. // ARC forbids the implicit conversion of object pointers to 'void *',
  5691. // so these types are not compatible.
  5692. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5693. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5694. LHS = RHS = true;
  5695. return QualType();
  5696. }
  5697. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5698. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5699. QualType destPointee
  5700. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5701. QualType destType = Context.getPointerType(destPointee);
  5702. // Add qualifiers if necessary.
  5703. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5704. // Promote to void*.
  5705. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5706. return destType;
  5707. }
  5708. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5709. if (getLangOpts().ObjCAutoRefCount) {
  5710. // ARC forbids the implicit conversion of object pointers to 'void *',
  5711. // so these types are not compatible.
  5712. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5713. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5714. LHS = RHS = true;
  5715. return QualType();
  5716. }
  5717. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5718. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5719. QualType destPointee
  5720. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5721. QualType destType = Context.getPointerType(destPointee);
  5722. // Add qualifiers if necessary.
  5723. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5724. // Promote to void*.
  5725. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5726. return destType;
  5727. }
  5728. return QualType();
  5729. }
  5730. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5731. /// ParenRange in parentheses.
  5732. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5733. const PartialDiagnostic &Note,
  5734. SourceRange ParenRange) {
  5735. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5736. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5737. EndLoc.isValid()) {
  5738. Self.Diag(Loc, Note)
  5739. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5740. << FixItHint::CreateInsertion(EndLoc, ")");
  5741. } else {
  5742. // We can't display the parentheses, so just show the bare note.
  5743. Self.Diag(Loc, Note) << ParenRange;
  5744. }
  5745. }
  5746. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5747. return Opc >= BO_Mul && Opc <= BO_Shr;
  5748. }
  5749. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5750. /// expression, either using a built-in or overloaded operator,
  5751. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5752. /// expression.
  5753. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5754. Expr **RHSExprs) {
  5755. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5756. E = E->IgnoreImpCasts();
  5757. E = E->IgnoreConversionOperator();
  5758. E = E->IgnoreImpCasts();
  5759. // Built-in binary operator.
  5760. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5761. if (IsArithmeticOp(OP->getOpcode())) {
  5762. *Opcode = OP->getOpcode();
  5763. *RHSExprs = OP->getRHS();
  5764. return true;
  5765. }
  5766. }
  5767. // Overloaded operator.
  5768. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5769. if (Call->getNumArgs() != 2)
  5770. return false;
  5771. // Make sure this is really a binary operator that is safe to pass into
  5772. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5773. OverloadedOperatorKind OO = Call->getOperator();
  5774. if (OO < OO_Plus || OO > OO_Arrow ||
  5775. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5776. return false;
  5777. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5778. if (IsArithmeticOp(OpKind)) {
  5779. *Opcode = OpKind;
  5780. *RHSExprs = Call->getArg(1);
  5781. return true;
  5782. }
  5783. }
  5784. return false;
  5785. }
  5786. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5787. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5788. }
  5789. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5790. /// or is a logical expression such as (x==y) which has int type, but is
  5791. /// commonly interpreted as boolean.
  5792. static bool ExprLooksBoolean(Expr *E) {
  5793. E = E->IgnoreParenImpCasts();
  5794. if (E->getType()->isBooleanType())
  5795. return true;
  5796. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5797. return IsLogicOp(OP->getOpcode());
  5798. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5799. return OP->getOpcode() == UO_LNot;
  5800. if (E->getType()->isPointerType())
  5801. return true;
  5802. return false;
  5803. }
  5804. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5805. /// and binary operator are mixed in a way that suggests the programmer assumed
  5806. /// the conditional operator has higher precedence, for example:
  5807. /// "int x = a + someBinaryCondition ? 1 : 2".
  5808. static void DiagnoseConditionalPrecedence(Sema &Self,
  5809. SourceLocation OpLoc,
  5810. Expr *Condition,
  5811. Expr *LHSExpr,
  5812. Expr *RHSExpr) {
  5813. BinaryOperatorKind CondOpcode;
  5814. Expr *CondRHS;
  5815. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5816. return;
  5817. if (!ExprLooksBoolean(CondRHS))
  5818. return;
  5819. // The condition is an arithmetic binary expression, with a right-
  5820. // hand side that looks boolean, so warn.
  5821. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5822. << Condition->getSourceRange()
  5823. << BinaryOperator::getOpcodeStr(CondOpcode);
  5824. SuggestParentheses(Self, OpLoc,
  5825. Self.PDiag(diag::note_precedence_silence)
  5826. << BinaryOperator::getOpcodeStr(CondOpcode),
  5827. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5828. SuggestParentheses(Self, OpLoc,
  5829. Self.PDiag(diag::note_precedence_conditional_first),
  5830. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5831. }
  5832. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5833. /// in the case of a the GNU conditional expr extension.
  5834. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5835. SourceLocation ColonLoc,
  5836. Expr *CondExpr, Expr *LHSExpr,
  5837. Expr *RHSExpr) {
  5838. if (!getLangOpts().CPlusPlus) {
  5839. // C cannot handle TypoExpr nodes in the condition because it
  5840. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5841. // been dealt with before checking the operands.
  5842. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5843. if (!CondResult.isUsable()) return ExprError();
  5844. CondExpr = CondResult.get();
  5845. }
  5846. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5847. // was the condition.
  5848. OpaqueValueExpr *opaqueValue = nullptr;
  5849. Expr *commonExpr = nullptr;
  5850. if (!LHSExpr) {
  5851. commonExpr = CondExpr;
  5852. // Lower out placeholder types first. This is important so that we don't
  5853. // try to capture a placeholder. This happens in few cases in C++; such
  5854. // as Objective-C++'s dictionary subscripting syntax.
  5855. if (commonExpr->hasPlaceholderType()) {
  5856. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5857. if (!result.isUsable()) return ExprError();
  5858. commonExpr = result.get();
  5859. }
  5860. // We usually want to apply unary conversions *before* saving, except
  5861. // in the special case of a C++ l-value conditional.
  5862. if (!(getLangOpts().CPlusPlus
  5863. && !commonExpr->isTypeDependent()
  5864. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5865. && commonExpr->isGLValue()
  5866. && commonExpr->isOrdinaryOrBitFieldObject()
  5867. && RHSExpr->isOrdinaryOrBitFieldObject()
  5868. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5869. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5870. if (commonRes.isInvalid())
  5871. return ExprError();
  5872. commonExpr = commonRes.get();
  5873. }
  5874. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5875. commonExpr->getType(),
  5876. commonExpr->getValueKind(),
  5877. commonExpr->getObjectKind(),
  5878. commonExpr);
  5879. LHSExpr = CondExpr = opaqueValue;
  5880. }
  5881. ExprValueKind VK = VK_RValue;
  5882. ExprObjectKind OK = OK_Ordinary;
  5883. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5884. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5885. VK, OK, QuestionLoc);
  5886. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5887. RHS.isInvalid())
  5888. return ExprError();
  5889. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5890. RHS.get());
  5891. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5892. if (!commonExpr)
  5893. return new (Context)
  5894. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5895. RHS.get(), result, VK, OK);
  5896. return new (Context) BinaryConditionalOperator(
  5897. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5898. ColonLoc, result, VK, OK);
  5899. }
  5900. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5901. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5902. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5903. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5904. // FIXME: add a couple examples in this comment.
  5905. static Sema::AssignConvertType
  5906. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5907. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5908. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5909. // get the "pointed to" type (ignoring qualifiers at the top level)
  5910. const Type *lhptee, *rhptee;
  5911. Qualifiers lhq, rhq;
  5912. std::tie(lhptee, lhq) =
  5913. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5914. std::tie(rhptee, rhq) =
  5915. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5916. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5917. // C99 6.5.16.1p1: This following citation is common to constraints
  5918. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5919. // qualifiers of the type *pointed to* by the right;
  5920. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5921. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5922. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5923. // Ignore lifetime for further calculation.
  5924. lhq.removeObjCLifetime();
  5925. rhq.removeObjCLifetime();
  5926. }
  5927. if (!lhq.compatiblyIncludes(rhq)) {
  5928. // Treat address-space mismatches as fatal. TODO: address subspaces
  5929. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5930. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5931. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5932. // and from void*.
  5933. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5934. .compatiblyIncludes(
  5935. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5936. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5937. ; // keep old
  5938. // Treat lifetime mismatches as fatal.
  5939. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5940. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5941. // For GCC compatibility, other qualifier mismatches are treated
  5942. // as still compatible in C.
  5943. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5944. }
  5945. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5946. // incomplete type and the other is a pointer to a qualified or unqualified
  5947. // version of void...
  5948. if (lhptee->isVoidType()) {
  5949. if (rhptee->isIncompleteOrObjectType())
  5950. return ConvTy;
  5951. // As an extension, we allow cast to/from void* to function pointer.
  5952. assert(rhptee->isFunctionType());
  5953. return Sema::FunctionVoidPointer;
  5954. }
  5955. if (rhptee->isVoidType()) {
  5956. if (lhptee->isIncompleteOrObjectType())
  5957. return ConvTy;
  5958. // As an extension, we allow cast to/from void* to function pointer.
  5959. assert(lhptee->isFunctionType());
  5960. return Sema::FunctionVoidPointer;
  5961. }
  5962. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5963. // unqualified versions of compatible types, ...
  5964. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5965. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5966. // Check if the pointee types are compatible ignoring the sign.
  5967. // We explicitly check for char so that we catch "char" vs
  5968. // "unsigned char" on systems where "char" is unsigned.
  5969. if (lhptee->isCharType())
  5970. ltrans = S.Context.UnsignedCharTy;
  5971. else if (lhptee->hasSignedIntegerRepresentation())
  5972. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5973. if (rhptee->isCharType())
  5974. rtrans = S.Context.UnsignedCharTy;
  5975. else if (rhptee->hasSignedIntegerRepresentation())
  5976. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5977. if (ltrans == rtrans) {
  5978. // Types are compatible ignoring the sign. Qualifier incompatibility
  5979. // takes priority over sign incompatibility because the sign
  5980. // warning can be disabled.
  5981. if (ConvTy != Sema::Compatible)
  5982. return ConvTy;
  5983. return Sema::IncompatiblePointerSign;
  5984. }
  5985. // If we are a multi-level pointer, it's possible that our issue is simply
  5986. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5987. // the eventual target type is the same and the pointers have the same
  5988. // level of indirection, this must be the issue.
  5989. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5990. do {
  5991. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5992. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5993. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5994. if (lhptee == rhptee)
  5995. return Sema::IncompatibleNestedPointerQualifiers;
  5996. }
  5997. // General pointer incompatibility takes priority over qualifiers.
  5998. return Sema::IncompatiblePointer;
  5999. }
  6000. if (!S.getLangOpts().CPlusPlus &&
  6001. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  6002. return Sema::IncompatiblePointer;
  6003. return ConvTy;
  6004. }
  6005. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6006. /// block pointer types are compatible or whether a block and normal pointer
  6007. /// are compatible. It is more restrict than comparing two function pointer
  6008. // types.
  6009. static Sema::AssignConvertType
  6010. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6011. QualType RHSType) {
  6012. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6013. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6014. QualType lhptee, rhptee;
  6015. // get the "pointed to" type (ignoring qualifiers at the top level)
  6016. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6017. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6018. // In C++, the types have to match exactly.
  6019. if (S.getLangOpts().CPlusPlus)
  6020. return Sema::IncompatibleBlockPointer;
  6021. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6022. // For blocks we enforce that qualifiers are identical.
  6023. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  6024. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6025. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6026. return Sema::IncompatibleBlockPointer;
  6027. return ConvTy;
  6028. }
  6029. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6030. /// for assignment compatibility.
  6031. static Sema::AssignConvertType
  6032. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6033. QualType RHSType) {
  6034. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6035. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6036. if (LHSType->isObjCBuiltinType()) {
  6037. // Class is not compatible with ObjC object pointers.
  6038. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6039. !RHSType->isObjCQualifiedClassType())
  6040. return Sema::IncompatiblePointer;
  6041. return Sema::Compatible;
  6042. }
  6043. if (RHSType->isObjCBuiltinType()) {
  6044. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6045. !LHSType->isObjCQualifiedClassType())
  6046. return Sema::IncompatiblePointer;
  6047. return Sema::Compatible;
  6048. }
  6049. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6050. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6051. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6052. // make an exception for id<P>
  6053. !LHSType->isObjCQualifiedIdType())
  6054. return Sema::CompatiblePointerDiscardsQualifiers;
  6055. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6056. return Sema::Compatible;
  6057. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6058. return Sema::IncompatibleObjCQualifiedId;
  6059. return Sema::IncompatiblePointer;
  6060. }
  6061. Sema::AssignConvertType
  6062. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6063. QualType LHSType, QualType RHSType) {
  6064. // Fake up an opaque expression. We don't actually care about what
  6065. // cast operations are required, so if CheckAssignmentConstraints
  6066. // adds casts to this they'll be wasted, but fortunately that doesn't
  6067. // usually happen on valid code.
  6068. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6069. ExprResult RHSPtr = &RHSExpr;
  6070. CastKind K = CK_Invalid;
  6071. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  6072. }
  6073. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6074. /// has code to accommodate several GCC extensions when type checking
  6075. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6076. ///
  6077. /// int a, *pint;
  6078. /// short *pshort;
  6079. /// struct foo *pfoo;
  6080. ///
  6081. /// pint = pshort; // warning: assignment from incompatible pointer type
  6082. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6083. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6084. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6085. ///
  6086. /// As a result, the code for dealing with pointers is more complex than the
  6087. /// C99 spec dictates.
  6088. ///
  6089. /// Sets 'Kind' for any result kind except Incompatible.
  6090. Sema::AssignConvertType
  6091. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6092. CastKind &Kind) {
  6093. QualType RHSType = RHS.get()->getType();
  6094. QualType OrigLHSType = LHSType;
  6095. // Get canonical types. We're not formatting these types, just comparing
  6096. // them.
  6097. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6098. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6099. // Common case: no conversion required.
  6100. if (LHSType == RHSType) {
  6101. Kind = CK_NoOp;
  6102. return Compatible;
  6103. }
  6104. // If we have an atomic type, try a non-atomic assignment, then just add an
  6105. // atomic qualification step.
  6106. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6107. Sema::AssignConvertType result =
  6108. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6109. if (result != Compatible)
  6110. return result;
  6111. if (Kind != CK_NoOp)
  6112. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6113. Kind = CK_NonAtomicToAtomic;
  6114. return Compatible;
  6115. }
  6116. // If the left-hand side is a reference type, then we are in a
  6117. // (rare!) case where we've allowed the use of references in C,
  6118. // e.g., as a parameter type in a built-in function. In this case,
  6119. // just make sure that the type referenced is compatible with the
  6120. // right-hand side type. The caller is responsible for adjusting
  6121. // LHSType so that the resulting expression does not have reference
  6122. // type.
  6123. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6124. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6125. Kind = CK_LValueBitCast;
  6126. return Compatible;
  6127. }
  6128. return Incompatible;
  6129. }
  6130. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6131. // to the same ExtVector type.
  6132. if (LHSType->isExtVectorType()) {
  6133. if (RHSType->isExtVectorType())
  6134. return Incompatible;
  6135. if (RHSType->isArithmeticType()) {
  6136. // CK_VectorSplat does T -> vector T, so first cast to the
  6137. // element type.
  6138. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  6139. if (elType != RHSType) {
  6140. Kind = PrepareScalarCast(RHS, elType);
  6141. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  6142. }
  6143. Kind = CK_VectorSplat;
  6144. return Compatible;
  6145. }
  6146. }
  6147. // Conversions to or from vector type.
  6148. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6149. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6150. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6151. // vector type and vice versa
  6152. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6153. Kind = CK_BitCast;
  6154. return Compatible;
  6155. }
  6156. // If we are allowing lax vector conversions, and LHS and RHS are both
  6157. // vectors, the total size only needs to be the same. This is a bitcast;
  6158. // no bits are changed but the result type is different.
  6159. if (isLaxVectorConversion(RHSType, LHSType)) {
  6160. Kind = CK_BitCast;
  6161. return IncompatibleVectors;
  6162. }
  6163. }
  6164. return Incompatible;
  6165. }
  6166. // Arithmetic conversions.
  6167. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6168. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6169. Kind = PrepareScalarCast(RHS, LHSType);
  6170. return Compatible;
  6171. }
  6172. // Conversions to normal pointers.
  6173. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6174. // U* -> T*
  6175. if (isa<PointerType>(RHSType)) {
  6176. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6177. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6178. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6179. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6180. }
  6181. // int -> T*
  6182. if (RHSType->isIntegerType()) {
  6183. Kind = CK_IntegralToPointer; // FIXME: null?
  6184. return IntToPointer;
  6185. }
  6186. // C pointers are not compatible with ObjC object pointers,
  6187. // with two exceptions:
  6188. if (isa<ObjCObjectPointerType>(RHSType)) {
  6189. // - conversions to void*
  6190. if (LHSPointer->getPointeeType()->isVoidType()) {
  6191. Kind = CK_BitCast;
  6192. return Compatible;
  6193. }
  6194. // - conversions from 'Class' to the redefinition type
  6195. if (RHSType->isObjCClassType() &&
  6196. Context.hasSameType(LHSType,
  6197. Context.getObjCClassRedefinitionType())) {
  6198. Kind = CK_BitCast;
  6199. return Compatible;
  6200. }
  6201. Kind = CK_BitCast;
  6202. return IncompatiblePointer;
  6203. }
  6204. // U^ -> void*
  6205. if (RHSType->getAs<BlockPointerType>()) {
  6206. if (LHSPointer->getPointeeType()->isVoidType()) {
  6207. Kind = CK_BitCast;
  6208. return Compatible;
  6209. }
  6210. }
  6211. return Incompatible;
  6212. }
  6213. // Conversions to block pointers.
  6214. if (isa<BlockPointerType>(LHSType)) {
  6215. // U^ -> T^
  6216. if (RHSType->isBlockPointerType()) {
  6217. Kind = CK_BitCast;
  6218. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6219. }
  6220. // int or null -> T^
  6221. if (RHSType->isIntegerType()) {
  6222. Kind = CK_IntegralToPointer; // FIXME: null
  6223. return IntToBlockPointer;
  6224. }
  6225. // id -> T^
  6226. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6227. Kind = CK_AnyPointerToBlockPointerCast;
  6228. return Compatible;
  6229. }
  6230. // void* -> T^
  6231. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6232. if (RHSPT->getPointeeType()->isVoidType()) {
  6233. Kind = CK_AnyPointerToBlockPointerCast;
  6234. return Compatible;
  6235. }
  6236. return Incompatible;
  6237. }
  6238. // Conversions to Objective-C pointers.
  6239. if (isa<ObjCObjectPointerType>(LHSType)) {
  6240. // A* -> B*
  6241. if (RHSType->isObjCObjectPointerType()) {
  6242. Kind = CK_BitCast;
  6243. Sema::AssignConvertType result =
  6244. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6245. if (getLangOpts().ObjCAutoRefCount &&
  6246. result == Compatible &&
  6247. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6248. result = IncompatibleObjCWeakRef;
  6249. return result;
  6250. }
  6251. // int or null -> A*
  6252. if (RHSType->isIntegerType()) {
  6253. Kind = CK_IntegralToPointer; // FIXME: null
  6254. return IntToPointer;
  6255. }
  6256. // In general, C pointers are not compatible with ObjC object pointers,
  6257. // with two exceptions:
  6258. if (isa<PointerType>(RHSType)) {
  6259. Kind = CK_CPointerToObjCPointerCast;
  6260. // - conversions from 'void*'
  6261. if (RHSType->isVoidPointerType()) {
  6262. return Compatible;
  6263. }
  6264. // - conversions to 'Class' from its redefinition type
  6265. if (LHSType->isObjCClassType() &&
  6266. Context.hasSameType(RHSType,
  6267. Context.getObjCClassRedefinitionType())) {
  6268. return Compatible;
  6269. }
  6270. return IncompatiblePointer;
  6271. }
  6272. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6273. if (RHSType->isBlockPointerType() &&
  6274. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6275. maybeExtendBlockObject(RHS);
  6276. Kind = CK_BlockPointerToObjCPointerCast;
  6277. return Compatible;
  6278. }
  6279. return Incompatible;
  6280. }
  6281. // Conversions from pointers that are not covered by the above.
  6282. if (isa<PointerType>(RHSType)) {
  6283. // T* -> _Bool
  6284. if (LHSType == Context.BoolTy) {
  6285. Kind = CK_PointerToBoolean;
  6286. return Compatible;
  6287. }
  6288. // T* -> int
  6289. if (LHSType->isIntegerType()) {
  6290. Kind = CK_PointerToIntegral;
  6291. return PointerToInt;
  6292. }
  6293. return Incompatible;
  6294. }
  6295. // Conversions from Objective-C pointers that are not covered by the above.
  6296. if (isa<ObjCObjectPointerType>(RHSType)) {
  6297. // T* -> _Bool
  6298. if (LHSType == Context.BoolTy) {
  6299. Kind = CK_PointerToBoolean;
  6300. return Compatible;
  6301. }
  6302. // T* -> int
  6303. if (LHSType->isIntegerType()) {
  6304. Kind = CK_PointerToIntegral;
  6305. return PointerToInt;
  6306. }
  6307. return Incompatible;
  6308. }
  6309. // struct A -> struct B
  6310. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6311. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6312. Kind = CK_NoOp;
  6313. return Compatible;
  6314. }
  6315. }
  6316. return Incompatible;
  6317. }
  6318. /// \brief Constructs a transparent union from an expression that is
  6319. /// used to initialize the transparent union.
  6320. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6321. ExprResult &EResult, QualType UnionType,
  6322. FieldDecl *Field) {
  6323. // Build an initializer list that designates the appropriate member
  6324. // of the transparent union.
  6325. Expr *E = EResult.get();
  6326. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6327. E, SourceLocation());
  6328. Initializer->setType(UnionType);
  6329. Initializer->setInitializedFieldInUnion(Field);
  6330. // Build a compound literal constructing a value of the transparent
  6331. // union type from this initializer list.
  6332. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6333. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6334. VK_RValue, Initializer, false);
  6335. }
  6336. Sema::AssignConvertType
  6337. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6338. ExprResult &RHS) {
  6339. QualType RHSType = RHS.get()->getType();
  6340. // If the ArgType is a Union type, we want to handle a potential
  6341. // transparent_union GCC extension.
  6342. const RecordType *UT = ArgType->getAsUnionType();
  6343. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6344. return Incompatible;
  6345. // The field to initialize within the transparent union.
  6346. RecordDecl *UD = UT->getDecl();
  6347. FieldDecl *InitField = nullptr;
  6348. // It's compatible if the expression matches any of the fields.
  6349. for (auto *it : UD->fields()) {
  6350. if (it->getType()->isPointerType()) {
  6351. // If the transparent union contains a pointer type, we allow:
  6352. // 1) void pointer
  6353. // 2) null pointer constant
  6354. if (RHSType->isPointerType())
  6355. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6356. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6357. InitField = it;
  6358. break;
  6359. }
  6360. if (RHS.get()->isNullPointerConstant(Context,
  6361. Expr::NPC_ValueDependentIsNull)) {
  6362. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6363. CK_NullToPointer);
  6364. InitField = it;
  6365. break;
  6366. }
  6367. }
  6368. CastKind Kind = CK_Invalid;
  6369. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6370. == Compatible) {
  6371. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6372. InitField = it;
  6373. break;
  6374. }
  6375. }
  6376. if (!InitField)
  6377. return Incompatible;
  6378. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6379. return Compatible;
  6380. }
  6381. Sema::AssignConvertType
  6382. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6383. bool Diagnose,
  6384. bool DiagnoseCFAudited) {
  6385. // HLSL Change Starts
  6386. if (getLangOpts().HLSL) {
  6387. // implicit conversion will take care of diagnostics.
  6388. return Compatible;
  6389. }
  6390. // HLSL Change Ends
  6391. if (getLangOpts().CPlusPlus) {
  6392. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6393. // C++ 5.17p3: If the left operand is not of class type, the
  6394. // expression is implicitly converted (C++ 4) to the
  6395. // cv-unqualified type of the left operand.
  6396. ExprResult Res;
  6397. if (Diagnose) {
  6398. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6399. AA_Assigning);
  6400. } else {
  6401. ImplicitConversionSequence ICS =
  6402. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6403. /*SuppressUserConversions=*/false,
  6404. /*AllowExplicit=*/false,
  6405. /*InOverloadResolution=*/false,
  6406. /*CStyle=*/false,
  6407. /*AllowObjCWritebackConversion=*/false);
  6408. if (ICS.isFailure())
  6409. return Incompatible;
  6410. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6411. ICS, AA_Assigning);
  6412. }
  6413. if (Res.isInvalid())
  6414. return Incompatible;
  6415. Sema::AssignConvertType result = Compatible;
  6416. if (getLangOpts().ObjCAutoRefCount &&
  6417. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6418. RHS.get()->getType()))
  6419. result = IncompatibleObjCWeakRef;
  6420. RHS = Res;
  6421. return result;
  6422. }
  6423. // FIXME: Currently, we fall through and treat C++ classes like C
  6424. // structures.
  6425. // FIXME: We also fall through for atomics; not sure what should
  6426. // happen there, though.
  6427. }
  6428. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6429. // a null pointer constant.
  6430. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6431. LHSType->isBlockPointerType()) &&
  6432. RHS.get()->isNullPointerConstant(Context,
  6433. Expr::NPC_ValueDependentIsNull)) {
  6434. CastKind Kind;
  6435. CXXCastPath Path;
  6436. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6437. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6438. return Compatible;
  6439. }
  6440. // This check seems unnatural, however it is necessary to ensure the proper
  6441. // conversion of functions/arrays. If the conversion were done for all
  6442. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6443. // expressions that suppress this implicit conversion (&, sizeof).
  6444. //
  6445. // Suppress this for references: C++ 8.5.3p5.
  6446. if (!LHSType->isReferenceType()) {
  6447. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6448. if (RHS.isInvalid())
  6449. return Incompatible;
  6450. }
  6451. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6452. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6453. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6454. if (PDecl && !PDecl->hasDefinition()) {
  6455. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6456. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6457. }
  6458. }
  6459. CastKind Kind = CK_Invalid;
  6460. Sema::AssignConvertType result =
  6461. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6462. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6463. // type of the assignment expression.
  6464. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6465. // so that we can use references in built-in functions even in C.
  6466. // The getNonReferenceType() call makes sure that the resulting expression
  6467. // does not have reference type.
  6468. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6469. QualType Ty = LHSType.getNonLValueExprType(Context);
  6470. Expr *E = RHS.get();
  6471. if (getLangOpts().ObjCAutoRefCount)
  6472. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6473. DiagnoseCFAudited);
  6474. if (getLangOpts().ObjC1 &&
  6475. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6476. LHSType, E->getType(), E) ||
  6477. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6478. RHS = E;
  6479. return Compatible;
  6480. }
  6481. RHS = ImpCastExprToType(E, Ty, Kind);
  6482. }
  6483. return result;
  6484. }
  6485. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6486. ExprResult &RHS) {
  6487. Diag(Loc, diag::err_typecheck_invalid_operands)
  6488. << LHS.get()->getType() << RHS.get()->getType()
  6489. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6490. return QualType();
  6491. }
  6492. /// Try to convert a value of non-vector type to a vector type by converting
  6493. /// the type to the element type of the vector and then performing a splat.
  6494. /// If the language is OpenCL, we only use conversions that promote scalar
  6495. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6496. /// for float->int.
  6497. ///
  6498. /// \param scalar - if non-null, actually perform the conversions
  6499. /// \return true if the operation fails (but without diagnosing the failure)
  6500. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6501. QualType scalarTy,
  6502. QualType vectorEltTy,
  6503. QualType vectorTy) {
  6504. // The conversion to apply to the scalar before splatting it,
  6505. // if necessary.
  6506. CastKind scalarCast = CK_Invalid;
  6507. if (vectorEltTy->isIntegralType(S.Context)) {
  6508. if (!scalarTy->isIntegralType(S.Context))
  6509. return true;
  6510. if (S.getLangOpts().OpenCL &&
  6511. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6512. return true;
  6513. scalarCast = CK_IntegralCast;
  6514. } else if (vectorEltTy->isRealFloatingType()) {
  6515. if (scalarTy->isRealFloatingType()) {
  6516. if (S.getLangOpts().OpenCL &&
  6517. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6518. return true;
  6519. scalarCast = CK_FloatingCast;
  6520. }
  6521. else if (scalarTy->isIntegralType(S.Context))
  6522. scalarCast = CK_IntegralToFloating;
  6523. else
  6524. return true;
  6525. } else {
  6526. return true;
  6527. }
  6528. // Adjust scalar if desired.
  6529. if (scalar) {
  6530. if (scalarCast != CK_Invalid)
  6531. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6532. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6533. }
  6534. return false;
  6535. }
  6536. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6537. SourceLocation Loc, bool IsCompAssign,
  6538. bool AllowBothBool,
  6539. bool AllowBoolConversions) {
  6540. if (!IsCompAssign) {
  6541. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6542. if (LHS.isInvalid())
  6543. return QualType();
  6544. }
  6545. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6546. if (RHS.isInvalid())
  6547. return QualType();
  6548. // For conversion purposes, we ignore any qualifiers.
  6549. // For example, "const float" and "float" are equivalent.
  6550. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6551. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6552. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6553. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6554. assert(LHSVecType || RHSVecType);
  6555. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6556. // for some operators but not others.
  6557. if (!AllowBothBool &&
  6558. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6559. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6560. return InvalidOperands(Loc, LHS, RHS);
  6561. // If the vector types are identical, return.
  6562. if (Context.hasSameType(LHSType, RHSType))
  6563. return LHSType;
  6564. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6565. if (LHSVecType && RHSVecType &&
  6566. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6567. if (isa<ExtVectorType>(LHSVecType)) {
  6568. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6569. return LHSType;
  6570. }
  6571. if (!IsCompAssign)
  6572. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6573. return RHSType;
  6574. }
  6575. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6576. // can be mixed, with the result being the non-bool type. The non-bool
  6577. // operand must have integer element type.
  6578. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6579. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6580. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6581. Context.getTypeSize(RHSVecType->getElementType()))) {
  6582. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6583. LHSVecType->getElementType()->isIntegerType() &&
  6584. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6585. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6586. return LHSType;
  6587. }
  6588. if (!IsCompAssign &&
  6589. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6590. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6591. RHSVecType->getElementType()->isIntegerType()) {
  6592. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6593. return RHSType;
  6594. }
  6595. }
  6596. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6597. // the vector element type and splat.
  6598. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6599. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6600. LHSVecType->getElementType(), LHSType))
  6601. return LHSType;
  6602. }
  6603. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6604. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6605. LHSType, RHSVecType->getElementType(),
  6606. RHSType))
  6607. return RHSType;
  6608. }
  6609. // If we're allowing lax vector conversions, only the total (data) size
  6610. // needs to be the same.
  6611. // FIXME: Should we really be allowing this?
  6612. // FIXME: We really just pick the LHS type arbitrarily?
  6613. if (isLaxVectorConversion(RHSType, LHSType)) {
  6614. QualType resultType = LHSType;
  6615. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6616. return resultType;
  6617. }
  6618. // Okay, the expression is invalid.
  6619. // If there's a non-vector, non-real operand, diagnose that.
  6620. if ((!RHSVecType && !RHSType->isRealType()) ||
  6621. (!LHSVecType && !LHSType->isRealType())) {
  6622. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6623. << LHSType << RHSType
  6624. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6625. return QualType();
  6626. }
  6627. // Otherwise, use the generic diagnostic.
  6628. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6629. << LHSType << RHSType
  6630. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6631. return QualType();
  6632. }
  6633. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6634. // expression. These are mainly cases where the null pointer is used as an
  6635. // integer instead of a pointer.
  6636. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6637. SourceLocation Loc, bool IsCompare) {
  6638. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6639. // but we use a bit of a hack here for speed; this is a relatively
  6640. // hot path, and isNullPointerConstant is slow.
  6641. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6642. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6643. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6644. // Avoid analyzing cases where the result will either be invalid (and
  6645. // diagnosed as such) or entirely valid and not something to warn about.
  6646. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6647. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6648. return;
  6649. // Comparison operations would not make sense with a null pointer no matter
  6650. // what the other expression is.
  6651. if (!IsCompare) {
  6652. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6653. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6654. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6655. return;
  6656. }
  6657. // The rest of the operations only make sense with a null pointer
  6658. // if the other expression is a pointer.
  6659. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6660. NonNullType->canDecayToPointerType())
  6661. return;
  6662. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6663. << LHSNull /* LHS is NULL */ << NonNullType
  6664. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6665. }
  6666. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6667. SourceLocation Loc,
  6668. bool IsCompAssign, bool IsDiv) {
  6669. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6670. if (LHS.get()->getType()->isVectorType() ||
  6671. RHS.get()->getType()->isVectorType())
  6672. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6673. /*AllowBothBool*/getLangOpts().AltiVec,
  6674. /*AllowBoolConversions*/false);
  6675. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6676. if (LHS.isInvalid() || RHS.isInvalid())
  6677. return QualType();
  6678. if (compType.isNull() || !compType->isArithmeticType())
  6679. return InvalidOperands(Loc, LHS, RHS);
  6680. // Check for division by zero.
  6681. llvm::APSInt RHSValue;
  6682. if (IsDiv && !RHS.get()->isValueDependent() &&
  6683. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6684. DiagRuntimeBehavior(Loc, RHS.get(),
  6685. PDiag(diag::warn_division_by_zero)
  6686. << RHS.get()->getSourceRange());
  6687. return compType;
  6688. }
  6689. QualType Sema::CheckRemainderOperands(
  6690. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6691. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6692. if (LHS.get()->getType()->isVectorType() ||
  6693. RHS.get()->getType()->isVectorType()) {
  6694. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6695. RHS.get()->getType()->hasIntegerRepresentation())
  6696. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6697. /*AllowBothBool*/getLangOpts().AltiVec,
  6698. /*AllowBoolConversions*/false);
  6699. return InvalidOperands(Loc, LHS, RHS);
  6700. }
  6701. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6702. if (LHS.isInvalid() || RHS.isInvalid())
  6703. return QualType();
  6704. if (compType.isNull() || !compType->isIntegerType())
  6705. return InvalidOperands(Loc, LHS, RHS);
  6706. // Check for remainder by zero.
  6707. llvm::APSInt RHSValue;
  6708. if (!RHS.get()->isValueDependent() &&
  6709. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6710. DiagRuntimeBehavior(Loc, RHS.get(),
  6711. PDiag(diag::warn_remainder_by_zero)
  6712. << RHS.get()->getSourceRange());
  6713. return compType;
  6714. }
  6715. /// \brief Diagnose invalid arithmetic on two void pointers.
  6716. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6717. Expr *LHSExpr, Expr *RHSExpr) {
  6718. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6719. ? diag::err_typecheck_pointer_arith_void_type
  6720. : diag::ext_gnu_void_ptr)
  6721. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6722. << RHSExpr->getSourceRange();
  6723. }
  6724. /// \brief Diagnose invalid arithmetic on a void pointer.
  6725. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6726. Expr *Pointer) {
  6727. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6728. ? diag::err_typecheck_pointer_arith_void_type
  6729. : diag::ext_gnu_void_ptr)
  6730. << 0 /* one pointer */ << Pointer->getSourceRange();
  6731. }
  6732. /// \brief Diagnose invalid arithmetic on two function pointers.
  6733. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6734. Expr *LHS, Expr *RHS) {
  6735. assert(LHS->getType()->isAnyPointerType());
  6736. assert(RHS->getType()->isAnyPointerType());
  6737. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6738. ? diag::err_typecheck_pointer_arith_function_type
  6739. : diag::ext_gnu_ptr_func_arith)
  6740. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6741. // We only show the second type if it differs from the first.
  6742. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6743. RHS->getType())
  6744. << RHS->getType()->getPointeeType()
  6745. << LHS->getSourceRange() << RHS->getSourceRange();
  6746. }
  6747. /// \brief Diagnose invalid arithmetic on a function pointer.
  6748. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6749. Expr *Pointer) {
  6750. assert(Pointer->getType()->isAnyPointerType());
  6751. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6752. ? diag::err_typecheck_pointer_arith_function_type
  6753. : diag::ext_gnu_ptr_func_arith)
  6754. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6755. << 0 /* one pointer, so only one type */
  6756. << Pointer->getSourceRange();
  6757. }
  6758. /// \brief Emit error if Operand is incomplete pointer type
  6759. ///
  6760. /// \returns True if pointer has incomplete type
  6761. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6762. Expr *Operand) {
  6763. QualType ResType = Operand->getType();
  6764. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6765. ResType = ResAtomicType->getValueType();
  6766. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6767. QualType PointeeTy = ResType->getPointeeType();
  6768. return S.RequireCompleteType(Loc, PointeeTy,
  6769. diag::err_typecheck_arithmetic_incomplete_type,
  6770. PointeeTy, Operand->getSourceRange());
  6771. }
  6772. /// \brief Check the validity of an arithmetic pointer operand.
  6773. ///
  6774. /// If the operand has pointer type, this code will check for pointer types
  6775. /// which are invalid in arithmetic operations. These will be diagnosed
  6776. /// appropriately, including whether or not the use is supported as an
  6777. /// extension.
  6778. ///
  6779. /// \returns True when the operand is valid to use (even if as an extension).
  6780. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6781. Expr *Operand) {
  6782. QualType ResType = Operand->getType();
  6783. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6784. ResType = ResAtomicType->getValueType();
  6785. if (!ResType->isAnyPointerType()) return true;
  6786. QualType PointeeTy = ResType->getPointeeType();
  6787. if (PointeeTy->isVoidType()) {
  6788. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6789. return !S.getLangOpts().CPlusPlus;
  6790. }
  6791. if (PointeeTy->isFunctionType()) {
  6792. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6793. return !S.getLangOpts().CPlusPlus;
  6794. }
  6795. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6796. return true;
  6797. }
  6798. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6799. /// operands.
  6800. ///
  6801. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6802. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6803. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6804. /// are (potentially problematic) pointers.
  6805. ///
  6806. /// \returns True when the operand is valid to use (even if as an extension).
  6807. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6808. Expr *LHSExpr, Expr *RHSExpr) {
  6809. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6810. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6811. if (!isLHSPointer && !isRHSPointer) return true;
  6812. QualType LHSPointeeTy, RHSPointeeTy;
  6813. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6814. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6815. // if both are pointers check if operation is valid wrt address spaces
  6816. if (isLHSPointer && isRHSPointer) {
  6817. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6818. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6819. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6820. S.Diag(Loc,
  6821. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6822. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6823. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6824. return false;
  6825. }
  6826. }
  6827. // Check for arithmetic on pointers to incomplete types.
  6828. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6829. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6830. if (isLHSVoidPtr || isRHSVoidPtr) {
  6831. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6832. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6833. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6834. return !S.getLangOpts().CPlusPlus;
  6835. }
  6836. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6837. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6838. if (isLHSFuncPtr || isRHSFuncPtr) {
  6839. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6840. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6841. RHSExpr);
  6842. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6843. return !S.getLangOpts().CPlusPlus;
  6844. }
  6845. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6846. return false;
  6847. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6848. return false;
  6849. return true;
  6850. }
  6851. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6852. /// literal.
  6853. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6854. Expr *LHSExpr, Expr *RHSExpr) {
  6855. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6856. Expr* IndexExpr = RHSExpr;
  6857. if (!StrExpr) {
  6858. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6859. IndexExpr = LHSExpr;
  6860. }
  6861. bool IsStringPlusInt = StrExpr &&
  6862. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6863. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6864. return;
  6865. llvm::APSInt index;
  6866. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6867. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6868. if (index.isNonNegative() &&
  6869. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6870. index.isUnsigned()))
  6871. return;
  6872. }
  6873. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6874. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6875. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6876. // Only print a fixit for "str" + int, not for int + "str".
  6877. if (IndexExpr == RHSExpr) {
  6878. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6879. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6880. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6881. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6882. << FixItHint::CreateInsertion(EndLoc, "]");
  6883. } else
  6884. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6885. }
  6886. /// \brief Emit a warning when adding a char literal to a string.
  6887. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6888. Expr *LHSExpr, Expr *RHSExpr) {
  6889. const Expr *StringRefExpr = LHSExpr;
  6890. const CharacterLiteral *CharExpr =
  6891. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6892. if (!CharExpr) {
  6893. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6894. StringRefExpr = RHSExpr;
  6895. }
  6896. if (!CharExpr || !StringRefExpr)
  6897. return;
  6898. const QualType StringType = StringRefExpr->getType();
  6899. // Return if not a PointerType.
  6900. if (!StringType->isAnyPointerType())
  6901. return;
  6902. // Return if not a CharacterType.
  6903. if (!StringType->getPointeeType()->isAnyCharacterType())
  6904. return;
  6905. ASTContext &Ctx = Self.getASTContext();
  6906. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6907. const QualType CharType = CharExpr->getType();
  6908. if (!CharType->isAnyCharacterType() &&
  6909. CharType->isIntegerType() &&
  6910. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6911. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6912. << DiagRange << Ctx.CharTy;
  6913. } else {
  6914. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6915. << DiagRange << CharExpr->getType();
  6916. }
  6917. // Only print a fixit for str + char, not for char + str.
  6918. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6919. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6920. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6921. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6922. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6923. << FixItHint::CreateInsertion(EndLoc, "]");
  6924. } else {
  6925. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6926. }
  6927. }
  6928. /// \brief Emit error when two pointers are incompatible.
  6929. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6930. Expr *LHSExpr, Expr *RHSExpr) {
  6931. assert(LHSExpr->getType()->isAnyPointerType());
  6932. assert(RHSExpr->getType()->isAnyPointerType());
  6933. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6934. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6935. << RHSExpr->getSourceRange();
  6936. }
  6937. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6938. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6939. QualType* CompLHSTy) {
  6940. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6941. if (LHS.get()->getType()->isVectorType() ||
  6942. RHS.get()->getType()->isVectorType()) {
  6943. QualType compType = CheckVectorOperands(
  6944. LHS, RHS, Loc, CompLHSTy,
  6945. /*AllowBothBool*/getLangOpts().AltiVec,
  6946. /*AllowBoolConversions*/getLangOpts().ZVector);
  6947. if (CompLHSTy) *CompLHSTy = compType;
  6948. return compType;
  6949. }
  6950. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6951. if (LHS.isInvalid() || RHS.isInvalid())
  6952. return QualType();
  6953. // Diagnose "string literal" '+' int and string '+' "char literal".
  6954. if (Opc == BO_Add) {
  6955. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6956. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6957. }
  6958. // handle the common case first (both operands are arithmetic).
  6959. if (!compType.isNull() && compType->isArithmeticType()) {
  6960. if (CompLHSTy) *CompLHSTy = compType;
  6961. return compType;
  6962. }
  6963. // Type-checking. Ultimately the pointer's going to be in PExp;
  6964. // note that we bias towards the LHS being the pointer.
  6965. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6966. bool isObjCPointer;
  6967. if (PExp->getType()->isPointerType()) {
  6968. isObjCPointer = false;
  6969. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6970. isObjCPointer = true;
  6971. } else {
  6972. std::swap(PExp, IExp);
  6973. if (PExp->getType()->isPointerType()) {
  6974. isObjCPointer = false;
  6975. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6976. isObjCPointer = true;
  6977. } else {
  6978. return InvalidOperands(Loc, LHS, RHS);
  6979. }
  6980. }
  6981. assert(PExp->getType()->isAnyPointerType());
  6982. if (!IExp->getType()->isIntegerType())
  6983. return InvalidOperands(Loc, LHS, RHS);
  6984. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6985. return QualType();
  6986. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6987. return QualType();
  6988. // Check array bounds for pointer arithemtic
  6989. CheckArrayAccess(PExp, IExp);
  6990. if (CompLHSTy) {
  6991. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6992. if (LHSTy.isNull()) {
  6993. LHSTy = LHS.get()->getType();
  6994. if (LHSTy->isPromotableIntegerType())
  6995. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6996. }
  6997. *CompLHSTy = LHSTy;
  6998. }
  6999. return PExp->getType();
  7000. }
  7001. // C99 6.5.6
  7002. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  7003. SourceLocation Loc,
  7004. QualType* CompLHSTy) {
  7005. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7006. if (LHS.get()->getType()->isVectorType() ||
  7007. RHS.get()->getType()->isVectorType()) {
  7008. QualType compType = CheckVectorOperands(
  7009. LHS, RHS, Loc, CompLHSTy,
  7010. /*AllowBothBool*/getLangOpts().AltiVec,
  7011. /*AllowBoolConversions*/getLangOpts().ZVector);
  7012. if (CompLHSTy) *CompLHSTy = compType;
  7013. return compType;
  7014. }
  7015. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7016. if (LHS.isInvalid() || RHS.isInvalid())
  7017. return QualType();
  7018. // Enforce type constraints: C99 6.5.6p3.
  7019. // Handle the common case first (both operands are arithmetic).
  7020. if (!compType.isNull() && compType->isArithmeticType()) {
  7021. if (CompLHSTy) *CompLHSTy = compType;
  7022. return compType;
  7023. }
  7024. // Either ptr - int or ptr - ptr.
  7025. if (LHS.get()->getType()->isAnyPointerType()) {
  7026. QualType lpointee = LHS.get()->getType()->getPointeeType();
  7027. // Diagnose bad cases where we step over interface counts.
  7028. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  7029. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  7030. return QualType();
  7031. // The result type of a pointer-int computation is the pointer type.
  7032. if (RHS.get()->getType()->isIntegerType()) {
  7033. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  7034. return QualType();
  7035. // Check array bounds for pointer arithemtic
  7036. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  7037. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  7038. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7039. return LHS.get()->getType();
  7040. }
  7041. // Handle pointer-pointer subtractions.
  7042. if (const PointerType *RHSPTy
  7043. = RHS.get()->getType()->getAs<PointerType>()) {
  7044. QualType rpointee = RHSPTy->getPointeeType();
  7045. if (getLangOpts().CPlusPlus) {
  7046. // Pointee types must be the same: C++ [expr.add]
  7047. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  7048. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7049. }
  7050. } else {
  7051. // Pointee types must be compatible C99 6.5.6p3
  7052. if (!Context.typesAreCompatible(
  7053. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  7054. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  7055. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7056. return QualType();
  7057. }
  7058. }
  7059. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  7060. LHS.get(), RHS.get()))
  7061. return QualType();
  7062. // The pointee type may have zero size. As an extension, a structure or
  7063. // union may have zero size or an array may have zero length. In this
  7064. // case subtraction does not make sense.
  7065. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7066. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7067. if (ElementSize.isZero()) {
  7068. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7069. << rpointee.getUnqualifiedType()
  7070. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7071. }
  7072. }
  7073. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7074. return Context.getPointerDiffType();
  7075. }
  7076. }
  7077. return InvalidOperands(Loc, LHS, RHS);
  7078. }
  7079. static bool isScopedEnumerationType(QualType T) {
  7080. if (const EnumType *ET = T->getAs<EnumType>())
  7081. return ET->getDecl()->isScoped();
  7082. return false;
  7083. }
  7084. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7085. SourceLocation Loc, unsigned Opc,
  7086. QualType LHSType) {
  7087. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7088. // so skip remaining warnings as we don't want to modify values within Sema.
  7089. if (S.getLangOpts().OpenCL)
  7090. return;
  7091. llvm::APSInt Right;
  7092. // Check right/shifter operand
  7093. if (RHS.get()->isValueDependent() ||
  7094. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7095. return;
  7096. if (Right.isNegative()) {
  7097. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7098. S.PDiag(diag::warn_shift_negative)
  7099. << RHS.get()->getSourceRange());
  7100. return;
  7101. }
  7102. llvm::APInt LeftBits(Right.getBitWidth(),
  7103. S.Context.getTypeSize(LHS.get()->getType()));
  7104. if (Right.uge(LeftBits)) {
  7105. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7106. S.PDiag(diag::warn_shift_gt_typewidth)
  7107. << RHS.get()->getSourceRange());
  7108. return;
  7109. }
  7110. if (Opc != BO_Shl)
  7111. return;
  7112. // When left shifting an ICE which is signed, we can check for overflow which
  7113. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7114. // integers have defined behavior modulo one more than the maximum value
  7115. // representable in the result type, so never warn for those.
  7116. llvm::APSInt Left;
  7117. if (LHS.get()->isValueDependent() ||
  7118. LHSType->hasUnsignedIntegerRepresentation() ||
  7119. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7120. return;
  7121. // If LHS does not have a signed type and non-negative value
  7122. // then, the behavior is undefined. Warn about it.
  7123. if (Left.isNegative()) {
  7124. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7125. S.PDiag(diag::warn_shift_lhs_negative)
  7126. << LHS.get()->getSourceRange());
  7127. return;
  7128. }
  7129. llvm::APInt ResultBits =
  7130. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7131. if (LeftBits.uge(ResultBits))
  7132. return;
  7133. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  7134. Result = Result.shl(Right);
  7135. // Print the bit representation of the signed integer as an unsigned
  7136. // hexadecimal number.
  7137. SmallString<40> HexResult;
  7138. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  7139. // If we are only missing a sign bit, this is less likely to result in actual
  7140. // bugs -- if the result is cast back to an unsigned type, it will have the
  7141. // expected value. Thus we place this behind a different warning that can be
  7142. // turned off separately if needed.
  7143. if (LeftBits == ResultBits - 1) {
  7144. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  7145. << HexResult << LHSType
  7146. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7147. return;
  7148. }
  7149. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  7150. << HexResult.str() << Result.getMinSignedBits() << LHSType
  7151. << Left.getBitWidth() << LHS.get()->getSourceRange()
  7152. << RHS.get()->getSourceRange();
  7153. }
  7154. /// \brief Return the resulting type when an OpenCL vector is shifted
  7155. /// by a scalar or vector shift amount.
  7156. static QualType checkOpenCLVectorShift(Sema &S,
  7157. ExprResult &LHS, ExprResult &RHS,
  7158. SourceLocation Loc, bool IsCompAssign) {
  7159. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  7160. if (!LHS.get()->getType()->isVectorType()) {
  7161. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  7162. << RHS.get()->getType() << LHS.get()->getType()
  7163. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7164. return QualType();
  7165. }
  7166. if (!IsCompAssign) {
  7167. LHS = S.UsualUnaryConversions(LHS.get());
  7168. if (LHS.isInvalid()) return QualType();
  7169. }
  7170. RHS = S.UsualUnaryConversions(RHS.get());
  7171. if (RHS.isInvalid()) return QualType();
  7172. QualType LHSType = LHS.get()->getType();
  7173. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  7174. QualType LHSEleType = LHSVecTy->getElementType();
  7175. // Note that RHS might not be a vector.
  7176. QualType RHSType = RHS.get()->getType();
  7177. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  7178. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  7179. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  7180. if (!LHSEleType->isIntegerType()) {
  7181. S.Diag(Loc, diag::err_typecheck_expect_int)
  7182. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7183. return QualType();
  7184. }
  7185. if (!RHSEleType->isIntegerType()) {
  7186. S.Diag(Loc, diag::err_typecheck_expect_int)
  7187. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7188. return QualType();
  7189. }
  7190. if (RHSVecTy) {
  7191. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7192. // are applied component-wise. So if RHS is a vector, then ensure
  7193. // that the number of elements is the same as LHS...
  7194. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7195. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7196. << LHS.get()->getType() << RHS.get()->getType()
  7197. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7198. return QualType();
  7199. }
  7200. } else {
  7201. // ...else expand RHS to match the number of elements in LHS.
  7202. QualType VecTy =
  7203. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7204. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7205. }
  7206. return LHSType;
  7207. }
  7208. // C99 6.5.7
  7209. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7210. SourceLocation Loc, unsigned Opc,
  7211. bool IsCompAssign) {
  7212. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7213. // Vector shifts promote their scalar inputs to vector type.
  7214. if (LHS.get()->getType()->isVectorType() ||
  7215. RHS.get()->getType()->isVectorType()) {
  7216. if (LangOpts.OpenCL)
  7217. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7218. if (LangOpts.ZVector) {
  7219. // The shift operators for the z vector extensions work basically
  7220. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7221. // allowed to be a "vector bool".
  7222. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7223. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7224. return InvalidOperands(Loc, LHS, RHS);
  7225. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7226. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7227. return InvalidOperands(Loc, LHS, RHS);
  7228. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7229. }
  7230. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7231. /*AllowBothBool*/true,
  7232. /*AllowBoolConversions*/false);
  7233. }
  7234. // Shifts don't perform usual arithmetic conversions, they just do integer
  7235. // promotions on each operand. C99 6.5.7p3
  7236. // For the LHS, do usual unary conversions, but then reset them away
  7237. // if this is a compound assignment.
  7238. ExprResult OldLHS = LHS;
  7239. LHS = UsualUnaryConversions(LHS.get());
  7240. if (LHS.isInvalid())
  7241. return QualType();
  7242. QualType LHSType = LHS.get()->getType();
  7243. if (IsCompAssign) LHS = OldLHS;
  7244. // The RHS is simpler.
  7245. RHS = UsualUnaryConversions(RHS.get());
  7246. if (RHS.isInvalid())
  7247. return QualType();
  7248. QualType RHSType = RHS.get()->getType();
  7249. // C99 6.5.7p2: Each of the operands shall have integer type.
  7250. if (!LHSType->hasIntegerRepresentation() ||
  7251. !RHSType->hasIntegerRepresentation())
  7252. return InvalidOperands(Loc, LHS, RHS);
  7253. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7254. // hasIntegerRepresentation() above instead of this.
  7255. if (isScopedEnumerationType(LHSType) ||
  7256. isScopedEnumerationType(RHSType)) {
  7257. return InvalidOperands(Loc, LHS, RHS);
  7258. }
  7259. // Sanity-check shift operands
  7260. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7261. // "The type of the result is that of the promoted left operand."
  7262. return LHSType;
  7263. }
  7264. static bool IsWithinTemplateSpecialization(Decl *D) {
  7265. if (DeclContext *DC = D->getDeclContext()) {
  7266. if (isa<ClassTemplateSpecializationDecl>(DC))
  7267. return true;
  7268. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7269. return FD->isFunctionTemplateSpecialization();
  7270. }
  7271. return false;
  7272. }
  7273. /// If two different enums are compared, raise a warning.
  7274. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7275. Expr *RHS) {
  7276. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7277. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7278. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7279. if (!LHSEnumType)
  7280. return;
  7281. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7282. if (!RHSEnumType)
  7283. return;
  7284. // Ignore anonymous enums.
  7285. if (!LHSEnumType->getDecl()->getIdentifier())
  7286. return;
  7287. if (!RHSEnumType->getDecl()->getIdentifier())
  7288. return;
  7289. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7290. return;
  7291. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7292. << LHSStrippedType << RHSStrippedType
  7293. << LHS->getSourceRange() << RHS->getSourceRange();
  7294. }
  7295. /// \brief Diagnose bad pointer comparisons.
  7296. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7297. ExprResult &LHS, ExprResult &RHS,
  7298. bool IsError) {
  7299. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7300. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7301. << LHS.get()->getType() << RHS.get()->getType()
  7302. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7303. }
  7304. /// \brief Returns false if the pointers are converted to a composite type,
  7305. /// true otherwise.
  7306. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7307. ExprResult &LHS, ExprResult &RHS) {
  7308. // C++ [expr.rel]p2:
  7309. // [...] Pointer conversions (4.10) and qualification
  7310. // conversions (4.4) are performed on pointer operands (or on
  7311. // a pointer operand and a null pointer constant) to bring
  7312. // them to their composite pointer type. [...]
  7313. //
  7314. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7315. // comparisons of pointers.
  7316. // C++ [expr.eq]p2:
  7317. // In addition, pointers to members can be compared, or a pointer to
  7318. // member and a null pointer constant. Pointer to member conversions
  7319. // (4.11) and qualification conversions (4.4) are performed to bring
  7320. // them to a common type. If one operand is a null pointer constant,
  7321. // the common type is the type of the other operand. Otherwise, the
  7322. // common type is a pointer to member type similar (4.4) to the type
  7323. // of one of the operands, with a cv-qualification signature (4.4)
  7324. // that is the union of the cv-qualification signatures of the operand
  7325. // types.
  7326. QualType LHSType = LHS.get()->getType();
  7327. QualType RHSType = RHS.get()->getType();
  7328. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7329. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7330. bool NonStandardCompositeType = false;
  7331. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7332. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7333. if (T.isNull()) {
  7334. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7335. return true;
  7336. }
  7337. if (NonStandardCompositeType)
  7338. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7339. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7340. << RHS.get()->getSourceRange();
  7341. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7342. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7343. return false;
  7344. }
  7345. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7346. ExprResult &LHS,
  7347. ExprResult &RHS,
  7348. bool IsError) {
  7349. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7350. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7351. << LHS.get()->getType() << RHS.get()->getType()
  7352. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7353. }
  7354. #if 1 // HLSL Change Starts
  7355. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7356. return LK_None;
  7357. }
  7358. #else
  7359. static bool isObjCObjectLiteral(ExprResult &E) {
  7360. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7361. case Stmt::ObjCArrayLiteralClass:
  7362. case Stmt::ObjCDictionaryLiteralClass:
  7363. case Stmt::ObjCStringLiteralClass:
  7364. case Stmt::ObjCBoxedExprClass:
  7365. return true;
  7366. default:
  7367. // Note that ObjCBoolLiteral is NOT an object literal!
  7368. return false;
  7369. }
  7370. }
  7371. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7372. const ObjCObjectPointerType *Type =
  7373. LHS->getType()->getAs<ObjCObjectPointerType>();
  7374. // If this is not actually an Objective-C object, bail out.
  7375. if (!Type)
  7376. return false;
  7377. // Get the LHS object's interface type.
  7378. QualType InterfaceType = Type->getPointeeType();
  7379. // If the RHS isn't an Objective-C object, bail out.
  7380. if (!RHS->getType()->isObjCObjectPointerType())
  7381. return false;
  7382. // Try to find the -isEqual: method.
  7383. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7384. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7385. InterfaceType,
  7386. /*instance=*/true);
  7387. if (!Method) {
  7388. if (Type->isObjCIdType()) {
  7389. // For 'id', just check the global pool.
  7390. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7391. /*receiverId=*/true);
  7392. } else {
  7393. // Check protocols.
  7394. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7395. /*instance=*/true);
  7396. }
  7397. }
  7398. if (!Method)
  7399. return false;
  7400. QualType T = Method->parameters()[0]->getType();
  7401. if (!T->isObjCObjectPointerType())
  7402. return false;
  7403. QualType R = Method->getReturnType();
  7404. if (!R->isScalarType())
  7405. return false;
  7406. return true;
  7407. }
  7408. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7409. FromE = FromE->IgnoreParenImpCasts();
  7410. switch (FromE->getStmtClass()) {
  7411. default:
  7412. break;
  7413. case Stmt::ObjCStringLiteralClass:
  7414. // "string literal"
  7415. return LK_String;
  7416. case Stmt::ObjCArrayLiteralClass:
  7417. // "array literal"
  7418. return LK_Array;
  7419. case Stmt::ObjCDictionaryLiteralClass:
  7420. // "dictionary literal"
  7421. return LK_Dictionary;
  7422. case Stmt::BlockExprClass:
  7423. return LK_Block;
  7424. case Stmt::ObjCBoxedExprClass: {
  7425. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7426. switch (Inner->getStmtClass()) {
  7427. case Stmt::IntegerLiteralClass:
  7428. case Stmt::FloatingLiteralClass:
  7429. case Stmt::CharacterLiteralClass:
  7430. case Stmt::ObjCBoolLiteralExprClass:
  7431. case Stmt::CXXBoolLiteralExprClass:
  7432. // "numeric literal"
  7433. return LK_Numeric;
  7434. case Stmt::ImplicitCastExprClass: {
  7435. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7436. // Boolean literals can be represented by implicit casts.
  7437. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7438. return LK_Numeric;
  7439. break;
  7440. }
  7441. default:
  7442. break;
  7443. }
  7444. return LK_Boxed;
  7445. }
  7446. }
  7447. return LK_None;
  7448. }
  7449. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7450. ExprResult &LHS, ExprResult &RHS,
  7451. BinaryOperator::Opcode Opc){
  7452. Expr *Literal;
  7453. Expr *Other;
  7454. if (isObjCObjectLiteral(LHS)) {
  7455. Literal = LHS.get();
  7456. Other = RHS.get();
  7457. } else {
  7458. Literal = RHS.get();
  7459. Other = LHS.get();
  7460. }
  7461. // Don't warn on comparisons against nil.
  7462. Other = Other->IgnoreParenCasts();
  7463. if (Other->isNullPointerConstant(S.getASTContext(),
  7464. Expr::NPC_ValueDependentIsNotNull))
  7465. return;
  7466. // This should be kept in sync with warn_objc_literal_comparison.
  7467. // LK_String should always be after the other literals, since it has its own
  7468. // warning flag.
  7469. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7470. assert(LiteralKind != Sema::LK_Block);
  7471. if (LiteralKind == Sema::LK_None) {
  7472. llvm_unreachable("Unknown Objective-C object literal kind");
  7473. }
  7474. if (LiteralKind == Sema::LK_String)
  7475. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7476. << Literal->getSourceRange();
  7477. else
  7478. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7479. << LiteralKind << Literal->getSourceRange();
  7480. if (BinaryOperator::isEqualityOp(Opc) &&
  7481. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7482. SourceLocation Start = LHS.get()->getLocStart();
  7483. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7484. CharSourceRange OpRange =
  7485. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7486. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7487. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7488. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7489. << FixItHint::CreateInsertion(End, "]");
  7490. }
  7491. }
  7492. #endif // HLSL Change Ends
  7493. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7494. ExprResult &RHS,
  7495. SourceLocation Loc,
  7496. unsigned OpaqueOpc) {
  7497. // This checking requires bools.
  7498. if (!S.getLangOpts().Bool) return;
  7499. // Check that left hand side is !something.
  7500. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7501. if (!UO || UO->getOpcode() != UO_LNot) return;
  7502. // Only check if the right hand side is non-bool arithmetic type.
  7503. if (RHS.get()->getType()->isBooleanType()) return;
  7504. // Make sure that the something in !something is not bool.
  7505. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7506. if (SubExpr->getType()->isBooleanType()) return;
  7507. // Emit warning.
  7508. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7509. << Loc;
  7510. // First note suggest !(x < y)
  7511. SourceLocation FirstOpen = SubExpr->getLocStart();
  7512. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7513. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7514. if (FirstClose.isInvalid())
  7515. FirstOpen = SourceLocation();
  7516. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7517. << FixItHint::CreateInsertion(FirstOpen, "(")
  7518. << FixItHint::CreateInsertion(FirstClose, ")");
  7519. // Second note suggests (!x) < y
  7520. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7521. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7522. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7523. if (SecondClose.isInvalid())
  7524. SecondOpen = SourceLocation();
  7525. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7526. << FixItHint::CreateInsertion(SecondOpen, "(")
  7527. << FixItHint::CreateInsertion(SecondClose, ")");
  7528. }
  7529. // Get the decl for a simple expression: a reference to a variable,
  7530. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7531. static ValueDecl *getCompareDecl(Expr *E) {
  7532. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7533. return DR->getDecl();
  7534. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7535. if (Ivar->isFreeIvar())
  7536. return Ivar->getDecl();
  7537. }
  7538. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7539. if (Mem->isImplicitAccess())
  7540. return Mem->getMemberDecl();
  7541. }
  7542. return nullptr;
  7543. }
  7544. // C99 6.5.8, C++ [expr.rel]
  7545. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7546. SourceLocation Loc, unsigned OpaqueOpc,
  7547. bool IsRelational) {
  7548. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7549. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7550. // Handle vector comparisons separately.
  7551. if (LHS.get()->getType()->isVectorType() ||
  7552. RHS.get()->getType()->isVectorType())
  7553. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7554. QualType LHSType = LHS.get()->getType();
  7555. QualType RHSType = RHS.get()->getType();
  7556. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7557. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7558. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7559. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7560. if (!LHSType->hasFloatingRepresentation() &&
  7561. !(LHSType->isBlockPointerType() && IsRelational) &&
  7562. !LHS.get()->getLocStart().isMacroID() &&
  7563. !RHS.get()->getLocStart().isMacroID() &&
  7564. ActiveTemplateInstantiations.empty()) {
  7565. // For non-floating point types, check for self-comparisons of the form
  7566. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7567. // often indicate logic errors in the program.
  7568. //
  7569. // NOTE: Don't warn about comparison expressions resulting from macro
  7570. // expansion. Also don't warn about comparisons which are only self
  7571. // comparisons within a template specialization. The warnings should catch
  7572. // obvious cases in the definition of the template anyways. The idea is to
  7573. // warn when the typed comparison operator will always evaluate to the same
  7574. // result.
  7575. ValueDecl *DL = getCompareDecl(LHSStripped);
  7576. ValueDecl *DR = getCompareDecl(RHSStripped);
  7577. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7578. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7579. << 0 // self-
  7580. << (Opc == BO_EQ
  7581. || Opc == BO_LE
  7582. || Opc == BO_GE));
  7583. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7584. !DL->getType()->isReferenceType() &&
  7585. !DR->getType()->isReferenceType()) {
  7586. // what is it always going to eval to?
  7587. char always_evals_to;
  7588. switch(Opc) {
  7589. case BO_EQ: // e.g. array1 == array2
  7590. always_evals_to = 0; // false
  7591. break;
  7592. case BO_NE: // e.g. array1 != array2
  7593. always_evals_to = 1; // true
  7594. break;
  7595. default:
  7596. // best we can say is 'a constant'
  7597. always_evals_to = 2; // e.g. array1 <= array2
  7598. break;
  7599. }
  7600. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7601. << 1 // array
  7602. << always_evals_to);
  7603. }
  7604. if (isa<CastExpr>(LHSStripped))
  7605. LHSStripped = LHSStripped->IgnoreParenCasts();
  7606. if (isa<CastExpr>(RHSStripped))
  7607. RHSStripped = RHSStripped->IgnoreParenCasts();
  7608. // Warn about comparisons against a string constant (unless the other
  7609. // operand is null), the user probably wants strcmp.
  7610. Expr *literalString = nullptr;
  7611. Expr *literalStringStripped = nullptr;
  7612. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7613. !RHSStripped->isNullPointerConstant(Context,
  7614. Expr::NPC_ValueDependentIsNull)) {
  7615. literalString = LHS.get();
  7616. literalStringStripped = LHSStripped;
  7617. } else if ((isa<StringLiteral>(RHSStripped) ||
  7618. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7619. !LHSStripped->isNullPointerConstant(Context,
  7620. Expr::NPC_ValueDependentIsNull)) {
  7621. literalString = RHS.get();
  7622. literalStringStripped = RHSStripped;
  7623. }
  7624. if (literalString) {
  7625. DiagRuntimeBehavior(Loc, nullptr,
  7626. PDiag(diag::warn_stringcompare)
  7627. << isa<ObjCEncodeExpr>(literalStringStripped)
  7628. << literalString->getSourceRange());
  7629. }
  7630. }
  7631. // C99 6.5.8p3 / C99 6.5.9p4
  7632. UsualArithmeticConversions(LHS, RHS);
  7633. if (LHS.isInvalid() || RHS.isInvalid())
  7634. return QualType();
  7635. LHSType = LHS.get()->getType();
  7636. RHSType = RHS.get()->getType();
  7637. // The result of comparisons is 'bool' in C++, 'int' in C.
  7638. QualType ResultTy = Context.getLogicalOperationType();
  7639. if (IsRelational) {
  7640. if (LHSType->isRealType() && RHSType->isRealType())
  7641. return ResultTy;
  7642. } else {
  7643. // Check for comparisons of floating point operands using != and ==.
  7644. if (LHSType->hasFloatingRepresentation())
  7645. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7646. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7647. return ResultTy;
  7648. }
  7649. const Expr::NullPointerConstantKind LHSNullKind =
  7650. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7651. const Expr::NullPointerConstantKind RHSNullKind =
  7652. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7653. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7654. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7655. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7656. bool IsEquality = Opc == BO_EQ;
  7657. if (RHSIsNull)
  7658. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7659. RHS.get()->getSourceRange());
  7660. else
  7661. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7662. LHS.get()->getSourceRange());
  7663. }
  7664. // All of the following pointer-related warnings are GCC extensions, except
  7665. // when handling null pointer constants.
  7666. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7667. QualType LCanPointeeTy =
  7668. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7669. QualType RCanPointeeTy =
  7670. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7671. if (getLangOpts().CPlusPlus) {
  7672. if (LCanPointeeTy == RCanPointeeTy)
  7673. return ResultTy;
  7674. if (!IsRelational &&
  7675. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7676. // Valid unless comparison between non-null pointer and function pointer
  7677. // This is a gcc extension compatibility comparison.
  7678. // In a SFINAE context, we treat this as a hard error to maintain
  7679. // conformance with the C++ standard.
  7680. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7681. && !LHSIsNull && !RHSIsNull) {
  7682. diagnoseFunctionPointerToVoidComparison(
  7683. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7684. if (isSFINAEContext())
  7685. return QualType();
  7686. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7687. return ResultTy;
  7688. }
  7689. }
  7690. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7691. return QualType();
  7692. else
  7693. return ResultTy;
  7694. }
  7695. // C99 6.5.9p2 and C99 6.5.8p2
  7696. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7697. RCanPointeeTy.getUnqualifiedType())) {
  7698. // Valid unless a relational comparison of function pointers
  7699. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7700. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7701. << LHSType << RHSType << LHS.get()->getSourceRange()
  7702. << RHS.get()->getSourceRange();
  7703. }
  7704. } else if (!IsRelational &&
  7705. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7706. // Valid unless comparison between non-null pointer and function pointer
  7707. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7708. && !LHSIsNull && !RHSIsNull)
  7709. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7710. /*isError*/false);
  7711. } else {
  7712. // Invalid
  7713. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7714. }
  7715. if (LCanPointeeTy != RCanPointeeTy) {
  7716. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7717. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7718. Diag(Loc,
  7719. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7720. << LHSType << RHSType << 0 /* comparison */
  7721. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7722. }
  7723. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7724. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7725. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7726. : CK_BitCast;
  7727. if (LHSIsNull && !RHSIsNull)
  7728. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7729. else
  7730. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7731. }
  7732. return ResultTy;
  7733. }
  7734. if (getLangOpts().CPlusPlus) {
  7735. // Comparison of nullptr_t with itself.
  7736. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7737. return ResultTy;
  7738. // Comparison of pointers with null pointer constants and equality
  7739. // comparisons of member pointers to null pointer constants.
  7740. if (RHSIsNull &&
  7741. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7742. (!IsRelational &&
  7743. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7744. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7745. LHSType->isMemberPointerType()
  7746. ? CK_NullToMemberPointer
  7747. : CK_NullToPointer);
  7748. return ResultTy;
  7749. }
  7750. if (LHSIsNull &&
  7751. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7752. (!IsRelational &&
  7753. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7754. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7755. RHSType->isMemberPointerType()
  7756. ? CK_NullToMemberPointer
  7757. : CK_NullToPointer);
  7758. return ResultTy;
  7759. }
  7760. // Comparison of member pointers.
  7761. if (!IsRelational &&
  7762. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7763. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7764. return QualType();
  7765. else
  7766. return ResultTy;
  7767. }
  7768. // Handle scoped enumeration types specifically, since they don't promote
  7769. // to integers.
  7770. if (LHS.get()->getType()->isEnumeralType() &&
  7771. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7772. RHS.get()->getType()))
  7773. return ResultTy;
  7774. }
  7775. // Handle block pointer types.
  7776. if (!IsRelational && LHSType->isBlockPointerType() &&
  7777. RHSType->isBlockPointerType()) {
  7778. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7779. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7780. if (!LHSIsNull && !RHSIsNull &&
  7781. !Context.typesAreCompatible(lpointee, rpointee)) {
  7782. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7783. << LHSType << RHSType << LHS.get()->getSourceRange()
  7784. << RHS.get()->getSourceRange();
  7785. }
  7786. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7787. return ResultTy;
  7788. }
  7789. // Allow block pointers to be compared with null pointer constants.
  7790. if (!IsRelational
  7791. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7792. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7793. if (!LHSIsNull && !RHSIsNull) {
  7794. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7795. ->getPointeeType()->isVoidType())
  7796. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7797. ->getPointeeType()->isVoidType())))
  7798. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7799. << LHSType << RHSType << LHS.get()->getSourceRange()
  7800. << RHS.get()->getSourceRange();
  7801. }
  7802. if (LHSIsNull && !RHSIsNull)
  7803. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7804. RHSType->isPointerType() ? CK_BitCast
  7805. : CK_AnyPointerToBlockPointerCast);
  7806. else
  7807. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7808. LHSType->isPointerType() ? CK_BitCast
  7809. : CK_AnyPointerToBlockPointerCast);
  7810. return ResultTy;
  7811. }
  7812. if (LHSType->isObjCObjectPointerType() ||
  7813. RHSType->isObjCObjectPointerType()) {
  7814. const PointerType *LPT = LHSType->getAs<PointerType>();
  7815. const PointerType *RPT = RHSType->getAs<PointerType>();
  7816. if (LPT || RPT) {
  7817. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7818. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7819. if (!LPtrToVoid && !RPtrToVoid &&
  7820. !Context.typesAreCompatible(LHSType, RHSType)) {
  7821. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7822. /*isError*/false);
  7823. }
  7824. if (LHSIsNull && !RHSIsNull) {
  7825. Expr *E = LHS.get();
  7826. #if 0 // HLSL Change - no ObjC support
  7827. if (getLangOpts().ObjCAutoRefCount)
  7828. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7829. #endif // HLSL Change
  7830. LHS = ImpCastExprToType(E, RHSType,
  7831. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7832. }
  7833. else {
  7834. Expr *E = RHS.get();
  7835. #if 0 // HLSL Change - no ObjC support
  7836. if (getLangOpts().ObjCAutoRefCount)
  7837. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7838. Opc);
  7839. #endif // HLSL Change
  7840. RHS = ImpCastExprToType(E, LHSType,
  7841. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7842. }
  7843. return ResultTy;
  7844. }
  7845. #if 0 // HLSL Change - no ObjC support
  7846. if (LHSType->isObjCObjectPointerType() &&
  7847. RHSType->isObjCObjectPointerType()) {
  7848. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7849. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7850. /*isError*/false);
  7851. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7852. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7853. if (LHSIsNull && !RHSIsNull)
  7854. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7855. else
  7856. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7857. return ResultTy;
  7858. }
  7859. #endif // HLSL Change
  7860. }
  7861. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7862. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7863. unsigned DiagID = 0;
  7864. bool isError = false;
  7865. if (LangOpts.DebuggerSupport) {
  7866. // Under a debugger, allow the comparison of pointers to integers,
  7867. // since users tend to want to compare addresses.
  7868. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7869. (RHSIsNull && RHSType->isIntegerType())) {
  7870. if (IsRelational && !getLangOpts().CPlusPlus)
  7871. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7872. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7873. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7874. else if (getLangOpts().CPlusPlus) {
  7875. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7876. isError = true;
  7877. } else
  7878. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7879. if (DiagID) {
  7880. Diag(Loc, DiagID)
  7881. << LHSType << RHSType << LHS.get()->getSourceRange()
  7882. << RHS.get()->getSourceRange();
  7883. if (isError)
  7884. return QualType();
  7885. }
  7886. if (LHSType->isIntegerType())
  7887. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7888. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7889. else
  7890. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7891. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7892. return ResultTy;
  7893. }
  7894. // Handle block pointers.
  7895. if (!IsRelational && RHSIsNull
  7896. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7897. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7898. return ResultTy;
  7899. }
  7900. if (!IsRelational && LHSIsNull
  7901. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7902. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7903. return ResultTy;
  7904. }
  7905. return InvalidOperands(Loc, LHS, RHS);
  7906. }
  7907. // Return a signed type that is of identical size and number of elements.
  7908. // For floating point vectors, return an integer type of identical size
  7909. // and number of elements.
  7910. QualType Sema::GetSignedVectorType(QualType V) {
  7911. const VectorType *VTy = V->getAs<VectorType>();
  7912. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7913. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7914. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7915. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7916. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7917. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7918. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7919. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7920. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7921. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7922. "Unhandled vector element size in vector compare");
  7923. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7924. }
  7925. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7926. /// operates on extended vector types. Instead of producing an IntTy result,
  7927. /// like a scalar comparison, a vector comparison produces a vector of integer
  7928. /// types.
  7929. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7930. SourceLocation Loc,
  7931. bool IsRelational) {
  7932. // Check to make sure we're operating on vectors of the same type and width,
  7933. // Allowing one side to be a scalar of element type.
  7934. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7935. /*AllowBothBool*/true,
  7936. /*AllowBoolConversions*/getLangOpts().ZVector);
  7937. if (vType.isNull())
  7938. return vType;
  7939. QualType LHSType = LHS.get()->getType();
  7940. // If AltiVec, the comparison results in a numeric type, i.e.
  7941. // bool for C++, int for C
  7942. if (getLangOpts().AltiVec &&
  7943. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7944. return Context.getLogicalOperationType();
  7945. // For non-floating point types, check for self-comparisons of the form
  7946. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7947. // often indicate logic errors in the program.
  7948. if (!LHSType->hasFloatingRepresentation() &&
  7949. ActiveTemplateInstantiations.empty()) {
  7950. if (DeclRefExpr* DRL
  7951. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7952. if (DeclRefExpr* DRR
  7953. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7954. if (DRL->getDecl() == DRR->getDecl())
  7955. DiagRuntimeBehavior(Loc, nullptr,
  7956. PDiag(diag::warn_comparison_always)
  7957. << 0 // self-
  7958. << 2 // "a constant"
  7959. );
  7960. }
  7961. // Check for comparisons of floating point operands using != and ==.
  7962. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7963. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7964. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7965. }
  7966. // Return a signed type for the vector.
  7967. return GetSignedVectorType(LHSType);
  7968. }
  7969. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7970. SourceLocation Loc) {
  7971. // Ensure that either both operands are of the same vector type, or
  7972. // one operand is of a vector type and the other is of its element type.
  7973. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7974. /*AllowBothBool*/true,
  7975. /*AllowBoolConversions*/false);
  7976. if (vType.isNull())
  7977. return InvalidOperands(Loc, LHS, RHS);
  7978. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7979. vType->hasFloatingRepresentation())
  7980. return InvalidOperands(Loc, LHS, RHS);
  7981. return GetSignedVectorType(LHS.get()->getType());
  7982. }
  7983. inline QualType Sema::CheckBitwiseOperands(
  7984. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7985. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7986. if (LHS.get()->getType()->isVectorType() ||
  7987. RHS.get()->getType()->isVectorType()) {
  7988. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7989. RHS.get()->getType()->hasIntegerRepresentation())
  7990. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7991. /*AllowBothBool*/true,
  7992. /*AllowBoolConversions*/getLangOpts().ZVector);
  7993. return InvalidOperands(Loc, LHS, RHS);
  7994. }
  7995. ExprResult LHSResult = LHS, RHSResult = RHS;
  7996. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7997. IsCompAssign);
  7998. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7999. return QualType();
  8000. LHS = LHSResult.get();
  8001. RHS = RHSResult.get();
  8002. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  8003. return compType;
  8004. return InvalidOperands(Loc, LHS, RHS);
  8005. }
  8006. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  8007. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  8008. // Check vector operands differently.
  8009. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  8010. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  8011. // Diagnose cases where the user write a logical and/or but probably meant a
  8012. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  8013. // is a constant.
  8014. if (LHS.get()->getType()->isIntegerType() &&
  8015. !LHS.get()->getType()->isBooleanType() &&
  8016. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  8017. // Don't warn in macros or template instantiations.
  8018. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  8019. // If the RHS can be constant folded, and if it constant folds to something
  8020. // that isn't 0 or 1 (which indicate a potential logical operation that
  8021. // happened to fold to true/false) then warn.
  8022. // Parens on the RHS are ignored.
  8023. llvm::APSInt Result;
  8024. if (RHS.get()->EvaluateAsInt(Result, Context))
  8025. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  8026. !RHS.get()->getExprLoc().isMacroID()) ||
  8027. (Result != 0 && Result != 1)) {
  8028. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  8029. << RHS.get()->getSourceRange()
  8030. << (Opc == BO_LAnd ? "&&" : "||");
  8031. // Suggest replacing the logical operator with the bitwise version
  8032. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  8033. << (Opc == BO_LAnd ? "&" : "|")
  8034. << FixItHint::CreateReplacement(SourceRange(
  8035. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  8036. getLangOpts())),
  8037. Opc == BO_LAnd ? "&" : "|");
  8038. if (Opc == BO_LAnd)
  8039. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  8040. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  8041. << FixItHint::CreateRemoval(
  8042. SourceRange(
  8043. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  8044. 0, getSourceManager(),
  8045. getLangOpts()),
  8046. RHS.get()->getLocEnd()));
  8047. }
  8048. }
  8049. if (!Context.getLangOpts().CPlusPlus) {
  8050. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  8051. // not operate on the built-in scalar and vector float types.
  8052. if (Context.getLangOpts().OpenCL &&
  8053. Context.getLangOpts().OpenCLVersion < 120) {
  8054. if (LHS.get()->getType()->isFloatingType() ||
  8055. RHS.get()->getType()->isFloatingType())
  8056. return InvalidOperands(Loc, LHS, RHS);
  8057. }
  8058. LHS = UsualUnaryConversions(LHS.get());
  8059. if (LHS.isInvalid())
  8060. return QualType();
  8061. RHS = UsualUnaryConversions(RHS.get());
  8062. if (RHS.isInvalid())
  8063. return QualType();
  8064. if (!LHS.get()->getType()->isScalarType() ||
  8065. !RHS.get()->getType()->isScalarType())
  8066. return InvalidOperands(Loc, LHS, RHS);
  8067. return Context.IntTy;
  8068. }
  8069. // The following is safe because we only use this method for
  8070. // non-overloadable operands.
  8071. // C++ [expr.log.and]p1
  8072. // C++ [expr.log.or]p1
  8073. // The operands are both contextually converted to type bool.
  8074. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  8075. if (LHSRes.isInvalid())
  8076. return InvalidOperands(Loc, LHS, RHS);
  8077. LHS = LHSRes;
  8078. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  8079. if (RHSRes.isInvalid())
  8080. return InvalidOperands(Loc, LHS, RHS);
  8081. RHS = RHSRes;
  8082. // C++ [expr.log.and]p2
  8083. // C++ [expr.log.or]p2
  8084. // The result is a bool.
  8085. return Context.BoolTy;
  8086. }
  8087. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  8088. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  8089. if (!ME) return false;
  8090. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  8091. ObjCMessageExpr *Base =
  8092. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  8093. if (!Base) return false;
  8094. return Base->getMethodDecl() != nullptr;
  8095. }
  8096. /// Is the given expression (which must be 'const') a reference to a
  8097. /// variable which was originally non-const, but which has become
  8098. /// 'const' due to being captured within a block?
  8099. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  8100. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  8101. assert(E->isLValue() && E->getType().isConstQualified());
  8102. E = E->IgnoreParens();
  8103. // Must be a reference to a declaration from an enclosing scope.
  8104. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  8105. if (!DRE) return NCCK_None;
  8106. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  8107. // The declaration must be a variable which is not declared 'const'.
  8108. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  8109. if (!var) return NCCK_None;
  8110. if (var->getType().isConstQualified()) return NCCK_None;
  8111. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  8112. // Decide whether the first capture was for a block or a lambda.
  8113. DeclContext *DC = S.CurContext, *Prev = nullptr;
  8114. while (DC != var->getDeclContext()) {
  8115. Prev = DC;
  8116. DC = DC->getParent();
  8117. }
  8118. // Unless we have an init-capture, we've gone one step too far.
  8119. if (!var->isInitCapture())
  8120. DC = Prev;
  8121. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  8122. }
  8123. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  8124. Ty = Ty.getNonReferenceType();
  8125. if (IsDereference && Ty->isPointerType())
  8126. Ty = Ty->getPointeeType();
  8127. return !Ty.isConstQualified();
  8128. }
  8129. /// Emit the "read-only variable not assignable" error and print notes to give
  8130. /// more information about why the variable is not assignable, such as pointing
  8131. /// to the declaration of a const variable, showing that a method is const, or
  8132. /// that the function is returning a const reference.
  8133. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  8134. SourceLocation Loc) {
  8135. // Update err_typecheck_assign_const and note_typecheck_assign_const
  8136. // when this enum is changed.
  8137. enum {
  8138. ConstFunction,
  8139. ConstVariable,
  8140. ConstMember,
  8141. ConstMethod,
  8142. ConstUnknown, // Keep as last element
  8143. };
  8144. SourceRange ExprRange = E->getSourceRange();
  8145. // Only emit one error on the first const found. All other consts will emit
  8146. // a note to the error.
  8147. bool DiagnosticEmitted = false;
  8148. // Track if the current expression is the result of a derefence, and if the
  8149. // next checked expression is the result of a derefence.
  8150. bool IsDereference = false;
  8151. bool NextIsDereference = false;
  8152. // Loop to process MemberExpr chains.
  8153. while (true) {
  8154. IsDereference = NextIsDereference;
  8155. NextIsDereference = false;
  8156. E = E->IgnoreParenImpCasts();
  8157. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  8158. NextIsDereference = ME->isArrow();
  8159. const ValueDecl *VD = ME->getMemberDecl();
  8160. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  8161. // Mutable fields can be modified even if the class is const.
  8162. if (Field->isMutable()) {
  8163. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  8164. break;
  8165. }
  8166. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  8167. if (!DiagnosticEmitted) {
  8168. S.Diag(Loc, diag::err_typecheck_assign_const)
  8169. << ExprRange << ConstMember << false /*static*/ << Field
  8170. << Field->getType();
  8171. DiagnosticEmitted = true;
  8172. }
  8173. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8174. << ConstMember << false /*static*/ << Field << Field->getType()
  8175. << Field->getSourceRange();
  8176. }
  8177. E = ME->getBase();
  8178. continue;
  8179. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  8180. if (VDecl->getType().isConstQualified()) {
  8181. if (!DiagnosticEmitted) {
  8182. S.Diag(Loc, diag::err_typecheck_assign_const)
  8183. << ExprRange << ConstMember << true /*static*/ << VDecl
  8184. << VDecl->getType();
  8185. DiagnosticEmitted = true;
  8186. }
  8187. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8188. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  8189. << VDecl->getSourceRange();
  8190. }
  8191. // Static fields do not inherit constness from parents.
  8192. break;
  8193. }
  8194. break;
  8195. } // End MemberExpr
  8196. break;
  8197. }
  8198. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8199. // Function calls
  8200. const FunctionDecl *FD = CE->getDirectCallee();
  8201. if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8202. if (!DiagnosticEmitted) {
  8203. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8204. << ConstFunction << FD;
  8205. DiagnosticEmitted = true;
  8206. }
  8207. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8208. diag::note_typecheck_assign_const)
  8209. << ConstFunction << FD << FD->getReturnType()
  8210. << FD->getReturnTypeSourceRange();
  8211. }
  8212. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8213. // Point to variable declaration.
  8214. if (const ValueDecl *VD = DRE->getDecl()) {
  8215. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8216. if (!DiagnosticEmitted) {
  8217. S.Diag(Loc, diag::err_typecheck_assign_const)
  8218. << ExprRange << ConstVariable << VD << VD->getType();
  8219. DiagnosticEmitted = true;
  8220. }
  8221. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8222. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8223. }
  8224. }
  8225. } else if (isa<CXXThisExpr>(E)) {
  8226. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8227. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8228. if (MD->isConst()) {
  8229. if (!DiagnosticEmitted) {
  8230. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8231. << ConstMethod << MD;
  8232. DiagnosticEmitted = true;
  8233. }
  8234. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8235. << ConstMethod << MD << MD->getSourceRange();
  8236. }
  8237. }
  8238. }
  8239. }
  8240. if (DiagnosticEmitted)
  8241. return;
  8242. // Can't determine a more specific message, so display the generic error.
  8243. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8244. }
  8245. static bool HLSLCheckForModifiableLValue(
  8246. Expr *E,
  8247. SourceLocation Loc,
  8248. Sema &S
  8249. ) {
  8250. assert(isa<CXXOperatorCallExpr>(E));
  8251. const CXXOperatorCallExpr *expr = cast<CXXOperatorCallExpr>(E);
  8252. const Expr *LHS = expr->getArg(0);
  8253. QualType qt = LHS->getType();
  8254. // Check modifying const matrix with double subscript operator calls
  8255. if (isa<CXXOperatorCallExpr>(expr->getArg(0)))
  8256. return HLSLCheckForModifiableLValue(const_cast<Expr *>(expr->getArg(0)), Loc, S);
  8257. if (qt.isConstQualified() && (hlsl::IsMatrixType(&S, qt) || hlsl::IsVectorType(&S, qt))) {
  8258. DiagnoseConstAssignment(S, LHS, Loc);
  8259. return true;
  8260. }
  8261. if (!LHS->isLValue()) {
  8262. S.Diag(Loc, diag::err_typecheck_expression_not_modifiable_lvalue);
  8263. return true;
  8264. }
  8265. return false;
  8266. }
  8267. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8268. /// emit an error and return true. If so, return false.
  8269. bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { // HLSL Change: export this function
  8270. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8271. // HLSL Change Starts - check const for array subscript operator for HLSL vector/matrix
  8272. if (S.Context.getLangOpts().HLSL && E->getStmtClass() == Stmt::CXXOperatorCallExprClass) {
  8273. // check if it's a vector or matrix
  8274. return HLSLCheckForModifiableLValue(E, Loc, S);
  8275. }
  8276. // HLSL Change Ends
  8277. SourceLocation OrigLoc = Loc;
  8278. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8279. &Loc);
  8280. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8281. IsLV = Expr::MLV_InvalidMessageExpression;
  8282. if (IsLV == Expr::MLV_Valid)
  8283. return false;
  8284. unsigned DiagID = 0;
  8285. bool NeedType = false;
  8286. switch (IsLV) { // C99 6.5.16p2
  8287. case Expr::MLV_ConstQualified:
  8288. // Use a specialized diagnostic when we're assigning to an object
  8289. // from an enclosing function or block.
  8290. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8291. if (NCCK == NCCK_Block)
  8292. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8293. else
  8294. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8295. break;
  8296. }
  8297. // In ARC, use some specialized diagnostics for occasions where we
  8298. // infer 'const'. These are always pseudo-strong variables.
  8299. if (S.getLangOpts().ObjCAutoRefCount) {
  8300. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8301. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8302. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8303. // Use the normal diagnostic if it's pseudo-__strong but the
  8304. // user actually wrote 'const'.
  8305. if (var->isARCPseudoStrong() &&
  8306. (!var->getTypeSourceInfo() ||
  8307. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8308. // There are two pseudo-strong cases:
  8309. // - self
  8310. ObjCMethodDecl *method = S.getCurMethodDecl();
  8311. if (method && var == method->getSelfDecl())
  8312. DiagID = method->isClassMethod()
  8313. ? diag::err_typecheck_arc_assign_self_class_method
  8314. : diag::err_typecheck_arc_assign_self;
  8315. // - fast enumeration variables
  8316. else
  8317. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8318. SourceRange Assign;
  8319. if (Loc != OrigLoc)
  8320. Assign = SourceRange(OrigLoc, OrigLoc);
  8321. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8322. // We need to preserve the AST regardless, so migration tool
  8323. // can do its job.
  8324. return false;
  8325. }
  8326. }
  8327. }
  8328. // If none of the special cases above are triggered, then this is a
  8329. // simple const assignment.
  8330. if (DiagID == 0) {
  8331. DiagnoseConstAssignment(S, E, Loc);
  8332. return true;
  8333. }
  8334. break;
  8335. case Expr::MLV_ConstAddrSpace:
  8336. DiagnoseConstAssignment(S, E, Loc);
  8337. return true;
  8338. case Expr::MLV_ArrayType:
  8339. case Expr::MLV_ArrayTemporary:
  8340. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8341. NeedType = true;
  8342. break;
  8343. case Expr::MLV_NotObjectType:
  8344. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8345. NeedType = true;
  8346. break;
  8347. case Expr::MLV_LValueCast:
  8348. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8349. break;
  8350. case Expr::MLV_Valid:
  8351. llvm_unreachable("did not take early return for MLV_Valid");
  8352. case Expr::MLV_InvalidExpression:
  8353. case Expr::MLV_MemberFunction:
  8354. case Expr::MLV_ClassTemporary:
  8355. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8356. break;
  8357. case Expr::MLV_IncompleteType:
  8358. case Expr::MLV_IncompleteVoidType:
  8359. return S.RequireCompleteType(Loc, E->getType(),
  8360. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8361. case Expr::MLV_DuplicateVectorComponents:
  8362. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8363. break;
  8364. // HLSL Change Starts
  8365. case Expr::MLV_DuplicateMatrixComponents:
  8366. DiagID = diag::err_hlsl_typecheck_duplicate_matrix_components_not_mlvalue;
  8367. break;
  8368. // HLSL Change Ends
  8369. case Expr::MLV_NoSetterProperty:
  8370. llvm_unreachable("readonly properties should be processed differently");
  8371. case Expr::MLV_InvalidMessageExpression:
  8372. DiagID = diag::error_readonly_message_assignment;
  8373. break;
  8374. case Expr::MLV_SubObjCPropertySetting:
  8375. DiagID = diag::error_no_subobject_property_setting;
  8376. break;
  8377. }
  8378. SourceRange Assign;
  8379. if (Loc != OrigLoc)
  8380. Assign = SourceRange(OrigLoc, OrigLoc);
  8381. if (NeedType)
  8382. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8383. else
  8384. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8385. return true;
  8386. }
  8387. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8388. SourceLocation Loc,
  8389. Sema &Sema) {
  8390. // C / C++ fields
  8391. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8392. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8393. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8394. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8395. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8396. }
  8397. // Objective-C instance variables
  8398. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8399. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8400. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8401. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8402. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8403. if (RL && RR && RL->getDecl() == RR->getDecl())
  8404. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8405. }
  8406. }
  8407. // C99 6.5.16.1
  8408. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8409. SourceLocation Loc,
  8410. QualType CompoundType) {
  8411. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8412. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8413. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8414. return QualType();
  8415. QualType LHSType = LHSExpr->getType();
  8416. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8417. CompoundType;
  8418. AssignConvertType ConvTy;
  8419. if (CompoundType.isNull()) {
  8420. Expr *RHSCheck = RHS.get();
  8421. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8422. QualType LHSTy(LHSType);
  8423. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8424. if (RHS.isInvalid())
  8425. return QualType();
  8426. // Special case of NSObject attributes on c-style pointer types.
  8427. if (ConvTy == IncompatiblePointer &&
  8428. ((Context.isObjCNSObjectType(LHSType) &&
  8429. RHSType->isObjCObjectPointerType()) ||
  8430. (Context.isObjCNSObjectType(RHSType) &&
  8431. LHSType->isObjCObjectPointerType())))
  8432. ConvTy = Compatible;
  8433. if (ConvTy == Compatible &&
  8434. LHSType->isObjCObjectType())
  8435. Diag(Loc, diag::err_objc_object_assignment)
  8436. << LHSType;
  8437. // If the RHS is a unary plus or minus, check to see if they = and + are
  8438. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8439. // instead of "x += 4".
  8440. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8441. RHSCheck = ICE->getSubExpr();
  8442. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8443. if ((UO->getOpcode() == UO_Plus ||
  8444. UO->getOpcode() == UO_Minus) &&
  8445. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8446. // Only if the two operators are exactly adjacent.
  8447. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8448. // And there is a space or other character before the subexpr of the
  8449. // unary +/-. We don't want to warn on "x=-1".
  8450. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8451. UO->getSubExpr()->getLocStart().isFileID()) {
  8452. Diag(Loc, diag::warn_not_compound_assign)
  8453. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8454. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8455. }
  8456. }
  8457. #if 0 // HLSL Change Starts
  8458. if (ConvTy == Compatible) {
  8459. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8460. // Warn about retain cycles where a block captures the LHS, but
  8461. // not if the LHS is a simple variable into which the block is
  8462. // being stored...unless that variable can be captured by reference!
  8463. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8464. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8465. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8466. checkRetainCycles(LHSExpr, RHS.get());
  8467. // It is safe to assign a weak reference into a strong variable.
  8468. // Although this code can still have problems:
  8469. // id x = self.weakProp;
  8470. // id y = self.weakProp;
  8471. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8472. // paths through the function. This should be revisited if
  8473. // -Wrepeated-use-of-weak is made flow-sensitive.
  8474. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8475. RHS.get()->getLocStart()))
  8476. getCurFunction()->markSafeWeakUse(RHS.get());
  8477. } else if (getLangOpts().ObjCAutoRefCount) {
  8478. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8479. }
  8480. }
  8481. #endif // HLSL Change Ends
  8482. } else {
  8483. // Compound assignment "x += y"
  8484. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8485. }
  8486. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8487. RHS.get(), AA_Assigning))
  8488. return QualType();
  8489. CheckForNullPointerDereference(*this, LHSExpr);
  8490. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8491. // left operand unless the left operand has qualified type, in which case
  8492. // it is the unqualified version of the type of the left operand.
  8493. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8494. // is converted to the type of the assignment expression (above).
  8495. // C++ 5.17p1: the type of the assignment expression is that of its left
  8496. // operand.
  8497. return (getLangOpts().CPlusPlus
  8498. ? LHSType : LHSType.getUnqualifiedType());
  8499. }
  8500. // C99 6.5.17
  8501. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8502. SourceLocation Loc) {
  8503. LHS = S.CheckPlaceholderExpr(LHS.get());
  8504. RHS = S.CheckPlaceholderExpr(RHS.get());
  8505. if (LHS.isInvalid() || RHS.isInvalid())
  8506. return QualType();
  8507. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8508. // operands, but not unary promotions.
  8509. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8510. // So we treat the LHS as a ignored value, and in C++ we allow the
  8511. // containing site to determine what should be done with the RHS.
  8512. LHS = S.IgnoredValueConversions(LHS.get());
  8513. if (LHS.isInvalid())
  8514. return QualType();
  8515. S.DiagnoseUnusedExprResult(LHS.get());
  8516. if (!S.getLangOpts().CPlusPlus) {
  8517. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8518. if (RHS.isInvalid())
  8519. return QualType();
  8520. if (!RHS.get()->getType()->isVoidType())
  8521. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8522. diag::err_incomplete_type);
  8523. }
  8524. return RHS.get()->getType();
  8525. }
  8526. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8527. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8528. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8529. ExprValueKind &VK,
  8530. ExprObjectKind &OK,
  8531. SourceLocation OpLoc,
  8532. bool IsInc, bool IsPrefix) {
  8533. if (Op->isTypeDependent())
  8534. return S.Context.DependentTy;
  8535. QualType ResType = Op->getType();
  8536. // Atomic types can be used for increment / decrement where the non-atomic
  8537. // versions can, so ignore the _Atomic() specifier for the purpose of
  8538. // checking.
  8539. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8540. ResType = ResAtomicType->getValueType();
  8541. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8542. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8543. // Decrement of bool is not allowed.
  8544. if (!IsInc) {
  8545. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8546. return QualType();
  8547. }
  8548. // Increment of bool sets it to true, but is deprecated.
  8549. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  8550. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8551. // Error on enum increments and decrements in C++ mode
  8552. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8553. return QualType();
  8554. } else if (ResType->isRealType()) {
  8555. // OK!
  8556. } else if (ResType->isPointerType()) {
  8557. // C99 6.5.2.4p2, 6.5.6p2
  8558. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8559. return QualType();
  8560. } else if (ResType->isObjCObjectPointerType()) {
  8561. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8562. // Otherwise, we just need a complete type.
  8563. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8564. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8565. return QualType();
  8566. } else if (ResType->isAnyComplexType()) {
  8567. // C99 does not support ++/-- on complex types, we allow as an extension.
  8568. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8569. << ResType << Op->getSourceRange();
  8570. } else if (ResType->isPlaceholderType()) {
  8571. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8572. if (PR.isInvalid()) return QualType();
  8573. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8574. IsInc, IsPrefix);
  8575. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8576. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8577. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8578. (ResType->getAs<VectorType>()->getVectorKind() !=
  8579. VectorType::AltiVecBool)) {
  8580. // The z vector extensions allow ++ and -- for non-bool vectors.
  8581. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8582. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8583. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8584. } else {
  8585. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8586. << ResType << int(IsInc) << Op->getSourceRange();
  8587. return QualType();
  8588. }
  8589. // At this point, we know we have a real, complex or pointer type.
  8590. // Now make sure the operand is a modifiable lvalue.
  8591. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8592. return QualType();
  8593. // In C++, a prefix increment is the same type as the operand. Otherwise
  8594. // (in C or with postfix), the increment is the unqualified type of the
  8595. // operand.
  8596. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8597. VK = VK_LValue;
  8598. OK = Op->getObjectKind();
  8599. return ResType;
  8600. } else {
  8601. VK = VK_RValue;
  8602. return ResType.getUnqualifiedType();
  8603. }
  8604. }
  8605. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8606. /// This routine allows us to typecheck complex/recursive expressions
  8607. /// where the declaration is needed for type checking. We only need to
  8608. /// handle cases when the expression references a function designator
  8609. /// or is an lvalue. Here are some examples:
  8610. /// - &(x) => x
  8611. /// - &*****f => f for f a function designator.
  8612. /// - &s.xx => s
  8613. /// - &s.zz[1].yy -> s, if zz is an array
  8614. /// - *(x + 1) -> x, if x is an array
  8615. /// - &"123"[2] -> 0
  8616. /// - & __real__ x -> x
  8617. static ValueDecl *getPrimaryDecl(Expr *E) {
  8618. switch (E->getStmtClass()) {
  8619. case Stmt::DeclRefExprClass:
  8620. return cast<DeclRefExpr>(E)->getDecl();
  8621. case Stmt::MemberExprClass:
  8622. // If this is an arrow operator, the address is an offset from
  8623. // the base's value, so the object the base refers to is
  8624. // irrelevant.
  8625. if (cast<MemberExpr>(E)->isArrow())
  8626. return nullptr;
  8627. // Otherwise, the expression refers to a part of the base
  8628. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8629. case Stmt::ArraySubscriptExprClass: {
  8630. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8631. // promotion of register arrays earlier.
  8632. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8633. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8634. if (ICE->getSubExpr()->getType()->isArrayType())
  8635. return getPrimaryDecl(ICE->getSubExpr());
  8636. }
  8637. return nullptr;
  8638. }
  8639. case Stmt::UnaryOperatorClass: {
  8640. UnaryOperator *UO = cast<UnaryOperator>(E);
  8641. switch(UO->getOpcode()) {
  8642. case UO_Real:
  8643. case UO_Imag:
  8644. case UO_Extension:
  8645. return getPrimaryDecl(UO->getSubExpr());
  8646. default:
  8647. return nullptr;
  8648. }
  8649. }
  8650. case Stmt::ParenExprClass:
  8651. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8652. case Stmt::ImplicitCastExprClass:
  8653. // If the result of an implicit cast is an l-value, we care about
  8654. // the sub-expression; otherwise, the result here doesn't matter.
  8655. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8656. default:
  8657. return nullptr;
  8658. }
  8659. }
  8660. namespace {
  8661. enum {
  8662. AO_Bit_Field = 0,
  8663. AO_Vector_Element = 1,
  8664. AO_Property_Expansion = 2,
  8665. AO_Register_Variable = 3,
  8666. AO_No_Error = 4
  8667. };
  8668. }
  8669. /// \brief Diagnose invalid operand for address of operations.
  8670. ///
  8671. /// \param Type The type of operand which cannot have its address taken.
  8672. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8673. Expr *E, unsigned Type) {
  8674. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8675. }
  8676. /// CheckAddressOfOperand - The operand of & must be either a function
  8677. /// designator or an lvalue designating an object. If it is an lvalue, the
  8678. /// object cannot be declared with storage class register or be a bit field.
  8679. /// Note: The usual conversions are *not* applied to the operand of the &
  8680. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8681. /// In C++, the operand might be an overloaded function name, in which case
  8682. /// we allow the '&' but retain the overloaded-function type.
  8683. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8684. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8685. if (PTy->getKind() == BuiltinType::Overload) {
  8686. Expr *E = OrigOp.get()->IgnoreParens();
  8687. if (!isa<OverloadExpr>(E)) {
  8688. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8689. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8690. << OrigOp.get()->getSourceRange();
  8691. return QualType();
  8692. }
  8693. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8694. if (isa<UnresolvedMemberExpr>(Ovl))
  8695. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8696. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8697. << OrigOp.get()->getSourceRange();
  8698. return QualType();
  8699. }
  8700. return Context.OverloadTy;
  8701. }
  8702. if (PTy->getKind() == BuiltinType::UnknownAny)
  8703. return Context.UnknownAnyTy;
  8704. if (PTy->getKind() == BuiltinType::BoundMember) {
  8705. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8706. << OrigOp.get()->getSourceRange();
  8707. return QualType();
  8708. }
  8709. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8710. if (OrigOp.isInvalid()) return QualType();
  8711. }
  8712. if (OrigOp.get()->isTypeDependent())
  8713. return Context.DependentTy;
  8714. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8715. // Make sure to ignore parentheses in subsequent checks
  8716. Expr *op = OrigOp.get()->IgnoreParens();
  8717. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8718. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8719. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8720. return QualType();
  8721. }
  8722. if (getLangOpts().C99) {
  8723. // Implement C99-only parts of addressof rules.
  8724. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8725. if (uOp->getOpcode() == UO_Deref)
  8726. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8727. // (assuming the deref expression is valid).
  8728. return uOp->getSubExpr()->getType();
  8729. }
  8730. // Technically, there should be a check for array subscript
  8731. // expressions here, but the result of one is always an lvalue anyway.
  8732. }
  8733. ValueDecl *dcl = getPrimaryDecl(op);
  8734. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8735. unsigned AddressOfError = AO_No_Error;
  8736. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8737. bool sfinae = (bool)isSFINAEContext();
  8738. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8739. : diag::ext_typecheck_addrof_temporary)
  8740. << op->getType() << op->getSourceRange();
  8741. if (sfinae)
  8742. return QualType();
  8743. // Materialize the temporary as an lvalue so that we can take its address.
  8744. OrigOp = op = new (Context)
  8745. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8746. } else if (isa<ObjCSelectorExpr>(op)) {
  8747. return Context.getPointerType(op->getType());
  8748. } else if (lval == Expr::LV_MemberFunction) {
  8749. // If it's an instance method, make a member pointer.
  8750. // The expression must have exactly the form &A::foo.
  8751. // If the underlying expression isn't a decl ref, give up.
  8752. if (!isa<DeclRefExpr>(op)) {
  8753. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8754. << OrigOp.get()->getSourceRange();
  8755. return QualType();
  8756. }
  8757. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8758. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8759. // The id-expression was parenthesized.
  8760. if (OrigOp.get() != DRE) {
  8761. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8762. << OrigOp.get()->getSourceRange();
  8763. // The method was named without a qualifier.
  8764. } else if (!DRE->getQualifier()) {
  8765. if (MD->getParent()->getName().empty())
  8766. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8767. << op->getSourceRange();
  8768. else {
  8769. SmallString<32> Str;
  8770. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8771. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8772. << op->getSourceRange()
  8773. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8774. }
  8775. }
  8776. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8777. if (isa<CXXDestructorDecl>(MD))
  8778. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8779. QualType MPTy = Context.getMemberPointerType(
  8780. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8781. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8782. RequireCompleteType(OpLoc, MPTy, 0);
  8783. return MPTy;
  8784. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8785. // C99 6.5.3.2p1
  8786. // The operand must be either an l-value or a function designator
  8787. if (!op->getType()->isFunctionType()) {
  8788. // Use a special diagnostic for loads from property references.
  8789. if (isa<PseudoObjectExpr>(op)) {
  8790. AddressOfError = AO_Property_Expansion;
  8791. } else {
  8792. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8793. << op->getType() << op->getSourceRange();
  8794. return QualType();
  8795. }
  8796. }
  8797. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8798. // The operand cannot be a bit-field
  8799. AddressOfError = AO_Bit_Field;
  8800. } else if (op->getObjectKind() == OK_VectorComponent) {
  8801. // The operand cannot be an element of a vector
  8802. AddressOfError = AO_Vector_Element;
  8803. } else if (dcl) { // C99 6.5.3.2p1
  8804. // We have an lvalue with a decl. Make sure the decl is not declared
  8805. // with the register storage-class specifier.
  8806. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8807. // in C++ it is not error to take address of a register
  8808. // variable (c++03 7.1.1P3)
  8809. if (vd->getStorageClass() == SC_Register &&
  8810. !getLangOpts().CPlusPlus) {
  8811. AddressOfError = AO_Register_Variable;
  8812. }
  8813. } else if (isa<MSPropertyDecl>(dcl)) {
  8814. AddressOfError = AO_Property_Expansion;
  8815. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8816. return Context.OverloadTy;
  8817. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8818. // Okay: we can take the address of a field.
  8819. // Could be a pointer to member, though, if there is an explicit
  8820. // scope qualifier for the class.
  8821. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8822. DeclContext *Ctx = dcl->getDeclContext();
  8823. if (Ctx && Ctx->isRecord()) {
  8824. if (dcl->getType()->isReferenceType()) {
  8825. Diag(OpLoc,
  8826. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8827. << dcl->getDeclName() << dcl->getType();
  8828. return QualType();
  8829. }
  8830. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8831. Ctx = Ctx->getParent();
  8832. QualType MPTy = Context.getMemberPointerType(
  8833. op->getType(),
  8834. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8835. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8836. RequireCompleteType(OpLoc, MPTy, 0);
  8837. return MPTy;
  8838. }
  8839. }
  8840. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8841. llvm_unreachable("Unknown/unexpected decl type");
  8842. }
  8843. if (AddressOfError != AO_No_Error) {
  8844. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8845. return QualType();
  8846. }
  8847. if (lval == Expr::LV_IncompleteVoidType) {
  8848. // Taking the address of a void variable is technically illegal, but we
  8849. // allow it in cases which are otherwise valid.
  8850. // Example: "extern void x; void* y = &x;".
  8851. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8852. }
  8853. // If the operand has type "type", the result has type "pointer to type".
  8854. if (op->getType()->isObjCObjectType())
  8855. return Context.getObjCObjectPointerType(op->getType());
  8856. return Context.getPointerType(op->getType());
  8857. }
  8858. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8859. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8860. if (!DRE)
  8861. return;
  8862. const Decl *D = DRE->getDecl();
  8863. if (!D)
  8864. return;
  8865. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8866. if (!Param)
  8867. return;
  8868. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8869. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8870. return;
  8871. if (FunctionScopeInfo *FD = S.getCurFunction())
  8872. if (!FD->ModifiedNonNullParams.count(Param))
  8873. FD->ModifiedNonNullParams.insert(Param);
  8874. }
  8875. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8876. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8877. SourceLocation OpLoc) {
  8878. if (Op->isTypeDependent())
  8879. return S.Context.DependentTy;
  8880. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8881. if (ConvResult.isInvalid())
  8882. return QualType();
  8883. Op = ConvResult.get();
  8884. QualType OpTy = Op->getType();
  8885. QualType Result;
  8886. if (isa<CXXReinterpretCastExpr>(Op)) {
  8887. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8888. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8889. Op->getSourceRange());
  8890. }
  8891. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8892. Result = PT->getPointeeType();
  8893. else if (const ObjCObjectPointerType *OPT =
  8894. OpTy->getAs<ObjCObjectPointerType>())
  8895. Result = OPT->getPointeeType();
  8896. else {
  8897. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8898. if (PR.isInvalid()) return QualType();
  8899. if (PR.get() != Op)
  8900. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8901. }
  8902. if (Result.isNull()) {
  8903. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8904. << OpTy << Op->getSourceRange();
  8905. return QualType();
  8906. }
  8907. // Note that per both C89 and C99, indirection is always legal, even if Result
  8908. // is an incomplete type or void. It would be possible to warn about
  8909. // dereferencing a void pointer, but it's completely well-defined, and such a
  8910. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8911. // for pointers to 'void' but is fine for any other pointer type:
  8912. //
  8913. // C++ [expr.unary.op]p1:
  8914. // [...] the expression to which [the unary * operator] is applied shall
  8915. // be a pointer to an object type, or a pointer to a function type
  8916. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8917. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8918. << OpTy << Op->getSourceRange();
  8919. // Dereferences are usually l-values...
  8920. VK = VK_LValue;
  8921. // ...except that certain expressions are never l-values in C.
  8922. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8923. VK = VK_RValue;
  8924. return Result;
  8925. }
  8926. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8927. BinaryOperatorKind Opc;
  8928. switch (Kind) {
  8929. default: llvm_unreachable("Unknown binop!");
  8930. case tok::periodstar: Opc = BO_PtrMemD; break;
  8931. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8932. case tok::star: Opc = BO_Mul; break;
  8933. case tok::slash: Opc = BO_Div; break;
  8934. case tok::percent: Opc = BO_Rem; break;
  8935. case tok::plus: Opc = BO_Add; break;
  8936. case tok::minus: Opc = BO_Sub; break;
  8937. case tok::lessless: Opc = BO_Shl; break;
  8938. case tok::greatergreater: Opc = BO_Shr; break;
  8939. case tok::lessequal: Opc = BO_LE; break;
  8940. case tok::less: Opc = BO_LT; break;
  8941. case tok::greaterequal: Opc = BO_GE; break;
  8942. case tok::greater: Opc = BO_GT; break;
  8943. case tok::exclaimequal: Opc = BO_NE; break;
  8944. case tok::equalequal: Opc = BO_EQ; break;
  8945. case tok::amp: Opc = BO_And; break;
  8946. case tok::caret: Opc = BO_Xor; break;
  8947. case tok::pipe: Opc = BO_Or; break;
  8948. case tok::ampamp: Opc = BO_LAnd; break;
  8949. case tok::pipepipe: Opc = BO_LOr; break;
  8950. case tok::equal: Opc = BO_Assign; break;
  8951. case tok::starequal: Opc = BO_MulAssign; break;
  8952. case tok::slashequal: Opc = BO_DivAssign; break;
  8953. case tok::percentequal: Opc = BO_RemAssign; break;
  8954. case tok::plusequal: Opc = BO_AddAssign; break;
  8955. case tok::minusequal: Opc = BO_SubAssign; break;
  8956. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8957. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8958. case tok::ampequal: Opc = BO_AndAssign; break;
  8959. case tok::caretequal: Opc = BO_XorAssign; break;
  8960. case tok::pipeequal: Opc = BO_OrAssign; break;
  8961. case tok::comma: Opc = BO_Comma; break;
  8962. }
  8963. return Opc;
  8964. }
  8965. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8966. tok::TokenKind Kind) {
  8967. UnaryOperatorKind Opc;
  8968. switch (Kind) {
  8969. default: llvm_unreachable("Unknown unary op!");
  8970. case tok::plusplus: Opc = UO_PreInc; break;
  8971. case tok::minusminus: Opc = UO_PreDec; break;
  8972. case tok::amp: Opc = UO_AddrOf; break;
  8973. case tok::star: Opc = UO_Deref; break;
  8974. case tok::plus: Opc = UO_Plus; break;
  8975. case tok::minus: Opc = UO_Minus; break;
  8976. case tok::tilde: Opc = UO_Not; break;
  8977. case tok::exclaim: Opc = UO_LNot; break;
  8978. case tok::kw___real: Opc = UO_Real; break;
  8979. case tok::kw___imag: Opc = UO_Imag; break;
  8980. case tok::kw___extension__: Opc = UO_Extension; break;
  8981. }
  8982. return Opc;
  8983. }
  8984. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8985. /// This warning is only emitted for builtin assignment operations. It is also
  8986. /// suppressed in the event of macro expansions.
  8987. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8988. SourceLocation OpLoc) {
  8989. if (!S.ActiveTemplateInstantiations.empty())
  8990. return;
  8991. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8992. return;
  8993. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8994. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8995. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8996. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8997. if (!LHSDeclRef || !RHSDeclRef ||
  8998. LHSDeclRef->getLocation().isMacroID() ||
  8999. RHSDeclRef->getLocation().isMacroID())
  9000. return;
  9001. const ValueDecl *LHSDecl =
  9002. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  9003. const ValueDecl *RHSDecl =
  9004. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  9005. if (LHSDecl != RHSDecl)
  9006. return;
  9007. if (LHSDecl->getType().isVolatileQualified())
  9008. return;
  9009. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  9010. if (RefTy->getPointeeType().isVolatileQualified())
  9011. return;
  9012. S.Diag(OpLoc, diag::warn_self_assignment)
  9013. << LHSDeclRef->getType()
  9014. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  9015. }
  9016. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  9017. /// is usually indicative of introspection within the Objective-C pointer.
  9018. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  9019. SourceLocation OpLoc) {
  9020. if (!S.getLangOpts().ObjC1)
  9021. return;
  9022. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  9023. const Expr *LHS = L.get();
  9024. const Expr *RHS = R.get();
  9025. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  9026. ObjCPointerExpr = LHS;
  9027. OtherExpr = RHS;
  9028. }
  9029. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  9030. ObjCPointerExpr = RHS;
  9031. OtherExpr = LHS;
  9032. }
  9033. // This warning is deliberately made very specific to reduce false
  9034. // positives with logic that uses '&' for hashing. This logic mainly
  9035. // looks for code trying to introspect into tagged pointers, which
  9036. // code should generally never do.
  9037. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  9038. unsigned Diag = diag::warn_objc_pointer_masking;
  9039. // Determine if we are introspecting the result of performSelectorXXX.
  9040. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  9041. // Special case messages to -performSelector and friends, which
  9042. // can return non-pointer values boxed in a pointer value.
  9043. // Some clients may wish to silence warnings in this subcase.
  9044. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  9045. Selector S = ME->getSelector();
  9046. StringRef SelArg0 = S.getNameForSlot(0);
  9047. if (SelArg0.startswith("performSelector"))
  9048. Diag = diag::warn_objc_pointer_masking_performSelector;
  9049. }
  9050. S.Diag(OpLoc, Diag)
  9051. << ObjCPointerExpr->getSourceRange();
  9052. }
  9053. }
  9054. static NamedDecl *getDeclFromExpr(Expr *E) {
  9055. if (!E)
  9056. return nullptr;
  9057. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  9058. return DRE->getDecl();
  9059. if (auto *ME = dyn_cast<MemberExpr>(E))
  9060. return ME->getMemberDecl();
  9061. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  9062. return IRE->getDecl();
  9063. return nullptr;
  9064. }
  9065. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  9066. /// operator @p Opc at location @c TokLoc. This routine only supports
  9067. /// built-in operations; ActOnBinOp handles overloaded operators.
  9068. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  9069. BinaryOperatorKind Opc,
  9070. Expr *LHSExpr, Expr *RHSExpr) {
  9071. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  9072. // The syntax only allows initializer lists on the RHS of assignment,
  9073. // so we don't need to worry about accepting invalid code for
  9074. // non-assignment operators.
  9075. // C++11 5.17p9:
  9076. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  9077. // of x = {} is x = T().
  9078. InitializationKind Kind =
  9079. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  9080. InitializedEntity Entity =
  9081. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  9082. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  9083. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  9084. if (Init.isInvalid())
  9085. return Init;
  9086. RHSExpr = Init.get();
  9087. }
  9088. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  9089. QualType ResultTy; // Result type of the binary operator.
  9090. // The following two variables are used for compound assignment operators
  9091. QualType CompLHSTy; // Type of LHS after promotions for computation
  9092. QualType CompResultTy; // Type of computation result
  9093. ExprValueKind VK = VK_RValue;
  9094. ExprObjectKind OK = OK_Ordinary;
  9095. // HLSL Change Starts
  9096. // Handle HLSL binary operands differently
  9097. if (getLangOpts().HLSL) {
  9098. hlsl::CheckBinOpForHLSL(*this, OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  9099. if (!ResultTy.isNull() && Opc == BO_Comma) {
  9100. // In C/C++, the RHS value kind should propagate. In HLSL, it should yield an r-value.
  9101. // VK = RHS.get()->getValueKind();
  9102. OK = RHS.get()->getObjectKind();
  9103. }
  9104. goto CasesHandled;
  9105. }
  9106. // HLSL Change Ends
  9107. if (!getLangOpts().CPlusPlus) {
  9108. // C cannot handle TypoExpr nodes on either side of a binop because it
  9109. // doesn't handle dependent types properly, so make sure any TypoExprs have
  9110. // been dealt with before checking the operands.
  9111. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  9112. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  9113. if (Opc != BO_Assign)
  9114. return ExprResult(E);
  9115. // Avoid correcting the RHS to the same Expr as the LHS.
  9116. Decl *D = getDeclFromExpr(E);
  9117. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  9118. });
  9119. if (!LHS.isUsable() || !RHS.isUsable())
  9120. return ExprError();
  9121. }
  9122. switch (Opc) {
  9123. case BO_Assign:
  9124. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  9125. if (getLangOpts().CPlusPlus &&
  9126. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  9127. VK = LHS.get()->getValueKind();
  9128. OK = LHS.get()->getObjectKind();
  9129. }
  9130. if (!ResultTy.isNull()) {
  9131. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9132. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  9133. }
  9134. RecordModifiableNonNullParam(*this, LHS.get());
  9135. break;
  9136. case BO_PtrMemD:
  9137. case BO_PtrMemI:
  9138. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  9139. Opc == BO_PtrMemI);
  9140. break;
  9141. case BO_Mul:
  9142. case BO_Div:
  9143. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  9144. Opc == BO_Div);
  9145. break;
  9146. case BO_Rem:
  9147. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  9148. break;
  9149. case BO_Add:
  9150. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  9151. break;
  9152. case BO_Sub:
  9153. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  9154. break;
  9155. case BO_Shl:
  9156. case BO_Shr:
  9157. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  9158. break;
  9159. case BO_LE:
  9160. case BO_LT:
  9161. case BO_GE:
  9162. case BO_GT:
  9163. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  9164. break;
  9165. case BO_EQ:
  9166. case BO_NE:
  9167. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  9168. break;
  9169. case BO_And:
  9170. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  9171. case BO_Xor:
  9172. case BO_Or:
  9173. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  9174. break;
  9175. case BO_LAnd:
  9176. case BO_LOr:
  9177. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  9178. break;
  9179. case BO_MulAssign:
  9180. case BO_DivAssign:
  9181. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  9182. Opc == BO_DivAssign);
  9183. CompLHSTy = CompResultTy;
  9184. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9185. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9186. break;
  9187. case BO_RemAssign:
  9188. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  9189. CompLHSTy = CompResultTy;
  9190. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9191. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9192. break;
  9193. case BO_AddAssign:
  9194. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  9195. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9196. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9197. break;
  9198. case BO_SubAssign:
  9199. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  9200. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9201. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9202. break;
  9203. case BO_ShlAssign:
  9204. case BO_ShrAssign:
  9205. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  9206. CompLHSTy = CompResultTy;
  9207. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9208. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9209. break;
  9210. case BO_AndAssign:
  9211. case BO_OrAssign: // fallthrough
  9212. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9213. case BO_XorAssign:
  9214. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  9215. CompLHSTy = CompResultTy;
  9216. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9217. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9218. break;
  9219. case BO_Comma:
  9220. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  9221. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  9222. VK = RHS.get()->getValueKind();
  9223. OK = RHS.get()->getObjectKind();
  9224. }
  9225. break;
  9226. }
  9227. CasesHandled: // HLSL Change: minimize code changes by avoiding a branch above
  9228. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  9229. return ExprError();
  9230. // Check for array bounds violations for both sides of the BinaryOperator
  9231. CheckArrayAccess(LHS.get());
  9232. CheckArrayAccess(RHS.get());
  9233. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  9234. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  9235. &Context.Idents.get("object_setClass"),
  9236. SourceLocation(), LookupOrdinaryName);
  9237. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  9238. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  9239. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  9240. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  9241. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  9242. FixItHint::CreateInsertion(RHSLocEnd, ")");
  9243. }
  9244. else
  9245. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9246. }
  9247. else if (const ObjCIvarRefExpr *OIRE =
  9248. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9249. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9250. if (CompResultTy.isNull())
  9251. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9252. OK, OpLoc, FPFeatures.fp_contract);
  9253. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9254. OK_ObjCProperty) {
  9255. VK = VK_LValue;
  9256. OK = LHS.get()->getObjectKind();
  9257. }
  9258. return new (Context) CompoundAssignOperator(
  9259. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9260. OpLoc, FPFeatures.fp_contract);
  9261. }
  9262. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9263. /// operators are mixed in a way that suggests that the programmer forgot that
  9264. /// comparison operators have higher precedence. The most typical example of
  9265. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9266. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9267. SourceLocation OpLoc, Expr *LHSExpr,
  9268. Expr *RHSExpr) {
  9269. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9270. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9271. // Check that one of the sides is a comparison operator.
  9272. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9273. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9274. if (!isLeftComp && !isRightComp)
  9275. return;
  9276. // Bitwise operations are sometimes used as eager logical ops.
  9277. // Don't diagnose this.
  9278. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9279. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9280. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9281. return;
  9282. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9283. OpLoc)
  9284. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9285. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9286. SourceRange ParensRange = isLeftComp ?
  9287. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9288. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9289. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9290. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9291. SuggestParentheses(Self, OpLoc,
  9292. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9293. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9294. SuggestParentheses(Self, OpLoc,
  9295. Self.PDiag(diag::note_precedence_bitwise_first)
  9296. << BinaryOperator::getOpcodeStr(Opc),
  9297. ParensRange);
  9298. }
  9299. /// \brief It accepts a '&' expr that is inside a '|' one.
  9300. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9301. /// in parentheses.
  9302. static void
  9303. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9304. BinaryOperator *Bop) {
  9305. assert(Bop->getOpcode() == BO_And);
  9306. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9307. << Bop->getSourceRange() << OpLoc;
  9308. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9309. Self.PDiag(diag::note_precedence_silence)
  9310. << Bop->getOpcodeStr(),
  9311. Bop->getSourceRange());
  9312. }
  9313. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9314. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9315. /// in parentheses.
  9316. static void
  9317. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9318. BinaryOperator *Bop) {
  9319. assert(Bop->getOpcode() == BO_LAnd);
  9320. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9321. << Bop->getSourceRange() << OpLoc;
  9322. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9323. Self.PDiag(diag::note_precedence_silence)
  9324. << Bop->getOpcodeStr(),
  9325. Bop->getSourceRange());
  9326. }
  9327. /// \brief Returns true if the given expression can be evaluated as a constant
  9328. /// 'true'.
  9329. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9330. bool Res;
  9331. return !E->isValueDependent() &&
  9332. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9333. }
  9334. /// \brief Returns true if the given expression can be evaluated as a constant
  9335. /// 'false'.
  9336. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9337. bool Res;
  9338. return !E->isValueDependent() &&
  9339. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9340. }
  9341. /// \brief Look for '&&' in the left hand of a '||' expr.
  9342. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9343. Expr *LHSExpr, Expr *RHSExpr) {
  9344. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9345. if (Bop->getOpcode() == BO_LAnd) {
  9346. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9347. if (EvaluatesAsFalse(S, RHSExpr))
  9348. return;
  9349. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9350. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9351. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9352. } else if (Bop->getOpcode() == BO_LOr) {
  9353. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9354. // If it's "a || b && 1 || c" we didn't warn earlier for
  9355. // "a || b && 1", but warn now.
  9356. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9357. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9358. }
  9359. }
  9360. }
  9361. }
  9362. /// \brief Look for '&&' in the right hand of a '||' expr.
  9363. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9364. Expr *LHSExpr, Expr *RHSExpr) {
  9365. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9366. if (Bop->getOpcode() == BO_LAnd) {
  9367. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9368. if (EvaluatesAsFalse(S, LHSExpr))
  9369. return;
  9370. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9371. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9372. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9373. }
  9374. }
  9375. }
  9376. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9377. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9378. Expr *OrArg) {
  9379. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9380. if (Bop->getOpcode() == BO_And)
  9381. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9382. }
  9383. }
  9384. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9385. Expr *SubExpr, StringRef Shift) {
  9386. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9387. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9388. StringRef Op = Bop->getOpcodeStr();
  9389. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9390. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9391. SuggestParentheses(S, Bop->getOperatorLoc(),
  9392. S.PDiag(diag::note_precedence_silence) << Op,
  9393. Bop->getSourceRange());
  9394. }
  9395. }
  9396. }
  9397. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9398. Expr *LHSExpr, Expr *RHSExpr) {
  9399. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9400. if (!OCE)
  9401. return;
  9402. FunctionDecl *FD = OCE->getDirectCallee();
  9403. if (!FD || !FD->isOverloadedOperator())
  9404. return;
  9405. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9406. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9407. return;
  9408. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9409. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9410. << (Kind == OO_LessLess);
  9411. SuggestParentheses(S, OCE->getOperatorLoc(),
  9412. S.PDiag(diag::note_precedence_silence)
  9413. << (Kind == OO_LessLess ? "<<" : ">>"),
  9414. OCE->getSourceRange());
  9415. SuggestParentheses(S, OpLoc,
  9416. S.PDiag(diag::note_evaluate_comparison_first),
  9417. SourceRange(OCE->getArg(1)->getLocStart(),
  9418. RHSExpr->getLocEnd()));
  9419. }
  9420. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9421. /// precedence.
  9422. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9423. SourceLocation OpLoc, Expr *LHSExpr,
  9424. Expr *RHSExpr){
  9425. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9426. if (BinaryOperator::isBitwiseOp(Opc))
  9427. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9428. // Diagnose "arg1 & arg2 | arg3"
  9429. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9430. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9431. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9432. }
  9433. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9434. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9435. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9436. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9437. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9438. }
  9439. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9440. || Opc == BO_Shr) {
  9441. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9442. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9443. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9444. }
  9445. // Warn on overloaded shift operators and comparisons, such as:
  9446. // cout << 5 == 4;
  9447. if (BinaryOperator::isComparisonOp(Opc))
  9448. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9449. }
  9450. // Binary Operators. 'Tok' is the token for the operator.
  9451. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9452. tok::TokenKind Kind,
  9453. Expr *LHSExpr, Expr *RHSExpr) {
  9454. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9455. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9456. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9457. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9458. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9459. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9460. }
  9461. /// Build an overloaded binary operator expression in the given scope.
  9462. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9463. BinaryOperatorKind Opc,
  9464. Expr *LHS, Expr *RHS) {
  9465. // Find all of the overloaded operators visible from this
  9466. // point. We perform both an operator-name lookup from the local
  9467. // scope and an argument-dependent lookup based on the types of
  9468. // the arguments.
  9469. UnresolvedSet<16> Functions;
  9470. OverloadedOperatorKind OverOp
  9471. = BinaryOperator::getOverloadedOperator(Opc);
  9472. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9473. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9474. RHS->getType(), Functions);
  9475. // Build the (potentially-overloaded, potentially-dependent)
  9476. // binary operation.
  9477. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9478. }
  9479. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9480. BinaryOperatorKind Opc,
  9481. Expr *LHSExpr, Expr *RHSExpr) {
  9482. // We want to end up calling one of checkPseudoObjectAssignment
  9483. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9484. // both expressions are overloadable or either is type-dependent),
  9485. // or CreateBuiltinBinOp (in any other case). We also want to get
  9486. // any placeholder types out of the way.
  9487. // Handle pseudo-objects in the LHS.
  9488. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9489. // Assignments with a pseudo-object l-value need special analysis.
  9490. if (pty->getKind() == BuiltinType::PseudoObject &&
  9491. BinaryOperator::isAssignmentOp(Opc))
  9492. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9493. // Don't resolve overloads if the other type is overloadable.
  9494. if (pty->getKind() == BuiltinType::Overload) {
  9495. // We can't actually test that if we still have a placeholder,
  9496. // though. Fortunately, none of the exceptions we see in that
  9497. // code below are valid when the LHS is an overload set. Note
  9498. // that an overload set can be dependently-typed, but it never
  9499. // instantiates to having an overloadable type.
  9500. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9501. if (resolvedRHS.isInvalid()) return ExprError();
  9502. RHSExpr = resolvedRHS.get();
  9503. if (RHSExpr->isTypeDependent() ||
  9504. RHSExpr->getType()->isOverloadableType())
  9505. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9506. }
  9507. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9508. if (LHS.isInvalid()) return ExprError();
  9509. LHSExpr = LHS.get();
  9510. }
  9511. // Handle pseudo-objects in the RHS.
  9512. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9513. // An overload in the RHS can potentially be resolved by the type
  9514. // being assigned to.
  9515. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9516. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9517. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9518. if (LHSExpr->getType()->isOverloadableType())
  9519. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9520. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9521. }
  9522. // Don't resolve overloads if the other type is overloadable.
  9523. if (pty->getKind() == BuiltinType::Overload &&
  9524. LHSExpr->getType()->isOverloadableType())
  9525. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9526. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9527. if (!resolvedRHS.isUsable()) return ExprError();
  9528. RHSExpr = resolvedRHS.get();
  9529. }
  9530. // HLSL Change: bypass binary operator overload work, which isn't supported in any case;
  9531. // otherwise more extensive changes need to be done to add HLSL-specific behavior to
  9532. // be considered when building overload candidate sets
  9533. if (getLangOpts().CPlusPlus && !getLangOpts().HLSL) {
  9534. // If either expression is type-dependent, always build an
  9535. // overloaded op.
  9536. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9537. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9538. // Otherwise, build an overloaded op if either expression has an
  9539. // overloadable type.
  9540. if (LHSExpr->getType()->isOverloadableType() ||
  9541. RHSExpr->getType()->isOverloadableType())
  9542. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9543. }
  9544. // Build a built-in binary operation.
  9545. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9546. }
  9547. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9548. UnaryOperatorKind Opc,
  9549. Expr *InputExpr) {
  9550. ExprResult Input = InputExpr;
  9551. ExprValueKind VK = VK_RValue;
  9552. ExprObjectKind OK = OK_Ordinary;
  9553. QualType resultType;
  9554. // HLSL Change Starts
  9555. if (getLangOpts().HLSL) {
  9556. resultType = hlsl::CheckUnaryOpForHLSL(*this, OpLoc, Opc, Input, VK, OK);
  9557. goto CasesHandled;
  9558. }
  9559. // HLSL Change Ends
  9560. switch (Opc) {
  9561. case UO_PreInc:
  9562. case UO_PreDec:
  9563. case UO_PostInc:
  9564. case UO_PostDec:
  9565. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9566. OpLoc,
  9567. Opc == UO_PreInc ||
  9568. Opc == UO_PostInc,
  9569. Opc == UO_PreInc ||
  9570. Opc == UO_PreDec);
  9571. break;
  9572. case UO_AddrOf:
  9573. resultType = CheckAddressOfOperand(Input, OpLoc);
  9574. RecordModifiableNonNullParam(*this, InputExpr);
  9575. break;
  9576. case UO_Deref: {
  9577. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9578. if (Input.isInvalid()) return ExprError();
  9579. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9580. break;
  9581. }
  9582. case UO_Plus:
  9583. case UO_Minus:
  9584. Input = UsualUnaryConversions(Input.get());
  9585. if (Input.isInvalid()) return ExprError();
  9586. resultType = Input.get()->getType();
  9587. if (resultType->isDependentType())
  9588. break;
  9589. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9590. break;
  9591. else if (resultType->isVectorType() &&
  9592. // The z vector extensions don't allow + or - with bool vectors.
  9593. (!Context.getLangOpts().ZVector ||
  9594. resultType->getAs<VectorType>()->getVectorKind() !=
  9595. VectorType::AltiVecBool))
  9596. break;
  9597. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9598. Opc == UO_Plus &&
  9599. resultType->isPointerType())
  9600. break;
  9601. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9602. << resultType << Input.get()->getSourceRange());
  9603. case UO_Not: // bitwise complement
  9604. Input = UsualUnaryConversions(Input.get());
  9605. if (Input.isInvalid())
  9606. return ExprError();
  9607. resultType = Input.get()->getType();
  9608. if (resultType->isDependentType())
  9609. break;
  9610. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9611. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9612. // C99 does not support '~' for complex conjugation.
  9613. Diag(OpLoc, diag::ext_integer_complement_complex)
  9614. << resultType << Input.get()->getSourceRange();
  9615. else if (resultType->hasIntegerRepresentation())
  9616. break;
  9617. else if (resultType->isExtVectorType()) {
  9618. if (Context.getLangOpts().OpenCL) {
  9619. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9620. // on vector float types.
  9621. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9622. if (!T->isIntegerType())
  9623. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9624. << resultType << Input.get()->getSourceRange());
  9625. }
  9626. break;
  9627. } else {
  9628. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9629. << resultType << Input.get()->getSourceRange());
  9630. }
  9631. break;
  9632. case UO_LNot: // logical negation
  9633. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9634. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9635. if (Input.isInvalid()) return ExprError();
  9636. resultType = Input.get()->getType();
  9637. // Though we still have to promote half FP to float...
  9638. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9639. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9640. resultType = Context.FloatTy;
  9641. }
  9642. if (resultType->isDependentType())
  9643. break;
  9644. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9645. // C99 6.5.3.3p1: ok, fallthrough;
  9646. if (Context.getLangOpts().CPlusPlus) {
  9647. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9648. // operand contextually converted to bool.
  9649. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9650. ScalarTypeToBooleanCastKind(resultType));
  9651. } else if (Context.getLangOpts().OpenCL &&
  9652. Context.getLangOpts().OpenCLVersion < 120) {
  9653. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9654. // operate on scalar float types.
  9655. if (!resultType->isIntegerType())
  9656. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9657. << resultType << Input.get()->getSourceRange());
  9658. }
  9659. } else if (resultType->isExtVectorType()) {
  9660. if (Context.getLangOpts().OpenCL &&
  9661. Context.getLangOpts().OpenCLVersion < 120) {
  9662. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9663. // operate on vector float types.
  9664. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9665. if (!T->isIntegerType())
  9666. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9667. << resultType << Input.get()->getSourceRange());
  9668. }
  9669. // Vector logical not returns the signed variant of the operand type.
  9670. resultType = GetSignedVectorType(resultType);
  9671. break;
  9672. } else {
  9673. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9674. << resultType << Input.get()->getSourceRange());
  9675. }
  9676. // LNot always has type int. C99 6.5.3.3p5.
  9677. // In C++, it's bool. C++ 5.3.1p8
  9678. resultType = Context.getLogicalOperationType();
  9679. break;
  9680. case UO_Real:
  9681. case UO_Imag:
  9682. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9683. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9684. // complex l-values to ordinary l-values and all other values to r-values.
  9685. if (Input.isInvalid()) return ExprError();
  9686. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9687. if (Input.get()->getValueKind() != VK_RValue &&
  9688. Input.get()->getObjectKind() == OK_Ordinary)
  9689. VK = Input.get()->getValueKind();
  9690. } else if (!getLangOpts().CPlusPlus) {
  9691. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9692. Input = DefaultLvalueConversion(Input.get());
  9693. }
  9694. break;
  9695. case UO_Extension:
  9696. resultType = Input.get()->getType();
  9697. VK = Input.get()->getValueKind();
  9698. OK = Input.get()->getObjectKind();
  9699. break;
  9700. }
  9701. CasesHandled: // HLSL Change: add label to skip C/C++ unary operator processing
  9702. if (resultType.isNull() || Input.isInvalid())
  9703. return ExprError();
  9704. // Check for array bounds violations in the operand of the UnaryOperator,
  9705. // except for the '*' and '&' operators that have to be handled specially
  9706. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9707. // that are explicitly defined as valid by the standard).
  9708. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9709. CheckArrayAccess(Input.get());
  9710. return new (Context)
  9711. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9712. }
  9713. /// \brief Determine whether the given expression is a qualified member
  9714. /// access expression, of a form that could be turned into a pointer to member
  9715. /// with the address-of operator.
  9716. static bool isQualifiedMemberAccess(Expr *E) {
  9717. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9718. if (!DRE->getQualifier())
  9719. return false;
  9720. ValueDecl *VD = DRE->getDecl();
  9721. if (!VD->isCXXClassMember())
  9722. return false;
  9723. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9724. return true;
  9725. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9726. return Method->isInstance();
  9727. return false;
  9728. }
  9729. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9730. if (!ULE->getQualifier())
  9731. return false;
  9732. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9733. DEnd = ULE->decls_end();
  9734. D != DEnd; ++D) {
  9735. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9736. if (Method->isInstance())
  9737. return true;
  9738. } else {
  9739. // Overload set does not contain methods.
  9740. break;
  9741. }
  9742. }
  9743. return false;
  9744. }
  9745. return false;
  9746. }
  9747. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9748. UnaryOperatorKind Opc, Expr *Input) {
  9749. // HLSL Change Starts - placeholders and overloaded operators not supported
  9750. if (getLangOpts().HLSL)
  9751. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9752. // HLSL Change Ends
  9753. // First things first: handle placeholders so that the
  9754. // overloaded-operator check considers the right type.
  9755. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9756. // Increment and decrement of pseudo-object references.
  9757. if (pty->getKind() == BuiltinType::PseudoObject &&
  9758. UnaryOperator::isIncrementDecrementOp(Opc))
  9759. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9760. // extension is always a builtin operator.
  9761. if (Opc == UO_Extension)
  9762. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9763. // & gets special logic for several kinds of placeholder.
  9764. // The builtin code knows what to do.
  9765. if (Opc == UO_AddrOf &&
  9766. (pty->getKind() == BuiltinType::Overload ||
  9767. pty->getKind() == BuiltinType::UnknownAny ||
  9768. pty->getKind() == BuiltinType::BoundMember))
  9769. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9770. // Anything else needs to be handled now.
  9771. ExprResult Result = CheckPlaceholderExpr(Input);
  9772. if (Result.isInvalid()) return ExprError();
  9773. Input = Result.get();
  9774. }
  9775. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9776. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9777. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9778. // Find all of the overloaded operators visible from this
  9779. // point. We perform both an operator-name lookup from the local
  9780. // scope and an argument-dependent lookup based on the types of
  9781. // the arguments.
  9782. UnresolvedSet<16> Functions;
  9783. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9784. if (S && OverOp != OO_None)
  9785. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9786. Functions);
  9787. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9788. }
  9789. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9790. }
  9791. // Unary Operators. 'Tok' is the token for the operator.
  9792. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9793. tok::TokenKind Op, Expr *Input) {
  9794. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9795. }
  9796. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9797. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9798. LabelDecl *TheDecl) {
  9799. TheDecl->markUsed(Context);
  9800. // Create the AST node. The address of a label always has type 'void*'.
  9801. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9802. Context.getPointerType(Context.VoidTy));
  9803. }
  9804. /// Given the last statement in a statement-expression, check whether
  9805. /// the result is a producing expression (like a call to an
  9806. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9807. /// release out of the full-expression. Otherwise, return null.
  9808. /// Cannot fail.
  9809. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9810. // Should always be wrapped with one of these.
  9811. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9812. if (!cleanups) return nullptr;
  9813. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9814. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9815. return nullptr;
  9816. // Splice out the cast. This shouldn't modify any interesting
  9817. // features of the statement.
  9818. Expr *producer = cast->getSubExpr();
  9819. assert(producer->getType() == cast->getType());
  9820. assert(producer->getValueKind() == cast->getValueKind());
  9821. cleanups->setSubExpr(producer);
  9822. return cleanups;
  9823. }
  9824. void Sema::ActOnStartStmtExpr() {
  9825. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9826. }
  9827. void Sema::ActOnStmtExprError() {
  9828. // Note that function is also called by TreeTransform when leaving a
  9829. // StmtExpr scope without rebuilding anything.
  9830. DiscardCleanupsInEvaluationContext();
  9831. PopExpressionEvaluationContext();
  9832. }
  9833. ExprResult
  9834. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9835. SourceLocation RPLoc) { // "({..})"
  9836. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9837. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9838. if (hasAnyUnrecoverableErrorsInThisFunction())
  9839. DiscardCleanupsInEvaluationContext();
  9840. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9841. PopExpressionEvaluationContext();
  9842. // FIXME: there are a variety of strange constraints to enforce here, for
  9843. // example, it is not possible to goto into a stmt expression apparently.
  9844. // More semantic analysis is needed.
  9845. // If there are sub-stmts in the compound stmt, take the type of the last one
  9846. // as the type of the stmtexpr.
  9847. QualType Ty = Context.VoidTy;
  9848. bool StmtExprMayBindToTemp = false;
  9849. if (!Compound->body_empty()) {
  9850. Stmt *LastStmt = Compound->body_back();
  9851. LabelStmt *LastLabelStmt = nullptr;
  9852. // If LastStmt is a label, skip down through into the body.
  9853. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9854. LastLabelStmt = Label;
  9855. LastStmt = Label->getSubStmt();
  9856. }
  9857. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9858. // Do function/array conversion on the last expression, but not
  9859. // lvalue-to-rvalue. However, initialize an unqualified type.
  9860. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9861. if (LastExpr.isInvalid())
  9862. return ExprError();
  9863. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9864. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9865. // In ARC, if the final expression ends in a consume, splice
  9866. // the consume out and bind it later. In the alternate case
  9867. // (when dealing with a retainable type), the result
  9868. // initialization will create a produce. In both cases the
  9869. // result will be +1, and we'll need to balance that out with
  9870. // a bind.
  9871. if (Expr *rebuiltLastStmt
  9872. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9873. LastExpr = rebuiltLastStmt;
  9874. } else {
  9875. LastExpr = PerformCopyInitialization(
  9876. InitializedEntity::InitializeResult(LPLoc,
  9877. Ty,
  9878. false),
  9879. SourceLocation(),
  9880. LastExpr);
  9881. }
  9882. if (LastExpr.isInvalid())
  9883. return ExprError();
  9884. if (LastExpr.get() != nullptr) {
  9885. if (!LastLabelStmt)
  9886. Compound->setLastStmt(LastExpr.get());
  9887. else
  9888. LastLabelStmt->setSubStmt(LastExpr.get());
  9889. StmtExprMayBindToTemp = true;
  9890. }
  9891. }
  9892. }
  9893. }
  9894. // FIXME: Check that expression type is complete/non-abstract; statement
  9895. // expressions are not lvalues.
  9896. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9897. if (StmtExprMayBindToTemp)
  9898. return MaybeBindToTemporary(ResStmtExpr);
  9899. return ResStmtExpr;
  9900. }
  9901. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9902. TypeSourceInfo *TInfo,
  9903. OffsetOfComponent *CompPtr,
  9904. unsigned NumComponents,
  9905. SourceLocation RParenLoc) {
  9906. QualType ArgTy = TInfo->getType();
  9907. bool Dependent = ArgTy->isDependentType();
  9908. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9909. // We must have at least one component that refers to the type, and the first
  9910. // one is known to be a field designator. Verify that the ArgTy represents
  9911. // a struct/union/class.
  9912. if (!Dependent && !ArgTy->isRecordType())
  9913. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9914. << ArgTy << TypeRange);
  9915. // Type must be complete per C99 7.17p3 because a declaring a variable
  9916. // with an incomplete type would be ill-formed.
  9917. if (!Dependent
  9918. && RequireCompleteType(BuiltinLoc, ArgTy,
  9919. diag::err_offsetof_incomplete_type, TypeRange))
  9920. return ExprError();
  9921. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9922. // GCC extension, diagnose them.
  9923. // FIXME: This diagnostic isn't actually visible because the location is in
  9924. // a system header!
  9925. if (NumComponents != 1)
  9926. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9927. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9928. bool DidWarnAboutNonPOD = false;
  9929. QualType CurrentType = ArgTy;
  9930. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9931. SmallVector<OffsetOfNode, 4> Comps;
  9932. SmallVector<Expr*, 4> Exprs;
  9933. for (unsigned i = 0; i != NumComponents; ++i) {
  9934. const OffsetOfComponent &OC = CompPtr[i];
  9935. if (OC.isBrackets) {
  9936. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9937. if (!CurrentType->isDependentType()) {
  9938. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9939. if(!AT)
  9940. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9941. << CurrentType);
  9942. CurrentType = AT->getElementType();
  9943. } else
  9944. CurrentType = Context.DependentTy;
  9945. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9946. if (IdxRval.isInvalid())
  9947. return ExprError();
  9948. Expr *Idx = IdxRval.get();
  9949. // The expression must be an integral expression.
  9950. // FIXME: An integral constant expression?
  9951. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9952. !Idx->getType()->isIntegerType())
  9953. return ExprError(Diag(Idx->getLocStart(),
  9954. diag::err_typecheck_subscript_not_integer)
  9955. << Idx->getSourceRange());
  9956. // Record this array index.
  9957. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9958. Exprs.push_back(Idx);
  9959. continue;
  9960. }
  9961. // Offset of a field.
  9962. if (CurrentType->isDependentType()) {
  9963. // We have the offset of a field, but we can't look into the dependent
  9964. // type. Just record the identifier of the field.
  9965. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9966. CurrentType = Context.DependentTy;
  9967. continue;
  9968. }
  9969. // We need to have a complete type to look into.
  9970. if (RequireCompleteType(OC.LocStart, CurrentType,
  9971. diag::err_offsetof_incomplete_type))
  9972. return ExprError();
  9973. // Look for the designated field.
  9974. const RecordType *RC = CurrentType->getAs<RecordType>();
  9975. if (!RC)
  9976. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9977. << CurrentType);
  9978. RecordDecl *RD = RC->getDecl();
  9979. // C++ [lib.support.types]p5:
  9980. // The macro offsetof accepts a restricted set of type arguments in this
  9981. // International Standard. type shall be a POD structure or a POD union
  9982. // (clause 9).
  9983. // C++11 [support.types]p4:
  9984. // If type is not a standard-layout class (Clause 9), the results are
  9985. // undefined.
  9986. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9987. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9988. unsigned DiagID =
  9989. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9990. : diag::ext_offsetof_non_pod_type;
  9991. if (!IsSafe && !DidWarnAboutNonPOD &&
  9992. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9993. PDiag(DiagID)
  9994. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  9995. << CurrentType))
  9996. DidWarnAboutNonPOD = true;
  9997. }
  9998. // Look for the field.
  9999. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  10000. LookupQualifiedName(R, RD);
  10001. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  10002. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  10003. if (!MemberDecl) {
  10004. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  10005. MemberDecl = IndirectMemberDecl->getAnonField();
  10006. }
  10007. if (!MemberDecl)
  10008. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  10009. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  10010. OC.LocEnd));
  10011. // C99 7.17p3:
  10012. // (If the specified member is a bit-field, the behavior is undefined.)
  10013. //
  10014. // We diagnose this as an error.
  10015. if (MemberDecl->isBitField()) {
  10016. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  10017. << MemberDecl->getDeclName()
  10018. << SourceRange(BuiltinLoc, RParenLoc);
  10019. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  10020. return ExprError();
  10021. }
  10022. RecordDecl *Parent = MemberDecl->getParent();
  10023. if (IndirectMemberDecl)
  10024. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  10025. // If the member was found in a base class, introduce OffsetOfNodes for
  10026. // the base class indirections.
  10027. CXXBasePaths Paths;
  10028. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  10029. if (Paths.getDetectedVirtual()) {
  10030. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  10031. << MemberDecl->getDeclName()
  10032. << SourceRange(BuiltinLoc, RParenLoc);
  10033. return ExprError();
  10034. }
  10035. CXXBasePath &Path = Paths.front();
  10036. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  10037. B != BEnd; ++B)
  10038. Comps.push_back(OffsetOfNode(B->Base));
  10039. }
  10040. if (IndirectMemberDecl) {
  10041. for (auto *FI : IndirectMemberDecl->chain()) {
  10042. assert(isa<FieldDecl>(FI));
  10043. Comps.push_back(OffsetOfNode(OC.LocStart,
  10044. cast<FieldDecl>(FI), OC.LocEnd));
  10045. }
  10046. } else
  10047. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  10048. CurrentType = MemberDecl->getType().getNonReferenceType();
  10049. }
  10050. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  10051. Comps, Exprs, RParenLoc);
  10052. }
  10053. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  10054. SourceLocation BuiltinLoc,
  10055. SourceLocation TypeLoc,
  10056. ParsedType ParsedArgTy,
  10057. OffsetOfComponent *CompPtr,
  10058. unsigned NumComponents,
  10059. SourceLocation RParenLoc) {
  10060. TypeSourceInfo *ArgTInfo;
  10061. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  10062. if (ArgTy.isNull())
  10063. return ExprError();
  10064. if (!ArgTInfo)
  10065. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  10066. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  10067. RParenLoc);
  10068. }
  10069. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  10070. Expr *CondExpr,
  10071. Expr *LHSExpr, Expr *RHSExpr,
  10072. SourceLocation RPLoc) {
  10073. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  10074. ExprValueKind VK = VK_RValue;
  10075. ExprObjectKind OK = OK_Ordinary;
  10076. QualType resType;
  10077. bool ValueDependent = false;
  10078. bool CondIsTrue = false;
  10079. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  10080. resType = Context.DependentTy;
  10081. ValueDependent = true;
  10082. } else {
  10083. // The conditional expression is required to be a constant expression.
  10084. llvm::APSInt condEval(32);
  10085. ExprResult CondICE
  10086. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  10087. diag::err_typecheck_choose_expr_requires_constant, false);
  10088. if (CondICE.isInvalid())
  10089. return ExprError();
  10090. CondExpr = CondICE.get();
  10091. CondIsTrue = condEval.getZExtValue();
  10092. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  10093. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  10094. resType = ActiveExpr->getType();
  10095. ValueDependent = ActiveExpr->isValueDependent();
  10096. VK = ActiveExpr->getValueKind();
  10097. OK = ActiveExpr->getObjectKind();
  10098. }
  10099. return new (Context)
  10100. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  10101. CondIsTrue, resType->isDependentType(), ValueDependent);
  10102. }
  10103. //===----------------------------------------------------------------------===//
  10104. // Clang Extensions.
  10105. //===----------------------------------------------------------------------===//
  10106. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  10107. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  10108. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  10109. if (LangOpts.CPlusPlus) {
  10110. Decl *ManglingContextDecl;
  10111. if (MangleNumberingContext *MCtx =
  10112. getCurrentMangleNumberContext(Block->getDeclContext(),
  10113. ManglingContextDecl)) {
  10114. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  10115. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  10116. }
  10117. }
  10118. PushBlockScope(CurScope, Block);
  10119. CurContext->addDecl(Block);
  10120. if (CurScope)
  10121. PushDeclContext(CurScope, Block);
  10122. else
  10123. CurContext = Block;
  10124. getCurBlock()->HasImplicitReturnType = true;
  10125. // Enter a new evaluation context to insulate the block from any
  10126. // cleanups from the enclosing full-expression.
  10127. PushExpressionEvaluationContext(PotentiallyEvaluated);
  10128. }
  10129. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  10130. Scope *CurScope) {
  10131. assert(ParamInfo.getIdentifier() == nullptr &&
  10132. "block-id should have no identifier!");
  10133. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  10134. BlockScopeInfo *CurBlock = getCurBlock();
  10135. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  10136. QualType T = Sig->getType();
  10137. // FIXME: We should allow unexpanded parameter packs here, but that would,
  10138. // in turn, make the block expression contain unexpanded parameter packs.
  10139. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  10140. // Drop the parameters.
  10141. FunctionProtoType::ExtProtoInfo EPI;
  10142. EPI.HasTrailingReturn = false;
  10143. EPI.TypeQuals |= DeclSpec::TQ_const;
  10144. T = Context.getFunctionType(Context.DependentTy, None, EPI, None); // HLSL Change - add param mods
  10145. Sig = Context.getTrivialTypeSourceInfo(T);
  10146. }
  10147. // GetTypeForDeclarator always produces a function type for a block
  10148. // literal signature. Furthermore, it is always a FunctionProtoType
  10149. // unless the function was written with a typedef.
  10150. assert(T->isFunctionType() &&
  10151. "GetTypeForDeclarator made a non-function block signature");
  10152. // Look for an explicit signature in that function type.
  10153. FunctionProtoTypeLoc ExplicitSignature;
  10154. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  10155. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  10156. // Check whether that explicit signature was synthesized by
  10157. // GetTypeForDeclarator. If so, don't save that as part of the
  10158. // written signature.
  10159. if (ExplicitSignature.getLocalRangeBegin() ==
  10160. ExplicitSignature.getLocalRangeEnd()) {
  10161. // This would be much cheaper if we stored TypeLocs instead of
  10162. // TypeSourceInfos.
  10163. TypeLoc Result = ExplicitSignature.getReturnLoc();
  10164. unsigned Size = Result.getFullDataSize();
  10165. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  10166. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  10167. ExplicitSignature = FunctionProtoTypeLoc();
  10168. }
  10169. }
  10170. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  10171. CurBlock->FunctionType = T;
  10172. const FunctionType *Fn = T->getAs<FunctionType>();
  10173. QualType RetTy = Fn->getReturnType();
  10174. bool isVariadic =
  10175. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  10176. CurBlock->TheDecl->setIsVariadic(isVariadic);
  10177. // Context.DependentTy is used as a placeholder for a missing block
  10178. // return type. TODO: what should we do with declarators like:
  10179. // ^ * { ... }
  10180. // If the answer is "apply template argument deduction"....
  10181. if (RetTy != Context.DependentTy) {
  10182. CurBlock->ReturnType = RetTy;
  10183. CurBlock->TheDecl->setBlockMissingReturnType(false);
  10184. CurBlock->HasImplicitReturnType = false;
  10185. }
  10186. // Push block parameters from the declarator if we had them.
  10187. SmallVector<ParmVarDecl*, 8> Params;
  10188. if (ExplicitSignature) {
  10189. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  10190. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  10191. if (Param->getIdentifier() == nullptr &&
  10192. !Param->isImplicit() &&
  10193. !Param->isInvalidDecl() &&
  10194. !getLangOpts().CPlusPlus)
  10195. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10196. Params.push_back(Param);
  10197. }
  10198. // Fake up parameter variables if we have a typedef, like
  10199. // ^ fntype { ... }
  10200. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  10201. for (const auto &I : Fn->param_types()) {
  10202. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  10203. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  10204. Params.push_back(Param);
  10205. }
  10206. }
  10207. // Set the parameters on the block decl.
  10208. if (!Params.empty()) {
  10209. CurBlock->TheDecl->setParams(Params);
  10210. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  10211. CurBlock->TheDecl->param_end(),
  10212. /*CheckParameterNames=*/false);
  10213. }
  10214. // Finally we can process decl attributes.
  10215. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  10216. // Put the parameter variables in scope.
  10217. for (auto AI : CurBlock->TheDecl->params()) {
  10218. AI->setOwningFunction(CurBlock->TheDecl);
  10219. // If this has an identifier, add it to the scope stack.
  10220. if (AI->getIdentifier()) {
  10221. CheckShadow(CurBlock->TheScope, AI);
  10222. PushOnScopeChains(AI, CurBlock->TheScope);
  10223. }
  10224. }
  10225. }
  10226. /// ActOnBlockError - If there is an error parsing a block, this callback
  10227. /// is invoked to pop the information about the block from the action impl.
  10228. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  10229. // Leave the expression-evaluation context.
  10230. DiscardCleanupsInEvaluationContext();
  10231. PopExpressionEvaluationContext();
  10232. // Pop off CurBlock, handle nested blocks.
  10233. PopDeclContext();
  10234. PopFunctionScopeInfo();
  10235. }
  10236. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  10237. /// literal was successfully completed. ^(int x){...}
  10238. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  10239. Stmt *Body, Scope *CurScope) {
  10240. // HLSL Changes Start
  10241. llvm_unreachable("block statements unsupported and unreachable in HLSL");
  10242. #if 0
  10243. // HLSL Changes End
  10244. // If blocks are disabled, emit an error.
  10245. if (!LangOpts.Blocks)
  10246. Diag(CaretLoc, diag::err_blocks_disable);
  10247. // Leave the expression-evaluation context.
  10248. if (hasAnyUnrecoverableErrorsInThisFunction())
  10249. DiscardCleanupsInEvaluationContext();
  10250. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  10251. PopExpressionEvaluationContext();
  10252. if (getLangOpts().HLSL) {
  10253. return ExprError();
  10254. }
  10255. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  10256. if (BSI->HasImplicitReturnType)
  10257. deduceClosureReturnType(*BSI);
  10258. PopDeclContext();
  10259. QualType RetTy = Context.VoidTy;
  10260. if (!BSI->ReturnType.isNull())
  10261. RetTy = BSI->ReturnType;
  10262. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  10263. QualType BlockTy;
  10264. // Set the captured variables on the block.
  10265. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10266. SmallVector<BlockDecl::Capture, 4> Captures;
  10267. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10268. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10269. if (Cap.isThisCapture())
  10270. continue;
  10271. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10272. Cap.isNested(), Cap.getInitExpr());
  10273. Captures.push_back(NewCap);
  10274. }
  10275. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  10276. BSI->CXXThisCaptureIndex != 0);
  10277. // If the user wrote a function type in some form, try to use that.
  10278. if (!BSI->FunctionType.isNull()) {
  10279. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10280. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10281. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10282. // Turn protoless block types into nullary block types.
  10283. if (isa<FunctionNoProtoType>(FTy)) {
  10284. FunctionProtoType::ExtProtoInfo EPI;
  10285. EPI.ExtInfo = Ext;
  10286. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10287. // Otherwise, if we don't need to change anything about the function type,
  10288. // preserve its sugar structure.
  10289. } else if (FTy->getReturnType() == RetTy &&
  10290. (!NoReturn || FTy->getNoReturnAttr())) {
  10291. BlockTy = BSI->FunctionType;
  10292. // Otherwise, make the minimal modifications to the function type.
  10293. } else {
  10294. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10295. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10296. EPI.TypeQuals = 0; // FIXME: silently?
  10297. EPI.ExtInfo = Ext;
  10298. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10299. }
  10300. // If we don't have a function type, just build one from nothing.
  10301. } else {
  10302. FunctionProtoType::ExtProtoInfo EPI;
  10303. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10304. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10305. }
  10306. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10307. BSI->TheDecl->param_end());
  10308. BlockTy = Context.getBlockPointerType(BlockTy);
  10309. // If needed, diagnose invalid gotos and switches in the block.
  10310. if (getCurFunction()->NeedsScopeChecking() &&
  10311. !PP.isCodeCompletionEnabled())
  10312. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10313. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10314. // Try to apply the named return value optimization. We have to check again
  10315. // if we can do this, though, because blocks keep return statements around
  10316. // to deduce an implicit return type.
  10317. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10318. !BSI->TheDecl->isDependentContext())
  10319. computeNRVO(Body, BSI);
  10320. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10321. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10322. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10323. // If the block isn't obviously global, i.e. it captures anything at
  10324. // all, then we need to do a few things in the surrounding context:
  10325. if (Result->getBlockDecl()->hasCaptures()) {
  10326. // First, this expression has a new cleanup object.
  10327. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10328. ExprNeedsCleanups = true;
  10329. // It also gets a branch-protected scope if any of the captured
  10330. // variables needs destruction.
  10331. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10332. const VarDecl *var = CI.getVariable();
  10333. if (var->getType().isDestructedType() != QualType::DK_none) {
  10334. getCurFunction()->setHasBranchProtectedScope();
  10335. break;
  10336. }
  10337. }
  10338. }
  10339. return Result;
  10340. #endif // HLSL Change
  10341. }
  10342. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10343. Expr *E, ParsedType Ty,
  10344. SourceLocation RPLoc) {
  10345. TypeSourceInfo *TInfo;
  10346. GetTypeFromParser(Ty, &TInfo);
  10347. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10348. }
  10349. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10350. Expr *E, TypeSourceInfo *TInfo,
  10351. SourceLocation RPLoc) {
  10352. Expr *OrigExpr = E;
  10353. // Get the va_list type
  10354. QualType VaListType = Context.getBuiltinVaListType();
  10355. if (VaListType->isArrayType()) {
  10356. // Deal with implicit array decay; for example, on x86-64,
  10357. // va_list is an array, but it's supposed to decay to
  10358. // a pointer for va_arg.
  10359. VaListType = Context.getArrayDecayedType(VaListType);
  10360. // Make sure the input expression also decays appropriately.
  10361. ExprResult Result = UsualUnaryConversions(E);
  10362. if (Result.isInvalid())
  10363. return ExprError();
  10364. E = Result.get();
  10365. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10366. // If va_list is a record type and we are compiling in C++ mode,
  10367. // check the argument using reference binding.
  10368. InitializedEntity Entity
  10369. = InitializedEntity::InitializeParameter(Context,
  10370. Context.getLValueReferenceType(VaListType), false);
  10371. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10372. if (Init.isInvalid())
  10373. return ExprError();
  10374. E = Init.getAs<Expr>();
  10375. } else {
  10376. // Otherwise, the va_list argument must be an l-value because
  10377. // it is modified by va_arg.
  10378. if (!E->isTypeDependent() &&
  10379. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10380. return ExprError();
  10381. }
  10382. if (!E->isTypeDependent() &&
  10383. !Context.hasSameType(VaListType, E->getType())) {
  10384. return ExprError(Diag(E->getLocStart(),
  10385. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10386. << OrigExpr->getType() << E->getSourceRange());
  10387. }
  10388. if (!TInfo->getType()->isDependentType()) {
  10389. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10390. diag::err_second_parameter_to_va_arg_incomplete,
  10391. TInfo->getTypeLoc()))
  10392. return ExprError();
  10393. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10394. TInfo->getType(),
  10395. diag::err_second_parameter_to_va_arg_abstract,
  10396. TInfo->getTypeLoc()))
  10397. return ExprError();
  10398. if (!TInfo->getType().isPODType(Context)) {
  10399. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10400. TInfo->getType()->isObjCLifetimeType()
  10401. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10402. : diag::warn_second_parameter_to_va_arg_not_pod)
  10403. << TInfo->getType()
  10404. << TInfo->getTypeLoc().getSourceRange();
  10405. }
  10406. // Check for va_arg where arguments of the given type will be promoted
  10407. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10408. QualType PromoteType;
  10409. if (TInfo->getType()->isPromotableIntegerType()) {
  10410. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10411. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10412. PromoteType = QualType();
  10413. }
  10414. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10415. PromoteType = Context.DoubleTy;
  10416. if (!PromoteType.isNull())
  10417. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10418. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10419. << TInfo->getType()
  10420. << PromoteType
  10421. << TInfo->getTypeLoc().getSourceRange());
  10422. }
  10423. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10424. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  10425. }
  10426. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10427. // The type of __null will be int or long, depending on the size of
  10428. // pointers on the target.
  10429. QualType Ty;
  10430. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10431. if (pw == Context.getTargetInfo().getIntWidth())
  10432. Ty = Context.IntTy;
  10433. else if (pw == Context.getTargetInfo().getLongWidth())
  10434. Ty = Context.LongTy;
  10435. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10436. Ty = Context.LongLongTy;
  10437. else {
  10438. llvm_unreachable("I don't know size of pointer!");
  10439. }
  10440. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10441. }
  10442. bool
  10443. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10444. if (!getLangOpts().ObjC1)
  10445. return false;
  10446. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10447. if (!PT)
  10448. return false;
  10449. if (!PT->isObjCIdType()) {
  10450. // Check if the destination is the 'NSString' interface.
  10451. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10452. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10453. return false;
  10454. }
  10455. // Ignore any parens, implicit casts (should only be
  10456. // array-to-pointer decays), and not-so-opaque values. The last is
  10457. // important for making this trigger for property assignments.
  10458. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10459. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10460. if (OV->getSourceExpr())
  10461. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10462. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10463. if (!SL || !SL->isAscii())
  10464. return false;
  10465. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10466. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10467. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10468. return true;
  10469. }
  10470. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10471. SourceLocation Loc,
  10472. QualType DstType, QualType SrcType,
  10473. Expr *SrcExpr, AssignmentAction Action,
  10474. bool *Complained) {
  10475. if (Complained)
  10476. *Complained = false;
  10477. // Decode the result (notice that AST's are still created for extensions).
  10478. bool CheckInferredResultType = false;
  10479. bool isInvalid = false;
  10480. unsigned DiagKind = 0;
  10481. FixItHint Hint;
  10482. ConversionFixItGenerator ConvHints;
  10483. bool MayHaveConvFixit = false;
  10484. bool MayHaveFunctionDiff = false;
  10485. const ObjCInterfaceDecl *IFace = nullptr;
  10486. const ObjCProtocolDecl *PDecl = nullptr;
  10487. switch (ConvTy) {
  10488. case Compatible:
  10489. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10490. return false;
  10491. case PointerToInt:
  10492. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10493. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10494. MayHaveConvFixit = true;
  10495. break;
  10496. case IntToPointer:
  10497. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10498. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10499. MayHaveConvFixit = true;
  10500. break;
  10501. case IncompatiblePointer:
  10502. DiagKind =
  10503. (Action == AA_Passing_CFAudited ?
  10504. diag::err_arc_typecheck_convert_incompatible_pointer :
  10505. diag::ext_typecheck_convert_incompatible_pointer);
  10506. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10507. SrcType->isObjCObjectPointerType();
  10508. if (Hint.isNull() && !CheckInferredResultType) {
  10509. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10510. }
  10511. else if (CheckInferredResultType) {
  10512. SrcType = SrcType.getUnqualifiedType();
  10513. DstType = DstType.getUnqualifiedType();
  10514. }
  10515. MayHaveConvFixit = true;
  10516. break;
  10517. case IncompatiblePointerSign:
  10518. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10519. break;
  10520. case FunctionVoidPointer:
  10521. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10522. break;
  10523. case IncompatiblePointerDiscardsQualifiers: {
  10524. // Perform array-to-pointer decay if necessary.
  10525. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10526. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10527. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10528. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10529. DiagKind = diag::err_typecheck_incompatible_address_space;
  10530. break;
  10531. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10532. DiagKind = diag::err_typecheck_incompatible_ownership;
  10533. break;
  10534. }
  10535. llvm_unreachable("unknown error case for discarding qualifiers!");
  10536. // fallthrough
  10537. }
  10538. case CompatiblePointerDiscardsQualifiers:
  10539. // If the qualifiers lost were because we were applying the
  10540. // (deprecated) C++ conversion from a string literal to a char*
  10541. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10542. // Ideally, this check would be performed in
  10543. // checkPointerTypesForAssignment. However, that would require a
  10544. // bit of refactoring (so that the second argument is an
  10545. // expression, rather than a type), which should be done as part
  10546. // of a larger effort to fix checkPointerTypesForAssignment for
  10547. // C++ semantics.
  10548. if (getLangOpts().CPlusPlus &&
  10549. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10550. return false;
  10551. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10552. break;
  10553. case IncompatibleNestedPointerQualifiers:
  10554. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10555. break;
  10556. case IntToBlockPointer:
  10557. DiagKind = diag::err_int_to_block_pointer;
  10558. break;
  10559. case IncompatibleBlockPointer:
  10560. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10561. break;
  10562. case IncompatibleObjCQualifiedId: {
  10563. if (SrcType->isObjCQualifiedIdType()) {
  10564. const ObjCObjectPointerType *srcOPT =
  10565. SrcType->getAs<ObjCObjectPointerType>();
  10566. for (auto *srcProto : srcOPT->quals()) {
  10567. PDecl = srcProto;
  10568. break;
  10569. }
  10570. if (const ObjCInterfaceType *IFaceT =
  10571. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10572. IFace = IFaceT->getDecl();
  10573. }
  10574. else if (DstType->isObjCQualifiedIdType()) {
  10575. const ObjCObjectPointerType *dstOPT =
  10576. DstType->getAs<ObjCObjectPointerType>();
  10577. for (auto *dstProto : dstOPT->quals()) {
  10578. PDecl = dstProto;
  10579. break;
  10580. }
  10581. if (const ObjCInterfaceType *IFaceT =
  10582. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10583. IFace = IFaceT->getDecl();
  10584. }
  10585. DiagKind = diag::warn_incompatible_qualified_id;
  10586. break;
  10587. }
  10588. case IncompatibleVectors:
  10589. DiagKind = diag::warn_incompatible_vectors;
  10590. break;
  10591. case IncompatibleObjCWeakRef:
  10592. DiagKind = diag::err_arc_weak_unavailable_assign;
  10593. break;
  10594. case Incompatible:
  10595. DiagKind = diag::err_typecheck_convert_incompatible;
  10596. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10597. MayHaveConvFixit = true;
  10598. isInvalid = true;
  10599. MayHaveFunctionDiff = true;
  10600. break;
  10601. }
  10602. QualType FirstType, SecondType;
  10603. switch (Action) {
  10604. case AA_Assigning:
  10605. case AA_Initializing:
  10606. // The destination type comes first.
  10607. FirstType = DstType;
  10608. SecondType = SrcType;
  10609. break;
  10610. case AA_Returning:
  10611. case AA_Passing:
  10612. case AA_Passing_CFAudited:
  10613. case AA_Converting:
  10614. case AA_Sending:
  10615. case AA_Casting:
  10616. // The source type comes first.
  10617. FirstType = SrcType;
  10618. SecondType = DstType;
  10619. break;
  10620. }
  10621. PartialDiagnostic FDiag = PDiag(DiagKind);
  10622. if (Action == AA_Passing_CFAudited)
  10623. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10624. else
  10625. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10626. // If we can fix the conversion, suggest the FixIts.
  10627. assert(ConvHints.isNull() || Hint.isNull());
  10628. if (!ConvHints.isNull()) {
  10629. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10630. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10631. FDiag << *HI;
  10632. } else {
  10633. FDiag << Hint;
  10634. }
  10635. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10636. if (MayHaveFunctionDiff)
  10637. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10638. Diag(Loc, FDiag);
  10639. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10640. PDecl && IFace && !IFace->hasDefinition())
  10641. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10642. << IFace->getName() << PDecl->getName();
  10643. if (SecondType == Context.OverloadTy)
  10644. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10645. FirstType);
  10646. if (CheckInferredResultType)
  10647. EmitRelatedResultTypeNote(SrcExpr);
  10648. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10649. EmitRelatedResultTypeNoteForReturn(DstType);
  10650. if (Complained)
  10651. *Complained = true;
  10652. return isInvalid;
  10653. }
  10654. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10655. llvm::APSInt *Result) {
  10656. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10657. public:
  10658. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10659. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10660. }
  10661. } Diagnoser;
  10662. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10663. }
  10664. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10665. llvm::APSInt *Result,
  10666. unsigned DiagID,
  10667. bool AllowFold) {
  10668. class IDDiagnoser : public VerifyICEDiagnoser {
  10669. unsigned DiagID;
  10670. public:
  10671. IDDiagnoser(unsigned DiagID)
  10672. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10673. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10674. S.Diag(Loc, DiagID) << SR;
  10675. }
  10676. } Diagnoser(DiagID);
  10677. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10678. }
  10679. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10680. SourceRange SR) {
  10681. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10682. }
  10683. ExprResult
  10684. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10685. VerifyICEDiagnoser &Diagnoser,
  10686. bool AllowFold) {
  10687. SourceLocation DiagLoc = E->getLocStart();
  10688. if (getLangOpts().CPlusPlus11) {
  10689. // C++11 [expr.const]p5:
  10690. // If an expression of literal class type is used in a context where an
  10691. // integral constant expression is required, then that class type shall
  10692. // have a single non-explicit conversion function to an integral or
  10693. // unscoped enumeration type
  10694. ExprResult Converted;
  10695. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10696. public:
  10697. CXX11ConvertDiagnoser(bool Silent)
  10698. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10699. Silent, true) {}
  10700. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10701. QualType T) override {
  10702. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10703. }
  10704. SemaDiagnosticBuilder diagnoseIncomplete(
  10705. Sema &S, SourceLocation Loc, QualType T) override {
  10706. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10707. }
  10708. SemaDiagnosticBuilder diagnoseExplicitConv(
  10709. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10710. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10711. }
  10712. SemaDiagnosticBuilder noteExplicitConv(
  10713. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10714. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10715. << ConvTy->isEnumeralType() << ConvTy;
  10716. }
  10717. SemaDiagnosticBuilder diagnoseAmbiguous(
  10718. Sema &S, SourceLocation Loc, QualType T) override {
  10719. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10720. }
  10721. SemaDiagnosticBuilder noteAmbiguous(
  10722. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10723. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10724. << ConvTy->isEnumeralType() << ConvTy;
  10725. }
  10726. SemaDiagnosticBuilder diagnoseConversion(
  10727. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10728. llvm_unreachable("conversion functions are permitted");
  10729. }
  10730. } ConvertDiagnoser(Diagnoser.Suppress);
  10731. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10732. ConvertDiagnoser);
  10733. if (Converted.isInvalid())
  10734. return Converted;
  10735. E = Converted.get();
  10736. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10737. return ExprError();
  10738. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10739. // An ICE must be of integral or unscoped enumeration type.
  10740. if (!Diagnoser.Suppress)
  10741. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10742. return ExprError();
  10743. }
  10744. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10745. // in the non-ICE case.
  10746. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10747. if (Result)
  10748. *Result = E->EvaluateKnownConstInt(Context);
  10749. return E;
  10750. }
  10751. Expr::EvalResult EvalResult;
  10752. SmallVector<PartialDiagnosticAt, 8> Notes;
  10753. EvalResult.Diag = &Notes;
  10754. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10755. // not a constant expression as a side-effect.
  10756. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10757. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10758. // In C++11, we can rely on diagnostics being produced for any expression
  10759. // which is not a constant expression. If no diagnostics were produced, then
  10760. // this is a constant expression.
  10761. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10762. if (Result)
  10763. *Result = EvalResult.Val.getInt();
  10764. return E;
  10765. }
  10766. // If our only note is the usual "invalid subexpression" note, just point
  10767. // the caret at its location rather than producing an essentially
  10768. // redundant note.
  10769. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10770. diag::note_invalid_subexpr_in_const_expr) {
  10771. DiagLoc = Notes[0].first;
  10772. Notes.clear();
  10773. }
  10774. if (!Folded || !AllowFold) {
  10775. if (!Diagnoser.Suppress) {
  10776. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10777. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10778. Diag(Notes[I].first, Notes[I].second);
  10779. }
  10780. return ExprError();
  10781. }
  10782. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10783. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10784. Diag(Notes[I].first, Notes[I].second);
  10785. if (Result)
  10786. *Result = EvalResult.Val.getInt();
  10787. return E;
  10788. }
  10789. namespace {
  10790. // Handle the case where we conclude a expression which we speculatively
  10791. // considered to be unevaluated is actually evaluated.
  10792. class TransformToPE : public TreeTransform<TransformToPE> {
  10793. typedef TreeTransform<TransformToPE> BaseTransform;
  10794. public:
  10795. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10796. // Make sure we redo semantic analysis
  10797. bool AlwaysRebuild() { return true; }
  10798. // Make sure we handle LabelStmts correctly.
  10799. // FIXME: This does the right thing, but maybe we need a more general
  10800. // fix to TreeTransform?
  10801. StmtResult TransformLabelStmt(LabelStmt *S) {
  10802. S->getDecl()->setStmt(nullptr);
  10803. return BaseTransform::TransformLabelStmt(S);
  10804. }
  10805. // We need to special-case DeclRefExprs referring to FieldDecls which
  10806. // are not part of a member pointer formation; normal TreeTransforming
  10807. // doesn't catch this case because of the way we represent them in the AST.
  10808. // FIXME: This is a bit ugly; is it really the best way to handle this
  10809. // case?
  10810. //
  10811. // Error on DeclRefExprs referring to FieldDecls.
  10812. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10813. if (isa<FieldDecl>(E->getDecl()) &&
  10814. !SemaRef.isUnevaluatedContext())
  10815. return SemaRef.Diag(E->getLocation(),
  10816. diag::err_invalid_non_static_member_use)
  10817. << E->getDecl() << E->getSourceRange();
  10818. return BaseTransform::TransformDeclRefExpr(E);
  10819. }
  10820. // Exception: filter out member pointer formation
  10821. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10822. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10823. return E;
  10824. return BaseTransform::TransformUnaryOperator(E);
  10825. }
  10826. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10827. // Lambdas never need to be transformed.
  10828. return E;
  10829. }
  10830. };
  10831. }
  10832. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10833. assert(isUnevaluatedContext() &&
  10834. "Should only transform unevaluated expressions");
  10835. ExprEvalContexts.back().Context =
  10836. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10837. if (isUnevaluatedContext())
  10838. return E;
  10839. return TransformToPE(*this).TransformExpr(E);
  10840. }
  10841. void
  10842. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10843. Decl *LambdaContextDecl,
  10844. bool IsDecltype) {
  10845. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10846. ExprNeedsCleanups, LambdaContextDecl,
  10847. IsDecltype);
  10848. ExprNeedsCleanups = false;
  10849. if (!MaybeODRUseExprs.empty())
  10850. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10851. }
  10852. void
  10853. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10854. ReuseLambdaContextDecl_t,
  10855. bool IsDecltype) {
  10856. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10857. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10858. }
  10859. void Sema::PopExpressionEvaluationContext() {
  10860. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10861. unsigned NumTypos = Rec.NumTypos;
  10862. if (!Rec.Lambdas.empty()) {
  10863. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10864. unsigned D;
  10865. if (Rec.isUnevaluated()) {
  10866. // C++11 [expr.prim.lambda]p2:
  10867. // A lambda-expression shall not appear in an unevaluated operand
  10868. // (Clause 5).
  10869. D = diag::err_lambda_unevaluated_operand;
  10870. } else {
  10871. // C++1y [expr.const]p2:
  10872. // A conditional-expression e is a core constant expression unless the
  10873. // evaluation of e, following the rules of the abstract machine, would
  10874. // evaluate [...] a lambda-expression.
  10875. D = diag::err_lambda_in_constant_expression;
  10876. }
  10877. for (const auto *L : Rec.Lambdas)
  10878. Diag(L->getLocStart(), D);
  10879. } else {
  10880. // Mark the capture expressions odr-used. This was deferred
  10881. // during lambda expression creation.
  10882. for (auto *Lambda : Rec.Lambdas) {
  10883. for (auto *C : Lambda->capture_inits())
  10884. MarkDeclarationsReferencedInExpr(C);
  10885. }
  10886. }
  10887. }
  10888. // When are coming out of an unevaluated context, clear out any
  10889. // temporaries that we may have created as part of the evaluation of
  10890. // the expression in that context: they aren't relevant because they
  10891. // will never be constructed.
  10892. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10893. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10894. ExprCleanupObjects.end());
  10895. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10896. CleanupVarDeclMarking();
  10897. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10898. // Otherwise, merge the contexts together.
  10899. } else {
  10900. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10901. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10902. Rec.SavedMaybeODRUseExprs.end());
  10903. }
  10904. // Pop the current expression evaluation context off the stack.
  10905. ExprEvalContexts.pop_back();
  10906. if (!ExprEvalContexts.empty())
  10907. ExprEvalContexts.back().NumTypos += NumTypos;
  10908. else
  10909. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10910. "last ExpressionEvaluationContextRecord");
  10911. }
  10912. void Sema::DiscardCleanupsInEvaluationContext() {
  10913. ExprCleanupObjects.erase(
  10914. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10915. ExprCleanupObjects.end());
  10916. ExprNeedsCleanups = false;
  10917. MaybeODRUseExprs.clear();
  10918. }
  10919. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10920. if (!E->getType()->isVariablyModifiedType())
  10921. return E;
  10922. return TransformToPotentiallyEvaluated(E);
  10923. }
  10924. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10925. // Do not mark anything as "used" within a dependent context; wait for
  10926. // an instantiation.
  10927. if (SemaRef.CurContext->isDependentContext())
  10928. return false;
  10929. switch (SemaRef.ExprEvalContexts.back().Context) {
  10930. case Sema::Unevaluated:
  10931. case Sema::UnevaluatedAbstract:
  10932. // We are in an expression that is not potentially evaluated; do nothing.
  10933. // (Depending on how you read the standard, we actually do need to do
  10934. // something here for null pointer constants, but the standard's
  10935. // definition of a null pointer constant is completely crazy.)
  10936. return false;
  10937. case Sema::ConstantEvaluated:
  10938. case Sema::PotentiallyEvaluated:
  10939. // We are in a potentially evaluated expression (or a constant-expression
  10940. // in C++03); we need to do implicit template instantiation, implicitly
  10941. // define class members, and mark most declarations as used.
  10942. return true;
  10943. case Sema::PotentiallyEvaluatedIfUsed:
  10944. // Referenced declarations will only be used if the construct in the
  10945. // containing expression is used.
  10946. return false;
  10947. }
  10948. llvm_unreachable("Invalid context");
  10949. }
  10950. /// \brief Mark a function referenced, and check whether it is odr-used
  10951. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10952. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10953. bool OdrUse) {
  10954. assert(Func && "No function?");
  10955. Func->setReferenced();
  10956. // C++11 [basic.def.odr]p3:
  10957. // A function whose name appears as a potentially-evaluated expression is
  10958. // odr-used if it is the unique lookup result or the selected member of a
  10959. // set of overloaded functions [...].
  10960. //
  10961. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10962. // can just check that here. Skip the rest of this function if we've already
  10963. // marked the function as used.
  10964. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10965. !IsPotentiallyEvaluatedContext(*this)) {
  10966. // C++11 [temp.inst]p3:
  10967. // Unless a function template specialization has been explicitly
  10968. // instantiated or explicitly specialized, the function template
  10969. // specialization is implicitly instantiated when the specialization is
  10970. // referenced in a context that requires a function definition to exist.
  10971. //
  10972. // We consider constexpr function templates to be referenced in a context
  10973. // that requires a definition to exist whenever they are referenced.
  10974. //
  10975. // FIXME: This instantiates constexpr functions too frequently. If this is
  10976. // really an unevaluated context (and we're not just in the definition of a
  10977. // function template or overload resolution or other cases which we
  10978. // incorrectly consider to be unevaluated contexts), and we're not in a
  10979. // subexpression which we actually need to evaluate (for instance, a
  10980. // template argument, array bound or an expression in a braced-init-list),
  10981. // we are not permitted to instantiate this constexpr function definition.
  10982. //
  10983. // FIXME: This also implicitly defines special members too frequently. They
  10984. // are only supposed to be implicitly defined if they are odr-used, but they
  10985. // are not odr-used from constant expressions in unevaluated contexts.
  10986. // However, they cannot be referenced if they are deleted, and they are
  10987. // deleted whenever the implicit definition of the special member would
  10988. // fail.
  10989. if (!Func->isConstexpr() || Func->getBody())
  10990. return;
  10991. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10992. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10993. return;
  10994. }
  10995. // Note that this declaration has been used.
  10996. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10997. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10998. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10999. if (Constructor->isDefaultConstructor()) {
  11000. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  11001. return;
  11002. DefineImplicitDefaultConstructor(Loc, Constructor);
  11003. } else if (Constructor->isCopyConstructor()) {
  11004. DefineImplicitCopyConstructor(Loc, Constructor);
  11005. } else if (Constructor->isMoveConstructor()) {
  11006. DefineImplicitMoveConstructor(Loc, Constructor);
  11007. }
  11008. } else if (Constructor->getInheritedConstructor()) {
  11009. DefineInheritingConstructor(Loc, Constructor);
  11010. }
  11011. } else if (CXXDestructorDecl *Destructor =
  11012. dyn_cast<CXXDestructorDecl>(Func)) {
  11013. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  11014. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  11015. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  11016. return;
  11017. DefineImplicitDestructor(Loc, Destructor);
  11018. }
  11019. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  11020. MarkVTableUsed(Loc, Destructor->getParent());
  11021. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  11022. if (MethodDecl->isOverloadedOperator() &&
  11023. MethodDecl->getOverloadedOperator() == OO_Equal) {
  11024. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  11025. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  11026. if (MethodDecl->isCopyAssignmentOperator())
  11027. DefineImplicitCopyAssignment(Loc, MethodDecl);
  11028. else
  11029. DefineImplicitMoveAssignment(Loc, MethodDecl);
  11030. }
  11031. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  11032. MethodDecl->getParent()->isLambda()) {
  11033. CXXConversionDecl *Conversion =
  11034. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  11035. if (Conversion->isLambdaToBlockPointerConversion())
  11036. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  11037. else
  11038. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  11039. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  11040. MarkVTableUsed(Loc, MethodDecl->getParent());
  11041. }
  11042. // Recursive functions should be marked when used from another function.
  11043. // FIXME: Is this really right?
  11044. if (CurContext == Func) return;
  11045. // Resolve the exception specification for any function which is
  11046. // used: CodeGen will need it.
  11047. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  11048. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  11049. ResolveExceptionSpec(Loc, FPT);
  11050. if (!OdrUse) return;
  11051. // Implicit instantiation of function templates and member functions of
  11052. // class templates.
  11053. if (Func->isImplicitlyInstantiable()) {
  11054. bool AlreadyInstantiated = false;
  11055. SourceLocation PointOfInstantiation = Loc;
  11056. if (FunctionTemplateSpecializationInfo *SpecInfo
  11057. = Func->getTemplateSpecializationInfo()) {
  11058. if (SpecInfo->getPointOfInstantiation().isInvalid())
  11059. SpecInfo->setPointOfInstantiation(Loc);
  11060. else if (SpecInfo->getTemplateSpecializationKind()
  11061. == TSK_ImplicitInstantiation) {
  11062. AlreadyInstantiated = true;
  11063. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  11064. }
  11065. } else if (MemberSpecializationInfo *MSInfo
  11066. = Func->getMemberSpecializationInfo()) {
  11067. if (MSInfo->getPointOfInstantiation().isInvalid())
  11068. MSInfo->setPointOfInstantiation(Loc);
  11069. else if (MSInfo->getTemplateSpecializationKind()
  11070. == TSK_ImplicitInstantiation) {
  11071. AlreadyInstantiated = true;
  11072. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  11073. }
  11074. }
  11075. if (!AlreadyInstantiated || Func->isConstexpr()) {
  11076. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  11077. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  11078. ActiveTemplateInstantiations.size())
  11079. PendingLocalImplicitInstantiations.push_back(
  11080. std::make_pair(Func, PointOfInstantiation));
  11081. else if (Func->isConstexpr())
  11082. // Do not defer instantiations of constexpr functions, to avoid the
  11083. // expression evaluator needing to call back into Sema if it sees a
  11084. // call to such a function.
  11085. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  11086. else {
  11087. PendingInstantiations.push_back(std::make_pair(Func,
  11088. PointOfInstantiation));
  11089. // Notify the consumer that a function was implicitly instantiated.
  11090. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  11091. }
  11092. }
  11093. } else {
  11094. // Walk redefinitions, as some of them may be instantiable.
  11095. for (auto i : Func->redecls()) {
  11096. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  11097. MarkFunctionReferenced(Loc, i);
  11098. }
  11099. }
  11100. // Keep track of used but undefined functions.
  11101. if (!Func->isDefined()) {
  11102. if (mightHaveNonExternalLinkage(Func))
  11103. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11104. else if (Func->getMostRecentDecl()->isInlined() &&
  11105. !LangOpts.GNUInline &&
  11106. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  11107. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11108. }
  11109. // Normally the most current decl is marked used while processing the use and
  11110. // any subsequent decls are marked used by decl merging. This fails with
  11111. // template instantiation since marking can happen at the end of the file
  11112. // and, because of the two phase lookup, this function is called with at
  11113. // decl in the middle of a decl chain. We loop to maintain the invariant
  11114. // that once a decl is used, all decls after it are also used.
  11115. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  11116. F->markUsed(Context);
  11117. if (F == Func)
  11118. break;
  11119. }
  11120. }
  11121. static void
  11122. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  11123. VarDecl *var, DeclContext *DC) {
  11124. DeclContext *VarDC = var->getDeclContext();
  11125. // If the parameter still belongs to the translation unit, then
  11126. // we're actually just using one parameter in the declaration of
  11127. // the next.
  11128. if (isa<ParmVarDecl>(var) &&
  11129. isa<TranslationUnitDecl>(VarDC))
  11130. return;
  11131. // For C code, don't diagnose about capture if we're not actually in code
  11132. // right now; it's impossible to write a non-constant expression outside of
  11133. // function context, so we'll get other (more useful) diagnostics later.
  11134. //
  11135. // For C++, things get a bit more nasty... it would be nice to suppress this
  11136. // diagnostic for certain cases like using a local variable in an array bound
  11137. // for a member of a local class, but the correct predicate is not obvious.
  11138. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  11139. return;
  11140. if (isa<CXXMethodDecl>(VarDC) &&
  11141. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  11142. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  11143. << var->getIdentifier();
  11144. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  11145. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  11146. << var->getIdentifier() << fn->getDeclName();
  11147. } else if (isa<BlockDecl>(VarDC)) {
  11148. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  11149. << var->getIdentifier();
  11150. } else {
  11151. // FIXME: Is there any other context where a local variable can be
  11152. // declared?
  11153. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  11154. << var->getIdentifier();
  11155. }
  11156. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  11157. << var->getIdentifier();
  11158. // FIXME: Add additional diagnostic info about class etc. which prevents
  11159. // capture.
  11160. }
  11161. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  11162. bool &SubCapturesAreNested,
  11163. QualType &CaptureType,
  11164. QualType &DeclRefType) {
  11165. // Check whether we've already captured it.
  11166. if (CSI->CaptureMap.count(Var)) {
  11167. // If we found a capture, any subcaptures are nested.
  11168. SubCapturesAreNested = true;
  11169. // Retrieve the capture type for this variable.
  11170. CaptureType = CSI->getCapture(Var).getCaptureType();
  11171. // Compute the type of an expression that refers to this variable.
  11172. DeclRefType = CaptureType.getNonReferenceType();
  11173. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  11174. if (Cap.isCopyCapture() &&
  11175. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  11176. DeclRefType.addConst();
  11177. return true;
  11178. }
  11179. return false;
  11180. }
  11181. // Only block literals, captured statements, and lambda expressions can
  11182. // capture; other scopes don't work.
  11183. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  11184. SourceLocation Loc,
  11185. const bool Diagnose, Sema &S) {
  11186. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  11187. return getLambdaAwareParentOfDeclContext(DC);
  11188. else if (Var->hasLocalStorage()) {
  11189. if (Diagnose)
  11190. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  11191. }
  11192. return nullptr;
  11193. }
  11194. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11195. // certain types of variables (unnamed, variably modified types etc.)
  11196. // so check for eligibility.
  11197. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  11198. SourceLocation Loc,
  11199. const bool Diagnose, Sema &S) {
  11200. bool IsBlock = isa<BlockScopeInfo>(CSI);
  11201. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  11202. // Lambdas are not allowed to capture unnamed variables
  11203. // (e.g. anonymous unions).
  11204. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  11205. // assuming that's the intent.
  11206. if (IsLambda && !Var->getDeclName()) {
  11207. if (Diagnose) {
  11208. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  11209. S.Diag(Var->getLocation(), diag::note_declared_at);
  11210. }
  11211. return false;
  11212. }
  11213. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  11214. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  11215. if (Diagnose) {
  11216. S.Diag(Loc, diag::err_ref_vm_type);
  11217. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11218. << Var->getDeclName();
  11219. }
  11220. return false;
  11221. }
  11222. // Prohibit structs with flexible array members too.
  11223. // We cannot capture what is in the tail end of the struct.
  11224. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  11225. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  11226. if (Diagnose) {
  11227. if (IsBlock)
  11228. S.Diag(Loc, diag::err_ref_flexarray_type);
  11229. else
  11230. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  11231. << Var->getDeclName();
  11232. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11233. << Var->getDeclName();
  11234. }
  11235. return false;
  11236. }
  11237. }
  11238. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11239. // Lambdas and captured statements are not allowed to capture __block
  11240. // variables; they don't support the expected semantics.
  11241. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  11242. if (Diagnose) {
  11243. S.Diag(Loc, diag::err_capture_block_variable)
  11244. << Var->getDeclName() << !IsLambda;
  11245. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11246. << Var->getDeclName();
  11247. }
  11248. return false;
  11249. }
  11250. return true;
  11251. }
  11252. // Returns true if the capture by block was successful.
  11253. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  11254. SourceLocation Loc,
  11255. const bool BuildAndDiagnose,
  11256. QualType &CaptureType,
  11257. QualType &DeclRefType,
  11258. const bool Nested,
  11259. Sema &S) {
  11260. Expr *CopyExpr = nullptr;
  11261. bool ByRef = false;
  11262. // Blocks are not allowed to capture arrays.
  11263. if (CaptureType->isArrayType()) {
  11264. if (BuildAndDiagnose) {
  11265. S.Diag(Loc, diag::err_ref_array_type);
  11266. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11267. << Var->getDeclName();
  11268. }
  11269. return false;
  11270. }
  11271. // Forbid the block-capture of autoreleasing variables.
  11272. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11273. if (BuildAndDiagnose) {
  11274. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11275. << /*block*/ 0;
  11276. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11277. << Var->getDeclName();
  11278. }
  11279. return false;
  11280. }
  11281. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11282. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11283. // Block capture by reference does not change the capture or
  11284. // declaration reference types.
  11285. ByRef = true;
  11286. } else {
  11287. // Block capture by copy introduces 'const'.
  11288. CaptureType = CaptureType.getNonReferenceType().withConst();
  11289. DeclRefType = CaptureType;
  11290. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11291. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11292. // The capture logic needs the destructor, so make sure we mark it.
  11293. // Usually this is unnecessary because most local variables have
  11294. // their destructors marked at declaration time, but parameters are
  11295. // an exception because it's technically only the call site that
  11296. // actually requires the destructor.
  11297. if (isa<ParmVarDecl>(Var))
  11298. S.FinalizeVarWithDestructor(Var, Record);
  11299. // Enter a new evaluation context to insulate the copy
  11300. // full-expression.
  11301. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11302. // According to the blocks spec, the capture of a variable from
  11303. // the stack requires a const copy constructor. This is not true
  11304. // of the copy/move done to move a __block variable to the heap.
  11305. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11306. DeclRefType.withConst(),
  11307. VK_LValue, Loc);
  11308. ExprResult Result
  11309. = S.PerformCopyInitialization(
  11310. InitializedEntity::InitializeBlock(Var->getLocation(),
  11311. CaptureType, false),
  11312. Loc, DeclRef);
  11313. // Build a full-expression copy expression if initialization
  11314. // succeeded and used a non-trivial constructor. Recover from
  11315. // errors by pretending that the copy isn't necessary.
  11316. if (!Result.isInvalid() &&
  11317. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11318. ->isTrivial()) {
  11319. Result = S.MaybeCreateExprWithCleanups(Result);
  11320. CopyExpr = Result.get();
  11321. }
  11322. }
  11323. }
  11324. }
  11325. // Actually capture the variable.
  11326. if (BuildAndDiagnose)
  11327. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11328. SourceLocation(), CaptureType, CopyExpr);
  11329. return true;
  11330. }
  11331. /// \brief Capture the given variable in the captured region.
  11332. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11333. VarDecl *Var,
  11334. SourceLocation Loc,
  11335. const bool BuildAndDiagnose,
  11336. QualType &CaptureType,
  11337. QualType &DeclRefType,
  11338. const bool RefersToCapturedVariable,
  11339. Sema &S) {
  11340. // By default, capture variables by reference.
  11341. bool ByRef = true;
  11342. // Using an LValue reference type is consistent with Lambdas (see below).
  11343. if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
  11344. DeclRefType = DeclRefType.getUnqualifiedType();
  11345. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11346. Expr *CopyExpr = nullptr;
  11347. if (BuildAndDiagnose) {
  11348. // The current implementation assumes that all variables are captured
  11349. // by references. Since there is no capture by copy, no expression
  11350. // evaluation will be needed.
  11351. RecordDecl *RD = RSI->TheRecordDecl;
  11352. FieldDecl *Field
  11353. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11354. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11355. nullptr, false, ICIS_NoInit);
  11356. Field->setImplicit(true);
  11357. Field->setAccess(AS_private);
  11358. RD->addDecl(Field);
  11359. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11360. DeclRefType, VK_LValue, Loc);
  11361. Var->setReferenced(true);
  11362. Var->markUsed(S.Context);
  11363. }
  11364. // Actually capture the variable.
  11365. if (BuildAndDiagnose)
  11366. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11367. SourceLocation(), CaptureType, CopyExpr);
  11368. return true;
  11369. }
  11370. /// \brief Create a field within the lambda class for the variable
  11371. /// being captured.
  11372. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11373. QualType FieldType, QualType DeclRefType,
  11374. SourceLocation Loc,
  11375. bool RefersToCapturedVariable) {
  11376. CXXRecordDecl *Lambda = LSI->Lambda;
  11377. // Build the non-static data member.
  11378. FieldDecl *Field
  11379. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11380. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11381. nullptr, false, ICIS_NoInit);
  11382. Field->setImplicit(true);
  11383. Field->setAccess(AS_private);
  11384. Lambda->addDecl(Field);
  11385. }
  11386. /// \brief Capture the given variable in the lambda.
  11387. static bool captureInLambda(LambdaScopeInfo *LSI,
  11388. VarDecl *Var,
  11389. SourceLocation Loc,
  11390. const bool BuildAndDiagnose,
  11391. QualType &CaptureType,
  11392. QualType &DeclRefType,
  11393. const bool RefersToCapturedVariable,
  11394. const Sema::TryCaptureKind Kind,
  11395. SourceLocation EllipsisLoc,
  11396. const bool IsTopScope,
  11397. Sema &S) {
  11398. // Determine whether we are capturing by reference or by value.
  11399. bool ByRef = false;
  11400. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11401. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11402. } else {
  11403. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11404. }
  11405. // Compute the type of the field that will capture this variable.
  11406. if (ByRef) {
  11407. // C++11 [expr.prim.lambda]p15:
  11408. // An entity is captured by reference if it is implicitly or
  11409. // explicitly captured but not captured by copy. It is
  11410. // unspecified whether additional unnamed non-static data
  11411. // members are declared in the closure type for entities
  11412. // captured by reference.
  11413. //
  11414. // FIXME: It is not clear whether we want to build an lvalue reference
  11415. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11416. // to do the former, while EDG does the latter. Core issue 1249 will
  11417. // clarify, but for now we follow GCC because it's a more permissive and
  11418. // easily defensible position.
  11419. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11420. } else {
  11421. // C++11 [expr.prim.lambda]p14:
  11422. // For each entity captured by copy, an unnamed non-static
  11423. // data member is declared in the closure type. The
  11424. // declaration order of these members is unspecified. The type
  11425. // of such a data member is the type of the corresponding
  11426. // captured entity if the entity is not a reference to an
  11427. // object, or the referenced type otherwise. [Note: If the
  11428. // captured entity is a reference to a function, the
  11429. // corresponding data member is also a reference to a
  11430. // function. - end note ]
  11431. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11432. if (!RefType->getPointeeType()->isFunctionType())
  11433. CaptureType = RefType->getPointeeType();
  11434. }
  11435. // Forbid the lambda copy-capture of autoreleasing variables.
  11436. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11437. if (BuildAndDiagnose) {
  11438. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11439. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11440. << Var->getDeclName();
  11441. }
  11442. return false;
  11443. }
  11444. // Make sure that by-copy captures are of a complete and non-abstract type.
  11445. if (BuildAndDiagnose) {
  11446. if (!CaptureType->isDependentType() &&
  11447. S.RequireCompleteType(Loc, CaptureType,
  11448. diag::err_capture_of_incomplete_type,
  11449. Var->getDeclName()))
  11450. return false;
  11451. if (S.RequireNonAbstractType(Loc, CaptureType,
  11452. diag::err_capture_of_abstract_type))
  11453. return false;
  11454. }
  11455. }
  11456. // Capture this variable in the lambda.
  11457. if (BuildAndDiagnose)
  11458. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11459. RefersToCapturedVariable);
  11460. // Compute the type of a reference to this captured variable.
  11461. if (ByRef)
  11462. DeclRefType = CaptureType.getNonReferenceType();
  11463. else {
  11464. // C++ [expr.prim.lambda]p5:
  11465. // The closure type for a lambda-expression has a public inline
  11466. // function call operator [...]. This function call operator is
  11467. // declared const (9.3.1) if and only if the lambda-expression’s
  11468. // parameter-declaration-clause is not followed by mutable.
  11469. DeclRefType = CaptureType.getNonReferenceType();
  11470. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11471. DeclRefType.addConst();
  11472. }
  11473. // Add the capture.
  11474. if (BuildAndDiagnose)
  11475. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11476. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11477. return true;
  11478. }
  11479. bool Sema::tryCaptureVariable(
  11480. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11481. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11482. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11483. // An init-capture is notionally from the context surrounding its
  11484. // declaration, but its parent DC is the lambda class.
  11485. DeclContext *VarDC = Var->getDeclContext();
  11486. if (Var->isInitCapture())
  11487. VarDC = VarDC->getParent();
  11488. DeclContext *DC = CurContext;
  11489. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11490. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11491. // We need to sync up the Declaration Context with the
  11492. // FunctionScopeIndexToStopAt
  11493. if (FunctionScopeIndexToStopAt) {
  11494. unsigned FSIndex = FunctionScopes.size() - 1;
  11495. while (FSIndex != MaxFunctionScopesIndex) {
  11496. DC = getLambdaAwareParentOfDeclContext(DC);
  11497. --FSIndex;
  11498. }
  11499. }
  11500. // If the variable is declared in the current context, there is no need to
  11501. // capture it.
  11502. if (VarDC == DC) return true;
  11503. // Capture global variables if it is required to use private copy of this
  11504. // variable.
  11505. bool IsGlobal = !Var->hasLocalStorage();
  11506. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11507. return true;
  11508. // Walk up the stack to determine whether we can capture the variable,
  11509. // performing the "simple" checks that don't depend on type. We stop when
  11510. // we've either hit the declared scope of the variable or find an existing
  11511. // capture of that variable. We start from the innermost capturing-entity
  11512. // (the DC) and ensure that all intervening capturing-entities
  11513. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11514. // declcontext can either capture the variable or have already captured
  11515. // the variable.
  11516. CaptureType = Var->getType();
  11517. DeclRefType = CaptureType.getNonReferenceType();
  11518. bool Nested = false;
  11519. bool Explicit = (Kind != TryCapture_Implicit);
  11520. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11521. unsigned OpenMPLevel = 0;
  11522. do {
  11523. // Only block literals, captured statements, and lambda expressions can
  11524. // capture; other scopes don't work.
  11525. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11526. ExprLoc,
  11527. BuildAndDiagnose,
  11528. *this);
  11529. // We need to check for the parent *first* because, if we *have*
  11530. // private-captured a global variable, we need to recursively capture it in
  11531. // intermediate blocks, lambdas, etc.
  11532. if (!ParentDC) {
  11533. if (IsGlobal) {
  11534. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11535. break;
  11536. }
  11537. return true;
  11538. }
  11539. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11540. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11541. // Check whether we've already captured it.
  11542. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11543. DeclRefType))
  11544. break;
  11545. if (getLangOpts().OpenMP) {
  11546. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11547. // OpenMP private variables should not be captured in outer scope, so
  11548. // just break here.
  11549. if (RSI->CapRegionKind == CR_OpenMP) {
  11550. if (isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11551. Nested = true;
  11552. DeclRefType = DeclRefType.getUnqualifiedType();
  11553. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11554. break;
  11555. }
  11556. ++OpenMPLevel;
  11557. }
  11558. }
  11559. }
  11560. // If we are instantiating a generic lambda call operator body,
  11561. // we do not want to capture new variables. What was captured
  11562. // during either a lambdas transformation or initial parsing
  11563. // should be used.
  11564. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11565. if (BuildAndDiagnose) {
  11566. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11567. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11568. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11569. Diag(Var->getLocation(), diag::note_previous_decl)
  11570. << Var->getDeclName();
  11571. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11572. } else
  11573. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11574. }
  11575. return true;
  11576. }
  11577. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11578. // certain types of variables (unnamed, variably modified types etc.)
  11579. // so check for eligibility.
  11580. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11581. return true;
  11582. // Try to capture variable-length arrays types.
  11583. if (Var->getType()->isVariablyModifiedType()) {
  11584. // We're going to walk down into the type and look for VLA
  11585. // expressions.
  11586. QualType QTy = Var->getType();
  11587. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11588. QTy = PVD->getOriginalType();
  11589. do {
  11590. const Type *Ty = QTy.getTypePtr();
  11591. switch (Ty->getTypeClass()) {
  11592. #define TYPE(Class, Base)
  11593. #define ABSTRACT_TYPE(Class, Base)
  11594. #define NON_CANONICAL_TYPE(Class, Base)
  11595. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11596. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11597. #include "clang/AST/TypeNodes.def"
  11598. QTy = QualType();
  11599. break;
  11600. // These types are never variably-modified.
  11601. case Type::Builtin:
  11602. case Type::Complex:
  11603. case Type::Vector:
  11604. case Type::ExtVector:
  11605. case Type::Record:
  11606. case Type::Enum:
  11607. case Type::Elaborated:
  11608. case Type::TemplateSpecialization:
  11609. case Type::ObjCObject:
  11610. case Type::ObjCInterface:
  11611. case Type::ObjCObjectPointer:
  11612. llvm_unreachable("type class is never variably-modified!");
  11613. case Type::Adjusted:
  11614. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11615. break;
  11616. case Type::Decayed:
  11617. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11618. break;
  11619. case Type::Pointer:
  11620. QTy = cast<PointerType>(Ty)->getPointeeType();
  11621. break;
  11622. case Type::BlockPointer:
  11623. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11624. break;
  11625. case Type::LValueReference:
  11626. case Type::RValueReference:
  11627. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11628. break;
  11629. case Type::MemberPointer:
  11630. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11631. break;
  11632. case Type::ConstantArray:
  11633. case Type::IncompleteArray:
  11634. // Losing element qualification here is fine.
  11635. QTy = cast<ArrayType>(Ty)->getElementType();
  11636. break;
  11637. case Type::VariableArray: {
  11638. // Losing element qualification here is fine.
  11639. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11640. // Unknown size indication requires no size computation.
  11641. // Otherwise, evaluate and record it.
  11642. if (auto Size = VAT->getSizeExpr()) {
  11643. if (!CSI->isVLATypeCaptured(VAT)) {
  11644. RecordDecl *CapRecord = nullptr;
  11645. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11646. CapRecord = LSI->Lambda;
  11647. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11648. CapRecord = CRSI->TheRecordDecl;
  11649. }
  11650. if (CapRecord) {
  11651. auto ExprLoc = Size->getExprLoc();
  11652. auto SizeType = Context.getSizeType();
  11653. // Build the non-static data member.
  11654. auto Field = FieldDecl::Create(
  11655. Context, CapRecord, ExprLoc, ExprLoc,
  11656. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11657. /*BW*/ nullptr, /*Mutable*/ false,
  11658. /*InitStyle*/ ICIS_NoInit);
  11659. Field->setImplicit(true);
  11660. Field->setAccess(AS_private);
  11661. Field->setCapturedVLAType(VAT);
  11662. CapRecord->addDecl(Field);
  11663. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11664. }
  11665. }
  11666. }
  11667. QTy = VAT->getElementType();
  11668. break;
  11669. }
  11670. case Type::FunctionProto:
  11671. case Type::FunctionNoProto:
  11672. QTy = cast<FunctionType>(Ty)->getReturnType();
  11673. break;
  11674. case Type::Paren:
  11675. case Type::TypeOf:
  11676. case Type::UnaryTransform:
  11677. case Type::Attributed:
  11678. case Type::SubstTemplateTypeParm:
  11679. case Type::PackExpansion:
  11680. // Keep walking after single level desugaring.
  11681. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11682. break;
  11683. case Type::Typedef:
  11684. QTy = cast<TypedefType>(Ty)->desugar();
  11685. break;
  11686. case Type::Decltype:
  11687. QTy = cast<DecltypeType>(Ty)->desugar();
  11688. break;
  11689. case Type::Auto:
  11690. QTy = cast<AutoType>(Ty)->getDeducedType();
  11691. break;
  11692. case Type::TypeOfExpr:
  11693. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11694. break;
  11695. case Type::Atomic:
  11696. QTy = cast<AtomicType>(Ty)->getValueType();
  11697. break;
  11698. }
  11699. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11700. }
  11701. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11702. // No capture-default, and this is not an explicit capture
  11703. // so cannot capture this variable.
  11704. if (BuildAndDiagnose) {
  11705. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11706. Diag(Var->getLocation(), diag::note_previous_decl)
  11707. << Var->getDeclName();
  11708. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11709. diag::note_lambda_decl);
  11710. // FIXME: If we error out because an outer lambda can not implicitly
  11711. // capture a variable that an inner lambda explicitly captures, we
  11712. // should have the inner lambda do the explicit capture - because
  11713. // it makes for cleaner diagnostics later. This would purely be done
  11714. // so that the diagnostic does not misleadingly claim that a variable
  11715. // can not be captured by a lambda implicitly even though it is captured
  11716. // explicitly. Suggestion:
  11717. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11718. // at the function head
  11719. // - cache the StartingDeclContext - this must be a lambda
  11720. // - captureInLambda in the innermost lambda the variable.
  11721. }
  11722. return true;
  11723. }
  11724. FunctionScopesIndex--;
  11725. DC = ParentDC;
  11726. Explicit = false;
  11727. } while (!VarDC->Equals(DC));
  11728. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11729. // computing the type of the capture at each step, checking type-specific
  11730. // requirements, and adding captures if requested.
  11731. // If the variable had already been captured previously, we start capturing
  11732. // at the lambda nested within that one.
  11733. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11734. ++I) {
  11735. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11736. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11737. if (!captureInBlock(BSI, Var, ExprLoc,
  11738. BuildAndDiagnose, CaptureType,
  11739. DeclRefType, Nested, *this))
  11740. return true;
  11741. Nested = true;
  11742. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11743. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11744. BuildAndDiagnose, CaptureType,
  11745. DeclRefType, Nested, *this))
  11746. return true;
  11747. Nested = true;
  11748. } else {
  11749. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11750. if (!captureInLambda(LSI, Var, ExprLoc,
  11751. BuildAndDiagnose, CaptureType,
  11752. DeclRefType, Nested, Kind, EllipsisLoc,
  11753. /*IsTopScope*/I == N - 1, *this))
  11754. return true;
  11755. Nested = true;
  11756. }
  11757. }
  11758. return false;
  11759. }
  11760. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11761. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11762. QualType CaptureType;
  11763. QualType DeclRefType;
  11764. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11765. /*BuildAndDiagnose=*/true, CaptureType,
  11766. DeclRefType, nullptr);
  11767. }
  11768. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11769. QualType CaptureType;
  11770. QualType DeclRefType;
  11771. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11772. /*BuildAndDiagnose=*/false, CaptureType,
  11773. DeclRefType, nullptr);
  11774. }
  11775. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11776. QualType CaptureType;
  11777. QualType DeclRefType;
  11778. // Determine whether we can capture this variable.
  11779. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11780. /*BuildAndDiagnose=*/false, CaptureType,
  11781. DeclRefType, nullptr))
  11782. return QualType();
  11783. return DeclRefType;
  11784. }
  11785. // If either the type of the variable or the initializer is dependent,
  11786. // return false. Otherwise, determine whether the variable is a constant
  11787. // expression. Use this if you need to know if a variable that might or
  11788. // might not be dependent is truly a constant expression.
  11789. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11790. ASTContext &Context) {
  11791. if (Var->getType()->isDependentType())
  11792. return false;
  11793. const VarDecl *DefVD = nullptr;
  11794. Var->getAnyInitializer(DefVD);
  11795. if (!DefVD)
  11796. return false;
  11797. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11798. Expr *Init = cast<Expr>(Eval->Value);
  11799. if (Init->isValueDependent())
  11800. return false;
  11801. return IsVariableAConstantExpression(Var, Context);
  11802. }
  11803. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11804. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11805. // an object that satisfies the requirements for appearing in a
  11806. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11807. // is immediately applied." This function handles the lvalue-to-rvalue
  11808. // conversion part.
  11809. MaybeODRUseExprs.erase(E->IgnoreParens());
  11810. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11811. // to a variable that is a constant expression, and if so, identify it as
  11812. // a reference to a variable that does not involve an odr-use of that
  11813. // variable.
  11814. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11815. Expr *SansParensExpr = E->IgnoreParens();
  11816. VarDecl *Var = nullptr;
  11817. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11818. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11819. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11820. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11821. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11822. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11823. }
  11824. }
  11825. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11826. Res = CorrectDelayedTyposInExpr(Res);
  11827. if (!Res.isUsable())
  11828. return Res;
  11829. // If a constant-expression is a reference to a variable where we delay
  11830. // deciding whether it is an odr-use, just assume we will apply the
  11831. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11832. // (a non-type template argument), we have special handling anyway.
  11833. UpdateMarkingForLValueToRValue(Res.get());
  11834. return Res;
  11835. }
  11836. void Sema::CleanupVarDeclMarking() {
  11837. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11838. e = MaybeODRUseExprs.end();
  11839. i != e; ++i) {
  11840. VarDecl *Var;
  11841. SourceLocation Loc;
  11842. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11843. Var = cast<VarDecl>(DRE->getDecl());
  11844. Loc = DRE->getLocation();
  11845. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11846. Var = cast<VarDecl>(ME->getMemberDecl());
  11847. Loc = ME->getMemberLoc();
  11848. } else {
  11849. llvm_unreachable("Unexpected expression");
  11850. }
  11851. MarkVarDeclODRUsed(Var, Loc, *this,
  11852. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11853. }
  11854. MaybeODRUseExprs.clear();
  11855. }
  11856. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11857. VarDecl *Var, Expr *E) {
  11858. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11859. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11860. Var->setReferenced();
  11861. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11862. bool MarkODRUsed = true;
  11863. // If the context is not potentially evaluated, this is not an odr-use and
  11864. // does not trigger instantiation.
  11865. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11866. if (SemaRef.isUnevaluatedContext())
  11867. return;
  11868. // If we don't yet know whether this context is going to end up being an
  11869. // evaluated context, and we're referencing a variable from an enclosing
  11870. // scope, add a potential capture.
  11871. //
  11872. // FIXME: Is this necessary? These contexts are only used for default
  11873. // arguments, where local variables can't be used.
  11874. const bool RefersToEnclosingScope =
  11875. (SemaRef.CurContext != Var->getDeclContext() &&
  11876. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11877. if (RefersToEnclosingScope) {
  11878. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11879. // If a variable could potentially be odr-used, defer marking it so
  11880. // until we finish analyzing the full expression for any
  11881. // lvalue-to-rvalue
  11882. // or discarded value conversions that would obviate odr-use.
  11883. // Add it to the list of potential captures that will be analyzed
  11884. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11885. // unless the variable is a reference that was initialized by a constant
  11886. // expression (this will never need to be captured or odr-used).
  11887. assert(E && "Capture variable should be used in an expression.");
  11888. if (!Var->getType()->isReferenceType() ||
  11889. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11890. LSI->addPotentialCapture(E->IgnoreParens());
  11891. }
  11892. }
  11893. if (!isTemplateInstantiation(TSK))
  11894. return;
  11895. // Instantiate, but do not mark as odr-used, variable templates.
  11896. MarkODRUsed = false;
  11897. }
  11898. VarTemplateSpecializationDecl *VarSpec =
  11899. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11900. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11901. "Can't instantiate a partial template specialization.");
  11902. // Perform implicit instantiation of static data members, static data member
  11903. // templates of class templates, and variable template specializations. Delay
  11904. // instantiations of variable templates, except for those that could be used
  11905. // in a constant expression.
  11906. if (isTemplateInstantiation(TSK)) {
  11907. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11908. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11909. if (Var->getPointOfInstantiation().isInvalid()) {
  11910. // This is a modification of an existing AST node. Notify listeners.
  11911. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11912. L->StaticDataMemberInstantiated(Var);
  11913. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11914. // Don't bother trying to instantiate it again, unless we might need
  11915. // its initializer before we get to the end of the TU.
  11916. TryInstantiating = false;
  11917. }
  11918. if (Var->getPointOfInstantiation().isInvalid())
  11919. Var->setTemplateSpecializationKind(TSK, Loc);
  11920. if (TryInstantiating) {
  11921. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11922. bool InstantiationDependent = false;
  11923. bool IsNonDependent =
  11924. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11925. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11926. : true;
  11927. // Do not instantiate specializations that are still type-dependent.
  11928. if (IsNonDependent) {
  11929. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11930. // Do not defer instantiations of variables which could be used in a
  11931. // constant expression.
  11932. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11933. } else {
  11934. SemaRef.PendingInstantiations
  11935. .push_back(std::make_pair(Var, PointOfInstantiation));
  11936. }
  11937. }
  11938. }
  11939. }
  11940. if(!MarkODRUsed) return;
  11941. // HLSL Change Begin -External variable is in cbuffer, cannot use as immediate.
  11942. // Mark used for referenced external variable.
  11943. if (SemaRef.getLangOpts().HLSL && Var->hasExternalFormalLinkage() &&
  11944. !isa<EnumConstantDecl>(Var))
  11945. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11946. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11947. // HLSL Change End.
  11948. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11949. // the requirements for appearing in a constant expression (5.19) and, if
  11950. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11951. // is immediately applied." We check the first part here, and
  11952. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11953. // Note that we use the C++11 definition everywhere because nothing in
  11954. // C++03 depends on whether we get the C++03 version correct. The second
  11955. // part does not apply to references, since they are not objects.
  11956. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11957. // A reference initialized by a constant expression can never be
  11958. // odr-used, so simply ignore it.
  11959. if (!Var->getType()->isReferenceType())
  11960. SemaRef.MaybeODRUseExprs.insert(E);
  11961. } else
  11962. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11963. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11964. }
  11965. /// \brief Mark a variable referenced, and check whether it is odr-used
  11966. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11967. /// used directly for normal expressions referring to VarDecl.
  11968. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11969. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11970. }
  11971. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11972. Decl *D, Expr *E, bool OdrUse) {
  11973. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11974. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11975. return;
  11976. }
  11977. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11978. // If this is a call to a method via a cast, also mark the method in the
  11979. // derived class used in case codegen can devirtualize the call.
  11980. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11981. if (!ME)
  11982. return;
  11983. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11984. if (!MD)
  11985. return;
  11986. // Only attempt to devirtualize if this is truly a virtual call.
  11987. bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
  11988. if (!IsVirtualCall)
  11989. return;
  11990. const Expr *Base = ME->getBase();
  11991. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11992. if (!MostDerivedClassDecl)
  11993. return;
  11994. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11995. if (!DM || DM->isPure())
  11996. return;
  11997. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11998. }
  11999. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  12000. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  12001. // TODO: update this with DR# once a defect report is filed.
  12002. // C++11 defect. The address of a pure member should not be an ODR use, even
  12003. // if it's a qualified reference.
  12004. bool OdrUse = true;
  12005. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  12006. if (Method->isVirtual())
  12007. OdrUse = false;
  12008. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  12009. }
  12010. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  12011. void Sema::MarkMemberReferenced(MemberExpr *E) {
  12012. // C++11 [basic.def.odr]p2:
  12013. // A non-overloaded function whose name appears as a potentially-evaluated
  12014. // expression or a member of a set of candidate functions, if selected by
  12015. // overload resolution when referred to from a potentially-evaluated
  12016. // expression, is odr-used, unless it is a pure virtual function and its
  12017. // name is not explicitly qualified.
  12018. bool OdrUse = true;
  12019. if (!E->hasQualifier()) {
  12020. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  12021. if (Method->isPure())
  12022. OdrUse = false;
  12023. }
  12024. SourceLocation Loc = E->getMemberLoc().isValid() ?
  12025. E->getMemberLoc() : E->getLocStart();
  12026. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  12027. }
  12028. /// \brief Perform marking for a reference to an arbitrary declaration. It
  12029. /// marks the declaration referenced, and performs odr-use checking for
  12030. /// functions and variables. This method should not be used when building a
  12031. /// normal expression which refers to a variable.
  12032. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  12033. if (OdrUse) {
  12034. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12035. MarkVariableReferenced(Loc, VD);
  12036. return;
  12037. }
  12038. }
  12039. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  12040. MarkFunctionReferenced(Loc, FD, OdrUse);
  12041. return;
  12042. }
  12043. D->setReferenced();
  12044. }
  12045. namespace {
  12046. // Mark all of the declarations referenced
  12047. // FIXME: Not fully implemented yet! We need to have a better understanding
  12048. // of when we're entering
  12049. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  12050. Sema &S;
  12051. SourceLocation Loc;
  12052. public:
  12053. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  12054. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  12055. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  12056. bool TraverseRecordType(RecordType *T);
  12057. };
  12058. }
  12059. bool MarkReferencedDecls::TraverseTemplateArgument(
  12060. const TemplateArgument &Arg) {
  12061. if (Arg.getKind() == TemplateArgument::Declaration) {
  12062. if (Decl *D = Arg.getAsDecl())
  12063. S.MarkAnyDeclReferenced(Loc, D, true);
  12064. }
  12065. return Inherited::TraverseTemplateArgument(Arg);
  12066. }
  12067. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  12068. if (ClassTemplateSpecializationDecl *Spec
  12069. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  12070. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  12071. return TraverseTemplateArguments(Args.data(), Args.size());
  12072. }
  12073. return true;
  12074. }
  12075. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  12076. MarkReferencedDecls Marker(*this, Loc);
  12077. Marker.TraverseType(Context.getCanonicalType(T));
  12078. }
  12079. namespace {
  12080. /// \brief Helper class that marks all of the declarations referenced by
  12081. /// potentially-evaluated subexpressions as "referenced".
  12082. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  12083. Sema &S;
  12084. bool SkipLocalVariables;
  12085. public:
  12086. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  12087. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  12088. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  12089. void VisitDeclRefExpr(DeclRefExpr *E) {
  12090. // If we were asked not to visit local variables, don't.
  12091. if (SkipLocalVariables) {
  12092. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  12093. if (VD->hasLocalStorage())
  12094. return;
  12095. }
  12096. S.MarkDeclRefReferenced(E);
  12097. }
  12098. void VisitMemberExpr(MemberExpr *E) {
  12099. S.MarkMemberReferenced(E);
  12100. Inherited::VisitMemberExpr(E);
  12101. }
  12102. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  12103. S.MarkFunctionReferenced(E->getLocStart(),
  12104. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  12105. Visit(E->getSubExpr());
  12106. }
  12107. void VisitCXXNewExpr(CXXNewExpr *E) {
  12108. if (E->getOperatorNew())
  12109. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  12110. if (E->getOperatorDelete())
  12111. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12112. Inherited::VisitCXXNewExpr(E);
  12113. }
  12114. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  12115. if (E->getOperatorDelete())
  12116. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12117. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  12118. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  12119. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  12120. S.MarkFunctionReferenced(E->getLocStart(),
  12121. S.LookupDestructor(Record));
  12122. }
  12123. Inherited::VisitCXXDeleteExpr(E);
  12124. }
  12125. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  12126. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  12127. Inherited::VisitCXXConstructExpr(E);
  12128. }
  12129. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  12130. Visit(E->getExpr());
  12131. }
  12132. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12133. Inherited::VisitImplicitCastExpr(E);
  12134. if (E->getCastKind() == CK_LValueToRValue)
  12135. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  12136. }
  12137. };
  12138. }
  12139. /// \brief Mark any declarations that appear within this expression or any
  12140. /// potentially-evaluated subexpressions as "referenced".
  12141. ///
  12142. /// \param SkipLocalVariables If true, don't mark local variables as
  12143. /// 'referenced'.
  12144. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  12145. bool SkipLocalVariables) {
  12146. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  12147. }
  12148. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  12149. /// of the program being compiled.
  12150. ///
  12151. /// This routine emits the given diagnostic when the code currently being
  12152. /// type-checked is "potentially evaluated", meaning that there is a
  12153. /// possibility that the code will actually be executable. Code in sizeof()
  12154. /// expressions, code used only during overload resolution, etc., are not
  12155. /// potentially evaluated. This routine will suppress such diagnostics or,
  12156. /// in the absolutely nutty case of potentially potentially evaluated
  12157. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  12158. /// later.
  12159. ///
  12160. /// This routine should be used for all diagnostics that describe the run-time
  12161. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  12162. /// Failure to do so will likely result in spurious diagnostics or failures
  12163. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  12164. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  12165. const PartialDiagnostic &PD) {
  12166. switch (ExprEvalContexts.back().Context) {
  12167. case Unevaluated:
  12168. case UnevaluatedAbstract:
  12169. // The argument will never be evaluated, so don't complain.
  12170. break;
  12171. case ConstantEvaluated:
  12172. // Relevant diagnostics should be produced by constant evaluation.
  12173. break;
  12174. case PotentiallyEvaluated:
  12175. case PotentiallyEvaluatedIfUsed:
  12176. if (Statement && getCurFunctionOrMethodDecl()) {
  12177. FunctionScopes.back()->PossiblyUnreachableDiags.
  12178. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  12179. }
  12180. else
  12181. Diag(Loc, PD);
  12182. return true;
  12183. }
  12184. return false;
  12185. }
  12186. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  12187. CallExpr *CE, FunctionDecl *FD) {
  12188. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  12189. return false;
  12190. // If we're inside a decltype's expression, don't check for a valid return
  12191. // type or construct temporaries until we know whether this is the last call.
  12192. if (ExprEvalContexts.back().IsDecltype) {
  12193. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  12194. return false;
  12195. }
  12196. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  12197. FunctionDecl *FD;
  12198. CallExpr *CE;
  12199. public:
  12200. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  12201. : FD(FD), CE(CE) { }
  12202. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  12203. if (!FD) {
  12204. S.Diag(Loc, diag::err_call_incomplete_return)
  12205. << T << CE->getSourceRange();
  12206. return;
  12207. }
  12208. S.Diag(Loc, diag::err_call_function_incomplete_return)
  12209. << CE->getSourceRange() << FD->getDeclName() << T;
  12210. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  12211. << FD->getDeclName();
  12212. }
  12213. } Diagnoser(FD, CE);
  12214. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  12215. return true;
  12216. return false;
  12217. }
  12218. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  12219. // will prevent this condition from triggering, which is what we want.
  12220. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  12221. SourceLocation Loc;
  12222. unsigned diagnostic = diag::warn_condition_is_assignment;
  12223. bool IsOrAssign = false;
  12224. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  12225. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  12226. return;
  12227. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  12228. // Greylist some idioms by putting them into a warning subcategory.
  12229. if (ObjCMessageExpr *ME
  12230. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  12231. Selector Sel = ME->getSelector();
  12232. // self = [<foo> init...]
  12233. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  12234. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12235. // <foo> = [<bar> nextObject]
  12236. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  12237. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12238. }
  12239. Loc = Op->getOperatorLoc();
  12240. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  12241. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  12242. return;
  12243. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  12244. Loc = Op->getOperatorLoc();
  12245. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  12246. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  12247. else {
  12248. // Not an assignment.
  12249. return;
  12250. }
  12251. Diag(Loc, diagnostic) << E->getSourceRange();
  12252. SourceLocation Open = E->getLocStart();
  12253. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  12254. Diag(Loc, diag::note_condition_assign_silence)
  12255. << FixItHint::CreateInsertion(Open, "(")
  12256. << FixItHint::CreateInsertion(Close, ")");
  12257. if (IsOrAssign)
  12258. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  12259. << FixItHint::CreateReplacement(Loc, "!=");
  12260. else
  12261. Diag(Loc, diag::note_condition_assign_to_comparison)
  12262. << FixItHint::CreateReplacement(Loc, "==");
  12263. }
  12264. /// \brief Redundant parentheses over an equality comparison can indicate
  12265. /// that the user intended an assignment used as condition.
  12266. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  12267. // Don't warn if the parens came from a macro.
  12268. SourceLocation parenLoc = ParenE->getLocStart();
  12269. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  12270. return;
  12271. // Don't warn for dependent expressions.
  12272. if (ParenE->isTypeDependent())
  12273. return;
  12274. Expr *E = ParenE->IgnoreParens();
  12275. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12276. if (opE->getOpcode() == BO_EQ &&
  12277. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12278. == Expr::MLV_Valid) {
  12279. SourceLocation Loc = opE->getOperatorLoc();
  12280. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12281. SourceRange ParenERange = ParenE->getSourceRange();
  12282. Diag(Loc, diag::note_equality_comparison_silence)
  12283. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12284. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12285. Diag(Loc, diag::note_equality_comparison_to_assign)
  12286. << FixItHint::CreateReplacement(Loc, "=");
  12287. }
  12288. }
  12289. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12290. DiagnoseAssignmentAsCondition(E);
  12291. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12292. DiagnoseEqualityWithExtraParens(parenE);
  12293. ExprResult result = CheckPlaceholderExpr(E);
  12294. if (result.isInvalid()) return ExprError();
  12295. E = result.get();
  12296. if (!E->isTypeDependent()) {
  12297. if (getLangOpts().CPlusPlus)
  12298. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12299. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12300. if (ERes.isInvalid())
  12301. return ExprError();
  12302. E = ERes.get();
  12303. QualType T = E->getType();
  12304. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12305. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12306. << T << E->getSourceRange();
  12307. return ExprError();
  12308. }
  12309. CheckBoolLikeConversion(E, Loc);
  12310. }
  12311. return E;
  12312. }
  12313. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12314. Expr *SubExpr) {
  12315. if (!SubExpr)
  12316. return ExprError();
  12317. return CheckBooleanCondition(SubExpr, Loc);
  12318. }
  12319. namespace {
  12320. /// A visitor for rebuilding a call to an __unknown_any expression
  12321. /// to have an appropriate type.
  12322. struct RebuildUnknownAnyFunction
  12323. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12324. Sema &S;
  12325. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12326. ExprResult VisitStmt(Stmt *S) {
  12327. llvm_unreachable("unexpected statement!");
  12328. }
  12329. ExprResult VisitExpr(Expr *E) {
  12330. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12331. << E->getSourceRange();
  12332. return ExprError();
  12333. }
  12334. /// Rebuild an expression which simply semantically wraps another
  12335. /// expression which it shares the type and value kind of.
  12336. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12337. ExprResult SubResult = Visit(E->getSubExpr());
  12338. if (SubResult.isInvalid()) return ExprError();
  12339. Expr *SubExpr = SubResult.get();
  12340. E->setSubExpr(SubExpr);
  12341. E->setType(SubExpr->getType());
  12342. E->setValueKind(SubExpr->getValueKind());
  12343. assert(E->getObjectKind() == OK_Ordinary);
  12344. return E;
  12345. }
  12346. ExprResult VisitParenExpr(ParenExpr *E) {
  12347. return rebuildSugarExpr(E);
  12348. }
  12349. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12350. return rebuildSugarExpr(E);
  12351. }
  12352. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12353. ExprResult SubResult = Visit(E->getSubExpr());
  12354. if (SubResult.isInvalid()) return ExprError();
  12355. Expr *SubExpr = SubResult.get();
  12356. E->setSubExpr(SubExpr);
  12357. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12358. assert(E->getValueKind() == VK_RValue);
  12359. assert(E->getObjectKind() == OK_Ordinary);
  12360. return E;
  12361. }
  12362. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12363. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12364. E->setType(VD->getType());
  12365. assert(E->getValueKind() == VK_RValue);
  12366. if (S.getLangOpts().CPlusPlus &&
  12367. !(isa<CXXMethodDecl>(VD) &&
  12368. cast<CXXMethodDecl>(VD)->isInstance()))
  12369. E->setValueKind(VK_LValue);
  12370. return E;
  12371. }
  12372. ExprResult VisitMemberExpr(MemberExpr *E) {
  12373. return resolveDecl(E, E->getMemberDecl());
  12374. }
  12375. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12376. return resolveDecl(E, E->getDecl());
  12377. }
  12378. };
  12379. }
  12380. /// Given a function expression of unknown-any type, try to rebuild it
  12381. /// to have a function type.
  12382. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12383. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12384. if (Result.isInvalid()) return ExprError();
  12385. return S.DefaultFunctionArrayConversion(Result.get());
  12386. }
  12387. namespace {
  12388. /// A visitor for rebuilding an expression of type __unknown_anytype
  12389. /// into one which resolves the type directly on the referring
  12390. /// expression. Strict preservation of the original source
  12391. /// structure is not a goal.
  12392. struct RebuildUnknownAnyExpr
  12393. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12394. Sema &S;
  12395. /// The current destination type.
  12396. QualType DestType;
  12397. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12398. : S(S), DestType(CastType) {}
  12399. ExprResult VisitStmt(Stmt *S) {
  12400. llvm_unreachable("unexpected statement!");
  12401. }
  12402. ExprResult VisitExpr(Expr *E) {
  12403. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12404. << E->getSourceRange();
  12405. return ExprError();
  12406. }
  12407. ExprResult VisitCallExpr(CallExpr *E);
  12408. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12409. /// Rebuild an expression which simply semantically wraps another
  12410. /// expression which it shares the type and value kind of.
  12411. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12412. ExprResult SubResult = Visit(E->getSubExpr());
  12413. if (SubResult.isInvalid()) return ExprError();
  12414. Expr *SubExpr = SubResult.get();
  12415. E->setSubExpr(SubExpr);
  12416. E->setType(SubExpr->getType());
  12417. E->setValueKind(SubExpr->getValueKind());
  12418. assert(E->getObjectKind() == OK_Ordinary);
  12419. return E;
  12420. }
  12421. ExprResult VisitParenExpr(ParenExpr *E) {
  12422. return rebuildSugarExpr(E);
  12423. }
  12424. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12425. return rebuildSugarExpr(E);
  12426. }
  12427. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12428. const PointerType *Ptr = DestType->getAs<PointerType>();
  12429. if (!Ptr) {
  12430. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12431. << E->getSourceRange();
  12432. return ExprError();
  12433. }
  12434. assert(E->getValueKind() == VK_RValue);
  12435. assert(E->getObjectKind() == OK_Ordinary);
  12436. E->setType(DestType);
  12437. // Build the sub-expression as if it were an object of the pointee type.
  12438. DestType = Ptr->getPointeeType();
  12439. ExprResult SubResult = Visit(E->getSubExpr());
  12440. if (SubResult.isInvalid()) return ExprError();
  12441. E->setSubExpr(SubResult.get());
  12442. return E;
  12443. }
  12444. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12445. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12446. ExprResult VisitMemberExpr(MemberExpr *E) {
  12447. return resolveDecl(E, E->getMemberDecl());
  12448. }
  12449. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12450. return resolveDecl(E, E->getDecl());
  12451. }
  12452. };
  12453. }
  12454. /// Rebuilds a call expression which yielded __unknown_anytype.
  12455. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12456. Expr *CalleeExpr = E->getCallee();
  12457. enum FnKind {
  12458. FK_MemberFunction,
  12459. FK_FunctionPointer,
  12460. FK_BlockPointer
  12461. };
  12462. FnKind Kind;
  12463. QualType CalleeType = CalleeExpr->getType();
  12464. if (CalleeType == S.Context.BoundMemberTy) {
  12465. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12466. Kind = FK_MemberFunction;
  12467. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12468. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12469. CalleeType = Ptr->getPointeeType();
  12470. Kind = FK_FunctionPointer;
  12471. } else {
  12472. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12473. Kind = FK_BlockPointer;
  12474. }
  12475. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12476. // Verify that this is a legal result type of a function.
  12477. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12478. unsigned diagID = diag::err_func_returning_array_function;
  12479. if (Kind == FK_BlockPointer)
  12480. diagID = diag::err_block_returning_array_function;
  12481. S.Diag(E->getExprLoc(), diagID)
  12482. << DestType->isFunctionType() << DestType;
  12483. return ExprError();
  12484. }
  12485. // Otherwise, go ahead and set DestType as the call's result.
  12486. E->setType(DestType.getNonLValueExprType(S.Context));
  12487. E->setValueKind(Expr::getValueKindForType(DestType));
  12488. assert(E->getObjectKind() == OK_Ordinary);
  12489. // Rebuild the function type, replacing the result type with DestType.
  12490. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12491. if (Proto) {
  12492. // __unknown_anytype(...) is a special case used by the debugger when
  12493. // it has no idea what a function's signature is.
  12494. //
  12495. // We want to build this call essentially under the K&R
  12496. // unprototyped rules, but making a FunctionNoProtoType in C++
  12497. // would foul up all sorts of assumptions. However, we cannot
  12498. // simply pass all arguments as variadic arguments, nor can we
  12499. // portably just call the function under a non-variadic type; see
  12500. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12501. // However, it turns out that in practice it is generally safe to
  12502. // call a function declared as "A foo(B,C,D);" under the prototype
  12503. // "A foo(B,C,D,...);". The only known exception is with the
  12504. // Windows ABI, where any variadic function is implicitly cdecl
  12505. // regardless of its normal CC. Therefore we change the parameter
  12506. // types to match the types of the arguments.
  12507. //
  12508. // This is a hack, but it is far superior to moving the
  12509. // corresponding target-specific code from IR-gen to Sema/AST.
  12510. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12511. SmallVector<QualType, 8> ArgTypes;
  12512. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12513. ArgTypes.reserve(E->getNumArgs());
  12514. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12515. Expr *Arg = E->getArg(i);
  12516. QualType ArgType = Arg->getType();
  12517. if (E->isLValue()) {
  12518. ArgType = S.Context.getLValueReferenceType(ArgType);
  12519. } else if (E->isXValue()) {
  12520. ArgType = S.Context.getRValueReferenceType(ArgType);
  12521. }
  12522. ArgTypes.push_back(ArgType);
  12523. }
  12524. ParamTypes = ArgTypes;
  12525. }
  12526. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12527. Proto->getExtProtoInfo(),
  12528. Proto->getParamMods()); // HLSL Change - assume args are preserved
  12529. } else {
  12530. DestType = S.Context.getFunctionNoProtoType(DestType,
  12531. FnType->getExtInfo());
  12532. }
  12533. // Rebuild the appropriate pointer-to-function type.
  12534. switch (Kind) {
  12535. case FK_MemberFunction:
  12536. // Nothing to do.
  12537. break;
  12538. case FK_FunctionPointer:
  12539. DestType = S.Context.getPointerType(DestType);
  12540. break;
  12541. case FK_BlockPointer:
  12542. DestType = S.Context.getBlockPointerType(DestType);
  12543. break;
  12544. }
  12545. // Finally, we can recurse.
  12546. ExprResult CalleeResult = Visit(CalleeExpr);
  12547. if (!CalleeResult.isUsable()) return ExprError();
  12548. E->setCallee(CalleeResult.get());
  12549. // Bind a temporary if necessary.
  12550. return S.MaybeBindToTemporary(E);
  12551. }
  12552. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12553. // Verify that this is a legal result type of a call.
  12554. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12555. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12556. << DestType->isFunctionType() << DestType;
  12557. return ExprError();
  12558. }
  12559. // Rewrite the method result type if available.
  12560. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12561. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12562. Method->setReturnType(DestType);
  12563. }
  12564. // Change the type of the message.
  12565. E->setType(DestType.getNonReferenceType());
  12566. E->setValueKind(Expr::getValueKindForType(DestType));
  12567. return S.MaybeBindToTemporary(E);
  12568. }
  12569. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12570. // The only case we should ever see here is a function-to-pointer decay.
  12571. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12572. assert(E->getValueKind() == VK_RValue);
  12573. assert(E->getObjectKind() == OK_Ordinary);
  12574. E->setType(DestType);
  12575. // Rebuild the sub-expression as the pointee (function) type.
  12576. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12577. ExprResult Result = Visit(E->getSubExpr());
  12578. if (!Result.isUsable()) return ExprError();
  12579. E->setSubExpr(Result.get());
  12580. return E;
  12581. } else if (E->getCastKind() == CK_LValueToRValue) {
  12582. assert(E->getValueKind() == VK_RValue);
  12583. assert(E->getObjectKind() == OK_Ordinary);
  12584. assert(isa<BlockPointerType>(E->getType()));
  12585. E->setType(DestType);
  12586. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12587. DestType = S.Context.getLValueReferenceType(DestType);
  12588. ExprResult Result = Visit(E->getSubExpr());
  12589. if (!Result.isUsable()) return ExprError();
  12590. E->setSubExpr(Result.get());
  12591. return E;
  12592. } else {
  12593. llvm_unreachable("Unhandled cast type!");
  12594. }
  12595. }
  12596. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12597. ExprValueKind ValueKind = VK_LValue;
  12598. QualType Type = DestType;
  12599. // We know how to make this work for certain kinds of decls:
  12600. // - functions
  12601. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12602. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12603. DestType = Ptr->getPointeeType();
  12604. ExprResult Result = resolveDecl(E, VD);
  12605. if (Result.isInvalid()) return ExprError();
  12606. return S.ImpCastExprToType(Result.get(), Type,
  12607. CK_FunctionToPointerDecay, VK_RValue);
  12608. }
  12609. if (!Type->isFunctionType()) {
  12610. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12611. << VD << E->getSourceRange();
  12612. return ExprError();
  12613. }
  12614. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12615. // We must match the FunctionDecl's type to the hack introduced in
  12616. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12617. // type. See the lengthy commentary in that routine.
  12618. QualType FDT = FD->getType();
  12619. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12620. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12621. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12622. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12623. SourceLocation Loc = FD->getLocation();
  12624. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12625. FD->getDeclContext(),
  12626. Loc, Loc, FD->getNameInfo().getName(),
  12627. DestType, FD->getTypeSourceInfo(),
  12628. SC_None, false/*isInlineSpecified*/,
  12629. FD->hasPrototype(),
  12630. false/*isConstexprSpecified*/);
  12631. if (FD->getQualifier())
  12632. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12633. SmallVector<ParmVarDecl*, 16> Params;
  12634. for (const auto &AI : FT->param_types()) {
  12635. ParmVarDecl *Param =
  12636. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12637. Param->setScopeInfo(0, Params.size());
  12638. Params.push_back(Param);
  12639. }
  12640. NewFD->setParams(Params);
  12641. DRE->setDecl(NewFD);
  12642. VD = DRE->getDecl();
  12643. }
  12644. }
  12645. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12646. if (MD->isInstance()) {
  12647. ValueKind = VK_RValue;
  12648. Type = S.Context.BoundMemberTy;
  12649. }
  12650. // Function references aren't l-values in C.
  12651. if (!S.getLangOpts().CPlusPlus)
  12652. ValueKind = VK_RValue;
  12653. // - variables
  12654. } else if (isa<VarDecl>(VD)) {
  12655. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12656. Type = RefTy->getPointeeType();
  12657. } else if (Type->isFunctionType()) {
  12658. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12659. << VD << E->getSourceRange();
  12660. return ExprError();
  12661. }
  12662. // - nothing else
  12663. } else {
  12664. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12665. << VD << E->getSourceRange();
  12666. return ExprError();
  12667. }
  12668. // Modifying the declaration like this is friendly to IR-gen but
  12669. // also really dangerous.
  12670. VD->setType(DestType);
  12671. E->setType(Type);
  12672. E->setValueKind(ValueKind);
  12673. return E;
  12674. }
  12675. /// Check a cast of an unknown-any type. We intentionally only
  12676. /// trigger this for C-style casts.
  12677. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12678. Expr *CastExpr, CastKind &CastKind,
  12679. ExprValueKind &VK, CXXCastPath &Path) {
  12680. // Rewrite the casted expression from scratch.
  12681. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12682. if (!result.isUsable()) return ExprError();
  12683. CastExpr = result.get();
  12684. VK = CastExpr->getValueKind();
  12685. CastKind = CK_NoOp;
  12686. return CastExpr;
  12687. }
  12688. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12689. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12690. }
  12691. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12692. Expr *arg, QualType &paramType) {
  12693. // If the syntactic form of the argument is not an explicit cast of
  12694. // any sort, just do default argument promotion.
  12695. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12696. if (!castArg) {
  12697. ExprResult result = DefaultArgumentPromotion(arg);
  12698. if (result.isInvalid()) return ExprError();
  12699. paramType = result.get()->getType();
  12700. return result;
  12701. }
  12702. // Otherwise, use the type that was written in the explicit cast.
  12703. assert(!arg->hasPlaceholderType());
  12704. paramType = castArg->getTypeAsWritten();
  12705. // Copy-initialize a parameter of that type.
  12706. InitializedEntity entity =
  12707. InitializedEntity::InitializeParameter(Context, paramType,
  12708. /*consumed*/ false);
  12709. return PerformCopyInitialization(entity, callLoc, arg);
  12710. }
  12711. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12712. Expr *orig = E;
  12713. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12714. while (true) {
  12715. E = E->IgnoreParenImpCasts();
  12716. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12717. E = call->getCallee();
  12718. diagID = diag::err_uncasted_call_of_unknown_any;
  12719. } else {
  12720. break;
  12721. }
  12722. }
  12723. SourceLocation loc;
  12724. NamedDecl *d;
  12725. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12726. loc = ref->getLocation();
  12727. d = ref->getDecl();
  12728. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12729. loc = mem->getMemberLoc();
  12730. d = mem->getMemberDecl();
  12731. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12732. diagID = diag::err_uncasted_call_of_unknown_any;
  12733. loc = msg->getSelectorStartLoc();
  12734. d = msg->getMethodDecl();
  12735. if (!d) {
  12736. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12737. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12738. << orig->getSourceRange();
  12739. return ExprError();
  12740. }
  12741. } else {
  12742. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12743. << E->getSourceRange();
  12744. return ExprError();
  12745. }
  12746. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12747. // Never recoverable.
  12748. return ExprError();
  12749. }
  12750. /// Check for operands with placeholder types and complain if found.
  12751. /// Returns true if there was an error and no recovery was possible.
  12752. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12753. if (!getLangOpts().CPlusPlus) {
  12754. // C cannot handle TypoExpr nodes on either side of a binop because it
  12755. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12756. // been dealt with before checking the operands.
  12757. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12758. if (!Result.isUsable()) return ExprError();
  12759. E = Result.get();
  12760. }
  12761. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12762. if (!placeholderType) return E;
  12763. switch (placeholderType->getKind()) {
  12764. // Overloaded expressions.
  12765. case BuiltinType::Overload: {
  12766. // Try to resolve a single function template specialization.
  12767. // This is obligatory.
  12768. ExprResult result = E;
  12769. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12770. return result;
  12771. // If that failed, try to recover with a call.
  12772. } else {
  12773. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12774. /*complain*/ true);
  12775. return result;
  12776. }
  12777. }
  12778. // Bound member functions.
  12779. case BuiltinType::BoundMember: {
  12780. ExprResult result = E;
  12781. const Expr *BME = E->IgnoreParens();
  12782. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12783. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12784. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12785. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12786. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12787. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12788. DeclarationName::CXXDestructorName)
  12789. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12790. }
  12791. tryToRecoverWithCall(result, PD,
  12792. /*complain*/ true);
  12793. return result;
  12794. }
  12795. // ARC unbridged casts.
  12796. case BuiltinType::ARCUnbridgedCast: {
  12797. Expr *realCast = stripARCUnbridgedCast(E);
  12798. diagnoseARCUnbridgedCast(realCast);
  12799. return realCast;
  12800. }
  12801. // Expressions of unknown type.
  12802. case BuiltinType::UnknownAny:
  12803. return diagnoseUnknownAnyExpr(*this, E);
  12804. // Pseudo-objects.
  12805. case BuiltinType::PseudoObject:
  12806. return checkPseudoObjectRValue(E);
  12807. case BuiltinType::BuiltinFn: {
  12808. // Accept __noop without parens by implicitly converting it to a call expr.
  12809. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12810. if (DRE) {
  12811. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12812. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12813. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12814. CK_BuiltinFnToFnPtr).get();
  12815. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12816. VK_RValue, SourceLocation());
  12817. }
  12818. }
  12819. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12820. return ExprError();
  12821. }
  12822. // Everything else should be impossible.
  12823. #define BUILTIN_TYPE(Id, SingletonId) \
  12824. case BuiltinType::Id:
  12825. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12826. #include "clang/AST/BuiltinTypes.def"
  12827. break;
  12828. }
  12829. llvm_unreachable("invalid placeholder type!");
  12830. }
  12831. bool Sema::CheckCaseExpression(Expr *E) {
  12832. if (E->isTypeDependent())
  12833. return true;
  12834. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12835. return E->getType()->isIntegralOrEnumerationType();
  12836. return false;
  12837. }
  12838. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12839. ExprResult
  12840. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12841. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12842. "Unknown Objective-C Boolean value!");
  12843. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12844. if (!Context.getBOOLDecl()) {
  12845. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12846. Sema::LookupOrdinaryName);
  12847. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12848. NamedDecl *ND = Result.getFoundDecl();
  12849. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12850. Context.setBOOLDecl(TD);
  12851. }
  12852. }
  12853. if (Context.getBOOLDecl())
  12854. BoolT = Context.getBOOLType();
  12855. return new (Context)
  12856. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12857. }